diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index 2941d4ee86..d2fa60d30f 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -21,11 +21,19 @@ // state.json persists the keys already shown. Absent file = the // pre-#1057 hand-fed charges only. No balances or debt data ever // pass through: candidates are charge evidence only. -// - orchestration.json — the orchestration job's latest section -// (#899: tiers, dependencies, goal measurements), embedded only -// after normalizeOrchestrationSection accepts it (the collector -// gate in the publisher -> collector -> aggregator contract, -// #1176); absent/malformed = section omitted. The publisher's +// - the orchestration section (#899: tiers, dependencies, goal +// measurements) — read since the #10504 reader flip from the +// latest public.orch_runs.document on Supabase muse-dev2 (the +// writer cutover's store), through the same Management API SQL +// route and Bitwarden token as the AA section; orchestration.json +// (still regenerated by the writer every pass) is the fallback on +// any DB failure and the rollback source under +// ORCHESTRATION_SOURCE=file. Embedded only after +// normalizeOrchestrationSection accepts it (the collector gate in +// the publisher -> collector -> aggregator contract, #1176); +// absent/malformed = section omitted, and a DB failure that falls +// back to the file marks the section "error" so the aggregator +// surfaces it while serving the last good document. The publisher's // pre-publish gate is `bun run contract:check -- --publisher // ` (scripts/check-contract-corpus.ts), which runs this // same validator; the shared corpus lives in @@ -106,6 +114,12 @@ import { type FeedSectionStatus, type FleetFeed, } from "../src/feed.ts"; +import { + LATEST_ORCH_RUN_SQL, + orchestrationDocumentFromRows, + orchestrationSourceFromEnv, + resolveOrchestrationDocument, +} from "../src/orchestration-db.ts"; import { computeCheckoutDrift } from "../src/checkout-drift.ts"; import { assembleCollectorFeed } from "../src/feed-contract.ts"; import { defaultNeedsDrewFile, listAnswers } from "../src/needs-drew.ts"; @@ -1000,31 +1014,70 @@ async function main(): Promise { } } - // --- orchestration section (#899) -------------------------------------- + // --- orchestration section (#899; reader flip #10504) ------------------ + // Post-flip the section is read from the latest orch_runs.document; + // orchestration.json is the fallback + rollback path only (see + // src/orchestration-db.ts for the contract and its tests). let orchestration: OrchestrationSection | undefined; - try { - const parsed: unknown = JSON.parse(await readFile(orchestrationPath, "utf8")); - // Embed the normalized form (#1110): the feed carries the section - // in the one canonical shape the aggregator serves, whatever - // provenance form the publisher emitted. - const normalized = normalizeOrchestrationSection(parsed); - if (normalized) { - orchestration = normalized; - markSection("orchestration", "ok"); + { + const resolution = await resolveOrchestrationDocument({ + source: orchestrationSourceFromEnv(process.env), + readDb: async () => { + const token = await resolveBwsSecret("supabase.muse-dev2.access-token-muse-cli"); + if (!token) throw new Error("no Supabase management token available (bws)"); + const ref = await resolveSupabaseProjectRef(resolveBwsSecret); + if (!ref) throw new Error("no Supabase project ref available (bws)"); + const row = orchestrationDocumentFromRows(await supabaseQuery(token, ref, LATEST_ORCH_RUN_SQL)); + if (!row) throw new Error("orch_runs returned no usable latest row"); + return row.document; + }, + readFile: async (): Promise => JSON.parse(await readFile(orchestrationPath, "utf8")), + validate: (document) => orchestrationSectionProblem(document), + }); + if (resolution.document !== null) { + // Embed the normalized form (#1110): the feed carries the section + // in the one canonical shape the aggregator serves, whatever + // provenance form the publisher emitted. + const normalized = normalizeOrchestrationSection(resolution.document); + if (normalized) { + orchestration = normalized; + if (resolution.dbError) { + // Serving the last good document (the file export) with the + // DB failure surfaced: the aggregator's provenance reads + // "error — collector error: …; serving embedded section …". + console.error( + `collector: orch_runs read failed (${resolution.dbError}); serving the orchestration.json export`, + ); + markSection( + "orchestration", + "error", + `orch_runs read failed (${resolution.dbError}); serving orchestration.json export`, + ); + } else { + markSection("orchestration", "ok"); + } + } else { + console.error( + `collector: orchestration document failed its structural check (${orchestrationSectionProblem(resolution.document)}); section omitted`, + ); + markSection( + "orchestration", + "error", + `orchestration section failed structural check: ${orchestrationSectionProblem(resolution.document)}`, + ); + } + } else if (resolution.fileMissing && !resolution.dbError) { + // No orchestration file yet (the job has not run) is the normal + // pre-#899 state — omit the section silently. + markSection("orchestration", "skipped"); } else { - console.error( - `collector: orchestration.json failed its structural check (${orchestrationSectionProblem(parsed)}); section omitted`, - ); - markSection( - "orchestration", - "error", - `orchestration section failed structural check: ${orchestrationSectionProblem(parsed)}`, - ); + const reason = + resolution.dbError && resolution.fileMissing + ? `orch_runs read failed (${resolution.dbError}); orchestration.json export is also missing` + : (resolution.dbError ?? resolution.fileError ?? "orchestration document unavailable"); + console.error(`collector: orchestration section unavailable (${reason}); section omitted`); + markSection("orchestration", "error", reason); } - } catch (err) { - // No orchestration file yet (the job has not run) is the normal - // pre-#899 state — omit the section silently. - markSection("orchestration", isMissingInput(err) ? "skipped" : "error", err); } // --- GitHub Project pool (#910 stage 5) -------------------------------- diff --git a/pm-stack/aggregator/src/orchestration-db.ts b/pm-stack/aggregator/src/orchestration-db.ts new file mode 100644 index 0000000000..f3fb4a8658 --- /dev/null +++ b/pm-stack/aggregator/src/orchestration-db.ts @@ -0,0 +1,112 @@ +// Orchestration reader flip (#10504, phase 1 of #3142): the fleet-feed +// collector's orchestration section is read from the latest +// public.orch_runs.document on Supabase muse-dev2 — the writer cutover +// (task 14838, PR #10381) has written every hourly pass there since +// 2026-11-15 — and orchestration.json, which the writer still +// regenerates every pass, becomes the export + rollback path only. +// +// Fallback contract (from #10504): on any DB read failure the reader +// serves the last good document — the file, which is never behind +// because the writer's step 3 keeps regenerating it from the stored +// document — and surfaces the failure; a partial or invalid DB +// document is never served. Rollback is ORCHESTRATION_SOURCE=file, +// which points the reader back at the file and loses nothing. +// +// This module is the decision logic only: the collector injects its +// own Supabase query route (Management API SQL, the same one the AA +// section uses) and its file read, so the flip is unit-testable +// without a database. + +/** The latest run's complete document, newest first. generated_at is + * the document's own generatedAt (writer contract, ORCHESTRATION.md); + * run_id breaks ties deterministically. */ +export const LATEST_ORCH_RUN_SQL = + "SELECT run_id, document FROM public.orch_runs ORDER BY generated_at DESC, run_id DESC LIMIT 1"; + +/** Extract the document from a Management API result for + * LATEST_ORCH_RUN_SQL. Returns null for anything that is not exactly + * one usable row shape (no rows, a non-object document, a missing + * run_id): the caller treats null as a DB read failure and falls + * back — a partial document is never served. */ +export function orchestrationDocumentFromRows(rows: unknown): { runId: string; document: unknown } | null { + if (!Array.isArray(rows) || rows.length === 0) return null; + const row: unknown = rows[0]; + if (typeof row !== "object" || row === null) return null; + const { run_id: runId, document } = row as { run_id?: unknown; document?: unknown }; + if (typeof runId !== "string" || runId.length === 0) return null; + if (typeof document !== "object" || document === null || Array.isArray(document)) return null; + return { runId, document }; +} + +/** Which source the reader consults first. "file" is the rollback + * position (#10504): the export the writer still regenerates every + * pass, so pointing back at it loses nothing. Anything but the exact + * string "file" selects the DB, the post-flip default. */ +export function orchestrationSourceFromEnv(env: Readonly>): "db" | "file" { + return env.ORCHESTRATION_SOURCE?.trim().toLowerCase() === "file" ? "file" : "db"; +} + +export interface OrchestrationResolution { + /** The document to serve, or null when neither source produced one. */ + document: unknown | null; + /** Where the served document came from; null when none was served. */ + source: "db" | "file" | null; + /** Why the DB read failed, when it was attempted and failed. Set + * alongside a file-sourced document so the caller can surface the + * failure while serving the last good document. */ + dbError?: string; + /** Why the file read failed, when it was attempted and failed. */ + fileError?: string; + /** True when the file read failed because the file does not exist + * (the pre-#899 normal state), as opposed to an unreadable file. */ + fileMissing?: boolean; +} + +const errorText = (err: unknown): string => (err instanceof Error ? err.message : "read failed"); + +const isMissing = (err: unknown): boolean => + typeof err === "object" && err !== null && "code" in err && (err as { code?: unknown }).code === "ENOENT"; + +/** + * Resolve the orchestration document per the flip contract. + * + * - DB source (default): read the latest orch_runs.document and + * validate it with `validate` (the shared structural check — + * orchestrationSectionProblem). A read failure *or* an invalid + * document is a DB failure: fall back to the file and carry the + * reason in `dbError` so it is surfaced, never hidden. + * - File source (rollback): the DB is not consulted at all. + * - The file read's own failure is reported, not hidden: `fileError`, + * plus `fileMissing` for the not-yet-published case, so the caller + * keeps today's skipped-vs-error distinction. + */ +export async function resolveOrchestrationDocument(deps: { + source: "db" | "file"; + readDb: () => Promise; + readFile: () => Promise; + validate: (document: unknown) => string | null; +}): Promise { + let dbError: string | undefined; + if (deps.source === "db") { + try { + const document = await deps.readDb(); + const problem = deps.validate(document); + if (problem === null) return { document, source: "db" }; + dbError = `latest orch_runs.document failed its structural check (${problem})`; + } catch (err) { + dbError = errorText(err); + } + } + try { + const document = await deps.readFile(); + return { document, source: "file", ...(dbError ? { dbError } : {}) }; + } catch (err) { + return { + document: null, + source: null, + ...(dbError ? { dbError } : {}), + fileError: errorText(err), + fileMissing: isMissing(err), + }; + } +} diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index bc7f5d2000..60a2ef1c90 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -2072,7 +2072,9 @@ export function liveSource( }, async orchestration(): Promise { // #899: the orchestration section rides the fleet feed, embedded - // by the collector from the orchestrator's own output file. The + // by the collector from the latest orch_runs.document since the + // #10504 reader flip (orchestration.json export as its fallback). + // The // section carries its own provenance; absent = not measured yet. // #1140: three states, told apart — live (accepted, served in // the normalized contract shape, #1110), invalid (a section is diff --git a/pm-stack/aggregator/test/orchestration-db.test.ts b/pm-stack/aggregator/test/orchestration-db.test.ts new file mode 100644 index 0000000000..8309b0b03e --- /dev/null +++ b/pm-stack/aggregator/test/orchestration-db.test.ts @@ -0,0 +1,147 @@ +// #10504 reader flip: the collector reads the orchestration section +// from the latest orch_runs.document; orchestration.json is the +// fallback + rollback path. The oracle for every case is the #10504 +// fallback contract: on DB failure serve the last good document and +// surface the failure — never a partial document. +import { describe, expect, test } from "bun:test"; +import { + LATEST_ORCH_RUN_SQL, + orchestrationDocumentFromRows, + orchestrationSourceFromEnv, + resolveOrchestrationDocument, +} from "../src/orchestration-db.ts"; + +const doc = { runId: "orch-1", version: 1 }; +const validate = (d: unknown): string | null => + typeof d === "object" && d !== null && "runId" in d ? null : "missing runId"; + +describe("orchestrationDocumentFromRows", () => { + test("extracts runId + document from a well-shaped row", () => { + expect(orchestrationDocumentFromRows([{ run_id: "orch-1", document: doc }])).toEqual({ + runId: "orch-1", + document: doc, + }); + }); + + test("rejects shapes that would serve a partial document", () => { + expect(orchestrationDocumentFromRows([])).toBeNull(); + expect(orchestrationDocumentFromRows(null)).toBeNull(); + expect(orchestrationDocumentFromRows([{ run_id: "orch-1" }])).toBeNull(); + expect(orchestrationDocumentFromRows([{ run_id: "orch-1", document: null }])).toBeNull(); + expect(orchestrationDocumentFromRows([{ run_id: "orch-1", document: [1] }])).toBeNull(); + expect(orchestrationDocumentFromRows([{ document: doc }])).toBeNull(); + expect(orchestrationDocumentFromRows([{ run_id: 7, document: doc }])).toBeNull(); + }); + + test("the SQL reads the newest run's complete document", () => { + expect(LATEST_ORCH_RUN_SQL).toContain("FROM public.orch_runs"); + expect(LATEST_ORCH_RUN_SQL).toContain("document"); + expect(LATEST_ORCH_RUN_SQL).toContain("ORDER BY generated_at DESC"); + expect(LATEST_ORCH_RUN_SQL).toContain("LIMIT 1"); + }); +}); + +describe("orchestrationSourceFromEnv", () => { + test("db is the default; only the exact file value rolls back", () => { + expect(orchestrationSourceFromEnv({})).toBe("db"); + expect(orchestrationSourceFromEnv({ ORCHESTRATION_SOURCE: "db" })).toBe("db"); + expect(orchestrationSourceFromEnv({ ORCHESTRATION_SOURCE: "garbage" })).toBe("db"); + expect(orchestrationSourceFromEnv({ ORCHESTRATION_SOURCE: "file" })).toBe("file"); + expect(orchestrationSourceFromEnv({ ORCHESTRATION_SOURCE: " File " })).toBe("file"); + }); +}); + +describe("resolveOrchestrationDocument", () => { + test("db success serves the DB document and never reads the file", async () => { + let fileReads = 0; + const res = await resolveOrchestrationDocument({ + source: "db", + readDb: async () => doc, + readFile: async () => { + fileReads++; + return { runId: "orch-file" }; + }, + validate, + }); + expect(res).toEqual({ document: doc, source: "db" }); + expect(fileReads).toBe(0); + }); + + test("db failure serves the last good file document and surfaces the failure", async () => { + const fileDoc = { runId: "orch-file" }; + const res = await resolveOrchestrationDocument({ + source: "db", + readDb: async () => { + throw new Error("Supabase query failed (HTTP 503)"); + }, + readFile: async () => fileDoc, + validate, + }); + expect(res.source).toBe("file"); + expect(res.document).toBe(fileDoc); + expect(res.dbError).toContain("HTTP 503"); + }); + + test("an invalid DB document is a DB failure, never served", async () => { + const fileDoc = { runId: "orch-file" }; + const res = await resolveOrchestrationDocument({ + source: "db", + readDb: async () => ({ partial: true }), + readFile: async () => fileDoc, + validate, + }); + expect(res.source).toBe("file"); + expect(res.document).toBe(fileDoc); + expect(res.dbError).toContain("structural check"); + expect(res.dbError).toContain("missing runId"); + }); + + test("db failure + missing file reports both, with fileMissing set", async () => { + const enoent = Object.assign(new Error("ENOENT: no such file"), { code: "ENOENT" }); + const res = await resolveOrchestrationDocument({ + source: "db", + readDb: async () => { + throw new Error("no Supabase management token available (bws)"); + }, + readFile: async () => { + throw enoent; + }, + validate, + }); + expect(res.document).toBeNull(); + expect(res.source).toBeNull(); + expect(res.dbError).toContain("management token"); + expect(res.fileMissing).toBe(true); + }); + + test("rollback (source=file) never consults the DB", async () => { + let dbReads = 0; + const fileDoc = { runId: "orch-file" }; + const res = await resolveOrchestrationDocument({ + source: "file", + readDb: async () => { + dbReads++; + return doc; + }, + readFile: async () => fileDoc, + validate, + }); + expect(res).toEqual({ document: fileDoc, source: "file" }); + expect(dbReads).toBe(0); + }); + + test("rollback + missing file is the pre-#899 skipped state, no dbError", async () => { + const enoent = Object.assign(new Error("ENOENT: no such file"), { code: "ENOENT" }); + const res = await resolveOrchestrationDocument({ + source: "file", + readDb: async () => doc, + readFile: async () => { + throw enoent; + }, + validate, + }); + expect(res.document).toBeNull(); + expect(res.fileMissing).toBe(true); + expect(res.dbError).toBeUndefined(); + }); +}); diff --git a/pm-stack/shared-schema/ORCHESTRATION.md b/pm-stack/shared-schema/ORCHESTRATION.md index bb51743261..1106685ab0 100644 --- a/pm-stack/shared-schema/ORCHESTRATION.md +++ b/pm-stack/shared-schema/ORCHESTRATION.md @@ -69,9 +69,9 @@ One transaction per pass, in this order: 2. Replace `orch_items` with the document's tiers: delete the previous snapshot, insert one row per item, carrying `first_seen_run_id` forward for items that already existed. -3. Regenerate `orchestration.json` from the run's `document` (until - the reader flip, the file is still written every pass — it is - both the export and the rollback path). +3. Regenerate `orchestration.json` from the run's `document` (the + file is still written every pass — it is both the export and the + rollback path). Until that slice lands and verifies (a pass reads its state back from the tables and the dashboard serves the generated export @@ -83,6 +83,15 @@ one full cycle, per the migration plan's reversibility rule. Rollback at every stage is "point the pass back at the files": the files are never behind, because step 3 keeps writing them. +Reader flip (#10504, landed after the writer dual cycle verified): +the fleet-feed collector reads the latest `orch_runs.document` +(`src/orchestration-db.ts` in the aggregator) and embeds that as the +dashboard's orchestration section; on any DB read failure it serves +the file document instead and marks the section in error so the +failure is surfaced, and `ORCHESTRATION_SOURCE=file` points the +reader back at the file outright — the rollback above, which loses +nothing because step 3 never stopped writing the file. + ## What this slice is not - No DDL applied to `muse-dev2`, no rows copied, no writer or reader