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
1 change: 1 addition & 0 deletions pm-stack/aggregator/c4-methodology-log.jsonl
Original file line number Diff line number Diff line change
@@ -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"}
48 changes: 48 additions & 0 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -1281,6 +1286,49 @@ export async function main(): Promise<number> {
);
}

// 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<string, string>();
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");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Separate new records from a torn log tail before appending

If a previous append was interrupted before its terminating newline, the parser skips the torn final line, but this append concatenates the next tick's first record directly onto that fragment. The resulting line is invalid JSON, so the first new prediction is also lost from the readable log and cannot become a subsequent supersedes target; for the usual single-record tick, this loses the entire tick locally even though the ledger write proceeds. Repair or delimit an unterminated tail before appending new records so the intended torn-log recovery preserves the next prediction.

Useful? React with 👍 / 👎.

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),
Expand Down
291 changes: 291 additions & 0 deletions pm-stack/aggregator/src/quota-downtime.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): 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<string, QuotaForecastPool[]>): 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");
});
});
Loading