Skip to content

feat(aggregator): forecast backtest + calibration report (#3986) - #8436

Merged
dezren39 merged 2 commits into
mainfrom
queue/14816-3986-forecast-backtest
Nov 14, 2026
Merged

dezren39 merged 2 commits into
mainfrom
queue/14816-3986-forecast-backtest

Conversation

@dezren39

@dezren39 dezren39 commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Closes #3986.

What lands

Forecasts (ETA bands #3982, contract objects #3984) were published with no measurement of usefulness or calibration. This adds the measurement, in pm-stack/aggregator:

  • Snapshot store (src/backtest.ts): createSnapshot / appendSnapshot / loadSnapshots freeze weekly forecast captures as JSONL — model version, cutoff, source watermarks, and the full epic-completion contract objects (the minimal reproducible inputs: scope, input window/coverage, remaining units, reasons). One snapshot carries exactly one model version; mixed versions and non-epic contracts are refused at capture.
  • Rolling-origin evaluation: an evaluation as of T reads snapshots only — it sees no snapshot captured after T and no outcome recorded after T, so a backtest cannot leak the future into a forecast's score. Scores are per model version, never mixed.
  • Calibration report: sample counts, median absolute ETA error, and P80 interval coverage by 2/4/8-week horizon and confidence grade, compared against the documented no-change baseline (the subject's previous snapshot p50). The not-yet-calibrated gate is enforced: no calibrated state before 30 resolved forecasts across 8 distinct cutoffs; P80 coverage outside 70–90% in two successive eligible windows, or a model persistently worse than baseline, flags the report and sets recommendUnavailable (the documented disable/revert-to-unavailable rule).
  • Quota-wall classification is explicitly not_evaluated: the aggregator: forecast per-pool quota exhaustion intervals #3983 outcome history does not exist yet and the issue scope excludes it until it does. No forecast-derivation semantics change.
  • Commands: scripts/forecast-snapshot.ts (the weekly capture job) and scripts/backtest-report.ts (evaluate a store + outcome history, print the report).

Tests

  • bun test test/backtest.test.ts — 9/9 pass: store round-trip + capture refusals, median-error/P80 metrics by horizon and grade, cutoff isolation (future-captured snapshot and late-recorded outcome are invisible), model-version separation, baseline scoring, and the calibration gate (calibrated / flagged / not-yet).
  • CLI smoke: snapshot script captured a fixture forecast; report script resolved it (median error 2d, coverage 1.0).
  • Neighboring suites forecast-3982 + forecast-contract-3984: 48 pass, 1 fail — the failure is a 5s timeout in deriveEpicEta > partially censored distribution (#6386) that reproduces identically on clean main in the primary clone (pre-existing, untouched by this change).
  • bunx tsc --noEmit: 24 errors, the same 24 as clean main; none in the new files.

Queue: task 14816, lane code-e.


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

@dezren39
dezren39 requested a review from a team as a code owner November 11, 2026 02:27
@coderabbitai

coderabbitai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 58 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b2bf81ce-e289-488a-80eb-01837d3922e3
Commits

Reviewing files that changed from the base of the PR and between 49911d0 and 5cb77a4.

Files selected for processing: 4

  • pm-stack/aggregator/scripts/backtest-report.ts
  • pm-stack/aggregator/scripts/forecast-snapshot.ts
  • pm-stack/aggregator/src/backtest.ts
  • pm-stack/aggregator/test/backtest.test.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-14T21:03:40.374936Z
We couldn’t complete this review. Comment @codex review to try again.
5cb77a4 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 40e0a9e3bc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +29 to +30
const parsed = JSON.parse(await readFile(forecastsPath, "utf8")) as ForecastContract[] | { forecasts: ForecastContract[] };
const forecasts = Array.isArray(parsed) ? parsed : parsed.forecasts;

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 Accept the actual forecast API response in the snapshot command

When --forecasts contains the documented /api/forecasts.json response, this reads undefined: the handler in src/server.ts returns a contracts array, not forecasts. createSnapshot then throws while iterating it, so the advertised capture workflow cannot write a snapshot. That API also includes stall-risk and quota contracts, which createSnapshot deliberately rejects. Extract the actual API field and select epic-completion contracts at the CLI boundary while retaining the store's strict validation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5cb77a4 (task 17228, lane any-c). The CLI now accepts the actual /api/forecasts.json shape: when the parsed file carries a contracts array, it selects the epic_completion contracts at the CLI boundary before calling createSnapshot, which keeps its strict validation for direct callers. Bare arrays and {forecasts} files pass through unfiltered, so mixed files in those shapes still fail loudly. Regression test: "forecast-snapshot CLI captures the /api/forecasts.json contracts shape" spawns the CLI on a fixture API response containing quota-exhaustion and stall-risk contracts and asserts only the epic contract is stored. bun test test/backtest.test.ts passes 13/13.

Comment on lines +286 to +290
const outcome = outcomeBySubject.get(f.subjectRef);
const completedMs = outcome?.completedAt ? Date.parse(outcome.completedAt) : null;
if (completedMs === null || completedMs > asOfMs) {
unresolved++;
continue;

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 Exclude outcomes completed before the forecast origin

When a captured subject was already complete at its forecast origin, this still adds it to the scored forecasts because the only completion-time check is against the evaluation date. This occurs with existing production derivation: allForecastContracts retains subjects from historical item cutoffs, and deriveEpicEta returns p50 = p80 = asOf when all children are complete. Subsequent captures therefore repeatedly score already-known completions, assign their negative horizons to 2w, and inflate the resolved count and P80 coverage. Exclude already-completed subjects from prospective forecast scoring before updating metrics and calibration eligibility.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5cb77a4 (task 17228, lane any-c). Scoring now excludes any forecast whose outcome completed at or before the snapshot cutoff — the completion was known at the forecast origin — and counts it separately as excludedAlreadyComplete on the report instead of letting it inflate resolved counts, horizon buckets, or P80 coverage. Regression test: "excludes subjects already complete at the forecast origin" (a p50 = p80 = asOf subject completed before the cutoff is excluded; a genuinely prospective forecast still scores). bun test test/backtest.test.ts passes 13/13.

Comment on lines +332 to +335
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!));

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 Compare model and baseline errors on the same subjects

When a cutoff contains both continuing subjects and first-seen subjects, modelMed includes every forecast while baseMed includes only forecasts with a predecessor. For example, a continuing forecast improving from 10 days of baseline error to 5 days of model error is still marked worse if two new subjects have 100-day errors. Repeating that mix for two cutoffs can incorrectly set recommendUnavailable; the opposite mix can hide a real regression. Compute both medians over baseRows so the retirement decision compares paired observations.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5cb77a4 (task 17228, lane any-c). The window comparison now computes the model median over baseRows — the same paired subjects that have a baseline — so first-seen subjects no longer enter the model median alone and the subject mix cannot drive persistentlyWorseThanBaseline / recommendUnavailable. Regression test: "compares model and baseline errors over the same subjects" builds two windows where unpaired medians would flag worse (52.5 > 40, 51 > 5) while the paired comparison shows the model improving (5 < 40, 2 < 5), and asserts the flag stays false. bun test test/backtest.test.ts passes 13/13.

Comment thread pm-stack/aggregator/src/backtest.ts Outdated
const worse = successive(windowWorse);

const allGroup = groupMetrics(scored, "all", "all");
const gateMet = scored.length >= CALIBRATION_MIN_RESOLVED && cutoffs.length >= CALIBRATION_MIN_CUTOFFS;

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 Require resolved evidence across eight weekly cutoffs

When seven weekly snapshots contain only unavailable forecasts (p50: null) and the eighth contains 30 forecasts that later resolve with 80% P80 coverage, this gate returns calibrated: cutoffs includes every stored snapshot, although all scored evidence comes from a single weekly origin. This bypasses the documented minimum of 30 resolved forecasts across eight weekly cutoffs. Derive the gate's cutoff count—and the corresponding eligibility check above—from weekly cutoffs contributing scored forecasts rather than all captured snapshots.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5cb77a4 (task 17228, lane any-c). The gate now derives its cutoff count from weekly cutoffs contributing scored forecasts (scoredCutoffs), and the per-window eligibility check uses the scored-cutoff count accumulated so far; calibration.distinctCutoffs reports the scored count. Snapshots whose forecasts are all unavailable (p50 null) no longer count toward the eight-cutoff minimum. Regression test: "calibration gate counts only cutoffs contributing scored forecasts" reproduces your scenario — seven unavailable-only snapshots plus one snapshot with 30 forecasts resolving at 80% P80 coverage — and asserts distinctCutoffs is 1 and the state stays not_yet_calibrated. bun test test/backtest.test.ts passes 13/13.

@dezren39

Copy link
Copy Markdown
Member Author

Agent note — task 17228 picked up (lane any-c)

  • state: claimed
  • Task 17228 (pr_shepherd) claimed by lane any-c; execution-lane assignment: direct.
  • Revalidating PR feat(aggregator): forecast backtest + calibration report (#3986) #8436 fresh: still open, head queue/14816-3986-forecast-backtest @ 40e0a9e, no labels (no hard stops); not landed on main; issue aggregator: backtest forecasting models and report calibration #3986 still OPEN.
  • Four Codex P2 findings to disposition (comments 4533268095, 4533268099, 4533268104, 4533268112): snapshot CLI must read the API's contracts field and select epic-completion contracts; exclude subjects already complete at forecast origin from scoring; compute model/baseline median errors over the same (paired) subjects; calibration gate must count weekly cutoffs contributing scored forecasts.
  • Next: rebase, fix each finding with tests, run the aggregator suite, then merge per task 17228 acceptance.

@dezren39 dezren39 added queue/claimed Queue worker lifecycle state work/assigned Queue worker lifecycle state status/in-progress Queue worker lifecycle state labels Nov 14, 2026
repo-worker-code-k added 2 commits November 14, 2026 14:49
#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.
@dezren39
dezren39 force-pushed the queue/14816-3986-forecast-backtest branch from 40e0a9e to 5cb77a4 Compare November 14, 2026 21:03
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@dezren39
dezren39 merged commit 18692d0 into main Nov 14, 2026
2 checks passed
@dezren39
dezren39 deleted the queue/14816-3986-forecast-backtest branch November 14, 2026 21:05
@dezren39

Copy link
Copy Markdown
Member Author

Agent note — task 17228 done: fixed_merged (lane any-c)

  • PR feat(aggregator): forecast backtest + calibration report (#3986) #8436 MERGED at 2026-11-14T21:05:06Z, merge commit 18692d0. Issue aggregator: backtest forecasting models and report calibration #3986 CLOSED by the merge.
  • All four Codex P2 findings fixed in 5cb77a4 and dispositioned on their threads (replies 4575640680, 4575640966, 4575641188, 4575641315): snapshot CLI accepts the real /api/forecasts.json contracts shape and selects epic-completion contracts at the CLI boundary; scoring excludes subjects already complete at the forecast origin (new excludedAlreadyComplete count); worse-than-baseline windows compare paired subjects only; the calibration gate counts cutoffs contributing scored forecasts.
  • Tests: bun test test/backtest.test.ts — 13/13 pass, including one new regression test per finding. Full aggregator suite on this branch: 43 failures vs 44 on a clean-main baseline run the same hour (2352 tests), none in the touched area — pre-existing/environmental. Branch was rebased onto current main before the fix commit; merge state CLEAN/MERGEABLE immediately before merging.

@dezren39 dezren39 removed status/in-progress Queue worker lifecycle state queue/claimed Queue worker lifecycle state work/assigned Queue worker lifecycle state labels Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

aggregator: backtest forecasting models and report calibration

1 participant