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

Full suite red: test/boot-beside-peer.test.ts #16126

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16124-full-suite-red-test-boot-beside-peer-tes → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/16124-full-suite-red-test-boot-beside-peer-tes was merged into main as 496c986.

Review

Sign in to review this change.
3 files changed +115 −21
test/boot-beside-peer.test.ts +77 −16
@@ -1,6 +1,6 @@
11 /**
2 * A forge booting beside one still draining on the same database answers
3 * /healthz within a second throughout (#6957). 0.7.278 came up while
2 * A forge booting beside one still draining on the same database never
3 * waits on that one's write lock, so /healthz answers throughout (#6957). 0.7.278 came up while
44 * 0.7.276 finished a batch of gates on the shared data, started its own
55 * work, and waited on the old pod's write lock on the one thread it serves
66 * from: readiness timed out for minutes.
@@ -15,6 +15,9 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
1515 import { tmpdir } from "node:os";
1616 import { join } from "node:path";
1717 import { createApp } from "../src/app.ts";
18 import { createLog } from "../src/kernel/log.ts";
19 import { timeStatements } from "../src/kernel/slow_sql.ts";
20 import { HELD_MS, heldThread } from "./helpers/held-thread.ts";
1821 import { waitFor } from "./helpers/poll.ts";
1922
2023 // The peer's ceiling: it lets go sooner, once the forge is up and has
@@ -28,10 +31,10 @@ const HOLD_MS = 1_500;
2831 const GAP_MS = 150;
2932
3033 /**
31 * Holds the write lock `HOLD_MS` of every `HOLD_MS + GAP_MS`, renewing the 8 leases each time,
34 * Holds the write lock `holdMs` of every `holdMs + GAP_MS`, renewing the 8 leases each time,
3235 * until told on stdin or `PEER_MS`; then lands them and exits.
3336 */
34 const peerScript = `
37 const peerScript = (holdMs: number): string => `
3538 const { Database } = require("bun:sqlite");
3639 const db = new Database(process.argv[2]);
3740 db.run("PRAGMA busy_timeout = 15000");
@@ -51,7 +54,7 @@ const tick = () => {
5154 if (told) return land();
5255 db.run("BEGIN IMMEDIATE");
5356 db.run("UPDATE run SET heartbeat_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id IN (" + ids.map((i) => "'" + i + "'").join(",") + ")");
54 spin(${HOLD_MS});
57 spin(${holdMs});
5558 db.run("COMMIT");
5659 if (Date.now() < until) return void setTimeout(tick, ${GAP_MS});
5760 land();
@@ -59,6 +62,19 @@ const tick = () => {
5962 tick();
6063 `;
6164
65 // How far past HELD_MS the one-shot peer holds: slack for reading its "held" line late.
66 const HOLD_PAST_MS = 400;
67
68 /** Takes the write lock, says "held" once it has it, and lets go `holdMs` later. */
69 const heldScript = (holdMs: number): string => `
70 const { Database } = require("bun:sqlite");
71 const db = new Database(process.argv[2]);
72 db.run("BEGIN IMMEDIATE");
73 db.run("UPDATE run SET heartbeat_at = heartbeat_at");
74 console.log("held");
75 setTimeout(() => { db.run("COMMIT"); process.exit(0); }, ${holdMs});
76 `;
77
6278 /**
6379 * The boot beside the peer, as plain data: whether it came up, the probes that were slow, how
6480 * many were asked while the lock was held, and what the forge said.
@@ -74,7 +90,7 @@ async function bootBeside() {
7490 .run(`gate-${n}`, now);
7591 seed.close();
7692 const script = join(dataDir, "..", `${dataDir.split("/").pop()}-peer.js`);
77 await writeFile(script, peerScript);
93 await writeFile(script, peerScript(HOLD_MS));
7894
7995 const peer = Bun.spawn(["bun", script, join(dataDir, "forge.db")], { stdin: "pipe", stdout: "pipe", stderr: "inherit" });
8096 await peer.stdout.getReader().read();
@@ -105,9 +121,10 @@ async function bootBeside() {
105121 await Bun.sleep(100);
106122 }
107123 }
108 if (!up) return { up, slow: [], held: 0, out };
124 if (!up) return { up, slow: [], refused: [], held: 0, out };
109125 // Then every probe answers within a second while the peer holds on, and after.
110126 const slow: number[] = [];
127 const refused: string[] = [];
111128 let held = 0;
outdated

Push the error name or message, not a bare 0, and print the forge log when refused is non-empty (the log is printed only for slow at present).

112129 let end = Number.POSITIVE_INFINITY;
113130 void peer.exited.then(() => (end = performance.now() + 1_000));
@@ -116,20 +133,23 @@ async function bootBeside() {
116133 const t = performance.now();
117134 try {
118135 const res = await fetch(`http://127.0.0.1:${web}/healthz`, { signal: AbortSignal.timeout(1_000) });
119 if (!res.ok) slow.push(-res.status);
136 if (!res.ok) refused.push(`status ${res.status}`);
120137 // Answered while the peer still held on: counted only once it came back.
121138 else if (peer.exitCode === null && ++held === HELD_PROBES) {
122139 peer.stdin.write("let go\n");
123140 void peer.stdin.flush();
124141 }
125 } catch {
126 slow.push(Math.round(performance.now() - t));
142 } catch (e) {
143 // A timeout is slow; any other failure (a refused connection) is not load.
144 const { name, message } = e as Error;
145 if (name === "TimeoutError" || name === "AbortError") slow.push(Math.round(performance.now() - t));
146 else refused.push(`${name}: ${message}`);
outdated

A test file should not export a helper. Move the rule into a module the test imports, or inline it.

127147 }
128148 await Bun.sleep(200);
129149 }
130150 await peer.exited;
131151 await waitFor(() => out.includes("the other forge let go of this database"), { every: 100, within: 10_000 });
132 return { up, slow, held, out };
152 return { up, slow, refused, held, out };
133153 } finally {
134154 peer.kill();
135155 // Its shutdown is not what is proven here, and a drain takes seconds (#12397).
@@ -145,14 +165,55 @@ beforeAll(async () => {
145165 boot = await bootBeside();
146166 }, 90_000);
147167
148 test("healthz answers within 1 s throughout a boot beside a draining forge's batch of 8, and work starts once it lets go", () => {
168 test("healthz answers throughout a boot beside a draining forge's batch of 8, its thread never waits on that forge's lock, and work starts once it lets go", () => {
149169 expect(boot.up).toBe(true);
150 // A probe that timed out: the forge's own log names what held it.
151 if (boot.slow.length > 0) console.log(boot.out);
152 expect(boot.slow).toEqual([]);
170 // A probe that timed out or was refused: the forge's own log names what held it.
171 if (boot.slow.length > 0 || boot.refused.length > 0) console.log(boot.out);
172 // Any non-timeout failure or bad status is a failure outright.
173 expect(boot.refused).toEqual([]);
174 // The regression (#6957) is the forge's one thread waiting on the peer's
outdated

This restates length >= 2. It would not fail if the boot test stopped catching a lock-blocked forge. Prove the guard against a deliberately blocking forge instead.

175 // write lock, and the forge names that wait itself: a statement that held
176 // the thread a second or more. A probe that timed out with no such
177 // statement is the machine starving the process (#16124), which no test
178 // of this forge can rule out, so the probe times are the diagnosis and the
179 // statements are the verdict. Bound: it sees waits on the handles the
180 // forge times (src/main.ts's and the worker's), not one opened elsewhere.
181 expect(heldThread(boot.out)).toEqual([]);
153182 // The forge was asked while the peer still held the lock, not only after.
154183 expect(boot.held).toBeGreaterThanOrEqual(HELD_PROBES);
155184 expect(boot.out).toContain("another forge still works this database");
156185 expect(boot.out).toContain("the other forge let go of this database");
157 expect(boot.out).not.toContain("event loop stalled");
158186 });
187
188 test("a forge's handle that writes while the peer holds its lock is named as holding the thread", async () => {
189 const dataDir = await mkdtemp(join(tmpdir(), "forge-bootpeer-lock-"));
190 const script = join(dataDir, "..", `${dataDir.split("/").pop()}-peer.js`);
191 const app = createApp({ dataDir, port: 0 });
192 const lines: string[] = [];
193 const warn = console.warn;
194 let peer: ReturnType<typeof Bun.spawn> | undefined;
195 try {
196 // One hold, begun before "held" is printed and let go HOLD_PAST_MS past the line, so the
197 // write waits over the line if it starts within that slack, and the test keeps its 2 s budget.
198 await writeFile(script, heldScript(HELD_MS + HOLD_PAST_MS));
199 const held = Bun.spawn(["bun", script, join(dataDir, "forge.db")], { stdout: "pipe", stderr: "inherit" });
200 peer = held;
201 await held.stdout.getReader().read();
202 console.warn = (...args: unknown[]) => void lines.push(args.map(String).join(" "));
203 timeStatements(app.db, createLog("sql"));
204 // What the regressed forge did: its own write, on the thread it serves from, during the hold.
205 app.db.run("UPDATE run SET heartbeat_at = heartbeat_at WHERE state = 'running'");
206 console.warn = warn;
207 await held.exited;
208 const out = lines.join("\n");
209 expect(heldThread(out)).toHaveLength(1);
210 expect(heldThread(out)[0]!).toBeGreaterThanOrEqual(HELD_MS);
211 } finally {
212 console.warn = warn;
213 peer?.kill();
214 await peer?.exited;
215 app.close();
216 await rm(dataDir, { recursive: true, force: true });
217 await rm(script, { force: true });
218 }
219 }, 30_000);
test/egress-literals.test.ts +15 −5
@@ -43,13 +43,23 @@ const NOT_CALLED: Record<string, string> = {
4343
4444 const transpiler = new Bun.Transpiler({ loader: "ts" });
4545
46 /** Hosts in a file's code strings, its comments removed. */
46 /** Each text's hosts, so the suite transpiles a file once and not once a test. */
47 const hostsOf = new Map<string, Set<string>>();
48
49 /**
50 * Hosts in a file's code strings, its comments removed. A file that never writes `https://` or
51 * `wss://` names none, so only the few that do are transpiled: the whole tree took over 2 s.
52 */
4753 function codeHosts(text: string): Set<string> {
54 const known = hostsOf.get(text);
55 if (known) return known;
4856 const hosts = new Set<string>();
49 for (const m of transpiler.transformSync(text).matchAll(URL_HOST)) {
50 const host = (m[1] ?? "").toLowerCase();
51 if (!RESERVED.test(host)) hosts.add(host);
52 }
57 if (/(?:https|wss):\/\//i.test(text))
58 for (const m of transpiler.transformSync(text).matchAll(URL_HOST)) {
59 const host = (m[1] ?? "").toLowerCase();
60 if (!RESERVED.test(host)) hosts.add(host);
61 }
62 hostsOf.set(text, hosts);
5363 return hosts;
5464 }
5565
test/helpers/held-thread.ts added +23
@@ -0,0 +1,23 @@
1 /**
2 * The statements a forge's own log says held its thread (#16124). The forge
3 * times every statement on its handle (src/kernel/slow_sql.ts) and warns
4 * `[sql] slow statement held the thread ms=N` for any over 200 ms. A forge
5 * waiting on another process's write lock waits inside one of those
6 * statements, so its wait is named here. A machine too loaded to answer a
7 * probe in time is not, which tells the lock from the load.
8 */
9
10 /**
11 * A statement holding the thread this long is the forge waiting, not the machine: a probe gives up
12 * at 1 s.
13 */
14 export const HELD_MS = 1_000;
15
16 const LINE = /\[sql\] slow statement held the thread ms=(\d+)/g;
17
18 /**
19 * The ms of every logged statement in `out` that held the thread `overMs` or more, in log order.
20 */
21 export function heldThread(out: string, overMs = HELD_MS): number[] {
22 return [...out.matchAll(LINE)].map((m) => Number(m[1])).filter((ms) => ms >= overMs);
23 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs