Public: anyone can read this; the crew can change it.

Release boot proof boots a production copy in full and can re-deliver signed webhooks #14833

Closed opened this
Closed without merging

scout/forge:scout/14832-release-boot-proof-boots-a-production-co → main 3 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +158 −4
docs/features/inert-boot.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Ship and undo
3 row: The inert boot a release proof uses
4 ---
5 # The inert boot
6
7 `FORGE_INERT=1` boots the forge in full for a release proof (#14832): it migrates the data
8 directory and serves on its port, then does nothing that reaches outside it. No timers, apps,
9 crew, children, mirrors, snapshots or terminal, and `deliverDue` takes an `inert` argument and
10 returns 0, so a copy of production's data never re-sends a signed webhook. Rows stay pending.
11
12 The release proof (`src/release/boot.ts`) sets it on the candidate's copy. The engine is forced
13 inline, as for a read-only standby. This serves the release pipeline: a proof that boots the real
14 data must be unable to act on it. `test/inert-boot.test.ts` boots the real `src/main.ts` this way
15 over a pending webhook and checks the row is untouched.
src/core/webhooks.ts +3
@@ -325,7 +325,10 @@ export async function deliverDue(
325325 outbound: OutboundOptions = {},
326326 bus: EventBus = new EventBus(db),
327327 timeoutMs: number = DELIVER_TIMEOUT_MS,
328 inert = false,
328329 ): Promise<number> {
330 // An inert boot (a release proof's copy of production) never sends: its rows are the real ones.
331 if (inert) return 0;
outdated

Reading process.env inside the delivery function hides a global; take an inert option from the caller and test that.

329332 const nowIso = now.toISOString();
330333 const events = db
331334 .query<DueRow, [string]>(
src/kernel/inert.ts added +12
@@ -0,0 +1,12 @@
1 /**
2 * The inert boot (`FORGE_INERT=1`): the process migrates and serves, and does
3 * nothing that reaches outside its own data directory. A release proof boots a
4 * copy of production's data in it: the copy must show that a new version boots
5 * in full, and must never send a signed webhook, run an app, or start a timer.
6 * (`FORGE_READ_ONLY` is the standby's mode and skips migrations' consequences;
7 * this one keeps the boot whole and drops the duties.)
8 */
9
10 /** True when the environment asks for the inert boot (`FORGE_INERT=1`). */
11 export const inertFrom = (env: Record<string, string | undefined>): boolean =>
12 (env["FORGE_INERT"] ?? "").trim() === "1";
src/main.ts +9 −4
@@ -4,6 +4,7 @@
44 * environment-only — a handful of variables, all with sane defaults.
55 */
66
7 import { inertFrom } from "./kernel/inert.ts";
78 import { join } from "node:path";
89 import { sweepEntitlements } from "./billing/sync.ts";
910 import { sweepDesk } from "./actions/desk.ts";
@@ -230,7 +231,10 @@ survivesFull(dataDirOf(process.env));
230231 // A read-only standby (FORGE_READ_ONLY=1, #9657) serves reads from a restored
231232 // directory: no terminal, no apps, no crew, no jobs.
232233 const readOnly = readOnlyFrom(process.env);
233 const sshPort = readOnly ? 0 : Number(process.env.FORGE_SSH_PORT ?? (hosted ? 0 : 2222));
234 // An inert boot (FORGE_INERT=1, `kernel/inert.ts`, #14832): migrations run and the listener
235 // serves; duties, webhook delivery, notifier, apps, children, snapshots, mirrors and timers do not.
236 const inert = inertFrom(process.env);

Inert must also reach engineChoice (line ~306) and the config, or worker mode starts before the early return at the if (readOnly || inert) branch.

237 const sshPort = readOnly || inert ? 0 : Number(process.env.FORGE_SSH_PORT ?? (hosted ? 0 : 2222));
234238
235239 // FORGE_URL is the address people reach the forge at when a proxy in front
236240 // terminates TLS. Parsed once here so a typo fails the boot, not a request.
@@ -303,7 +307,7 @@ watchStalls(loopLog, undefined, undefined, undefined, (late, at) => {
303307
304308 const previewKey = previewIdentityKey(process.env);
305309
306 const engineShape = engineChoice(process.env, { hosted, readOnly, machine: readMachine() });
310 const engineShape = engineChoice(process.env, { hosted, readOnly: readOnly || inert, machine: readMachine() });
307311
308312 const app = createApp({
309313 dataDir,
@@ -407,11 +411,12 @@ const tail = engineOn ? tailEvents(app.db, app.bus) : undefined;
407411 // had (`engine/run.ts`).
408412 const loneWriter = engineOn ? tuneForSplit(app.db) : () => {};
409413 await refreshCatalogQuietly(app);
410 if (readOnly) {
414 if (readOnly || inert) {
411415 const servers = await serve(app, { warm: {} });
412416 // Only the listener runs: no reconcile, perf watcher, timers, apps, crew,
413417 // checks, releases, mirrors, snapshots or nightly jobs. Reads are answered until a signal.
414 app.log.info("forge is up, read-only standby", { url: servers.url, data: app.config.dataDir });
418 const upLine = inert ? "forge is up, inert" : "forge is up, read-only standby";
419 app.log.info(upLine, { url: servers.url, data: app.config.dataDir });
415420 const stop = (): void => {
416421 servers.stop();
417422 app.close();
src/release/boot.ts +3
@@ -96,6 +96,9 @@ async function bootOnPort(
9696 FORGE_SSH_PORT: "0",
9797 // The crew stays off a copy of production's queue.
9898 FORGE_APP_ENV: "preview",
99 // Migrate and serve, nothing else: no duties, no signed webhooks out of a copy of production
100 // (#14832).
101 FORGE_INERT: "1",
99102 FORGE_VERSION: input.version,
100103 };
101104 for (const key of ["HOME", "TMPDIR", "FORGE_TEST_SOCKET"]) {
test/inert-boot.test.ts added +116
@@ -0,0 +1,116 @@
1 /** The inert boot (#14832): a release proof's copy migrates and serves, and never delivers. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { Database } from "bun:sqlite";
4 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { createRepo } from "../src/core/repos.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { createWebhook, deliverDue, enqueueForEvent } from "../src/core/webhooks.ts";
11 import { inertFrom } from "../src/kernel/inert.ts";
12 import { bootProof } from "../src/release/boot.ts";
13
14 let root: string;
15 beforeAll(() => {
16 root = mkdtempSync(join(tmpdir(), "forge-inert-"));
17 });
18 afterAll(() => rmSync(root, { recursive: true, force: true }));
19
20 test("only FORGE_INERT=1 selects the inert boot", () => {
21 expect(inertFrom({ FORGE_INERT: "1" })).toBe(true);
22 expect(inertFrom({ FORGE_INERT: "0" })).toBe(false);
23 expect(inertFrom({})).toBe(false);
24 });
25
26 test("the release proof boots its copy with FORGE_INERT=1", async () => {
27 const dir = join(root, "tree");
28 mkdirSync(join(dir, "src"), { recursive: true });
29 // Health answers as the version only when the proof's environment says inert.
30 writeFileSync(
31 join(dir, "src", "main.ts"),
32 `Bun.serve({ hostname: "127.0.0.1", port: Number(process.env.PORT), fetch() {
33 return Response.json({ ok: true, version: process.env.FORGE_INERT === "1" ? process.env.FORGE_VERSION : "not-inert" });
34 } });`,
35 );
36 const result = await bootProof({ tree: dir, version: "9.9.9", dataDir: join(root, "data"), budgetMs: 30_000 });
37 expect(result).toMatchObject({ ok: true });
38 });
39
40 test("deliverDue refuses in the inert boot and leaves the rows pending", async () => {
41 const app: App = createApp({ dataDir: join(root, "app"), port: 0 });
42 const u = await createUser(app.db, {
43 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
44 password: "a-good-passphrase", adminIfFirst: true,
45 });
46 if (!u.ok) throw new Error(u.error);
47 const r = await createRepo(app.db, app.reposRoot, { ownerId: u.value.id, name: "lobby" });
48 if (!r.ok) throw new Error(String(r.error));
49 const repoId = r.value.id;
50 const w = createWebhook(app.db, { repoId, url: "https://example.com/hook", kinds: "*", secret: "s3cret-signing-key-0123456789" });
51 if (!w.ok) throw new Error(w.error);
52 enqueueForEvent(app.db, app.bus.append({ kind: "push", repoId, actorId: u.value.id, payload: {} }));
53 const pending = (): number =>
54 app.db.query<{ n: number }, []>("SELECT count(*) n FROM webhook_delivery WHERE state = 'pending' AND attempts = 0").get()!.n;
55 expect(pending()).toBe(1);
56 const later = new Date(Date.now() + 86_400_000);
57 expect(await deliverDue(app.db, app.log, later, {}, app.bus, undefined, true)).toBe(0);
58 expect(pending()).toBe(1);
59 app.close();
60 });
61
62 test("the real src/main.ts booted with FORGE_INERT=1 answers /healthz and delivers nothing", async () => {
63 const data = join(root, "real");
64 const seed: App = createApp({ dataDir: data, port: 0 });
65 const u = await createUser(seed.db, {
66 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
67 password: "a-good-passphrase", adminIfFirst: true,
68 });
69 if (!u.ok) throw new Error(u.error);
70 const r = await createRepo(seed.db, seed.reposRoot, { ownerId: u.value.id, name: "lobby" });
71 if (!r.ok) throw new Error(String(r.error));
72 {
73 const w = createWebhook(seed.db, { repoId: r.value.id, url: "https://example.com/hook", kinds: "*", secret: "s3cret-signing-key-0123456789" });
74 if (!w.ok) throw new Error(w.error);
75 enqueueForEvent(seed.db, seed.bus.append({ kind: "push", repoId: r.value.id, actorId: u.value.id, payload: {} }));
76 seed.close();
77 const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("") });
78 const port = probe.port;
79 probe.stop(true);
80 const child = Bun.spawn([process.execPath, "src/main.ts"], {
81 cwd: join(import.meta.dir, ".."),
82 env: {
83 PATH: process.env["PATH"] ?? "", HOME: root, FORGE_INERT: "1", FORGE_ENGINE: "worker",
84 FORGE_DATA: data, PORT: String(port), FORGE_SSH_PORT: "2222",
85 ...(process.env["FORGE_TEST_SOCKET"] ? { FORGE_TEST_SOCKET: process.env["FORGE_TEST_SOCKET"] } : {}),
86 },
87 stdout: "pipe",
88 stderr: "pipe",
89 });
90 let logged = "";
91 let sawUp = (): void => {};
92 const up = new Promise<void>((done) => { sawUp = done; });
93 const read = async (stream: ReadableStream<Uint8Array>): Promise<void> => {
94 for await (const c of stream) {
95 logged += new TextDecoder().decode(c);
96 if (logged.includes("forge is up, inert")) sawUp();
97 }
98 sawUp(); // the child ended without saying it: the assertions below show its log
99 };
100 void read(child.stdout);
101 void read(child.stderr);
102 try {
103 await up;
104 expect(logged).toContain("forge is up, inert");
105 expect((await fetch(`http://127.0.0.1:${port}/healthz`)).status).toBe(200);
106 expect(logged).not.toContain("worker");
107 } finally {
108 child.kill();
109 await child.exited;
110 }
111 const db = new Database(join(data, "forge.db"), { readonly: true });
112 const rows = db.query<{ state: string; attempts: number }, []>("SELECT state, attempts FROM webhook_delivery").all();
113 db.close();
114 expect(rows).toEqual([{ state: "pending", attempts: 0 }]);
115 }
116 }, 90_000);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs