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

An idle fresh forge has a memory budget test that names where its memory goes #16883

Merged opened this

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

Merged

scout/forge:scout/16851-an-idle-fresh-forge-has-a-memory-budget → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/16851-an-idle-fresh-forge-has-a-memory-budget was merged into main as 3bcfa79.

Review

Sign in to review this change.
6 files changed +124 −16
scripts/gate.ts +1
@@ -51,6 +51,7 @@ export const EXCLUDED: readonly Exclusion[] = [];
5151 * short: an entry is a debt with an owner, not a home.
5252 */
5353 export const SLOW: readonly Exclusion[] = [
54 { file: "test/boot-idle-memory.test.ts", reason: "boots the real src/main.ts and waits real seconds for its RSS to settle; 8.6 s a test", issue: 16851 },
5455 { file: "test/landsim.test.ts", reason: "runs seeded landing simulations over real repositories and queues; 16 s a file alone, 28.8 s and 2.8 s a test under full-suite load", issue: 13765 },
5556 { file: "test/propose-via-fork.test.ts", reason: "runs two real forges and a fake origin, each test pushing real git branches through a fork; 11 s a file alone, 23.9 s and 4.4 s a test under full-suite load", issue: 15193 },
5657 { file: "test/red-on-main.test.ts", reason: "runs test-shards.ts end to end in a scratch git repository, twice over main and the pull; 6.4 s a test under full-suite load", issue: 15319 },
src/main.ts +2 −2
@@ -157,7 +157,7 @@ import { createStallRelay } from "./kernel/stall_relay.ts";
157157 import { startPerfWatcher, TICK_MS } from "./perf/duty.ts";
158158 import { during } from "./perf/jobs.ts";
159159 import { stallLine } from "./perf/loop.ts";
160 import { memoryWatch } from "./perf/memory_watch.ts";
160 import { memoryWatch, workerMemoryEvery } from "./perf/memory_watch.ts";
161161 import { bootStall, gitRecord, liveOf } from "./perf/live.ts";
162162 import type { ProbeDoor } from "./perf/probe.ts";
163163 import { keepFlowReadings, KEPT_MS } from "./flow/kept.ts";
@@ -771,7 +771,7 @@ const sampler = startSampler(app, {});
771771 // always, kept out of the write clock; the age rule and the deploy backfill are the engine's when
772772 // it has a thread of its own.
773773 const stopRetention = startRetention(app, { local: true, engine: !engineOn });
774 const memorySampler = startMemorySampler(app);
774 const memorySampler = startMemorySampler(app, workerMemoryEvery());
775775 // Off unless FORGE_HEAP_CAPTURE_DIR is set, for a copy of production (perf/heap_capture.ts).
776776 const stopHeapCapture = startHeapCapture(process.env, (m) => app.log.info(m));
777777 // The starting boards, once each (actions/boards.ts).
src/perf/memory_watch.ts +3 −2
@@ -521,8 +521,9 @@ export function startWorkerMemory(
521521 }
522522
523523 /**
524 * How often a worker writes its line: a minute, or `FORGE_WORKER_MEMORY_MS` (a test seam,
525 * a positive integer).
524 * How often a worker, and the serving forge's own sampler, write their line: a minute, or
525 * `FORGE_WORKER_MEMORY_MS` (a test seam, a positive integer; the idle-memory test shortens it
526 * so a line exists at the settle point).
526527 */
527528 export function workerMemoryEvery(env: Record<string, string | undefined> = process.env): number {
528529 const raw = env.FORGE_WORKER_MEMORY_MS;
test/boot-idle-memory.test.ts added +96
@@ -0,0 +1,96 @@
1 /**
2 * A fresh forge on empty data, booted as production boots it, settles under `IDLE_RSS_BUDGET`
3 * (#16851). When it does not, the failure prints the forge's own memory line (JS heap, mimalloc
4 * committed, RSS) so the cause is named, not only the total.
5 *
6 * Linux only (`IDLE_SKIP_REASON`).
7 *
8 * @tree-scan: boots all of src/ through main.ts.
9 */
10 import { afterAll, beforeAll, expect, test } from "bun:test";
11 import { readFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { freePort } from "../src/kernel/port.ts";
15 import { collectOutput } from "./helpers/collect-output.ts";
16 import { productionEnv } from "./helpers/production-env.ts";
17
18 const MAIN = join(import.meta.dir, "..", "src", "main.ts");
19 const MIB = 1048576;
20 /**
21 * The most RSS an idle fresh forge may settle at: 281 MiB measured on Linux 2026-11-30, plus a
22 * margin for a loaded host.
23 */
24 const IDLE_RSS_BUDGET = 400 * MIB;
25 /** Why the budget is not held off Linux. */
26 const IDLE_SKIP_REASON = "RSS is measured from /proc on Linux; other hosts count resident memory differently";
27 /** Real time, named: RSS settles over seconds of a real process, there is no event to await. */
28 const POLL_MS = 250;
29 const SETTLE_MS = 1_000;
30 const STOP_GRACE_MS = 4_000;
31 const linux = process.platform === "linux";
32 const run = linux ? test : test.skip;
33 if (!linux) console.warn(`boot-idle-memory skipped: ${IDLE_SKIP_REASON}`);
34
35 /** Resident bytes of a process, from /proc (the page size is 4 KiB on every Linux we run). */
36 function rssOf(pid: number): number {
37 const m = /^VmRSS:\s+(\d+) kB/m.exec(readFileSync(`/proc/${pid}/status`, "utf8"));
38 return m ? Number(m[1]) * 1024 : 0;
39 }
40
41 let root = "";
42 beforeAll(() => {
43 root = mkdtempSync(join(tmpdir(), "forge-boot-idle-memory-"));
44 });
45 afterAll(() => rmSync(root, { recursive: true, force: true }));
46
47 run(
48 "an idle fresh forge settles under its memory budget",
49 async () => {
50 const dir = join(root, "boot");
51 mkdirSync(join(dir, "data"), { recursive: true });
52 const caFile = join(dir, "ca.crt");
53 writeFileSync(caFile, "-----BEGIN CERTIFICATE-----\nMIIBfake\n-----END CERTIFICATE-----\n");
54 const env: Record<string, string> = {
55 PATH: process.env["PATH"] ?? "/usr/local/bin:/usr/bin:/bin",
56 ...productionEnv({ dataDir: join(dir, "data"), port: await freePort(), sshPort: await freePort(), caFile }),
57 };
58 env["FORGE_WORKER_MEMORY_MS"] = String(SETTLE_MS); // the seam the sampler reads: a line each second, so one exists at the settle point
59 for (const key of ["HOME", "TMPDIR", "FORGE_CELLS", "FORGE_TEST_SOCKET"]) {
60 const value = process.env[key];
61 if (value !== undefined && value !== "") env[key] = value;
62 }
outdated

This take duplicates the one in test/boot-production.test.ts (the gate warns about it). Move it to test/helpers/ and import it in both.

63 const child = Bun.spawn([process.execPath, MAIN], { cwd: dir, env, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
64 const out = { text: "" };
65 const reading = collectOutput(out, child.stdout, child.stderr);
66 let settled = 0;
67 let own = "";
68 try {
69 for (const waited = performance.now(); child.exitCode === null && !/forge is up/.test(out.text) && performance.now() - waited < 40_000; )
70 await Bun.sleep(POLL_MS); // real-timer: a real boot
71 expect(child.exitCode).toBeNull();
72 // Settled: three readings a second apart within 2% of each other (at most 20 s).
73 const seen: number[] = [];
74 for (const started = performance.now(); performance.now() - started < 20_000; ) {
75 await Bun.sleep(SETTLE_MS); // real-timer: RSS settles over real seconds
76 seen.push(rssOf(child.pid));
77 const last = seen.slice(-3);
78 if (last.length === 3 && Math.max(...last) - Math.min(...last) <= Math.max(...last) * 0.02) break;
79 }
80 settled = seen[seen.length - 1] ?? 0;
81 // The forge's own reading beside it: the newest line is at most one sample old.
82 own = out.text.split("\n").filter((l) => /memory main:/.test(l)).pop() ?? "(the forge logged no memory line)";
83 } finally {
84 child.kill("SIGINT");
85 const gone = await Promise.race([child.exited.then(() => true), Bun.sleep(STOP_GRACE_MS).then(() => false)]); // real-timer: stop grace
86 if (!gone) child.kill("SIGKILL");
87 await child.exited;
88 await reading;
89 }
90 const shown = `${(settled / MIB).toFixed(0)} MiB`;
outdated

This is the forge's first (boot-time) memory line, not one taken at settle. Capture a line at the settle point so the heap, mimalloc and RSS figures belong to the same moment as the measured RSS.

91 console.log(`idle rss ${shown} of ${(IDLE_RSS_BUDGET / MIB).toFixed(0)} MiB; ${own}`);
92 expect(settled, `could not read the RSS of the forge (pid ${child.pid}); output: ${out.text.slice(-500)}`).toBeGreaterThan(0);
93 expect(settled, `idle RSS ${shown} over the ${(IDLE_RSS_BUDGET / MIB).toFixed(0)} MiB budget; the forge's own line at settle: ${own}`).toBeLessThan(IDLE_RSS_BUDGET);
outdated

This assertion is that RSS is above 0, and its message says 'over the budget'. Give it its own wording, and build the shared message once.

94 },
95 120_000,
96 );
test/boot-production.test.ts +6 −12
@@ -22,6 +22,7 @@ import { tmpdir } from "node:os";
2222 import { join } from "node:path";
2323 import { bunAtLeast } from "../src/engine/mode.ts";
2424 import { freePort } from "../src/kernel/port.ts";
25 import { collectOutput } from "./helpers/collect-output.ts";
2526 import {
2627 PRODUCTION_VARIABLES,
2728 productionEnv,
@@ -82,15 +83,8 @@ async function boot(name: string, engine: string | undefined): Promise<Boot> {
8283 stdout: "pipe",
8384 stderr: "pipe",
8485 });
85 let output = "";
86 const take = async (stream: ReadableStream<Uint8Array>): Promise<void> => {
87 const decoder = new TextDecoder();
88 for await (const chunk of stream)
89 output += decoder.decode(chunk, { stream: true });
90 };
91 const reading = Promise.all([take(child.stdout), take(child.stderr)]).catch(
92 () => undefined,
93 );
86 const out = { text: "" };
87 const reading = collectOutput(out, child.stdout, child.stderr);
9488 try {
9589 const started = performance.now();
9690 while (performance.now() - started < HOLD_MS && child.exitCode === null)
@@ -117,7 +111,7 @@ async function boot(name: string, engine: string | undefined): Promise<Boot> {
117111 for (
118112 const waited = performance.now();
119113 child.exitCode === null &&
120 !/forge is up/.test(output) &&
114 !/forge is up/.test(out.text) &&
121115 performance.now() - waited < 30_000;
122116
123117 )
@@ -126,12 +120,12 @@ async function boot(name: string, engine: string | undefined): Promise<Boot> {
126120 for (
127121 const waited = performance.now();
128122 child.exitCode === null &&
129 !/the engine is up|Worker is given up/.test(output) &&
123 !/the engine is up|Worker is given up/.test(out.text) &&
130124 performance.now() - waited < 10_000;
131125
132126 )
133127 await Bun.sleep(250); // real-timer: the Worker's own start line
134 return { name, alive, exitCode: child.exitCode, health, output };
128 return { name, alive, exitCode: child.exitCode, health, output: out.text };
135129 } finally {
136130 // A person's stop: no linger for routers. Killed if it has not gone in four seconds.
137131 child.kill("SIGINT");
test/helpers/collect-output.ts added +16
@@ -0,0 +1,16 @@
1 /**
2 * Collect a child process's output streams into one growing string (shared by the tests that boot
3 * the real forge and read its log).
4 */
5
6 /** Start reading `streams` into `into.text`; the promise ends when they close, never rejects. */
7 export function collectOutput(into: { text: string }, ...streams: ReadableStream<Uint8Array>[]): Promise<void> {
8 const take = async (stream: ReadableStream<Uint8Array>): Promise<void> => {
9 const decoder = new TextDecoder();
10 for await (const chunk of stream) into.text += decoder.decode(chunk, { stream: true });
11 };
12 return Promise.all(streams.map(take)).then(
13 () => undefined,
14 () => undefined,
15 );
16 }

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs