From 3cf80bfb3862ebd8aa2908f33352db4de5aa6d4d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 05:34:11 -0500 Subject: [PATCH] =?UTF-8?q?feat(aggregator):=20validate.ts=20ingest=20prim?= =?UTF-8?q?itives=20+=20contract=20+=20probe=20matrix=20=E2=80=94=20#2576?= =?UTF-8?q?=20Phase=201=20(#2577)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pm-stack/aggregator/README.md | 35 +++ pm-stack/aggregator/src/feed.ts | 7 +- pm-stack/aggregator/src/validate.ts | 164 ++++++++++++++ pm-stack/aggregator/test/validate.test.ts | 262 ++++++++++++++++++++++ 4 files changed, 466 insertions(+), 2 deletions(-) create mode 100644 pm-stack/aggregator/src/validate.ts create mode 100644 pm-stack/aggregator/test/validate.test.ts diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index 0ca0c022ce..6b3e38c8c9 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -286,6 +286,41 @@ the sessions that worked them. The OpenCode tool in Both render in the board cards (execution strip) and the item drill-down. +## Ingest contract — validate once at the boundary (#2576) + +Every document this aggregator ingests — fleet feed files, quota +exports, snapshot history, session lists, billing and provider +exports — is validated **once, at its ingest boundary**, before any +consumer, store append, or render sees it. Validation covers shape, +element types, value ranges, and real calendar dates. The shared +primitives live in `src/validate.ts` (no new dependency); boundaries +compose them instead of re-deriving checks privately. + +A validation failure produces exactly one of three sanctioned +outcomes, chosen per boundary and recorded in its guard: + +- **Reject and retain** — the document/section/entry is refused; the + previously retained value stays and ages. +- **Drop the element, count it** — where elements are independent, + the malformed element alone is dropped and the drop is counted + somewhere visible, never silently and never at the cost of its + siblings. +- **Refuse the append** — a snapshot record that fails validation is + not appended; the append reports the refusal. A record the store + cannot read back is a record it must not accept. + +Three outcomes are forbidden everywhere: throwing across the +boundary and discarding valid siblings; fabricating rows, ids, or +zeros from malformed input; and publishing an out-of-range value as +live measured data. A genuine zero is a successful validation whose +value is 0 — an unparseable value never becomes a zero. + +The contract's existing embodiment is `src/token-adapter.ts` +(#1153): fail-closed parsing, a drifted payload raises +`AdapterError("unparseable")`, the previous value is retained and +ages, and an expired session is its own signal, never zero usage. +The probe matrix for the primitives is `test/validate.test.ts`. + ## Run it ```bash diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 5727e44ace..5d15e664d5 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -7,6 +7,7 @@ import { readFile } from "node:fs/promises"; import type { UnmatchedCharge } from "./charges-match.ts"; import type { CheckoutDrift } from "./checkout-drift.ts"; import { isProjectPoolItem } from "./projects.ts"; +import { isIsoDate } from "./validate.ts"; import type { AaFeedSection, ChargeRow, @@ -251,8 +252,10 @@ export function isFleetFeed(v: unknown): v is FleetFeed { const f = v as Partial; return ( f.version === 1 && - typeof f.generatedAt === "string" && - Number.isFinite(Date.parse(f.generatedAt)) && + // #2576 Phase 1 proof consumer: the strict date primitive, so an + // impossible generatedAt (2026-02-30, 2026-13-01) is rejected + // instead of rolling over via Date.parse. + isIsoDate(f.generatedAt) && typeof f.quota === "object" && f.quota !== null && Array.isArray((f.quota as QuotaView).pools) && diff --git a/pm-stack/aggregator/src/validate.ts b/pm-stack/aggregator/src/validate.ts new file mode 100644 index 0000000000..e60a236a10 --- /dev/null +++ b/pm-stack/aggregator/src/validate.ts @@ -0,0 +1,164 @@ +// validate.ts — the shared ingest validation primitives (#2576 Phase 1, +// design: code-aggregator-ingest-contract.md). +// +// Every document the aggregator ingests is validated once, at its +// ingest boundary, before any consumer, store append, or render sees +// it. This module is the one place those checks live, so boundaries +// stop re-deriving them privately and disagreeing. It has no +// dependencies beyond the language. +// +// The contract these primitives serve (README, "Ingest contract"): +// a validation failure produces exactly one of three sanctioned +// outcomes — reject-and-retain, drop-the-element-and-count, or +// refuse-the-append — and never one of the three forbidden ones: +// throwing away valid siblings, fabricating rows/ids/zeros, or +// publishing an out-of-range value as live data. A genuine zero is a +// successful validation whose value is 0 (#1153's wording): nothing +// here treats 0 as missing. + +/** A plain object (not null, not an array) — the shape every ingested + * document and element is expected to have before its fields are read. */ +export function isRecord(v: unknown): v is Record { + return typeof v === "object" && v !== null && !Array.isArray(v); +} + +/** A string with at least one character — ids, names, keys. */ +export function isNonEmptyString(v: unknown): v is string { + return typeof v === "string" && v.length > 0; +} + +/** An array whose every element is a string. */ +export function isStringArray(v: unknown): v is string[] { + return Array.isArray(v) && v.every((e) => typeof e === "string"); +} + +/** A real number: finite, not NaN — the check `Number.isFinite` sites + * used to re-derive privately (27 scattered call sites at design time). */ +export function isFiniteNumber(v: unknown): v is number { + return typeof v === "number" && Number.isFinite(v); +} + +/** A finite number that is >= 0. Counts and amounts: a negative is + * malformed input, never live data (#2553). Zero passes — a genuine + * zero is a measurement, not an absence. */ +export function isNonNegative(v: unknown): v is number { + return isFiniteNumber(v) && v >= 0; +} + +/** A percent of the limit the document itself carries: finite, >= 0, + * and <= limit (the #2571 `limit: 100` case — a window at -20% or 1e9% + * is malformed, not a measurement). Curried so a boundary builds the + * guard for its document's limit once. */ +export function isPercentOf(limit: number): (v: unknown) => boolean { + return (v: unknown) => isFiniteNumber(v) && v >= 0 && v <= limit; +} + +const ISO_DATE_RE = + /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(?:([Zz])|([+-])(\d{2}):?(\d{2}))?)?$/; + +function daysInMonth(year: number, month: number): number { + // month is 1-based here; day 0 of the next month is this month's last. + return new Date(Date.UTC(year, month, 0)).getUTCDate(); +} + +/** Parse an ISO-8601 date or timestamp into a Date, or return null. + * + * Strict where `Date.parse` is not: components are extracted and + * re-checked against the real calendar, so impossible dates — + * 2026-02-30, 2026-13-01 — fail instead of rolling over into a + * phantom March date (#2264's defect shape). A missing timezone on a + * timestamp is read as UTC, matching how the fleet's producers stamp + * `generatedAt`. Non-strings, non-ISO shapes, and out-of-range time + * components all return null. */ +export function parseIsoDate(v: unknown): Date | null { + if (typeof v !== "string") return null; + const m = ISO_DATE_RE.exec(v.trim()); + if (!m) return null; + const year = Number(m[1]); + const month = Number(m[2]); + const day = Number(m[3]); + if (month < 1 || month > 12) return null; + if (day < 1 || day > daysInMonth(year, month)) return null; + const hour = m[4] === undefined ? 0 : Number(m[4]); + const minute = m[5] === undefined ? 0 : Number(m[5]); + const second = m[6] === undefined ? 0 : Number(m[6]); + if (hour > 23 || minute > 59 || second > 59) return null; + const ms = m[7] === undefined ? 0 : Number((m[7] + "000").slice(0, 3)); + let t = Date.UTC(year, month - 1, day, hour, minute, second, ms); + if (m[9] !== undefined) { + // An explicit ±hh:mm offset: shift the wall-clock components to UTC. + const offH = Number(m[10]); + const offM = Number(m[11]); + if (offH > 23 || offM > 59) return null; + const off = (offH * 60 + offM) * 60_000; + t += m[9] === "+" ? -off : off; + } + const d = new Date(t); + // Belt and braces: the constructed date's UTC components (before any + // offset shift, which the regex-bounded components already make + // safe) must be the components that were asked for. + if (m[9] === undefined) { + if ( + d.getUTCFullYear() !== year || + d.getUTCMonth() !== month - 1 || + d.getUTCDate() !== day || + d.getUTCHours() !== hour || + d.getUTCMinutes() !== minute || + d.getUTCSeconds() !== second + ) { + return null; + } + } + return d; +} + +/** A string holding a real calendar date (see parseIsoDate). */ +export function isIsoDate(v: unknown): v is string { + return parseIsoDate(v) !== null; +} + +/** The default future-skew bound for generatedAt-style stamps: + * five minutes. */ +export const DEFAULT_FUTURE_SKEW_MS = 5 * 60_000; + +/** A timestamp that is a real date and not implausibly in the future: + * a `generatedAt` more than the skew bound ahead of now is not + * "maximally fresh", it is invalid (#2242's defect shape). Curried so + * a boundary can pin its own bound; `now` is injectable for tests. */ +export function isTimestampNotFuture( + boundMs: number = DEFAULT_FUTURE_SKEW_MS, +): (v: unknown, now?: Date) => boolean { + return (v: unknown, now: Date = new Date()) => { + const d = parseIsoDate(v); + return d !== null && d.getTime() <= now.getTime() + boundMs; + }; +} + +/** The result of validating a container's elements: the values that + * passed the guard, and how many were dropped. The count is part of + * the result so the drop is visible, never silent (the contract's + * "drop the element, count it" outcome). */ +export interface ArrayOfResult { + values: T[]; + dropped: number; +} + +/** Validate a container with an element guard: returns the passing + * elements and the drop count, or null when the container itself is + * not an array (that is the caller's reject decision, not an empty + * list — a string `items` must not fabricate an empty session list, + * #2531). */ +export function arrayOf( + guard: (v: unknown) => v is T, +): (v: unknown) => ArrayOfResult | null { + return (v: unknown) => { + if (!Array.isArray(v)) return null; + const values: T[] = []; + let dropped = 0; + for (const e of v) { + if (guard(e)) values.push(e); + else dropped++; + } + return { values, dropped }; + }; +} diff --git a/pm-stack/aggregator/test/validate.test.ts b/pm-stack/aggregator/test/validate.test.ts new file mode 100644 index 0000000000..fb7a47353f --- /dev/null +++ b/pm-stack/aggregator/test/validate.test.ts @@ -0,0 +1,262 @@ +// #2576 Phase 1: the malformed-input probe matrix for src/validate.ts — +// one table per primitive. The must-pass rows are the real shapes the +// fleet's producers emit (fixture shapes from src/sources/fixtures.ts); +// the must-fail rows are the defect shapes the validation family of +// issues kept re-filing: impossible dates, non-finite numbers, +// negative counts, over-limit percents, and null/string/array element +// confusion. +import { describe, expect, test } from "bun:test"; +import { isFleetFeed } from "../src/feed.ts"; +import { FIXTURE_DNS } from "../src/sources/fixtures.ts"; +import { + arrayOf, + isFiniteNumber, + isIsoDate, + isNonEmptyString, + isNonNegative, + isPercentOf, + isRecord, + isStringArray, + isTimestampNotFuture, + parseIsoDate, +} from "../src/validate.ts"; + +describe("isRecord", () => { + const cases: Array<[unknown, boolean]> = [ + [{}, true], + [{ a: 1 }, true], + [null, false], + [[], false], + [["a"], false], + ["{}", false], + [42, false], + [undefined, false], + ]; + for (const [v, want] of cases) { + test(`${JSON.stringify(v)} -> ${want}`, () => { + expect(isRecord(v)).toBe(want); + }); + } +}); + +describe("isNonEmptyString", () => { + const cases: Array<[unknown, boolean]> = [ + ["demo", true], + ["0", true], + ["", false], + [null, false], + [0, false], + [["x"], false], + [{}, false], + ]; + for (const [v, want] of cases) { + test(`${JSON.stringify(v)} -> ${want}`, () => { + expect(isNonEmptyString(v)).toBe(want); + }); + } +}); + +describe("isStringArray", () => { + const cases: Array<[unknown, boolean]> = [ + [[], true], + [["a", "b"], true], + [["a", 1], false], + [["a", null], false], + ["a,b", false], + [null, false], + [{ 0: "a" }, false], + ]; + for (const [v, want] of cases) { + test(`${JSON.stringify(v)} -> ${want}`, () => { + expect(isStringArray(v)).toBe(want); + }); + } +}); + +describe("isFiniteNumber / isNonNegative", () => { + const finite: Array<[unknown, boolean]> = [ + [0, true], // a genuine 0 is a measurement (#1153) + [-0, true], + [3.14, true], + [-7, true], + [Number.MAX_SAFE_INTEGER, true], + [NaN, false], + [Infinity, false], + [-Infinity, false], + ["42", false], + [null, false], + [undefined, false], + ]; + for (const [v, want] of finite) { + test(`isFiniteNumber(${String(v)}) -> ${want}`, () => { + expect(isFiniteNumber(v)).toBe(want); + }); + } + const nonNeg: Array<[unknown, boolean]> = [ + [0, true], // zero passes as zero + [0.5, true], + [1e9, true], + [-1, false], // negative counts are malformed, not live data + [-0.01, false], + [NaN, false], + [Infinity, false], + ["3", false], + ]; + for (const [v, want] of nonNeg) { + test(`isNonNegative(${String(v)}) -> ${want}`, () => { + expect(isNonNegative(v)).toBe(want); + }); + } +}); + +describe("isPercentOf(limit)", () => { + const pct100 = isPercentOf(100); + const cases: Array<[unknown, boolean]> = [ + [0, true], + [42.5, true], + [100, true], + [100.01, false], + [1e9, false], // #2571: an over-limit window is malformed + [-20, false], // #2571: so is a negative one + [NaN, false], + [Infinity, false], + ["50", false], + [null, false], + ]; + for (const [v, want] of cases) { + test(`isPercentOf(100)(${String(v)}) -> ${want}`, () => { + expect(pct100(v)).toBe(want); + }); + } + test("the limit is the document's own, not a constant", () => { + expect(isPercentOf(1000)(999)).toBe(true); + expect(isPercentOf(1000)(1001)).toBe(false); + }); +}); + +describe("parseIsoDate / isIsoDate — real calendar dates only", () => { + const valid = [ + "2026-02-28", + "2024-02-29", // leap day, real in 2024 + "2026-10-25T17:00:00Z", // FIXTURE_DNS generatedAt shape + "2026-10-26T18:05:00Z", + "2026-01-01T00:00:00.500Z", + "2026-06-15T12:30:00+02:00", + "2026-06-15", + ]; + for (const s of valid) { + test(`accepts ${s}`, () => { + expect(isIsoDate(s)).toBe(true); + expect(parseIsoDate(s)).toBeInstanceOf(Date); + }); + } + const invalid: Array = [ + "2026-02-30", // Date.parse rolls this into March — we must not + "2026-02-29", // 2026 is not a leap year + "2026-13-01", // no thirteenth month + "2026-00-10", + "2026-04-31", // April has 30 days + "2026-01-01T25:00:00Z", // no 25th hour + "2026-01-01T00:61:00Z", + "2026-1-1", // shape alone is not ISO + "10/25/2026", + "2026-10-25T17:00:00Z trailing", + "", + "not a date", + null, + 1761435600000, // epoch numbers are not date strings + undefined, + {}, + ["2026-01-01"], + ]; + for (const s of invalid) { + test(`rejects ${JSON.stringify(s)}`, () => { + expect(isIsoDate(s)).toBe(false); + expect(parseIsoDate(s)).toBeNull(); + }); + } + test("parses the components it was given, in UTC", () => { + const d = parseIsoDate("2026-10-25T17:00:00Z"); + expect(d?.toISOString()).toBe("2026-10-25T17:00:00.000Z"); + }); + test("an explicit offset shifts to the matching UTC instant", () => { + const d = parseIsoDate("2026-06-15T12:30:00+02:00"); + expect(d?.toISOString()).toBe("2026-06-15T10:30:00.000Z"); + }); +}); + +describe("isTimestampNotFuture — the #2242 skew bound", () => { + const now = new Date("2026-10-31T10:00:00Z"); + const guard = isTimestampNotFuture(); // default 5-minute skew + const cases: Array<[unknown, boolean]> = [ + ["2026-10-31T09:00:00Z", true], + ["2026-10-31T10:04:59Z", true], // inside the skew + ["2026-10-31T10:05:01Z", false], // just past it + ["2027-01-01T00:00:00Z", false], // maximally "fresh" is invalid + ["2026-02-30T10:00:00Z", false], // impossible dates fail first + [null, false], + ]; + for (const [v, want] of cases) { + test(`${JSON.stringify(v)} -> ${want}`, () => { + expect(guard(v, now)).toBe(want); + }); + } + test("a boundary can pin its own bound", () => { + const strict = isTimestampNotFuture(0); + expect(strict("2026-10-31T10:00:01Z", now)).toBe(false); + expect(strict("2026-10-31T10:00:00Z", now)).toBe(true); + }); +}); + +describe("arrayOf — drop the element, count it", () => { + const strings = arrayOf(isNonEmptyString); + test("keeps good elements and counts the dropped ones", () => { + expect(strings(["a", "", null, "b", 42])).toEqual({ + values: ["a", "b"], + dropped: 3, + }); + }); + test("an all-good container drops zero", () => { + expect(strings(["a"])).toEqual({ values: ["a"], dropped: 0 }); + }); + test("an empty container is an empty result, not a failure", () => { + expect(strings([])).toEqual({ values: [], dropped: 0 }); + }); + test("a non-array container is null — never a fabricated empty list", () => { + expect(strings("a,b")).toBeNull(); + expect(strings(null)).toBeNull(); + expect(strings({ 0: "a", length: 1 })).toBeNull(); + }); + test("composes with the numeric guards", () => { + const counts = arrayOf(isNonNegative); + expect(counts([3, -1, 0, NaN, 7])).toEqual({ + values: [3, 0, 7], + dropped: 2, + }); + }); +}); + +describe("fixture shapes must pass (the over-strict-validation guard)", () => { + test("FIXTURE_DNS carries a real generatedAt and a finite total", () => { + expect(isIsoDate(FIXTURE_DNS.generatedAt)).toBe(true); + expect(isTimestampNotFuture()(FIXTURE_DNS.generatedAt, new Date("2026-10-25T17:04:00Z"))).toBe(true); + expect(isNonNegative(FIXTURE_DNS.totalAnnualListUsd)).toBe(true); + expect(isPercentOf(100)(42.5)).toBe(true); + }); +}); + +describe("isFleetFeed proof consumer — strict generatedAt (#2577)", () => { + const feed = (generatedAt: unknown) => ({ + version: 1, + generatedAt, + quota: { pools: [] }, + attention: [], + }); + test("accepts a real timestamp", () => { + expect(isFleetFeed(feed("2026-10-25T17:00:00Z"))).toBe(true); + }); + test("rejects the impossible dates Date.parse used to roll over", () => { + expect(isFleetFeed(feed("2026-02-30T00:00:00Z"))).toBe(false); + expect(isFleetFeed(feed("2026-13-01T00:00:00Z"))).toBe(false); + }); +});