From cd6dd77cf48d6ecb94072e5eb7617f02c0437418 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:52:01 -0600 Subject: [PATCH] feat(aggregator): day-type sample-sufficiency re-measure for C4.3 (#13259) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The C4 design §5 admits a day-type adjustment for a cell only when the cell holds >=8 independent samples; below the gate the state is adjustment_unavailable. Stage-3 deferred the models at ~4-5 samples per weekday (33 days of store history); C4.3 re-measures first. - src/quota-daytype-sufficiency.ts: counts independent samples (distinct America/Chicago dates with >=1 reading) per pool/window over the design grain ladder — weekday, dayclass, daypart, weekday-daypart — over the same rename-joined percent series the S2 harness scores, and renders the report. - scripts/quota-daytype-sufficiency.ts (+ package.json script measure:daytype-sufficiency): the re-measure as a command over the live snapshot store, strict #3352 argument contract. - Tests name their oracles: the §5 gate, the Stage-3 §2 arithmetic reproduced (33 days => 4-5 per weekday, no weekday cell admitted), the §4 Chicago calendar, the §2 rename join. Live re-measure (2026-11-23, 20,979 records, 63 pool/windows, 2,583 cells): 51 cells admitted — all at the coarse grains (daypart 39, dayclass-weekday 12); weekday and weekday-daypart grains admit none (max 4 samples). The measurement is recorded on #13259; the issue stays open on its adjustment + earn-in criteria. --- pm-stack/aggregator/package.json | 1 + .../scripts/quota-daytype-sufficiency.ts | 107 ++++++ .../src/quota-daytype-sufficiency.test.ts | 207 +++++++++++ .../src/quota-daytype-sufficiency.ts | 330 ++++++++++++++++++ 4 files changed, 645 insertions(+) create mode 100644 pm-stack/aggregator/scripts/quota-daytype-sufficiency.ts create mode 100644 pm-stack/aggregator/src/quota-daytype-sufficiency.test.ts create mode 100644 pm-stack/aggregator/src/quota-daytype-sufficiency.ts diff --git a/pm-stack/aggregator/package.json b/pm-stack/aggregator/package.json index 1f2f19036e..9181ceadb0 100644 --- a/pm-stack/aggregator/package.json +++ b/pm-stack/aggregator/package.json @@ -10,6 +10,7 @@ "test": "bun test", "report:generate": "bun run scripts/generate-report.ts", "backtest:quota-forecast": "bun run scripts/quota-forecast-backtest.ts", + "measure:daytype-sufficiency": "bun run scripts/quota-daytype-sufficiency.ts", "replay:quota-anomaly": "bun run scripts/quota-anomaly-replay.ts", "contract:check": "bun run scripts/check-contract-corpus.ts", "provenance:check": "bun run scripts/check-provenance-matrix.ts", diff --git a/pm-stack/aggregator/scripts/quota-daytype-sufficiency.ts b/pm-stack/aggregator/scripts/quota-daytype-sufficiency.ts new file mode 100644 index 0000000000..6e943741eb --- /dev/null +++ b/pm-stack/aggregator/scripts/quota-daytype-sufficiency.ts @@ -0,0 +1,107 @@ +#!/usr/bin/env bun +// Re-measure day-type sample sufficiency over the aggregator +// snapshot store: per pool/window/day-type cell, how many +// independent samples the store holds against the C4 design §5 +// gate (≥8), and which cells are admitted vs adjustment_unavailable +// (#13259, slice C4.3 of #9572). +// +// bun run scripts/quota-daytype-sufficiency.ts --store-dir \ +// [--report-out ] [--json-out ] [--as-of ] +// +// (Committed as the package.json script `measure:daytype-sufficiency`.) +// +// The store is read through SnapshotStore.readAll — read-only; this +// script never writes to the store dir. Outputs are the human +// report (stdout unless --report-out) and optionally the full +// per-cell measurement as JSON. --as-of defaults to the store's +// last reading, never the wall clock, so a run over a fixed store +// copy is reproducible. +// +// Argument contract (#3352): the whole command line is declared +// here — the four value options above, in `--opt value` or +// `--opt=value` form — and parsed strictly before any file is read +// or written. An unknown argument, a stray positional, or a +// present-but-valueless option is a usage error (exit 2) naming +// the offending argument. +import { writeFile } from "node:fs/promises"; +import { SnapshotStore } from "../src/snapshots.ts"; +import { + measureDayTypeSufficiency, + renderDayTypeSufficiencyReport, +} from "../src/quota-daytype-sufficiency.ts"; + +const VALUE_OPTIONS = ["--store-dir", "--report-out", "--json-out", "--as-of"] as const; +type ValueOption = (typeof VALUE_OPTIONS)[number]; + +function usageError(message: string): never { + console.error(`quota-daytype-sufficiency: ${message}`); + console.error( + "usage: quota-daytype-sufficiency --store-dir [--report-out ] [--json-out ] [--as-of ]", + ); + process.exit(2); +} + +function parseArgs(argv: string[]): Record { + const out: Record = { + "--store-dir": undefined, + "--report-out": undefined, + "--json-out": undefined, + "--as-of": undefined, + }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] as string; + const eq = arg.indexOf("="); + const name = (eq >= 0 ? arg.slice(0, eq) : arg) as ValueOption; + if (!VALUE_OPTIONS.includes(name)) { + usageError(`unknown argument '${arg}'; refusing to run, no files read or written`); + } + let value: string | undefined; + if (eq >= 0) { + value = arg.slice(eq + 1); + } else { + value = argv[i + 1]; + if (value !== undefined) i++; + } + if (value === undefined || value.trim() === "" || value.startsWith("--")) { + usageError(`option '${name}' requires a non-empty value; refusing to run, no files read or written`); + } + out[name] = value; + } + return out; +} + +async function main(): Promise { + const args = parseArgs(process.argv.slice(2)); + const storeDir = args["--store-dir"]; + if (!storeDir) usageError("--store-dir is required; refusing to run, no files read or written"); + let asOfMs: number | undefined; + if (args["--as-of"] !== undefined) { + asOfMs = Date.parse(args["--as-of"]); + if (!Number.isFinite(asOfMs)) usageError(`--as-of '${args["--as-of"]}' is not a parseable instant`); + } + + const records = await new SnapshotStore(storeDir).readAll(); + if (!records.length) { + console.error(`quota-daytype-sufficiency: no snapshot records in ${storeDir} — nothing to measure`); + process.exit(1); + } + const measurement = measureDayTypeSufficiency(records, { asOfMs }); + const report = renderDayTypeSufficiencyReport(measurement); + + if (args["--report-out"]) { + await writeFile(args["--report-out"], report, "utf8"); + } else { + console.log(report); + } + if (args["--json-out"]) { + await writeFile(args["--json-out"], JSON.stringify(measurement, null, 2) + "\n", "utf8"); + } + const cells = measurement.poolWindows.flatMap((pw) => pw.cells); + const admitted = cells.filter((c) => c.state === "admitted").length; + console.error( + `quota-daytype-sufficiency: ${measurement.store.records} records, ` + + `${measurement.poolWindows.length} pool/windows, ${admitted}/${cells.length} cells admitted`, + ); +} + +await main(); diff --git a/pm-stack/aggregator/src/quota-daytype-sufficiency.test.ts b/pm-stack/aggregator/src/quota-daytype-sufficiency.test.ts new file mode 100644 index 0000000000..90b82ffb05 --- /dev/null +++ b/pm-stack/aggregator/src/quota-daytype-sufficiency.test.ts @@ -0,0 +1,207 @@ +// Tests for the C4.3 day-type sample-sufficiency re-measure +// (#13259). Every test names its oracle: the C4 design §5 gate +// (≥8 independent samples per cell; below it the state is +// adjustment_unavailable), the Stage-3 design §2 arithmetic it +// re-measures (33 days of history ⇒ ~4–5 samples of each weekday +// per window, too thin), the design §2 rename join as carried by +// the S2 harness, and the America/Chicago calendar the design §4 +// renders in. +import { describe, expect, test } from "bun:test"; +import { + DAY_TYPE_SAMPLE_GATE, + dayTypeParts, + measureDayTypeSufficiency, + type DayTypeCellMeasurement, +} from "./quota-daytype-sufficiency.ts"; +import type { SnapshotRecord } from "./model.ts"; + +function rec(serviceId: string, metricId: string, isoTs: string, value: number = 50): SnapshotRecord { + return { + ts: isoTs, + serviceId, + metricId, + value, + unit: "pct", + limit: 100, + resetsAt: null, + source: "api", + observedBy: "test", + }; +} + +/** 15:00Z is 09:00–10:00 in Chicago (CST/CDT) — a morning reading. */ +function morningOn(date: string): string { + return `${date}T15:00:00.000Z`; +} + +function cell( + m: ReturnType, + pool: string, + window: string, + grain: string, + name: string, +): DayTypeCellMeasurement { + const pw = m.poolWindows.find((p) => p.pool === pool && p.window === window); + expect(pw).toBeDefined(); + const c = pw?.cells.find((x) => x.grain === grain && x.cell === name); + expect(c).toBeDefined(); + return c as DayTypeCellMeasurement; +} + +describe("the gate (oracle: C4 design §5)", () => { + test("the gate is 8 independent samples", () => { + expect(DAY_TYPE_SAMPLE_GATE).toBe(8); + }); + + test("a cell with exactly 8 independent samples is admitted; 7 is not", () => { + // Eight Fridays: 2026-10-30, 11-06, 11-13, 11-20, 11-27, + // 12-04, 12-11, 12-18 (weekly cadence from Friday 2026-10-30). + const fridays = [ + "2026-10-30", + "2026-11-06", + "2026-11-13", + "2026-11-20", + "2026-11-27", + "2026-12-04", + "2026-12-11", + "2026-12-18", + ]; + const eight = measureDayTypeSufficiency(fridays.map((d) => rec("meta", "5h", morningOn(d)))); + expect(cell(eight, "meta", "5h", "weekday", "Fri").samples).toBe(8); + expect(cell(eight, "meta", "5h", "weekday", "Fri").state).toBe("admitted"); + const seven = measureDayTypeSufficiency( + fridays.slice(0, 7).map((d) => rec("meta", "5h", morningOn(d))), + ); + expect(cell(seven, "meta", "5h", "weekday", "Fri").samples).toBe(7); + expect(cell(seven, "meta", "5h", "weekday", "Fri").state).toBe("adjustment_unavailable"); + }); + + test("readings are not samples: two readings on one date are one independent sample", () => { + const m = measureDayTypeSufficiency([ + rec("meta", "5h", "2026-11-06T15:00:00.000Z"), + rec("meta", "5h", "2026-11-06T16:00:00.000Z"), + ]); + const fri = cell(m, "meta", "5h", "weekday", "Fri"); + expect(fri.samples).toBe(1); + expect(fri.readings).toBe(2); + }); +}); + +describe("the Stage-3 deferral, reproduced (oracle: Stage-3 design §2)", () => { + test("33 days of dense history gives ~4–5 samples per weekday and admits no weekday cell", () => { + // 2026-10-26 (Mon) .. 2026-11-27 (Fri) inclusive is 33 days — + // the span Stage-3 §2 measured. Four readings a day stands in + // for the gatherer's dense sampling; samples count dates. The + // hours are 06:00–15:00 Chicago, so every reading falls on its + // UTC date in the Chicago calendar too. + const records: SnapshotRecord[] = []; + const start = Date.parse("2026-10-26T00:00:00.000Z"); + for (let d = 0; d < 33; d++) { + for (const h of [12, 15, 18, 21]) { + records.push(rec("meta", "5h", new Date(start + d * 86_400_000 + h * 3_600_000).toISOString())); + } + } + const m = measureDayTypeSufficiency(records); + for (const wd of ["Mon", "Tue", "Wed", "Thu", "Fri"]) { + expect(cell(m, "meta", "5h", "weekday", wd).samples).toBe(5); + } + for (const wd of ["Sat", "Sun"]) { + expect(cell(m, "meta", "5h", "weekday", wd).samples).toBe(4); + } + const weekdayCells = m.poolWindows[0]?.cells.filter((c) => c.grain === "weekday") ?? []; + expect(weekdayCells.every((c) => c.state === "adjustment_unavailable")).toBe(true); + // The coarser grains the design names do cross on the same + // history: weekends pool Sat+Sun dates, dayparts pool all days. + expect(cell(m, "meta", "5h", "dayclass", "weekend").samples).toBe(8); + expect(cell(m, "meta", "5h", "dayclass", "weekend").state).toBe("admitted"); + expect(cell(m, "meta", "5h", "daypart", "morning").samples).toBe(33); + expect(cell(m, "meta", "5h", "daypart", "morning").state).toBe("admitted"); + // The finest grain stays under: no weekday-daypart cell can + // hold more samples than its weekday. + const fine = m.poolWindows[0]?.cells.filter((c) => c.grain === "weekday-daypart") ?? []; + expect(fine.every((c) => c.state === "adjustment_unavailable")).toBe(true); + }); +}); + +describe("the calendar (oracle: C4 design §4 — America/Chicago wall clock)", () => { + test("a reading at 05:00Z in November is the previous Chicago evening", () => { + // 2026-11-23T05:00Z is Sunday 2026-11-22 23:00 CST — a Sunday + // evening sample, not a Monday night one. + const parts = dayTypeParts(Date.parse("2026-11-23T05:00:00.000Z")); + expect(parts).toEqual({ date: "2026-11-22", weekday: "Sun", daypart: "evening" }); + const m = measureDayTypeSufficiency([rec("deepseek", "5h", "2026-11-23T05:00:00.000Z")]); + expect(cell(m, "deepseek", "5h", "weekday", "Sun").samples).toBe(1); + expect(cell(m, "deepseek", "5h", "weekday", "Mon").samples).toBe(0); + expect(cell(m, "deepseek", "5h", "weekday-daypart", "Sun evening").samples).toBe(1); + }); + + test("dayparts are quarter-day blocks: night 00–06, morning 06–12, afternoon 12–18, evening 18–24 Chicago", () => { + // Chicago is UTC-6 on 2026-11-22 (CST): local hour = UTC hour - 6. + const at = (utcHour: number) => dayTypeParts(Date.parse(`2026-11-22T${String(utcHour).padStart(2, "0")}:00:00.000Z`)).daypart; + expect(at(6)).toBe("night"); // 00:00 local + expect(at(11)).toBe("night"); // 05:00 local + expect(at(12)).toBe("morning"); // 06:00 local + expect(at(17)).toBe("morning"); // 11:00 local + expect(at(18)).toBe("afternoon"); // 12:00 local + expect(at(23)).toBe("afternoon"); // 17:00 local + expect(at(0)).toBe("evening"); // 18:00 local, previous UTC day + expect(at(5)).toBe("evening"); // 23:00 local + }); +}); + +describe("the join (oracle: Stage-3 design §2 + the S2 harness's own rules)", () => { + test("renamed service ids fold into one pool row", () => { + const m = measureDayTypeSufficiency([ + rec("antigravity", "5h", morningOn("2026-11-06")), + rec("_antigravity", "5h", morningOn("2026-11-13")), + rec("openai.alternate", "5h", morningOn("2026-11-06")), + rec("openai", "5h", morningOn("2026-11-13")), + ]); + // The rename join (S2's SERVICE_ID_RENAME_ALIASES): the + // underscore spelling folds into antigravity; the alternate + // account's spelling joins its own pool (openai.alt), and the + // bare spelling joins the main account's pool (openai.main). + const pools = m.poolWindows.map((p) => p.pool).sort(); + expect(pools).toEqual(["antigravity", "openai.alt", "openai.main"]); + expect(cell(m, "antigravity", "5h", "weekday", "Fri").samples).toBe(2); + expect(cell(m, "openai.alt", "5h", "weekday", "Fri").samples).toBe(1); + expect(cell(m, "openai.main", "5h", "weekday", "Fri").samples).toBe(1); + const ag = m.poolWindows.find((p) => p.pool === "antigravity"); + expect(ag?.serviceIds).toEqual(["_antigravity", "antigravity"]); + }); + + test("window spellings fold: 7d and weekly are one window; a ':5h' suffix counts for 5h", () => { + const m = measureDayTypeSufficiency([ + rec("meta", "7d", morningOn("2026-11-06")), + rec("meta", "weekly", morningOn("2026-11-13")), + rec("meta", "door:5h", morningOn("2026-11-06")), + ]); + expect(cell(m, "meta", "weekly", "weekday", "Fri").samples).toBe(2); + expect(cell(m, "meta", "5h", "weekday", "Fri").samples).toBe(1); + }); + + test("non-percent records and unparseable timestamps are not measured", () => { + const estimate: SnapshotRecord = { + ...rec("meta", "5h", morningOn("2026-11-06")), + value: { low: 1, high: 2 }, + unit: "usd-est", + }; + const m = measureDayTypeSufficiency([ + estimate, + { ...rec("meta", "5h", morningOn("2026-11-06")), ts: "not-a-date" }, + rec("meta", "5h", morningOn("2026-11-06")), + ]); + expect(m.store.pctRecords).toBe(1); + expect(cell(m, "meta", "5h", "weekday", "Fri").samples).toBe(1); + }); + + test("as-of excludes later readings, so a run over a fixed store copy is reproducible", () => { + const records = [ + rec("meta", "5h", morningOn("2026-11-06")), + rec("meta", "5h", morningOn("2026-11-13")), + ]; + const m = measureDayTypeSufficiency(records, { asOfMs: Date.parse("2026-11-10T00:00:00.000Z") }); + expect(cell(m, "meta", "5h", "weekday", "Fri").samples).toBe(1); + expect(m.store.toIso).toBe("2026-11-06T15:00:00.000Z"); + }); +}); diff --git a/pm-stack/aggregator/src/quota-daytype-sufficiency.ts b/pm-stack/aggregator/src/quota-daytype-sufficiency.ts new file mode 100644 index 0000000000..5b8bacde2e --- /dev/null +++ b/pm-stack/aggregator/src/quota-daytype-sufficiency.ts @@ -0,0 +1,330 @@ +// Day-type sample-sufficiency re-measure for the C4 forecast +// adjustments (#13259, slice C4.3 of #9572; C4 design +// doc/2026-11-13T15-12-00Z_design_reporting-architecture-event-driven/ +// c4-forecasting-design.md §5). +// +// The Stage-3 design deferred day-type modelling on evidence: at +// 33 days of snapshot-store history each weekday cell held ~4–5 +// samples per window — too thin to tune on (Stage-3 design §2, §8 +// alternative B). The C4 design defines the models and the gate +// that admits them, and does not waive the gate: +// +// "An adjustment ships for a cell only when the cell holds ≥8 +// independent samples (Stage-3 measured ~4–5 per weekday at +// 33 days — under gate ...) Below the gate: +// adjustment_unavailable, unadjusted forecast stands. Admission +// is measured, not scheduled (C4.3 re-measures first)." +// +// This module is that re-measure. It reads the same percent series +// the forecast is fit on — indexPercentRecords' rename join and +// FORECAST_WINDOW_METRICS, so the measurement and the S2 accuracy +// harness agree on the inputs — and counts, per pool/window, the +// independent samples in every day-type cell on the design's grain +// ladder (§5: cells are {weekday × daypart} "at the coarsest grain +// the data supports"): +// +// weekday Mon..Sun ("other Fridays", S2.6) +// dayclass weekday | weekend ("other weekends", S2.6) +// daypart night | morning | afternoon | evening +// ("same time-of-day on +// other days", S2.6) +// weekday-daypart weekday × daypart (the finest cell, §5) +// +// An independent sample is one America/Chicago calendar date +// contributing at least one reading to the cell. Readings inside a +// single occurrence of a cell are one burn episode, not independent +// evidence — at the gatherer's ~15-minute cadence, counting +// readings would call a single Friday morning ~24 samples and the +// gate would admit cells on one day's data. Dayparts are the +// design §4 names on quarter-day Chicago wall-clock blocks: night +// 00–06, morning 06–12, afternoon 12–18, evening 18–24. Day-type is +// Drew-local, so cells are Chicago calendar cells (the design §4 +// wall clock), never UTC cells. +// +// The measurement changes nothing: a cell at or over the gate is +// reported "admitted" — eligible for the adjustment slice, which +// must still earn in against the unadjusted forecast in the S2 +// harness before it publishes (§5) — and a cell under the gate is +// reported with the design's honesty state, +// adjustment_unavailable. Pools are the store's folded series keys +// (the rename join's output); each row names the raw service ids +// folded into it, so the join stays auditable. +import { + FORECAST_WINDOW_METRICS, + FORECAST_WINDOWS, + indexPercentRecords, +} from "./quota-forecast-accuracy.ts"; +import type { SnapshotRecord } from "./model.ts"; + +/** The C4 design §5 sufficiency gate: the independent samples a + * cell must hold before an adjustment may ship for it. */ +export const DAY_TYPE_SAMPLE_GATE = 8; + +/** Day-type cells are America/Chicago calendar cells (design §4). */ +export const DAY_TYPE_TIME_ZONE = "America/Chicago"; + +export const DAY_TYPE_WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const; +export const DAY_TYPE_DAYCLASSES = ["weekday", "weekend"] as const; +export const DAY_TYPE_DAYPARTS = ["night", "morning", "afternoon", "evening"] as const; +export const DAY_TYPE_GRAINS = ["weekday", "dayclass", "daypart", "weekday-daypart"] as const; +export type DayTypeGrain = (typeof DAY_TYPE_GRAINS)[number]; + +/** The design §5 verdict for one cell: admitted at/over the gate, + * the honesty state below it. */ +export type DayTypeCellState = "admitted" | "adjustment_unavailable"; + +export interface DayTypeCellMeasurement { + grain: DayTypeGrain; + cell: string; + /** Independent samples: distinct Chicago dates in the cell. */ + samples: number; + /** Raw readings behind the samples — context, never the gate unit. */ + readings: number; + state: DayTypeCellState; +} + +export interface DayTypePoolWindowMeasurement { + /** Folded series key (the rename join's output). */ + pool: string; + /** Raw store service ids folded into `pool`. */ + serviceIds: string[]; + /** Canonical window name (FORECAST_WINDOW_METRICS key). */ + window: string; + readings: number; + /** Distinct Chicago dates with any reading in this pool/window. */ + days: number; + /** The full grain ladder, every cell present (0 samples is a + * measurement, not an omission). */ + cells: DayTypeCellMeasurement[]; +} + +export interface DayTypeSufficiencyMeasurement { + gate: number; + timeZone: string; + store: { + records: number; + /** Percent readings with a parseable ts (the measured universe). */ + pctRecords: number; + fromIso: string | null; + toIso: string | null; + }; + poolWindows: DayTypePoolWindowMeasurement[]; +} + +const partsFormatter = new Intl.DateTimeFormat("en-US", { + timeZone: DAY_TYPE_TIME_ZONE, + weekday: "short", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + hourCycle: "h23", +}); + +/** The Chicago calendar cell a reading falls in: its local date, + * weekday, and daypart. */ +export function dayTypeParts(tsMs: number): { date: string; weekday: string; daypart: string } { + const parts = partsFormatter.formatToParts(new Date(tsMs)); + const get = (type: string) => parts.find((p) => p.type === type)?.value ?? ""; + const hour = Number(get("hour")) % 24; + const daypart = hour < 6 ? "night" : hour < 12 ? "morning" : hour < 18 ? "afternoon" : "evening"; + return { date: `${get("year")}-${get("month")}-${get("day")}`, weekday: get("weekday"), daypart }; +} + +function cellNames(grain: DayTypeGrain): string[] { + switch (grain) { + case "weekday": + return [...DAY_TYPE_WEEKDAYS]; + case "dayclass": + return [...DAY_TYPE_DAYCLASSES]; + case "daypart": + return [...DAY_TYPE_DAYPARTS]; + case "weekday-daypart": + return DAY_TYPE_WEEKDAYS.flatMap((w) => DAY_TYPE_DAYPARTS.map((d) => `${w} ${d}`)); + } +} + +function cellsFor(parts: { weekday: string; daypart: string }): Record { + const dayclass = parts.weekday === "Sat" || parts.weekday === "Sun" ? "weekend" : "weekday"; + return { + weekday: parts.weekday, + dayclass, + daypart: parts.daypart, + "weekday-daypart": `${parts.weekday} ${parts.daypart}`, + }; +} + +/** + * Measure day-type sample sufficiency over snapshot records. + * `asOfMs` (optional) excludes readings after that instant, so a + * run over a fixed store copy is reproducible (the backtest + * script's --as-of discipline). + */ +export function measureDayTypeSufficiency( + records: readonly SnapshotRecord[], + opts: { asOfMs?: number } = {}, +): DayTypeSufficiencyMeasurement { + const { index, joinedIds } = indexPercentRecords(records); + let pctRecords = 0; + let fromMs: number | null = null; + let toMs: number | null = null; + const poolWindows: DayTypePoolWindowMeasurement[] = []; + + for (const pool of [...index.keys()].sort()) { + const series = index.get(pool) as SnapshotRecord[]; + for (const window of FORECAST_WINDOWS) { + const aliases = FORECAST_WINDOW_METRICS[window] as string[]; + const metrics = new Set(aliases); + const matched = series.filter( + (r) => metrics.has(r.metricId) || aliases.some((a) => r.metricId.endsWith(`:${a}`)), + ); + if (!matched.length) continue; + + const daysByCell = new Map>(); + const readingsByCell = new Map(); + for (const grain of DAY_TYPE_GRAINS) { + for (const cell of cellNames(grain)) { + daysByCell.set(`${grain}:${cell}`, new Set()); + readingsByCell.set(`${grain}:${cell}`, 0); + } + } + const allDays = new Set(); + let readings = 0; + for (const r of matched) { + const ts = Date.parse(r.ts); + if (!Number.isFinite(ts)) continue; + if (opts.asOfMs !== undefined && ts > opts.asOfMs) continue; + readings++; + const parts = dayTypeParts(ts); + allDays.add(parts.date); + const cells = cellsFor(parts); + for (const grain of DAY_TYPE_GRAINS) { + const key = `${grain}:${cells[grain]}`; + (daysByCell.get(key) as Set).add(parts.date); + readingsByCell.set(key, (readingsByCell.get(key) as number) + 1); + } + } + if (!readings) continue; + + const cells: DayTypeCellMeasurement[] = []; + for (const grain of DAY_TYPE_GRAINS) { + for (const cell of cellNames(grain)) { + const key = `${grain}:${cell}`; + const samples = (daysByCell.get(key) as Set).size; + cells.push({ + grain, + cell, + samples, + readings: readingsByCell.get(key) as number, + state: samples >= DAY_TYPE_SAMPLE_GATE ? "admitted" : "adjustment_unavailable", + }); + } + } + poolWindows.push({ + pool, + serviceIds: joinedIds.get(pool) ?? [pool], + window, + readings, + days: allDays.size, + cells, + }); + } + } + + for (const r of records) { + if (typeof r.value !== "number" || r.unit !== "pct") continue; + const ts = Date.parse(r.ts); + if (!Number.isFinite(ts)) continue; + if (opts.asOfMs !== undefined && ts > opts.asOfMs) continue; + pctRecords++; + if (fromMs === null || ts < fromMs) fromMs = ts; + if (toMs === null || ts > toMs) toMs = ts; + } + + return { + gate: DAY_TYPE_SAMPLE_GATE, + timeZone: DAY_TYPE_TIME_ZONE, + store: { + records: records.length, + pctRecords, + fromIso: fromMs === null ? null : new Date(fromMs).toISOString(), + toIso: toMs === null ? null : new Date(toMs).toISOString(), + }, + poolWindows, + }; +} + +/** The human report: gate + basis, per-grain totals, the admitted + * cells (the decision-relevant set), and one summary row per + * pool/window. Full per-cell detail rides in the JSON form. */ +export function renderDayTypeSufficiencyReport(m: DayTypeSufficiencyMeasurement): string { + const lines: string[] = []; + lines.push("# Day-type sample sufficiency — C4.3 re-measure (#13259)"); + lines.push(""); + lines.push( + `Gate: **≥${m.gate} independent samples** per cell (C4 design §5). A sample is one ` + + `${m.timeZone} calendar date with ≥1 reading in the cell; cells are ${m.timeZone} ` + + `calendar cells. Below the gate the state is \`adjustment_unavailable\` and the ` + + `unadjusted forecast stands.`, + ); + lines.push( + `Store: ${m.store.records} records (${m.store.pctRecords} percent readings), ` + + `${m.store.fromIso ?? "?"} → ${m.store.toIso ?? "?"}. Pools are folded series keys ` + + `(the S2 rename join); windows are the canonical forecast windows.`, + ); + lines.push(""); + + lines.push("## By grain"); + lines.push(""); + lines.push("| grain | cells | admitted | adjustment_unavailable | max samples |"); + lines.push("| --- | ---: | ---: | ---: | ---: |"); + for (const grain of DAY_TYPE_GRAINS) { + const cells = m.poolWindows.flatMap((pw) => pw.cells.filter((c) => c.grain === grain)); + const admitted = cells.filter((c) => c.state === "admitted").length; + const max = cells.reduce((acc, c) => Math.max(acc, c.samples), 0); + lines.push( + `| ${grain} | ${cells.length} | ${admitted} | ${cells.length - admitted} | ${max} |`, + ); + } + lines.push(""); + + lines.push("## Admitted cells"); + lines.push(""); + const admittedRows: string[] = []; + for (const pw of m.poolWindows) { + for (const c of pw.cells) { + if (c.state === "admitted") { + admittedRows.push(`| ${pw.pool} | ${pw.window} | ${c.grain} | ${c.cell} | ${c.samples} |`); + } + } + } + if (admittedRows.length) { + lines.push("| pool | window | grain | cell | samples |"); + lines.push("| --- | --- | --- | --- | ---: |"); + lines.push(...admittedRows); + } else { + lines.push("None — every cell is under the gate; every adjustment stays unavailable."); + } + lines.push(""); + + lines.push("## Per pool/window"); + lines.push(""); + lines.push( + "| pool | window | readings | days | weekday adm/max | dayclass adm/max | daypart adm/max | weekday-daypart adm/max |", + ); + lines.push("| --- | --- | ---: | ---: | --- | --- | --- | --- |"); + for (const pw of m.poolWindows) { + const per = (grain: DayTypeGrain) => { + const cells = pw.cells.filter((c) => c.grain === grain); + const admitted = cells.filter((c) => c.state === "admitted").length; + const max = cells.reduce((acc, c) => Math.max(acc, c.samples), 0); + return `${admitted}/${cells.length} · ${max}`; + }; + lines.push( + `| ${pw.pool} | ${pw.window} | ${pw.readings} | ${pw.days} | ${per("weekday")} | ` + + `${per("dayclass")} | ${per("daypart")} | ${per("weekday-daypart")} |`, + ); + } + lines.push(""); + return lines.join("\n"); +}