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
1 change: 1 addition & 0 deletions pm-stack/aggregator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"test": "bun test",
"report:generate": "bun run scripts/generate-report.ts",
"backtest:quota-forecast": "bun run scripts/quota-forecast-backtest.ts",
"replay:quota-anomaly": "bun run scripts/quota-anomaly-replay.ts",
"contract:check": "bun run scripts/check-contract-corpus.ts",
"provenance:check": "bun run scripts/check-provenance-matrix.ts",
"typecheck": "bunx tsc --noEmit",
Expand Down
113 changes: 113 additions & 0 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,19 @@
// forecast product. SHADOW ONLY: no live path reads it; the
// live ordering is computed from the measured entries alone.
// Fail-soft on the same terms as the forecast.
// - quota-anomaly-state.json + quota-anomaly-history.jsonl beside
// quota-current.json — the Stage-3 anomaly detectors (#12699,
// design D6): burn spike, adapter schema drift, vendor plan
// change, run by src/quota-anomaly.ts over this tick's entries
// and records + the store's history. The state file holds the
// recorded baselines (parsed shapes, limits, window sets,
// fired keys); each NEW finding is appended to the history
// JSONL as an evidence-baseline diff record and posted to the
// alerts ledger (AlertsStore.postIncident, source
// "quota-anomaly"; no alerts store = the history record still
// stands). Fail-soft on the same terms: a detector failure
// never fails the tick, and a lost/corrupt state file simply
// re-baselines (no alert storm).
//
// Fail-soft contract: if the subcommand cannot be run or its output
// cannot be parsed, the tick writes a heartbeat carrying the error
Expand All @@ -121,6 +134,8 @@
// QUOTA_SHADOW_PLACEMENT_PATH / QUOTA_SHADOW_PLACEMENT_HISTORY_PATH
// (defaults: quota-shadow-placement.json /
// quota-shadow-placement-history.jsonl beside QUOTA_CURRENT_PATH),
// QUOTA_ANOMALY_STATE_PATH / QUOTA_ANOMALY_HISTORY_PATH
// (defaults beside QUOTA_CURRENT_PATH),
// QUOTA_GATHERER_STATE_PATH, QUOTA_SNAPSHOTS_DIR (./snapshots),
// USAGE_SNAPSHOT_OUTBOX_PATH,
// QUOTA_GATHER_CONCURRENCY (retained for interface stability;
Expand Down Expand Up @@ -169,6 +184,13 @@ import { readProviderAuthAlerts } from "../src/provider-auth-alerts.ts";
import { projectPoolState } from "../src/pool-state.ts";
import { buildForecastLedgerRows, buildQuotaForecast, type QuotaForecastFile } from "../src/quota-forecast.ts";
import { buildShadowPlacement } from "../src/quota-shadow-placement.ts";
import {
anomalyIncidentInput,
emptyAnomalyState,
isAnomalyStateFile,
runAnomalyTick,
type AnomalyStateFile,
} from "../src/quota-anomaly.ts";
import { renewMetaSession } from "../src/meta-renewal.ts";
import { classEnabled, getAlertsStore } from "../src/alerts.ts";
import { sendPush, type PushTarget } from "../src/push.ts";
Expand Down Expand Up @@ -210,6 +232,12 @@ const shadowPlacementPath =
process.env.QUOTA_SHADOW_PLACEMENT_PATH ?? join(dirname(currentPath), "quota-shadow-placement.json");
const shadowPlacementHistoryPath =
process.env.QUOTA_SHADOW_PLACEMENT_HISTORY_PATH ?? join(dirname(currentPath), "quota-shadow-placement-history.jsonl");
// #12699: the Stage-3 anomaly detectors' state + history, beside
// quota-current.json in the quota-watchdog shape (design D6).
const anomalyStatePath =
process.env.QUOTA_ANOMALY_STATE_PATH ?? join(dirname(currentPath), "quota-anomaly-state.json");
const anomalyHistoryPath =
process.env.QUOTA_ANOMALY_HISTORY_PATH ?? join(dirname(currentPath), "quota-anomaly-history.jsonl");
/** Strict millisecond parse for boot-time env (#2835 env-number contract):
* digits only, 1..2^31-1, else fail naming the variable and the value
* instead of coercing NaN/negative/huge values into a fetch deadline. */
Expand Down Expand Up @@ -946,6 +974,85 @@ async function writeTursoForecastRecords(
}
}

/**
* The Stage-3 anomaly detectors (#12699, design D6), run beside
* the tick after the forecast publish. All logic is
* src/quota-anomaly.ts (pure); this wrapper does the state/history
* file IO and the alerts-ledger posts. Fail-soft throughout: any
* failure is logged and the tick still succeeds; a missing or
* corrupt state file re-baselines from empty (the detectors'
* recorded shapes/limits rebuild from the next ticks' parses, and
* re-baselining files no findings — a state loss never becomes an
* alert storm). No alerts store (Turso unavailable) = the history
* records still stand and the skip is logged, the meta-keeper
* posture.
*/
async function runAnomalyDetectors(args: {
entries: QuotaCurrentEntry[];
fresh: SnapshotRecord[];
tickAt: string;
}): Promise<void> {
try {
let state: AnomalyStateFile = emptyAnomalyState(new Date(args.tickAt));
try {
const raw: unknown = JSON.parse(await readFile(anomalyStatePath, "utf8"));
if (isAnomalyStateFile(raw)) state = raw;
else console.log("quota-gatherer: anomaly state file unreadable as a v1 state — re-baselining");
} catch {
// No state file yet (or unreadable): re-baseline from empty.
}
const stored = await new SnapshotStore(snapshotsDir).readAll().catch((): SnapshotRecord[] => []);
const result = runAnomalyTick({
state,
entries: args.entries,
freshRecords: args.fresh,
history: [...stored, ...args.fresh],
now: new Date(args.tickAt),
});
if (result.findings.length) {
await mkdir(dirname(anomalyHistoryPath), { recursive: true });
await appendFile(
anomalyHistoryPath,
result.findings.map((f) => JSON.stringify({ kind: "quota-anomaly-finding", version: 1, ...f })).join("\n") +
"\n",
"utf8",
);
const store = await getAlertsStore();
if (!store) {
console.log(
`quota-gatherer: anomaly: ${result.findings.length} finding(s) recorded in history; no alerts store — no ledger post`,
);
} else {
for (const f of result.findings) {
try {
await store.postIncident(anomalyIncidentInput(f), {
detector: f.detector,
serviceId: f.serviceId,
window: f.window,
baseline: f.baseline,
observed: f.observed,
detail: f.detail,
});
} catch (err) {
console.log(
`quota-gatherer: anomaly: ledger post failed-soft for ${f.key}: ${safeProviderReason(err instanceof Error ? err.message : String(err))}`,
);
}
}
}
}
await writeAtomic(anomalyStatePath, JSON.stringify(result.state, null, 2) + "\n");
const unevaluable = result.evaluations.filter((e) => e.state === "unevaluable").length;
console.log(
`quota-gatherer: anomaly detectors: ${result.findings.length} new finding(s), ${result.evaluations.length} evaluations (${unevaluable} unevaluable)`,
);
} catch (err) {
console.error(
`quota-gatherer: anomaly detectors failed-soft: ${safeProviderReason(err instanceof Error ? err.message : String(err))}`,
);
}
}

async function main(): Promise<number> {
const started = Date.now();
const tickAt = new Date(started).toISOString();
Expand Down Expand Up @@ -1199,6 +1306,12 @@ async function main(): Promise<number> {
);
}

// Stage-3 S5 (#12699, design D6): the anomaly detectors beside
// the tick (burn spike / schema drift / plan change). Fail-soft
// inside runAnomalyDetectors; the tick's own result never
// depends on it.
await runAnomalyDetectors({ entries, fresh, tickAt });

