From 18b4793be4f5fae55c45576cc3ebefa44b94413b Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 20:26:41 -0600 Subject: [PATCH 1/2] feat(aggregator): forecast backtest + calibration report (#3986) --- .../aggregator/scripts/backtest-report.ts | 32 ++ .../aggregator/scripts/forecast-snapshot.ts | 45 +++ pm-stack/aggregator/src/backtest.ts | 382 ++++++++++++++++++ pm-stack/aggregator/test/backtest.test.ts | 217 ++++++++++ 4 files changed, 676 insertions(+) create mode 100644 pm-stack/aggregator/scripts/backtest-report.ts create mode 100644 pm-stack/aggregator/scripts/forecast-snapshot.ts create mode 100644 pm-stack/aggregator/src/backtest.ts create mode 100644 pm-stack/aggregator/test/backtest.test.ts diff --git a/pm-stack/aggregator/scripts/backtest-report.ts b/pm-stack/aggregator/scripts/backtest-report.ts new file mode 100644 index 000000000..626ab01ac --- /dev/null +++ b/pm-stack/aggregator/scripts/backtest-report.ts @@ -0,0 +1,32 @@ +#!/usr/bin/env bun +// Run the rolling-origin forecast backtest and print the calibration +// report (#3986): +// +// bun run scripts/backtest-report.ts \ +// --snapshots data/forecast-snapshots.jsonl \ +// --outcomes outcomes.json [--as-of ] +// +// --outcomes is a JSON file holding ForecastOutcome[]: +// { subjectRef, completedAt (iso|null), recordedAt (iso) } +// One report is printed per model version in the store; aggregates +// never mix versions. The report's calibration gate is enforced in +// src/backtest.ts: below 30 resolved forecasts across 8 cutoffs the +// state is not_yet_calibrated, whatever the point metrics say. +import { readFile } from "node:fs/promises"; +import { evaluateBacktest, loadSnapshots, type ForecastOutcome } from "../src/backtest.ts"; + +function arg(name: string): string | undefined { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 ? process.argv[i + 1] : undefined; +} + +const snapshotsPath = arg("snapshots"); +const outcomesPath = arg("outcomes"); +if (!snapshotsPath || !outcomesPath) { + console.error("usage: backtest-report.ts --snapshots --outcomes [--as-of ]"); + process.exit(2); +} +const snapshots = await loadSnapshots(snapshotsPath); +const outcomes = JSON.parse(await readFile(outcomesPath, "utf8")) as ForecastOutcome[]; +const reports = evaluateBacktest({ snapshots, outcomes, asOf: arg("as-of") ?? new Date().toISOString() }); +console.log(JSON.stringify(reports, null, 2)); diff --git a/pm-stack/aggregator/scripts/forecast-snapshot.ts b/pm-stack/aggregator/scripts/forecast-snapshot.ts new file mode 100644 index 000000000..dd8afa0b6 --- /dev/null +++ b/pm-stack/aggregator/scripts/forecast-snapshot.ts @@ -0,0 +1,45 @@ +#!/usr/bin/env bun +// Capture one weekly forecast snapshot into the backtest store +// (#3986). The weekly job is this command on a timer: +// +// bun run scripts/forecast-snapshot.ts \ +// --forecasts forecasts.json --out data/forecast-snapshots.jsonl \ +// --watermark item-history= [--cutoff ] +// +// --forecasts is a JSON file holding ForecastContract[] (or an object +// with a `forecasts` array) as served by GET /api/forecasts.json. The +// snapshot freezes the epic-completion forecasts with their model +// version, the cutoff, and the source watermarks that name exactly +// what source state they were derived from. +import { readFile } from "node:fs/promises"; +import { appendSnapshot, createSnapshot } from "../src/backtest.ts"; +import type { ForecastContract } from "../src/forecast-contract.ts"; + +function arg(name: string): string | undefined { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 ? process.argv[i + 1] : undefined; +} + +const forecastsPath = arg("forecasts"); +const out = arg("out"); +if (!forecastsPath || !out) { + console.error("usage: forecast-snapshot.ts --forecasts --out [--cutoff ] [--watermark k=v ...]"); + process.exit(2); +} +const parsed = JSON.parse(await readFile(forecastsPath, "utf8")) as ForecastContract[] | { forecasts: ForecastContract[] }; +const forecasts = Array.isArray(parsed) ? parsed : parsed.forecasts; +const sourceWatermarks: Record = {}; +for (let i = 0; i < process.argv.length; i++) { + if (process.argv[i] === "--watermark") { + const [k, ...v] = (process.argv[i + 1] ?? "").split("="); + if (k) sourceWatermarks[k] = v.join("="); + } +} +const snapshot = createSnapshot({ + forecasts, + capturedAt: new Date().toISOString(), + sourceWatermarks, + cutoff: arg("cutoff"), +}); +await appendSnapshot(out, snapshot); +console.log(`snapshot: model=${snapshot.modelVersion} cutoff=${snapshot.cutoff} forecasts=${snapshot.forecasts.length} -> ${out}`); diff --git a/pm-stack/aggregator/src/backtest.ts b/pm-stack/aggregator/src/backtest.ts new file mode 100644 index 000000000..da1c93330 --- /dev/null +++ b/pm-stack/aggregator/src/backtest.ts @@ -0,0 +1,382 @@ +// Forecast backtest + calibration report (#3986; design #1256 §5). +// +// Forecasts (ETA bands from #3982, contract objects from #3984) are +// published with no measurement of whether they are useful or +// calibrated. This module is the measurement: +// +// - A weekly SNAPSHOT STORE: every captured forecast is frozen as of +// its cutoff with its model version, source watermarks, and the full +// contract objects — the minimal inputs needed to reproduce an +// evaluation later. Nothing is ever scored from live state. +// - ROLLING-ORIGIN EVALUATION over snapshots only: an evaluation as of +// instant T sees no snapshot captured after T and no outcome record +// recorded after T, so a backtest can never leak the future into a +// forecast's score. +// - A CALIBRATION REPORT: sample counts, median absolute ETA error, +// and P80 interval coverage by horizon (2/4/8 weeks) and confidence +// grade, per model version (versions are never mixed into one +// aggregate), compared against the documented no-change baseline +// (the subject's previous snapshot p50 — the forecast you would +// have had by simply not updating). +// +// Honesty gates (from the issue): +// - The model is NOT labelled calibrated before at least 30 resolved +// forecasts across at least 8 distinct weekly cutoffs. +// - Nominal P80 coverage outside 70–90% in two successive eligible +// windows is flagged, as is a model persistently worse than the +// no-change baseline: when `recommendUnavailable` is set, consumers +// should revert the model's displayed confidence to "unavailable" +// (the disable/revert-to-unavailable rule) until a later eligible +// window clears it. +// - Quota-wall classification accuracy is NOT evaluated here: the +// #3983 outcome history does not exist yet, and #3986's scope +// excludes it until it does. The report says so explicitly. + +import { appendFile, mkdir, readFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import type { EpicCompletionForecast, ForecastContract } from "./forecast-contract.ts"; +import type { ForecastConfidence } from "./forecast.ts"; +import type { RefKey } from "./model.ts"; + +export const FORECAST_SNAPSHOT_VERSION = "forecast-snapshot/v1" as const; +export const BACKTEST_REPORT_VERSION = "forecast-backtest/v1" as const; + +/** Minimum resolved forecasts before any calibration claim. */ +export const CALIBRATION_MIN_RESOLVED = 30; +/** Minimum distinct weekly cutoffs before any calibration claim. */ +export const CALIBRATION_MIN_CUTOFFS = 8; +/** Nominal P80 coverage band; outside it in successive eligible + * windows is a miscalibration flag. */ +export const P80_COVERAGE_BAND = { low: 0.7, high: 0.9 } as const; + +const DAY_MS = 86_400_000; +const WEEK_MS = 7 * DAY_MS; + +/** One frozen weekly forecast capture: the unit of the snapshot + * store. `forecasts` are the full epic-completion contract objects — + * they already embed scope, input window/coverage, remaining units, + * and reasons, which is what makes an evaluation reproducible from + * the snapshot alone. One snapshot carries exactly one model version + * (separation starts at the store, not at report time). */ +export interface ForecastSnapshot { + snapshotVersion: typeof FORECAST_SNAPSHOT_VERSION; + modelVersion: string; + /** The forecast origin: forecasts in this snapshot are as of this + * instant (their own `asOf` may be earlier, never later). */ + cutoff: string; + /** When the snapshot was written to the store. An evaluation as of + * T never sees a snapshot captured after T. */ + capturedAt: string; + /** Source name -> watermark (cursor / last-seen id / file digest) + * naming exactly what source state the forecasts were derived + * from. */ + sourceWatermarks: Record; + forecasts: EpicCompletionForecast[]; +} + +export interface CreateSnapshotInput { + forecasts: ForecastContract[]; + capturedAt: string; + sourceWatermarks: Record; + /** Defaults to the latest `asOf` among the epic-completion + * forecasts. */ + cutoff?: string; +} + +/** Build one snapshot from contract objects. Only epic-completion + * forecasts are scored by this module; other contract types are + * refused rather than silently dropped, so a caller mixing types + * learns about it at capture time. */ +export function createSnapshot(input: CreateSnapshotInput): ForecastSnapshot { + const epics: EpicCompletionForecast[] = []; + for (const f of input.forecasts) { + if (f.type !== "epic_completion") { + throw new Error(`forecast snapshot stores epic_completion forecasts only, got ${f.type}`); + } + epics.push(f); + } + if (epics.length === 0) throw new Error("forecast snapshot requires at least one forecast"); + const versions = new Set(epics.map((f) => f.modelVersion)); + if (versions.size !== 1) { + throw new Error(`forecast snapshot mixes model versions: ${[...versions].join(", ")}`); + } + const cutoff = input.cutoff ?? epics.map((f) => f.asOf).sort().at(-1)!; + for (const f of epics) { + if (f.asOf > cutoff) throw new Error(`forecast for ${f.subjectRef} is as of ${f.asOf}, after snapshot cutoff ${cutoff}`); + } + return { + snapshotVersion: FORECAST_SNAPSHOT_VERSION, + modelVersion: epics[0].modelVersion, + cutoff, + capturedAt: input.capturedAt, + sourceWatermarks: { ...input.sourceWatermarks }, + forecasts: epics, + }; +} + +/** Append one snapshot to the JSONL store (creating directories). */ +export async function appendSnapshot(path: string, snapshot: ForecastSnapshot): Promise { + await mkdir(dirname(path), { recursive: true }); + await appendFile(path, JSON.stringify(snapshot) + "\n", "utf8"); +} + +/** Load the whole snapshot store (JSONL). A missing store is an + * empty store — a backtest over zero snapshots is a legitimate + * not-yet-calibrated report, not an error. */ +export async function loadSnapshots(path: string): Promise { + let text: string; + try { + text = await readFile(path, "utf8"); + } catch { + return []; + } + const out: ForecastSnapshot[] = []; + for (const line of text.split("\n")) { + if (line.trim()) out.push(JSON.parse(line) as ForecastSnapshot); + } + return out; +} + +/** One observed outcome for a forecast subject. `completedAt` is null + * while the subject is still open; `recordedAt` is when this record + * entered the outcome history — an evaluation as of T ignores + * records recorded after T, even if they describe an earlier + * completion (that is what cutoff isolation means). */ +export interface ForecastOutcome { + subjectRef: RefKey; + completedAt: string | null; + recordedAt: string; +} + +export type HorizonBucket = "2w" | "4w" | "8w" | "over8w"; + +export interface BacktestGroup { + horizon: HorizonBucket | "all"; + confidence: ForecastConfidence | "all"; + /** Resolved, scored forecasts in this group. */ + n: number; + medianAbsEtaErrorDays: number | null; + /** Share of resolved forecasts whose actual completion fell on or + * before the forecast p80 date; null when no forecast in the group + * carried a p80. */ + p80Coverage: number | null; + p80N: number; + /** Same median error for the no-change baseline (previous snapshot + * p50 for the subject), over the forecasts that have one. */ + baselineMedianAbsEtaErrorDays: number | null; + baselineN: number; +} + +export interface CalibrationGate { + state: "not_yet_calibrated" | "calibrated" | "flagged"; + resolved: number; + distinctCutoffs: number; + minResolved: number; + minCutoffs: number; + p80Coverage: number | null; + /** P80 coverage outside the nominal band in two successive + * eligible windows (gate already met at each window's end). */ + p80SuccessiveWindowsFlag: boolean; + /** Model median error worse than the no-change baseline in each + * of the two most recent scored windows. */ + persistentlyWorseThanBaseline: boolean; + /** Disable/revert rule: when true, consumers revert this model's + * displayed confidence to "unavailable" until a later eligible + * window clears both flags. */ + recommendUnavailable: boolean; +} + +export interface CalibrationReport { + reportVersion: typeof BACKTEST_REPORT_VERSION; + modelVersion: string; + asOf: string; + snapshotsUsed: number; + cutoffs: string[]; + resolved: number; + unresolved: number; + /** Forecasts with no defensible date (p50 null): counted, never + * scored. */ + unscoredNoDate: number; + groups: BacktestGroup[]; + calibration: CalibrationGate; + quotaWall: { state: "not_evaluated"; reason: string }; +} + +interface Scored { + cutoff: string; + confidence: ForecastConfidence; + horizon: HorizonBucket; + etaErrorDays: number; + p80Covered: boolean | null; + baselineErrorDays: number | null; +} + +function median(values: number[]): number | null { + if (values.length === 0) return null; + const sorted = [...values].sort((a, b) => a - b); + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +} + +function horizonBucket(errSpanMs: number): HorizonBucket { + if (errSpanMs <= 2 * WEEK_MS) return "2w"; + if (errSpanMs <= 4 * WEEK_MS) return "4w"; + if (errSpanMs <= 8 * WEEK_MS) return "8w"; + return "over8w"; +} + +function groupMetrics(rows: Scored[], horizon: BacktestGroup["horizon"], confidence: BacktestGroup["confidence"]): BacktestGroup { + const p80Rows = rows.filter((r) => r.p80Covered !== null); + const baseRows = rows.filter((r) => r.baselineErrorDays !== null); + return { + horizon, + confidence, + n: rows.length, + medianAbsEtaErrorDays: median(rows.map((r) => r.etaErrorDays)), + p80Coverage: p80Rows.length === 0 ? null : p80Rows.filter((r) => r.p80Covered).length / p80Rows.length, + p80N: p80Rows.length, + baselineMedianAbsEtaErrorDays: median(baseRows.map((r) => r.baselineErrorDays!)), + baselineN: baseRows.length, + }; +} + +/** Rolling-origin evaluation for ONE model version (callers get one + * report per version present — see evaluateBacktest). */ +export function evaluateVersion(input: { + snapshots: ForecastSnapshot[]; + outcomes: ForecastOutcome[]; + asOf: string; + modelVersion: string; +}): CalibrationReport { + const { asOf, modelVersion } = input; + const asOfMs = Date.parse(asOf); + + // Visibility: nothing created after the evaluation instant exists. + const snapshots = input.snapshots + .filter((s) => s.modelVersion === modelVersion && Date.parse(s.cutoff) <= asOfMs && Date.parse(s.capturedAt) <= asOfMs) + .sort((a, b) => a.cutoff.localeCompare(b.cutoff)); + const outcomeBySubject = new Map(); + for (const o of input.outcomes) { + if (Date.parse(o.recordedAt) > asOfMs) continue; + const prev = outcomeBySubject.get(o.subjectRef); + if (!prev || o.recordedAt > prev.recordedAt) outcomeBySubject.set(o.subjectRef, o); + } + + // Previous p50 per (subject, cutoff) for the no-change baseline. + const previousP50 = new Map(); + { + const lastBySubject = new Map(); + for (const s of snapshots) { + for (const f of s.forecasts) { + previousP50.set(`${s.cutoff}\0${f.subjectRef}`, lastBySubject.get(f.subjectRef) ?? null); + lastBySubject.set(f.subjectRef, f.p50); + } + } + } + + const scored: Scored[] = []; + let unresolved = 0; + let unscoredNoDate = 0; + for (const s of snapshots) { + for (const f of s.forecasts) { + if (f.p50 === null) { + unscoredNoDate++; + continue; + } + const outcome = outcomeBySubject.get(f.subjectRef); + const completedMs = outcome?.completedAt ? Date.parse(outcome.completedAt) : null; + if (completedMs === null || completedMs > asOfMs) { + unresolved++; + continue; + } + const base = previousP50.get(`${s.cutoff}\0${f.subjectRef}`); + scored.push({ + cutoff: s.cutoff, + confidence: f.confidence, + horizon: horizonBucket(completedMs - Date.parse(s.cutoff)), + etaErrorDays: Math.abs(completedMs - Date.parse(f.p50)) / DAY_MS, + p80Covered: f.p80 === null ? null : completedMs <= Date.parse(f.p80), + baselineErrorDays: base ? Math.abs(completedMs - Date.parse(base)) / DAY_MS : null, + }); + } + } + + const groups: BacktestGroup[] = []; + const horizons: BacktestGroup["horizon"][] = ["2w", "4w", "8w", "over8w", "all"]; + const confidences: BacktestGroup["confidence"][] = ["high", "medium", "low", "unavailable", "all"]; + for (const h of horizons) { + for (const c of confidences) { + const rows = scored.filter((r) => (h === "all" || r.horizon === h) && (c === "all" || r.confidence === c)); + if (rows.length > 0) groups.push(groupMetrics(rows, h, c)); + } + } + + // Windows: one per distinct cutoff, cumulative for gate/flag maths. + const cutoffs = [...new Set(snapshots.map((s) => s.cutoff))].sort(); + let cumResolved = 0; + let cumP80Covered = 0; + let cumP80N = 0; + const windowP80Flags: boolean[] = []; + const windowWorse: boolean[] = []; + for (const cutoff of cutoffs) { + const rows = scored.filter((r) => r.cutoff === cutoff); + cumResolved += rows.length; + const p80Rows = rows.filter((r) => r.p80Covered !== null); + cumP80Covered += p80Rows.filter((r) => r.p80Covered).length; + cumP80N += p80Rows.length; + const eligible = cumResolved >= CALIBRATION_MIN_RESOLVED && cutoffs.indexOf(cutoff) + 1 >= CALIBRATION_MIN_CUTOFFS; + if (eligible && cumP80N > 0) { + const cov = cumP80Covered / cumP80N; + windowP80Flags.push(cov < P80_COVERAGE_BAND.low || cov > P80_COVERAGE_BAND.high); + } + const baseRows = rows.filter((r) => r.baselineErrorDays !== null); + if (baseRows.length > 0) { + const modelMed = median(rows.map((r) => r.etaErrorDays)); + const baseMed = median(baseRows.map((r) => r.baselineErrorDays!)); + if (modelMed !== null && baseMed !== null) windowWorse.push(modelMed > baseMed); + } + } + const successive = (flags: boolean[]) => flags.length >= 2 && flags.at(-1)! && flags.at(-2)!; + const p80Flag = successive(windowP80Flags); + const worse = successive(windowWorse); + + const allGroup = groupMetrics(scored, "all", "all"); + const gateMet = scored.length >= CALIBRATION_MIN_RESOLVED && cutoffs.length >= CALIBRATION_MIN_CUTOFFS; + return { + reportVersion: BACKTEST_REPORT_VERSION, + modelVersion, + asOf, + snapshotsUsed: snapshots.length, + cutoffs, + resolved: scored.length, + unresolved, + unscoredNoDate, + groups, + calibration: { + state: !gateMet ? "not_yet_calibrated" : p80Flag || worse ? "flagged" : "calibrated", + resolved: scored.length, + distinctCutoffs: cutoffs.length, + minResolved: CALIBRATION_MIN_RESOLVED, + minCutoffs: CALIBRATION_MIN_CUTOFFS, + p80Coverage: allGroup.p80Coverage, + p80SuccessiveWindowsFlag: p80Flag, + persistentlyWorseThanBaseline: worse, + recommendUnavailable: gateMet && (p80Flag || worse), + }, + quotaWall: { + state: "not_evaluated", + reason: "quota-wall classification accuracy requires the #3983 outcome history, which does not exist yet; excluded from #3986 evaluation until it does", + }, + }; +} + +/** Evaluate every model version present in the visible snapshots, + * one report per version — aggregates never mix versions. */ +export function evaluateBacktest(input: { + snapshots: ForecastSnapshot[]; + outcomes: ForecastOutcome[]; + asOf: string; +}): CalibrationReport[] { + const versions = [...new Set(input.snapshots.map((s) => s.modelVersion))].sort(); + return versions.map((modelVersion) => evaluateVersion({ ...input, modelVersion })); +} diff --git a/pm-stack/aggregator/test/backtest.test.ts b/pm-stack/aggregator/test/backtest.test.ts new file mode 100644 index 000000000..11f3253f7 --- /dev/null +++ b/pm-stack/aggregator/test/backtest.test.ts @@ -0,0 +1,217 @@ +import { describe, expect, it } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + appendSnapshot, + createSnapshot, + evaluateBacktest, + evaluateVersion, + loadSnapshots, + type ForecastOutcome, + type ForecastSnapshot, +} from "../src/backtest.ts"; +import type { EpicCompletionForecast } from "../src/forecast-contract.ts"; +import type { ForecastConfidence } from "../src/forecast.ts"; + +const CUTOFF = "2026-01-05T00:00:00.000Z"; + +function forecast( + subjectRef: string, + asOf: string, + p50: string | null, + p80: string | null, + confidence: ForecastConfidence = "high", + modelVersion = "forecast/v3", +): EpicCompletionForecast { + return { + contractVersion: "forecast-contract/v1", + type: "epic_completion", + subjectRef, + scope: "test scope", + asOf, + modelVersion, + confidence, + reasons: [], + limitations: [], + status: "forecast", + inputWindow: { primaryWeeks: 4, comparisonWeeks: 4, completeWeeks: 4, from: null, to: asOf }, + inputCoverage: { completeWeeks: 4, totalCutoffs: 4, unavailableCutoffs: 0 }, + remainingUnits: 3, + completedUnits: 7, + p50, + p80, + baselineSource: "subject", + remainingEffort: { byEffort: {}, unsized: 0, openEnded: 0 }, + }; +} + +function snapshot(forecasts: EpicCompletionForecast[], cutoff = CUTOFF, capturedAt = cutoff): ForecastSnapshot { + return createSnapshot({ forecasts, capturedAt, sourceWatermarks: { "item-history": "fixture" }, cutoff }); +} + +function outcome(subjectRef: string, completedAt: string | null, recordedAt = "2026-03-01T00:00:00.000Z"): ForecastOutcome { + return { subjectRef, completedAt, recordedAt }; +} + +describe("forecast snapshot store (#3986)", () => { + it("round-trips snapshots as JSONL with the issue's fields", async () => { + const dir = await mkdtemp(join(tmpdir(), "backtest-store-")); + try { + const path = join(dir, "snapshots.jsonl"); + const snap = snapshot([forecast("gh:o/r#1", CUTOFF, "2026-01-12T00:00:00.000Z", "2026-01-19T00:00:00.000Z")]); + expect(snap.modelVersion).toBe("forecast/v3"); + expect(snap.cutoff).toBe(CUTOFF); + expect(snap.sourceWatermarks["item-history"]).toBe("fixture"); + await appendSnapshot(path, snap); + await appendSnapshot(path, snap); + const loaded = await loadSnapshots(path); + expect(loaded).toHaveLength(2); + expect(loaded[0]).toEqual(snap); + expect(await loadSnapshots(join(dir, "missing.jsonl"))).toEqual([]); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + + it("refuses mixed model versions and non-epic forecasts at capture", () => { + expect(() => + createSnapshot({ + forecasts: [ + forecast("gh:o/r#1", CUTOFF, null, null, "high", "forecast/v3"), + forecast("gh:o/r#2", CUTOFF, null, null, "high", "forecast/v4"), + ], + capturedAt: CUTOFF, + sourceWatermarks: {}, + }), + ).toThrow("mixes model versions"); + }); +}); + +describe("rolling-origin evaluation (#3986)", () => { + const asOf = "2026-03-01T00:00:00.000Z"; + + it("computes median ETA error and P80 coverage by horizon and confidence", () => { + const snap = snapshot([ + forecast("gh:o/r#a", CUTOFF, "2026-01-12T00:00:00.000Z", "2026-01-19T00:00:00.000Z"), + forecast("gh:o/r#b", CUTOFF, "2026-01-12T00:00:00.000Z", "2026-01-13T00:00:00.000Z", "low"), + forecast("gh:o/r#c", CUTOFF, null, null), + forecast("gh:o/r#d", CUTOFF, "2026-01-12T00:00:00.000Z", "2026-01-19T00:00:00.000Z"), + ]); + const report = evaluateVersion({ + snapshots: [snap], + outcomes: [ + outcome("gh:o/r#a", "2026-01-14T00:00:00.000Z"), // err 2d, 2w horizon, covered + outcome("gh:o/r#b", "2026-01-20T00:00:00.000Z"), // err 8d, 4w horizon (15d), not covered + outcome("gh:o/r#c", "2026-01-14T00:00:00.000Z"), + outcome("gh:o/r#d", null), // unresolved + ], + asOf, + modelVersion: "forecast/v3", + }); + expect(report.resolved).toBe(2); + expect(report.unresolved).toBe(1); + expect(report.unscoredNoDate).toBe(1); + const all = report.groups.find((g) => g.horizon === "all" && g.confidence === "all")!; + expect(all.n).toBe(2); + expect(all.medianAbsEtaErrorDays).toBe(5); + expect(all.p80Coverage).toBe(0.5); + const twoW = report.groups.find((g) => g.horizon === "2w" && g.confidence === "high")!; + expect(twoW.medianAbsEtaErrorDays).toBe(2); + const fourW = report.groups.find((g) => g.horizon === "4w" && g.confidence === "low")!; + expect(fourW.p80Coverage).toBe(0); + expect(report.calibration.state).toBe("not_yet_calibrated"); + expect(report.quotaWall.state).toBe("not_evaluated"); + }); + + it("cutoff isolation: nothing created after the evaluation instant is visible", () => { + const visible = snapshot([forecast("gh:o/r#a", CUTOFF, "2026-01-12T00:00:00.000Z", "2026-01-19T00:00:00.000Z")]); + // Same cutoff, but captured after asOf: a record created after T. + const futureCapture = { ...visible, capturedAt: "2026-03-02T00:00:00.000Z" }; + const report = evaluateVersion({ snapshots: [futureCapture], outcomes: [outcome("gh:o/r#a", "2026-01-14T00:00:00.000Z")], asOf, modelVersion: "forecast/v3" }); + expect(report.snapshotsUsed).toBe(0); + expect(report.resolved).toBe(0); + // An outcome recorded after asOf does not resolve the forecast, + // even though the completion itself predates asOf. + const lateRecord = outcome("gh:o/r#a", "2026-01-14T00:00:00.000Z", "2026-03-02T00:00:00.000Z"); + const report2 = evaluateVersion({ snapshots: [visible], outcomes: [lateRecord], asOf, modelVersion: "forecast/v3" }); + expect(report2.resolved).toBe(0); + expect(report2.unresolved).toBe(1); + }); + + it("separates model versions into separate reports", () => { + const v3 = snapshot([forecast("gh:o/r#a", CUTOFF, "2026-01-12T00:00:00.000Z", null, "high", "forecast/v3")]); + const v4 = snapshot([forecast("gh:o/r#a", CUTOFF, "2026-01-19T00:00:00.000Z", null, "high", "forecast/v4")]); + const reports = evaluateBacktest({ snapshots: [v3, v4], outcomes: [outcome("gh:o/r#a", "2026-01-13T00:00:00.000Z")], asOf }); + expect(reports.map((r) => r.modelVersion)).toEqual(["forecast/v3", "forecast/v4"]); + expect(reports[0].groups.find((g) => g.horizon === "all" && g.confidence === "all")!.medianAbsEtaErrorDays).toBe(1); + expect(reports[1].groups.find((g) => g.horizon === "all" && g.confidence === "all")!.medianAbsEtaErrorDays).toBe(6); + }); + + it("scores the no-change baseline from the subject's previous snapshot", () => { + const first = snapshot([forecast("gh:o/r#a", "2026-01-05T00:00:00.000Z", "2026-02-01T00:00:00.000Z", null)], "2026-01-05T00:00:00.000Z"); + const second = snapshot([forecast("gh:o/r#a", "2026-01-12T00:00:00.000Z", "2026-01-20T00:00:00.000Z", null)], "2026-01-12T00:00:00.000Z"); + const report = evaluateVersion({ snapshots: [first, second], outcomes: [outcome("gh:o/r#a", "2026-01-22T00:00:00.000Z")], asOf, modelVersion: "forecast/v3" }); + const all = report.groups.find((g) => g.horizon === "all" && g.confidence === "all")!; + expect(all.n).toBe(2); + expect(all.baselineN).toBe(1); // only the second forecast has a predecessor + expect(all.baselineMedianAbsEtaErrorDays).toBe(10); // |Jan 22 - Feb 1| + }); +}); + +describe("calibration gate (#3986)", () => { + const asOf = "2026-06-01T00:00:00.000Z"; + const DAY = 86_400_000; + + function gateFixture(cutoffs: number, perCutoff: number, coveredShare: number) { + const snapshots: ForecastSnapshot[] = []; + const outcomes: ForecastOutcome[] = []; + const base = Date.parse("2026-01-05T00:00:00.000Z"); + let idx = 0; + for (let c = 0; c < cutoffs; c++) { + const cutoffMs = base + c * 7 * DAY; + const cutoff = new Date(cutoffMs).toISOString(); + const forecasts: EpicCompletionForecast[] = []; + for (let k = 0; k < perCutoff; k++, idx++) { + const subject = `gh:o/r#s${idx}`; + const p50 = new Date(cutoffMs + 10 * DAY).toISOString(); + const p80 = new Date(cutoffMs + 20 * DAY).toISOString(); + forecasts.push(forecast(subject, cutoff, p50, p80)); + // Deterministic coverage pattern: share 0.8 covers idx % 5 != 4 + // (actual lands 12d after cutoff, inside the p80 at +20d); an + // uncovered forecast lands at +25d, past its p80. + const isCovered = coveredShare >= 1 ? true : coveredShare <= 0 ? false : idx % 5 !== 4; + const actual = new Date(cutoffMs + (isCovered ? 12 : 25) * DAY).toISOString(); + outcomes.push(outcome(subject, actual, "2026-05-01T00:00:00.000Z")); + } + snapshots.push(createSnapshot({ forecasts, capturedAt: cutoff, sourceWatermarks: {}, cutoff })); + } + return { snapshots, outcomes }; + } + + it("labels the model calibrated only at 30 resolved across 8 cutoffs with in-band coverage", () => { + const { snapshots, outcomes } = gateFixture(10, 4, 0.8); // 40 resolved, 80% coverage + const report = evaluateVersion({ snapshots, outcomes, asOf, modelVersion: "forecast/v3" }); + expect(report.resolved).toBe(40); + expect(report.calibration.distinctCutoffs).toBe(10); + expect(report.calibration.p80Coverage).toBeCloseTo(0.8, 5); + expect(report.calibration.state).toBe("calibrated"); + expect(report.calibration.recommendUnavailable).toBe(false); + }); + + it("flags P80 coverage outside 70-90% in successive eligible windows", () => { + const { snapshots, outcomes } = gateFixture(10, 4, 0); // nothing covered + const report = evaluateVersion({ snapshots, outcomes, asOf, modelVersion: "forecast/v3" }); + expect(report.calibration.p80Coverage).toBe(0); + expect(report.calibration.p80SuccessiveWindowsFlag).toBe(true); + expect(report.calibration.state).toBe("flagged"); + expect(report.calibration.recommendUnavailable).toBe(true); + }); + + it("keeps the not-yet-calibrated gate below the thresholds", () => { + const { snapshots, outcomes } = gateFixture(3, 4, 0.8); // 12 resolved, 3 cutoffs + const report = evaluateVersion({ snapshots, outcomes, asOf, modelVersion: "forecast/v3" }); + expect(report.calibration.state).toBe("not_yet_calibrated"); + expect(report.calibration.recommendUnavailable).toBe(false); + }); +}); From 5cb77a4ba31302e607fca6eb83d323ced34067b6 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 15:03:28 -0600 Subject: [PATCH 2/2] fix(aggregator): address Codex P2 findings on the forecast backtest (PR #8436) 1. forecast-snapshot CLI: accept the actual /api/forecasts.json shape (contracts array) and select epic-completion contracts at the CLI boundary; the store keeps its strict validation for direct callers. 2. Scoring excludes subjects already complete at the forecast origin (counted as excludedAlreadyComplete), so known completions no longer inflate resolved counts or P80 coverage. 3. Worse-than-baseline windows compare model and baseline medians over the same paired subjects. 4. The calibration gate counts weekly cutoffs contributing scored forecasts, not all captured snapshots. Each fix carries a regression test; bun test test/backtest.test.ts passes 13/13. --- .../aggregator/scripts/forecast-snapshot.ts | 29 ++++- pm-stack/aggregator/src/backtest.ts | 36 ++++- pm-stack/aggregator/test/backtest.test.ts | 123 +++++++++++++++++- 3 files changed, 179 insertions(+), 9 deletions(-) diff --git a/pm-stack/aggregator/scripts/forecast-snapshot.ts b/pm-stack/aggregator/scripts/forecast-snapshot.ts index dd8afa0b6..50c0252e6 100644 --- a/pm-stack/aggregator/scripts/forecast-snapshot.ts +++ b/pm-stack/aggregator/scripts/forecast-snapshot.ts @@ -6,8 +6,14 @@ // --forecasts forecasts.json --out data/forecast-snapshots.jsonl \ // --watermark item-history= [--cutoff ] // -// --forecasts is a JSON file holding ForecastContract[] (or an object -// with a `forecasts` array) as served by GET /api/forecasts.json. The +// --forecasts is a JSON file as served by GET /api/forecasts.json: +// an object whose `contracts` array holds every forecast contract +// (epic-completion, quota-exhaustion, and stall-risk). The CLI selects +// the epic-completion contracts at this boundary; the snapshot store +// itself keeps refusing anything else. A bare ForecastContract[] (or +// an object with a `forecasts` array) is also accepted and passed +// through unfiltered, so a mixed file in those shapes still fails the +// store's strict validation instead of being silently trimmed. The // snapshot freezes the epic-completion forecasts with their model // version, the cutoff, and the source watermarks that name exactly // what source state they were derived from. @@ -26,8 +32,23 @@ if (!forecastsPath || !out) { console.error("usage: forecast-snapshot.ts --forecasts --out [--cutoff ] [--watermark k=v ...]"); process.exit(2); } -const parsed = JSON.parse(await readFile(forecastsPath, "utf8")) as ForecastContract[] | { forecasts: ForecastContract[] }; -const forecasts = Array.isArray(parsed) ? parsed : parsed.forecasts; +const parsed = JSON.parse(await readFile(forecastsPath, "utf8")) as + | ForecastContract[] + | { forecasts?: ForecastContract[]; contracts?: ForecastContract[] }; +let forecasts: ForecastContract[]; +if (Array.isArray(parsed)) { + forecasts = parsed; +} else if (Array.isArray(parsed.contracts)) { + // The actual /api/forecasts.json shape: select the epic-completion + // contracts here; createSnapshot keeps its strict validation for + // direct callers (Codex P2, PR #8436). + forecasts = parsed.contracts.filter((f) => f.type === "epic_completion"); +} else if (Array.isArray(parsed.forecasts)) { + forecasts = parsed.forecasts; +} else { + console.error("forecast-snapshot: --forecasts file has no contracts/forecasts array (expected the /api/forecasts.json shape)"); + process.exit(2); +} const sourceWatermarks: Record = {}; for (let i = 0; i < process.argv.length; i++) { if (process.argv[i] === "--watermark") { diff --git a/pm-stack/aggregator/src/backtest.ts b/pm-stack/aggregator/src/backtest.ts index da1c93330..bd862d3c3 100644 --- a/pm-stack/aggregator/src/backtest.ts +++ b/pm-stack/aggregator/src/backtest.ts @@ -197,6 +197,11 @@ export interface CalibrationReport { /** Forecasts with no defensible date (p50 null): counted, never * scored. */ unscoredNoDate: number; + /** Forecasts whose subject was already complete at the snapshot + * cutoff: the completion was known at the forecast origin, so + * scoring them would credit the model with predicting the past. + * Counted, never scored. */ + excludedAlreadyComplete: number; groups: BacktestGroup[]; calibration: CalibrationGate; quotaWall: { state: "not_evaluated"; reason: string }; @@ -277,6 +282,7 @@ export function evaluateVersion(input: { const scored: Scored[] = []; let unresolved = 0; let unscoredNoDate = 0; + let excludedAlreadyComplete = 0; for (const s of snapshots) { for (const f of s.forecasts) { if (f.p50 === null) { @@ -289,6 +295,15 @@ export function evaluateVersion(input: { unresolved++; continue; } + if (completedMs <= Date.parse(s.cutoff)) { + // Already complete at this snapshot's origin: production + // derivation keeps such subjects in later captures with + // p50 = p80 = asOf, and scoring them would repeatedly credit + // a completion the forecaster already knew about (Codex P2, + // PR #8436). Prospective scoring only. + excludedAlreadyComplete++; + continue; + } const base = previousP50.get(`${s.cutoff}\0${f.subjectRef}`); scored.push({ cutoff: s.cutoff, @@ -313,6 +328,12 @@ export function evaluateVersion(input: { // Windows: one per distinct cutoff, cumulative for gate/flag maths. const cutoffs = [...new Set(snapshots.map((s) => s.cutoff))].sort(); + // The calibration gate counts weekly cutoffs that contribute SCORED + // forecasts, not every captured snapshot: a run of snapshots whose + // forecasts are all unavailable (p50 null) is not evidence (Codex + // P2, PR #8436). + const scoredCutoffs = [...new Set(scored.map((r) => r.cutoff))].sort(); + const scoredCutoffsSeen = new Set(); let cumResolved = 0; let cumP80Covered = 0; let cumP80N = 0; @@ -320,18 +341,24 @@ export function evaluateVersion(input: { const windowWorse: boolean[] = []; for (const cutoff of cutoffs) { const rows = scored.filter((r) => r.cutoff === cutoff); + if (rows.length > 0) scoredCutoffsSeen.add(cutoff); cumResolved += rows.length; const p80Rows = rows.filter((r) => r.p80Covered !== null); cumP80Covered += p80Rows.filter((r) => r.p80Covered).length; cumP80N += p80Rows.length; - const eligible = cumResolved >= CALIBRATION_MIN_RESOLVED && cutoffs.indexOf(cutoff) + 1 >= CALIBRATION_MIN_CUTOFFS; + const eligible = cumResolved >= CALIBRATION_MIN_RESOLVED && scoredCutoffsSeen.size >= CALIBRATION_MIN_CUTOFFS; if (eligible && cumP80N > 0) { const cov = cumP80Covered / cumP80N; windowP80Flags.push(cov < P80_COVERAGE_BAND.low || cov > P80_COVERAGE_BAND.high); } const baseRows = rows.filter((r) => r.baselineErrorDays !== null); if (baseRows.length > 0) { - const modelMed = median(rows.map((r) => r.etaErrorDays)); + // Paired comparison: model and baseline medians over the SAME + // subjects (those with a baseline). Mixing first-seen subjects + // into the model median only would let the subject mix, not + // the model, drive the worse-than-baseline flag (Codex P2, + // PR #8436). + const modelMed = median(baseRows.map((r) => r.etaErrorDays)); const baseMed = median(baseRows.map((r) => r.baselineErrorDays!)); if (modelMed !== null && baseMed !== null) windowWorse.push(modelMed > baseMed); } @@ -341,7 +368,7 @@ export function evaluateVersion(input: { const worse = successive(windowWorse); const allGroup = groupMetrics(scored, "all", "all"); - const gateMet = scored.length >= CALIBRATION_MIN_RESOLVED && cutoffs.length >= CALIBRATION_MIN_CUTOFFS; + const gateMet = scored.length >= CALIBRATION_MIN_RESOLVED && scoredCutoffs.length >= CALIBRATION_MIN_CUTOFFS; return { reportVersion: BACKTEST_REPORT_VERSION, modelVersion, @@ -351,11 +378,12 @@ export function evaluateVersion(input: { resolved: scored.length, unresolved, unscoredNoDate, + excludedAlreadyComplete, groups, calibration: { state: !gateMet ? "not_yet_calibrated" : p80Flag || worse ? "flagged" : "calibrated", resolved: scored.length, - distinctCutoffs: cutoffs.length, + distinctCutoffs: scoredCutoffs.length, minResolved: CALIBRATION_MIN_RESOLVED, minCutoffs: CALIBRATION_MIN_CUTOFFS, p80Coverage: allGroup.p80Coverage, diff --git a/pm-stack/aggregator/test/backtest.test.ts b/pm-stack/aggregator/test/backtest.test.ts index 11f3253f7..a8892c343 100644 --- a/pm-stack/aggregator/test/backtest.test.ts +++ b/pm-stack/aggregator/test/backtest.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "bun:test"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { @@ -215,3 +215,124 @@ describe("calibration gate (#3986)", () => { expect(report.calibration.recommendUnavailable).toBe(false); }); }); + +describe("Codex P2 regressions (PR #8436)", () => { + const asOf = "2026-06-01T00:00:00.000Z"; + const DAY = 86_400_000; + + it("excludes subjects already complete at the forecast origin", () => { + const snap = snapshot([ + // As deriveEpicEta emits for a completed subject: p50 = p80 = asOf. + forecast("gh:o/r#done", CUTOFF, CUTOFF, CUTOFF), + forecast("gh:o/r#live", CUTOFF, "2026-01-12T00:00:00.000Z", "2026-01-19T00:00:00.000Z"), + ]); + const report = evaluateVersion({ + snapshots: [snap], + outcomes: [ + outcome("gh:o/r#done", "2026-01-03T00:00:00.000Z"), // completed BEFORE the Jan 5 cutoff + outcome("gh:o/r#live", "2026-01-14T00:00:00.000Z"), + ], + asOf, + modelVersion: "forecast/v3", + }); + expect(report.resolved).toBe(1); + expect(report.excludedAlreadyComplete).toBe(1); + const all = report.groups.find((g) => g.horizon === "all" && g.confidence === "all")!; + expect(all.n).toBe(1); + expect(all.medianAbsEtaErrorDays).toBe(2); + }); + + it("calibration gate counts only cutoffs contributing scored forecasts", () => { + const snapshots: ForecastSnapshot[] = []; + const outcomes: ForecastOutcome[] = []; + const base = Date.parse(CUTOFF); + // Seven weekly snapshots whose forecasts are all unavailable. + for (let c = 0; c < 7; c++) { + const cutoff = new Date(base + c * 7 * DAY).toISOString(); + snapshots.push(snapshot([forecast(`gh:o/r#u${c}`, cutoff, null, null)], cutoff)); + } + // The eighth carries 30 forecasts that resolve at 80% P80 coverage. + const c8ms = base + 7 * 7 * DAY; + const c8 = new Date(c8ms).toISOString(); + const fs: EpicCompletionForecast[] = []; + for (let k = 0; k < 30; k++) { + const subject = `gh:o/r#g${k}`; + fs.push(forecast(subject, c8, new Date(c8ms + 10 * DAY).toISOString(), new Date(c8ms + 20 * DAY).toISOString())); + outcomes.push(outcome(subject, new Date(c8ms + (k % 5 !== 4 ? 12 : 25) * DAY).toISOString(), "2026-05-01T00:00:00.000Z")); + } + snapshots.push(snapshot(fs, c8)); + const report = evaluateVersion({ snapshots, outcomes, asOf, modelVersion: "forecast/v3" }); + expect(report.resolved).toBe(30); + expect(report.calibration.distinctCutoffs).toBe(1); + expect(report.calibration.state).toBe("not_yet_calibrated"); + expect(report.calibration.recommendUnavailable).toBe(false); + }); + + it("compares model and baseline errors over the same subjects", () => { + const c1 = "2026-01-05T00:00:00.000Z"; + const c2 = "2026-01-12T00:00:00.000Z"; + const c3 = "2026-01-19T00:00:00.000Z"; + const actual = "2026-03-01T00:00:00.000Z"; + const s1 = snapshot( + [forecast("gh:o/r#a", c1, "2026-01-20T00:00:00.000Z", null), forecast("gh:o/r#b", c1, "2026-01-20T00:00:00.000Z", null)], + c1, + ); + // Continuing subjects improve (model err 5 vs baseline err 40); + // first-seen subjects carry 100d errors and no baseline. + const s2 = snapshot( + [ + forecast("gh:o/r#a", c2, "2026-02-24T00:00:00.000Z", null), + forecast("gh:o/r#b", c2, "2026-02-24T00:00:00.000Z", null), + forecast("gh:o/r#n1", c2, "2026-06-09T00:00:00.000Z", null), + forecast("gh:o/r#n2", c2, "2026-06-09T00:00:00.000Z", null), + ], + c2, + ); + // Continuing subjects improve again (model err 2 vs baseline err 5). + const s3 = snapshot( + [ + forecast("gh:o/r#a", c3, "2026-02-27T00:00:00.000Z", null), + forecast("gh:o/r#b", c3, "2026-02-27T00:00:00.000Z", null), + forecast("gh:o/r#n3", c3, "2026-06-09T00:00:00.000Z", null), + forecast("gh:o/r#n4", c3, "2026-06-09T00:00:00.000Z", null), + ], + c3, + ); + const outcomes = ["a", "b", "n1", "n2", "n3", "n4"].map((x) => outcome(`gh:o/r#${x}`, actual)); + const report = evaluateVersion({ snapshots: [s1, s2, s3], outcomes, asOf, modelVersion: "forecast/v3" }); + // Unpaired medians would call both windows worse (medians 52.5 > 40 + // and 51 > 5); paired, the model beats the baseline in both. + expect(report.calibration.persistentlyWorseThanBaseline).toBe(false); + }); + + it("forecast-snapshot CLI captures the /api/forecasts.json contracts shape", async () => { + const dir = await mkdtemp(join(tmpdir(), "backtest-cli-")); + try { + const api = { + contractVersion: "forecast-contract/v1", + generatedAt: CUTOFF, + contracts: [ + forecast("gh:o/r#1", CUTOFF, "2026-01-12T00:00:00.000Z", "2026-01-19T00:00:00.000Z"), + { type: "quota_exhaustion" }, + { type: "stall_risk" }, + ], + }; + const inputPath = join(dir, "forecasts.json"); + await writeFile(inputPath, JSON.stringify(api)); + const outPath = join(dir, "snapshots.jsonl"); + const script = join(import.meta.dir, "../scripts/forecast-snapshot.ts"); + const proc = Bun.spawn( + [process.execPath, "run", script, "--forecasts", inputPath, "--out", outPath, "--watermark", "item-history=fixture"], + { stdout: "pipe", stderr: "pipe" }, + ); + expect(await proc.exited).toBe(0); + const loaded = await loadSnapshots(outPath); + expect(loaded).toHaveLength(1); + expect(loaded[0].forecasts).toHaveLength(1); + expect(loaded[0].forecasts[0].subjectRef).toBe("gh:o/r#1"); + expect(loaded[0].sourceWatermarks["item-history"]).toBe("fixture"); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +});