diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index be1d16ce34..f6bc7e9c05 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -128,6 +128,7 @@ import { chargeServiceCatalog } from "../src/charges-catalog.ts"; import { filterNewUnmatched, mergeChargeRows, parseChargeCandidates } from "../src/charges-collect.ts"; import { extractQuotaPools } from "../src/quota-extract.ts"; import { computeChoices } from "../src/quota-guidance.ts"; +import { deriveExhaustionForecasts } from "../src/quota-exhaustion.ts"; import { deriveBurnHistory, deriveMeasuredRatesFromPoolTokens, @@ -1234,6 +1235,9 @@ async function main(): Promise { ratesSet += 1; } } + // Exhaustion intervals (#3983) compose the same observations: + // per-pool forecasts ride on the pool like burnTokensPerMin. + deriveExhaustionForecasts(pools, mergedObservations, now); markSection("burnHistory", burnSegments.length || ratesSet ? "ok" : "skipped"); } catch (err) { console.error("collector: burn-history derivation failed; burn stays empty this run"); diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index b10d003940..23e7bbe181 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -291,6 +291,10 @@ export interface QuotaPool { windows: QuotaWindow[]; /** tokens/min over the recent window, when measurable. */ burnTokensPerMin?: number; + /** Per-window exhaustion interval forecasts (#3983), set by the + * collector from the measured burn history. Additive for existing + * consumers; absent when the collector did not derive them. */ + exhaustion?: ExhaustionForecast[]; /** Sessions currently burning this pool, with cumulative tokens. */ activeSessions?: { session: string; model: string; tokens: number }[]; /** Gatherer freshness for this pool (#1151), set when @@ -304,6 +308,42 @@ export interface QuotaPool { credentials?: QuotaCredentialRow[]; } +/** One window's time-to-exhaustion forecast (#3983): an interval + * projected from the measured burn-rate distribution of the #3933 + * contract, or an explicit unknown — never a fabricated date. */ +export interface ExhaustionForecast { + pool: string; + provider: string; + window: string; + unit: string; + state: "forecast" | "unknown" | "exhausted"; + /** Why no forecast exists, when state is "unknown". */ + reason?: + | "missing_limit" + | "missing_reset" + | "reset_passed" + | "stale_source" + | "no_measured_burn" + | "insufficient_observations" + | "zero_rate"; + /** limit - used for the window; null when the limit is unknown. */ + remaining: number | null; + resetsAt: string | null; + /** The named measurement window pair rates must fit inside. */ + rateWindowMs: number; + /** Gatherer source for the pool read, when freshness is known. */ + source: string | null; + /** Same-period pair rates behind the percentiles, when forecast. */ + sampleRates?: number; + ratesPerMin?: { p50: number; p80: number }; + p50ExhaustsAt?: string; + p80ExhaustsAt?: string; + p50VsReset?: "before" | "after"; + p80VsReset?: "before" | "after"; + /** When state is "exhausted": the collection instant (already there). */ + exhaustsAt?: string; +} + /** One credential's own quota read within a pool (#1113). */ export interface QuotaCredentialRow { /** The gatherer's credential label (e.g. "OpenAI 2"), or the diff --git a/pm-stack/aggregator/src/quota-current.ts b/pm-stack/aggregator/src/quota-current.ts index eca4448638..3b6f64b287 100644 --- a/pm-stack/aggregator/src/quota-current.ts +++ b/pm-stack/aggregator/src/quota-current.ts @@ -272,6 +272,14 @@ function applyEntry(pool: QuotaPool, entry: QuotaCurrentEntry, state: FreshState if (state === "error") freshness.error = !entry.error && legError ? legError : errorText(entry); if (state === "lapsed") freshness.error = errorText(entry); pool.freshness = freshness; + // #3983 forecasts are derived from the windows they were computed + // against (the collector dated fallback). This overlay replaces, + // adopts, or clears those windows from the live gatherer read, so + // a forecast calculated for the old values must never ride along + // beside the new ones (Codex P2 on PR #8522). The overlay has no + // observation history to recompute from: dropping the forecast is + // the honest state until the next collector derivation. + delete pool.exhaustion; if (state === "error") { pool.state = "error"; adoptEntryWindows(pool, entry); diff --git a/pm-stack/aggregator/src/quota-exhaustion.ts b/pm-stack/aggregator/src/quota-exhaustion.ts new file mode 100644 index 0000000000..debc150d29 --- /dev/null +++ b/pm-stack/aggregator/src/quota-exhaustion.ts @@ -0,0 +1,160 @@ +/** + * Per-pool quota exhaustion intervals (#3983), composing the live + * quota contract #3933 landed: pool identity, remaining/limit, reset + * time, measured timestamped burn (PoolWindowObservation series), + * source freshness, and explicit missing markers. + * + * The forecast complements — never replaces — the existing point + * pace (digest) and near-limit/wall derivations, and adds no new + * threshold or attention path: it only projects when the current + * window fills at the measured burn-rate distribution, and says so + * honestly as an interval (P50/P80 of the observed same-period pair + * rates within RATE_WINDOW_MS). + * + * Honesty rules, mirroring burn-history: anything not measurable is + * an explicit `unknown` with a reason — never "safe", never a + * fabricated date. Rates come only from consecutive same-period + * observation pairs (a pair straddling a reset measures nothing + * about the current window). Queued work is never converted into + * token demand; only measured burn is projected. + */ +import { RATE_WINDOW_MS, type PoolWindowObservation } from "./burn-history.ts"; +import type { ExhaustionForecast, QuotaPool } from "./model.ts"; + +/** Minimum same-period pair rates before percentiles mean anything: + * with fewer, the honest answer is an unknown, not a point dressed + * up as an interval. */ +export const MIN_RATE_SAMPLES = 2; + +/** Nearest-rank percentile of an ascending-sorted sample. */ +function percentile(sortedAsc: number[], p: number): number { + const rank = Math.max(1, Math.ceil((p / 100) * sortedAsc.length)); + return sortedAsc[rank - 1]; +} + +export function deriveExhaustionForecasts( + pools: QuotaPool[], + observations: PoolWindowObservation[], + now = new Date(), +): ExhaustionForecast[] { + const nowMs = now.getTime(); + const byWindow = new Map(); + for (const o of observations) { + const k = `${o.pool}${o.window}`; + const list = byWindow.get(k) ?? []; + list.push(o); + byWindow.set(k, list); + } + + const out: ExhaustionForecast[] = []; + for (const pool of pools) { + const forecasts: ExhaustionForecast[] = []; + for (const w of pool.windows) { + const base = { + pool: pool.id, + provider: pool.provider, + window: w.name, + unit: w.unit, + resetsAt: w.resetsAt ?? null, + rateWindowMs: RATE_WINDOW_MS, + source: pool.freshness?.source ?? null, + }; + const unknown = (reason: NonNullable, remaining: number | null) => { + forecasts.push({ ...base, state: "unknown", reason, remaining }); + }; + + if (w.limit === null || !Number.isFinite(w.limit)) { + unknown("missing_limit", null); + continue; + } + const remaining = w.limit - w.used; + // Freshness BEFORE the exhausted shortcut (Codex P2 on PR #8522): + // a stale/errored pool can retain a last-known window at its + // limit (quota-current.ts preserves dated windows for stale + // reads and adopts retained windows on errors); if the quota + // has since reset, that retained reading asserts nothing about + // current exhaustion. Stale source = explicit unknown, always. + if (pool.freshness && pool.freshness.state !== "ok") { + unknown("stale_source", remaining); + continue; + } + const resetMs = w.resetsAt ? Date.parse(w.resetsAt) : Number.NaN; + if (Number.isFinite(resetMs) && resetMs <= nowMs) { + unknown("reset_passed", remaining); + continue; + } + if (remaining <= 0) { + forecasts.push({ ...base, state: "exhausted", remaining, exhaustsAt: now.toISOString() }); + continue; + } + if (!w.resetsAt || !Number.isFinite(Date.parse(w.resetsAt))) { + unknown("missing_reset", remaining); + continue; + } + + // Measured pair rates for the CURRENT period only: both sides + // carry this window's resetsAt, are strictly ordered, and are + // at most RATE_WINDOW_MS apart with a non-negative delta. + // Filter to the current period BEFORE pairing: a previous- + // reset observation interleaved in time must not break the + // adjacency of consecutive current-period pairs (property + // coverage, Codex P1 on PR #8522). + const series = [...(byWindow.get(`${pool.id}${w.name}`) ?? [])] + .filter((o) => o.resetsAt === w.resetsAt) + .sort((a, b) => Date.parse(a.at) - Date.parse(b.at)); + const newest = series[series.length - 1]; + if (!newest || nowMs - Date.parse(newest.at) > RATE_WINDOW_MS) { + unknown("no_measured_burn", remaining); + continue; + } + const rates: number[] = []; + for (let i = 1; i < series.length; i++) { + const prev = series[i - 1]; + const last = series[i]; + if (prev.resetsAt !== w.resetsAt || last.resetsAt !== w.resetsAt) continue; + const dtMs = Date.parse(last.at) - Date.parse(prev.at); + const delta = last.used - prev.used; + // Recency, not just separation (Codex P2 on PR #8522): a pair + // whose later side is itself older than RATE_WINDOW_MS before + // now measures obsolete activity, not current burn — two + // qualifying pairs from yesterday plus one observation now + // must not publish a forecast from yesterday's rates. + const ageMs = nowMs - Date.parse(last.at); + if (dtMs > 0 && dtMs <= RATE_WINDOW_MS && ageMs <= RATE_WINDOW_MS && delta >= 0) { + rates.push(delta / (dtMs / 60000)); + } + } + if (rates.length === 0) { + unknown("no_measured_burn", remaining); + continue; + } + if (rates.length < MIN_RATE_SAMPLES) { + unknown("insufficient_observations", remaining); + continue; + } + rates.sort((a, b) => a - b); + const p50 = percentile(rates, 50); + const p80 = percentile(rates, 80); + if (!(p50 > 0)) { + unknown("zero_rate", remaining); + continue; + } + const p50ExhaustsMs = nowMs + (remaining / p50) * 60000; + const p80ExhaustsMs = nowMs + (remaining / p80) * 60000; + forecasts.push({ + ...base, + state: "forecast", + remaining, + sampleRates: rates.length, + ratesPerMin: { p50, p80 }, + p50ExhaustsAt: new Date(p50ExhaustsMs).toISOString(), + p80ExhaustsAt: new Date(p80ExhaustsMs).toISOString(), + p50VsReset: p50ExhaustsMs < resetMs ? "before" : "after", + p80VsReset: p80ExhaustsMs < resetMs ? "before" : "after", + }); + } + out.push(...forecasts); + if (forecasts.length) pool.exhaustion = forecasts; + } + return out; +} diff --git a/pm-stack/aggregator/test/quota-exhaustion.test.ts b/pm-stack/aggregator/test/quota-exhaustion.test.ts new file mode 100644 index 0000000000..61b9453627 --- /dev/null +++ b/pm-stack/aggregator/test/quota-exhaustion.test.ts @@ -0,0 +1,227 @@ +// #3983: per-pool quota exhaustion intervals over the #3933 live +// contract. Oracle: hand-computed pair rates from the observation +// series below — rates are consecutive same-period deltas per minute; +// P50/P80 are nearest-rank; exhaustion = now + remaining / rate. +import { describe, expect, test } from "bun:test"; +import type { PoolWindowObservation } from "../src/burn-history.ts"; +import type { QuotaPool } from "../src/model.ts"; +import { deriveExhaustionForecasts } from "../src/quota-exhaustion.ts"; +import { overlayQuotaCurrent } from "../src/quota-current.ts"; +import type { QuotaCurrentFile, QuotaView } from "../src/model.ts"; + +const NOW = new Date("2026-11-01T02:00:00Z"); +const RESET = "2026-11-01T12:00:00Z"; // 10h after NOW + +function obs(used: number, at: string, resetsAt: string | null = RESET): PoolWindowObservation { + return { pool: "p1", provider: "meta", window: "5h", unit: "tokens", used, resetsAt, at }; +} + +function pool(partial: Partial = {}, windowPartial: Record = {}): QuotaPool { + return { + id: "p1", + provider: "meta", + plan: "pro", + state: "ok", + windows: [ + { name: "5h", unit: "tokens", limit: 10000, used: 4000, resetsAt: RESET, ...windowPartial }, + ], + freshness: { measuredAt: "2026-11-01T01:59:00Z", source: "test-gatherer", state: "ok" }, + ...partial, + } as QuotaPool; +} + +// Pair rates 100, 200, 300 tokens/min; newest obs 30min before NOW +// (inside RATE_WINDOW_MS). Pool remaining is 10000 - 4000 = 6000. +const clean = [ + obs(1000, "2026-11-01T01:00:00Z"), + obs(2000, "2026-11-01T01:10:00Z"), // +1000 over 10min = 100/min + obs(4000, "2026-11-01T01:20:00Z"), // +2000 over 10min = 200/min + obs(7000, "2026-11-01T01:30:00Z"), // +3000 over 10min = 300/min +]; + +describe("deriveExhaustionForecasts (#3983)", () => { + test("measured exhaustion before reset: interval from P50/P80 rates", () => { + const [f] = deriveExhaustionForecasts([pool()], clean, NOW); + expect(f.state).toBe("forecast"); + expect(f.remaining).toBe(6000); + expect(f.ratesPerMin).toEqual({ p50: 200, p80: 300 }); + expect(f.p50ExhaustsAt).toBe("2026-11-01T02:30:00.000Z"); // 6000/200 = 30min + expect(f.p80ExhaustsAt).toBe("2026-11-01T02:20:00.000Z"); // 6000/300 = 20min + expect(f.p50VsReset).toBe("before"); + expect(f.p80VsReset).toBe("before"); + expect(f.rateWindowMs).toBe(120 * 60 * 1000); + expect(f.source).toBe("test-gatherer"); + expect(f.sampleRates).toBe(3); + }); + + test("obsolete pairs do not publish a forecast from yesterday's rates (Codex P2, PR #8522)", () => { + // Two qualifying pairs yesterday (10min apart, inside the rate + // window by separation) plus one observation now: the bridging + // pair spans > RATE_WINDOW_MS, and yesterday's pairs end more + // than RATE_WINDOW_MS before now, so no recent pair remains. + const stale = [ + obs(1000, "2026-10-31T01:00:00Z"), + obs(2000, "2026-10-31T01:10:00Z"), // +100/min, obsolete + obs(4000, "2026-10-31T01:20:00Z"), // +200/min, obsolete + obs(7000, "2026-11-01T01:59:00Z"), // now-side, no recent pair + ]; + const [f] = deriveExhaustionForecasts([pool()], stale, NOW); + expect(f.state).toBe("unknown"); + expect(f.reason).toBe("no_measured_burn"); + }); + + test("slow measured burn puts P50 after reset while P80 lands before", () => { + const slow = [ + obs(3900, "2026-11-01T01:00:00Z"), + obs(3950, "2026-11-01T01:10:00Z"), // 5/min + obs(4000, "2026-11-01T01:20:00Z"), // 5/min + obs(7000, "2026-11-01T01:30:00Z"), // 300/min + ]; + const [f] = deriveExhaustionForecasts([pool()], slow, NOW); + expect(f.state).toBe("forecast"); + expect(f.ratesPerMin).toEqual({ p50: 5, p80: 300 }); + expect(f.p50VsReset).toBe("after"); // 6000/5 = 20h > reset in 10h + expect(f.p80VsReset).toBe("before"); + }); + + test("reset boundary: pairs straddling a reset measure nothing for the current window", () => { + const straddling = [ + obs(9000, "2026-11-01T01:00:00Z", "2026-11-01T01:15:00Z"), // prior period + obs(100, "2026-11-01T01:20:00Z", RESET), // current period starts over + obs(400, "2026-11-01T01:30:00Z", RESET), // one current-period pair only + ]; + const [f] = deriveExhaustionForecasts([pool()], straddling, NOW); + expect(f.state).toBe("unknown"); + expect(f.reason).toBe("insufficient_observations"); + }); + + test("stale source is an explicit unknown, never a forecast", () => { + const stale = pool({ freshness: { measuredAt: "2026-11-01T00:00:00Z", source: "test-gatherer", state: "stale" } }); + const [f] = deriveExhaustionForecasts([stale], clean, NOW); + expect(f.state).toBe("unknown"); + expect(f.reason).toBe("stale_source"); + }); + + test("missing limit and missing reset are explicit unknowns", () => { + const [noLimit] = deriveExhaustionForecasts([pool({}, { limit: null })], clean, NOW); + expect(noLimit).toMatchObject({ state: "unknown", reason: "missing_limit", remaining: null }); + const [noReset] = deriveExhaustionForecasts([pool({}, { resetsAt: null })], clean, NOW); + expect(noReset).toMatchObject({ state: "unknown", reason: "missing_reset", remaining: 6000 }); + }); + + test("no measured burn history is an explicit unknown", () => { + const [f] = deriveExhaustionForecasts([pool()], [], NOW); + expect(f).toMatchObject({ state: "unknown", reason: "no_measured_burn" }); + const old = [obs(1000, "2026-10-31T20:00:00Z"), obs(2000, "2026-10-31T20:10:00Z")]; + const [staleObs] = deriveExhaustionForecasts([pool()], old, NOW); + expect(staleObs).toMatchObject({ state: "unknown", reason: "no_measured_burn" }); + }); + + test("zero measured rate is an explicit unknown, not a fabricated date", () => { + const flat = [obs(4000, "2026-11-01T01:00:00Z"), obs(4000, "2026-11-01T01:10:00Z"), obs(4000, "2026-11-01T01:20:00Z")]; + const [f] = deriveExhaustionForecasts([pool()], flat, NOW); + expect(f).toMatchObject({ state: "unknown", reason: "zero_rate" }); + }); + + test("limit already reached reports exhausted at the collection instant", () => { + const [f] = deriveExhaustionForecasts([pool({}, { used: 10000 })], clean, NOW); + expect(f.state).toBe("exhausted"); + expect(f.remaining).toBe(0); + expect(f.exhaustsAt).toBe(NOW.toISOString()); + }); + + test("a passed reset is unknown even when the dated window is at its limit", () => { + const [f] = deriveExhaustionForecasts( + [pool({}, { used: 10000, resetsAt: "2026-11-01T01:59:00Z" })], + clean, + NOW, + ); + expect(f).toMatchObject({ state: "unknown", reason: "reset_passed", remaining: 0 }); + expect(f.exhaustsAt).toBeUndefined(); + }); + + test("the pool carries its forecasts for view consumers", () => { + const p = pool(); + deriveExhaustionForecasts([p], clean, NOW); + expect(p.exhaustion).toHaveLength(1); + expect(p.exhaustion?.[0].state).toBe("forecast"); + }); + + test("stale or errored source at the limit is unknown, never exhausted (Codex P2, PR #8522)", () => { + for (const state of ["stale", "error"] as const) { + const p = pool({}, { used: 10000 }); + p.freshness = { measuredAt: "2026-11-01T00:00:00Z", source: "test-gatherer", state }; + const [f] = deriveExhaustionForecasts([p], clean, NOW); + expect(f).toMatchObject({ state: "unknown", reason: "stale_source", remaining: 0 }); + } + }); + + test("overlay replacing windows drops forecasts derived from the old windows (Codex P2, PR #8522)", () => { + const p = pool(); + deriveExhaustionForecasts([p], clean, NOW); + expect(p.exhaustion).toHaveLength(1); + const view: QuotaView = { + pools: [{ ...p, id: "p1svc" }], + burn: [], + choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] }, + }; + const file: QuotaCurrentFile = { + version: 1, + generatedAt: NOW.toISOString(), + source: "test-gatherer", + heartbeat: { tickAt: NOW.toISOString(), ok: true, durationMs: 1, perProvider: {} }, + providers: [ + { + providerId: "meta", + providerName: "Meta", + serviceId: "p1svc", + state: "ok", + measuredAt: NOW.toISOString(), + source: "test-gatherer", + windows: [{ name: "5h", pctOfLimit: 10, resetsAt: RESET }], + }, + ], + }; + const out = overlayQuotaCurrent(view, file, NOW); + expect(out.pools[0].windows[0].used).toBe(10); + expect(out.pools[0].exhaustion).toBeUndefined(); + }); + + // Property coverage (Codex P1, PR #8522). Oracle: the invariants + // themselves over generated histories from a seeded PRNG (no new + // dependency; the seed makes every failure reproducible). + test("properties: P80 never exhausts later than P50; foreign/reset-straddling obs never change a forecast", () => { + let seed = 0x3983; + const rnd = () => { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed / 0x7fffffff; + }; + for (let iter = 0; iter < 200; iter++) { + const n = 3 + Math.floor(rnd() * 6); // 3..8 observations -> 2..7 pair rates + const series: PoolWindowObservation[] = []; + let used = Math.floor(rnd() * 2000); + let t = Date.parse("2026-11-01T00:30:00Z"); + for (let i = 0; i < n; i++) { + series.push(obs(used, new Date(t).toISOString())); + used += Math.floor(rnd() * 900); + t += (5 + Math.floor(rnd() * 10)) * 60000; + } + const newestMs = Date.parse(series[series.length - 1].at); + const now = new Date(newestMs + 30 * 60000); + const mkPool = () => pool({}, { used: Math.min(used, 9000) }); + const [f] = deriveExhaustionForecasts([mkPool()], series, now); + if (f.state === "forecast") { + expect(f.ratesPerMin!.p80).toBeGreaterThanOrEqual(f.ratesPerMin!.p50); + expect(Date.parse(f.p80ExhaustsAt!)).toBeLessThanOrEqual(Date.parse(f.p50ExhaustsAt!)); + } + // Foreign-pool observations and previous-reset observations are noise: + const noisy = [ + ...series, + { pool: "other", provider: "meta", window: "5h", unit: "tokens", used: 99999, resetsAt: RESET, at: series[0].at }, + obs(99999, series[0].at, "2026-10-31T12:00:00Z"), + ]; + const [g] = deriveExhaustionForecasts([mkPool()], noisy, now); + expect(g).toEqual(f); + } + }); +});