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

Sentinel: memory-growth was degraded 14 minutes today: The forge's own memory is 4287 MiB, over twice its first-hour 1716 MiB and past the 2176 MiB more its database caches m… #17561

opened this

Merged 22h 54m ago, live in production

mason/forge:mason/17558-sentinel-memory-growth-was-degraded-14-m → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/17558-sentinel-memory-growth-was-degraded-14-m was merged into main as 6a374d7.

Review

Sign in to review this change.
6 files changed +107 −8
docs/features/memory-growth.md +2
@@ -35,6 +35,8 @@ The sentinel's memory-growth issue quotes the watch's evidence: each VM's heap,
3535
3636 **The snapshot collects as it reads (#17493).** The finding after that fix still had `snapshot-stream` open before the trip and the main heap at 416 MiB in the first hour, 2855 MiB at the trip and 462 MiB now: garbage again, held every count flat. One forge's pass cuts a multi-GiB database through fresh buffers, so collecting once per forge left the pile inside it. `takeSnapshot` now runs `Bun.gc(false)` each 256 MiB of plain bytes read (`settle`, `settleBytes` are its test seams). Not measured on production's data: the next finding's `memory heap main` line at the trip says whether it was the whole. Test: `test/snapshot-stream.test.ts`.
3737
38 **A full collection when the asked one falls behind (#17558).** The finding after that fix, on a release that had it, still had `snapshot-stream` open before the trip and the main heap at 416 MiB in the first hour, 1927 MiB at the trip and 2655 MiB afterwards: `Bun.gc(false)` only asks, and on a heap of GiB the ask did not keep up. `src/snapshot/settle.ts` (`settler`) keeps the asked collection, and when what the VM holds (JS heap plus external memory, where a chunk's fresh buffers are counted) stands 512 MiB above where the last full one left it, runs `Bun.gc(true)` and watches from there; the stream pass and `takeSnapshot` both use it. The loop is held for each full collection, a few hundred ms on a live heap of a few hundred MiB. Not measured on production's data: the next finding's `memory heap main` line says whether it was the whole. Test: `test/snapshot-settle.test.ts`.
39
3840 A restart between the growth and the filing (a release restarts the forge several times a day) leaves a watch that never saw it: the sentence is the stored one of the process that grew, and its own evidence would say `trip none`. So each minute the need is open, the sampler writes the watch's evidence to `memory-kept.json` under the data directory (`perf/memory_kept.ts`, #16872); a finding filed by a later process that has not tripped quotes those lines, kept that day, under `memory kept by the process started …, at its last grown minute …; the forge restarted since`, and ends with one `memory now (process started …)` line for the process reading it.
3941
4042 The need clears by itself once RSS falls under twice the baseline. A process that slept through its first hour has no baseline and raises none.
src/snapshot/settle.ts added +45
@@ -0,0 +1,45 @@
1 /**
2 * Letting go of a snapshot's garbage while it is being cut (#17558).
3 *
4 * `Bun.gc(false)` asks for a collection and returns; on a heap of GiB the request did not keep up
5 * with a pass cutting multi-GiB databases through fresh buffers: the finding after #17493 still had
6 * the main heap at 416 MiB in the first hour, 1927 MiB at the trip and 2655 MiB afterwards. So the
7 * asked collection stays the usual one, and when what the VM holds stands `FORCE_AFTER_BYTES`
8 * above where the last forced collection left it, the next one is run to the end, the loop held
9 * for it.
10 *
11 * What the VM holds is its JS heap plus its external memory: a chunk's fresh `Uint8Array` and
12 * `Buffer` bytes are counted as external, not as `heapUsed`.
13 */
14
15 /** Growth over the last full collection that earns a full one now. */
16 const FORCE_AFTER_BYTES = 512 * 1024 * 1024;
17
18 /** The reading the default settler takes; a test replaces `read` to move it. */
19 export const held = {
20 read: (): number => {
21 const m = process.memoryUsage();
22 return m.heapUsed + Math.max(m.external, m.arrayBuffers);
23 },
outdated

heapUsed excludes ArrayBuffer/external memory, which is where the snapshot's fresh buffers live. Measure external + arrayBuffers too (or RSS), or the threshold may never be reached. Also read the heap once per call.

24 };
25
26 /**
27 * A `settle` for one pass. `heap` and `gc` are the test seams (bytes the VM holds; `Bun.gc`). The
28 * reading is taken once per call.
29 */
30 export function settler(
31 heap: () => number = () => held.read(),
32 gc: (full: boolean) => void = (full) => void Bun.gc(full),
33 forceAfter = FORCE_AFTER_BYTES,
34 ): () => void {
35 let floor = heap();
36 return () => {
37 const now = heap();
38 if (now - floor >= forceAfter) {
39 gc(true);
40 floor = heap();
41 return;
42 }
43 gc(false);
44 };
45 }
src/snapshot/snapshot.ts +3 −2
@@ -53,6 +53,7 @@ import type { PackedFile } from "./parts.ts";
5353 import { bodiesOf, type Store } from "../blob/store.ts";
5454 import { putsAtOnce } from "./line.ts";
5555 import { unwrapKey, wrapKey, WRAPPED_KEY } from "./wrap.ts";
56 import { settler } from "./settle.ts";
5657 import { during } from "../perf/jobs.ts";
5758
5859 const log = createLog("snapshot");
@@ -350,7 +351,7 @@ export interface Snapshotter {
350351 readonly chunks?: ChunkView | undefined;
351352 /**
352353 * Test seams for the collection inside one forge's pass (#17493): `settle` runs each time
353 * `settleBytes` more plain bytes were read. Default: `Bun.gc(false)` every 256 MiB.
354 * `settleBytes` more plain bytes were read. Default: a `settler()` every 256 MiB.
354355 */
355356 readonly settle?: (() => void) | undefined;
356357 readonly settleBytes?: number | undefined;
@@ -515,7 +516,7 @@ export async function takeSnapshot(
515516 let found = 0;
516517 // One chunk: its name, and its bytes to the queue unless the store has them.
517518 const settleAt = forge.settleBytes ?? SETTLE_BYTES;
518 const settle = forge.settle ?? ((): void => void Bun.gc(false));
519 const settle = forge.settle ?? settler();
519520 let settledAt = 0;
520521 const send = async (plain: Uint8Array): Promise<string> => {
521522 // A forge of several GiB cuts every chunk through fresh buffers; the collector lets them pile
src/snapshot/stream.ts +2 −6
@@ -13,6 +13,7 @@ import { readFileSync } from "node:fs";
1313 import { join } from "node:path";
1414 import { hostedSources } from "./hosted.ts";
1515 import { keepJson } from "./kept_file.ts";
16 import { settler } from "./settle.ts";
1617
1718 /** How often a pass runs. */
1819 export const STREAM_EVERY_MS = 5 * 60_000;
@@ -75,11 +76,6 @@ export function streamLag(dataDir: string, now = Date.now()): StreamLag[] {
7576 .sort((a, b) => (a.name < b.name ? -1 : 1));
7677 }
7778
78 /** A collection between forges: not forced to be full, so the loop is held briefly. */
79 const collectGarbage = (): void => {
80 Bun.gc(false);
81 };
82
8379 /**
8480 * One pass over every hosted forge, one after another. `take` stores one forge and answers the
8581 * bytes it holds, or throws; a forge that throws costs that forge, never the pass. A forge that is
@@ -89,7 +85,7 @@ export async function streamPass(
8985 dataDir: string,
9086 take: (name: string) => Promise<{ readonly bytes: number; readonly hosted?: readonly { readonly why?: string | undefined }[] | undefined }>,
9187 now: () => Date = () => new Date(),
92 settle: () => void = collectGarbage,
88 settle: () => void = settler(),

This default is the fix, but nothing tests it: reverting to Bun.gc(false) keeps every test green. Add a test that observes the default.

9389 ): Promise<StreamEntry[]> {
9490 const before = new Map(readStream(dataDir).map((e) => [e.name, e]));
9591 const out: StreamEntry[] = [];
test/snapshot-settle.test.ts added +29
@@ -0,0 +1,29 @@
1 import { expect, test } from "bun:test";
2 import { held, settler } from "../src/snapshot/settle.ts";
3
4 test("a heap that outgrows its last full collection is collected to the end, then watched from there (#17558)", () => {
5 let heap = 100;
6 const calls: boolean[] = [];
7 const settle = settler(() => heap, (full) => void calls.push(full), 50);
8 settle();
9 heap = 149;
10 settle();
11 expect(calls).toEqual([false, false]);
12 heap = 150;
13 settle();
14 expect(calls).toEqual([false, false, true]);
15 settle();
16 expect(calls).toEqual([false, false, true, false]);
17 });
18
19 test("what the VM holds counts external buffers, not only the JS heap (#17558)", () => {
20 const real = process.memoryUsage;
21 try {
22 process.memoryUsage = Object.assign(() => ({ rss: 0, heapTotal: 0, heapUsed: 10, external: 5, arrayBuffers: 40 }), { rss: real.rss });
23 expect(held.read()).toBe(50);
24 process.memoryUsage = Object.assign(() => ({ rss: 0, heapTotal: 0, heapUsed: 10, external: 70, arrayBuffers: 40 }), { rss: real.rss });
25 expect(held.read()).toBe(80);
26 } finally {
27 process.memoryUsage = real;
28 }
29 });
test/snapshot-stream.test.ts +26
@@ -22,6 +22,7 @@ import { readStream, STREAM_LATE_MS, streamLag, streamPass } from "../src/snapsh
2222 import type { Ctx } from "../src/http/context.ts";
2323 import { tool as systemTool } from "../src/http/mcp/tools/system.ts";
2424 import { pollUntil } from "./helpers/poll.ts";
25 import { held } from "../src/snapshot/settle.ts";
2526
2627 const PASS = "correct horse battery staple";
2728
@@ -123,6 +124,31 @@ describe("the stream of hosted forges", () => {
123124 expect(seen).toEqual(["take kid", "settle", "take kid", "settle"]);
124125 });
125126
127 test("the defaults collect to the end once the VM's held bytes have outgrown the last collection (#17558)", async () => {
128 const store = dirStore(join(root, `store-${n++}`));
129 const realGc = Bun.gc;
130 const realRead = held.read;
131 const calls: boolean[] = [];
132 let bytes = 0;
133 held.read = () => bytes;
134 (Bun as { gc: unknown }).gc = (full?: boolean) => void calls.push(full === true);
135 try {
136 // The pass's default settle: the forge's take raises what the VM holds by 1 GiB.
137 await streamPass(parent.config.dataDir, async () => { bytes += 2 ** 30; throw new Error("no"); });
138 expect(calls).toEqual([true]);
139 // The snapshot's default settle, at its first read.
140 calls.length = 0;
141 bytes = 0;
142 const sent = takeSnapshot({ ...shape(), stream: "kid", settleBytes: 1 }, store);
143 bytes += 2 ** 30;
144 await sent;
145 expect(calls).toContain(true);
146 } finally {
147 (Bun as { gc: unknown }).gc = realGc;
148 held.read = realRead;
149 }
150 });
151
126152 test("a forge's pass collects as it reads, not only when it ends (#17493)", async () => {
127153 const store = dirStore(join(root, `store-${n++}`));
128154 let ran = 0;

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

Keyboard shortcuts

Docs