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
128 changes: 97 additions & 31 deletions pm-stack/aggregator/src/forecast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@
// observed weeks in scope. Below that, the result is either a
// clearly named borrowed baseline (low confidence) or
// "not_enough_history" with NO dates — never an invented date.
//
// - The estimator (design §1) resamples the complete weekly
// completion buckets — zero weeks included — with replacement
// under a seeded PRNG, estimating the distribution of
// weeks-to-complete for the remaining units; P50 and the
// conservative P80 are percentiles of that distribution. The seed
// derives from the buckets and the remaining-unit count, so the
// same inputs always produce the same forecast. A scope whose
// total observed pace is zero still returns "no_measurable_pace":
// resampling zero buckets can only ever draw zero.
// - Effort stays explicit: remaining work is reported per effort
// label, unsized work is counted as unsized, and `l` (an open-ended
// floor in weights.ts) is flagged open-ended. No size is inferred.
Expand All @@ -31,7 +41,12 @@ import type { ItemHistoryCutoff } from "./item-history.ts";
import { blockerFirstObserved, weeklyTransitions } from "./item-history.ts";
import type { RefKey } from "./model.ts";

export const FORECAST_MODEL_VERSION = "forecast/v1";
// forecast/v2 (#5274): the ETA pace derivation is the design §1
// resampling estimator, replacing v1's median/lower-quartile pace.
// Outputs for the same inputs change materially (bursty scopes with
// a zero median bucket now forecast instead of returning
// no_measurable_pace), so the model version bumps.
export const FORECAST_MODEL_VERSION = "forecast/v2";
export const STALL_MODEL_VERSION = "stall-risk/v1";

/** At/above this score an item is surfaced as "at risk" (§3). */
Expand Down Expand Up @@ -70,26 +85,79 @@ function addDays(iso: string, days: number): string {
return new Date(Date.parse(iso) + days * DAY_MS).toISOString();
}

