From 9fa5ba868046abc0088ebe00a8f64a750cd0616d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:38:15 -0600 Subject: [PATCH] =?UTF-8?q?feat(pm-agg):=20forecast=20input=20for=20quota?= =?UTF-8?q?=20admission=20=E2=80=94=20Stage-3=20S4=20slice=20for=20#12698?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Design D4: buildQuotaAdmission gains an optional forecasts input, supplied per exact billing scope like observations. A window opts in via forecastMarginMs; a fresh forecast projected from the window's current reading (state projected, wallsBeforeReset, wall at least the margin before reset) adds pace_hold to an otherwise eligible window. Stale, superseded, conflicting or honesty-state forecasts are exactly current behaviour (criterion 3). No forecast input = byte-identical projection. Plus the D4 flag in PM_AGG_STORE_BACKEND posture (quota-admission-forecast-config.ts): PM_AGG_FORECAST_ADMISSION off by default; on requires the one named pool and a positive margin; invalid values throw. Flipping back is the whole rollback. Nothing is enabled by this change; go-live stays gated on S3's shadow week. --- .../src/quota-admission-forecast-config.ts | 54 ++++++ pm-stack/aggregator/src/quota-admission.ts | 100 +++++++++- .../quota-admission-forecast-config.test.ts | 59 ++++++ .../test/quota-admission-forecast.test.ts | 176 ++++++++++++++++++ 4 files changed, 388 insertions(+), 1 deletion(-) create mode 100644 pm-stack/aggregator/src/quota-admission-forecast-config.ts create mode 100644 pm-stack/aggregator/test/quota-admission-forecast-config.test.ts create mode 100644 pm-stack/aggregator/test/quota-admission-forecast.test.ts diff --git a/pm-stack/aggregator/src/quota-admission-forecast-config.ts b/pm-stack/aggregator/src/quota-admission-forecast-config.ts new file mode 100644 index 0000000000..96876cdbd3 --- /dev/null +++ b/pm-stack/aggregator/src/quota-admission-forecast-config.ts @@ -0,0 +1,54 @@ +// Live forecast-admission switch for Stage-3 S4 (#12698, epic +// #12694; design doc/2026-11-22T22-35-00Z_design_quota-plane-stage-3, +// decision D4), in the PM_AGG_STORE_BACKEND posture (store-backend.ts): +// +// PM_AGG_FORECAST_ADMISSION "off" (default) | "on" +// PM_AGG_FORECAST_ADMISSION_POOL canonical provider id of the ONE +// pool forecast admission is live +// for (required when on) +// PM_AGG_FORECAST_ADMISSION_MARGIN_MS +// a projected wall at least this +// many ms before the window reset +// yields pace_hold (required when +// on; positive integer) +// +// The default is today's behaviour: no forecast input reaches the +// admission projection. Flipping the flag back to "off" is the whole +// rollback — no deploy, no data change. Pool and margin are +// configuration set from the S2 calibration (#12696); once live they +// change only via the design's proposal mechanism (D5). An assembler +// that supplies forecast rows to buildQuotaAdmission reads this +// config; the projection itself stays pure and env-free. Any invalid +// value fails loudly, never silently defaults. + +export interface ForecastAdmissionConfig { + enabled: boolean; + /** Canonical provider id of the one live pool; null while off. */ + providerId: string | null; + /** Configured margin in ms; null while off. */ + marginMs: number | null; +} + +export function parseForecastAdmissionConfig( + env: Record = process.env, +): ForecastAdmissionConfig { + const raw = (env.PM_AGG_FORECAST_ADMISSION ?? "").trim(); + if (raw === "" || raw === "off") return { enabled: false, providerId: null, marginMs: null }; + if (raw !== "on") { + throw new Error( + `Invalid PM_AGG_FORECAST_ADMISSION=${JSON.stringify(env.PM_AGG_FORECAST_ADMISSION)}; expected "off" or "on"`, + ); + } + const providerId = (env.PM_AGG_FORECAST_ADMISSION_POOL ?? "").trim(); + if (!providerId) { + throw new Error("PM_AGG_FORECAST_ADMISSION=on requires PM_AGG_FORECAST_ADMISSION_POOL (the one live pool)"); + } + const marginRaw = (env.PM_AGG_FORECAST_ADMISSION_MARGIN_MS ?? "").trim(); + const marginMs = Number(marginRaw); + if (!marginRaw || !Number.isInteger(marginMs) || marginMs <= 0) { + throw new Error( + `Invalid PM_AGG_FORECAST_ADMISSION_MARGIN_MS=${JSON.stringify(env.PM_AGG_FORECAST_ADMISSION_MARGIN_MS)}; expected a positive integer (ms)`, + ); + } + return { enabled: true, providerId, marginMs }; +} diff --git a/pm-stack/aggregator/src/quota-admission.ts b/pm-stack/aggregator/src/quota-admission.ts index ced4c38568..446400036d 100644 --- a/pm-stack/aggregator/src/quota-admission.ts +++ b/pm-stack/aggregator/src/quota-admission.ts @@ -3,6 +3,19 @@ * windows; dashboard pool/service labels are deliberately not accepted as identity. * Times are epoch milliseconds. Prior walls/stops must be carried by the caller; * omission is NOT a release protocol. This module neither fetches nor persists. + * + * Stage-3 S4 (#12698, design D4): the caller may also carry forecast rows + * (the S1 projection, per exact billing scope like observations). A fresh + * forecast projected from the window's current reading that says projected + * + wallsBeforeReset, with the projected wall at least the window's + * configured forecastMarginMs before the reset, adds pace_hold to an + * otherwise eligible window — and can do nothing else: it never overrides + * a measured verdict, never manufactures evidence for an unknown window, + * and a stale, superseded, conflicting or honesty-state forecast is + * exactly current behaviour (#12698 criterion 3). Pool-level consumption + * exclusions from S2's calibration (e.g. the bare opencode-go monthly + * series) are the caller's duty: display pool identity is not accepted + * here, so the caller assembles rows only for scopes it may consume. */ export type Verdict = "eligible" | "unknown" | "pace_hold" | "walled" | "stopped"; export interface Scope { @@ -21,6 +34,10 @@ export interface Binding extends Scope { collectionMs: number; reservePct?: number; pacePpHour?: number; + /** S4: a projected wall at least this many ms before the reset + * yields pace_hold. Absent = forecasts never affect this window + * (per-window opt-in; the one live pool's windows carry it). */ + forecastMarginMs?: number; }[]; } export interface Observation extends Scope { @@ -49,12 +66,28 @@ export interface PriorWall extends Scope { resetsAt: number; evidenceId: string; } +export interface Forecast extends Scope { + kind: string; + period: string; + /** Evidence id of the forecast row (the S1 product/ledger row). */ + id: string; + /** The underlying reading's stamp the projection was made from. */ + measuredAt: number; + resetsAt: number; + /** The S1 projection state, verbatim (quota-analytics ProjectionState). */ + state: "projected" | "walled" | "no-wall-before-reset" | "insufficient-history"; + /** Projected instant the window reaches 100%, epoch ms. */ + projectedWallAt: number | null; + wallsBeforeReset: boolean | null; +} export interface AdmissionInput { generation: string; bindings: readonly Binding[]; observations: readonly Observation[]; stops: readonly Stop[]; priorWalls: readonly PriorWall[]; + /** S4 forecast rows, per exact scope; absent = pre-S4 behaviour. */ + forecasts?: readonly Forecast[]; } export interface WindowDecision { kind: string; @@ -93,6 +126,62 @@ const validScope = (s: Scope) => [s.provider, s.account, s.bucket].every(nonempt const sorted = (s: readonly string[]) => [...new Set(s)].sort(); const worst = (v: Verdict[]) => v.reduce((a, b) => (rank[a] >= rank[b] ? a : b), "eligible"); +/** The one forecast row that may speak for this window, or null. A row + * speaks only when it is the latest, internally consistent, projected + * from the window's current reading, and still fresh by the same bound + * the measured path applies to observations; every other row — stale, + * superseded, conflicting, or an honesty state — is current behaviour + * (#12698 criterion 3), never a reason and never a hold. */ +function applicableForecast( + input: AdmissionInput, + b: Binding, + w: Binding["windows"][number], + now: number, + latestMeasuredAt: number | null, +): Forecast | null { + const rows = (input.forecasts ?? []).filter( + (x) => same(x, b) && x.kind === w.kind && x.period === w.period && x.resetsAt === w.resetsAt, + ); + if (!rows.length) return null; + const ids = new Map(); + for (const x of rows) { + if ( + !nonempty(x.id) || + !finite(x.measuredAt) || + x.measuredAt > now || + (x.projectedWallAt !== null && !finite(x.projectedWallAt)) || + (x.wallsBeforeReset !== null && typeof x.wallsBeforeReset !== "boolean") || + (x.state !== "projected" && + x.state !== "walled" && + x.state !== "no-wall-before-reset" && + x.state !== "insufficient-history") + ) + return null; + const signature = JSON.stringify([x.measuredAt, x.state, x.projectedWallAt, x.wallsBeforeReset]); + if (ids.has(x.id) && ids.get(x.id) !== signature) return null; + ids.set(x.id, signature); + } + const unique = [...new Map(rows.map((x) => [x.id, x])).values()].sort( + (a, c) => c.measuredAt - a.measuredAt || ordinal(a.id, c.id), + ); + const latest = unique[0]; + const tied = unique.filter((x) => x.measuredAt === latest.measuredAt); + if ( + tied.some( + (x) => + x.state !== latest.state || + x.projectedWallAt !== latest.projectedWallAt || + x.wallsBeforeReset !== latest.wallsBeforeReset, + ) + ) + return null; + if (latest.state !== "projected" || latest.wallsBeforeReset !== true || latest.projectedWallAt === null) return null; + if (latest.projectedWallAt >= w.resetsAt) return null; + if (now - latest.measuredAt > Math.min(w.freshnessMs, 60 * 60_000)) return null; + if (latestMeasuredAt === null || latest.measuredAt < latestMeasuredAt) return null; + return latest; +} + function projectWindow(input: AdmissionInput, b: Binding, w: Binding["windows"][number], now: number): WindowDecision { const out: WindowDecision = { kind: w.kind, @@ -120,7 +209,8 @@ function projectWindow(input: AdmissionInput, b: Binding, w: Binding["windows"][ !finite(w.collectionMs) || w.collectionMs <= 0 || (w.reservePct !== undefined && (!finite(w.reservePct) || w.reservePct < 0 || w.reservePct > 100)) || - (w.pacePpHour !== undefined && (!finite(w.pacePpHour) || w.pacePpHour < 0)) + (w.pacePpHour !== undefined && (!finite(w.pacePpHour) || w.pacePpHour < 0)) || + (w.forecastMarginMs !== undefined && (!finite(w.forecastMarginMs) || w.forecastMarginMs < 0)) ) return unknown("invalid_window_policy"); if (w.resetsAt <= now) return unknown("period_expired"); @@ -234,6 +324,14 @@ function projectWindow(input: AdmissionInput, b: Binding, w: Binding["windows"][ out.reasons.push("projected_exhaustion"); if (previous) out.evidenceIds = sorted([...out.evidenceIds, previous.id]); } + if (out.verdict === "eligible" && w.forecastMarginMs !== undefined) { + const f = applicableForecast(input, b, w, now, out.measuredAt); + if (f && f.projectedWallAt !== null && w.resetsAt - f.projectedWallAt >= w.forecastMarginMs) { + out.verdict = "pace_hold"; + out.reasons.push("forecast_projected_wall"); + out.evidenceIds = sorted([...out.evidenceIds, f.id]); + } + } if (out.verdict === "eligible") out.reasons.push("fresh_window"); return out; } diff --git a/pm-stack/aggregator/test/quota-admission-forecast-config.test.ts b/pm-stack/aggregator/test/quota-admission-forecast-config.test.ts new file mode 100644 index 0000000000..0b461bcad2 --- /dev/null +++ b/pm-stack/aggregator/test/quota-admission-forecast-config.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from "bun:test"; +import { parseForecastAdmissionConfig } from "../src/quota-admission-forecast-config.ts"; + +// Oracle: Stage-3 design D4 (#12698) — live forecast admission enters +// behind a backend-style flag in the PM_AGG_STORE_BACKEND posture: +// default is today's behaviour, the flag names ONE pool and the +// configured margin, and flipping the flag back is the whole rollback. +// Invalid configuration fails loudly, never silently defaults. +describe("forecast admission flag: oracle = design D4 flag posture", () => { + test("unset flag is off — today's behaviour is the default", () => { + expect(parseForecastAdmissionConfig({})).toEqual({ enabled: false, providerId: null, marginMs: null }); + }); + + test("explicit off is off even with pool and margin present", () => { + const c = parseForecastAdmissionConfig({ + PM_AGG_FORECAST_ADMISSION: "off", + PM_AGG_FORECAST_ADMISSION_POOL: "opendesign", + PM_AGG_FORECAST_ADMISSION_MARGIN_MS: "3600000", + }); + expect(c.enabled).toBe(false); + }); + + test("on requires a named pool and a positive margin", () => { + expect(() => parseForecastAdmissionConfig({ PM_AGG_FORECAST_ADMISSION: "on" })).toThrow(); + expect(() => + parseForecastAdmissionConfig({ PM_AGG_FORECAST_ADMISSION: "on", PM_AGG_FORECAST_ADMISSION_POOL: "opendesign" }), + ).toThrow(); + expect(() => + parseForecastAdmissionConfig({ + PM_AGG_FORECAST_ADMISSION: "on", + PM_AGG_FORECAST_ADMISSION_POOL: "opendesign", + PM_AGG_FORECAST_ADMISSION_MARGIN_MS: "0", + }), + ).toThrow(); + expect(() => + parseForecastAdmissionConfig({ + PM_AGG_FORECAST_ADMISSION: "on", + PM_AGG_FORECAST_ADMISSION_POOL: "opendesign", + PM_AGG_FORECAST_ADMISSION_MARGIN_MS: "abc", + }), + ).toThrow(); + }); + + test("on with pool and margin parses", () => { + expect( + parseForecastAdmissionConfig({ + PM_AGG_FORECAST_ADMISSION: "on", + PM_AGG_FORECAST_ADMISSION_POOL: "opendesign", + PM_AGG_FORECAST_ADMISSION_MARGIN_MS: "3600000", + }), + ).toEqual({ enabled: true, providerId: "opendesign", marginMs: 3_600_000 }); + }); + + test("an unrecognized flag value fails loudly", () => { + expect(() => parseForecastAdmissionConfig({ PM_AGG_FORECAST_ADMISSION: "yes" })).toThrow( + /PM_AGG_FORECAST_ADMISSION/, + ); + }); +}); diff --git a/pm-stack/aggregator/test/quota-admission-forecast.test.ts b/pm-stack/aggregator/test/quota-admission-forecast.test.ts new file mode 100644 index 0000000000..d44eeb08df --- /dev/null +++ b/pm-stack/aggregator/test/quota-admission-forecast.test.ts @@ -0,0 +1,176 @@ +import { describe, expect, test } from "bun:test"; +import { type AdmissionInput, buildQuotaAdmission, type Forecast, type Observation } from "../src/quota-admission.ts"; + +// Oracle: Stage-3 design D4 (#12698, epic #12694) — a window whose +// forecast says projected with wallsBeforeReset and a projected wall at +// least the configured margin before the reset yields pace_hold — plus +// #12698 criterion 3: no decision is ever taken on a stale or +// honesty-flagged forecast (stale forecast = current behaviour). The +// forecast may only ever add a pace_hold to an otherwise eligible +// window; it never overrides a measured verdict and never manufactures +// evidence for an unknown window. +const now = 10_000_000; +const scope = { provider: "go", account: "a", bucket: "plan" }; +const resetsAt = now + 86_400_000; +const marginMs = 3_600_000; + +const read = (patch: Partial = {}): Observation => ({ + ...scope, + kind: "monthly", + period: "p1", + id: "new", + source: "fixture", + measuredAt: now, + resetsAt, + percent: 50, + state: "ok", + denominator: "100", + ...patch, +}); + +const fc = (patch: Partial = {}): Forecast => ({ + ...scope, + kind: "monthly", + period: "p1", + id: "fc-1", + measuredAt: now, + resetsAt, + state: "projected", + projectedWallAt: now + 3_600_000, + wallsBeforeReset: true, + ...patch, +}); + +function fixture(patch: Partial = {}, windowPatch: Record = {}): AdmissionInput { + return { + generation: "fixture-v1", + bindings: [ + { + ...scope, + aliases: ["cred-a"], + windows: [ + { + kind: "monthly", + period: "p1", + resetsAt, + freshnessMs: 1_200_000, + collectionMs: 900_000, + forecastMarginMs: marginMs, + ...windowPatch, + }, + ], + }, + ], + observations: [read()], + stops: [], + priorWalls: [], + forecasts: [fc()], + ...patch, + }; +} + +const account = (f: AdmissionInput) => buildQuotaAdmission(f, now).accounts[0]; +const window = (f: AdmissionInput) => account(f).windows[0]; + +describe("quota admission forecast input: oracle = design D4 + #12698 criterion 3", () => { + test("projected wall at least the margin before reset yields pace_hold", () => { + const f = fixture(); + expect(account(f).verdict).toBe("pace_hold"); + expect(window(f).reasons).toContain("forecast_projected_wall"); + expect(window(f).evidenceIds).toContain("fc-1"); + }); + + test("wall exactly at the margin holds (at least the configured margin)", () => { + const f = fixture({ forecasts: [fc({ projectedWallAt: resetsAt - marginMs })] }); + expect(account(f).verdict).toBe("pace_hold"); + }); + + test("wall inside the margin does not hold", () => { + const f = fixture({ forecasts: [fc({ projectedWallAt: resetsAt - marginMs + 1 })] }); + expect(account(f).verdict).toBe("eligible"); + expect(window(f).reasons).toEqual(["fresh_window"]); + }); + + test("no forecast input is byte-identical to the pre-S4 projection", () => { + const without = fixture(); + delete (without as { forecasts?: unknown }).forecasts; + (without.bindings[0].windows[0] as { forecastMarginMs?: number }).forecastMarginMs = undefined; + const a = buildQuotaAdmission(without, now); + const b = fixture({ forecasts: [] }); + delete (b.bindings[0].windows[0] as { forecastMarginMs?: number }).forecastMarginMs; + expect(buildQuotaAdmission(b, now)).toEqual(a); + expect(account(without).verdict).toBe("eligible"); + }); + + test("window without forecastMarginMs ignores forecasts (per-window opt-in)", () => { + const f = fixture(); + delete (f.bindings[0].windows[0] as { forecastMarginMs?: number }).forecastMarginMs; + expect(account(f).verdict).toBe("eligible"); + }); + + test("honesty states never hold: insufficient-history, no-wall-before-reset, walled forecast", () => { + for (const patch of [ + { state: "insufficient-history" as const, projectedWallAt: null, wallsBeforeReset: null }, + { state: "no-wall-before-reset" as const, projectedWallAt: resetsAt + 3_600_000, wallsBeforeReset: false }, + { state: "walled" as const, projectedWallAt: now, wallsBeforeReset: true }, + ]) { + const f = fixture({ forecasts: [fc(patch)] }); + expect(account(f).verdict).toBe("eligible"); + expect(window(f).reasons).toEqual(["fresh_window"]); + } + }); + + test("stale forecast = current behaviour (criterion 3)", () => { + const f = fixture({ forecasts: [fc({ measuredAt: now - 1_200_001 })] }); + expect(account(f).verdict).toBe("eligible"); + expect(window(f).reasons).toEqual(["fresh_window"]); + expect(window(f).evidenceIds).not.toContain("fc-1"); + }); + + test("forecast projected from a superseded reading does not hold", () => { + const f = fixture({ + observations: [ + read({ id: "old", measuredAt: now - 900_000, percent: 40 }), + read({ id: "new", measuredAt: now, percent: 50 }), + ], + forecasts: [fc({ measuredAt: now - 900_000 })], + }); + expect(account(f).verdict).toBe("eligible"); + }); + + test("forecast never overrides a measured wall", () => { + const f = fixture({ observations: [read({ percent: 100 })] }); + expect(account(f).verdict).toBe("walled"); + expect(window(f).reasons).toEqual(["known_100"]); + }); + + test("forecast never manufactures evidence for an unknown window", () => { + const f = fixture({ observations: [] }); + expect(account(f).verdict).toBe("unknown"); + expect(window(f).reasons).toEqual(["missing_observation"]); + }); + + test("forecast for a different period is ignored", () => { + const f = fixture({ forecasts: [fc({ period: "p2" })] }); + expect(account(f).verdict).toBe("eligible"); + }); + + test("conflicting duplicate forecast ids are ignored, byte-equivalent duplicates still hold", () => { + const conflict = fixture({ forecasts: [fc(), fc({ projectedWallAt: now + 7_200_000 })] }); + expect(account(conflict).verdict).toBe("eligible"); + const dup = fixture({ forecasts: [fc(), fc()] }); + expect(account(dup).verdict).toBe("pace_hold"); + }); + + test("forecast does not stack reasons on a measured pace_hold", () => { + const f = fixture({}, { reservePct: 40 }); + expect(account(f).verdict).toBe("pace_hold"); + expect(window(f).reasons).toEqual(["reserve_threshold"]); + }); + + test("invalid forecastMarginMs is an invalid window policy", () => { + const f = fixture({}, { forecastMarginMs: -1 }); + expect(account(f).verdict).toBe("unknown"); + expect(window(f).reasons).toEqual(["invalid_window_policy"]); + }); +});