Public: anyone can read this; the crew can change it.
Sentinel: memory-growth was degraded 33 minutes today: The forge's own memory is 4600 MiB, over twice its first-hour 1962 MiB and past the 2176 MiB more its database caches m… #17159
Merged 37h 45m ago, live in production
mason/forge:mason/17130-sentinel-memory-growth-was-degraded-33-m → main 0 commits fork
5 files
changed +104
−20
docs/features/memory-growth.md +3 −1
| @@ -47,7 +47,9 @@ Found on a copy of production's data with no network, production's own work on ( | ||
| 47 | 47 | |
| 48 | 48 | 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). |
| 49 | 49 | |
| 50 | **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`. | |
| 50 | **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. Test: `test/fixed-texts.test.ts`. | |
| 51 | ||
| 52 | **A statement pushed out is finalized (#17130).** The cache let a statement it pushed out go to the collector, and its compiled program stayed in malloc until a full collection, which a heap of a GiB or more rarely runs. The forge has more than 1,024 fixed texts, so on production the main connection's count sat at 1,024 all day (`statements kept: trip 1024, now 1024` on #17130) while the cache turned over, and the memory outside every heap climbed from 1281 to 3025 MiB. On a 700 MiB heap, 60,000 texts pushed out of a connection held about 930 MiB more RSS; finalized, RSS stayed flat. Now each connection keeps its last 64 pushed out (`RETIRING_KEPT`), so a caller still stepping one in this turn finishes, and finalizes the oldest past that; `close` finalizes the rest. A statement is asked from `db.query` at each use, never held across an `await` (`src/flows/radar.ts` held one across its registry lookups and now asks at each write): one held may be finalized under it. `statements kept` pinned at 1,024 now means the cache is turning over, not that native memory is growing. Test: `test/fixed-texts.test.ts`, `test/pages-memory.test.ts`. | |
| 51 | 53 | |
| 52 | 54 | ## Reading the retainers (#15286) |
| 53 | 55 |
src/flows/radar.ts +11 −7
| @@ -76,6 +76,10 @@ async function npmAdvisory(name: string, version: string): Promise<string> { | ||
| 76 | 76 | } |
| 77 | 77 | } |
| 78 | 78 | |
| 79 | const PUT_LATEST = `INSERT INTO dep_latest (repo_id, name, latest, error, checked_at, advisory) VALUES (?1, ?2, ?3, ?4, ?5, ?6) | |
| 80 | ON CONFLICT (repo_id, name) DO UPDATE SET latest = excluded.latest, | |
| 81 | error = excluded.error, checked_at = excluded.checked_at, advisory = excluded.advisory`; | |
| 82 | ||
| 79 | 83 | /** |
| 80 | 84 | * Read upstream for every exact pin and store the answers, a few at a time and |
| 81 | 85 | * within a total deadline; a pin not reached keeps its last row. Returns how |
| @@ -89,11 +93,11 @@ export async function refreshRadar( | ||
| 89 | 93 | now = new Date(), |
| 90 | 94 | deadlineMs = RUN_DEADLINE_MS, |
| 91 | 95 | ): Promise<number> { |
| 92 | const put = db.query( | |
| 93 | `INSERT INTO dep_latest (repo_id, name, latest, error, checked_at, advisory) VALUES (?1, ?2, ?3, ?4, ?5, ?6) | |
| 94 | ON CONFLICT (repo_id, name) DO UPDATE SET latest = excluded.latest, | |
| 95 | error = excluded.error, checked_at = excluded.checked_at, advisory = excluded.advisory`, | |
| 96 | ); | |
| 96 | // Asked at each write, never held across the lookup's await: a statement the connection's cache | |
| 97 | // pushes out meanwhile is finalized (#17130). | |
| 98 | const put = (...row: [string, string, string, string, string, string]): void => { | |
| 99 | db.query(PUT_LATEST).run(...row); | |
| 100 | }; | |
| 97 | 101 | const todo = pins.slice(0, MAX_PINS).filter((p) => p.version !== ""); |
| 98 | 102 | const stop = Date.now() + deadlineMs; |
| 99 | 103 | let next = 0; |
| @@ -103,8 +107,8 @@ export async function refreshRadar( | ||
| 103 | 107 | const pin = todo[next++]!; |
| 104 | 108 | const answer = await lookup(pin.name, pin.version); |
| 105 | 109 | const at = now.toISOString(); |
| 106 | if (typeof answer === "string") put.run(repoId, pin.name, "", answer.slice(0, 200), at, ""); | |
| 107 | else put.run(repoId, pin.name, answer.latest, "", at, (answer.advisory ?? "").slice(0, 200)); | |
| 110 | if (typeof answer === "string") put(repoId, pin.name, "", answer.slice(0, 200), at, ""); | |
| 111 | else put(repoId, pin.name, answer.latest, "", at, (answer.advisory ?? "").slice(0, 200)); | |
| 108 | 112 | written++; |
| 109 | 113 | } |
| 110 | 114 | }; |
src/kernel/list_texts.ts +27 −6
| @@ -12,9 +12,14 @@ | ||
| 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. 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. | |
| 15 | * length repeats is still prepared once. Every other text is kept the same way, in a cache of | |
| 16 | * `FIXED_TEXTS_KEPT` (#16942), so Bun's first-come, kept-forever cache serves no wrapped | |
| 17 | * connection. | |
| 18 | * | |
| 19 | * A statement pushed out is finalized, not left to the collector (#17130). Its compiled program | |
| 20 | * lives in malloc until a full collection, which a large heap rarely runs; the forge has more than | |
| 21 | * 1,024 fixed texts, so the main connection's cache turned over all day, and on a 700 MiB heap | |
| 22 | * 60,000 texts pushed out held about 930 MiB outside every heap, where finalizing held it flat. | |
| 18 | 23 | */ |
| 19 | 24 | |
| 20 | 25 | import type { Database, Statement } from "bun:sqlite"; |
| @@ -31,6 +36,13 @@ export const isListText = (sql: string): boolean => LIST.test(sql); | ||
| 31 | 36 | /** The fixed texts one connection keeps prepared, least recently used out first (#16942). */ |
| 32 | 37 | export const FIXED_TEXTS_KEPT = 1024; |
| 33 | 38 | |
| 39 | /** | |
| 40 | * The statements pushed out a connection holds before it finalizes the oldest (#17130): a caller | |
| 41 | * still stepping one (an `iterate` whose loop asks other texts) has this many more texts pushed out | |
| 42 | * after it before its statement goes. | |
| 43 | */ | |
| 44 | export const RETIRING_KEPT = 64; | |
| 45 | ||
| 34 | 46 | /** The list texts kept on this thread, across its connections. */ |
| 35 | 47 | let keptHere = 0; |
| 36 | 48 | /** The fixed texts kept on this thread, across its connections. */ |
| @@ -54,8 +66,10 @@ const listsOf = new WeakMap<Database, Map<string, Statement>>(); | ||
| 54 | 66 | * churn never pushes out a fixed text. Bun's own cache keeps the first texts a connection meets |
| 55 | 67 | * for its whole life and never lets one go: a text that names a number (a page's `OFFSET`, a |
| 56 | 68 | * 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. | |
| 69 | * program in malloc the collector never feels (#16942). A statement pushed out waits among the | |
| 70 | * connection's last `RETIRING_KEPT` pushed out, then is finalized (#17130). A caller asks | |
| 71 | * `db.query` at each use rather than holding a statement across an `await`: a held one may be | |
| 72 | * finalized under it. | |
| 59 | 73 | */ |
| 60 | 74 | export function keepFixedTexts(db: Database): Database { |
| 61 | 75 | if (listsOf.has(db)) return db; |
| @@ -67,6 +81,8 @@ export function keepFixedTexts(db: Database): Database { | ||
| 67 | 81 | const lists = new Map<string, Statement>(); |
| 68 | 82 | const fixed = new Map<string, Statement>(); |
| 69 | 83 | listsOf.set(db, lists); |
| 84 | // Pushed out, oldest first: finalized once `RETIRING_KEPT` newer ones are behind it. | |
| 85 | const retiring: Statement[] = []; | |
| 70 | 86 | const keep = (kept: Map<string, Statement>, sql: string, max: number): [Statement, number] => { |
| 71 | 87 | const known = kept.get(sql); |
| 72 | 88 | if (known !== undefined) { |
| @@ -77,7 +93,10 @@ export function keepFixedTexts(db: Database): Database { | ||
| 77 | 93 | const made = prepare(sql); |
| 78 | 94 | kept.set(sql, made); |
| 79 | 95 | if (kept.size <= max) return [made, 1]; |
| 80 | kept.delete(kept.keys().next().value!); | |
| 96 | const oldest = kept.keys().next().value!; | |
| 97 | retiring.push(kept.get(oldest)!); | |
| 98 | kept.delete(oldest); | |
| 99 | if (retiring.length > RETIRING_KEPT) retiring.shift()!.finalize(); | |
| 81 | 100 | return [made, 0]; |
| 82 | 101 | }; |
| 83 | 102 | handle.query = (sql: string): Statement => { |
| @@ -98,8 +117,10 @@ export function keepFixedTexts(db: Database): Database { | ||
| 98 | 117 | // Finalized here as Bun finalizes its own cache on close: a statement left open keeps SQLite's |
| 99 | 118 | // connection alive past `close`, and its -wal and -shm files with it. |
| 100 | 119 | for (const kept of [lists, fixed]) for (const s of kept.values()) s.finalize(); |
| 120 | for (const s of retiring) s.finalize(); | |
| 101 | 121 | lists.clear(); |
| 102 | 122 | fixed.clear(); |
| 123 | retiring.length = 0; | |
| 103 | 124 | close(...a); |
| 104 | 125 | }; |
| 105 | 126 | return db; |
test/fixed-texts.test.ts +59 −3
| @@ -9,7 +9,7 @@ import { mkdtempSync, readdirSync, rmSync } from "node:fs"; | ||
| 9 | 9 | import { tmpdir } from "node:os"; |
| 10 | 10 | import { join } from "node:path"; |
| 11 | 11 | import { openDb } from "../src/kernel/db.ts"; |
| 12 | import { FIXED_TEXTS_KEPT, fixedTextsKeptHere, listTextsKeptHere } from "../src/kernel/list_texts.ts"; | |
| 12 | import { FIXED_TEXTS_KEPT, fixedTextsKeptHere, LIST_TEXTS_KEPT, listTextsKeptHere, RETIRING_KEPT } from "../src/kernel/list_texts.ts"; | |
| 13 | 13 | import { threadHeld } from "../src/perf/held.ts"; |
| 14 | 14 | |
| 15 | 15 | const statements = (): number => { |
| @@ -32,8 +32,9 @@ test("3,000 texts that each name a number keep at most FIXED_TEXTS_KEPT statemen | ||
| 32 | 32 | if (i % 100 === 0) expect(db.query(hot)).toBe(first); |
| 33 | 33 | } |
| 34 | 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); | |
| 35 | // Before #16942 every one of the 3,000 was still prepared here (Bun's cap is 4,096); the last | |
| 36 | // RETIRING_KEPT pushed out wait to be finalized (#17130). | |
| 37 | expect(statements() - before).toBeLessThan(FIXED_TEXTS_KEPT + RETIRING_KEPT + 50); | |
| 37 | 38 | expect(db.query(hot)).toBe(first); |
| 38 | 39 | expect((db.query(hot).get() as { n: number }).n).toBe(0); |
| 39 | 40 | // A fixed text's churn never counts as a list text. |
| @@ -45,6 +46,61 @@ test("3,000 texts that each name a number keep at most FIXED_TEXTS_KEPT statemen | ||
| 45 | 46 | expect(fixedTextsKeptHere()).toBe(keptBefore); |
| 46 | 47 | }, 60_000); |
| 47 | 48 | |
| 49 | /** | |
| 50 | * #17130: a statement pushed out was left to the collector, and its compiled program stayed in | |
| 51 | * malloc until a full collection, which a large heap rarely runs; the main connection's cache | |
| 52 | * turned over all day and the memory outside every heap climbed. Now one is finalized once | |
| 53 | * RETIRING_KEPT newer ones are pushed out behind it. | |
| 54 | */ | |
| 55 | test("a statement pushed out is finalized once RETIRING_KEPT more are pushed out after it", () => { | |
| 56 | const db = openDb(":memory:", []); | |
| 57 | try { | |
| 58 | db.run("CREATE TABLE t (n INTEGER)"); | |
| 59 | const text = (i: number): string => `SELECT n FROM t LIMIT ${i}`; | |
| 60 | const first = db.query(text(0)); | |
| 61 | // Fills the cache: `first` is now the least recently used. | |
| 62 | for (let i = 1; i < FIXED_TEXTS_KEPT; i++) db.query(text(i)).all(); | |
| 63 | // Pushed out, it still answers while fewer than RETIRING_KEPT are pushed out behind it: a | |
| 64 | // caller stepping it in this turn finishes. | |
| 65 | for (let i = 0; i < RETIRING_KEPT; i++) db.query(text(FIXED_TEXTS_KEPT + i)).all(); | |
| 66 | expect(first.all()).toEqual([]); | |
| 67 | // One more pushed out finalizes it; before #17130 it waited for the collector. | |
| 68 | db.query(text(FIXED_TEXTS_KEPT + RETIRING_KEPT)).all(); | |
| 69 | expect(() => first.all()).toThrow("Statement has finalized"); | |
| 70 | // The text asked again is prepared afresh and answers. | |
| 71 | expect(db.query(text(0)).all()).toEqual([]); | |
| 72 | } finally { | |
| 73 | db.close(); | |
| 74 | } | |
| 75 | }, 60_000); | |
| 76 | ||
| 77 | test("a list text pushed out is finalized the same way", () => { | |
| 78 | const db = openDb(":memory:", []); | |
| 79 | try { | |
| 80 | db.run("CREATE TABLE t (n INTEGER)"); | |
| 81 | const list = (n: number): string => `SELECT n FROM t WHERE n IN (${Array.from({ length: n }, () => "?").join(", ")})`; | |
| 82 | const args = (n: number): number[] => Array.from({ length: n }, (_, i) => i); | |
| 83 | const first = db.query(list(3)); | |
| 84 | for (let n = 4; n < 3 + LIST_TEXTS_KEPT + RETIRING_KEPT + 1; n++) db.query(list(n)).all(...args(n)); | |
| 85 | expect(() => first.all(...args(3))).toThrow("Statement has finalized"); | |
| 86 | } finally { | |
| 87 | db.close(); | |
| 88 | } | |
| 89 | }, 60_000); | |
| 90 | ||
| 91 | test("closing a connection finalizes the statements it pushed out and has not finalized yet", () => { | |
| 92 | const dir = mkdtempSync(join(tmpdir(), "fixed-texts-")); | |
| 93 | try { | |
| 94 | const db = openDb(join(dir, "forge.db"), []); | |
| 95 | db.run("CREATE TABLE t (n INTEGER)"); | |
| 96 | for (let i = 0; i < FIXED_TEXTS_KEPT + 5; i++) db.query(`SELECT n FROM t LIMIT ${i}`).all(); | |
| 97 | db.close(); | |
| 98 | expect(readdirSync(dir)).toEqual(["forge.db"]); | |
| 99 | } finally { | |
| 100 | rmSync(dir, { recursive: true, force: true }); | |
| 101 | } | |
| 102 | }); | |
| 103 | ||
| 48 | 104 | test("a text that is not a string is refused by Bun's own query, as before", () => { |
| 49 | 105 | const db = openDb(":memory:", []); |
| 50 | 106 | try { |
test/pages-memory.test.ts +4 −3
| @@ -22,7 +22,7 @@ import { getRepo, type Repo } from "../src/core/repos.ts"; | ||
| 22 | 22 | import { listReviewsFor } from "../src/core/reviews.ts"; |
| 23 | 23 | import { learnedPulls } from "../src/crew/hot_files.ts"; |
| 24 | 24 | import { pagesConfig, readPagePicture, type PageJob, type PagesEnv } from "../src/flow/pages_read.ts"; |
| 25 | import { isListText, keepFixedTexts, LIST_TEXTS_KEPT, listTextsKeptHere } from "../src/kernel/list_texts.ts"; | |
| 25 | import { isListText, keepFixedTexts, LIST_TEXTS_KEPT, listTextsKeptHere, RETIRING_KEPT } from "../src/kernel/list_texts.ts"; | |
| 26 | 26 | import { seedHomeFlow, type HomeFlowSeed } from "./helpers/home-flow-seed.ts"; |
| 27 | 27 | |
| 28 | 28 | const MIB = 1024 * 1024; |
| @@ -68,8 +68,9 @@ describe("a list text is kept apart, bounded", () => { | ||
| 68 | 68 | for (let n = 1; n <= 400; n++) listReviewsFor(db, Array.from({ length: n }, (_, i) => `id${i}`)); |
| 69 | 69 | const after = settled(); |
| 70 | 70 | expect(listTextsKeptHere() - keptBefore).toBe(LIST_TEXTS_KEPT); |
| 71 | // Before #14479 every one of the 400 texts was still prepared here, twice over on a rerun. | |
| 72 | expect(after.statements - before.statements).toBeLessThan(LIST_TEXTS_KEPT + 20); | |
| 71 | // Before #14479 every one of the 400 texts was still prepared here, twice over on a rerun; | |
| 72 | // the last RETIRING_KEPT pushed out wait to be finalized (#17130). | |
| 73 | expect(after.statements - before.statements).toBeLessThan(LIST_TEXTS_KEPT + RETIRING_KEPT + 20); | |
| 73 | 74 | const text = "SELECT id FROM issue WHERE id IN (?1,?2,?3)"; |
| 74 | 75 | expect(db.query(text)).toBe(db.query(text)); |
| 75 | 76 | const fixed = "SELECT id FROM issue WHERE id = ?1"; |
new above
offline