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

Bun process hygiene on a long-lived forge: no piped stdio we never read, RSS beside heap on /system #2044

Parked opened this in answer to
Closed without merging

scout/forge:scout/2041-bun-process-hygiene-on-a-long-lived-forg → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +231 −5
scripts/gate.ts +1
@@ -203,6 +203,7 @@ export const GATE: readonly string[] = [
203203 "test/schema-additive.test.ts",
204204 "test/schema-migrations.test.ts",
205205 "test/domains.test.ts",
206 "test/memory-hygiene.test.ts",
206207 "test/vitals.test.ts",
207208 "test/vitals-degraded.test.ts",
208209 "test/red-main.test.ts",
src/app.ts +11 −2
@@ -26,6 +26,7 @@ import {
2626 type Log,
2727 } from "./kernel/log.ts";
2828 import { RefusedLedger } from "./kernel/internal_refused.ts";
29 import { MemoryLedger } from "./kernel/memory_ledger.ts";
2930 import { closeReadersUnder } from "./git/read.ts";
3031
3132 export interface ForgeConfig {
@@ -191,7 +192,11 @@ export interface App {
191192 /** Per-boot secret every internal request must carry (`FORGE_HOOK_SECRET` in a hook's env). */
192193 readonly hookSecret: string;
193194 /** What `vitals` turns into needs: this forge's own, not the process's. */
194 readonly signals: { errors: ErrorLedger; refused: RefusedLedger };
195 readonly signals: {
196 errors: ErrorLedger;
197 refused: RefusedLedger;
198 memory: MemoryLedger;
199 };
195200 close(): void;
196201 }
197202
@@ -227,7 +232,11 @@ export function createApp(config: ForgeConfig): App {
227232 db,
228233 bus,
229234 log: createLog("forge", owner),
230 signals: { errors, refused: new RefusedLedger() },
235 signals: {
236 errors,
237 refused: new RefusedLedger(),
238 memory: new MemoryLedger(),
239 },
231240 reposRoot,
232241 // This process's own: two forges share a data directory for the length
233242 // of a release, and each spawns git with its own socket in the env.
src/git/smart-http.ts +4 −2
@@ -127,7 +127,9 @@ async function spawnService(
127127 env: gitEnv(env),
128128 stdin: "pipe",
129129 stdout: "pipe",
130 stderr: "pipe",
130 // Nothing reads it: a piped stream nobody drains is native memory held
131 // for the process's life, and a full one stalls git.
132 stderr: "ignore",
131133 });
132134 let proc: ReturnType<typeof spawn>;
133135 try {
@@ -174,7 +176,7 @@ async function spawnService(
174176 * loose in the process.
175177 */
176178 async function feedStdin(
177 proc: Bun.Subprocess<"pipe", "pipe", "pipe">,
179 proc: Bun.Subprocess<"pipe", "pipe", "ignore">,
178180 service: GitService,
179181 request: Request,
180182 ): Promise<void> {
src/http/abort.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * A handler whose client has gone settles. Bun keeps a request's context for
3 * as long as the handler's promise is pending, so one that waits on something
4 * slow after a hang-up holds memory for nothing. Racing the handler with the
5 * request's own abort answers 499 (nobody reads it) and lets go.
6 */
7
8 export const CLIENT_CLOSED = 499;
9
10 export async function settleOnAbort(
11 request: Request,
12 work: Promise<Response>,
13 ): Promise<Response> {
14 const signal = request.signal;
15 if (signal.aborted) {
16 work.catch(() => {});
17 return new Response(null, { status: CLIENT_CLOSED });
18 }
19 let onAbort = () => {};
20 const gone = new Promise<Response>((resolve) => {
21 onAbort = () => resolve(new Response(null, { status: CLIENT_CLOSED }));
22 signal.addEventListener("abort", onAbort, { once: true });
23 });
24 try {
25 return await Promise.race([work, gone]);
26 } finally {
27 signal.removeEventListener("abort", onAbort);
28 // A handler that loses the race still ends; its late rejection is not ours.
29 work.catch(() => {});
30 }
31 }
src/http/server.ts +7 −1
@@ -10,6 +10,7 @@ import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
1010 import { unsealReleased } from "../actions/sealed.ts";
1111 import { accessPage } from "../web/pages/access.ts";
1212 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
13 import { systemPage } from "../web/pages/system.ts";
1314 import { flowPage } from "../web/pages/flow.ts";
1415 import { resiliencePage } from "../web/pages/resilience.ts";
1516 import { limitsPage, limitsSet } from "../web/pages/admin-limits.ts";
@@ -54,6 +55,7 @@ import {
5455 verifyPassword,
5556 } from "../core/users.ts";
5657 import { edgeIdentity } from "./edge.ts";
58 import { settleOnAbort } from "./abort.ts";
5759 import { liveResponse, readyResponse } from "./health.ts";
5860 import { runGit } from "../git/env.ts";
5961 import { noteRefusedInternal } from "../kernel/internal_refused.ts";
@@ -726,6 +728,7 @@ export function buildRouter(): Router<Handler> {
726728 router.add("GET", "/settings/access", accessPage);
727729 router.add("GET", "/settings/capacity", capacityPage);
728730 router.add("POST", "/settings/capacity", capacitySet);
731 router.add("GET", "/system", systemPage);
729732 router.add("GET", "/boards", boardsList);
730733 router.add("GET", "/boards/data", boardsPage);
731734 router.add("POST", "/boards/new", boardNew);
@@ -1857,7 +1860,10 @@ export async function serve(app: App): Promise<Servers> {
18571860 // Everything the forge answers for itself leaves through this one
18581861 // door, so a responder added next year cannot forget the floor.
18591862 const response = securityFloor(
1860 await answer(app, router, apiRouter, limiter, request),
1863 await settleOnAbort(
1864 request,
1865 answer(app, router, apiRouter, limiter, request),
1866 ),
18611867 );
18621868 logged(app.config.dataDir, request, response, started);
18631869 await settleBody(request);
src/kernel/memory_ledger.ts added +50
@@ -0,0 +1,50 @@
1 /**
2 * Resident memory beside the JS heap, one reading an hour. RSS that climbs
3 * while the heap stays flat is native memory (a child's pipes, a request
4 * context Bun still holds), and only the two side by side say which. Kept in
5 * memory and bounded: a week of hours, never anything a person typed.
6 */
7
8 import { heapStats } from "bun:jsc";
9
10 const HOUR_MS = 3_600_000;
11 const KEEP = 24 * 7;
12
13 export interface MemoryReading {
14 readonly at: number;
15 readonly rssBytes: number;
16 readonly heapBytes: number;
17 readonly heapCapacityBytes: number;
18 readonly objects: number;
19 }
20
21 /** What this process holds right now. */
22 export function readMemory(now: number = Date.now()): MemoryReading {
23 const heap = heapStats();
24 return {
25 at: now,
26 rssBytes: process.memoryUsage().rss,
27 heapBytes: heap.heapSize,
28 heapCapacityBytes: heap.heapCapacity,
29 objects: heap.objectCount,
30 };
31 }
32
33 /** One forge's readings (`App.signals.memory`). */
34 export class MemoryLedger {
35 private readings: MemoryReading[] = [];
36
37 /** Keep a reading unless one from the same hour is already kept. */
38 note(reading: MemoryReading): boolean {
39 const last = this.readings.at(-1);
40 if (last !== undefined && reading.at - last.at < HOUR_MS) return false;
41 this.readings.push(reading);
42 if (this.readings.length > KEEP) this.readings.shift();
43 return true;
44 }
45
46 /** Newest first. */
47 recent(): MemoryReading[] {
48 return [...this.readings].reverse();
49 }
50 }
src/main.ts +9
@@ -4,6 +4,7 @@
44 * environment-only — a handful of variables, all with sane defaults.
55 */
66
7 import { readMemory } from "./kernel/memory_ledger.ts";
78 import { startSampler } from "./boards/sampler.ts";
89 import { sweepStanding } from "./crew/standing.ts";
910 import { handover } from "./release/swap.ts";
@@ -476,6 +477,13 @@ if (ssh)
476477 // failed; checks are queued again while their commit heads an open pull;
477478 // agent runs are the crew's to queue again, unless there is no crew here to
478479 // do it.
480 // RSS beside the heap, once an hour (the ledger keeps one reading an hour).
481 app.signals.memory.note(readMemory());
482 const memoryTimer = setInterval(
483 () => app.signals.memory.note(readMemory()),
484 60_000,
485 );
486
479487 const leaseTimer = setInterval(() => {
480488 failAbandonedRuns(
481489 app.db,
@@ -514,6 +522,7 @@ function shutdown(signal: NodeJS.Signals): void {
514522 clearInterval(heartbeatTimer);
515523 clearInterval(syncTimer);
516524 clearInterval(staleTimer);
525 clearInterval(memoryTimer);
517526 clearInterval(leaseTimer);
518527 // The platform's SIGTERM: the listener stays open while routers learn
519528 // this process is going. A person's Ctrl-C does not wait for routers.
src/web/pages/system.ts added +58
@@ -0,0 +1,58 @@
1 /**
2 * The process, for a forge admin: resident memory beside the JS heap, one
3 * reading an hour. RSS climbing over a flat heap is native memory — the
4 * signature of a leaked child pipe or a held request (`kernel/memory_ledger.ts`).
5 */
6
7 import type { Ctx } from "../../http/context.ts";
8 import { readMemory } from "../../kernel/memory_ledger.ts";
9 import { notFoundPage, signInFirst } from "../chrome.ts";
10 import { html } from "../html.ts";
11 import { page } from "../layout.ts";
12 import { card, icon } from "../ui.ts";
13
14 const mb = (bytes: number) => `${(bytes / 1_048_576).toFixed(1)} MB`;
15
16 // GET /system
17 export function systemPage(ctx: Ctx): Response {
18 if (!ctx.auth.user) return signInFirst(ctx);
19 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
20 const memory = ctx.app.signals.memory;
21 const now = readMemory();
22 memory.note(now);
23 const rows = memory.recent().map(
24 (r) => html`<tr>
25 <td class="mono">${new Date(r.at).toISOString().slice(0, 16)}Z</td>
26 <td class="mono">${mb(r.rssBytes)}</td>
27 <td class="mono">${mb(r.heapBytes)}</td>
28 <td class="mono">${mb(r.heapCapacityBytes)}</td>
29 <td class="mono">${String(r.objects)}</td>
30 </tr>`,
31 );
32 return page({
33 ctx,
34 title: "System",
35 body: html`<div class="page-head"><h1>System</h1></div>
36 <p class="muted small" id="now">
37 Now: ${mb(now.rssBytes)} resident, ${mb(now.heapBytes)} of JS heap.
38 Resident memory climbing while the heap stays flat is native memory.
39 </p>
40 ${card(
41 html`<table class="table small">
42 <thead>
43 <tr>
44 <th>Hour (UTC)</th>
45 <th>RSS</th>
46 <th>Heap</th>
47 <th>Heap capacity</th>
48 <th>Objects</th>
49 </tr>
50 </thead>
51 <tbody>
52 ${rows}
53 </tbody>
54 </table>`,
55 { head: html`${icon("activity")}<h2>Memory, hourly</h2>`, pad: false },
56 )}`,
57 });
58 }
test/memory-hygiene.test.ts added +44
@@ -0,0 +1,44 @@
1 /** Process hygiene: hourly memory readings, the /system page, and a handler that settles on abort. */
2
3 import { expect, test } from "bun:test";
4 import { settleOnAbort } from "../src/http/abort.ts";
5 import { MemoryLedger, readMemory } from "../src/kernel/memory_ledger.ts";
6
7 test("a reading carries RSS beside the heap", () => {
8 const r = readMemory(1);
9 expect(r.rssBytes).toBeGreaterThan(0);
10 expect(r.heapBytes).toBeGreaterThan(0);
11 expect(r.objects).toBeGreaterThan(0);
12 });
13
14 test("the ledger keeps one reading an hour, newest first, a week at most", () => {
15 const ledger = new MemoryLedger();
16 const base = readMemory(0);
17 expect(ledger.note({ ...base, at: 0 })).toBe(true);
18 expect(ledger.note({ ...base, at: 59 * 60_000 })).toBe(false);
19 for (let h = 1; h <= 200; h++) ledger.note({ ...base, at: h * 3_600_000 });
20 const seen = ledger.recent();
21 expect(seen.length).toBe(168);
22 expect(seen[0]!.at).toBe(200 * 3_600_000);
23 });
24
25 test("a handler still pending when the client hangs up settles as 499", async () => {
26 const abort = new AbortController();
27 const request = new Request("http://x/", { signal: abort.signal });
28 const never = new Promise<Response>(() => {});
29 const settled = settleOnAbort(request, never);
30 abort.abort();
31 expect((await settled).status).toBe(499);
32 });
33
34 test("a handler that answers first keeps its answer", async () => {
35 const request = new Request("http://x/");
36 const res = await settleOnAbort(request, Promise.resolve(new Response("hi")));
37 expect(await res.text()).toBe("hi");
38 });
39
40 test("an already-aborted request is answered 499 without waiting", async () => {
41 const request = new Request("http://x/", { signal: AbortSignal.abort() });
42 const res = await settleOnAbort(request, new Promise<Response>(() => {}));
43 expect(res.status).toBe(499);
44 });
test/vitals.test.ts +16
@@ -438,3 +438,19 @@ test("a lane older than its budget is degraded with its cause; a silent run is s
438438 expect(stuck?.sentence).toBe(`Run ${live.id} is stuck: no heartbeat for 4 min (limit 3).`);
439439 app.db.query("DELETE FROM run").run();
440440 });
441
442 test("/system shows RSS beside the heap to an admin only", async () => {
443 const anon = await fetch(servers.url + "/system", { redirect: "manual" });
444 expect(anon.status).not.toBe(200);
445 const plainRes = await fetch(servers.url + "/system", {
446 headers: { authorization: `Bearer ${plain}` },
447 });
448 expect(plainRes.status).toBe(404);
449 const res = await fetch(servers.url + "/system", {
450 headers: { authorization: `Bearer ${admin}` },
451 });
452 expect(res.status).toBe(200);
453 const text = await res.text();
454 expect(text).toContain("Memory, hourly");
455 expect(text).toContain("Heap capacity");
456 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs