diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index 2917123b30..1bc497bc59 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -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 }; } /** diff --git a/pm-stack/aggregator/src/quota-current.ts b/pm-stack/aggregator/src/quota-current.ts index 3e930bf1dc..b34b6b5397 100644 --- a/pm-stack/aggregator/src/quota-current.ts +++ b/pm-stack/aggregator/src/quota-current.ts @@ -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; @@ -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 => 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 }; + }); + return { + ...doc, + providers: validProviders, + sanitized: { droppedProviders: providers.dropped, droppedWindows }, + } as unknown as QuotaCurrentFile; } type FreshState = PoolFreshness["state"]; diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index d6d2fa290b..77c0555e8a 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -855,6 +855,10 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise 0) { + provenance.quota += ` · sanitized quota-current: dropped ${sanitized.droppedProviders} provider(s), ${sanitized.droppedWindows} window(s)`; + } return overlayQuotaCurrent(view, file); } } catch { diff --git a/pm-stack/aggregator/test/quota-current.test.ts b/pm-stack/aggregator/test/quota-current.test.ts index 4477040e9c..aa8a206a7f 100644 --- a/pm-stack/aggregator/test/quota-current.test.ts +++ b/pm-stack/aggregator/test/quota-current.test.ts @@ -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", () => {