diff --git a/pm-stack/aggregator/scripts/compact-usage-snapshots.ts b/pm-stack/aggregator/scripts/compact-usage-snapshots.ts new file mode 100755 index 0000000000..27a507386f --- /dev/null +++ b/pm-stack/aggregator/scripts/compact-usage-snapshots.ts @@ -0,0 +1,45 @@ +#!/usr/bin/env bun +// Compact old usage snapshot months into rollups (hub design §6, +// #1117): raw monthly files are kept 13 months, then replaced by a +// `usage-YYYY-MM.rollup.jsonl` holding min/max/last per +// service+metric, kept indefinitely. SnapshotStore.readAll expands +// rollups, so readers need no changes. +// +// The default mode is --dry-run: it prints the per-service +// before/after report and changes nothing. Pass --apply to perform +// the compaction. Either way the full report is printed as JSON on +// stdout (attach it to #1117 before the first real run). +// +// Usage: bun run scripts/compact-usage-snapshots.ts [--apply] [--months ] +// Env: PM_AGG_SNAPSHOTS_DIR (default: the aggregator package's +// snapshots/ directory — the same store default as src/config.ts, +// backfill-usage-snapshots.ts, and the quota gatherer, so running +// this script in the standard installation compacts the store the +// aggregator actually reads and writes). +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { SnapshotStore } from "../src/snapshots.ts"; + +const PKG = join(dirname(fileURLToPath(import.meta.url)), ".."); +const dir = process.env.PM_AGG_SNAPSHOTS_DIR ?? join(PKG, "snapshots"); +const apply = process.argv.includes("--apply"); +const monthsArg = process.argv.indexOf("--months"); +const retentionMonths = monthsArg >= 0 ? Number(process.argv[monthsArg + 1]) : 13; +if (!Number.isInteger(retentionMonths) || retentionMonths < 0) { + console.error(`compact-usage-snapshots: invalid --months '${process.argv[monthsArg + 1]}'`); + process.exit(2); +} + +const report = await new SnapshotStore(dir).compact({ dryRun: !apply, retentionMonths }); +console.log(JSON.stringify({ storeDir: dir, ...report }, null, 2)); +if (!report.months.length) { + console.error( + `compact-usage-snapshots: no months at or before the ${report.cutoffMonth} cutoff — nothing to do (${apply ? "apply" : "dry-run"})`, + ); +} else { + for (const m of report.months) { + console.error( + `compact-usage-snapshots: ${m.month}: ${m.recordsBefore} records -> ${m.recordsAfter} rollups (${m.dryRun ? "dry-run, unchanged" : "compacted"})`, + ); + } +} diff --git a/pm-stack/aggregator/src/snapshots.ts b/pm-stack/aggregator/src/snapshots.ts index bf49bf39e3..df8bb49ed6 100644 --- a/pm-stack/aggregator/src/snapshots.ts +++ b/pm-stack/aggregator/src/snapshots.ts @@ -4,12 +4,19 @@ // the owning jobs (fleet-feed collector, stewardship-cycle, the Jules // keeper) and the one-shot backfill script; the aggregator only reads. // +// Retention (§6, #1117): raw monthly files are kept for 13 months, +// then compacted in place into monthly rollup files +// (`usage-YYYY-MM.rollup.jsonl`) that keep min/max/last per +// service+metric and are kept indefinitely. SnapshotStore.readAll +// expands rollups back into records, so existing readers see a +// compacted store unchanged in shape. +// // Records keep their original observation timestamp and source class — // backfilled prose observations stay dated 2026-10-20 even when the // backfill runs later. Estimates are stored as a low/high pair with // unit "usd-est"; the 1.2×high counting rule applies at render, never // baked into history. -import { appendFile, mkdir, readdir, readFile } from "node:fs/promises"; +import { appendFile, link, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import { join } from "node:path"; import type { SnapshotRecord, UsageSourceClass } from "./model.ts"; @@ -17,6 +24,268 @@ const SOURCES: ReadonlySet = new Set(["api", "console", "manual", "estim const UNITS: ReadonlySet = new Set(["pct", "usd", "count", "gb", "tokens", "usd-est"]); const FILE_RE = /^usage-(\d{4}-\d{2})\.jsonl$/; +const ROLLUP_RE = /^usage-(\d{4}-\d{2})\.rollup\.jsonl$/; + +/** The rollup file a month's raw file compacts into. */ +export function rollupFileFor(month: string): string { + return `usage-${month}.rollup.jsonl`; +} + +/** + * One month's compaction of every record for one + * service+metric+unit+source: the count of raw records it replaces + * and their min/max/last values (each with the timestamp it was + * observed at). Estimate pairs ({low, high}) order by low, then high. + * `resetsAt`/`limit` are the last non-null values seen, so a quota + * window's reset effect survives compaction on the `last` record. + */ +export interface SnapshotRollup { + kind: "snapshot-rollup/v1"; + month: string; + serviceId: string; + metricId: string; + unit: SnapshotRecord["unit"]; + source: SnapshotRecord["source"]; + observedBy: string; + count: number; + firstTs: string; + lastTs: string; + valueMin: SnapshotRecord["value"]; + minTs: string; + valueMax: SnapshotRecord["value"]; + maxTs: string; + valueLast: SnapshotRecord["value"]; + resetsAt?: string | null; + /** Timestamp of the observation `resetsAt` came from (metadata is + * merged on its own clock, independently of the last value). */ + resetsAtTs?: string; + limit?: number | null; + /** Timestamp of the observation `limit` came from. */ + limitTs?: string; + /** Dedupe keys (snapshotKey form) of every compacted observation, + * so SnapshotStore.append stays safe to re-run after compaction. */ + keys: string[]; +} + +function rollupOrderKey(v: SnapshotRecord["value"]): [number, number] { + return typeof v === "number" ? [v, v] : [v.low, v.high]; +} + +function cmpValue(a: SnapshotRecord["value"], b: SnapshotRecord["value"]): number { + const [al, ah] = rollupOrderKey(a); + const [bl, bh] = rollupOrderKey(b); + return al - bl || ah - bh; +} + +/** Structural validation for one rollup line (store reads). */ +export function isSnapshotRollup(v: unknown): v is SnapshotRollup { + if (typeof v !== "object" || v === null) return false; + const r = v as Partial; + if (r.kind !== "snapshot-rollup/v1") return false; + if (typeof r.month !== "string" || !/^\d{4}-\d{2}$/.test(r.month)) return false; + if (typeof r.serviceId !== "string" || r.serviceId === "") return false; + if (typeof r.metricId !== "string" || r.metricId === "") return false; + if (typeof r.unit !== "string" || !UNITS.has(r.unit)) return false; + if (typeof r.source !== "string" || !SOURCES.has(r.source)) return false; + if (typeof r.count !== "number" || !(r.count >= 1)) return false; + if (typeof r.observedBy !== "string" || r.observedBy === "") return false; + for (const f of [r.firstTs, r.lastTs, r.minTs, r.maxTs]) { + if (typeof f !== "string" || Number.isNaN(Date.parse(f))) return false; + } + if (r.keys !== undefined && (!Array.isArray(r.keys) || r.keys.some((k) => typeof k !== "string"))) return false; + const val = (x: unknown): boolean => + (typeof x === "number" && Number.isFinite(x)) || + (typeof x === "object" && + x !== null && + typeof (x as { low?: unknown }).low === "number" && + typeof (x as { high?: unknown }).high === "number"); + return val(r.valueMin) && val(r.valueMax) && val(r.valueLast); +} + +interface RollupAgg { + rollup: SnapshotRollup; + keys: Set; +} + +function aggFromRecord(month: string, r: SnapshotRecord): RollupAgg { + return { + keys: new Set([snapshotKey(r)]), + rollup: { + kind: "snapshot-rollup/v1", + month, + serviceId: r.serviceId, + metricId: r.metricId, + unit: r.unit, + source: r.source, + observedBy: r.observedBy, + count: 1, + firstTs: r.ts, + lastTs: r.ts, + valueMin: r.value, + minTs: r.ts, + valueMax: r.value, + maxTs: r.ts, + valueLast: r.value, + keys: [], + ...(r.resetsAt != null ? { resetsAt: r.resetsAt, resetsAtTs: r.ts } : {}), + ...(r.limit != null ? { limit: r.limit, limitTs: r.ts } : {}), + }, + }; +} + +function aggFromRollup(r: SnapshotRollup): RollupAgg { + const rollup = { ...r }; + // Rollups written before the metadata clocks existed: their + // metadata came from the last observation by construction. + if (rollup.resetsAt != null && rollup.resetsAtTs === undefined) rollup.resetsAtTs = rollup.lastTs; + if (rollup.limit != null && rollup.limitTs === undefined) rollup.limitTs = rollup.lastTs; + return { rollup, keys: new Set(r.keys ?? []) }; +} + +function aggAddRecord(agg: RollupAgg, r: SnapshotRecord): void { + const o = agg.rollup; + const key = snapshotKey(r); + // Recovery after an interrupted compaction (rollup published, raw + // file still present) re-reads records already folded into the + // rollup; count and aggregates must not grow twice for them. + if (agg.keys.has(key)) return; + agg.keys.add(key); + o.count += 1; + if (r.ts < o.firstTs) o.firstTs = r.ts; + if (cmpValue(r.value, o.valueMin) < 0) { + o.valueMin = r.value; + o.minTs = r.ts; + } + if (cmpValue(r.value, o.valueMax) > 0) { + o.valueMax = r.value; + o.maxTs = r.ts; + } + if (r.ts >= o.lastTs) { + o.lastTs = r.ts; + o.valueLast = r.value; + o.observedBy = r.observedBy; + } + // Quota metadata merges on its own clock: a late record that + // predates lastTs still contributes its resetsAt/limit when it is + // the freshest observation carrying them, exactly as a one-pass + // compaction of the whole month would. + if (r.resetsAt != null && r.ts >= (o.resetsAtTs ?? "")) { + o.resetsAt = r.resetsAt; + o.resetsAtTs = r.ts; + } + if (r.limit != null && r.ts >= (o.limitTs ?? "")) { + o.limit = r.limit; + o.limitTs = r.ts; + } +} + +function rollupGroupKey(serviceId: string, metricId: string, unit: string, source: string): string { + return `${serviceId}|${metricId}|${unit}|${source}`; +} + +/** + * Compact one month's records into rollups: one per + * service+metric+unit+source, sorted for a stable file. Existing + * rollups for the month seed the aggregates (their counts and + * min/max/last survive), so re-compacting after late raw records + * arrive for an already-compacted month merges instead of losing + * history. + */ +export function compactRecordsToRollups( + month: string, + records: SnapshotRecord[], + existing: SnapshotRollup[] = [], +): SnapshotRollup[] { + const aggs = new Map(); + for (const r of existing) { + aggs.set(rollupGroupKey(r.serviceId, r.metricId, r.unit, r.source), aggFromRollup(r)); + } + const sorted = [...records].sort((a, b) => a.ts.localeCompare(b.ts)); + for (const r of sorted) { + const k = rollupGroupKey(r.serviceId, r.metricId, r.unit, r.source); + const agg = aggs.get(k); + if (agg) aggAddRecord(agg, r); + else aggs.set(k, aggFromRecord(month, r)); + } + return [...aggs.values()] + .map((a) => ({ ...a.rollup, keys: [...a.keys].sort() })) + .sort((a, b) => + rollupGroupKey(a.serviceId, a.metricId, a.unit, a.source).localeCompare( + rollupGroupKey(b.serviceId, b.metricId, b.unit, b.source), + ), + ); +} + +/** + * Expand a rollup back into records for the existing reading path: + * min, max, and last (deduped when they coincide). The `last` record + * carries the preserved resetsAt/limit, so latest-value readers and + * reset markers behave as they did on the raw store. + */ +export function expandRollup(r: SnapshotRollup): SnapshotRecord[] { + const base = { + serviceId: r.serviceId, + metricId: r.metricId, + unit: r.unit, + source: r.source, + observedBy: r.observedBy, + }; + const out: SnapshotRecord[] = []; + const seen = new Set(); + const push = (rec: SnapshotRecord): void => { + const k = snapshotKey(rec); + if (seen.has(k)) return; + seen.add(k); + out.push(rec); + }; + // Last first: when min or max IS the last observation (same ts and + // value), the dedupe keeps the record that carries resetsAt/limit. + push({ + ...base, + ts: r.lastTs, + value: r.valueLast, + ...(r.resetsAt !== undefined ? { resetsAt: r.resetsAt } : {}), + ...(r.limit !== undefined ? { limit: r.limit } : {}), + }); + push({ ...base, ts: r.minTs, value: r.valueMin }); + push({ ...base, ts: r.maxTs, value: r.valueMax }); + return out.sort((a, b) => a.ts.localeCompare(b.ts)); +} + +/** `YYYY-MM` shifted by whole months (negative = earlier). */ +export function shiftMonth(month: string, delta: number): string { + const [y, m] = month.split("-").map(Number); + const total = y * 12 + (m - 1) + delta; + const yy = Math.floor(total / 12); + const mm = (total % 12) + 1; + return `${yy}-${String(mm).padStart(2, "0")}`; +} + +/** Per-service before/after counts for one compacted month. */ +export interface CompactionServiceCounts { + before: number; + after: number; +} + +export interface CompactionMonthReport { + month: string; + /** Raw records read from the month's raw file. */ + recordsBefore: number; + /** Rollup records the month is represented by afterwards. */ + recordsAfter: number; + perService: Record; + dryRun: boolean; + /** True when nothing was (or would be) changed for this month. */ + unchanged: boolean; +} + +export interface CompactionReport { + /** Oldest month still kept raw; older months were eligible. */ + cutoffMonth: string; + months: CompactionMonthReport[]; + dryRun: boolean; +} + /** The monthly file a record belongs in, by its own timestamp. */ export function snapshotFileFor(ts: string): string { return `usage-${ts.slice(0, 7)}.jsonl`; @@ -46,6 +315,199 @@ export function snapshotKey(r: SnapshotRecord): string { return `${r.serviceId}|${r.metricId}|${r.ts}|${v}`; } +const LOCK_STALE_MS = 120_000; +const LOCK_TIMEOUT_MS = 30_000; + +/** + * Serialize store mutations (append, compact) across processes with + * a lockfile in the store dir: compaction's read/publish/delete + * sequence must never overlap an append to the same month, or the + * appended records would be deleted without entering the rollup. + * A lock older than LOCK_STALE_MS is treated as abandoned (its + * holder died) and stolen; failing to acquire within + * LOCK_TIMEOUT_MS is an error, never a silent unlocked write. + */ +export async function withSnapshotStoreLock(dir: string, fn: () => Promise): Promise { + await mkdir(dir, { recursive: true }); + const lockPath = join(dir, ".snapshots.lock"); + const guardPath = join(dir, ".snapshots.reclaim.guard"); + const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`; + const deadline = Date.now() + LOCK_TIMEOUT_MS; + + // Acquire the reclaim guard: a plain wx lock file whose critical + // sections are milliseconds long. Its own staleness uses the + // rename-and-verify reclaim below, which is safe here because the + // guard only ever serializes the *decision* to reclaim — the main + // lock is re-verified inside the guard before anything is removed. + // + // Restore protocol (Codex round 3 on PR #2379): a reclaimer that + // renames the guard may find it moved a *live* guard (a faster + // reclaimer had already replaced the abandoned one). The moved + // guard is linked back — but if its owner released it while it was + // moved aside, the restored file would be an ownerless orphan and + // waiters would stall until it went stale. So releaseGuard leaves + // a release tombstone whenever it cannot remove its own guard + // file, and the restorer (and, as a backstop, any later acquirer + // that finds a tombstoned guard token) deletes a restored guard + // whose owner has tombstoned its release. A guard is only ever + // deleted under its owner's token, and a tombstone is only ever + // written by that token's owner at release time. + const releasedPathFor = (t: string): string => + `${guardPath}.released-${t.replace(/[^a-zA-Z0-9.-]/g, "_")}`; + const restoreGuard = async (reclaimPath: string): Promise => { + const movedToken = await readFile(reclaimPath, "utf8").catch(() => ""); + try { + await link(reclaimPath, guardPath); + } catch { + await rm(reclaimPath, { force: true }); + return; // a guard is already in place — the moved file is superseded + } + await rm(reclaimPath, { force: true }); + if (!movedToken) return; + // Poll briefly for the owner's release tombstone: the owner + // releases the guard immediately after its (millisecond) critical + // section, so a tombstone appears promptly or not at all — in + // which case the owner is still holding the restored guard and + // will remove it itself at release. + for (let i = 0; i < 200; i++) { + const cur = await readFile(guardPath, "utf8").catch(() => ""); + if (cur !== movedToken) return; // released or replaced — not ours to touch + const tomb = await stat(releasedPathFor(movedToken)).catch(() => null); + const lockToken = await readFile(lockPath, "utf8").catch(() => ""); + if (tomb || lockToken === movedToken) { + // Tombstone: the owner released the guard while it was moved. + // Main-lock token: the owner uses the same token there and + // creates it immediately after releasing the guard, so its + // presence proves the same release. Either way the restored + // guard is ownerless. + const again = await readFile(guardPath, "utf8").catch(() => ""); + if (again === movedToken) await rm(guardPath, { force: true }); + await rm(releasedPathFor(movedToken), { force: true }); + return; + } + await new Promise((r) => setTimeout(r, 5)); + } + }; + const acquireGuard = async (): Promise => { + for (;;) { + try { + await writeFile(guardPath, token, { flag: "wx" }); + return true; + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; + // Backstop orphan sweep: a guard whose owner tombstoned its + // release is ownerless (see restore protocol above) — remove + // it instead of waiting for it to go stale. + const heldToken = await readFile(guardPath, "utf8").catch(() => ""); + if (heldToken && heldToken !== token) { + const tomb = await stat(releasedPathFor(heldToken)).catch(() => null); + if (tomb) { + const again = await readFile(guardPath, "utf8").catch(() => ""); + if (again === heldToken) await rm(guardPath, { force: true }); + await rm(releasedPathFor(heldToken), { force: true }); + continue; + } + } + let st; + try { + st = await stat(guardPath); + } catch (statErr) { + if ((statErr as NodeJS.ErrnoException).code === "ENOENT") continue; + throw statErr; + } + if (Date.now() - st.mtimeMs > LOCK_STALE_MS) { + const reclaimPath = `${guardPath}.reclaim-${token}`; + try { + await rename(guardPath, reclaimPath); + } catch (renameErr) { + if ((renameErr as NodeJS.ErrnoException).code === "ENOENT") continue; + throw renameErr; + } + const moved = await stat(reclaimPath).catch(() => null); + if (moved && moved.ino === st.ino && moved.mtimeMs === st.mtimeMs) { + await rm(reclaimPath, { force: true }); + } else if (moved) { + await restoreGuard(reclaimPath); + } + continue; + } + if (Date.now() > deadline) return false; // another reclaimer is at work — just wait for the lock instead + await new Promise((r) => setTimeout(r, 25)); + } + } + }; + const releaseGuard = async (): Promise => { + const cur = await readFile(guardPath, "utf8").catch(() => ""); + if (cur === token) { + await rm(guardPath, { force: true }); + } else { + // Our guard file was moved aside by a stale reclaimer (or is + // already gone): leave a release tombstone so whoever restores + // the moved file can tell it is an orphan, not a held guard. + await writeFile(releasedPathFor(token), token).catch(() => undefined); + } + }; + + for (;;) { + try { + await writeFile(lockPath, token, { flag: "wx" }); + break; + } catch (err) { + // Only EEXIST means contention. Anything else (EACCES on an + // unwritable store dir, ENOSPC, ...) is permanent and must + // surface instead of spinning past the deadline. + if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; + let st; + try { + st = await stat(lockPath); + } catch (statErr) { + if ((statErr as NodeJS.ErrnoException).code === "ENOENT") continue; // lock vanished between attempts — retry at once + throw statErr; + } + if (Date.now() - st.mtimeMs > LOCK_STALE_MS) { + if (Date.now() > deadline) throw new Error(`snapshot store lock timeout: ${lockPath}`); + // The lock looks abandoned. Reclaimers are serialized by the + // guard, and staleness is re-verified *inside* the guard + // against the file identity statted there: a lock is removed + // only while no other reclaimer can be replacing it, and + // plain acquirers cannot create a lock while the stale one + // is present — so the file removed is always the abandoned + // one, never a fresh replacement. (Unserialized, a slower + // reclaimer's rm deleted the fresh lock a faster reclaimer + // had just acquired and both critical sections ran at once.) + if (await acquireGuard()) { + try { + const cur = await stat(lockPath).catch(() => null); + if (cur && cur.ino === st.ino && Date.now() - cur.mtimeMs > LOCK_STALE_MS) { + await rm(lockPath, { force: true }); + } + } finally { + await releaseGuard(); + } + } + continue; + } + if (Date.now() > deadline) throw new Error(`snapshot store lock timeout: ${lockPath}`); + await new Promise((r) => setTimeout(r, 25)); + } + } + try { + return await fn(); + } finally { + const cur = await readFile(lockPath, "utf8").catch(() => ""); + if (cur === token) await rm(lockPath, { force: true }); + // Final orphan sweep: the guard is only ever held transiently + // during a reclaim, long before fn() ran, so a guard file still + // bearing our token here is a restored orphan (see the restore + // protocol above) — remove it and our release tombstone. If no + // restorer consumed the tombstone and no guard was restored, + // this just removes the tombstone. + const guardCur = await readFile(guardPath, "utf8").catch(() => ""); + if (guardCur === token) await rm(guardPath, { force: true }); + await rm(releasedPathFor(token), { force: true }); + } +} + export class SnapshotStore { constructor(private readonly dir: string) {} @@ -53,7 +515,7 @@ export class SnapshotStore { async readAll(): Promise { let names: string[]; try { - names = (await readdir(this.dir)).filter((n) => FILE_RE.test(n)).sort(); + names = (await readdir(this.dir)).filter((n) => FILE_RE.test(n) || ROLLUP_RE.test(n)).sort(); } catch { return []; // no store yet — history simply has not started } @@ -65,11 +527,16 @@ export class SnapshotStore { } catch { continue; } + const isRollup = ROLLUP_RE.test(name); for (const line of text.split("\n")) { if (!line.trim()) continue; try { const parsed: unknown = JSON.parse(line); - if (isSnapshotRecord(parsed)) out.push(parsed); + if (isRollup) { + if (isSnapshotRollup(parsed)) out.push(...expandRollup(parsed)); + } else if (isSnapshotRecord(parsed)) { + out.push(parsed); + } } catch { // one bad line never poisons the store } @@ -87,15 +554,47 @@ export class SnapshotStore { return grouped; } + /** Dedupe keys of every observation already compacted into rollups. */ + async rollupKeys(): Promise { + let names: string[]; + try { + names = (await readdir(this.dir)).filter((n) => ROLLUP_RE.test(n)).sort(); + } catch { + return []; + } + const out: string[] = []; + for (const name of names) { + const text = await readFile(join(this.dir, name), "utf8").catch(() => ""); + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + const parsed: unknown = JSON.parse(line); + if (isSnapshotRollup(parsed)) out.push(...(parsed.keys ?? [])); + } catch { + // one bad line never poisons the store + } + } + } + return out; + } + /** * Append records, skipping any already present (same dedupe key), so * writers and the backfill are safe to re-run. Returns how many were * actually appended. Records land in their own month's file. + * Dedupe consults rollup keys too: observations compacted out of + * the raw files stay known, so replaying a historical batch after + * compaction appends nothing. */ async append(records: SnapshotRecord[]): Promise { + return withSnapshotStoreLock(this.dir, () => this.appendLocked(records)); + } + + private async appendLocked(records: SnapshotRecord[]): Promise { const valid = records.filter(isSnapshotRecord); if (!valid.length) return 0; const seen = new Set((await this.readAll()).map(snapshotKey)); + for (const k of await this.rollupKeys()) seen.add(k); const fresh = valid.filter((r) => { const k = snapshotKey(r); if (seen.has(k)) return false; // stored already, or earlier in this batch @@ -115,6 +614,106 @@ export class SnapshotStore { } return fresh.length; } + + /** + * Retention (§6, #1117): compact every raw monthly file older + * than `retentionMonths` (default 13) into its rollup file, then + * remove the raw file. Months at or newer than the cutoff stay + * raw. Idempotent: a month with no raw file is skipped, and a + * month whose raw file reappears (late writer) merges into the + * existing rollup on the next run. With `dryRun`, the same report + * is computed and nothing on disk changes. + */ + async compact(opts: { now?: Date; retentionMonths?: number; dryRun?: boolean } = {}): Promise { + if (opts.dryRun) return this.compactInner(opts); + return withSnapshotStoreLock(this.dir, () => this.compactInner(opts)); + } + + private async compactInner(opts: { now?: Date; retentionMonths?: number; dryRun?: boolean }): Promise { + const now = opts.now ?? new Date(); + const retentionMonths = opts.retentionMonths ?? 13; + const dryRun = opts.dryRun ?? false; + const currentMonth = now.toISOString().slice(0, 7); + const cutoffMonth = shiftMonth(currentMonth, -retentionMonths); + const report: CompactionReport = { cutoffMonth, months: [], dryRun }; + let names: string[]; + try { + names = (await readdir(this.dir)).sort(); + } catch { + return report; // no store yet — nothing to compact + } + for (const name of names) { + const m = FILE_RE.exec(name); + if (!m) continue; + const month = m[1]; + if (month > cutoffMonth) continue; // still within the raw window + const rawText = await readFile(join(this.dir, name), "utf8").catch(() => ""); + const records: SnapshotRecord[] = []; + for (const line of rawText.split("\n")) { + if (!line.trim()) continue; + try { + const parsed: unknown = JSON.parse(line); + if (isSnapshotRecord(parsed)) records.push(parsed); + } catch { + // malformed lines are dropped by compaction, as reads skip them + } + } + const rollupName = rollupFileFor(month); + const existing: SnapshotRollup[] = []; + if (names.includes(rollupName)) { + // An unreadable rollup must abort compaction: treating it as + // empty would overwrite previously compacted history with only + // the late raw records, and the raw file is deleted right after. + let rollText: string; + try { + rollText = await readFile(join(this.dir, rollupName), "utf8"); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") { + rollText = ""; + } else { + throw new Error( + `compaction aborted: cannot read existing rollup ${rollupName}: ${(err as Error).message}`, + ); + } + } + for (const line of rollText.split("\n")) { + if (!line.trim()) continue; + try { + const parsed: unknown = JSON.parse(line); + if (isSnapshotRollup(parsed)) existing.push(parsed); + } catch { + // a bad rollup line never blocks compaction of the raw file + } + } + } + const rollups = compactRecordsToRollups(month, records, existing); + const perService: Record = {}; + for (const r of records) { + (perService[r.serviceId] ??= { before: 0, after: 0 }).before += 1; + } + for (const r of existing) { + (perService[r.serviceId] ??= { before: 0, after: 0 }).before += r.count; + } + for (const r of rollups) { + (perService[r.serviceId] ??= { before: 0, after: 0 }).after += 1; + } + const monthReport: CompactionMonthReport = { + month, + recordsBefore: records.length + existing.reduce((n, r) => n + r.count, 0), + recordsAfter: rollups.length, + perService, + dryRun, + unchanged: records.length === 0, + }; + report.months.push(monthReport); + if (dryRun || records.length === 0) continue; + const tmp = join(this.dir, `.${rollupName}.tmp`); + await writeFile(tmp, rollups.map((r) => JSON.stringify(r)).join("\n") + "\n", "utf8"); + await rename(tmp, join(this.dir, rollupName)); + await rm(join(this.dir, name)); + } + return report; + } } /** Source classes the store accepts, for writer-side validation messages. */ diff --git a/pm-stack/aggregator/test/snapshot-retention.test.ts b/pm-stack/aggregator/test/snapshot-retention.test.ts new file mode 100644 index 0000000000..c5f0ec021d --- /dev/null +++ b/pm-stack/aggregator/test/snapshot-retention.test.ts @@ -0,0 +1,352 @@ +// Snapshot retention (#1117, hub design §6): raw monthly files are +// kept 13 months, then compacted into monthly rollups (min/max/last +// per service+metric, resetsAt preserved). The existing reading path +// (SnapshotStore.readAll / byService) must read a compacted store +// with no changes to callers, and compaction must be idempotent. +import { describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, readdir, readFile, rm, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { SnapshotRecord } from "../src/model.ts"; +import { + SnapshotStore, + compactRecordsToRollups, + expandRollup, + rollupFileFor, + shiftMonth, + withSnapshotStoreLock, +} from "../src/snapshots.ts"; + +const NOW = new Date("2026-10-29T12:00:00Z"); // cutoff month: 2025-09 + +function rec(ts: string, serviceId: string, metricId: string, value: number, extra: Partial = {}): SnapshotRecord { + return { + ts, + serviceId, + metricId, + value, + unit: "pct", + source: "api", + observedBy: "test", + ...extra, + }; +} + +async function seedStore(dir: string): Promise { + await mkdir(dir, { recursive: true }); + // Eligible month (2025-06): two services, one with a resetsAt window. + const june: SnapshotRecord[] = [ + rec("2025-06-03T12:00:00Z", "svc-a", "weekly", 40, { limit: 100, resetsAt: "2025-06-08T00:00:00Z" }), + rec("2025-06-10T12:00:00Z", "svc-a", "weekly", 85, { limit: 100, resetsAt: "2025-06-15T00:00:00Z" }), + rec("2025-06-20T12:00:00Z", "svc-a", "weekly", 10, { limit: 100, resetsAt: "2025-06-22T00:00:00Z" }), + rec("2025-06-05T12:00:00Z", "svc-b", "tokens", 7, { unit: "count" }), + rec("2025-06-25T12:00:00Z", "svc-b", "tokens", 9, { unit: "count" }), + ]; + await writeFile(join(dir, "usage-2025-06.jsonl"), june.map((r) => JSON.stringify(r)).join("\n") + "\n"); + // Boundary month (2025-09, exactly 13 months back): eligible. + await writeFile( + join(dir, "usage-2025-09.jsonl"), + JSON.stringify(rec("2025-09-15T12:00:00Z", "svc-a", "weekly", 55)) + "\n", + ); + // Recent month (2025-10, 12 months back): stays raw. + await writeFile( + join(dir, "usage-2025-10.jsonl"), + JSON.stringify(rec("2025-10-15T12:00:00Z", "svc-a", "weekly", 66)) + "\n", + ); +} + +describe("shiftMonth", () => { + test("shifts across year boundaries", () => { + expect(shiftMonth("2026-10", -13)).toBe("2025-09"); + expect(shiftMonth("2026-01", -1)).toBe("2025-12"); + expect(shiftMonth("2025-12", 2)).toBe("2026-02"); + }); +}); + +describe("compactRecordsToRollups / expandRollup", () => { + test("min/max/last are per service+metric and resetsAt rides the last record", () => { + const records = [ + rec("2025-06-03T12:00:00Z", "svc-a", "weekly", 40, { resetsAt: "2025-06-08T00:00:00Z" }), + rec("2025-06-10T12:00:00Z", "svc-a", "weekly", 85, { resetsAt: "2025-06-15T00:00:00Z" }), + rec("2025-06-20T12:00:00Z", "svc-a", "weekly", 10, { resetsAt: "2025-06-22T00:00:00Z" }), + ]; + const rollups = compactRecordsToRollups("2025-06", records); + expect(rollups).toHaveLength(1); + const r = rollups[0]; + expect(r.count).toBe(3); + expect(r.valueMin).toBe(10); + expect(r.minTs).toBe("2025-06-20T12:00:00Z"); + expect(r.valueMax).toBe(85); + expect(r.valueLast).toBe(10); + expect(r.resetsAt).toBe("2025-06-22T00:00:00Z"); + const expanded = expandRollup(r); + const last = expanded[expanded.length - 1]; + expect(last.value).toBe(10); + expect(last.resetsAt).toBe("2025-06-22T00:00:00Z"); + expect(Math.min(...expanded.map((e) => e.value as number))).toBe(10); + expect(Math.max(...expanded.map((e) => e.value as number))).toBe(85); + }); + + test("estimate pairs compact by low/high and expand back to pairs", () => { + const records: SnapshotRecord[] = [ + { ts: "2025-06-02T12:00:00Z", serviceId: "svc-c", metricId: "payg-estimate", value: { low: 1, high: 5 }, unit: "usd-est", source: "estimate", observedBy: "test" }, + { ts: "2025-06-12T12:00:00Z", serviceId: "svc-c", metricId: "payg-estimate", value: { low: 3, high: 4 }, unit: "usd-est", source: "estimate", observedBy: "test" }, + ]; + const [r] = compactRecordsToRollups("2025-06", records); + expect(r.valueMin).toEqual({ low: 1, high: 5 }); + expect(r.valueLast).toEqual({ low: 3, high: 4 }); + expect(expandRollup(r).length).toBeGreaterThan(0); + }); +}); + +describe("SnapshotStore.compact", () => { + test("compacts eligible months, keeps recent raw, stays readable, idempotent", async () => { + const dir = await mkdtemp(join(tmpdir(), "snap-retention-")); + try { + await seedStore(dir); + const store = new SnapshotStore(dir); + + // Dry run first: report only, disk untouched. + const dry = await store.compact({ now: NOW, dryRun: true }); + expect(dry.cutoffMonth).toBe("2025-09"); + expect(dry.months.map((m) => m.month)).toEqual(["2025-06", "2025-09"]); + const june = dry.months[0]; + expect(june.recordsBefore).toBe(5); + expect(june.recordsAfter).toBe(2); + expect(june.perService["svc-a"]).toEqual({ before: 3, after: 1 }); + expect(june.perService["svc-b"]).toEqual({ before: 2, after: 1 }); + expect((await readdir(dir)).sort()).toEqual([ + "usage-2025-06.jsonl", + "usage-2025-09.jsonl", + "usage-2025-10.jsonl", + ]); + + // Real run. + const report = await store.compact({ now: NOW }); + expect(report.months).toHaveLength(2); + const names = (await readdir(dir)).sort(); + expect(names).toEqual([ + rollupFileFor("2025-06"), + rollupFileFor("2025-09"), + "usage-2025-10.jsonl", + ]); + + // The existing reading path reads the compacted store: svc-a's + // last June value and its resetsAt survive, the max is visible, + // and the October raw record is untouched. + const all = await store.readAll(); + const svcA = all.filter((r) => r.serviceId === "svc-a"); + expect(svcA.map((r) => r.value)).toContain(85); // June max preserved + expect(svcA.map((r) => r.value)).toContain(66); // October raw + const juneLast = svcA.filter((r) => r.ts.startsWith("2025-06")).at(-1); + expect(juneLast?.value).toBe(10); + expect(juneLast?.resetsAt).toBe("2025-06-22T00:00:00Z"); + const grouped = await store.byService(); + expect(grouped["svc-b"].map((r) => r.value)).toEqual([7, 9]); + + // Idempotent: a second run reports the months unchanged in + // effect (no raw records left to fold) and the files are + // byte-identical. + const rollupBefore = await readFile(join(dir, rollupFileFor("2025-06")), "utf8"); + const second = await store.compact({ now: NOW }); + expect(second.months.every((m) => m.recordsBefore === m.recordsAfter || m.unchanged)).toBe(true); + expect(await readFile(join(dir, rollupFileFor("2025-06")), "utf8")).toBe(rollupBefore); + expect((await store.readAll()).length).toBe(all.length); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + + test("a store with only recent data is a no-op", async () => { + const dir = await mkdtemp(join(tmpdir(), "snap-retention-")); + try { + await writeFile( + join(dir, "usage-2026-10.jsonl"), + JSON.stringify(rec("2026-10-05T12:00:00Z", "svc-a", "weekly", 12)) + "\n", + ); + const report = await new SnapshotStore(dir).compact({ now: NOW }); + expect(report.months).toEqual([]); + expect(await readdir(dir)).toEqual(["usage-2026-10.jsonl"]); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); + +describe("Codex review regressions (PR #2379)", () => { + test("append stays deduped after compaction: replaying a batch appends nothing", async () => { + const dir = await mkdtemp(join(tmpdir(), "snap-retention-")); + try { + const store = new SnapshotStore(dir); + const batch = [1, 2, 3, 4].map((v, i) => + rec(`2025-06-0${i + 2}T12:00:00Z`, "svc-a", "weekly", v), + ); + expect(await store.append(batch)).toBe(4); + await store.compact({ now: NOW }); + // The batch's non-extreme observations (2, 3) are no longer in + // the expanded history — only the rollup keys remember them. + expect(await store.append(batch)).toBe(0); + expect((await readdir(dir)).filter((n) => n === "usage-2025-06.jsonl")).toEqual([]); + expect((await store.rollupKeys()).length).toBe(4); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + + test("late records merge quota metadata on its own clock, matching one-pass compaction", async () => { + const dir = await mkdtemp(join(tmpdir(), "snap-retention-")); + const dir2 = await mkdtemp(join(tmpdir(), "snap-retention-")); + try { + const late = rec("2025-06-20T12:00:00Z", "svc-a", "weekly", 10); + const early = rec("2025-06-02T12:00:00Z", "svc-a", "weekly", 40, { + limit: 100, + resetsAt: "2025-06-08T00:00:00Z", + }); + // Incremental: compact the late record first, then merge the early one. + const inc = new SnapshotStore(dir); + await inc.append([late]); + await inc.compact({ now: NOW }); + await inc.append([early]); + await inc.compact({ now: NOW }); + // One-pass: both records compacted together. + const one = new SnapshotStore(dir2); + await one.append([late, early]); + await one.compact({ now: NOW }); + const incRollups = await readFile(join(dir, rollupFileFor("2025-06")), "utf8"); + const oneRollups = await readFile(join(dir2, rollupFileFor("2025-06")), "utf8"); + expect(JSON.parse(incRollups)).toEqual(JSON.parse(oneRollups)); + const last = (await inc.readAll()).at(-1); + expect(last?.resetsAt).toBe("2025-06-08T00:00:00Z"); + expect(last?.limit).toBe(100); + } finally { + await rm(dir, { recursive: true, force: true }); + await rm(dir2, { recursive: true, force: true }); + } + }); + + test("a malformed rollup line (missing timestamps) never poisons readAll", async () => { + const dir = await mkdtemp(join(tmpdir(), "snap-retention-")); + try { + await writeFile( + join(dir, rollupFileFor("2025-06")), + JSON.stringify({ + kind: "snapshot-rollup/v1", + month: "2025-06", + serviceId: "svc-a", + metricId: "weekly", + unit: "pct", + source: "api", + count: 3, + valueMin: 1, + valueMax: 1, + valueLast: 1, + }) + "\n", + ); + await writeFile( + join(dir, "usage-2026-10.jsonl"), + JSON.stringify(rec("2026-10-05T12:00:00Z", "svc-a", "weekly", 12)) + "\n", + ); + const all = await new SnapshotStore(dir).readAll(); + expect(all).toHaveLength(1); + expect(all[0].value).toBe(12); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + + test("concurrent append + compact lose no observations", async () => { + const dir = await mkdtemp(join(tmpdir(), "snap-retention-")); + try { + const a = new SnapshotStore(dir); + const b = new SnapshotStore(dir); + const batches = Array.from({ length: 6 }, (_, i) => [ + rec(`2025-06-1${i}T12:00:00Z`, "svc-a", "weekly", i + 1), + ]); + await Promise.all([ + (async () => { + for (const batch of batches) await a.append(batch); + })(), + (async () => { + for (let i = 0; i < 6; i++) await b.compact({ now: NOW }); + })(), + ]); + await b.compact({ now: NOW }); + // Every appended observation is durably remembered exactly once. + expect((await b.rollupKeys()).length).toBe(6); + const rollupText = await readFile(join(dir, rollupFileFor("2025-06")), "utf8"); + expect(JSON.parse(rollupText).count).toBe(6); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); + +describe("withSnapshotStoreLock stale reclamation (PR #2379 Codex round 2)", () => { + test("concurrent reclaimers of an abandoned lock never overlap critical sections", async () => { + // Regression: reclamation used to rm the lock path unconditionally, + // so a slower reclaimer could delete the fresh lock a faster one + // had just acquired and both critical sections ran at once. + for (let trial = 0; trial < 20; trial++) { + const dir = await mkdtemp(join(tmpdir(), "snap-lock-")); + try { + const lockPath = join(dir, ".snapshots.lock"); + await writeFile(lockPath, "dead-holder"); + const past = new Date(Date.now() - 10 * 60_000); + await utimes(lockPath, past, past); + let active = 0; + let maxActive = 0; + await Promise.all( + Array.from({ length: 6 }, () => + withSnapshotStoreLock(dir, async () => { + active++; + maxActive = Math.max(maxActive, active); + await new Promise((r) => setTimeout(r, 5)); + active--; + }), + ), + ); + expect(maxActive).toBe(1); + } finally { + await rm(dir, { recursive: true, force: true }); + } + } + }); + + test("both lockfiles abandoned: concurrent reclaimers all complete, never overlap", async () => { + // Regression (Codex round 3): when BOTH the main lock and the + // reclaim guard were abandoned, a reclaimer could rename a fresh + // guard another contender had just acquired and link it back + // after its owner had already released it — recreating an + // ownerless guard that stalled everyone else into a lock + // timeout. Seeding both files stale and running twelve + // concurrent 2 ms callbacks reproduced the timeout. + for (let trial = 0; trial < 20; trial++) { + const dir = await mkdtemp(join(tmpdir(), "snap-lock-")); + try { + const past = new Date(Date.now() - 10 * 60_000); + for (const name of [".snapshots.lock", ".snapshots.reclaim.guard"]) { + const f = join(dir, name); + await writeFile(f, "dead-holder"); + await utimes(f, past, past); + } + let active = 0; + let maxActive = 0; + await Promise.all( + Array.from({ length: 12 }, () => + withSnapshotStoreLock(dir, async () => { + active++; + maxActive = Math.max(maxActive, active); + await new Promise((r) => setTimeout(r, 2)); + active--; + }), + ), + ); + expect(maxActive).toBe(1); + // No guard, lock, reclaim, or tombstone debris is left behind. + expect(await readdir(dir)).toEqual([]); + } finally { + await rm(dir, { recursive: true, force: true }); + } + } + }, 30_000); +});