const okCount = runs.filter((r) => r.state === "ok").length;
console.log(
`quota-gatherer: tick ${tickAt} providers=${runs.length} ok=${okCount} records=+${fresh.length} durationMs=${heartbeat.durationMs} -> ${currentPath}`,
Expand Down
231 changes: 231 additions & 0 deletions pm-stack/aggregator/scripts/quota-anomaly-replay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
#!/usr/bin/env bun
// Replay the Stage-3 anomaly detectors over the aggregator
// snapshot store (#12699, slice S5 of epic #12694; design
// doc/2026-11-22T22-35-00Z_design_quota-plane-stage-3 §6, D6).
//
// bun run scripts/quota-anomaly-replay.ts --store-dir <dir> \
// [--report-out <md>] [--findings-out <jsonl>] [--as-of <iso>]
//
// (Committed as the package.json script `replay:quota-anomaly`.)
//
// The store is read through SnapshotStore.readAll — read-only; this
// script never writes to the store dir. The replay runs the same
// machines the gatherer tick runs (src/quota-anomaly.ts) over the
// store's stream in order and reports, per detector: every finding
// (the historical incidents it fires on), the per-series evaluation
// rollup (fired / silent / unevaluable / baseline-established — an
// unevaluable series is named, never counted as silence), and the
// longest finding-free span of >= 7 days inside the store span
// (the replayed clean week the acceptance asks each detector for).
// It also renders, for the first finding, the two records a live
// tick files for it — the evidence-baseline diff record (the
// history JSONL line) and the alerts-ledger incident input — the
// replay-injected demonstration of the finding's landing surfaces.
//
// Replay fidelity, stated plainly: burn-spike and the plan-change
// limit leg replay at full fidelity (the store carries their whole
// input). Schema drift replays at store fidelity — per-service
// per-day (metric, unit) field sets, removals sustained over 3
// active days because the store appends only on movement. The
// unparseable leg has no store trace (the store records no parse
// outcomes); it is covered by the live tick path and the unit
// fixtures, not by this replay.
//
// --as-of defaults to the store's last reading, never the wall
// clock, so a run over a fixed store copy is reproducible.
//
// Argument contract (#3352): the whole command line is declared
// here — the four value options above, in `--opt value` or
// `--opt=value` form — and parsed strictly before any file is read
// or written. An unknown argument, a stray positional, or a
// present-but-valueless option is a usage error (exit 2) naming
// the offending argument.
import { writeFile } from "node:fs/promises";
import { SnapshotStore } from "../src/snapshots.ts";
import {
anomalyIncidentInput,
runAnomalyReplay,
type AnomalyDetectorId,
type AnomalyFinding,
type DetectorEvaluation,
} from "../src/quota-anomaly.ts";

const VALUE_OPTIONS = ["--store-dir", "--report-out", "--findings-out", "--as-of"] as const;
type ValueOption = (typeof VALUE_OPTIONS)[number];

function usageError(message: string): never {
console.error(`quota-anomaly-replay: ${message}`);
console.error(
"usage: quota-anomaly-replay --store-dir <dir> [--report-out <md>] [--findings-out <jsonl>] [--as-of <iso>]",
);
process.exit(2);
}

function parseArgs(argv: string[]): Record<ValueOption, string | undefined> {
const out: Record<ValueOption, string | undefined> = {
"--store-dir": undefined,
"--report-out": undefined,
"--findings-out": undefined,
"--as-of": undefined,
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i] as string;
const eq = arg.indexOf("=");
const name = (eq >= 0 ? arg.slice(0, eq) : arg) as ValueOption;
if (!VALUE_OPTIONS.includes(name)) {
usageError(`unknown argument '${arg}'; refusing to run, no files read or written`);
}
let value: string | undefined;
if (eq >= 0) {
value = arg.slice(eq + 1);
} else {
value = argv[i + 1];
if (value !== undefined) i++;
}
if (value === undefined || value.trim() === "" || value.startsWith("--")) {
usageError(`option '${name}' requires a non-empty value; refusing to run, no files read or written`);
}
out[name] = value;
}
return out;
}

const DAY_MS = 86_400_000;

/** The longest span inside [fromMs, toMs] containing no finding of
* this detector; null when no >= 7-day span exists. */
function longestCleanSpan(
findings: readonly AnomalyFinding[],
detector: AnomalyDetectorId,
fromMs: number,
toMs: number,
): { startIso: string; endIso: string; days: number } | null {
const cuts = findings
.filter((f) => f.detector === detector)
.map((f) => Date.parse(f.at))
.filter(Number.isFinite)
.sort((a, b) => a - b);
let best: { start: number; end: number } | null = null;
let prev = fromMs;
for (const cut of [...cuts, toMs]) {
if (!best || cut - prev > best.end - best.start) best = { start: prev, end: cut };
prev = Math.max(prev, cut);
}
if (!best || best.end - best.start < 7 * DAY_MS) return null;
return {
startIso: new Date(best.start).toISOString(),
endIso: new Date(best.end).toISOString(),
days: Math.round(((best.end - best.start) / DAY_MS) * 10) / 10,
};
}

