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
4 changes: 4 additions & 0 deletions pm-stack/aggregator/scripts/collect-fleet-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1234,6 +1235,9 @@ async function main(): Promise<void> {
ratesSet += 1;
}
}
// Exhaustion intervals (#3983) compose the same observations:
// per-pool forecasts ride on the pool like burnTokensPerMin.
deriveExhaustionForecasts(pools, mergedObservations, now);
Comment thread
dezren39 marked this conversation as resolved.
Resolved
markSection("burnHistory", burnSegments.length || ratesSet ? "ok" : "skipped");
} catch (err) {
console.error("collector: burn-history derivation failed; burn stays empty this run");
Expand Down
40 changes: 40 additions & 0 deletions pm-stack/aggregator/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
8 changes: 8 additions & 0 deletions pm-stack/aggregator/src/quota-current.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
160 changes: 160 additions & 0 deletions pm-stack/aggregator/src/quota-exhaustion.ts
Original file line number Diff line number Diff line change
@@ -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<string, PoolWindowObservation[]>();
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<ExhaustionForecast["reason"]>, 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;
Comment thread
dezren39 marked this conversation as resolved.
Resolved
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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));
Comment thread
dezren39 marked this conversation as resolved.
Resolved
}
}
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;
}
Loading
Loading