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
4 changes: 2 additions & 2 deletions pm-stack/aggregator/COST-ANOMALY.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Cost anomaly detector (#4825, partial)

The detector and warning-only intake are implemented and covered by local fixtures. The alert tick (`runAlertTick`) now runs the detector whenever a caller injects an evidence loader (`AlertTickOptions.costAnomalyEvidence`), posting warning incidents to the same alert store as every other throat incident. **The production caller now exists** (`src/cost-anomaly-activation.ts`): server wiring builds the loader over the production rollup store and `startAlertEngine` injects it — but only when the operator explicitly opts in with `PM_COST_ANOMALY_ENABLED=1` (or `true`). Off (the default), no loader is built, the tick does not read evidence or call the alert store for anomalies, and the detector stays dormant. No route, timer, schema change, or notification class is added. This does not complete #4825: the census data behind the auxiliary certified seams is still unwired, so until it lands the enabled loader assembles store-only evidence whose uncertified classes suppress in the detector. **Production rollup ingestion has now landed** (#18127, `src/spend-ingestion.ts` + `pm-stack/queue-bindings-export/`): behind its own opt-in (`PM_SPEND_INGESTION_ENABLED`, default off), the aggregator reads the usage, bindings, and pool exports on the alert tick's cadence and appends attribution → rollups to the store this loader reads.
The detector and warning-only intake are implemented and covered by local fixtures. The alert tick (`runAlertTick`) now runs the detector whenever a caller injects an evidence loader (`AlertTickOptions.costAnomalyEvidence`), posting warning incidents to the same alert store as every other throat incident. **The production caller now exists** (`src/cost-anomaly-activation.ts`): server wiring builds the loader over the production rollup store and `startAlertEngine` injects it — but only when the operator explicitly opts in with `PM_COST_ANOMALY_ENABLED=1` (or `true`). Off (the default), no loader is built, the tick does not read evidence or call the alert store for anomalies, and the detector stays dormant. No route, timer, schema change, or notification class is added. This does not complete #4825: the census data producers behind the auxiliary certified seams have landed (#18137, `src/cost-anomaly-census-producers.ts`) but are not yet wired into this caller, so until that wiring lands the enabled loader assembles store-only evidence whose uncertified classes suppress in the detector. **Production rollup ingestion has now landed** (#18127, `src/spend-ingestion.ts` + `pm-stack/queue-bindings-export/`): behind its own opt-in (`PM_SPEND_INGESTION_ENABLED`, default off), the aggregator reads the usage, bindings, and pool exports on the alert tick's cadence and appends attribution → rollups to the store this loader reads.

The evidence producer now exists (`src/cost-anomaly-producer.ts`): it reads the rollup store through an injected reader, reduces records with `selectRollups` (one consistent attribution version per window), pairs adjacent unattributed windows, and assembles `CostEvidence` for all four classes, with the certified auxiliary facts below supplied through injected seams that return null when uncertified. It performs no I/O of its own and the server does not call it; the end-to-end store → producer → intake → alert-ledger path is covered by `test/cost-anomaly-producer-4825.test.ts`.

Expand All @@ -19,4 +19,4 @@ The warning includes the scope, UTC interval, compared values and a link to the

Production rollup ingestion landed with #18127: `src/spend-ingestion.ts` reads the three file exports (the existing OpenCode usage export, plus the bindings and pool documents emitted by `pm-stack/queue-bindings-export/`, the queue-side exporter in the usage exporter's shape) on the alert tick's cadence, behind `PM_SPEND_INGESTION_ENABLED` (default off — off, no export is read and no store write happens). Each export carries a coverage block (window start/end + whole-window `ok` assertion); missing, stale, or error exports, and any coverage block that does not assert `ok`, suppress the tick's append entirely, and a rollup window is labelled complete only when the intersection of the three ok coverage windows covers it whole. The producer's certified sources now all have in-repository implementations. The charges-side seams: `src/cost-anomaly-sources.ts` implements `monthlyCharges` from the charges pipeline's matched charges (exact cent totals per service and month) and `serviceActivity` from a per-service-month activity census, certifying `complete` only when an ok coverage span covers the whole calendar month — absent, partial, or conflicting census data certifies nothing. The rollup-side seams: `src/cost-anomaly-rollup-sources.ts` implements `closedChildren` from a per-scope-window closure census, `busiestRoot` as the maximum folded root total of a per-epic-window root-session census, and `sourceTotal` from a per-window source-population census, certifying `complete` only when ok coverage spans cover the whole rollup window — the busiest root only when every root entry is whole-window certified, since a partially covered root set could conceal a larger root. Before activation, verify the source-to-rollup reconciliation, and verify warning presentation in Needs-you and Today/brief against the live application architecture without sending pushes. Do not turn on a producer merely because the detector tests pass.

Pre-activation verification (2026-11-28, #4825): the reconciliation and presentation legs are now pinned by `test/cost-anomaly-presentation-4825.test.ts`. The producer, fed only through the certified source modules above, posts warnings whose printed values reconcile exactly to the rollup-store records and census totals that produced them, and certified real activity or closures silence exactly their own classes. Presentation was verified against the current application architecture: incident alerts live on the /alerts page (render-attention.ts; the Needs-you queue carries label-census items and the Today banners are health-strip signals), and the warnings render there at severity `warning` with their evidence named and with no delivery or escalation — warnings never push in v1. What remains before activation is the census data producers the auxiliary seams certify from, and the operator's deliberate opt-in for both switches (the production caller that injects the evidence loader has landed — `src/cost-anomaly-activation.ts`, opt-in via `PM_COST_ANOMALY_ENABLED` — and production rollup ingestion has landed with #18127, opt-in via `PM_SPEND_INGESTION_ENABLED`).
Pre-activation verification (2026-11-28, #4825): the reconciliation and presentation legs are now pinned by `test/cost-anomaly-presentation-4825.test.ts`. The producer, fed only through the certified source modules above, posts warnings whose printed values reconcile exactly to the rollup-store records and census totals that produced them, and certified real activity or closures silence exactly their own classes. Presentation was verified against the current application architecture: incident alerts live on the /alerts page (render-attention.ts; the Needs-you queue carries label-census items and the Today banners are health-strip signals), and the warnings render there at severity `warning` with their evidence named and with no delivery or escalation — warnings never push in v1. The census data producers the auxiliary seams certify from have now landed (#18137): `src/cost-anomaly-census-producers.ts` builds the root-session census from attribution output (completeness source: the usage export's coverage block), the source-population census from the pre-attribution session set, and the closure census from the aggregator's GitHub issue reads (completeness source: the read's pagination-exhausted marker) — a non-ok source, a corrupt record, or a truncated read downgrades the emitted coverage, so the seams suppress rather than fabricate. What remains before activation is wiring those producers into the production caller, and the operator's deliberate opt-in for both switches (the production caller that injects the evidence loader has landed — `src/cost-anomaly-activation.ts`, opt-in via `PM_COST_ANOMALY_ENABLED` — and production rollup ingestion has landed with #18127, opt-in via `PM_SPEND_INGESTION_ENABLED`).
218 changes: 218 additions & 0 deletions pm-stack/aggregator/src/cost-anomaly-census-producers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
// #4825 census data producers: build the census arrays the certified
// rollup-side sources (cost-anomaly-rollup-sources.ts) consume, over
// the completeness sources named in the #4825 design record (lane
// 2037-G, comment 7299197952):
//
// - Root-session census — derived from spend attribution output.
// Attribution (spend-attribution.ts) already folds sub-sessions
// into their root group, so one census entry per (epic, pool,
// root session) is a regrouping of attribution facts, never a
// re-walk of the session tree. Pool and the scalar token total
// follow the ingestion convention (spend-ingestion.ts): pool is
// `providerID ?? "unknown"`, tokens are the five-field total.
// Completeness source: the usage export's coverage block, supplied
// by the caller as coverage spans.
// - Source-population census — the per-pool session totals before
// attribution, from the same session set. Completeness source:
// the same export coverage block, supplied by the caller.
// - Closure census — per-scope counts of child-issue closures in
// the window, from the caller's GitHub issue reads (the caller
// supplies the closure timestamps it read). Completeness source:
// the read's pagination-exhausted marker: coverage is `ok` only
// when the caller asserts the read was complete.
//
// The #4825 core rule governs every producer: a producer never
// certifies beyond its source. When the source status is not `ok`,
// or any input record is invalid (non-finite or negative tokens, an
// unparseable closure timestamp), the emitted coverage spans are
// downgraded to non-`ok`, so the certified seams return `partial`
// or null and the detector suppresses — a corrupt or failed source
// never certifies a clean total. Pure and deterministic: no I/O,
// no clock reads. Wiring these producers into the production
// caller is a later slice; this module changes no activation
// behaviour (COST-ANOMALY.md).
import type {
ClosureCensusEntry,
RootSessionCensusEntry,
SourcePopulationCensusEntry,
} from "./cost-anomaly-rollup-sources.ts";
import type { SpendAttributionFact, SpendSession, SpendTokens } from "./spend-attribution.ts";
import type { RollupScopeKind, RollupWindowKind, SourceCoverageSpan } from "./spend-rollups.ts";

/** The canonical calendar window a census answers for. */
export interface CensusWindow {
windowKind: RollupWindowKind;
/** Inclusive window start (UTC, ISO). */
windowStart: string;
/** Exclusive window end (UTC, ISO). */
windowEnd: string;
}

/** A caller's source status plus the coverage spans its export or
* read carried. `ok` is the source's own whole-window assertion;
* anything else downgrades every emitted span. */
export interface CensusSource {
status: "ok" | "missing" | "error";
coverage: readonly SourceCoverageSpan[];
}

function effectiveCoverage(source: CensusSource, tainted: boolean): SourceCoverageSpan[] {
if (source.status === "ok" && !tainted) return source.coverage.map((s) => ({ ...s }));
return source.coverage.map((s) => ({ ...s, status: "failed" as const }));
}

function validTokens(t: SpendTokens): boolean {
return [t.input, t.output, t.reasoning, t.cacheRead, t.cacheWrite].every(
(v) => Number.isFinite(v) && v >= 0,
);
}

/** The ingestion scalar convention (spend-ingestion.ts). */
function totalTokens(t: SpendTokens): number {
return t.input + t.output + t.reasoning + t.cacheRead + t.cacheWrite;
}

/**
* Root-session census from attribution facts. Only facts that carry
* a root session, an epic, and tokens answer the census: facts with
* no epic are not epic rollups' roots, and a tokenless fact certifies
* no consumption. Facts for one root split by provider/model (the
* attribution subgrouping) regroup here by pool: same root, same
* pool sums; a different provider is a different pool's entry for
* the same root, exactly as the rollups key token measures by pool.
*/
export function rootSessionCensus(
facts: readonly SpendAttributionFact[],
window: CensusWindow,
source: CensusSource,
): RootSessionCensusEntry[] {
let tainted = false;
const byKey = new Map<string, RootSessionCensusEntry & { coverage: SourceCoverageSpan[] }>();
for (const fact of facts) {
if (fact.rootSessionId === null || fact.epicRef === null || fact.tokens === null) continue;
if (!validTokens(fact.tokens)) {
tainted = true;
continue;
}
const pool = fact.providerID ?? "unknown";
const key = [fact.epicRef, pool, fact.rootSessionId].join("|");
const existing = byKey.get(key);
if (existing) {
existing.tokens += totalTokens(fact.tokens);
} else {
byKey.set(key, {
scopeId: fact.epicRef,
windowKind: window.windowKind,
windowStart: window.windowStart,
windowEnd: window.windowEnd,
pool,
rootSessionId: fact.rootSessionId,
tokens: totalTokens(fact.tokens),
coverage: [],
});
}
}
const coverage = effectiveCoverage(source, tainted);
return [...byKey.values()]
.sort(
(a, b) =>
a.scopeId.localeCompare(b.scopeId) ||
a.pool.localeCompare(b.pool) ||
a.rootSessionId.localeCompare(b.rootSessionId),
)
.map((e) => ({ ...e, coverage }));
}

/**
* Source-population census from the session set, before attribution:
* one entry per pool with the total tokens of every session in that
* pool — never a sum of rollup rows (COST-ANOMALY.md). Every session
* counts, attributed or not; that is what makes it the denominator.
*/
export function sourcePopulationCensus(
sessions: readonly SpendSession[],
window: CensusWindow,
source: CensusSource,
): SourcePopulationCensusEntry[] {
let tainted = false;
const byPool = new Map<string, number>();
for (const session of sessions) {
if (!validTokens(session.tokens)) {
tainted = true;
continue;
}
const pool = session.providerID ?? "unknown";
byPool.set(pool, (byPool.get(pool) ?? 0) + totalTokens(session.tokens));
}
const coverage = effectiveCoverage(source, tainted);
return [...byPool.entries()]
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([pool, value]) => ({
windowKind: window.windowKind,
windowStart: window.windowStart,
windowEnd: window.windowEnd,
unit: "tokens" as const,
pool,
value,
coverage,
}));
}

/** One scope's closure read: the child-closure timestamps the
* caller read for that scope over the window. */
export interface ClosureObservation {
scopeKind: RollupScopeKind;
scopeId: string;
closedAt: readonly string[];
}

/**
* Closure census from caller-supplied closure reads. Only closures
* inside [windowStart, windowEnd) count. Coverage is a single span
* over the window, `ok` only when the caller asserts its reads were
* complete (pagination exhausted for every scope) and no timestamp
* was unparseable; a truncated read is `unknown`, never `ok` — a
* filtered or partial view does not certify a zero (COST-ANOMALY.md).
*/
export function closureCensus(
observations: readonly ClosureObservation[],
window: CensusWindow,
readComplete: boolean,
): ClosureCensusEntry[] {
const start = Date.parse(window.windowStart);
const end = Date.parse(window.windowEnd);
let tainted = !Number.isFinite(start) || !Number.isFinite(end);
const coverage: SourceCoverageSpan[] = [
{
from: window.windowStart,
to: window.windowEnd,
status: readComplete && !tainted ? "ok" : "unknown",
},
];
const entries: ClosureCensusEntry[] = observations.map((obs) => {
let count = 0;
for (const ts of obs.closedAt) {
const t = Date.parse(ts);
if (!Number.isFinite(t)) {
tainted = true;
continue;
}
if (t >= start && t < end) count += 1;
}
return {
scopeKind: obs.scopeKind,
scopeId: obs.scopeId,
windowKind: window.windowKind,
windowStart: window.windowStart,
windowEnd: window.windowEnd,
closedChildren: count,
coverage,
};
});
if (tainted) {
for (const e of entries) e.coverage = [{ from: window.windowStart, to: window.windowEnd, status: "unknown" }];
}
return entries.sort(
(a, b) => a.scopeKind.localeCompare(b.scopeKind) || a.scopeId.localeCompare(b.scopeId),
);
}
Loading