function renderReport(args: {
storeDir: string;
records: number;
fromIso: string | null;
toIso: string | null;
fromMs: number;
toMs: number;
findings: AnomalyFinding[];
evaluations: DetectorEvaluation[];
}): string {
const lines: string[] = [];
lines.push("# Quota anomaly detector replay — Stage-3 S5 (#12699)");
lines.push("");
lines.push(
`- Store: ${args.records} records, ${args.fromIso ?? "?"} → ${args.toIso ?? "?"} (dir: ${args.storeDir})`,
);
lines.push(
"- Method: the live detectors' own machines (src/quota-anomaly.ts) replayed over the snapshot store in stream order. Burn-spike and the plan-change limit leg replay at full fidelity; schema drift replays at store fidelity (per-service per-day field sets, 3-active-day removal sustain — the store appends only on movement); the unparseable leg has no store trace and is covered by the live path + unit fixtures, not this replay.",
);
lines.push("");
const detectors: AnomalyDetectorId[] = ["burn-spike", "schema-drift", "plan-change"];
for (const detector of detectors) {
const own = args.findings.filter((f) => f.detector === detector);
const evals = args.evaluations.filter((e) => e.detector === detector);
const count = (s: string): number => evals.filter((e) => e.state === s).length;
lines.push(`## ${detector} — ${own.length} finding(s)`);
lines.push("");
lines.push(
`Evaluations: ${evals.length} series — fired ${count("fired")}, silent ${count("silent")}, unevaluable ${count("unevaluable")}, baseline-established ${count("baseline-established")}.`,
);
const clean = longestCleanSpan(args.findings, detector, args.fromMs, args.toMs);
lines.push(
clean
? `Clean week: silent across ${clean.startIso} → ${clean.endIso} (${clean.days} days, the longest finding-free span in the store).`
: "Clean week: NO finding-free span of >= 7 days exists in the store for this detector — the period was change-dense for this signal throughout (stated, not rounded away).",
);
lines.push("");
for (const f of own) {
lines.push(`- **${f.at}** ${f.serviceId}${f.window ? ` ${f.window}` : ""} — ${f.title}`);
lines.push(` - baseline: ${f.baseline}`);
lines.push(` - observed: ${f.observed}`);
}
if (!own.length) lines.push("- (no findings over the store span)");
lines.push("");
const unevaluable = evals.filter((e) => e.state === "unevaluable");
if (unevaluable.length) {
lines.push("Unevaluable series (named, never counted as silence):");
for (const e of unevaluable) {
lines.push(`- ${e.serviceId}${e.window ? ` ${e.window}` : ""}: ${e.reason ?? ""}`);
}
lines.push("");
}
}
const first = args.findings[0];
if (first) {
lines.push("## Landing demonstration (replay-injected)");
lines.push("");
lines.push(
"For the first finding above, the two records a live gatherer tick files — the evidence-baseline diff record (one history JSONL line) and the alerts-ledger incident input (AlertsStore.postIncident, source \"quota-anomaly\"):",
);
lines.push("");
lines.push("```json");
lines.push(JSON.stringify({ kind: "quota-anomaly-finding", version: 1, ...first }));
lines.push(JSON.stringify(anomalyIncidentInput(first)));
lines.push("```");
lines.push("");
}
return lines.join("\n");
}

async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const storeDir = args["--store-dir"];
if (!storeDir) usageError("--store-dir is required; refusing to run, no files read or written");
let asOfMs: number | undefined;
if (args["--as-of"] !== undefined) {
asOfMs = Date.parse(args["--as-of"]);
if (!Number.isFinite(asOfMs)) usageError(`--as-of '${args["--as-of"]}' is not a parseable instant`);
}
const records = await new SnapshotStore(storeDir as string).readAll();
const stamps = records.map((r) => Date.parse(r.ts)).filter(Number.isFinite);
const fromMs = stamps.length ? Math.min(...stamps) : 0;
const toMs = stamps.length ? Math.max(...stamps) : 0;
const { findings, evaluations } = runAnomalyReplay(records, { asOfMs });
const report = renderReport({
storeDir: storeDir as string,
records: records.length,
fromIso: stamps.length ? new Date(fromMs).toISOString() : null,
toIso: stamps.length ? new Date(toMs).toISOString() : null,
fromMs,
toMs,
findings,
evaluations,
});
if (args["--report-out"]) {
await writeFile(args["--report-out"], report, "utf8");
console.log(`quota-anomaly-replay: report -> ${args["--report-out"]} (${findings.length} findings)`);
} else {
console.log(report);
}
if (args["--findings-out"]) {
const jsonl = findings
.map((f) => JSON.stringify({ kind: "quota-anomaly-finding", version: 1, ...f }))
.join("\n");
await writeFile(args["--findings-out"], jsonl ? `${jsonl}\n` : "", "utf8");
console.log(`quota-anomaly-replay: findings -> ${args["--findings-out"]}`);
}
}

await main();
Loading