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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16942-sentinel-memory-growth-was-degraded-25-m → main 0 commits fork 1 thread · 1 unresolved
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 ( | ||
| 45 | 45 | |
| 46 | 46 | 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). |
| 47 | 47 | |
| 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 | ||
| 48 | 50 | ## Reading the retainers (#15286) |
| 49 | 51 | |
| 50 | 52 | `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; | ||
| 61 | 61 | * preparing. The forge's queries are fixed texts (about 2,000 call sites), so |
| 62 | 62 | * this holds every one of them; a text past the cap is prepared per call as |
| 63 | 63 | * 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. | |
| 66 | 67 | */ |
| 67 | 68 | export const QUERY_CACHE = 4096; |
| 68 | 69 | (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 @@ | ||
| 12 | 12 | * |
| 13 | 13 | * `keepFixedTexts` hands a text with an `IN` list of three or more placeholders to a small cache |
| 14 | 14 | * 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. | |
| 18 | 18 | */ |
| 19 | 19 | |
| 20 | 20 | import type { Database, Statement } from "bun:sqlite"; |
| @@ -28,8 +28,13 @@ const LIST = /\bIN\s*\(\s*\?\d*(?:\s*,\s*\?\d*){2,}\s*\)/i; | ||
| 28 | 28 | /** Whether `sql` holds an `IN` list long enough to have been built from values. */ |
| 29 | 29 | export const isListText = (sql: string): boolean => LIST.test(sql); |
| 30 | 30 | |
| 31 | /** The fixed texts one connection keeps prepared, least recently used out first (#16942). */ | |
| 32 | export const FIXED_TEXTS_KEPT = 1024; | |
| 33 | ||
| 31 | 34 | /** The list texts kept on this thread, across its connections. */ |
| 32 | 35 | let keptHere = 0; |
| 36 | /** The fixed texts kept on this thread, across its connections. */ | |
| 37 | let fixedKeptHere = 0; | |
| 33 | 38 | |
| 34 | 39 | /** |
| 35 | 40 | * How many list texts this thread keeps prepared: `perf/held.ts` names it on the `memory holds:` |
| @@ -37,10 +42,21 @@ let keptHere = 0; | ||
| 37 | 42 | */ |
| 38 | 43 | export const listTextsKeptHere = (): number => keptHere; |
| 39 | 44 | |
| 45 | /** How many fixed texts this thread keeps prepared, named beside the list texts. */ | |
| 46 | export const fixedTextsKeptHere = (): number => fixedKeptHere; | |
| 47 | ||
| 40 | 48 | /** Each wrapped connection's list texts, oldest first. */ |
| 41 | 49 | const listsOf = new WeakMap<Database, Map<string, Statement>>(); |
| 42 | 50 | |
| 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 | */ | |
| 44 | 60 | export function keepFixedTexts(db: Database): Database { |
| 45 | 61 | if (listsOf.has(db)) return db; |
| 46 | 62 | const handle = db as unknown as { query: (sql: string) => Statement; close: (...a: unknown[]) => void }; |
| @@ -49,27 +65,41 @@ export function keepFixedTexts(db: Database): Database { | ||
| 49 | 65 | // Bound now, so a later wrapper of `db.prepare` (a statement counter) sees one call, not two. |
| 50 | 66 | const prepare = db.prepare.bind(db); |
| 51 | 67 | const lists = new Map<string, Statement>(); |
| 68 | const fixed = new Map<string, Statement>(); | |
| 52 | 69 | 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); | |
| 56 | 72 | 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]; | |
| 60 | 76 | } |
| 61 | 77 | 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; | |
| 67 | 90 | } |
| 91 | const [made, added] = keep(fixed, sql, FIXED_TEXTS_KEPT); | |
| 92 | fixedKeptHere += added; | |
| 68 | 93 | return made; |
| 69 | 94 | }; |
| 70 | 95 | handle.close = (...a: unknown[]): void => { |
| 71 | 96 | 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(); | |
| 72 | 101 | lists.clear(); |
| 102 | fixed.clear(); | |
| 73 | 103 | close(...a); |
| 74 | 104 | }; |
| 75 | 105 | return db; |
src/perf/held.ts +2 −1
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | * getter, so the registry is as large as the names in the source, never as the work done. |
| 13 | 13 | */ |
| 14 | 14 | |
| 15 | import { listTextsKeptHere } from "../kernel/list_texts.ts"; | |
| 15 | import { fixedTextsKeptHere, listTextsKeptHere } from "../kernel/list_texts.ts"; | |
| 16 | 16 | |
| 17 | 17 | export interface HeldCount { |
| 18 | 18 | readonly name: string; |
| @@ -68,6 +68,7 @@ export const threadHeld: Held = createHeld(); | ||
| 68 | 68 | // The kernel names nothing outside itself (test/kernel-boundary.test.ts), so its count is named |
| 69 | 69 | // here. |
| 70 | 70 | threadHeld.add("list statements kept", listTextsKeptHere); |
| 71 | threadHeld.add("statements kept", fixedTextsKeptHere); | |
| 71 | 72 | |
| 72 | 73 | /** A forge's own holders and the thread's, as one reading: largest first. */ |
| 73 | 74 | 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); | |
| 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 | }); |
new above
offline
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 thefixedTextsKeptHere()assertion above, which is deterministic.