Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pm-stack/aggregator/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1338,6 +1338,8 @@ export interface QuotaCurrentFile {
source: string;
heartbeat: QuotaGatherHeartbeat;
providers: QuotaCurrentEntry[];
/** Parser diagnostics for malformed entries removed at the ingest boundary. */
sanitized?: { droppedProviders: number; droppedWindows: number };
}

/**
Expand Down
69 changes: 59 additions & 10 deletions pm-stack/aggregator/src/quota-current.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import type {
UsageMetric,
UsageUnit,
} from "./model.ts";
import { arrayOf, isFiniteNumber, isIsoDate, isNonEmptyString, isRecord } from "./validate.ts";

/** Freshness bound for gatherer precedence: two missed ticks. */
export const QUOTA_CURRENT_FRESH_MS = 20 * 60_000;
Expand All @@ -47,21 +48,69 @@ export const QUOTA_CURRENT_FRESH_MS = 20 * 60_000;
*/
export const QUOTA_CURRENT_FUTURE_SKEW_MS = 60_000;

const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
function isQuotaCurrentWindow(value: unknown): value is QuotaCurrentFile["providers"][number]["windows"][number] {
if (!isRecord(value)) return false;
const finiteOrNull = (v: unknown) => v === null || isFiniteNumber(v);
return (
isNonEmptyString(value.name) &&
finiteOrNull(value.value) &&
finiteOrNull(value.pctOfLimit) &&
(value.valueLabel === null || typeof value.valueLabel === "string") &&
finiteOrNull(value.windowSeconds) &&
(value.resetsAt === null || isIsoDate(value.resetsAt)) &&
typeof value.measuredAt === "string" &&
typeof value.source === "string" &&
(value.state === "ok" || value.state === "error")
);
}

function isQuotaCurrentEntry(value: unknown): value is QuotaCurrentEntry {
return (
isRecord(value) &&
typeof value.providerId === "string" &&
typeof value.providerName === "string" &&
typeof value.serviceId === "string" &&
(value.state === "ok" || value.state === "error" || value.state === "unconfigured") &&
typeof value.measuredAt === "string" &&
typeof value.source === "string" &&
Array.isArray(value.windows)
);
}

/** Structural check of a parsed quota-current.json document. */
export function parseQuotaCurrent(doc: unknown): QuotaCurrentFile | null {
if (!isRecord(doc)) return null;
if (doc.version !== 1 || typeof doc.generatedAt !== "string") return null;
if (!Array.isArray(doc.providers)) return null;
for (const p of doc.providers) {
if (!isRecord(p)) return null;
if (typeof p.providerId !== "string" || typeof p.serviceId !== "string") return null;
if (p.state !== "ok" && p.state !== "error" && p.state !== "unconfigured") return null;
if (typeof p.measuredAt !== "string" || typeof p.source !== "string") return null;
if (!Array.isArray(p.windows)) return null;
}
return doc as unknown as QuotaCurrentFile;
const providers = arrayOf(isQuotaCurrentEntry)(doc.providers);
// Keep rejecting a wholly malformed provider list; when at least one entry is valid,
// isolate malformed siblings so one provider cannot suppress unrelated overlays.
if (!providers || (providers.values.length === 0 && providers.dropped > 0)) return null;
let droppedWindows = 0;
const validProviders = providers.values.map((provider) => {
const windows = arrayOf(isQuotaCurrentWindow)(provider.windows)!;
droppedWindows += windows.dropped;
if (provider.state === "ok" && provider.windows.length > 0 && windows.values.length === 0) {
// Entirely discarded read (#2416, Codex finding on PR #4182): left
// as "ok", the entry would still win fresh-ok precedence in the
// overlay, stamp the pool's older windows with fresh provenance,
// and block a valid fresh sibling for the same service from
// supplying the headline. Downgrade it to the error it is. An
// entry that arrived with no windows at all is a legitimate
// balance-only read and keeps its state.
return {
...provider,
state: "error" as const,
error: "all quota windows were malformed and dropped at ingest",
windows: windows.values,
};
}
return { ...provider, windows: windows.values };
Comment on lines +90 to +107

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Downgrade providers whose windows are entirely discarded

When a fresh ok provider has only malformed windows, sanitization leaves it as an ok entry with an empty window list. overlayQuotaCurrent still selects it as the newest fresh entry, and applyEntry stamps the pool's existing dated windows with fresh ok provenance without replacing them. It also prevents an older valid fresh credential for the same service from supplying the headline windows. For example, a newest entry with windows: [null] and a valid sibling reporting 80% leaves the base pool's 11% displayed as freshly measured. Distinguish an entry emptied by validation from a legitimate balance-only read, and drop or downgrade the malformed entry so it cannot claim freshness or suppress a valid overlay.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6aee703. parseQuotaCurrent now downgrades an "ok" entry whose windows were entirely dropped by sanitization to state "error" (error: "all quota windows were malformed and dropped at ingest"), so it can no longer win fresh-ok precedence, stamp the pool's dated windows with fresh provenance, or block a valid fresh sibling. Entries that arrived windowless (balance-only reads) keep their state. Regression tests added in quota-current.test.ts: the sibling case (valid 80% read supplies the headline, freshness measuredAt from the sibling) and the sole-entry case (pool surfaces error, base windows keep their dated 11%).

});
return {
...doc,
providers: validProviders,
sanitized: { droppedProviders: providers.dropped, droppedWindows },
} as unknown as QuotaCurrentFile;
}

