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
scout/forge:scout/2041-bun-process-hygiene-on-a-long-lived-forg → main 2 commits fork
10 files
changed +231
−5
scripts/gate.ts +1
| @@ -203,6 +203,7 @@ export const GATE: readonly string[] = [ | ||
| 203 | 203 | "test/schema-additive.test.ts", |
| 204 | 204 | "test/schema-migrations.test.ts", |
| 205 | 205 | "test/domains.test.ts", |
| 206 | "test/memory-hygiene.test.ts", | |
| 206 | 207 | "test/vitals.test.ts", |
| 207 | 208 | "test/vitals-degraded.test.ts", |
| 208 | 209 | "test/red-main.test.ts", |
src/app.ts +11 −2
| @@ -26,6 +26,7 @@ import { | ||
| 26 | 26 | type Log, |
| 27 | 27 | } from "./kernel/log.ts"; |
| 28 | 28 | import { RefusedLedger } from "./kernel/internal_refused.ts"; |
| 29 | import { MemoryLedger } from "./kernel/memory_ledger.ts"; | |
| 29 | 30 | import { closeReadersUnder } from "./git/read.ts"; |
| 30 | 31 | |
| 31 | 32 | export interface ForgeConfig { |
| @@ -191,7 +192,11 @@ export interface App { | ||
| 191 | 192 | /** Per-boot secret every internal request must carry (`FORGE_HOOK_SECRET` in a hook's env). */ |
| 192 | 193 | readonly hookSecret: string; |
| 193 | 194 | /** 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 | }; | |
| 195 | 200 | close(): void; |
| 196 | 201 | } |
| 197 | 202 | |
| @@ -227,7 +232,11 @@ export function createApp(config: ForgeConfig): App { | ||
| 227 | 232 | db, |
| 228 | 233 | bus, |
| 229 | 234 | log: createLog("forge", owner), |
| 230 | signals: { errors, refused: new RefusedLedger() }, | |
| 235 | signals: { | |
| 236 | errors, | |
| 237 | refused: new RefusedLedger(), | |
| 238 | memory: new MemoryLedger(), | |
| 239 | }, | |
| 231 | 240 | reposRoot, |
| 232 | 241 | // This process's own: two forges share a data directory for the length |
| 233 | 242 | // 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( | ||
| 127 | 127 | env: gitEnv(env), |
| 128 | 128 | stdin: "pipe", |
| 129 | 129 | 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", | |
| 131 | 133 | }); |
| 132 | 134 | let proc: ReturnType<typeof spawn>; |
| 133 | 135 | try { |
| @@ -174,7 +176,7 @@ async function spawnService( | ||
| 174 | 176 | * loose in the process. |
| 175 | 177 | */ |
| 176 | 178 | async function feedStdin( |
| 177 | proc: Bun.Subprocess<"pipe", "pipe", "pipe">, | |
| 179 | proc: Bun.Subprocess<"pipe", "pipe", "ignore">, | |
| 178 | 180 | service: GitService, |
| 179 | 181 | request: Request, |
| 180 | 182 | ): 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"; | ||
| 10 | 10 | import { unsealReleased } from "../actions/sealed.ts"; |
| 11 | 11 | import { accessPage } from "../web/pages/access.ts"; |
| 12 | 12 | import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; |
| 13 | import { systemPage } from "../web/pages/system.ts"; | |
| 13 | 14 | import { flowPage } from "../web/pages/flow.ts"; |
| 14 | 15 | import { resiliencePage } from "../web/pages/resilience.ts"; |
| 15 | 16 | import { limitsPage, limitsSet } from "../web/pages/admin-limits.ts"; |
| @@ -54,6 +55,7 @@ import { | ||
| 54 | 55 | verifyPassword, |
| 55 | 56 | } from "../core/users.ts"; |
| 56 | 57 | import { edgeIdentity } from "./edge.ts"; |
| 58 | import { settleOnAbort } from "./abort.ts"; | |
| 57 | 59 | import { liveResponse, readyResponse } from "./health.ts"; |
| 58 | 60 | import { runGit } from "../git/env.ts"; |
| 59 | 61 | import { noteRefusedInternal } from "../kernel/internal_refused.ts"; |
| @@ -726,6 +728,7 @@ export function buildRouter(): Router<Handler> { | ||
| 726 | 728 | router.add("GET", "/settings/access", accessPage); |
| 727 | 729 | router.add("GET", "/settings/capacity", capacityPage); |
| 728 | 730 | router.add("POST", "/settings/capacity", capacitySet); |
| 731 | router.add("GET", "/system", systemPage); | |
| 729 | 732 | router.add("GET", "/boards", boardsList); |
| 730 | 733 | router.add("GET", "/boards/data", boardsPage); |
| 731 | 734 | router.add("POST", "/boards/new", boardNew); |
| @@ -1857,7 +1860,10 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1857 | 1860 | // Everything the forge answers for itself leaves through this one |
| 1858 | 1861 | // door, so a responder added next year cannot forget the floor. |
| 1859 | 1862 | const response = securityFloor( |
| 1860 | await answer(app, router, apiRouter, limiter, request), | |
| 1863 | await settleOnAbort( | |
| 1864 | request, | |
| 1865 | answer(app, router, apiRouter, limiter, request), | |
| 1866 | ), | |
| 1861 | 1867 | ); |
| 1862 | 1868 | logged(app.config.dataDir, request, response, started); |
| 1863 | 1869 | 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 @@ | ||
| 4 | 4 | * environment-only — a handful of variables, all with sane defaults. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { readMemory } from "./kernel/memory_ledger.ts"; | |
| 7 | 8 | import { startSampler } from "./boards/sampler.ts"; |
| 8 | 9 | import { sweepStanding } from "./crew/standing.ts"; |
| 9 | 10 | import { handover } from "./release/swap.ts"; |
| @@ -476,6 +477,13 @@ if (ssh) | ||
| 476 | 477 | // failed; checks are queued again while their commit heads an open pull; |
| 477 | 478 | // agent runs are the crew's to queue again, unless there is no crew here to |
| 478 | 479 | // 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 | ||
| 479 | 487 | const leaseTimer = setInterval(() => { |
| 480 | 488 | failAbandonedRuns( |
| 481 | 489 | app.db, |
| @@ -514,6 +522,7 @@ function shutdown(signal: NodeJS.Signals): void { | ||
| 514 | 522 | clearInterval(heartbeatTimer); |
| 515 | 523 | clearInterval(syncTimer); |
| 516 | 524 | clearInterval(staleTimer); |
| 525 | clearInterval(memoryTimer); | |
| 517 | 526 | clearInterval(leaseTimer); |
| 518 | 527 | // The platform's SIGTERM: the listener stays open while routers learn |
| 519 | 528 | // 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 | ||
| 438 | 438 | expect(stuck?.sentence).toBe(`Run ${live.id} is stuck: no heartbeat for 4 min (limit 3).`); |
| 439 | 439 | app.db.query("DELETE FROM run").run(); |
| 440 | 440 | }); |
| 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 | }); |
new above
offline