diff --git a/pm-stack/aggregator/c4-methodology-log.jsonl b/pm-stack/aggregator/c4-methodology-log.jsonl new file mode 100644 index 0000000000..3fdff105cb --- /dev/null +++ b/pm-stack/aggregator/c4-methodology-log.jsonl @@ -0,0 +1 @@ +{"change":"First C4 methodology. downtime_window records (C4.1, #13257) derive the complete-downtime interval by intersecting the Stage-3 S1 per-pool wall intervals [wall, reset) across every routing pool (keyed by canonical provider id), basis since_last_reset; the prediction range is [latest member wall, earliest member reset), rendered by the §4 formatter at issuance. Providers the forecast cannot project publish insufficient_history and veto a no-window verdict; a defensible no-window tick publishes no record. No day-type or spike-day adjustments (inputs.adjustments is []).","evidence":["doc/2026-11-13T15-12-00Z_design_reporting-architecture-event-driven/c4-forecasting-design.md","#12695 forecast product (quota-forecast.json)"],"expected_effect":"Downtime-window predictions exist on every gatherer tick and are scorable per design §3 (start/end error, interval overlap); §3's accuracy bar is coverage inside the calibrated band with median window error under one gatherer tick span at one-tick lead.","reason":"The C4 design (doc/2026-11-13T15-12-00Z_design_reporting-architecture-event-driven/c4-forecasting-design.md, PR #13268) specifies the record, scoring, and methodology-log formats, and S1's same-period pace projection is the only measured per-pool wall source; §5 adjustments are data-gated below their sufficiency thresholds.","review_after":"2026-12-21","ts":"2026-11-23T13:10:00.000Z","version":"c4-meth:1"} \ No newline at end of file diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index 3294d0bc74..1504e8d111 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -183,6 +183,7 @@ import { loadOpenChamberLib, resolveLibDir as resolveOpenChamberLib } from "../s import { readProviderAuthAlerts } from "../src/provider-auth-alerts.ts"; import { projectPoolState } from "../src/pool-state.ts"; import { buildForecastLedgerRows, buildQuotaForecast, type QuotaForecastFile } from "../src/quota-forecast.ts"; +import { buildDowntimeLedgerRows, deriveDowntimeWindowRecords } from "../src/quota-downtime.ts"; import { buildShadowPlacement } from "../src/quota-shadow-placement.ts"; import { anomalyIncidentInput, @@ -225,6 +226,10 @@ const poolStatePath = process.env.POOL_STATE_PATH ?? join(HOME, ".local/state/op // #12695: the Stage-3 forecast product, beside quota-current.json // (design D1: same directory, same fail-soft posture). const forecastPath = process.env.QUOTA_FORECAST_PATH ?? join(dirname(currentPath), "quota-forecast.json"); +// #13257: the C4 prediction log (design §1), beside quota-current.json +// like the forecast product — append-only, one JSONL record per +// prediction, monthly rotation like the snapshot store. +const predictionsPath = process.env.QUOTA_PREDICTIONS_PATH ?? join(dirname(currentPath), "quota-predictions.jsonl"); // #12697: the Stage-3 shadow placement record (design D3), beside // quota-current.json like the forecast: the latest diff record plus // the append-only history the weekly review (S7) scores. @@ -1281,6 +1286,49 @@ export async function main(): Promise { ); } + // C4.1 (#13257, component of #9572; C4 design §1/§7): the + // complete-downtime prediction records — derived by + // src/quota-downtime.ts from this tick's forecast product, + // appended to the C4 prediction log beside the forecast + // product, and mirrored into the Turso ledger under the C4 + // source "quota-prediction". Advisory only: no placement path + // reads them (the C6 pages and forecast alerts consume them). + // Fail-soft like the forecast write; a null forecast (the + // block above failed) derives nothing — the previous records + // stand and age with the previous forecast. The supersedes + // link reads the log's tail for the last downtime record per + // pool set; a missing or torn log just starts the chain over. + if (forecast) { + try { + const previous = new Map(); + const existing = await readFile(predictionsPath, "utf8").catch(() => ""); + for (const line of existing.split("\n").slice(-500)) { + if (!line.trim()) continue; + try { + const parsed = JSON.parse(line) as { kind?: string; id?: string; subject?: { pools?: string[] } }; + if (parsed.kind === "downtime_window" && parsed.id && parsed.subject?.pools) { + previous.set(parsed.subject.pools.join("+"), parsed.id); + } + } catch { + // A torn last line is not fatal. + } + } + const records = deriveDowntimeWindowRecords(forecast, previous); + if (records.length) { + await mkdir(dirname(predictionsPath), { recursive: true }); + await appendFile(predictionsPath, records.map((r) => JSON.stringify(r)).join("\n") + "\n", "utf8"); + await writeTursoForecastRecords(buildDowntimeLedgerRows(records, tickAt), tickAt); + } + console.log( + `quota-gatherer: downtime predictions ${records.map((r) => r.state).join(",") || "none"} -> ${predictionsPath}`, + ); + } catch (err) { + console.error( + `quota-gatherer: downtime failed-soft: ${safeProviderReason(err instanceof Error ? err.message : String(err))}`, + ); + } + } + // Stage-3 S3 (#12697, design D3): the shadow placement record — // the forecast-informed ordering logged beside the live ordering // as a per-decision diff record (src/quota-shadow-placement.ts), diff --git a/pm-stack/aggregator/src/quota-downtime.test.ts b/pm-stack/aggregator/src/quota-downtime.test.ts new file mode 100644 index 0000000000..6c1144c0ba --- /dev/null +++ b/pm-stack/aggregator/src/quota-downtime.test.ts @@ -0,0 +1,291 @@ +import { describe, expect, test } from "bun:test"; +import { + buildDowntimeLedgerRows, + deriveDowntimeWindowRecords, + renderPredictionRange, + C4_METHODOLOGY_VERSION, + PREDICTION_LEDGER_SOURCE, +} from "./quota-downtime.ts"; +import type { QuotaForecastFile, QuotaForecastPool, QuotaForecastWindow } from "./quota-forecast.ts"; + +// Oracle: the C4 design (doc/2026-11-13T15-12-00Z_design_reporting- +// architecture-event-driven/c4-forecasting-design.md §1 + §7, PR +// #13268) over the #12695 forecast product, and #13257 acceptance +// criteria 1 and 3. A downtime_window record is the design's +// prediction record: the all-walled interval intersected from the +// per-pool [wall, reset) intervals, earliest = the last member +// wall, latest = the earliest member reset, basis named, rendered +// stored; a window with no defensible basis is the published +// insufficient_history honesty state, and a defensible no-window +// verdict publishes NO record (absence is the scored signal). + +const AS_OF = "2026-11-23T12:00:00.000Z"; // 06:00 in America/Chicago +const H = 3_600_000; +const at = (hours: number) => new Date(Date.parse(AS_OF) + hours * H).toISOString(); + +function fwindow(over: Partial = {}): QuotaForecastWindow { + return { + name: "weekly", + state: "projected", + ratePtsPerHour: 5, + samples: 12, + projectedWallAt: Date.parse(at(2)), + durationUntilWallMs: 2 * H, + wallsBeforeReset: true, + pctNow: 90, + measuredAt: AS_OF, + resetsAt: at(10), + ...over, + }; +} + +function pool(providerId: string, windows: QuotaForecastWindow[], serviceId = `${providerId}-svc`): QuotaForecastPool { + return { providerId, serviceId, plan: null, windows }; +} + +function forecast(pools: Record): QuotaForecastFile { + return { version: 1, generatedAt: AS_OF, source: "gather-quota", pools }; +} + +describe("deriveDowntimeWindowRecords", () => { + test("overlapping walls publish one design-shaped predicted record", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [pool("a", [fwindow({ projectedWallAt: Date.parse(at(2)), resetsAt: at(10) })])], + b: [pool("b", [fwindow({ projectedWallAt: Date.parse(at(4)), resetsAt: at(8) })])], + }), + ); + expect(records).toHaveLength(1); + const r = records[0]; + expect(r.record_version).toBe(1); + expect(r.kind).toBe("downtime_window"); + expect(r.id).toBe(`c4:downtime_window:a+b@${Date.parse(at(4))}:${Date.parse(AS_OF)}`); + expect(r.subject.pools).toEqual(["a", "b"]); + expect(r.issued_at).toBe(AS_OF); + expect(r.basis.name).toBe("since_last_reset"); + expect(r.inputs.samples).toBe(24); + expect(r.inputs.adjustments).toEqual([]); + expect(r.methodology_version).toBe(C4_METHODOLOGY_VERSION); + expect(r.state).toBe("predicted"); + expect(r.state_reason).toBeNull(); + expect(r.supersedes).toBeNull(); + // earliest = the last member wall; latest = the earliest + // member reset (the first reopening ends the window). + expect(r.prediction?.earliest).toBe(at(4)); + expect(r.prediction?.latest).toBe(at(8)); + // 10:00 -> 14:00 Chicago, same day: duration form (§4). + expect(r.prediction?.rendered).toBe("between 4 and 8 hours from now"); + }); + + test("supersedes links the previous record for the same pool set", () => { + const prev = new Map([["a+b", "c4:downtime_window:a+b@111:222"]]); + const records = deriveDowntimeWindowRecords( + forecast({ + a: [pool("a", [fwindow()])], + b: [pool("b", [fwindow()])], + }), + prev, + ); + expect(records[0].supersedes).toBe("c4:downtime_window:a+b@111:222"); + }); + + test("pools already walled at the tick: the window is in progress, rendered in calendar form", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [ + pool("a", [ + fwindow({ state: "walled", projectedWallAt: null, durationUntilWallMs: 0, pctNow: 100, resetsAt: at(6) }), + ]), + ], + b: [ + pool("b", [ + fwindow({ state: "walled", projectedWallAt: null, durationUntilWallMs: 0, pctNow: 100, resetsAt: at(9) }), + ]), + ], + }), + ); + expect(records).toHaveLength(1); + expect(records[0].prediction?.earliest).toBe(AS_OF); + expect(records[0].prediction?.latest).toBe(at(6)); + // 06:00 -> 12:00 Chicago, start not in the future: dayparts. + expect(records[0].prediction?.rendered).toBe("between this morning and this afternoon"); + }); + + test("a pool that never walls: the defensible no-window verdict publishes NO record", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [pool("a", [fwindow()])], + b: [ + pool("b", [ + fwindow({ state: "no-wall-before-reset", projectedWallAt: null, wallsBeforeReset: false, pctNow: 40 }), + ]), + ], + }), + ); + expect(records).toEqual([]); + }); + + test("walls that never coincide publish no record either", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [pool("a", [fwindow({ projectedWallAt: Date.parse(at(1)), resetsAt: at(3) })])], + b: [pool("b", [fwindow({ projectedWallAt: Date.parse(at(5)), resetsAt: at(9) })])], + }), + ); + expect(records).toEqual([]); + }); + + test("an unprojectable pool with no known overlap publishes the honesty state, never a range", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [pool("a", [fwindow({ projectedWallAt: Date.parse(at(1)), resetsAt: at(3) })])], + b: [ + pool("b", [ + fwindow({ + state: "insufficient-history", + projectedWallAt: null, + wallsBeforeReset: null, + pctNow: null, + reason: "fewer than two same-period readings spanning 10 minutes", + }), + ]), + ], + }), + ); + expect(records).toHaveLength(1); + expect(records[0].state).toBe("insufficient_history"); + expect(records[0].prediction).toBeNull(); + expect(records[0].state_reason).toContain("b"); + }); + + test("unknown windows cannot remove a known overlap: predicted, unknowns named in the basis detail", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [ + pool("a", [ + fwindow({ projectedWallAt: Date.parse(at(2)), resetsAt: at(10) }), + fwindow({ + name: "5-hour", + state: "insufficient-history", + projectedWallAt: null, + wallsBeforeReset: null, + pctNow: null, + resetsAt: at(5), + reason: "fewer than two same-period readings spanning 10 minutes", + }), + ]), + ], + b: [pool("b", [fwindow({ projectedWallAt: Date.parse(at(3)), resetsAt: at(9) })])], + }), + ); + expect(records).toHaveLength(1); + expect(records[0].state).toBe("predicted"); + expect(records[0].prediction?.earliest).toBe(at(3)); + expect(records[0].basis.detail).toContain("a"); + }); + + test("a provider is down while ANY of its pool rows' windows is down", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [ + pool("a", [fwindow({ name: "5-hour", projectedWallAt: Date.parse(at(1)), resetsAt: at(2) })], "a-one"), + pool( + "a", + [fwindow({ state: "no-wall-before-reset", projectedWallAt: null, wallsBeforeReset: false, pctNow: 30 })], + "a-two", + ), + ], + b: [pool("b", [fwindow({ projectedWallAt: Date.parse(at(1.5)), resetsAt: at(5) })])], + }), + ); + expect(records).toHaveLength(1); + expect(records[0].prediction?.earliest).toBe(at(1.5)); + expect(records[0].prediction?.latest).toBe(at(2)); + }); + + test("two disjoint overlaps publish two records with distinct ids", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [pool("a", [fwindow({ projectedWallAt: Date.parse(at(1)), resetsAt: at(9) })])], + b: [ + pool("b", [ + fwindow({ name: "5-hour", projectedWallAt: Date.parse(at(2)), resetsAt: at(3) }), + fwindow({ name: "weekly", projectedWallAt: Date.parse(at(5)), resetsAt: at(6) }), + ]), + ], + }), + ); + expect(records.map((r) => [r.prediction?.earliest, r.prediction?.latest])).toEqual([ + [at(2), at(3)], + [at(5), at(6)], + ]); + expect(new Set(records.map((r) => r.id)).size).toBe(2); + }); + + test("no pools at all publishes the honesty state, never silence", () => { + const records = deriveDowntimeWindowRecords(forecast({})); + expect(records).toHaveLength(1); + expect(records[0].state).toBe("insufficient_history"); + expect(records[0].state_reason).toContain("no pools"); + }); + + test("an all-walled overlap no reset bounds is an honesty state, not an unbounded prediction", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [ + pool("a", [ + fwindow({ state: "walled", projectedWallAt: null, durationUntilWallMs: 0, pctNow: 100, resetsAt: null }), + ]), + ], + b: [ + pool("b", [ + fwindow({ state: "walled", projectedWallAt: null, durationUntilWallMs: 0, pctNow: 100, resetsAt: null }), + ]), + ], + }), + ); + expect(records).toHaveLength(1); + expect(records[0].state).toBe("insufficient_history"); + expect(records[0].prediction).toBeNull(); + expect(records[0].state_reason).toContain("cannot be bounded"); + }); +}); + +describe("renderPredictionRange", () => { + test("a range crossing a Chicago day boundary renders in calendar form", () => { + // Mon 06:00 CST -> Tue 12:00 CST / Wed 04:00 CST. + const rendered = renderPredictionRange(at(30), at(46), AS_OF); + expect(rendered.startsWith("between ")).toBe(true); + expect(rendered).toContain("tomorrow"); + }); + + test("a same-day future range renders in duration form, half-hour rounded", () => { + expect(renderPredictionRange(at(2.25), at(5.75), AS_OF)).toBe("between 2.5 and 6 hours from now"); + }); +}); + +describe("buildDowntimeLedgerRows", () => { + test("rows mirror the records under the C4 source, payload verbatim, resets = window end", () => { + const records = deriveDowntimeWindowRecords( + forecast({ + a: [pool("a", [fwindow({ projectedWallAt: Date.parse(at(2)), resetsAt: at(10) })])], + b: [pool("b", [fwindow({ projectedWallAt: Date.parse(at(4)), resetsAt: at(8) })])], + }), + ); + const rows = buildDowntimeLedgerRows(records, AS_OF); + expect(rows).toHaveLength(1); + expect(rows[0].source).toBe(PREDICTION_LEDGER_SOURCE); + expect(rows[0].source).toBe("quota-prediction"); + expect(rows[0].id).toBe(records[0].id); + expect(rows[0].resets).toBe(at(8)); + expect(rows[0].payload).toEqual({ ...records[0] }); + }); + + test("honesty records mirror too, with no resets", () => { + const records = deriveDowntimeWindowRecords(forecast({})); + const rows = buildDowntimeLedgerRows(records, AS_OF); + expect(rows).toHaveLength(1); + expect(rows[0].resets).toBeNull(); + expect((rows[0].payload as { state: string }).state).toBe("insufficient_history"); + }); +}); diff --git a/pm-stack/aggregator/src/quota-downtime.ts b/pm-stack/aggregator/src/quota-downtime.ts new file mode 100644 index 0000000000..961a39cda8 --- /dev/null +++ b/pm-stack/aggregator/src/quota-downtime.ts @@ -0,0 +1,329 @@ +// C4.1 — complete-downtime window predictions (#13257, component +// of the C4 quota-forecasting epic #9572). The record format, +// storage, and scoring contract are the C4 design: +// doc/2026-11-13T15-12-00Z_design_reporting-architecture-event-driven/ +// c4-forecasting-design.md (§1 the prediction record, §7 the +// downtime kind), landed by PR #13268. The input product is the +// Stage-3 forecast (quota-forecast.json, #12695). +// +// Derivation (§7): from the per-pool exhaustion projections + +// reset times — the interval where every routing pool's predicted +// wall has passed and the earliest reopening (any pool's reset) +// has not yet arrived. A pool window is down over [wall, reset): +// from its projected wall (or the tick itself, when the window is +// already walled) until its reset. A provider is down while any +// of its pool rows' windows is down (any binding limit blocks +// it), so a provider's down-set is the union of its windows' +// intervals; a complete-downtime window is a maximal interval in +// the intersection of every provider's down-set. Sets are the +// routing pools only — the forecast product's coverage — keyed by +// canonical provider id (the S1 keying lesson). +// +// The prediction range (§1): earliest is the all-walled +// interval's start (the last member wall), latest its end (the +// earliest member reset — the first reopening). earliest == +// latest is refused by construction (a zero-width overlap is no +// window), and an interval no member reset bounds is not a +// prediction at all: it publishes as an honesty state, because a +// model that cannot bound its answer emits one (§1). +// +// Honesty (§1, and #13257 criterion 3): insufficient_history is a +// published state with a named reason — never an invented range, +// never a silent absence. A provider whose windows the forecast +// could not project can only add downtime, never remove a known +// overlap, so a known overlap still publishes as predicted (the +// unknown providers named in the basis detail); but unknowns veto +// a no-window verdict, because absence of a record is the +// no-prediction signal the scorer reads (§3: a realized downtime +// with no prediction is a miss). A tick where every provider is +// projectable and no overlap exists therefore publishes NO +// record — that absence is the defensible "no window" claim. +// +// Basis (§1: mandatory, singular): since_last_reset — the S1 +// projections are fit on the current reset period's same-period +// series, and this module fits nothing itself; it intersects the +// oracle's published intervals. Methodology version c4-meth:1 +// (c4-methodology-log.jsonl beside this module's package root, +// §6). Advisory only: no placement path reads these records — +// the C6 pages and forecast alerts named by #9572 consume them. + +import type { ForecastLedgerRow, QuotaForecastFile } from "./quota-forecast.ts"; + +/** Turso ledger source for C4 prediction records (design §1): + * distinct from S1's "quota-forecast" — C4 records never mix + * into the S1 source. */ +export const PREDICTION_LEDGER_SOURCE = "quota-prediction"; + +export const C4_METHODOLOGY_VERSION = "c4-meth:1" as const; + +export interface C4PredictionRecord { + record_version: 1; + id: string; + kind: "downtime_window"; + subject: { pools: string[] }; + issued_at: string; + basis: { name: "since_last_reset"; detail: string }; + inputs: { + series: string; + samples: number; + span: { from: string | null; to: string }; + adjustments: string[]; + }; + prediction: { earliest: string; latest: string; rendered: string } | null; + methodology_version: typeof C4_METHODOLOGY_VERSION; + state: "predicted" | "insufficient_history"; + state_reason: string | null; + supersedes: string | null; +} + +interface WallInterval { + start: number; + /** ms epoch; Infinity when the pool reports no reset. */ + end: number; +} + +// --- Range rendering (design §4) ---------------------------------- +// One formatter for (earliest, latest, issued_at), in +// America/Chicago wall-clock terms. Duration form under 48h, +// day form at/over 48h, calendar form when the range crosses a +// Chicago day boundary — the form preferred for downtime windows +// and any range whose latest bound falls on a different day than +// its earliest. + +const CHICAGO = "America/Chicago"; +const dayKeyFmt = new Intl.DateTimeFormat("en-US", { timeZone: CHICAGO, year: "numeric", month: "2-digit", day: "2-digit" }); +const weekdayFmt = new Intl.DateTimeFormat("en-US", { timeZone: CHICAGO, weekday: "long" }); +const hourFmt = new Intl.DateTimeFormat("en-US", { timeZone: CHICAGO, hour: "numeric", hourCycle: "h23" }); + +function chicagoDayRef(ms: number, issuedMs: number): string { + const day = dayKeyFmt.format(new Date(ms)); + if (day === dayKeyFmt.format(new Date(issuedMs))) return "this"; + // Tomorrow in Chicago terms: the issued instant + 24h shares the + // next Chicago calendar day in all but pathological DST cases; + // the weekday name is the fallback and is never wrong. + if (day === dayKeyFmt.format(new Date(issuedMs + 24 * 3_600_000))) return "tomorrow"; + return weekdayFmt.format(new Date(ms)); +} + +function chicagoDaypart(ms: number, issuedMs: number): string { + const ref = chicagoDayRef(ms, issuedMs); + const hour = Number(hourFmt.format(new Date(ms))); + const namedHour = hour === 0 ? "12 am" : hour < 12 ? `${hour} am` : hour === 12 ? "12 pm" : `${hour - 12} pm`; + if (hour >= 5 && hour < 12) return ref === "this" ? "this morning" : `${ref} morning`; + if (hour >= 12 && hour < 17) return ref === "this" ? "this afternoon" : `${ref} afternoon`; + if (hour >= 17 && hour < 22) return ref === "this" ? "this evening" : `${ref} evening`; + // Night bounds are sharp in Drew's formats ("Sunday 2 am"). + return ref === "tomorrow" ? `tomorrow ${namedHour}` : ref === "this" ? `today ${namedHour}` : `${ref} ${namedHour}`; +} + +const roundHalf = (x: number) => Math.round(x * 2) / 2; +const fmtNum = (x: number) => (Number.isInteger(x) ? String(x) : x.toFixed(1)); + +/** The stored `rendered` string for a prediction range (§4): + * what was shown is exactly what is scored, so it is produced + * once, at issuance, by this formatter. */ +export function renderPredictionRange(earliestISO: string, latestISO: string, issuedAtISO: string): string { + const earliest = Date.parse(earliestISO); + const latest = Date.parse(latestISO); + const issued = Date.parse(issuedAtISO); + if (dayKeyFmt.format(new Date(earliest)) !== dayKeyFmt.format(new Date(latest))) { + return `between ${chicagoDaypart(earliest, issued)} and ${chicagoDaypart(latest, issued)}`; + } + const spanH = (latest - earliest) / 3_600_000; + if (spanH >= 48) { + const roundTenth = (x: number) => Math.round(x * 10) / 10; + return `${fmtNum(roundTenth((earliest - issued) / 86_400_000))} to ${fmtNum( + roundTenth((latest - issued) / 86_400_000), + )} days`; + } + if (earliest <= issued) { + // Already in progress: "from now" cannot express a start in + // the past, so the same-day calendar form carries it. + return `between ${chicagoDaypart(earliest, issued)} and ${chicagoDaypart(latest, issued)}`; + } + const fromH = (t: number) => roundHalf((t - issued) / 3_600_000); + return `between ${fmtNum(fromH(earliest))} and ${fmtNum(fromH(latest))} hours from now`; +} + +// --- Derivation ---------------------------------------------------- + +interface ProviderDown { + providerId: string; + intervals: WallInterval[]; + unknown: boolean; + samples: number; + measuredFrom: string | null; +} + +/** + * Derive one tick's downtime_window records from the tick's + * forecast product. Pure: no I/O, no clock reads — the tick time + * is the forecast's own generatedAt. `previous` maps a subject + * key (the pool set, joined) to the last record id issued for + * it, for the supersedes link (§1); pass an empty map when the + * caller has no history. + * + * Returns [] when the defensible verdict is "no complete + * downtime in the horizon" — absence is the no-prediction + * signal, per the design's scoring rules. + */ +export function deriveDowntimeWindowRecords( + forecast: QuotaForecastFile, + previous: ReadonlyMap = new Map(), +): C4PredictionRecord[] { + const issuedAt = forecast.generatedAt; + const issuedMs = Date.parse(issuedAt); + const providerIds = Object.keys(forecast.pools).sort(); + const subjectKey = providerIds.join("+"); + + const providers: ProviderDown[] = []; + for (const providerId of providerIds) { + const intervals: WallInterval[] = []; + let unknown = false; + let samples = 0; + let measuredFrom: string | null = null; + for (const pool of forecast.pools[providerId]) { + if (pool.windows.length === 0) unknown = true; + for (const w of pool.windows) { + if (measuredFrom === null || w.measuredAt < measuredFrom) measuredFrom = w.measuredAt; + if (w.state === "insufficient-history") { + unknown = true; + continue; + } + samples += w.samples; + const resetMs = w.resetsAt ? Date.parse(w.resetsAt) : NaN; + const end = Number.isFinite(resetMs) ? resetMs : Infinity; + if (w.state === "walled") { + intervals.push({ start: issuedMs, end }); + } else if (w.state === "projected" && w.projectedWallAt != null && w.wallsBeforeReset !== false) { + intervals.push({ start: w.projectedWallAt, end }); + } + } + } + providers.push({ providerId, intervals, unknown, samples, measuredFrom }); + } + + const totalSamples = providers.reduce((n, p) => n + p.samples, 0); + const spanFrom = providers.reduce( + (acc, p) => (p.measuredFrom !== null && (acc === null || p.measuredFrom < acc) ? p.measuredFrom : acc), + null, + ); + const unknownIds = providers.filter((p) => p.unknown).map((p) => p.providerId); + + const record = (over: Partial & Pick): C4PredictionRecord => ({ + record_version: 1, + kind: "downtime_window", + subject: { pools: providerIds }, + issued_at: issuedAt, + basis: { + name: "since_last_reset", + detail: + "complete-downtime interval intersected from the Stage-3 per-pool pace projections (quota-forecast.json, #12695): " + + "every routing pool's predicted wall has passed and the earliest reopening (any pool's reset) has not yet arrived", + }, + inputs: { series: "quota-forecast.json", samples: totalSamples, span: { from: spanFrom, to: issuedAt }, adjustments: [] }, + prediction: null, + methodology_version: C4_METHODOLOGY_VERSION, + state_reason: null, + supersedes: previous.get(subjectKey) ?? null, + ...over, + }); + + const honesty = (reason: string): C4PredictionRecord[] => [ + record({ + id: `c4:downtime_window:${subjectKey}@honesty:${issuedMs}`, + state: "insufficient_history", + state_reason: reason, + }), + ]; + + if (providerIds.length === 0) { + return honesty("the forecast product carries no pools; no downtime verdict is defensible"); + } + + // Maximal intervals where every provider has a covering + // interval: sweep the sorted boundary points; coverage is + // constant on each segment between consecutive points. + const covers = (intervals: WallInterval[], t: number) => intervals.some((iv) => iv.start <= t && t < iv.end); + const boundarySet = new Set([issuedMs]); + for (const p of providers) { + for (const iv of p.intervals) { + boundarySet.add(iv.start); + if (Number.isFinite(iv.end)) boundarySet.add(iv.end); + } + } + const points = [...boundarySet].sort((a, b) => a - b); + const overlaps: { start: number; end: number }[] = []; + let runStart: number | null = null; + for (let i = 0; i < points.length; i++) { + const t = points[i]; + const allDown = providers.every((p) => covers(p.intervals, t)); + if (allDown) { + if (runStart === null) runStart = t; + if (i === points.length - 1) { + const end = Math.min( + ...providers.map((p) => Math.min(...p.intervals.filter((iv) => iv.start <= t && t < iv.end).map((iv) => iv.end))), + ); + if (end > runStart) overlaps.push({ start: runStart, end }); + runStart = null; + } + } else if (runStart !== null) { + if (t > runStart) overlaps.push({ start: runStart, end: t }); + runStart = null; + } + } + + const bounded = overlaps.filter((o) => Number.isFinite(o.end)); + if (bounded.length > 0) { + return bounded.map((o) => { + const earliest = new Date(o.start).toISOString(); + const latest = new Date(o.end).toISOString(); + return record({ + id: `c4:downtime_window:${subjectKey}@${o.start}:${issuedMs}`, + state: "predicted", + basis: { + name: "since_last_reset", + detail: + "complete-downtime interval intersected from the Stage-3 per-pool pace projections (quota-forecast.json, #12695): " + + "every routing pool's predicted wall has passed and the earliest reopening (any pool's reset) has not yet arrived" + + (unknownIds.length > 0 + ? `; pools the forecast could not project (${unknownIds.join(", ")}) can only add downtime and do not affect this known overlap` + : ""), + }, + prediction: { earliest, latest, rendered: renderPredictionRange(earliest, latest, issuedAt) }, + }); + }); + } + if (overlaps.length > 0) { + return honesty( + "every pool is projected walled with no reported reset in common; the all-walled interval cannot be bounded, and an unbounded answer is not a prediction", + ); + } + if (unknownIds.length > 0) { + return honesty( + `no complete-downtime window is derivable and the forecast could not project: ${unknownIds.join(", ")} — absence of a window is not asserted`, + ); + } + return []; +} + +/** + * The ledger mirror (design §1): one row per record under the + * C4 source "quota-prediction", beside the S1 forecast rows in + * agent_quota_records, payload = the record verbatim so the + * accuracy scoring (§3) joins predictions to outcomes in one + * place. resets carries the predicted window end (the earliest + * reopening), mirroring the forecast rows' resets convention; + * null on honesty records, which publish no range. + */ +export function buildDowntimeLedgerRows(records: readonly C4PredictionRecord[], tickAt: string): ForecastLedgerRow[] { + return records.map((r) => ({ + id: r.id, + source: PREDICTION_LEDGER_SOURCE, + ts: tickAt, + plan: null, + weeklyPercent: null, + resets: r.prediction?.latest ?? null, + payload: { ...r }, + })); +} diff --git a/pm-stack/aggregator/test/gather-quota.test.ts b/pm-stack/aggregator/test/gather-quota.test.ts index 8c449b297a..de6197ed96 100644 --- a/pm-stack/aggregator/test/gather-quota.test.ts +++ b/pm-stack/aggregator/test/gather-quota.test.ts @@ -1004,6 +1004,23 @@ test("the tick publishes the Stage-3 forecast product beside quota-current.json expect(weekly.projectedWallAt).toBeGreaterThan(now - 60_000); expect(weekly.projectedWallAt).toBeLessThan(resetMs); expect(weekly.wallsBeforeReset).toBe(true); + + // C4.1 (#13257): the same tick appends the complete-downtime + // prediction record to the C4 log beside the forecast product. + // The fixture's single pool walls before its reset, so the + // all-pools-walled interval is that pool's own wall interval. + const predictions = (await readFile(join(dir, "quota-predictions.jsonl"), "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + const downtime = predictions.filter((r: { kind: string }) => r.kind === "downtime_window"); + expect(downtime).toHaveLength(1); + expect(downtime[0].subject.pools).toEqual(["cline-pass"]); + expect(downtime[0].state).toBe("predicted"); + expect(downtime[0].basis.name).toBe("since_last_reset"); + expect(downtime[0].prediction.earliest).toBe(new Date(weekly.projectedWallAt).toISOString()); + expect(downtime[0].prediction.latest).toBe(resetIso); + expect(typeof downtime[0].prediction.rendered).toBe("string"); } finally { await rm(dir, { recursive: true, force: true }); }