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

opened this

Merged 37h 45m ago, live in production

mason/forge:mason/17130-sentinel-memory-growth-was-degraded-33-m → main 0 commits fork

  • Merged. mason/17130-sentinel-memory-growth-was-degraded-33-m was merged into main as 2e8c816.

Review

Sign in to review this change.
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 (
4747
4848 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).
4949
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`.
5153
5254 ## Reading the retainers (#15286)
5355
src/flows/radar.ts +11 −7
@@ -76,6 +76,10 @@ async function npmAdvisory(name: string, version: string): Promise<string> {
7676 }
7777 }
7878
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
7983 /**
8084 * Read upstream for every exact pin and store the answers, a few at a time and
8185 * within a total deadline; a pin not reached keeps its last row. Returns how
@@ -89,11 +93,11 @@ export async function refreshRadar(
8993 now = new Date(),
9094 deadlineMs = RUN_DEADLINE_MS,
9195 ): 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 };
97101 const todo = pins.slice(0, MAX_PINS).filter((p) => p.version !== "");
98102 const stop = Date.now() + deadlineMs;
99103 let next = 0;
@@ -103,8 +107,8 @@ export async function refreshRadar(
103107 const pin = todo[next++]!;
104108 const answer = await lookup(pin.name, pin.version);
105109 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));
108112 written++;
109113 }
110114 };
src/kernel/list_texts.ts +27 −6
@@ -12,9 +12,14 @@
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. 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.
1823 */
1924
2025 import type { Database, Statement } from "bun:sqlite";
@@ -31,6 +36,13 @@ export const isListText = (sql: string): boolean => LIST.test(sql);
3136 /** The fixed texts one connection keeps prepared, least recently used out first (#16942). */
3237 export const FIXED_TEXTS_KEPT = 1024;
3338
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
3446 /** The list texts kept on this thread, across its connections. */
3547 let keptHere = 0;
3648 /** The fixed texts kept on this thread, across its connections. */
@@ -54,8 +66,10 @@ const listsOf = new WeakMap<Database, Map<string, Statement>>();
5466 * churn never pushes out a fixed text. Bun's own cache keeps the first texts a connection meets
5567 * for its whole life and never lets one go: a text that names a number (a page's `OFFSET`, a
5668 * 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.
5973 */
6074 export function keepFixedTexts(db: Database): Database {
6175 if (listsOf.has(db)) return db;
@@ -67,6 +81,8 @@ export function keepFixedTexts(db: Database): Database {
6781 const lists = new Map<string, Statement>();
6882 const fixed = new Map<string, Statement>();
6983 listsOf.set(db, lists);
84 // Pushed out, oldest first: finalized once `RETIRING_KEPT` newer ones are behind it.
85 const retiring: Statement[] = [];
7086 const keep = (kept: Map<string, Statement>, sql: string, max: number): [Statement, number] => {
7187 const known = kept.get(sql);
7288 if (known !== undefined) {
@@ -77,7 +93,10 @@ export function keepFixedTexts(db: Database): Database {
7793 const made = prepare(sql);
7894 kept.set(sql, made);
7995 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();
81100 return [made, 0];
82101 };
83102 handle.query = (sql: string): Statement => {
@@ -98,8 +117,10 @@ export function keepFixedTexts(db: Database): Database {
98117 // Finalized here as Bun finalizes its own cache on close: a statement left open keeps SQLite's
99118 // connection alive past `close`, and its -wal and -shm files with it.
100119 for (const kept of [lists, fixed]) for (const s of kept.values()) s.finalize();
120 for (const s of retiring) s.finalize();
101121 lists.clear();
102122 fixed.clear();
123 retiring.length = 0;
103124 close(...a);
104125 };
105126 return db;
test/fixed-texts.test.ts +59 −3
@@ -9,7 +9,7 @@ import { mkdtempSync, readdirSync, rmSync } from "node:fs";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 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";
1313 import { threadHeld } from "../src/perf/held.ts";
1414
1515 const statements = (): number => {
@@ -32,8 +32,9 @@ test("3,000 texts that each name a number keep at most FIXED_TEXTS_KEPT statemen
3232 if (i % 100 === 0) expect(db.query(hot)).toBe(first);
3333 }
3434 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);
3738 expect(db.query(hot)).toBe(first);
3839 expect((db.query(hot).get() as { n: number }).n).toBe(0);
3940 // 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
4546 expect(fixedTextsKeptHere()).toBe(keptBefore);
4647 }, 60_000);
4748
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
48104 test("a text that is not a string is refused by Bun's own query, as before", () => {
49105 const db = openDb(":memory:", []);
50106 try {
test/pages-memory.test.ts +4 −3
@@ -22,7 +22,7 @@ import { getRepo, type Repo } from "../src/core/repos.ts";
2222 import { listReviewsFor } from "../src/core/reviews.ts";
2323 import { learnedPulls } from "../src/crew/hot_files.ts";
2424 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";
2626 import { seedHomeFlow, type HomeFlowSeed } from "./helpers/home-flow-seed.ts";
2727
2828 const MIB = 1024 * 1024;
@@ -68,8 +68,9 @@ describe("a list text is kept apart, bounded", () => {
6868 for (let n = 1; n <= 400; n++) listReviewsFor(db, Array.from({ length: n }, (_, i) => `id${i}`));
6969 const after = settled();
7070 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);
7374 const text = "SELECT id FROM issue WHERE id IN (?1,?2,?3)";
7475 expect(db.query(text)).toBe(db.query(text));
7576 const fixed = "SELECT id FROM issue WHERE id = ?1";

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

Keyboard shortcuts

Docs