type FreshState = PoolFreshness["state"];
Expand Down
4 changes: 4 additions & 0 deletions pm-stack/aggregator/src/sources/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,10 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise<bo
const file = parseQuotaCurrent(JSON.parse(raw));
if (file) {
provenance.quota += ` · gatherer ${file.generatedAt}`;
const sanitized = file.sanitized;
if (sanitized && sanitized.droppedProviders + sanitized.droppedWindows > 0) {
provenance.quota += ` · sanitized quota-current: dropped ${sanitized.droppedProviders} provider(s), ${sanitized.droppedWindows} window(s)`;
}
return overlayQuotaCurrent(view, file);
}
} catch {
Expand Down
66 changes: 66 additions & 0 deletions pm-stack/aggregator/test/quota-current.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,72 @@ describe("quota-current overlay", () => {
expect(view.pools.find((p) => p.id === "meta:high-usage")!.windows[0].percent).toBe(100);
expect(view.gatherer).toBeUndefined();
});

test("malformed providers and windows are dropped without losing valid provider overlays", () => {
const doc = JSON.parse(
JSON.stringify(
file([
entry({ serviceId: "meta:high-usage", windows: [win("weekly", 42, iso(5 * 60_000))] }),
entry({ serviceId: "openai:codex", windows: [win("7-day", 17, iso(5 * 60_000))] }),
]),
),
);
doc.providers[0].windows.push(
null,
{ ...doc.providers[0].windows[0], name: 42 },
{ ...doc.providers[0].windows[0], resetsAt: { invalid: true } },
);
doc.providers.push(null);

const parsed = parseQuotaCurrent(doc);
expect(parsed?.sanitized).toEqual({ droppedProviders: 1, droppedWindows: 3 });
expect(parsed?.providers).toHaveLength(2);
const out = overlayQuotaCurrent(baseView(), parsed!, NOW);
expect(out.pools.find((p) => p.id === "meta:high-usage")?.windows.map((w) => [w.name, w.percent])).toEqual([
["weekly", 42],
]);
expect(out.pools.find((p) => p.id === "openai:codex")?.windows.map((w) => [w.name, w.percent])).toEqual([
["7-day", 17],
]);
});

test("an ok entry whose windows are entirely malformed is downgraded so a valid fresh sibling supplies the headline", () => {
const doc = JSON.parse(
JSON.stringify(
file([
entry({ serviceId: "openai:codex", measuredAt: iso(1 * 60_000), windows: [win("7-day", 55, iso(1 * 60_000))] }),
entry({ serviceId: "openai:codex", measuredAt: iso(5 * 60_000), windows: [win("7-day", 80, iso(5 * 60_000))] }),
]),
),
);
doc.providers[0].windows = [null];

const parsed = parseQuotaCurrent(doc);
expect(parsed?.providers[0].state).toBe("error");
const out = overlayQuotaCurrent(baseView(), parsed!, NOW);
const pool = out.pools.find((p) => p.id === "openai:codex")!;
// The base pool's dated 11% must not be re-stamped as fresh, and the
// older valid read (80%) supplies the headline instead.
expect(pool.windows.map((w) => [w.name, w.percent])).toEqual([["7-day", 80]]);
expect(pool.freshness?.state).toBe("ok");
expect(pool.freshness?.measuredAt).toBe(iso(5 * 60_000));
});

test("a sole ok entry whose windows are entirely malformed surfaces as an error, never as fresh provenance", () => {
const doc = JSON.parse(
JSON.stringify(
file([entry({ serviceId: "openai:codex", windows: [win("7-day", 55, iso(5 * 60_000))] })]),
),
);
doc.providers[0].windows = [null, { bogus: true }];

const parsed = parseQuotaCurrent(doc);
const out = overlayQuotaCurrent(baseView(), parsed!, NOW);
const pool = out.pools.find((p) => p.id === "openai:codex")!;
expect(pool.state).toBe("error");
expect(pool.freshness?.state).toBe("error");
expect(pool.windows.map((w) => w.percent)).toEqual([11]);
});
});

describe("parseQuotaCurrent", () => {
Expand Down
Loading