/** ETA date for a remaining-unit count at a weekly pace, or null when
* the horizon is not representable as a Date (an absurdly small pace
/** ETA date a whole number of weeks after `asOf`, or null when the
* horizon is not representable as a Date (an absurdly distant horizon
* would otherwise make toISOString throw a RangeError). */
function etaDate(asOf: string, remainingUnits: number, pacePerWeek: number): string | null {
const weeks = Math.ceil(remainingUnits / pacePerWeek);
function etaDateForWeeks(asOf: string, weeks: number): string | null {
const ms = Date.parse(asOf) + weeks * 7 * DAY_MS;
if (!Number.isFinite(ms) || Math.abs(ms) > 8.64e15) return null;
return addDays(asOf, weeks * 7);
}

function median(xs: number[]): number {
const s = [...xs].sort((a, b) => a - b);
const mid = Math.floor(s.length / 2);
return s.length % 2 === 1 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2;
/** mulberry32: a small seeded PRNG. The estimator's seed derives
* from its inputs, so resampling is a pure function of them — the
* same buckets and remaining-unit count always yield the same
* distribution, and therefore the same P50/P80 (determinism is part
* of this module's contract, asserted by the forecast tests). */
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}

/** FNV-1a hash of the estimator inputs, used as the resampling seed. */
function estimatorSeed(buckets: number[], remainingUnits: number): number {
const text = `${buckets.join(",")}|${remainingUnits}`;
let h = 0x811c9dc5;
for (let i = 0; i < text.length; i++) {
h ^= text.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return h >>> 0;
}

const RESAMPLE_TRIALS = 4096;
/** Per-trial week cap: with any positive bucket a trial finishes
* almost surely long before this; the cap only bounds pathological
* inputs (a huge remaining count over near-zero pace) so the pure
* function always terminates. A capped trial reads as that many
* weeks, which is conservative for both percentiles. */
const RESAMPLE_MAX_WEEKS = 100_000;

/**
* The design §1 resampling estimator: draw complete weekly
* completion buckets (zero weeks included — they are observations,
* not gaps) with replacement until the drawn completions cover the
* remaining units; the number of drawn weeks is one sample of the
* weeks-to-complete distribution. Returns the sorted samples.
* Precondition: the buckets' total is positive (the caller returns
* no_measurable_pace otherwise — resampling all-zero buckets can
* only draw zero and no trial would ever finish).
*/
function resampledWeeksToComplete(buckets: number[], remainingUnits: number): number[] {
const rng = mulberry32(estimatorSeed(buckets, remainingUnits));
const samples: number[] = [];
for (let trial = 0; trial < RESAMPLE_TRIALS; trial++) {
let completed = 0;
let weeks = 0;
while (completed < remainingUnits && weeks < RESAMPLE_MAX_WEEKS) {
completed += buckets[Math.floor(rng() * buckets.length)]!;
weeks++;
}
samples.push(weeks);

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 Keep unfinished trials out of completion-time quantiles

When remaining work cannot finish within the 100,000-week cap, this records unfinished trials as actual completions, making the forecast optimistic rather than conservative. For example, buckets [1, 1, 1, 1] with 100,001 remaining units yield P50 and P80 at 100,000 weeks even though completion takes exactly 100,001 weeks. Preserve capped trials as censored observations and return an unavailable date with a limitation when the requested percentile exceeds the simulation horizon, rather than publishing a completion date before the work finishes.

Useful? React with 👍 / 👎.

}
return samples.sort((a, b) => a - b);
}

/** Lower quartile — the conservative (slower) pace behind the P80. */
function lowerQuartile(xs: number[]): number {
const s = [...xs].sort((a, b) => a - b);
return s[Math.floor((s.length - 1) / 4)]!;
/** Nearest-rank percentile of an ascending-sorted sample. */
function percentile(sortedXs: number[], q: number): number {
const idx = Math.min(sortedXs.length - 1, Math.max(0, Math.ceil(q * sortedXs.length) - 1));
return sortedXs[idx]!;
}

export type ForecastConfidence = "high" | "medium" | "low" | "unavailable";
Expand Down Expand Up @@ -334,31 +402,29 @@ export function deriveEpicEta(input: EpicEtaInput): EpicEta {
return result;
}

const paceP50 = median(paceSeries);
if (paceP50 <= 0) {
const totalPace = paceSeries.reduce((a, b) => a + b, 0);
if (totalPace <= 0) {
// A truly zero total pace is "no measurable pace" (§1), exactly
// as before: resampling all-zero buckets can only draw zero, so
// no trial would ever cover the remaining units. A zero MEDIAN
// with positive total pace (bursty buckets like [0, 0, 0, 4]) is
// different — the resampling estimator below forecasts it,
// where v1's median pace returned no_measurable_pace (#5274).
result.status = "no_measurable_pace";
limitations.push("observed weekly pace is zero in the primary window; no date is returned");
return result;
}
const paceP80 = lowerQuartile(paceSeries);
// Whole weeks, rounded up: a partial week is not a completion date.
result.p50 = etaDate(asOf, remainingUnits, paceP50);
// Whole weeks only: a partial week is not a completion date. P50 is
// the median weeks-to-complete; P80 is the conservative (slower)
// tail of the same distribution, so P50 <= P80 by construction.
const weeksToComplete = resampledWeeksToComplete(paceSeries, remainingUnits);
result.p50 = etaDateForWeeks(asOf, percentile(weeksToComplete, 0.5));
if (result.p50 === null) {
limitations.push("P50 horizon exceeds the representable date range; no P50 date is returned");
}
if (paceP80 <= 0) {
// An unmeasurable conservative pace is stated, not converted into
// a finite denominator: a zero lower-quartile pace (a single
// observed zero-completion week can produce one) makes any P80
// date indefensible \u2014 an EPSILON pace overflows the Date range
// and throws.
result.p80 = null;
limitations.push("conservative (lower-quartile) weekly pace is zero in the pace window; no P80 date is defensible");
} else {
result.p80 = etaDate(asOf, remainingUnits, paceP80);
if (result.p80 === null) {
limitations.push("P80 horizon exceeds the representable date range; no P80 date is returned");
}
result.p80 = etaDateForWeeks(asOf, percentile(weeksToComplete, 0.8));
if (result.p80 === null) {
limitations.push("P80 horizon exceeds the representable date range; no P80 date is returned");
}

if (result.status === "forecast") {
Expand Down
190 changes: 187 additions & 3 deletions pm-stack/aggregator/test/forecast-3982.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,80 @@ function history(total: number, closesAtWeek: (number | null)[]): ItemHistoryCut
);
}


// --- Generated model-based coverage for the design \u00a71 resampling
// estimator (Codex P1 on PR #6169; testing doctrine: PBT/MBT with a
// named oracle). The fixed examples alone cannot detect a wrong
// resampling or percentile calculation (any deterministic ordered
// pair of dates passes them), so the estimator is also checked
// against an exact reference model over generated inputs.
//
// ORACLE (named): the exact completion-time distribution of the
// design \u00a71 model, computed by dynamic programming \u2014 each week
// independently draws one observed bucket uniformly with replacement,
// so the distribution of cumulative completions after w weeks is an
// exact convolution, and the completion-time quantile is the
// smallest w whose exact CDF reaches q. The oracle shares no code
// with the estimator's PRNG, sampling, or percentile code, so it
// decides the expected quantiles independently.
//
// SAMPLING TOLERANCE (explicit): the estimator reports nearest-rank
// quantiles of 4096 resampled trials, so its weeks can differ from
// the exact oracle by sampling error. Calibration over the generated
// range below (buckets 0..4, remaining 1..10) showed a maximum
// deviation of 1 week across 294 forecast cases; the tolerance is 2
// weeks \u2014 twice the observed maximum, and far smaller than the
// error a swapped percentile, a wrong bucket series, or a constant
// date would produce (the constant-bucket cases below are exact,
// tolerance zero).
const SAMPLING_TOLERANCE_WEEKS = 2;

function exactWeeksQuantile(buckets: number[], remaining: number, q: number): number {
let dist = new Map<number, number>([[0, 1]]);
for (let w = 1; w <= 100_000; w++) {
const next = new Map<number, number>();
for (const [sum, p] of dist) {
for (const b of buckets) {
const s = Math.min(remaining, sum + b);
next.set(s, (next.get(s) ?? 0) + p / buckets.length);
}
}
dist = next;
if ((dist.get(remaining) ?? 0) >= q) return w;
}
throw new Error("oracle did not converge");
}

/** Realize primary buckets b[0..3] as closures at weeks 1..4 plus
* `remaining` children that never close, over the first 5 cutoffs. */
function historyForBuckets(buckets: number[], remaining: number): ItemHistoryCutoff[] {
const closes: (number | null)[] = [];
buckets.forEach((count, i) => {
for (let k = 0; k < count; k++) closes.push(i + 1);
});
for (let k = 0; k < remaining; k++) closes.push(null);
return history(closes.length, closes).slice(0, 5);
}

function etaWeeks(eta: { p50: string | null; p80: string | null; asOf: string }): { p50: number; p80: number } {
const toWeeks = (d: string | null) => Math.round((Date.parse(d!) - Date.parse(eta.asOf)) / (7 * 24 * 3600 * 1000));
return { p50: toWeeks(eta.p50), p80: toWeeks(eta.p80) };
}

/** Deterministic case generator (fixed seed: the suite is a
* regression pin, not a fuzz run). */
function generatedEstimatorCases(count: number): { buckets: number[]; remaining: number }[] {
let s = 0x5eed_5274;
const rnd = () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 4294967296;
};
return Array.from({ length: count }, () => ({
buckets: Array.from({ length: 4 }, () => Math.floor(rnd() * 5)),
remaining: 1 + Math.floor(rnd() * 10),
}));
}

describe("deriveEpicEta", () => {
test("missing history: not_enough_history, no dates, unavailable confidence", () => {
const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs: [] });
Expand Down Expand Up @@ -168,17 +242,127 @@ describe("deriveEpicEta", () => {
expect(eta.remainingUnits).toBe(2);
});

test("zero lower-quartile pace: P50 present, P80 explicitly unmeasurable, no crash", () => {
// Primary weeks [0, 1, 1, 1]: median pace 1, lower quartile 0.
test("zero lower-quartile pace, re-pinned for the resampling estimator (#5274): P50 and P80 both present", () => {
// Primary weeks [0, 1, 1, 1]. Under forecast/v1 the median pace
// was 1 and the lower-quartile pace 0, so P80 was explicitly
// unmeasurable (the previous pin). The design \u00a71 resampling
// estimator (forecast/v2) draws the observed buckets themselves:
// a zero week is a draw, not a denominator, so the
// weeks-to-complete distribution has a finite conservative tail
// and P80 is defensible. This pin replaces the v1 pin with that
// rationale, per #5274's acceptance criteria.
const eta = deriveEpicEta({
subjectRef: EPIC,
cutoffs: history(5, [2, 3, 4, null, null]).slice(0, 5),
});
expect(eta.status).toBe("forecast");
expect(eta.sample.completionsPrimary).toBe(3);
expect(eta.p50).not.toBeNull();
expect(eta.p80).not.toBeNull();
expect(eta.p80! >= eta.p50!).toBe(true);
expect(eta.limitations.join(" ")).not.toContain("lower-quartile");
});

test("bursty zero-median buckets [0, 0, 0, 4]: forecast with finite P50 <= P80, not no_measurable_pace (#5274)", () => {
// 4 children close in the last observed week; 4 remain. The
// median bucket is 0, so forecast/v1 returned
// no_measurable_pace despite 4 completions of evidence; the
// resampling estimator forecasts from the bucket distribution.
const closes: (number | null)[] = [4, 4, 4, 4, null, null, null, null];
const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs: history(8, closes).slice(0, 5) });
expect(eta.status).toBe("forecast");
expect(eta.sample.completionsPrimary).toBe(4);
expect(eta.remainingUnits).toBe(4);
expect(eta.p50).not.toBeNull();
expect(eta.p80).not.toBeNull();
expect(Number.isFinite(Date.parse(eta.p50!))).toBe(true);
expect(Number.isFinite(Date.parse(eta.p80!))).toBe(true);
expect(eta.p80! >= eta.p50!).toBe(true);
Comment on lines +276 to +280

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add generated, model-backed coverage for the estimator

The new estimator is covered only by fixed examples asserting finite, ordered dates and repeatability; these tests would also pass if both percentiles were replaced with the same arbitrary deterministic date. The repository's testing doctrine requires generated property/model-based coverage where invariants and a design model exist, rather than example-only coverage. Add generated bucket/remaining-work cases with a named reference oracle for completion-time quantiles (and an explicit sampling tolerance), alongside determinism and P50 ≤ P80 properties, so incorrect resampling or percentile calculations are detected.

AGENTS.md reference: AGENTS.md:L41-L45

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 2c2a5e9 (this PR). Added generated, model-backed coverage to forecast-3982.test.ts:

  • Named oracle: the exact completion-time distribution of the design §1 model, computed by dynamic programming (each week independently draws one observed bucket uniformly with replacement; completion-time quantile = smallest w whose exact CDF reaches q). It shares no code with the estimator's PRNG, sampling, or percentile code.
  • Generated cases: 240 generated bucket/remaining-work cases (buckets 0–4, remaining 1–10, fixed seed) assert status routing (zero pace → no_measurable_pace, sparse → not_enough_history), finite dates, P50 ≤ P80, and |estimator − oracle| within tolerance for both quantiles; a guard asserts >150 cases actually exercise the forecast path.
  • Explicit sampling tolerance: 2 weeks, stated in the test with its calibration (max observed deviation 1 week across 294 forecast cases at 4096 trials). Constant-bucket generated cases are exact at tolerance zero (every resample draws the same pace, so P50 = P80 = ceil(remaining/c)), which catches swapped percentiles deterministically.
  • Determinism property: generated inputs re-derived produce identical outputs.

Tests: forecast-3982.test.ts 31 pass on laptop (bun test), 1883 expect() calls.

});

test("resampling estimator is deterministic: identical inputs produce identical outputs (#5274)", () => {
const closes: (number | null)[] = [4, 4, 4, 4, null, null, null, null];
const cutoffs = history(8, closes).slice(0, 5);
const a = deriveEpicEta({ subjectRef: EPIC, cutoffs });
const b = deriveEpicEta({ subjectRef: EPIC, cutoffs });
expect(b).toEqual(a);
});


test("generated cases match the exact DP oracle within the stated sampling tolerance (MBT, #5274 / PR #6169 Codex P1)", () => {
let forecastCases = 0;
for (const { buckets, remaining } of generatedEstimatorCases(240)) {
const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs: historyForBuckets(buckets, remaining) });
const total = buckets.reduce((a, b) => a + b, 0);
if (total === 0) {
expect(eta.status).toBe("no_measurable_pace");
expect(eta.p50).toBeNull();
expect(eta.p80).toBeNull();
continue;
}
if (total < 3) {
expect(eta.status).toBe("not_enough_history");
expect(eta.p50).toBeNull();
expect(eta.p80).toBeNull();
continue;
}
forecastCases++;
expect(eta.status).toBe("forecast");
expect(eta.p50).not.toBeNull();
expect(eta.p80).not.toBeNull();
const w = etaWeeks(eta);
expect(w.p50).toBeGreaterThanOrEqual(1);
expect(w.p80).toBeGreaterThanOrEqual(w.p50);
expect(Math.abs(w.p50 - exactWeeksQuantile(buckets, remaining, 0.5))).toBeLessThanOrEqual(
SAMPLING_TOLERANCE_WEEKS,
);
expect(Math.abs(w.p80 - exactWeeksQuantile(buckets, remaining, 0.8))).toBeLessThanOrEqual(
SAMPLING_TOLERANCE_WEEKS,
);
}
// Guard the generator itself: most generated cases must exercise
// the forecast path, or the oracle comparison above is vacuous.
expect(forecastCases).toBeGreaterThan(150);
});

test("generated cases are deterministic: identical generated inputs produce identical outputs (PBT, #5274)", () => {
generatedEstimatorCases(240).forEach(({ buckets, remaining }, i) => {
if (i % 10 !== 0) return;
const cutoffs = historyForBuckets(buckets, remaining);
expect(deriveEpicEta({ subjectRef: EPIC, cutoffs })).toEqual(deriveEpicEta({ subjectRef: EPIC, cutoffs }));
});
});

test("constant buckets are exact (tolerance zero): every resample draws the same pace (MBT, #5274)", () => {
for (const c of [1, 2, 3, 4]) {
for (const remaining of [1, 2, 5, 9, 12]) {
const buckets = [c, c, c, c];
const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs: historyForBuckets(buckets, remaining) });
expect(eta.status).toBe("forecast");
const exact = Math.ceil(remaining / c);
expect(exactWeeksQuantile(buckets, remaining, 0.5)).toBe(exact);
expect(exactWeeksQuantile(buckets, remaining, 0.8)).toBe(exact);
const w = etaWeeks(eta);
expect(w.p50).toBe(exact);
expect(w.p80).toBe(exact);
}
}
});

test("all-zero borrowed baseline buckets: still no_measurable_pace, no dates (#5274)", () => {
// Local evidence is below the floor (1 completion in the primary
// window) and the borrowed baseline's buckets are all zero: the
// total observed pace is zero, and resampling zero buckets can
// only draw zero \u2014 no date is defensible.
const closes: (number | null)[] = [3, null, null, null, null, null];
const eta = deriveEpicEta({
subjectRef: EPIC,
cutoffs: history(6, closes).slice(0, 6),
borrowedBaseline: { scopeRef: `${REPO}#200`, weeklyCompletions: [0, 0, 0, 0] },
});
expect(eta.status).toBe("no_measurable_pace");
expect(eta.p50).toBeNull();
expect(eta.p80).toBeNull();
expect(eta.limitations.join(" ")).toContain("lower-quartile");
});

test("inferred scope counts direct children only, not grandchildren via epicRef", () => {
Expand Down