Public: anyone can read this; the crew can change it.
A small forge reads its pictures on its own thread until one is slow, so an idle forge holds half the memory #16846
Juniper asked for changes (review 01m8q55kzxa24s4pscp782vpjp)
sold/idle-memory → main 2 commits 2 threads · 2 unresolved
This pull asks for more cpus. Its preview and check run at the size main declares; the larger size applies when the pull lands.
6 files
changed +148
−4
scripts/gate.ts +1
| @@ -58,6 +58,7 @@ export const SLOW: readonly Exclusion[] = [ | ||
| 58 | 58 | { file: "test/apps-toolbar.test.ts", reason: "its opt-out test deploys a real scaffolded app twice; 2.35 s under full-suite load, 2.8 s alone here", issue: 13773 }, |
| 59 | 59 | { file: "test/following-incoming.test.ts", reason: "makes 52 real commits to pass the 50-line cap of the incoming list; 2.4 s under full-suite load, 0.5 s alone", issue: 13144 }, |
| 60 | 60 | { file: "test/release-sweep-safety-14784.test.ts", reason: "boots the real src/main.ts twice at once (proof and live control) to prove the outbox untouched; 4.1 s a test under full-suite load", issue: 14784 }, |
| 61 | { file: "test/idle-memory.test.ts", reason: "boots the real src/main.ts and leaves it idle 15 s before reading its resident memory, the point where its boot work has settled; about 25 s a file alone", issue: 16840 }, | |
| 61 | 62 | { file: "test/spawn-cell-looks.test.ts", reason: "boots a real child forge in a cell (~30 s) and waits for its own looks job to take a picture", issue: 10620 }, |
| 62 | 63 | // From the breach list closing this pull's check log at e2a5c15 (#12088): |
| 63 | 64 | // every test over the 2 s budget, its file named once with its slowest time. |
src/flow/lanes.ts +6 −3
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | */ |
| 20 | 20 | |
| 21 | 21 | import type { Database } from "bun:sqlite"; |
| 22 | import { readHere, readsHere } from "./on_thread.ts"; | |
| 22 | 23 | import { queueStatus } from "../checks/queue.ts"; |
| 23 | 24 | import { canRead, getReposByIds, type Repo } from "../core/repos.ts"; |
| 24 | 25 | import type { User } from "../core/users.ts"; |
| @@ -260,9 +261,11 @@ function refresh( | ||
| 260 | 261 | state.startedAt = now; |
| 261 | 262 | const reading = reader !== undefined |
| 262 | 263 | ? reader(db, options, now, stamp) |
| 263 | : offThread(db) | |
| 264 | ? viaWorker(db, options, now, stamp) | |
| 265 | : Promise.resolve().then(() => readLanesInline(db, options, now)); | |
| 264 | : !offThread(db) | |
| 265 | ? Promise.resolve().then(() => readLanesInline(db, options, now)) | |
| 266 | : readsHere(db, "lanes") && worker === undefined | |
| 267 | ? readHere(db, "lanes", () => readLanesInline(db, options, now)) | |
| 268 | : viaWorker(db, options, now, stamp); | |
| 266 | 269 | const p = reading.then( |
| 267 | 270 | (picture) => { |
| 268 | 271 | state.picture = picture; |
src/flow/on_thread.ts added +37
| @@ -0,0 +1,37 @@ | ||
| 1 | /** | |
| 2 | * Where a picture is read (#16840): on the forge's own thread while its readings stay cheap, in a | |
| 3 | * worker once one is not. A worker thread loads its own copy of the reading code, about 2,450 | |
| 4 | * modules and some 100 MB a worker, so a small forge whose pictures read in a few milliseconds | |
| 5 | * never starts one; a forge whose readings grow moves that kind of reading to its worker at the | |
| 6 | * first slow one, and it stays there for as long as the process runs. The reading is the same | |
| 7 | * either way (the worker's code path, with its kept parts), only the thread differs. What has moved | |
| 8 | * is the forge's, kept by its database (#12569), so two forges in one process never share it. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { Database } from "bun:sqlite"; | |
| 12 | ||
| 13 | /** | |
| 14 | * A reading longer than `underMs` moves its kind to a worker for good. The one seam for a test: a | |
| 15 | * negative `underMs` sends every reading to its worker, as a test of the worker itself needs. | |
| 16 | */ | |
| 17 | export const readPlacement = { underMs: 50 }; | |
| 18 | ||
| 19 | /** The kinds that have had a slow reading, per forge (its database). */ | |
| 20 | const movedBy = new WeakMap<Database, Set<string>>(); | |
| 21 | ||
| 22 | /** True while a forge reads `kind` on this thread. */ | |
| 23 | export const readsHere = (db: Database, kind: string): boolean => readPlacement.underMs >= 0 && movedBy.get(db)?.has(kind) !== true; | |
| 24 | ||
| 25 | /** Read `kind` on this thread, timing it: a slow reading sends the forge's next ones to a worker. */ | |
| 26 | export async function readHere<T>(db: Database, kind: string, read: () => T | Promise<T>): Promise<T> { | |
| 27 | const began = performance.now(); | |
| 28 | try { | |
| 29 | return await read(); | |
| 30 | } finally { | |
| 31 | if (performance.now() - began > readPlacement.underMs) { | |
| 32 | const moved = movedBy.get(db) ?? new Set<string>(); | |
| 33 | movedBy.set(db, moved); | |
| 34 | moved.add(kind); | |
| 35 | } | |
| 36 | } | |
| 37 | } |
src/flow/pages.ts +13 −1
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | */ |
| 14 | 14 | |
| 15 | 15 | import type { Database } from "bun:sqlite"; |
| 16 | import { readHere, readsHere } from "./on_thread.ts"; | |
| 16 | 17 | import type { App } from "../app.ts"; |
| 17 | 18 | import { listPins } from "../core/pins.ts"; |
| 18 | 19 | import { getRepo, getReposByIds, type Repo } from "../core/repos.ts"; |
| @@ -168,11 +169,22 @@ export function usePagesReader(next: typeof reader): void { | ||
| 168 | 169 | |
| 169 | 170 | const offThread = (db: Database): boolean => reader !== undefined || (process.env["NODE_ENV"] !== "test" && db.filename !== "" && db.filename !== ":memory:"); |
| 170 | 171 | |
| 172 | /** The worker's reading, on this thread (`on_thread.ts`): the same code path and kept parts, the forge's own database. */ | |
| 173 | const threadEnvs = new WeakMap<Database, PagesEnv>(); | |
| 174 | function threadEnv(app: App): PagesEnv { | |
| 175 | let env = threadEnvs.get(app.db); | |
| 176 | if (env === undefined) threadEnvs.set(app.db, (env = { db: app.db, reposRoot: app.reposRoot, config: pagesConfig(app.config), ceilingUsd: forgeCeiling(app.config), inline: false })); | |
| 177 | return env; | |
| 178 | } | |
| 179 | ||
| 171 | 180 | function viaWorker(app: App, job: PageJob): Promise<Picture> { |
| 172 | 181 | if (reader !== undefined) return reader(app, job); |
| 182 | const lane = laneOf(job); | |
| 183 | // A lane reads here until a reading is slow, and never starts its worker before then. | |
| 184 | if (readsHere(app.db, `pages:${lane}`) && !workers.has(lane)) | |
| 185 | return readHere(app.db, `pages:${lane}`, () => readPagePicture(threadEnv(app), job, job.kind === "boards" ? learnedPulls() : [])); | |
| 173 | 186 | return new Promise((resolve, reject) => { |
| 174 | 187 | const id = ++askId; |
| 175 | const lane = laneOf(job); | |
| 176 | 188 | try { |
| 177 | 189 | const w = workerOf(lane); |
| 178 | 190 | open.set(id, { lane, worker: w, resolve, reject }); |
test/idle-memory.test.ts added +87
| @@ -0,0 +1,87 @@ | ||
| 1 | /** | |
| 2 | * An idle forge's memory (#16840, D1). A fresh forge is booted from `main.ts` in a child process, | |
| 3 | * left alone, and its resident memory read from the system (`ps`, as an operator reads it): it must | |
| 4 | * stay under the budget. Before #16840 a fresh forge sat at about 400 MB on macOS, two thirds of it | |
| 5 | * the pages and lanes workers, each loading its own ~2,450 modules for pictures a small forge reads | |
| 6 | * in milliseconds (`src/flow/on_thread.ts` now reads those on the forge's thread until one is | |
| 7 | * slow). Measured after, macOS arm64, Bun 1.4.4: 210 to 225 MB by the operator script, and 277 to 322 | |
| 8 | * MB 20 to 40 s into a boot, where the maintenance duties have run once. | |
| 9 | * | |
| 10 | * @tree-scan: boots all of src/ through main.ts. | |
| 11 | */ | |
| 12 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 13 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 14 | import { tmpdir } from "node:os"; | |
| 15 | import { join } from "node:path"; | |
| 16 | import { Database } from "bun:sqlite"; | |
| 17 | import { readHere, readPlacement, readsHere } from "../src/flow/on_thread.ts"; | |
| 18 | import { freePort } from "../src/kernel/port.ts"; | |
| 19 | ||
| 20 | const MAIN = join(import.meta.dir, "..", "src", "main.ts"); | |
| 21 | /** How long the forge is left alone after it answers before its memory is read. */ | |
| 22 | const IDLE_MS = 15_000; | |
| 23 | /** How soon a boot that has not answered yet is asked again. */ | |
| 24 | const ASK_AGAIN_MS = 250; | |
| 25 | /** | |
| 26 | * Idle resident memory, MB: the measured number with room for a loaded machine. Linux counts more | |
| 27 | * of what a process maps than macOS does (small forges on vxrail read 580 to 630 MB before this); | |
| 28 | * its budget is lowered to what a Linux check runner reports once one has. | |
| 29 | */ | |
| 30 | const BUDGET_MB: Record<string, number> = { darwin: 350, linux: 480 }; | |
| 31 | ||
| 32 | let root = ""; | |
| 33 | beforeAll(() => { | |
| 34 | root = mkdtempSync(join(tmpdir(), "forge-idle-memory-")); | |
| 35 | }); | |
| 36 | afterAll(() => rmSync(root, { recursive: true, force: true })); | |
| 37 | ||
| 38 | const rssMb = async (pid: number): Promise<number> => { | |
| 39 | const ps = Bun.spawn(["ps", "-o", "rss=", "-p", String(pid)], { stdout: "pipe", stderr: "ignore" }); | |
| 40 | return Math.round(Number((await new Response(ps.stdout).text()).trim()) / 1024); | |
| 41 | }; | |
| 42 | ||
| 43 | test.skipIf(BUDGET_MB[process.platform] === undefined)( | |
| 44 | "a fresh forge left alone stays under its memory budget", | |
| 45 | async () => { | |
| 46 | const port = await freePort(); | |
| 47 | const env: Record<string, string> = { | |
| 48 | PATH: process.env["PATH"] ?? "/usr/local/bin:/usr/bin:/bin", | |
| 49 | FORGE_DATA: join(root, "data"), PORT: String(port), FORGE_SSH_PORT: "0", FORGE_BIND: "127.0.0.1", FORGE_HOST: "localhost", | |
| 50 | }; | |
| 51 | for (const key of ["HOME", "TMPDIR", "FORGE_CELLS", "FORGE_TEST_SOCKET"]) { | |
| 52 | const value = process.env[key]; | |
| 53 | if (value !== undefined && value !== "") env[key] = value; | |
| 54 | } | |
| 55 | const child = Bun.spawn([process.execPath, MAIN], { cwd: root, env, stdin: "ignore", stdout: "ignore", stderr: "ignore" }); | |
| 56 | try { | |
| 57 | let health = 0; | |
| 58 | for (const asked = performance.now(); health !== 200 && child.exitCode === null && performance.now() - asked < 60_000; ) { | |
| 59 | health = await fetch(`http://127.0.0.1:${port}/healthz`, { signal: AbortSignal.timeout(5_000) }).then((r) => r.status, () => 0); | |
| 60 | if (health !== 200) await Bun.sleep(ASK_AGAIN_MS); // real-timer: a real forge in a child process, booting | |
| 61 | } | |
| 62 | expect(health, "the forge answers").toBe(200); | |
| 63 | await Bun.sleep(IDLE_MS); // real-timer: an idle forge, left alone for as long as its warm-ups take | |
| 64 | const rss = await rssMb(child.pid); | |
| 65 | expect(child.exitCode, "still running").toBeNull(); | |
| 66 | expect(rss, `idle resident memory ${rss} MB, budget ${BUDGET_MB[process.platform]} MB`).toBeLessThanOrEqual(BUDGET_MB[process.platform]!); | |
| 67 | } finally { | |
| 68 | child.kill(); | |
| 69 | await child.exited; | |
| 70 | } | |
| 71 | }, | |
| 72 | 120_000, | |
| 73 | ); | |
| 74 | ||
| 75 | test("a kind of picture reads on the forge's thread until one reading is slow, then stays off it", async () => { | |
| 76 | const db = new Database(":memory:"); | |
| 77 | const other = new Database(":memory:"); | |
| 78 | expect(readsHere(db, "test:fast")).toBe(true); | |
| 79 | expect(await readHere(db, "test:fast", () => 7)).toBe(7); | |
| 80 | expect(readsHere(db, "test:fast")).toBe(true); | |
| 81 | await readHere(db, "test:slow", () => Bun.sleep(readPlacement.underMs + 20).then(() => 1)); // real-timer: a reading that is slow on purpose | |
| 82 | expect(readsHere(db, "test:slow")).toBe(false); | |
| 83 | expect(readsHere(db, "test:fast")).toBe(true); | |
| 84 | // Another forge in the same process keeps its own placement. | |
| 85 | expect(readsHere(other, "test:slow")).toBe(true); | |
| 86 | await expect(readHere(db, "test:fails", () => Promise.reject(new Error("no")))).rejects.toThrow("no"); | |
| 87 | }); |
test/pages-worker-retire.test.ts +4
| @@ -9,6 +9,7 @@ import { tmpdir } from "node:os"; | ||
| 9 | 9 | import { join } from "node:path"; |
| 10 | 10 | import { createApp, type App } from "../src/app.ts"; |
| 11 | 11 | import { flowPicture, isFailed, pagesWorkers, RETIRE_AFTER } from "../src/flow/pages.ts"; |
| 12 | import { readPlacement } from "../src/flow/on_thread.ts"; | |
| 12 | 13 | import { seedHomeFlow, type HomeFlowSeed } from "./helpers/home-flow-seed.ts"; |
| 13 | 14 | |
| 14 | 15 | let dataDir: string; |
| @@ -22,10 +23,13 @@ beforeAll(async () => { | ||
| 22 | 23 | seed = await seedHomeFlow(app); |
| 23 | 24 | // The pages are read by the worker only outside `bun test`'s inline path. |
| 24 | 25 | process.env["NODE_ENV"] = "production"; |
| 26 | // And by the worker even while a reading is cheap enough for the forge's own thread (#16840). | |
| 27 | readPlacement.underMs = -1; | |
| 25 | 28 | }); |
| 26 | 29 | |
| 27 | 30 | afterAll(async () => { |
| 28 | 31 | pagesWorkers.retireAfter = RETIRE_AFTER; |
| 32 | readPlacement.underMs = 50; | |
| 29 | 33 | process.env["NODE_ENV"] = env ?? "test"; |
| 30 | 34 | app.close(); |
| 31 | 35 | await rm(dataDir, { recursive: true, force: true }); |
new above
offline
No test reaches this branch: nothing shows a cheap lanes reading starts no worker, or that a slow one moves later readings to it. Also, the first slow reading runs on the event loop before it is known to be slow (see the body).