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

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

Merged opened this

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

Merged

scout/forge:scout/16942-sentinel-memory-growth-was-degraded-25-m → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/16942-sentinel-memory-growth-was-degraded-25-m was merged into main as 9e6d1ed.

Review

Sign in to review this change.
5 files changed +121 −18
docs/features/memory-growth.md +2
@@ -45,6 +45,8 @@ Found on a copy of production's data with no network, production's own work on (
4545
4646 A new long-lived collection names itself in `heldOf(app)` (a forge's) or `threadHeld` (the thread's), with a bound and a test of its eviction. Named today: `turn`, `requests in flight`, `event streams`, `request counters`, `route timings`, `map plans`, `map lanes`, `map layouts`, `finishing said` (the newest 512 pulls, `src/crew/said_once.ts`), and three the crew keeps per pull or per check (`autonomy conflicted pulls`, `checks retried`, `app links said`), each now bounded to its newest 1024 entries (`src/perf/bounded.ts`, #15210).
4747
48 **Every statement a connection keeps is bounded (#16942).** Bun's statement cache, raised to 4,096 texts a connection (#9514), keeps the first texts it meets for the connection's life and never lets one go; a text that names a number (a browse page's `OFFSET`, a board's `LIMIT`) took a slot forever, each a compiled program in malloc that the collector never feels, so the memory outside every heap filled through the day. A connection `openDb` or a worker's `keepFixedTexts` makes now keeps its fixed texts in a cache of its own of 1,024, least recently used out first (`src/kernel/list_texts.ts`), beside the 64 list texts (#14479). Its count reads on the `memory holds:` line as `statements kept`, and the sentinel's finding quotes it: a count pinned at 1,024 a connection with the outside still climbing means the growth is elsewhere. Test: `test/fixed-texts.test.ts`.
49
4850 ## Reading the retainers (#15286)
4951
5052 `heapStats()` and a snapshot walk the whole heap, so neither runs on the serving process by default. On a copy of production's data (never production), set `FORGE_HEAP_CAPTURE_DIR=<dir under FORGE_APP_DATA or $TMPDIR>` (and `FORGE_HEAP_CAPTURE_MIN`, default 20): the process writes `heap-<minutes up>.json` (object counts by type after a full collection) and `heap-<minutes up>.snapshot.json` at boot and every interval (`src/perf/heap_capture.ts`; unset, nothing runs). Then `bun scripts/heap-growth.ts heap-0000.json heap-0060.json` prints the types that grew, bytes by type, and for the three that grew most the holders as `<holder type>.<edge name>` with count and bytes (`src/perf/heap_diff.ts`). The holder type and edge name point to the module: grep the property name.
src/kernel/db.ts +3 −2
@@ -61,8 +61,9 @@ const MMAP_BYTES = 512 * 1024 * 1024;
6161 * preparing. The forge's queries are fixed texts (about 2,000 call sites), so
6262 * this holds every one of them; a text past the cap is prepared per call as
6363 * before, never wrong. A text whose IN list grows with the data is not one of
64 * them: `list_texts.ts` keeps those apart, bounded (#14479). Bun reads it on each `query`, so set
65 * once here.
64 * them: `list_texts.ts` keeps those apart, bounded (#14479). A connection `openDb` makes keeps
65 * every text in `list_texts.ts`'s own bounded caches instead (#16942), so this cap now serves only
66 * a handle opened without `keepFixedTexts`. Bun reads it on each `query`, so set once here.
6667 */
6768 export const QUERY_CACHE = 4096;
6869 (Database as unknown as { MAX_QUERY_CACHE_SIZE: number }).MAX_QUERY_CACHE_SIZE = QUERY_CACHE;
src/kernel/list_texts.ts +45 −15
@@ -12,9 +12,9 @@
1212 *
1313 * `keepFixedTexts` hands a text with an `IN` list of three or more placeholders to a small cache
1414 * of its own instead (`LIST_TEXTS_KEPT` a connection, least recently used out first): a list whose
15 * length repeats is still prepared once, and one pushed out is garbage the collector frees. A text
16 * with no such list keeps Bun's cache, as before. A list of one or two placeholders stays there
17 * too: at most two texts a call site, however the data moves.
15 * length repeats is still prepared once, and one pushed out is garbage the collector frees. Every
16 * other text is kept the same way, in a cache of `FIXED_TEXTS_KEPT` (#16942), so Bun's
17 * first-come, kept-forever cache serves no wrapped connection.
1818 */
1919
2020 import type { Database, Statement } from "bun:sqlite";
@@ -28,8 +28,13 @@ const LIST = /\bIN\s*\(\s*\?\d*(?:\s*,\s*\?\d*){2,}\s*\)/i;
2828 /** Whether `sql` holds an `IN` list long enough to have been built from values. */
2929 export const isListText = (sql: string): boolean => LIST.test(sql);
3030
31 /** The fixed texts one connection keeps prepared, least recently used out first (#16942). */
32 export const FIXED_TEXTS_KEPT = 1024;
33
3134 /** The list texts kept on this thread, across its connections. */
3235 let keptHere = 0;
36 /** The fixed texts kept on this thread, across its connections. */
37 let fixedKeptHere = 0;
3338
3439 /**
3540 * How many list texts this thread keeps prepared: `perf/held.ts` names it on the `memory holds:`
@@ -37,10 +42,21 @@ let keptHere = 0;
3742 */
3843 export const listTextsKeptHere = (): number => keptHere;
3944
45 /** How many fixed texts this thread keeps prepared, named beside the list texts. */
46 export const fixedTextsKeptHere = (): number => fixedKeptHere;
47
4048 /** Each wrapped connection's list texts, oldest first. */
4149 const listsOf = new WeakMap<Database, Map<string, Statement>>();
4250
43 /** Route `db.query` so a list text is kept in a bounded cache of its own; returns `db`. */
51 /**
52 * Route `db.query` so every text is kept in a bounded cache of its own; returns `db`. A list text
53 * goes to one of `LIST_TEXTS_KEPT`, every other text to one of `FIXED_TEXTS_KEPT`, so a list's
54 * churn never pushes out a fixed text. Bun's own cache keeps the first texts a connection meets
55 * for its whole life and never lets one go: a text that names a number (a page's `OFFSET`, a
56 * board's `LIMIT`) took a slot forever, and the slots filled through the day, each a compiled
57 * program in malloc the collector never feels (#16942). A statement pushed out is not finalized
58 * (a caller may still be stepping it); it is garbage the collector frees.
59 */
4460 export function keepFixedTexts(db: Database): Database {
4561 if (listsOf.has(db)) return db;
4662 const handle = db as unknown as { query: (sql: string) => Statement; close: (...a: unknown[]) => void };
@@ -49,27 +65,41 @@ export function keepFixedTexts(db: Database): Database {
4965 // Bound now, so a later wrapper of `db.prepare` (a statement counter) sees one call, not two.
5066 const prepare = db.prepare.bind(db);
5167 const lists = new Map<string, Statement>();
68 const fixed = new Map<string, Statement>();
5269 listsOf.set(db, lists);
53 handle.query = (sql: string): Statement => {
54 if (typeof sql !== "string" || !isListText(sql)) return cached(sql);
55 const known = lists.get(sql);
70 const keep = (kept: Map<string, Statement>, sql: string, max: number): [Statement, number] => {
71 const known = kept.get(sql);
5672 if (known !== undefined) {
57 lists.delete(sql);
58 lists.set(sql, known);
59 return known;
73 kept.delete(sql);
74 kept.set(sql, known);
75 return [known, 0];
6076 }
6177 const made = prepare(sql);
62 lists.set(sql, made);
63 keptHere++;
64 if (lists.size > LIST_TEXTS_KEPT) {
65 lists.delete(lists.keys().next().value!);
66 keptHere--;
78 kept.set(sql, made);
79 if (kept.size <= max) return [made, 1];
80 kept.delete(kept.keys().next().value!);
81 return [made, 0];
82 };
83 handle.query = (sql: string): Statement => {
84 // Not a text: Bun's own query says what is wrong with it.
85 if (typeof sql !== "string") return cached(sql);
86 if (isListText(sql)) {
87 const [made, added] = keep(lists, sql, LIST_TEXTS_KEPT);
88 keptHere += added;
89 return made;
6790 }
91 const [made, added] = keep(fixed, sql, FIXED_TEXTS_KEPT);
92 fixedKeptHere += added;
6893 return made;
6994 };
7095 handle.close = (...a: unknown[]): void => {
7196 keptHere -= lists.size;
97 fixedKeptHere -= fixed.size;
98 // Finalized here as Bun finalizes its own cache on close: a statement left open keeps SQLite's
99 // connection alive past `close`, and its -wal and -shm files with it.
100 for (const kept of [lists, fixed]) for (const s of kept.values()) s.finalize();
72101 lists.clear();
102 fixed.clear();
73103 close(...a);
74104 };
75105 return db;
src/perf/held.ts +2 −1
@@ -12,7 +12,7 @@
1212 * getter, so the registry is as large as the names in the source, never as the work done.
1313 */
1414
15 import { listTextsKeptHere } from "../kernel/list_texts.ts";
15 import { fixedTextsKeptHere, listTextsKeptHere } from "../kernel/list_texts.ts";
1616
1717 export interface HeldCount {
1818 readonly name: string;
@@ -68,6 +68,7 @@ export const threadHeld: Held = createHeld();
6868 // The kernel names nothing outside itself (test/kernel-boundary.test.ts), so its count is named
6969 // here.
7070 threadHeld.add("list statements kept", listTextsKeptHere);
71 threadHeld.add("statements kept", fixedTextsKeptHere);
7172
7273 /** A forge's own holders and the thread's, as one reading: largest first. */
7374 export function heldNow(app: object): HeldCount[] {
test/fixed-texts.test.ts added +69
@@ -0,0 +1,69 @@
1 /**
2 * #16942: Bun's statement cache keeps the first 4,096 texts a connection meets for its whole life,
3 * so a text naming a number (a page's OFFSET) held a compiled program in malloc forever. A wrapped
4 * connection keeps its fixed texts in a bounded cache of its own, least recently used out first.
5 */
6 import { expect, test } from "bun:test";
7 import { heapStats } from "bun:jsc";
8 import { mkdtempSync, readdirSync, rmSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { openDb } from "../src/kernel/db.ts";
12 import { FIXED_TEXTS_KEPT, fixedTextsKeptHere, listTextsKeptHere } from "../src/kernel/list_texts.ts";
13 import { threadHeld } from "../src/perf/held.ts";
14
15 const statements = (): number => {
16 Bun.gc(true);
17 return heapStats().objectTypeCounts["SQLStatement"] ?? 0;
18 };
19
20 test("3,000 texts that each name a number keep at most FIXED_TEXTS_KEPT statements prepared", () => {
21 const keptBefore = fixedTextsKeptHere();
22 const listsBefore = listTextsKeptHere();
23 const db = openDb(":memory:", []);
24 try {
25 db.run("CREATE TABLE t (n INTEGER)");
26 const hot = "SELECT count(*) AS n FROM t";
27 const first = db.query(hot);
28 const before = statements();
29 for (let i = 0; i < 3000; i++) {
30 db.query(`SELECT n FROM t ORDER BY n LIMIT 10 OFFSET ${i * 10}`).all();
31 // A text asked all along stays kept: the same statement answers.
32 if (i % 100 === 0) expect(db.query(hot)).toBe(first);
33 }
34 expect(fixedTextsKeptHere() - keptBefore).toBe(FIXED_TEXTS_KEPT);
35 // Before #16942 every one of the 3,000 was still prepared here (Bun's cap is 4,096).
36 expect(statements() - before).toBeLessThan(FIXED_TEXTS_KEPT + 50);

This bound depends on GC timing: the heap count after Bun.gc(true) against 1,074. If it flakes under load, drop it and rely on the fixedTextsKeptHere() assertion above, which is deterministic.

37 expect(db.query(hot)).toBe(first);
38 expect((db.query(hot).get() as { n: number }).n).toBe(0);
39 // A fixed text's churn never counts as a list text.
40 expect(listTextsKeptHere()).toBe(listsBefore);
41 expect(threadHeld.read().find((h) => h.name === "statements kept")?.size).toBe(fixedTextsKeptHere());
42 } finally {
43 db.close();
44 }
45 expect(fixedTextsKeptHere()).toBe(keptBefore);
46 }, 60_000);
47
48 test("a text that is not a string is refused by Bun's own query, as before", () => {
49 const db = openDb(":memory:", []);
50 try {
51 expect(() => db.query(42 as unknown as string)).toThrow();
52 } finally {
53 db.close();
54 }
55 });
56
57 test("closing a connection finalizes its kept statements, so its -wal and -shm files go with it", () => {
58 const dir = mkdtempSync(join(tmpdir(), "fixed-texts-"));
59 try {
60 const db = openDb(join(dir, "forge.db"), []);
61 db.run("CREATE TABLE t (n INTEGER)");
62 db.query("INSERT INTO t VALUES (?)").run(1);
63 db.query("SELECT n FROM t WHERE n IN (?, ?, ?)").all(1, 2, 3);
64 db.close();
65 expect(readdirSync(dir)).toEqual(["forge.db"]);
66 } finally {
67 rmSync(dir, { recursive: true, force: true });
68 }
69 });

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

Keyboard shortcuts

Docs