From 08091e7f0196c2af6c63a9a2034291eed30a07c4 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 18 Nov 2026 07:11:41 -0600 Subject: [PATCH 1/3] feat(pm-stack): sample SLO budgets on health page (#9988) --- doc/fleet-schedule-registry.md | 10 ++ pm-stack/aggregator/src/config.ts | 7 + pm-stack/aggregator/src/health.ts | 7 + pm-stack/aggregator/src/render.ts | 22 +++ pm-stack/aggregator/src/server.ts | 43 ++++++ pm-stack/aggregator/src/slo-journal.ts | 48 +++++++ pm-stack/aggregator/src/slo-sampler.ts | 61 +++++++++ pm-stack/aggregator/src/slo.ts | 126 ++++++++++++++++++ pm-stack/aggregator/test/overview.test.ts | 1 + .../aggregator/test/slo-health-render.test.ts | 75 +++++++++++ pm-stack/aggregator/test/slo-journal.test.ts | 52 ++++++++ pm-stack/aggregator/test/slo-sampler.test.ts | 87 ++++++++++++ pm-stack/aggregator/test/slo.test.ts | 39 ++++++ 13 files changed, 578 insertions(+) create mode 100644 pm-stack/aggregator/src/slo-journal.ts create mode 100644 pm-stack/aggregator/src/slo-sampler.ts create mode 100644 pm-stack/aggregator/src/slo.ts create mode 100644 pm-stack/aggregator/test/slo-health-render.test.ts create mode 100644 pm-stack/aggregator/test/slo-journal.test.ts create mode 100644 pm-stack/aggregator/test/slo-sampler.test.ts create mode 100644 pm-stack/aggregator/test/slo.test.ts diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index e1b221034e..50fe192e4d 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -332,3 +332,13 @@ review, not silently normalised. | ----------------------------------------------------------------------- | --------------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------- | ---------- | ----------- | | `bws-freshness` (`.github/workflows/bws-freshness.yml`) | developing-today/code | `23 6 * * *` (daily 06:23 UTC) + `workflow_dispatch` | enabled (fixture tests); live check gated off pending a secure credentialed runner (`BWS_FRESHNESS_ENABLED`) | issue #5451 | `.github/workflows/bws-freshness.yml`; check implementation `lib/bws-to-sops.sh --check` | not recorded | Disable the schedule if the fixture tests fail on main repeatedly or the drift-issue automation misfires | 2026-11-05 | 2026-11-05 | | `dispatch-health-probe` (`.github/workflows/dispatch-health-probe.yml`) | developing-today/code | `*/30 * * * *` (every 30 min UTC) + `workflow_dispatch` | enabled; outside probe of dispatch.security.cab — opens/updates one `meta/dispatch-probe` alert issue on failure, comments + closes it on recovery | issue #6992 | `.github/workflows/dispatch-health-probe.yml` | not recorded | Disable the schedule if the probe misfires (repeated false alerts) or dispatch.security.cab is retired | 2026-11-11 | 2026-11-11 | + +## Surface 5 — PM-stack process intervals + +Recurring loops owned by the PM-stack aggregator process. These are not +external scheduler surfaces; this inventory records timers that run only +while the service is alive. + +| name/id | repo/scope | cadence | state | owner / scope | prompt/brief pointer | budget | kill criteria | created | last review | +| ------- | ---------- | ------- | ----- | ------------- | -------------------- | ------ | ------------- | ------- | ----------- | +| SLO journal sampler (#9988) | developing-today/code | every 60 seconds | live aggregator process only | issue #9988 | `pm-stack/aggregator/src/server.ts` (`SLO_SAMPLE_INTERVAL_MS`) | not recorded | Remove/disable if the health view or append-only journal becomes unavailable; sampler is unref'd and does not keep the process alive | 2026-11-18 | 2026-11-18 | diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index e6e2e5252e..6973536cb7 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -108,6 +108,9 @@ export interface Config { * (#3984) derives from: one cutoff per line, read via * ItemHistoryStore. */ itemHistoryFile: string; + /** Append-only SLO sample journal (#9988): one facet sample per minute, + * read back for the error-budget display on /health. */ + sloJournalFile: string; /** The stewardship quota view; the hub's live fallback source when the * fleet feed carries no saas/payg sections yet (hub §2.3). */ quotaViewFile: string; @@ -276,6 +279,10 @@ export function loadConfig(env: Record = process.env env.PM_AGG_ITEM_HISTORY_FILE, join(homedir(), ".local", "state", "pm-aggregator", "item-history.jsonl"), ), + sloJournalFile: s( + env.PM_AGG_SLO_JOURNAL_FILE, + join(homedir(), ".local", "state", "pm-aggregator", "slo-journal.jsonl"), + ), coverageSnapshotFile: s(env.PM_AGG_COVERAGE_SNAPSHOT_FILE, join(process.cwd(), "coverage-snapshot.json")), openchamberStateFile: s( env.PM_AGG_OPENCHAMBER_STATE, diff --git a/pm-stack/aggregator/src/health.ts b/pm-stack/aggregator/src/health.ts index bc4cc2ba52..ebacd14492 100644 --- a/pm-stack/aggregator/src/health.ts +++ b/pm-stack/aggregator/src/health.ts @@ -31,6 +31,7 @@ import { import type { GhItem, ProvenanceDetail, QuotaView, RefKey } from "./model.ts"; import type { PushHealthView } from "./freshness-reconcile.ts"; import { PAGES } from "./pages.ts"; +import type { SloFacetSummary } from "./slo.ts"; import { buildServices, type ServiceDef } from "./topology.ts"; import { fetchRfaState, @@ -254,6 +255,9 @@ export interface HealthView { * quiet source is not an outage. Null when the caller did not * assemble it (fixtures mode, older call sites) — never invented. */ push: PushHealthView | null; + /** #9988: per-facet error-budget summaries read from the SLO journal. + * Null when the caller did not assemble them (fixtures mode). */ + slo: SloFacetSummary[] | null; } // --- Render registry ------------------------------------------------------- @@ -413,6 +417,8 @@ export interface HealthInputs { /** #3976: the reconciler's current push-health view (server.ts * supplies it in live mode); absent/null renders as unassembled. */ pushHealth?: PushHealthView | null; + /** #9988: SLO budget summaries from the journal (server.ts supplies them in live mode). */ + slo?: SloFacetSummary[] | null; } export interface HealthDeps { @@ -601,6 +607,7 @@ export async function buildHealth(inputs: HealthInputs, deps: HealthDeps = {}): pages: pageHealth(now), rfa, push: inputs.pushHealth ?? null, + slo: inputs.slo ?? null, facets: inputs.detail ?? null, itemsCoverage: inputs.itemsCoverage ?? null, comments: inputs.comments ?? { pendingMessages: 0, pendingGithub: 0, total: 0 }, diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 2dfcf861e1..77fd4cd5f4 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -6508,6 +6508,27 @@ export function renderHealth(view: HealthView, provenance: Provenance): string {
${esc(push.state)} \u2014 ${esc(push.detail)}
last event ${push.lastEventAt ? esc(ageMsText(Math.max(0, nowMs - Date.parse(push.lastEventAt)))) : "none recorded"} \u00b7 last successful reconcile ${push.lastSuccessfulReconcileAt ? esc(ageMsText(Math.max(0, nowMs - Date.parse(push.lastSuccessfulReconcileAt)))) : "never in this process"} \u00b7 journal cursor ${push.cursor ?? "unknown"} \u00b7 gaps: ${push.gaps.open} open \u00b7 ${push.gaps.repairedTotal} repaired by reconciliation \u00b7 ${push.gaps.resetsTotal} journal reset(s)${push.gaps.lastResetAt ? ` (last ${esc(push.gaps.lastResetAt)})` : ""}
${push.sources.map((s) => ``).join("")}
Push sources \u2014 freshness is per source; a quiet source is silent, not an outage
SourceStateLast eventAgeLagNotices
${esc(s.source)}${esc(s.state)}${s.missingNotice ? ' \u00b7 notice missing \u2014 gap open' : ""}${s.lastEventAt ? esc(s.lastEventAt) : "\u2014"}${s.ageMs !== null ? esc(ageMsText(s.ageMs)) : "\u2014"}${s.lagMs !== null ? esc(ageMsText(s.lagMs)) : "\u2014"}${s.notices}
` : `

Push health \u2014 event-driven freshness (#3976)

\n

Push health is not assembled in this mode \u2014 no state is invented for it.

`; + const sloRows = (view.slo ?? []) + .map((s) => { + const current = !s.sourced + ? `unknown / no signal source` + : s.currentValue !== null + ? esc(ageMsText(s.currentValue)) + : s.latestBad === null + ? `\u2014` + : s.latestBad + ? "down" + : "up"; + const remaining = s.budgetRemainingPercent === null ? "\u2014" : `${s.budgetRemainingPercent.toFixed(1)}%`; + const burn = s.burnRate1h === null ? "\u2014" : s.burnRate1h.toFixed(2); + return `${esc(s.label)}${esc(s.target)}${current}${remaining}${burn}${esc(s.state)}`; + }) + .join(""); + const sloSection = view.slo + ? `

SLO error budgets (#9988)

+

Each minute the health view is sampled into an append-only journal. Budgets are computed over each facet's rolling window; a facet with no signal source is shown as unknown, never as good.

+
${sloRows}
SLO error budgets \u2014 remaining budget and 1-hour burn rate per facet
FacetTargetCurrentBudget remaining1h burnState
` + : ""; const cov = view.itemsCoverage; const coverageLine = cov && cov.total > 0 @@ -6543,6 +6564,7 @@ ${degraded}${modeNote}
${serviceRows}
Services, ports, and topology
ServicePortBindRuns asStateConsumed byIf it is down
${rfaSection} ${pushSection} +${sloSection}

Feed sections

${sectionRows}
Feed sections — presence, age, lag, and last sync
SectionPresentAgeBehind byLast syncLag noteNote

Quota gatherer sources

diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 77067aca89..f8aef2b5c1 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -229,6 +229,9 @@ import { dispatchStateFor, fetchRfaState, RFA_NOT_PICKED_UP } from "./sources/re import { TodayCache, TODAY_CACHE_TTL_MS } from "./today-cache.ts"; import { boardJsonBody, boardJsonViewBody } from "./board-json.ts"; import { ItemHistoryStore } from "./item-history.ts"; +import { SloJournal, groupSamplesByFacet } from "./slo-journal.ts"; +import { sampleSloFacets } from "./slo-sampler.ts"; +import { SLO_DEFINITIONS, summarizeSloFacet, type SloFacetSummary } from "./slo.ts"; import { computeFlowAnalytics } from "./flow-analytics.ts"; import { FORECAST_CONTRACT_VERSION, @@ -255,6 +258,8 @@ const commentsStore = new CommentsStore(cfg.commentsFile); const roadmapAnnotationsStore = new RoadmapAnnotationsStore(cfg.roadmapAnnotationsFile); const coverageStore = new CoverageSnapshotStore(cfg.coverageSnapshotFile); const itemHistoryStore = new ItemHistoryStore(cfg.itemHistoryFile); +const sloJournal = new SloJournal(cfg.sloJournalFile); +let sloSummaryCache: { at: number; value: SloFacetSummary[] } | null = null; const spendRollupStore = new SpendRollupStore(cfg.snapshotsDir); /** #4824: the Projects/Roadmap spend-beside-progress view over the * #4823 rollup store. A failed read renders no spend block (the @@ -580,9 +585,23 @@ async function healthContext(prime = true): Promise { comments: await commentsStore.pendingCounts().catch(() => undefined), conflicts: await assembleConflicts().catch(() => null), pushHealth: cfg.source === "fixtures" ? null : freshnessReconciler.health(new Date()), + slo: cfg.source === "fixtures" ? null : await sloSummaries(), }); } +// SLO error budgets (#9988): summaries are read from the append-only journal +// and cached for a minute, the same cadence the sampler writes at. +const SLO_SUMMARY_CACHE_MS = 60_000; +async function sloSummaries(nowMs = Date.now()): Promise { + if (sloSummaryCache && nowMs - sloSummaryCache.at < SLO_SUMMARY_CACHE_MS) return sloSummaryCache.value; + const byFacet = groupSamplesByFacet(await sloJournal.readAll().catch(() => [])); + const value = SLO_DEFINITIONS.map((definition) => + summarizeSloFacet(definition, byFacet.get(definition.id) ?? [], nowMs), + ); + sloSummaryCache = { at: nowMs, value }; + return value; +} + /** The identities half of the comment form options, behind a * stale-while-revalidate cache (#5082, 2026-11-14). commentFormOpts * is awaited on the request path of /program, /api/program.json and @@ -4455,6 +4474,30 @@ if (githubHotListConsumer) { }); } +// SLO sampler (#9988): one sample per facet per minute, appended to the +// journal from the same health view /health renders. Live mode only. +const SLO_SAMPLE_INTERVAL_MS = 60_000; +if (cfg.source !== "fixtures") { + let sloSampling = false; + const sampleSlo = async (): Promise => { + if (sloSampling) return; + sloSampling = true; + try { + const view = await healthContext(false); + await sloJournal.append(sampleSloFacets(view, Date.now())); + } catch (error) { + console.error( + `[slo] WARNING: SLO sample failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } finally { + sloSampling = false; + } + }; + void sampleSlo(); + const timer = setInterval(() => void sampleSlo(), SLO_SAMPLE_INTERVAL_MS); + timer.unref?.(); +} + // The alert throat's engine (#3676): the ~60s delivery/escalation // tick (live mode only, fail-soft — see src/alerts.ts). startAlertEngine(cfg, async (): Promise => { diff --git a/pm-stack/aggregator/src/slo-journal.ts b/pm-stack/aggregator/src/slo-journal.ts new file mode 100644 index 0000000000..ff36a7208d --- /dev/null +++ b/pm-stack/aggregator/src/slo-journal.ts @@ -0,0 +1,48 @@ +import { appendFile, mkdir, readFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import type { SloSample } from "./slo.ts"; + +/** One append-only line in the SLO journal (#9988): one facet's sample for + * one minute. The journal never rewrites or compacts a line. */ +export interface SloJournalLine extends SloSample { + facet: string; +} + +export class SloJournal { + private writes: Promise = Promise.resolve(); + + constructor(private readonly file: string) {} + + append(lines: readonly SloJournalLine[]): Promise { + if (lines.length === 0) return this.writes; + const payload = lines.map((line) => `${JSON.stringify(line)}\n`).join(""); + this.writes = this.writes.then(async () => { + await mkdir(dirname(this.file), { recursive: true }); + await appendFile(this.file, payload, "utf8"); + }); + return this.writes; + } + + async readAll(): Promise { + await this.writes; + const raw = await readFile(this.file, "utf8").catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return ""; + throw error; + }); + return raw + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as SloJournalLine); + } +} + +export function groupSamplesByFacet(lines: readonly SloJournalLine[]): Map { + const byFacet = new Map(); + for (const { facet, atMs, bad, value } of lines) { + const list = byFacet.get(facet); + const sample: SloSample = { atMs, bad, value }; + if (list) list.push(sample); + else byFacet.set(facet, [sample]); + } + return byFacet; +} diff --git a/pm-stack/aggregator/src/slo-sampler.ts b/pm-stack/aggregator/src/slo-sampler.ts new file mode 100644 index 0000000000..15d43f1758 --- /dev/null +++ b/pm-stack/aggregator/src/slo-sampler.ts @@ -0,0 +1,61 @@ +import type { HealthView, ServiceHealth } from "./health.ts"; +import type { SloJournalLine } from "./slo-journal.ts"; + +const MINUTE = 60_000; + +/** Per-facet bad thresholds, mirroring the SLO targets in slo.ts and the + * design note. Age facets are bad past their threshold; up facets are bad + * when a probed service answers not-ok. A facet with no probe or no age + * source records bad: null so it is excluded, never called good. */ +const FEED_BAD_AGE_MS = 10 * MINUTE; +const QUOTA_BAD_AGE_MS = 75 * MINUTE; +const ORCHESTRATION_BAD_AGE_MS = 90 * MINUTE; + +function serviceOk(view: HealthView, ids: readonly string[]): boolean | null { + const rows: ServiceHealth[] = ids.map((id) => view.services.find((s) => s.def.id === id)).filter( + (s): s is ServiceHealth => s !== undefined, + ); + if (rows.length !== ids.length) return null; + if (rows.some((s) => s.ok === false)) return false; + if (rows.every((s) => s.ok === true)) return true; + return null; +} + +function upSample(ids: readonly string[], view: HealthView): { bad: boolean | null; value: null } { + const ok = serviceOk(view, ids); + return { bad: ok === null ? null : !ok, value: null }; +} + +/** Sample every SLO facet once from an assembled health view (#9988). Pure: + * the caller supplies the view and the minute timestamp. */ +export function sampleSloFacets(view: HealthView, atMs: number): SloJournalLine[] { + const quotaAgeMs = view.quotaGatherer ? Math.max(0, atMs - Date.parse(view.quotaGatherer.generatedAt)) : null; + const orchestrationAgeMs = view.jobs.orchestration.ageMs ?? null; + const feedAgeMs = view.feed.ageMs; + const facets: SloJournalLine[] = [ + { + facet: "feed-age", + atMs, + value: feedAgeMs, + bad: feedAgeMs === null ? null : feedAgeMs > FEED_BAD_AGE_MS, + }, + { + facet: "quota-age", + atMs, + value: quotaAgeMs, + bad: quotaAgeMs === null ? null : quotaAgeMs > QUOTA_BAD_AGE_MS, + }, + { + facet: "orchestration-age", + atMs, + value: orchestrationAgeMs, + bad: orchestrationAgeMs === null ? null : orchestrationAgeMs > ORCHESTRATION_BAD_AGE_MS, + }, + { facet: "aggregator-up", atMs, ...upSample(["aggregator"], view) }, + { facet: "intake-up", atMs, ...upSample(["intake"], view) }, + { facet: "projector-up", atMs, ...upSample(["projector"], view) }, + { facet: "pad-grist-up", atMs, ...upSample(["pad", "grist"], view) }, + { facet: "tunnel-up", atMs, ...upSample(["tunnel"], view) }, + ]; + return facets; +} diff --git a/pm-stack/aggregator/src/slo.ts b/pm-stack/aggregator/src/slo.ts new file mode 100644 index 0000000000..f0451f364d --- /dev/null +++ b/pm-stack/aggregator/src/slo.ts @@ -0,0 +1,126 @@ +/** Pure SLO budget calculations for the watchdog health surface (#9988). + * The journal/sampler owns completeness; this module applies the design's + * one-minute sample semantics without inventing values for age facets. */ +export type SloSample = { + atMs: number; + bad: boolean | null; + value: number | null; +}; + +export type SloDefinition = { + id: string; + label: string; + target: string; + budgetFraction: number; + windowMs: number; + missing: "bad" | "unknown"; + /** Bad samples beyond this threshold consume extra budget minutes. */ + doubleBadAbove?: number; +}; + +const DAY = 86_400_000; +const MINUTE = 60_000; +const THIRTY_DAYS = 30 * DAY; + +export const SLO_DEFINITIONS: readonly SloDefinition[] = [ + { id: "feed-age", label: "Feed age", target: "p95 ≤ 10 min; none > 30 min", budgetFraction: 0.005, windowMs: 7 * DAY, missing: "unknown", doubleBadAbove: 30 * MINUTE }, + { id: "quota-age", label: "Quota read age", target: "p99 ≤ 75 min", budgetFraction: 0.01, windowMs: THIRTY_DAYS, missing: "unknown" }, + { id: "orchestration-age", label: "Orchestration freshness", target: "p99 ≤ 90 min", budgetFraction: 0.01, windowMs: THIRTY_DAYS, missing: "unknown" }, + { id: "aggregator-up", label: "Aggregator", target: "99.5% of minutes", budgetFraction: 0.005, windowMs: THIRTY_DAYS, missing: "bad" }, + { id: "intake-up", label: "Intake", target: "99.5% of minutes", budgetFraction: 0.005, windowMs: THIRTY_DAYS, missing: "bad" }, + { id: "projector-up", label: "Projector", target: "99.5% of minutes", budgetFraction: 0.005, windowMs: THIRTY_DAYS, missing: "bad" }, + { id: "pad-grist-up", label: "Pad / Grist", target: "99% of minutes", budgetFraction: 0.01, windowMs: THIRTY_DAYS, missing: "bad" }, + { id: "tunnel-up", label: "Tunnel", target: "99.9% of minutes", budgetFraction: 0.001, windowMs: THIRTY_DAYS, missing: "bad" }, +]; + +export type SloBudget = { + currentValue: number | null; + target: string; + budgetRemainingPercent: number | null; + burnRate1h: number | null; + state: "ok" | "burning" | "exhausted" | "unknown"; + badMinutes: number; + budgetMinutes: number; + unknownSamples: number; +}; + +/** Compute budget from observations in the rolling window. A missing minute + * is explicitly charged for up facets and excluded-but-counted for age facets. */ +export function computeSloBudget( + definition: SloDefinition, + samples: readonly SloSample[], + nowMs: number, + observedSinceMs?: number, +): SloBudget { + const start = nowMs - definition.windowMs; + const inWindow = samples.filter((s) => s.atMs > start && s.atMs <= nowMs).slice().sort((a, b) => a.atMs - b.atMs); + const windowStart = observedSinceMs === undefined ? start : Math.max(start, observedSinceMs - MINUTE); + const firstExpected = Math.floor(windowStart / MINUTE) * MINUTE + MINUTE; + const lastExpected = Math.floor(nowMs / MINUTE) * MINUTE; + const expected = Math.max(0, Math.floor((lastExpected - firstExpected) / MINUTE) + 1); + const seen = new Set(inWindow.map((s) => Math.floor(s.atMs / MINUTE) * MINUTE)); + let missing = Math.max(0, expected - seen.size); + let unknownSamples = 0; + let badMinutes = 0; + const badLastHour = new Set(); + for (const sample of inWindow) { + const minute = Math.floor(sample.atMs / MINUTE) * MINUTE; + if (sample.bad === null) { + unknownSamples++; + continue; + } + if (!sample.bad) continue; + const weight = definition.doubleBadAbove !== undefined && sample.value !== null && sample.value > definition.doubleBadAbove ? 2 : 1; + badMinutes += weight; + if (sample.atMs > nowMs - 60 * MINUTE) badLastHour.add(minute); + } + if (definition.missing === "bad") { + badMinutes += missing; + for (let at = firstExpected; at <= lastExpected; at += MINUTE) { + if (!seen.has(at) && at > nowMs - 60 * MINUTE) badLastHour.add(at); + } + } else { + unknownSamples += missing; + } + const budgetMinutes = Math.floor((definition.windowMs / MINUTE) * definition.budgetFraction); + const remaining = definition.missing === "unknown" && expected > 0 && unknownSamples / expected > 0.5 + ? null + : Math.max(0, 100 * (1 - badMinutes / budgetMinutes)); + const burnRate1h = budgetMinutes > 0 ? (badLastHour.size / 60) / (budgetMinutes / (definition.windowMs / MINUTE)) : null; + return { + currentValue: inWindow.at(-1)?.value ?? null, + target: definition.target, + budgetRemainingPercent: remaining, + burnRate1h, + state: remaining === null ? "unknown" : remaining <= 0 ? "exhausted" : badLastHour.size > 0 ? "burning" : "ok", + badMinutes, + budgetMinutes, + unknownSamples, + }; +} + +export type SloFacetSummary = SloBudget & { + id: string; + label: string; + /** False when no sample in the window carries a real signal (for example + * a facet whose probe is not wired yet); such facets show no budget. */ + sourced: boolean; + latestBad: boolean | null; +}; + +export function summarizeSloFacet(definition: SloDefinition, samples: readonly SloSample[], nowMs: number): SloFacetSummary { + const inWindow = samples.filter((s) => s.atMs > nowMs - definition.windowMs && s.atMs <= nowMs); + const sourced = inWindow.some((s) => s.bad !== null); + const earliest = inWindow.reduce((min, s) => (min === undefined || s.atMs < min ? s.atMs : min), undefined); + const budget = computeSloBudget(definition, inWindow, nowMs, earliest); + const latest = inWindow.reduce((last, s) => (last === undefined || s.atMs > last.atMs ? s : last), undefined); + return { + ...budget, + id: definition.id, + label: definition.label, + sourced, + latestBad: latest?.bad ?? null, + budgetRemainingPercent: sourced ? budget.budgetRemainingPercent : null, + state: sourced ? budget.state : "unknown", + }; +} diff --git a/pm-stack/aggregator/test/overview.test.ts b/pm-stack/aggregator/test/overview.test.ts index cc74d93e43..69d273b162 100644 --- a/pm-stack/aggregator/test/overview.test.ts +++ b/pm-stack/aggregator/test/overview.test.ts @@ -35,6 +35,7 @@ const health: HealthView = { comments: { pendingMessages: 0, pendingGithub: 0, total: 0 }, conflicts: null, push: null, + slo: null, rfa: { state: "fixtures", detail: "fixtures mode — no live harness read", repositories: [], backends: [] }, }; diff --git a/pm-stack/aggregator/test/slo-health-render.test.ts b/pm-stack/aggregator/test/slo-health-render.test.ts new file mode 100644 index 0000000000..b75cfdb6aa --- /dev/null +++ b/pm-stack/aggregator/test/slo-health-render.test.ts @@ -0,0 +1,75 @@ +import { expect, test } from "bun:test"; +import { loadConfig } from "../src/config.ts"; +import { buildHealth, createProbeCache, type HealthInputs, type ProbeFetch } from "../src/health.ts"; +import type { FleetFeed } from "../src/feed.ts"; +import { renderHealth } from "../src/render.ts"; + +const NOW = Date.parse("2026-11-18T00:00:00Z"); +const config = loadConfig({ PM_AGG_DEV: "1" }); +const feed: FleetFeed = { + version: 1, + generatedAt: new Date(NOW).toISOString(), + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + orchestration: { + version: 1, + generatedAt: new Date(NOW).toISOString(), + runId: "slo-render-test", + provenance: { sources: ["test"] }, + tiers: { needsDrew: [], needsOrchestrator: [] }, + dependencies: [], + goals: [], + actions: [], + }, +} as unknown as FleetFeed; + +test("health page renders SLO targets, current values, budgets, burn, and unknown state", async () => { + const fetcher: ProbeFetch = async () => ({ status: 200 }); + const inputs: HealthInputs = { + mode: "live", + cfg: config, + feed, + feedFileMtimeMs: NOW, + }; + const view = await buildHealth(inputs, { + fetcher, + cache: createProbeCache(), + now: NOW, + }); + view.slo = [ + { + id: "feed-age", + label: "Feed age", + target: "p95 ≤ 10 min", + sourced: true, + currentValue: 120_000, + latestBad: false, + budgetRemainingPercent: 98.5, + burnRate1h: 0.25, + state: "ok", + badMinutes: 1, + budgetMinutes: 216, + unknownSamples: 0, + }, + { + id: "tunnel-up", + label: "Tunnel", + target: "99.9% of minutes", + sourced: false, + currentValue: null, + latestBad: null, + budgetRemainingPercent: null, + burnRate1h: null, + state: "unknown", + badMinutes: 0, + budgetMinutes: 43, + unknownSamples: 0, + }, + ]; + + const html = renderHealth(view, {} as Parameters[1]); + expect(html).toContain("SLO error budgets (#9988)"); + expect(html).toContain("Feed agep95 ≤ 10 min2m old98.5%0.25ok"); + expect(html).toContain("Tunnel99.9% of minutesunknown / no signal source"); + expect(html).toContain("——unknown"); +}); diff --git a/pm-stack/aggregator/test/slo-journal.test.ts b/pm-stack/aggregator/test/slo-journal.test.ts new file mode 100644 index 0000000000..6af625ba1e --- /dev/null +++ b/pm-stack/aggregator/test/slo-journal.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { groupSamplesByFacet, SloJournal, type SloJournalLine } from "../src/slo-journal.ts"; + +const MINUTE = 60_000; + +describe("SLO journal", () => { + test("round-trips appended lines in order and never rewrites earlier ones", async () => { + const dir = await mkdtemp(join(tmpdir(), "slo-journal-")); + try { + const file = join(dir, "nested", "slo-journal.jsonl"); + const journal = new SloJournal(file); + const first: SloJournalLine[] = [ + { facet: "feed-age", atMs: MINUTE, value: 120_000, bad: false }, + { facet: "intake-up", atMs: MINUTE, value: null, bad: null }, + ]; + const second: SloJournalLine[] = [{ facet: "feed-age", atMs: 2 * MINUTE, value: 900_000, bad: true }]; + await journal.append(first); + await journal.append(second); + + expect(await journal.readAll()).toEqual([...first, ...second]); + const raw = await readFile(file, "utf8"); + expect(raw.trimEnd().split("\n")).toHaveLength(3); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + + test("reads an absent journal as empty", async () => { + const dir = await mkdtemp(join(tmpdir(), "slo-journal-")); + try { + expect(await new SloJournal(join(dir, "missing.jsonl")).readAll()).toEqual([]); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + + test("groups samples by facet without the facet key", () => { + const grouped = groupSamplesByFacet([ + { facet: "a", atMs: 1, value: null, bad: false }, + { facet: "b", atMs: 1, value: 5, bad: true }, + { facet: "a", atMs: 2, value: null, bad: true }, + ]); + expect(grouped.get("a")).toEqual([ + { atMs: 1, value: null, bad: false }, + { atMs: 2, value: null, bad: true }, + ]); + expect(grouped.get("b")).toEqual([{ atMs: 1, value: 5, bad: true }]); + }); +}); diff --git a/pm-stack/aggregator/test/slo-sampler.test.ts b/pm-stack/aggregator/test/slo-sampler.test.ts new file mode 100644 index 0000000000..c28da6aebe --- /dev/null +++ b/pm-stack/aggregator/test/slo-sampler.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, test } from "bun:test"; +import type { HealthView } from "../src/health.ts"; +import { sampleSloFacets } from "../src/slo-sampler.ts"; + +const NOW = Date.parse("2026-11-18T12:00:00Z"); + +function service(id: string, ok: boolean | null) { + return { def: { id }, ok } as unknown as HealthView["services"][number]; +} + +function view(overrides: { + services?: HealthView["services"]; + feedAgeMs?: number | null; + quotaGeneratedAt?: string | null; + orchestrationAgeMs?: number | null; +}): HealthView { + return { + services: overrides.services ?? [], + feed: { ageMs: overrides.feedAgeMs ?? null }, + quotaGatherer: + overrides.quotaGeneratedAt === null || overrides.quotaGeneratedAt === undefined + ? null + : { generatedAt: overrides.quotaGeneratedAt }, + jobs: { orchestration: { ageMs: overrides.orchestrationAgeMs ?? null } }, + } as unknown as HealthView; +} + +const byFacet = (lines: ReturnType) => new Map(lines.map((l) => [l.facet, l])); + +describe("SLO sampler", () => { + test("age facets are bad only past their thresholds", () => { + const fresh = byFacet( + sampleSloFacets( + view({ feedAgeMs: 4 * 60_000, quotaGeneratedAt: new Date(NOW - 10 * 60_000).toISOString(), orchestrationAgeMs: 30 * 60_000 }), + NOW, + ), + ); + expect(fresh.get("feed-age")).toMatchObject({ bad: false, value: 4 * 60_000 }); + expect(fresh.get("quota-age")).toMatchObject({ bad: false, value: 10 * 60_000 }); + expect(fresh.get("orchestration-age")).toMatchObject({ bad: false }); + + const stale = byFacet( + sampleSloFacets( + view({ feedAgeMs: 11 * 60_000, quotaGeneratedAt: new Date(NOW - 80 * 60_000).toISOString(), orchestrationAgeMs: 95 * 60_000 }), + NOW, + ), + ); + expect(stale.get("feed-age")?.bad).toBe(true); + expect(stale.get("quota-age")?.bad).toBe(true); + expect(stale.get("orchestration-age")?.bad).toBe(true); + }); + + test("missing age sources record unknown, never good", () => { + const missing = byFacet(sampleSloFacets(view({}), NOW)); + expect(missing.get("feed-age")?.bad).toBeNull(); + expect(missing.get("quota-age")?.bad).toBeNull(); + expect(missing.get("orchestration-age")?.bad).toBeNull(); + }); + + test("up facets follow the probed services and are unknown when unprobed", () => { + const sampled = byFacet( + sampleSloFacets( + view({ + services: [ + service("aggregator", true), + service("projector", false), + service("pad", true), + service("grist", true), + ], + }), + NOW, + ), + ); + expect(sampled.get("aggregator-up")?.bad).toBe(false); + expect(sampled.get("projector-up")?.bad).toBe(true); + expect(sampled.get("pad-grist-up")?.bad).toBe(false); + expect(sampled.get("intake-up")?.bad).toBeNull(); + expect(sampled.get("tunnel-up")?.bad).toBeNull(); + }); + + test("emits one line per facet at the given minute", () => { + const lines = sampleSloFacets(view({}), NOW); + expect(lines).toHaveLength(8); + expect(new Set(lines.map((l) => l.facet)).size).toBe(8); + expect(lines.every((l) => l.atMs === NOW)).toBe(true); + }); +}); diff --git a/pm-stack/aggregator/test/slo.test.ts b/pm-stack/aggregator/test/slo.test.ts new file mode 100644 index 0000000000..d10c91732b --- /dev/null +++ b/pm-stack/aggregator/test/slo.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, test } from "bun:test"; +import { computeSloBudget, SLO_DEFINITIONS, type SloDefinition, type SloSample } from "../src/slo.ts"; + +const MINUTE = 60_000; +const NOW = 30 * 24 * 60 * MINUTE; +const upFacet = SLO_DEFINITIONS.find((d) => d.id === "aggregator-up")!; +const ageFacet = SLO_DEFINITIONS.find((d) => d.id === "quota-age")!; + +function sample(atMs: number, bad: boolean | null, value: number | null = null): SloSample { + return { atMs, bad, value }; +} + +describe("SLO budget calculation", () => { + test("charges missed up-facet samples as bad minutes", () => { + const result = computeSloBudget(upFacet, [sample(NOW - MINUTE, false)], NOW); + expect(result.badMinutes).toBe(30 * 24 * 60 - 1); + expect(result.state).toBe("exhausted"); + }); + + test("excludes and flags missing age samples instead of calling them good", () => { + const result = computeSloBudget(ageFacet, [sample(NOW - MINUTE, false, 20 * MINUTE)], NOW); + expect(result.badMinutes).toBe(0); + expect(result.unknownSamples).toBeGreaterThan(0); + expect(result.state).toBe("unknown"); + expect(result.budgetRemainingPercent).toBeNull(); + }); + + test("double-weights feed samples beyond 30 minutes and reports current value", () => { + const feed: SloDefinition = SLO_DEFINITIONS.find((d) => d.id === "feed-age")!; + const result = computeSloBudget(feed, [sample(NOW - MINUTE, true, 31 * MINUTE)], NOW); + expect(result.badMinutes).toBe(2); + expect(result.currentValue).toBe(31 * MINUTE); + }); + + test("calculates one-hour burn against the window's per-hour budget", () => { + const result = computeSloBudget(upFacet, [sample(NOW - MINUTE, true)], NOW); + expect(result.burnRate1h).toBe(200); // the other 59 missing minutes in the hour are bad too + }); +}); From ea686bc16f0e337c046a9620ece242dafb1fec42 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:21:36 +0000 Subject: [PATCH 2/3] docs(fleet-schedule-registry): number the PM-stack intervals Surface 6 main added Surface 5 (Mac launchd) while this branch was open. Co-Authored-By: Claude Opus 5.5 --- doc/fleet-schedule-registry.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index fb7ec31def..11eabe1091 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -19,6 +19,8 @@ specified in the #2020 Jules investigation). Jules account (pilot #2265). - **Surface 5 — Mac launchd jobs:** timed launchd daemons and agents defined in `dezren39/darwin-nix` and deployed to the Mac (#11805). +- **Surface 6 — PM-stack process intervals:** timers inside the + PM-stack aggregator process, live only while it runs (#9988). **This registry is an input to the placement audit** proposed in the #2024 framework doc @@ -342,16 +344,6 @@ review, not silently normalised. | `bws-freshness` (`.github/workflows/bws-freshness.yml`) | developing-today/code | `23 6 * * *` (daily 06:23 UTC) + `workflow_dispatch` | enabled (fixture tests); live check gated off pending a secure credentialed runner (`BWS_FRESHNESS_ENABLED`) | issue #5451 | `.github/workflows/bws-freshness.yml`; check implementation `lib/bws-to-sops.sh --check` | not recorded | Disable the schedule if the fixture tests fail on main repeatedly or the drift-issue automation misfires | 2026-11-05 | 2026-11-05 | | `dispatch-health-probe` (`.github/workflows/dispatch-health-probe.yml`) | developing-today/code | `*/30 * * * *` (every 30 min UTC) + `workflow_dispatch` | enabled; outside probe of dispatch.security.cab — opens/updates one `meta/dispatch-probe` alert issue on failure, comments + closes it on recovery | issue #6992 | `.github/workflows/dispatch-health-probe.yml` | not recorded | Disable the schedule if the probe misfires (repeated false alerts) or dispatch.security.cab is retired | 2026-11-11 | 2026-11-11 | -## Surface 5 — PM-stack process intervals - -Recurring loops owned by the PM-stack aggregator process. These are not -external scheduler surfaces; this inventory records timers that run only -while the service is alive. - -| name/id | repo/scope | cadence | state | owner / scope | prompt/brief pointer | budget | kill criteria | created | last review | -| ------- | ---------- | ------- | ----- | ------------- | -------------------- | ------ | ------------- | ------- | ----------- | -| SLO journal sampler (#9988) | developing-today/code | every 60 seconds | live aggregator process only | issue #9988 | `pm-stack/aggregator/src/server.ts` (`SLO_SAMPLE_INTERVAL_MS`) | not recorded | Remove/disable if the health view or append-only journal becomes unavailable; sampler is unref'd and does not keep the process alive | 2026-11-18 | 2026-11-18 | - ## Surface 5 — Mac launchd jobs (3 entries) Timed launchd jobs from `dezren39/darwin-nix`, deployed to the Mac by @@ -371,3 +363,13 @@ list, which its own comment says is empty unless root-owned repos are registered. The primary user's repos are maintained by git's own per-user launchd agents, which `git maintenance start` installs outside Nix; they are not recorded here until a review reads them on the Mac. + +## Surface 6 — PM-stack process intervals (1 entry) + +Recurring loops owned by the PM-stack aggregator process. These are not +external scheduler surfaces; this inventory records timers that run only +while the service is alive. + +| name/id | repo/scope | cadence | state | owner / scope | prompt/brief pointer | budget | kill criteria | created | last review | +| ------- | ---------- | ------- | ----- | ------------- | -------------------- | ------ | ------------- | ------- | ----------- | +| SLO journal sampler (#9988) | developing-today/code | every 60 seconds | live aggregator process only | issue #9988 | `pm-stack/aggregator/src/server.ts` (`SLO_SAMPLE_INTERVAL_MS`) | not recorded | Remove/disable if the health view or append-only journal becomes unavailable; sampler is unref'd and does not keep the process alive | 2026-11-18 | 2026-11-18 | From 765ecced9b6df1fcf4c32ea263afa0e37d42e243 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:22:17 +0000 Subject: [PATCH 3/3] fix(pm-stack): SLO journal survives a torn line and a failed append readAll threw on a line cut short by a crash, blanking every budget on /health; it now skips the line. A rejected append left the write chain rejected, so every later append and read failed; each write now starts from the previous one settled. Co-Authored-By: Claude Opus 5.5 --- pm-stack/aggregator/src/slo-journal.ts | 17 +++++++++-- pm-stack/aggregator/test/slo-journal.test.ts | 31 +++++++++++++++++++- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/pm-stack/aggregator/src/slo-journal.ts b/pm-stack/aggregator/src/slo-journal.ts index ff36a7208d..99991399bf 100644 --- a/pm-stack/aggregator/src/slo-journal.ts +++ b/pm-stack/aggregator/src/slo-journal.ts @@ -16,7 +16,10 @@ export class SloJournal { append(lines: readonly SloJournalLine[]): Promise { if (lines.length === 0) return this.writes; const payload = lines.map((line) => `${JSON.stringify(line)}\n`).join(""); - this.writes = this.writes.then(async () => { + // A failed append must not poison the chain: each write starts from + // the previous one settled, so one bad write does not fail every + // later append and read. + this.writes = this.writes.catch(() => undefined).then(async () => { await mkdir(dirname(this.file), { recursive: true }); await appendFile(this.file, payload, "utf8"); }); @@ -24,7 +27,7 @@ export class SloJournal { } async readAll(): Promise { - await this.writes; + await this.writes.catch(() => undefined); const raw = await readFile(this.file, "utf8").catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return ""; throw error; @@ -32,7 +35,15 @@ export class SloJournal { return raw .split("\n") .filter(Boolean) - .map((line) => JSON.parse(line) as SloJournalLine); + .flatMap((line) => { + // A line cut short by a crash mid-append is skipped, not fatal: + // one torn line must not blank every budget on /health. + try { + return [JSON.parse(line) as SloJournalLine]; + } catch { + return []; + } + }); } } diff --git a/pm-stack/aggregator/test/slo-journal.test.ts b/pm-stack/aggregator/test/slo-journal.test.ts index 6af625ba1e..ddc6ea099b 100644 --- a/pm-stack/aggregator/test/slo-journal.test.ts +++ b/pm-stack/aggregator/test/slo-journal.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { groupSamplesByFacet, SloJournal, type SloJournalLine } from "../src/slo-journal.ts"; @@ -37,6 +37,35 @@ describe("SLO journal", () => { } }); + test("skips a torn line and keeps appending after a failed write", async () => { + const dir = await mkdtemp(join(tmpdir(), "slo-journal-")); + try { + const file = join(dir, "slo-journal.jsonl"); + const good: SloJournalLine = { facet: "feed-age", atMs: MINUTE, value: 1, bad: false }; + await writeFile(file, `${JSON.stringify(good)}\n{"facet":"feed-a`, "utf8"); + await appendFile(file, "\n", "utf8"); + const journal = new SloJournal(file); + expect(await journal.readAll()).toEqual([good]); + + // A journal whose parent is a file cannot be written: the append + // fails, and a later append to a writable journal is unaffected. + const blocker = join(dir, "blocker"); + await writeFile(blocker, "", "utf8"); + const broken = new SloJournal(join(blocker, "slo-journal.jsonl")); + await expect(broken.append([good])).rejects.toThrow(); + + const later: SloJournalLine = { facet: "feed-age", atMs: 2 * MINUTE, value: 2, bad: false }; + await mkdir(join(dir, "ok"), { recursive: true }); + const shared = new SloJournal(join(dir, "ok", "j.jsonl")); + // Poison the chain directly, then append: the append still lands. + (shared as unknown as { writes: Promise }).writes = Promise.reject(new Error("boom")); + await shared.append([later]); + expect(await shared.readAll()).toEqual([later]); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + test("groups samples by facet without the facet key", () => { const grouped = groupSamplesByFacet([ { facet: "a", atMs: 1, value: null, bad: false },