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

Database: one-shot compaction at boot (opt-in), incremental vacuum after, decision retention #16726

Merged opened this

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

Merged

db-compact → main 0 commits

  • Merged. db-compact was merged into main as c90d084.

Review

Sign in to review this change.
18 files changed +850 −14
docs/features/database-compaction.md added +28
@@ -0,0 +1,28 @@
1 ---
2 topic: When something is wrong
3 row: Make the database file small again, once, at the next boot
4 ---
5
6 # Make the database file small again, once, at the next boot
7
8 When the forge deletes old rows (the retention jobs in `src/system/retention.ts`), the space those rows used stays inside `forge.db` as free pages. The file keeps its size. /system's "Database size" shows this as "Free inside". The terminal's System screen (`src/tui/screens/system.ts`, key `d`) shows the same figure as "free inside". Production reached 4.9 GB with 64% of the file free, past the 2 GiB Bun maps.
9
10 ## Ask for one compaction
11
12 Put an empty file named `compact-on-boot` in the forge's data directory, for example `touch /srv/forge/data/compact-on-boot` on the host, as the user that owns the data. The next time the forge starts, before it answers anything, it:
13
14 1. removes the file, so it compacts once and not on every boot;
15 2. folds the WAL into the database and counts every table's rows;
16 3. copies the database with `VACUUM INTO` into `forge.db.compacting`, as an incremental-vacuum file;
17 4. checks the copy: `quick_check` is ok, every table has the same rows, the mode is incremental;
18 5. keeps the old file as `forge.db.before-compact-<UTC time>` and renames the copy to `forge.db`.
19
20 Each step's time is in the log under `[compact]`. The boot is longer by the time the copy takes. On a copy of production with 4.3 GB of live data, the whole job took 21.7 s; it scales with the live data, not the file's size.
21
22 If any step fails, the forge boots on the database it had, unchanged, and the log says why. Failures include another process holding the file, a check that disagrees, too little disk for the copy, or the whole job taking more than 45 s. The copy runs in a process of its own: past 45 s the forge kills it and waits for it to end before it removes the partial copy and opens the database.
23
24 ## After it
25
26 The file the database was is never removed by the forge. /system's "Database size" and the terminal's database size screen name it and its size ("Kept before compaction") until a person removes it.
27
28 From then on the `retention-vacuum` job gives free pages back to the disk a little at a time, at a twentieth of the thread, and logs how many each pass returned. So rows the retention jobs delete shrink the file without another compaction.
src/http/mcp/tools/system.ts +1 −1

Diff not shown — a line 3,186 characters wide (limit 2,000). +1 −1

View file
src/main.ts +5
@@ -106,6 +106,7 @@ import { engineChoice, readMachine, shapeWords } from "./engine/mode.ts";
106106 import { runSplit, tuneForSplit } from "./engine/run.ts";
107107 import { startDuties } from "./engine/duties.ts";
108108 import { startRetention } from "./system/retention.ts";
109 import { compactOnBoot } from "./system/compact.ts";
109110 import { startClogTick } from "./flow/clog_tick.ts";
110111 import { resumeAtBoot } from "./maintenance/service.ts";
111112 import { startKeeper } from "./flow/keeper.ts";
@@ -329,6 +330,10 @@ const previewKey = previewIdentityKey(process.env);
329330
330331 const engineShape = engineChoice(process.env, { hosted, readOnly, machine: readMachine() });
331332
333 // One compaction of the database, before anything opens it, only when an admin left the file that
334 // asks for it (`system/compact.ts`): never on a read-only standby, which serves a restored copy.
335 if (!readOnly) await compactOnBoot(dataDir, createLog("compact"));
336
332337 const app = createApp({
333338 dataDir,
334339 engine: engineShape,
src/system/compact.ts added +343
@@ -0,0 +1,343 @@
1 /**
2 * The database compacted once, at boot, when an admin asks.
3 *
4 * The retention drains (`system/retention.ts`) delete rows, and with `auto_vacuum` off a deleted
5 * row's pages stay inside the file on the freelist: production's `forge.db` was 4.9 GB with 64%
6 * of it free (2026-11-29), past the 2 GiB Bun maps (`system/db_size.ts`). Only a VACUUM gives
7 * those pages back, and a VACUUM holds the write lock for as long as it copies the live data, so
8 * it runs where nothing writes: at boot, before the forge listens, inside the release's own stop.
9 *
10 * It is one-shot and opt-in. It runs only when the file `compact-on-boot` is in the data
11 * directory, and the file is removed before anything else, so a boot killed half way does not
12 * try again. Without it nothing here runs, however much of the file is free.
13 *
14 * The steps, each timed and logged, all in a process of its own (`compact_child.ts`) so the boot
15 * holds the ceiling, and past it kills the process and waits for it to end:
16 * 1. checkpoint the WAL into the file (TRUNCATE), refused if anything else holds it;
17 * 2. count the rows of every table;
18 * 3. `VACUUM INTO forge.db.compacting` with `auto_vacuum = INCREMENTAL` pending, so the copy is
19 * an incremental-vacuum file and the `retention-vacuum` job can give pages back from then
20 * on in small slices, and this never needs to run again;
21 * 4. prove the copy: `quick_check` says ok, every table has the rows it had, the mode is 2.
22 *
23 * Only then the swap: the old file is kept under `forge.db.before-compact-<UTC stamp>` (a hard
24 * link, so there is no moment without a `forge.db`), and the copy is renamed over `forge.db`. The
25 * kept file is never deleted by the forge; /system names it and its size until a person removes
26 * it. Any failure (a step past `CEILING_MS` in all, a check that disagrees, too little disk)
27 * leaves `forge.db` as it was, removes the partial copy, logs the reason, and the boot goes on.
28 *
29 * Measured on a copy of production with 4.3 GB of live data, at nice 19 on a loaded host:
30 * `VACUUM INTO` took 14.2 s; an in-place `VACUUM` to incremental took 42.6 s, which is why the
31 * copy is made beside the file rather than in it.
32 */
33
34 import { Database } from "bun:sqlite";
35 import { chmodSync, existsSync, linkSync, readdirSync, renameSync, rmSync, statfsSync, statSync } from "node:fs";
36 import { join } from "node:path";
37 import type { Log } from "../kernel/log.ts";
38
39 /** The file an admin leaves in the data directory to ask for one compaction at the next boot. */
40 export const MARKER = "compact-on-boot";
41 /**
42 * The name the copy is made as, beside the database (and, like it, never copied as a top-level
43 * file).
44 */
45 export const COPY = "forge.db.compacting";
46 /** The prefix of the file the database was before a compaction, kept until a person removes it. */
47 export const KEPT_PREFIX = "forge.db.before-compact-";
48 /**
49 * The longest the whole job may take before it is abandoned and the forge boots on the file it
50 * had. The release waits 60 s for health from the container's start (`/srv/forge/run.sh`
51 * `HEALTH_WAIT`), so this leaves the boot itself room inside that.
52 */
53 export const CEILING_MS = 45_000;
54 /** Disk the copy needs beyond the database's own bytes (the copy is never larger than the file). */
55 export const DISK_SPARE = 256 * 1024 * 1024;
56
57 /** What the compaction process is asked: the database, and the file the copy is made as. */
58 export interface CompactJob {
59 readonly db: string;
60 readonly to: string;
61 }
62
63 export type CompactStep = "checkpoint" | "count" | "vacuum" | "check";
64
65 /** What the compaction process says: a step starting, or the verdict. */
66 export type CompactNote =
67 | { readonly step: CompactStep }
68 | { readonly done: true; readonly ok: true; readonly tables: number; readonly rows: number }
69 | { readonly done: true; readonly ok: false; readonly reason: string };
70
71 type Verdict = Extract<CompactNote, { done: true }>;
72
73 /**
74 * How the job runs: in a process of its own in a forge, or a stand-in in a test. On `abort` it
75 * settles only once the job has stopped for good: nothing writes the copy or holds the database
76 * after, so the boot may remove the copy and open the database.
77 */
78 export type Runner = (job: CompactJob, say: (step: CompactStep) => void, abort: AbortSignal) => Promise<Verdict>;
79
80 /** What a boot did about compaction. */
81 export type CompactOutcome =
82 | { readonly ran: false }
83 | { readonly ran: true; readonly ok: false; readonly reason: string; readonly steps: Readonly<Record<string, number>> }
84 | {
85 readonly ran: true;
86 readonly ok: true;
87 readonly kept: string;
88 readonly before: number;
89 readonly after: number;
90 readonly steps: Readonly<Record<string, number>>;
91 };
92
93 /** Rows in every table the schema names (its own `sqlite_` tables aside), by name. */
94 export function tableCounts(db: Database): Map<string, number> {
95 const names = db
96 .query<{ name: string }, []>(
97 "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
98 )
99 .all()
100 .map((r) => r.name);
101 const counts = new Map<string, number>();
102 for (const name of names) {
103 const quoted = `"${name.replaceAll('"', '""')}"`;
104 counts.set(name, db.query<{ n: number }, []>(`SELECT COUNT(*) AS n FROM ${quoted}`).get()?.n ?? 0);
105 }
106 return counts;
107 }
108
109 /** The first table whose rows differ between the two counts, said; undefined when they agree. */
110 export function countsDiffer(before: ReadonlyMap<string, number>, after: ReadonlyMap<string, number>): string | undefined {
111 if (before.size !== after.size) return `the copy has ${after.size} tables, the database ${before.size}`;
112 for (const [name, n] of before) {
113 const m = after.get(name);
114 if (m !== n) return `table ${name} has ${m ?? "no"} rows in the copy, ${n} in the database`;
115 }
116 return undefined;
117 }
118
119 /**
120 * The whole job on the calling thread; `say` hears each step as it starts. Never renames anything.
121 */
122 export function compactFile(job: CompactJob, say: (step: CompactStep) => void): Verdict {
123 let before: Map<string, number>;
124 const db = new Database(job.db, { strict: true });
125 try {
126 db.run("PRAGMA busy_timeout = 0");
127 say("checkpoint");
128 const cp = db.query<{ busy: number }, []>("PRAGMA wal_checkpoint(TRUNCATE)").get();
129 if (cp !== null && cp.busy !== 0)
130 return { done: true, ok: false, reason: "the checkpoint was refused: another connection holds the database" };
131 say("count");
132 before = tableCounts(db);
133 say("vacuum");
134 // A pending mode is what `VACUUM INTO` writes the copy as; the database's own header stays as
135 // it is.
136 db.run("PRAGMA auto_vacuum = INCREMENTAL");
137 db.run("VACUUM INTO ?1", [job.to]);
138 } finally {
139 db.close();
140 }
141 say("check");
142 const copy = new Database(job.to, { strict: true });
143 try {
144 const check = copy.query<{ quick_check: string }, []>("PRAGMA quick_check").all();
145 if (check.length !== 1 || check[0]?.quick_check !== "ok")
146 return {
147 done: true,
148 ok: false,
149 reason: `quick_check on the copy: ${check
150 .map((r) => r.quick_check)
151 .slice(0, 3)
152 .join("; ")}`,
153 };
154 const mode = copy.query<{ auto_vacuum: number }, []>("PRAGMA auto_vacuum").get()?.auto_vacuum;
155 if (mode !== 2) return { done: true, ok: false, reason: `the copy's auto_vacuum is ${String(mode)}, not 2 (incremental)` };
156 const after = tableCounts(copy);
157 const differ = countsDiffer(before, after);
158 if (differ !== undefined) return { done: true, ok: false, reason: differ };
159 let rows = 0;
160 for (const n of after.values()) rows += n;
161 return { done: true, ok: true, tables: after.size, rows };
162 } finally {
163 copy.close();
164 }
165 }
166
167 /**
168 * The job in a process of its own (`compact_child.ts`). A Worker cannot be stopped inside SQLite: a
169 * `VACUUM INTO` it began would go on writing the copy and reading the database after the boot moved
170 * on. A process can: an abort kills it, and the verdict waits for it to have exited. `script` is the
171 * child, a stand-in in a test.
172 */
173 export const inProcess =
174 (script = new URL("./compact_child.ts", import.meta.url).pathname): Runner =>
175 async (job, say, abort) => {
176 const proc = Bun.spawn([process.execPath, script, JSON.stringify(job)], { stdin: "ignore", stdout: "pipe", stderr: "ignore", env: {} });
177 const kill = (): void => void proc.kill("SIGKILL");
178 abort.addEventListener("abort", kill, { once: true });
179 if (abort.aborted) kill();
180 let verdict: Verdict | undefined;
181 try {
182 let rest = "";
183 const decoder = new TextDecoder();
184 for await (const chunk of proc.stdout) {
185 rest += decoder.decode(chunk, { stream: true });
186 let nl: number;
187 while ((nl = rest.indexOf("\n")) >= 0) {
188 const line = rest.slice(0, nl);
189 rest = rest.slice(nl + 1);
190 try {
191 const note = JSON.parse(line) as CompactNote;
192 if ("step" in note) say(note.step);
193 else verdict = note;
194 } catch {
195 // Not a note; the verdict alone decides.
196 }
197 }
198 }
199 } finally {
200 // Settled only once the process is gone, killed or done.
201 await proc.exited;
202 abort.removeEventListener("abort", kill);
203 }
204 if (abort.aborted) return { done: true, ok: false, reason: String(abort.reason) };
205 return verdict ?? { done: true, ok: false, reason: `the compaction process ended without a verdict (exit ${String(proc.exitCode ?? proc.signalCode)})` };
206 };
207
208 /** Bytes of a file, or 0 when it is absent. */
209 function sizeOf(path: string): number {
210 try {
211 return statSync(path).size;
212 } catch {
213 return 0;
214 }
215 }
216
217 /** `20261129T103800Z`: when a kept file was the database. */
218 const stamp = (d: Date): string =>
219 d
220 .toISOString()
221 .replace(/[-:]/g, "")
222 .replace(/\.\d{3}/, "");
223
224 export interface CompactOptions {
225 readonly runner?: Runner;
226 readonly ceilingMs?: number;
227 readonly now?: () => Date;
228 /** Bytes free on the data directory's disk; the filesystem's own answer unless a test says. */
229 readonly diskFree?: (dir: string) => number;
230 }
231
232 /** Free bytes for an unprivileged writer on the disk holding `dir`. */
233 function freeOn(dir: string): number {
234 const fs = statfsSync(dir);
235 return fs.bavail * fs.bsize;
236 }
237
238 /**
239 * At boot, before the database is opened: compact it once if `MARKER` asks, and say what
240 * happened. Never throws; a failure leaves the database as it was.
241 */
242 export async function compactOnBoot(dataDir: string, log: Log, opts: CompactOptions = {}): Promise<CompactOutcome> {
243 const marker = join(dataDir, MARKER);
244 if (!existsSync(marker)) return { ran: false };
245 // Consumed first: whatever happens next, the next boot does not try again unless asked again.
246 rmSync(marker, { force: true });
247 const db = join(dataDir, "forge.db");
248 const to = join(dataDir, COPY);
249 const steps: Record<string, number> = {};
250 const fail = (reason: string): CompactOutcome => {
251 for (const p of [to, `${to}-journal`]) rmSync(p, { force: true });
252 log.warn("compaction abandoned; the forge boots on the database as it was", { reason, ...steps });
253 return { ran: true, ok: false, reason, steps };
254 };
255 const before = sizeOf(db);
256 if (before === 0) return fail("there is no forge.db to compact");
257 rmSync(to, { force: true });
258 try {
259 const free = (opts.diskFree ?? freeOn)(dataDir);
260 if (free < before + DISK_SPARE) return fail(`the disk has ${free} bytes free; the copy needs up to ${before + DISK_SPARE}`);
261 } catch (error) {
262 return fail(`the disk's free space could not be read: ${String(error)}`);
263 }
264 const ceiling = opts.ceilingMs ?? CEILING_MS;
265 log.info("compacting the database before the forge listens", { bytes: before, ceilingMs: ceiling });
266 const started = performance.now();
267 let current: CompactStep | undefined;
268 let at = started;
269 const close = (now: number) => {
270 if (current !== undefined) steps[`${current}Ms`] = Math.round(now - at);
271 };
272 const say = (step: CompactStep) => {
273 const now = performance.now();
274 close(now);
275 current = step;
276 at = now;
277 };
278 const abort = new AbortController();
279 const timer = setTimeout(() => abort.abort(`past the ${ceiling} ms ceiling during ${current ?? "the start"}`), ceiling);
280 let verdict: Verdict;
281 try {
282 verdict = await (opts.runner ?? inProcess())({ db, to }, say, abort.signal);
283 } catch (error) {
284 verdict = { done: true, ok: false, reason: String(error) };
285 } finally {
286 clearTimeout(timer);
287 }
288 close(performance.now());
289 steps["totalMs"] = Math.round(performance.now() - started);
290 if (abort.signal.aborted) return fail(String(abort.signal.reason));
291 if (!verdict.ok) return fail(verdict.reason);
292 // The checkpoint emptied the WAL and the copy's connection was the last: a WAL with frames now
293 // holds writes the copy does not, so nothing is swapped.
294 if (sizeOf(`${db}-wal`) > 0) return fail("the WAL holds writes made after the copy");
295 const kept = join(dataDir, KEPT_PREFIX + stamp((opts.now ?? (() => new Date()))()));
296 try {
297 linkSync(db, kept);
298 } catch (error) {
299 return fail(`the database could not be kept as ${kept}: ${String(error)}`);
300 }
301 try {
302 chmodSync(to, 0o600);
303 renameSync(to, db);
304 } catch (error) {
305 // The link is the database itself; `forge.db` is untouched, so the extra name goes.
306 rmSync(kept, { force: true });
307 return fail(`the copy could not take the database's name: ${String(error)}`);
308 }
309 // The old file's empty WAL and its index belong to the file that is now `kept`.
310 for (const suffix of ["-wal", "-shm"]) rmSync(db + suffix, { force: true });
311 const after = sizeOf(db);
312 log.info("compacted the database; the file it was is kept until a person removes it", {
313 before,
314 after,
315 kept,
316 tables: verdict.tables,
317 rows: verdict.rows,
318 ...steps,
319 });
320 return { ran: true, ok: true, kept, before, after, steps };
321 }
322
323 /** A file the database was before a compaction: its name in the data directory and its bytes. */
324 export interface KeptCopy {
325 readonly name: string;
326 readonly bytes: number;
327 }
328
329 /**
330 * A kept file's whole name: the prefix and the stamp, never its `-wal` or `-shm` if it was opened.
331 */
332 const KEPT_NAME = /^forge\.db\.before-compact-\d{8}T\d{6}Z$/;
333
334 /** Every kept file in `dataDir`, oldest first; none when the directory cannot be read. */
335 export function keptCopies(dataDir: string): KeptCopy[] {
336 let names: string[];
337 try {
338 names = readdirSync(dataDir).filter((n) => KEPT_NAME.test(n));
339 } catch {
340 return [];
341 }
342 return names.sort().map((name) => ({ name, bytes: sizeOf(join(dataDir, name)) }));
343 }
src/system/compact_child.ts added +16
@@ -0,0 +1,16 @@
1 /**
2 * The process side of `compact.ts`: run the copy and its proof in a process of its own, which the
3 * boot can kill outright, saying each step as one JSON line on stdout. The job is the argument.
4 */
5
6 import { compactFile, type CompactJob, type CompactNote } from "./compact.ts";
7
8 const job = JSON.parse(process.argv[2] ?? "{}") as CompactJob;
9 const say = (note: CompactNote): void => void process.stdout.write(`${JSON.stringify(note)}\n`);
10 let note: CompactNote;
11 try {
12 note = compactFile(job, (step) => say({ step }));
13 } catch (error) {
14 note = { done: true, ok: false, reason: String(error) };
15 }
16 say(note);
src/system/db_size.ts +11 −3
@@ -24,6 +24,7 @@ import type { Database } from "bun:sqlite";
2424 import { statSync } from "node:fs";
2525 import { join } from "node:path";
2626 import type { Log } from "../kernel/log.ts";
27 import { keptCopies, type KeptCopy } from "./compact.ts";
2728
2829 /** Where a failed walk is said: the forge's log (`app.log`). */
2930 type Warn = Pick<Log, "warn">;
@@ -74,6 +75,11 @@ export interface DbSize {
7475 readonly growth: DbGrowth;
7576 /** The last walk of the file, or null while the first runs. */
7677 readonly walk: DbWalk | null;
78 /**
79 * The files the database was before a compaction (`system/compact.ts`), kept until a person
80 * removes them; listed with the walk, empty before the first.
81 */
82 readonly kept: readonly KeptCopy[];
7783 }
7884
7985 /** How many tables and indexes are named. */
@@ -391,7 +397,9 @@ export function dbSizeCache(
391397 walk: (db: Database, dataDir: string) => Promise<DbWalk> = (db, d) => measureDbWalk(db, d),
392398 clock: () => number = Date.now,
393399 ) {
394 let last: { at: number; dataDir: string; value: DbWalk } | null = null;
400 // The files a compaction kept are listed with the walk, an hour at most, so a page or a tool read
401 // scans no directory.
402 let last: { at: number; dataDir: string; value: DbWalk; kept: readonly KeptCopy[] } | null = null;
395403 // A walk that failed waits an hour too, so a broken file costs one try an hour.
396404 let triedAt: { at: number; dataDir: string } | null = null;
397405 let pending: Promise<DbWalk | null> | null = null;
@@ -403,7 +411,7 @@ export function dbSizeCache(
403411 triedAt = { at: clock(), dataDir };
404412 pending = walk(db, dataDir)
405413 .then((value) => {
406 last = { at: clock(), dataDir, value };
414 last = { at: clock(), dataDir, value, kept: keptCopies(dataDir) };
407415 return value;
408416 })
409417 .catch((e: unknown) => {
@@ -419,7 +427,7 @@ export function dbSizeCache(
419427 const current = (dataDir: string): DbWalk | null => (last?.dataDir === dataDir ? last.value : null);
420428 const now = (db: Database, dataDir: string, w: DbWalk | null): DbSize => {
421429 const file = fileBytes(dbFile(dataDir));
422 return { fileBytes: file, walBytes: fileBytes(`${dbFile(dataDir)}-wal`), growth: dbGrowth(db, file, clock()), walk: w };
430 return { fileBytes: file, walBytes: fileBytes(`${dbFile(dataDir)}-wal`), growth: dbGrowth(db, file, clock()), walk: w, kept: last?.dataDir === dataDir ? last.kept : [] };
423431 };
424432 return {
425433 /**
src/system/retention.ts +37 −8
@@ -1,7 +1,7 @@
11 /**
22 * What has left its window goes, in small slices on a pace (#12052, part of #11973).
33 *
4 * Six jobs, each a slice of bounded rows and so of bounded time, none holding a
4 * Seven jobs, each a slice of bounded rows and so of bounded time, none holding a
55 * transaction open past it, each named to the perf job watch (`perf/jobs.ts`) so a
66 * stall is blamed on it:
77 *
@@ -14,7 +14,10 @@
1414 * - `retention-deploys`: the old ledger's rows past the window (`system/retention_deploys.ts`),
1515 * 250 rows a slice, and only once `landed-backfill` has had a full pass;
1616 * - `retention-telemetry`: app probes and preview findings past 30 days
17 * (`system/retention_telemetry.ts`), 200 rows a table a slice.
17 * (`system/retention_telemetry.ts`), 200 rows a table a slice;
18 * - `retention-vacuum`: free pages given back to the disk once the file is incremental
19 * (`system/retention_vacuum.ts`), 256 pages a slice; each pass that gave any back says how many
20 * in the log.
1821 *
1922 * The pace is the cost of the slice: after a slice of `t` ms with more behind it, the next
2023 * waits `t * (1 / DUTY - 1)` (at least `MIN_GAP_MS`), so a job takes at most `DUTY` of the thread
@@ -25,12 +28,13 @@
2528 * (`engine/duties.ts` starts them on whichever thread runs the engine, never both).
2629 *
2730 * The write clock (`core/write_clock.ts`) is what tells a page cache that anything was written: a
28 * slice a few times a second for hours would keep every cache cold. A write nothing shows is left out
29 * of it (`quietly`) on the serving thread's connection, and a commit of the engine's connection cannot
30 * be left out. So the three jobs that only drain rows no page reads (`retention-samples`,
31 * `retention-live`, `retention-deploys`) are the serving thread's always (`local`), and the two whose
32 * writes are meaningful (`retention-events`: a feed shows what it leaves; `landed-backfill`: ask-to-live
33 * shows what it writes) are the engine's thread's when it has one (`engine`).
31 * slice a few times a second for hours would keep every cache cold. A write nothing shows is left
32 * out of it (`quietly`) on the serving thread's connection, and a commit of the engine's connection
33 * cannot be left out. So the jobs that only drain rows no page reads (`retention-samples`,
34 * `retention-live`, `retention-deploys`, `retention-telemetry`,
35 * `retention-vacuum`) are the serving thread's always (`local`), and the two whose writes are
36 * meaningful (`retention-events`: a feed shows what it leaves; `landed-backfill`: ask-to-live shows
37 * what it writes) are the engine's thread's when it has one (`engine`).
3438 */
3539
3640 import type { App } from "../app.ts";
@@ -49,6 +53,7 @@ import {
4953 } from "./retention_events.ts";
5054 import { pruneSamples, ROW_CAP } from "./retention_samples.ts";
5155 import { pruneTelemetry, type Cursor } from "./retention_telemetry.ts";
56 import { giveBack } from "./retention_vacuum.ts";
5257
5358 /** The share of the thread one job may take while it has work behind it. */
5459 export const DUTY = 0.05;
@@ -102,6 +107,7 @@ export interface Retention {
102107 readonly backfill: Job;
103108 readonly deploys: Job;
104109 readonly telemetry: Job;
110 readonly vacuum: Job;
105111 /** Whether `deploy_landed` has had a full pass from the old ledger. */
106112 landedReady(): boolean;
107113 }
@@ -111,6 +117,8 @@ export function retentionJobs(app: App): Retention {
111117 let filled = false;
112118 let cursor: { at: string; id: string } | undefined;
113119 const walked: Cursor = { probe: 0, finding: 0 };
120 /** Pages the vacuum's current pass has given back, said when the pass ends. */
121 let reclaimed = 0;
114122 const trimDeploys = deployRetention(
115123 db,
116124 undefined,
@@ -181,6 +189,19 @@ export function retentionJobs(app: App): Retention {
181189 return r === undefined ? { did: 0, more: false } : { did: r.deleted, more: r.more };
182190 },
183191 },
192 vacuum: {
193 idleMs: IDLE_MS,
194 slice() {
195 const r = quietly(db, () => withoutWaiting(db, () => giveBack(db)));
196 reclaimed += r.reclaimed;
197 if (!r.more && reclaimed > 0) {
198 const pageSize = (db.query("PRAGMA page_size").get() as { page_size: number } | null)?.page_size ?? 4096;
199 app.log.info("retention-vacuum gave free pages back to the disk", { pages: reclaimed, bytes: reclaimed * pageSize });
200 reclaimed = 0;
201 }
202 return { did: r.reclaimed, more: r.more };
203 },
204 },
184205 };
185206 }
186207
@@ -263,11 +284,19 @@ export function startRetention(app: App, which: { local: boolean; engine: boolea
263284 during("retention-telemetry", () => telemetry(work(jobs.telemetry, "probe and finding prune")), undefined, app);
264285 }, delay);
265286 };
287 const vacuum = (delay: number): void => {
288 pending[6] = setTimeout(() => {
289 if (stopped) return;
290 if (held(vacuum)) return;
291 during("retention-vacuum", () => vacuum(work(jobs.vacuum, "free page give-back")), undefined, app);
292 }, delay);
293 };
266294 if (which.local) {
267295 live(1_000);
268296 samples(5_000);
269297 deploys(7_000);
270298 telemetry(9_000);
299 vacuum(11_000);
271300 }
272301 return () => {
273302 stopped = true;
src/system/retention_vacuum.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * Free pages given back to the disk, a few at a time. Once the database is an incremental-vacuum
3 * file (`auto_vacuum = 2`, which a compaction makes it: `system/compact.ts`), a deleted row's pages
4 * wait on the freelist until `PRAGMA incremental_vacuum(n)` moves the last pages of the file into
5 * them and cuts the file shorter. In WAL mode the file itself shrinks at the next checkpoint
6 * (`engine/duties.ts` runs one every two seconds).
7 *
8 * A slice gives back `SLICE_PAGES` (1 MiB at 4 KiB a page). On a copy of production,
9 * `incremental_vacuum(2048)` took 35 ms at the median and 75 ms at the worst, so a slice of 256
10 * is a few milliseconds, and `system/retention.ts` paces it at a twentieth of the thread like
11 * every other drain. A file that is not incremental is left alone: changing the mode needs the
12 * whole VACUUM, which only a compaction does.
13 */
14 import type { Database } from "bun:sqlite";
15
16 /** Pages one slice gives back at most. */
17 export const SLICE_PAGES = 256;
18
19 const pragma = (db: Database, name: "auto_vacuum" | "freelist_count"): number =>
20 (db.query(`PRAGMA ${name}`).get() as Record<string, number> | null)?.[name] ?? 0;
21
22 /** One slice: the pages given back, and whether free pages are left. */
23 export function giveBack(db: Database, pages = SLICE_PAGES): { reclaimed: number; more: boolean } {
24 if (pragma(db, "auto_vacuum") !== 2) return { reclaimed: 0, more: false };
25 const free = pragma(db, "freelist_count");
26 if (free === 0) return { reclaimed: 0, more: false };
27 db.run(`PRAGMA incremental_vacuum(${Math.max(1, Math.floor(pages))})`);
28 const left = pragma(db, "freelist_count");
29 return { reclaimed: free - left, more: left > 0 };
30 }
src/tui/screens/system.ts +2
@@ -295,6 +295,8 @@ export function dbSizeLines(session: Session, size: DbSize, brief = false, inner
295295 "Database size",
296296 ...wrap(`forge.db ${bytes(size.fileBytes)}, WAL ${bytes(size.walBytes)}${w === null ? "" : `, ${bytes(w.freeBytes)} free inside`}; ${grows}`, inner),
297297 ...(said === undefined ? [] : wrap(said.sentence, inner)),
298 // What a compaction kept (`system/compact.ts`), said until a person removes it.
299 ...size.kept.flatMap((k) => wrap(`kept before compaction: ${k.name}, ${bytes(k.bytes)}`, inner)),
298300 ];
299301 // One line in the dialog, which does not scroll: the rest is a key away.
300302 if (brief) {
src/web/pages/system.ts +2 −1
@@ -147,7 +147,8 @@ export function dbSizeSection(size: DbSize): Html {
147147 ${fact("File", bytes(size.fileBytes))}
148148 ${fact("WAL", bytes(size.walBytes))}
149149 ${w === null ? null : fact("Free inside", bytes(w.freeBytes))}
150 ${fact("Growth", grows)}</dl>
150 ${fact("Growth", grows)}
151 ${size.kept.map((k) => fact("Kept before compaction", `${k.name}, ${bytes(k.bytes)}`))}</dl>
151152 ${w === null
152153 ? html`<p class="muted small">Its tables are being measured; reload in a moment.</p>`
153154 : html`<div class="table-scroll"><table class="table" data-dense aria-label="The ${String(TOP)} largest tables and indexes in the database">
test/db-compact.test.ts added +336
@@ -0,0 +1,336 @@
1 /**
2 * The one-shot compaction at boot (`system/compact.ts`) and the incremental give-back after it
3 * (`system/retention_vacuum.ts`). The compaction runs only on the marker and consumes it; the
4 * database is replaced only by a copy that proved itself, the file it was is kept, and every
5 * failure leaves the database byte for byte as it was.
6 */
7 import { afterEach, describe, expect, test } from "bun:test";
8 import { Database } from "bun:sqlite";
9 import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { migrations } from "../src/core/schema.ts";
13 import { openDb } from "../src/kernel/db.ts";
14 import type { Log } from "../src/kernel/log.ts";
15 import { compactFile, compactOnBoot, COPY, countsDiffer, inProcess, KEPT_PREFIX, keptCopies, MARKER, type Runner } from "../src/system/compact.ts";
16 import { giveBack } from "../src/system/retention_vacuum.ts";
17 import { retentionJobs } from "../src/system/retention.ts";
18 import type { App } from "../src/app.ts";
19
20 const now0 = Date.parse("2026-11-30T12:00:00.000Z");
21
22 const dirs: string[] = [];
23 afterEach(() => {
24 for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
25 });
26
27 function dataDir(): string {
28 const d = mkdtempSync(join(tmpdir(), "forge-compact-"));
29 dirs.push(d);
30 return d;
31 }
32
33 interface Said {
34 readonly level: string;
35 readonly message: string;
36 readonly fields: Record<string, unknown> | undefined;
37 }
38 function logged(): { log: Log; said: Said[] } {
39 const said: Said[] = [];
40 const at = (level: string) => (message: string, fields?: Record<string, unknown>) => void said.push({ level, message, fields });
41 return { log: { debug: at("debug"), info: at("info"), warn: at("warn"), error: at("error") }, said };
42 }
43
44 /**
45 * A WAL database like production's: two tables, most rows deleted so most pages are free, and
46 * the newest writes still only in the WAL (the handle stays open, so nothing checkpoints them).
47 */
48 function fragmented(dir: string): { path: string; held: Database } {
49 const path = join(dir, "forge.db");
50 const db = new Database(path, { create: true, strict: true });
51 db.run("PRAGMA journal_mode = WAL");
52 db.run("PRAGMA wal_autocheckpoint = 0");
53 db.run("CREATE TABLE event (id INTEGER PRIMARY KEY, body TEXT NOT NULL)");
54 db.run("CREATE TABLE comment (id INTEGER PRIMARY KEY, body TEXT NOT NULL)");
55 db.run("CREATE INDEX event_body ON event(body)");
56 const add = db.query("INSERT INTO event (body) VALUES (?1)");
57 db.transaction(() => {
58 for (let i = 0; i < 3000; i++) add.run(`${i}:${"x".repeat(900)}`);
59 })();
60 db.run("PRAGMA wal_checkpoint(TRUNCATE)");
61 db.run("DELETE FROM event WHERE id % 10 <> 0");
62 db.run("PRAGMA wal_checkpoint(TRUNCATE)");
63 // Written after the last checkpoint: only the WAL holds these.
64 db.run("INSERT INTO comment (body) VALUES ('kept in the WAL'), ('and this')");
65 return { path, held: db };
66 }
67
68 const pragma = (db: Database, name: string): number => (db.query(`PRAGMA ${name}`).get() as Record<string, number>)[name] ?? -1;
69
70 describe("compaction at boot", () => {
71 test("without the marker nothing runs, however much of the file is free", async () => {
72 const dir = dataDir();
73 const { path, held } = fragmented(dir);
74 held.close();
75 const bytes = readFileSync(path);
76 const { log, said } = logged();
77 expect(await compactOnBoot(dir, log)).toEqual({ ran: false });
78 expect(readFileSync(path).equals(bytes)).toBe(true);
79 expect(said).toEqual([]);
80 expect(keptCopies(dir)).toEqual([]);
81 });
82
83 test("with the marker: the copy replaces the file, smaller and incremental, every row kept; the old file is kept; the marker is consumed", async () => {
84 const dir = dataDir();
85 const { path, held } = fragmented(dir);
86 const counts = { event: pragma(held, "page_count") };
87 expect(pragma(held, "freelist_count")).toBeGreaterThan(counts.event / 2);
88 // A forge that stopped closes its handle; its WAL's frames are checkpointed by the job.
89 held.close();
90 const before = statSync(path).size;
91 writeFileSync(join(dir, MARKER), "");
92 const { log, said } = logged();
93 const out = await compactOnBoot(dir, log, { now: () => new Date("2026-11-30T10:38:00.123Z") });
94 if (!out.ran || !out.ok) throw new Error(`not compacted: ${JSON.stringify(out)}`);
95 expect(existsSync(join(dir, MARKER))).toBe(false);
96 expect(existsSync(join(dir, COPY))).toBe(false);
97 expect(out.kept).toBe(join(dir, `${KEPT_PREFIX}20261130T103800Z`));
98 expect(out.before).toBe(before);
99 expect(out.after).toBeLessThan(before / 2);
100 for (const step of ["checkpointMs", "countMs", "vacuumMs", "checkMs", "totalMs"]) expect(typeof out.steps[step]).toBe("number");
101 expect(said.at(-1)).toMatchObject({ level: "info", message: expect.stringContaining("compacted") });
102 expect(keptCopies(dir)).toEqual([{ name: `${KEPT_PREFIX}20261130T103800Z`, bytes: before }]);
103
104 // The forge opens the new file the one correct way, and it has every row, the WAL's too.
105 const db = new Database(path, { strict: true });
106 expect(pragma(db, "auto_vacuum")).toBe(2);
107 expect(pragma(db, "freelist_count")).toBe(0);
108 expect(db.query("SELECT COUNT(*) AS n FROM event").get()).toEqual({ n: 300 });
109 expect(db.query("SELECT body FROM comment ORDER BY id").all()).toEqual([{ body: "kept in the WAL" }, { body: "and this" }]);
110 expect(db.query("PRAGMA quick_check").get()).toEqual({ quick_check: "ok" });
111 db.close();
112 // The kept file is the database as it was, whole.
113 const old = new Database(out.kept, { strict: true });
114 expect(old.query("SELECT COUNT(*) AS n FROM comment").get()).toEqual({ n: 2 });
115 expect(pragma(old, "auto_vacuum")).toBe(0);
116 old.close();
117 // Its WAL and index, made by opening it, are not kept files of their own.
118 expect(keptCopies(dir).map((k) => k.name)).toEqual([`${KEPT_PREFIX}20261130T103800Z`]);
119
120 // One-shot: the next boot does nothing.
121 expect(await compactOnBoot(dir, log)).toEqual({ ran: false });
122 });
123
124 test("a schema database opens on the compacted file through openDb, migrations and all", async () => {
125 const dir = dataDir();
126 const path = join(dir, "forge.db");
127 openDb(path, migrations).close();
128 writeFileSync(join(dir, MARKER), "");
129 const out = await compactOnBoot(dir, logged().log);
130 expect(out).toMatchObject({ ran: true, ok: true });
131 const db = openDb(path, migrations);
132 expect(pragma(db, "auto_vacuum")).toBe(2);
133 expect(db.query("PRAGMA journal_mode").get()).toEqual({ journal_mode: "wal" });
134 db.close();
135 });
136
137 /** The database's bytes and its directory's names, to prove a failure changed nothing. */
138 function untouched(dir: string, path: string): () => void {
139 const bytes = readFileSync(path);
140 return () => {
141 expect(readFileSync(path).equals(bytes)).toBe(true);
142 expect(existsSync(join(dir, COPY))).toBe(false);
143 expect(keptCopies(dir)).toEqual([]);
144 expect(existsSync(join(dir, MARKER))).toBe(false);
145 };
146 }
147
148 test("past the ceiling it is abandoned: the database is as it was and the partial copy goes", async () => {
149 const dir = dataDir();
150 const { path, held } = fragmented(dir);
151 held.close();
152 const same = untouched(dir, path);
153 writeFileSync(join(dir, MARKER), "");
154 // A copy that never ends, until the ceiling aborts it; it leaves a partial file behind.
155 const stuck: Runner = (job, say, abort) => {
156 say("vacuum");
157 writeFileSync(job.to, "partial");
158 return new Promise((resolve) =>
159 abort.addEventListener("abort", () => resolve({ done: true, ok: false, reason: String(abort.reason) })),
160 );
161 };
162 const { log, said } = logged();
163 const out = await compactOnBoot(dir, log, { runner: stuck, ceilingMs: 1 });
164 expect(out).toMatchObject({ ran: true, ok: false, reason: expect.stringContaining("ceiling during vacuum") });
165 same();
166 expect(said.at(-1)).toMatchObject({ level: "warn", message: expect.stringContaining("abandoned") });
167 });
168
169 test("an abort waits for the copy's process to be gone before the copy is removed and the boot goes on", async () => {
170 const dir = dataDir();
171 const { path, held } = fragmented(dir);
172 held.close();
173 const same = untouched(dir, path);
174 writeFileSync(join(dir, MARKER), "");
175 // A stand-in for a VACUUM INTO that will not stop: it writes the copy for ever.
176 const pidFile = join(dir, "busy.pid");
177 const script = join(dir, "busy-child.ts");
178 writeFileSync(
179 script,
180 `import { appendFileSync, writeFileSync } from "node:fs";
181 const job = JSON.parse(process.argv[2]);
182 writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));
183 appendFileSync(job.to, "x");
184 process.stdout.write(JSON.stringify({ step: "vacuum" }) + "\\n");
185 for (;;) appendFileSync(job.to, "x".repeat(4096));
186 `,
187 );
188 // Aborted the moment it says it is copying: the runner settles only once the process is gone.
189 const stop = new AbortController();
190 const outliving: Runner = (job, say, abort) => {
191 abort.addEventListener("abort", () => stop.abort(abort.reason), { once: true });
192 return inProcess(script)(job, (step) => (say(step), stop.abort("aborted while copying")), stop.signal);
193 };
194 const out = await compactOnBoot(dir, logged().log, { runner: outliving });
195 expect(out).toMatchObject({ ran: true, ok: false, reason: "aborted while copying" });
196 const pid = Number(readFileSync(pidFile, "utf8"));
197 expect(() => process.kill(pid, 0)).toThrow();
198 expect(existsSync(join(dir, COPY))).toBe(false);
199 same();
200 });
201
202 test("a copy that fails its proof is never swapped in", async () => {
203 const dir = dataDir();
204 const { path, held } = fragmented(dir);
205 held.close();
206 const same = untouched(dir, path);
207 writeFileSync(join(dir, MARKER), "");
208 const lying: Runner = async (job) => {
209 writeFileSync(job.to, "a copy short of rows");
210 return { done: true, ok: false, reason: "table event has 299 rows in the copy, 300 in the database" };
211 };
212 const out = await compactOnBoot(dir, logged().log, { runner: lying });
213 expect(out).toMatchObject({ ran: true, ok: false, reason: expect.stringContaining("299 rows") });
214 same();
215 });
216
217 test("another connection holding the database refuses the checkpoint, and nothing is copied", async () => {
218 const dir = dataDir();
219 const { path, held } = fragmented(dir);
220 // A reader mid-transaction: the TRUNCATE checkpoint cannot finish behind it.
221 held.run("BEGIN");
222 held.query("SELECT COUNT(*) FROM event").get();
223 const verdict = compactFile({ db: path, to: join(dir, COPY) }, () => {});
224 expect(verdict).toEqual({ done: true, ok: false, reason: expect.stringContaining("checkpoint was refused") });
225 expect(existsSync(join(dir, COPY))).toBe(false);
226 held.run("COMMIT");
227 held.close();
228 });
229
230 test("too little disk for the copy: abandoned before it starts", async () => {
231 const dir = dataDir();
232 const { path, held } = fragmented(dir);
233 held.close();
234 const same = untouched(dir, path);
235 writeFileSync(join(dir, MARKER), "");
236 const never: Runner = () => {
237 throw new Error("the copy must not start");
238 };
239 const out = await compactOnBoot(dir, logged().log, { runner: never, diskFree: () => 1024 });
240 expect(out).toMatchObject({ ran: true, ok: false, reason: expect.stringContaining("bytes free") });
241 same();
242 });
243
244 test("a marker with no database consumes the marker and says so", async () => {
245 const dir = dataDir();
246 writeFileSync(join(dir, MARKER), "");
247 const out = await compactOnBoot(dir, logged().log);
248 expect(out).toMatchObject({ ran: true, ok: false, reason: expect.stringContaining("no forge.db") });
249 expect(existsSync(join(dir, MARKER))).toBe(false);
250 expect(existsSync(join(dir, "forge.db"))).toBe(false);
251 });
252
253 test("row counts that differ name the table", () => {
254 const a = new Map([
255 ["event", 300],
256 ["comment", 2],
257 ]);
258 expect(countsDiffer(a, new Map(a))).toBeUndefined();
259 expect(
260 countsDiffer(
261 a,
262 new Map([
263 ["event", 299],
264 ["comment", 2],
265 ]),
266 ),
267 ).toBe("table event has 299 rows in the copy, 300 in the database");
268 expect(countsDiffer(a, new Map([["event", 300]]))).toContain("1 tables");
269 });
270 });
271
272 describe("free pages given back", () => {
273 test("an incremental file gives its free pages back a slice at a time and shrinks at the checkpoint", async () => {
274 const dir = dataDir();
275 const { held } = fragmented(dir);
276 held.close();
277 writeFileSync(join(dir, MARKER), "");
278 expect(await compactOnBoot(dir, logged().log)).toMatchObject({ ok: true });
279 const path = join(dir, "forge.db");
280 const db = new Database(path, { strict: true });
281 db.run("PRAGMA journal_mode = WAL");
282 db.run("DELETE FROM event WHERE id % 20 <> 0");
283 const free = pragma(db, "freelist_count");
284 expect(free).toBeGreaterThan(16);
285 const first = giveBack(db, 8);
286 expect(first).toEqual({ reclaimed: 8, more: true });
287 let total = first.reclaimed;
288 for (;;) {
289 const r = giveBack(db, 8);
290 total += r.reclaimed;
291 if (!r.more) break;
292 }
293 expect(total).toBe(free);
294 expect(giveBack(db)).toEqual({ reclaimed: 0, more: false });
295 const pages = pragma(db, "page_count");
296 db.run("PRAGMA wal_checkpoint(TRUNCATE)");
297 expect(statSync(path).size).toBe(pages * pragma(db, "page_size"));
298 expect(db.query("SELECT COUNT(*) AS n FROM event").get()).toEqual({ n: 150 });
299 db.close();
300 });
301
302 test("the retention-vacuum job paces the slices and says what a pass gave back", async () => {
303 const dir = dataDir();
304 const { held } = fragmented(dir);
305 held.close();
306 writeFileSync(join(dir, MARKER), "");
307 expect(await compactOnBoot(dir, logged().log)).toMatchObject({ ok: true });
308 const db = new Database(join(dir, "forge.db"), { strict: true });
309 db.run("PRAGMA journal_mode = WAL");
310 db.run("DELETE FROM event");
311 const free = pragma(db, "freelist_count");
312 const { log, said } = logged();
313 const jobs = retentionJobs({ db, log } as unknown as App);
314 let did = 0;
315 for (;;) {
316 const r = jobs.vacuum.slice(now0);
317 did += r.did;
318 if (!r.more) break;
319 }
320 expect(did).toBe(free);
321 expect(said).toEqual([{ level: "info", message: "retention-vacuum gave free pages back to the disk", fields: { pages: free, bytes: free * 4096 } }]);
322 expect(jobs.vacuum.slice(now0)).toEqual({ did: 0, more: false });
323 expect(said).toHaveLength(1);
324 db.close();
325 });
326
327 test("a file that is not incremental is left alone", () => {
328 const dir = dataDir();
329 const { held } = fragmented(dir);
330 const free = pragma(held, "freelist_count");
331 expect(free).toBeGreaterThan(0);
332 expect(giveBack(held)).toEqual({ reclaimed: 0, more: false });
333 expect(pragma(held, "freelist_count")).toBe(free);
334 held.close();
335 });
336 });
test/db-size.test.ts +23 −1
@@ -8,7 +8,7 @@
88 */
99 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1010 import { Database } from "bun:sqlite";
11 import { mkdtempSync } from "node:fs";
11 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
1212 import { rm } from "node:fs/promises";
1313 import { tmpdir } from "node:os";
1414 import { join } from "node:path";
@@ -279,6 +279,21 @@ describe("growth and the need", () => {
279279 expect(cache.peek(app.db, dataDir).walk).toBe(read.walk);
280280 });
281281
282 test("the files a compaction kept are listed with the walk, so a peek scans no directory", async () => {
283 const cache = dbSizeCache((db, d) => measureDbWalk(db, d));
284 const name = "forge.db.before-compact-20261130T103800Z";
285 writeFileSync(join(dataDir, name), "old");
286 try {
287 expect(cache.peek(app.db, dataDir).kept).toEqual([]);
288 expect((await cache.read(app.db, dataDir, 5_000)).kept).toEqual([{ name, bytes: 3 }]);
289 // Gone from the directory, it is still the walk's list until the next walk: no scan per read.
290 rmSync(join(dataDir, name));
291 expect(cache.peek(app.db, dataDir).kept).toEqual([{ name, bytes: 3 }]);
292 } finally {
293 rmSync(join(dataDir, name), { force: true });
294 }
295 });
296
282297 test("last gives the cached walk without waiting, and starts the first one", async () => {
283298 let walks = 0;
284299 let finish = (): void => {};
@@ -337,6 +352,7 @@ describe("/system's Database size", () => {
337352 fileBytes: 3 * 1024 ** 3,
338353 walBytes: 4 * 1024 ** 2,
339354 growth: { perDay: 10 * 1024 ** 2, days: 7, readings: [] },
355 kept: [],
340356 walk: {
341357 at: "2026-11-13T12:00:00.000Z",
342358 pageSize: 4096,
@@ -373,6 +389,12 @@ describe("/system's Database size", () => {
373389 expect(index).toContain('colspan="2"');
374390 });
375391
392 test("a file kept before a compaction is named with its size, and none is no row", () => {
393 expect(String(dbSizeSection(size))).not.toContain("Kept before compaction");
394 const out = String(dbSizeSection({ ...size, kept: [{ name: "forge.db.before-compact-20261130T103800Z", bytes: 5 * 1024 ** 3 }] }));
395 expect(out).toContain("<dt>Kept before compaction</dt><dd>forge.db.before-compact-20261130T103800Z, 5.0 GiB</dd>");
396 });
397
376398 test("while the first walk runs it says so, and growth waits for a day of readings", () => {
377399 const out = String(dbSizeSection({ ...size, fileBytes: 1024, walk: null, growth: { perDay: null, days: 0, readings: [] } }));
378400 expect(out).toContain("being measured");
test/job-slices.test.ts +1
@@ -254,6 +254,7 @@ function jobs(): Record<string, () => unknown> {
254254 "landed-backfill": () => retention.backfill.slice(Date.now()),
255255 "retention-deploys": () => retention.deploys.slice(Date.now()),
256256 "retention-telemetry": () => retention.telemetry.slice(Date.now() + 40 * 86_400_000),
257 "retention-vacuum": () => retention.vacuum.slice(Date.now()),
257258 };
258259 }
259260
test/spawn-pipes.test.ts +1
@@ -20,6 +20,7 @@ const PIPING: Record<string, { sites: string[]; reason: string }> = {
2020 "src/apps/contain.ts": { sites: ["stderr"], reason: "stderr awaited with the exit; stdout ignored" },
2121 "src/apps/process.ts": { sites: ["stdout+stderr", "stdout+stderr"], reason: "pump() reads stdout and stderr of the app until exit" },
2222 "src/snapshot/drill_job.ts": { sites: ["stdout+stderr"], reason: "the drill child's stdout is read line by line for progress and its result, stderr to its end for the failure text, alongside the exit" },
23 "src/system/compact.ts": { sites: ["stdout"], reason: "the compaction child's stdout is read line by line for each step and its verdict, then the exit awaited (also after a kill on abort); stderr is ignored" },
2324 "src/spawn/archive.ts": { sites: ["stdout+stderr"], reason: "tar() reads the listing from stdout and the failure text from stderr, then waits for exit" },
2425 "src/spawn/cell.ts": { sites: ["stdout+stderr"], reason: "drain() reads the child forge's stdout and stderr to its log until exit" },
2526 "src/blob/large.ts": { sites: ["stdout"], reason: "cat-file stdout is the blob, read to the end into the store; stderr is ignored" },
test/spawn-sites.test.ts +2
@@ -101,6 +101,8 @@ const SITES: Record<string, string> = {
101101 "bun (process.execPath) on the forge's own restore script with a fixed argv, the kit written to a 0600 file in a scratch directory it just made; the passphrase in the environment only, nothing from a request",
102102 "src/snapshot/hosted.ts":
103103 "bun (process.execPath) on the forge's own hosted_copy.ts with an empty environment; its two arguments are a JSON job of three paths the snapshot built from a validated forge name and its own scratch directory, and the path its answer is written to: nothing from a request",
104 "src/system/compact.ts":
105 "bun (process.execPath) on the forge's own compact_child.ts with an empty environment, at boot only when an operator's compact-on-boot marker asks; its one argument is a JSON job of two paths under the forge's own data directory: nothing from a request",
104106 "src/spawn/archive.ts":
105107 "tar with fixed flags on the forge's own data directory and an archive path it derived from a validated name",
106108 "src/spawn/child_db.ts":
test/timers-named.test.ts +1
@@ -165,6 +165,7 @@ const ALLOWED: readonly Allowed[] = [
165165 ["src/system/footing.ts", "() => r(null)"],
166166 ["src/system/largest_dirs.ts", "() => r(null)"],
167167 ["src/system/db_size.ts", "() => r(null)"],
168 ["src/system/compact.ts", "() => abort.abort("],
168169 ["src/release/devtools.ts", "() => { if (pending.delete(n))"],
169170 ["src/release/devtools.ts", "() => { waiting.set(event"],
170171 ["src/release/prove.ts", "() => resolve(\"hung\")"],
test/tui-system.test.ts +10
@@ -189,6 +189,7 @@ describe("tui system database size (#12010)", () => {
189189 fileBytes: 3 * 1024 ** 3,
190190 walBytes: 4 * MiB,
191191 growth: { perDay: 10 * MiB, days: 7, readings: [] },
192 kept: [],
192193 walk: {
193194 at: new Date(Date.now() - 3 * 60_000).toISOString(),
194195 pageSize: 4096,
@@ -221,6 +222,15 @@ describe("tui system database size (#12010)", () => {
221222 }
222223 });
223224
225 test("a file kept before a compaction is said with its size in the whole, not in the dialog's line", () => {
226 const kept = { ...size, kept: [{ name: "forge.db.before-compact-20261130T103800Z", bytes: 5 * 1024 ** 3 }] };
227 const said = dbSizeLines(new Session(app, identity(carol)), kept).join(" ").replace(/\s+/g, " ");
228 expect(said).toContain("kept before compaction: forge.db.before-compact-20261130T103800Z, 5.0 GiB");
229 expect(said).not.toContain("never removes");
230 expect(dbSizeLines(new Session(app, identity(carol)), size).join(" ")).not.toContain("kept before compaction");
231 expect(dbSizeLines(new Session(app, identity(carol)), kept, true).join(" ")).not.toContain("kept before compaction");
232 });
233
224234 test("a member, an ungranted agent and a guest read nothing, brief or whole", () => {
225235 for (const who of [bob, bot, undefined])
226236 for (const brief of [false, true]) expect(dbSizeLines(new Session(app, identity(who)), size, brief)).toEqual([]);
test/worker-database-opens.test.ts +1
@@ -69,6 +69,7 @@ const REACHED: Record<string, { opens: number; why: string }> = {
6969 "src/snapshot/restore.ts": { opens: 1, why: "a restore reads the sealed names of the restored copy once, in the restore tool or a drill on the serving thread" },
7070 "src/snapshot/snapshot.ts": { opens: 1, why: "a snapshot counts the rows of its own copy once, as a duty of the serving thread (a hosted forge's copy is read in a process of its own, snapshot/hosted_copy.ts); the mirror Worker imports this file for the manifest only" },
7171 "src/spawn/child_runs.ts": { opens: 2, why: "called by the reader process (spawn/child_db_reader.ts), never by a thread of the forge; cell.ts re-exports the two for tests that read a file directly" },
72 "src/system/compact.ts": { opens: 2, why: "compactFile opens the database and its copy once each, called only by the compaction's own process (system/compact_child.ts) at boot when the compact-on-boot marker asks; Workers reach the file through db_size.ts's keptCopies, which opens nothing" },
7273 };
7374
7475 /** The one place a Worker is made from a URL it was handed: each asker names its module. */

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

Keyboard shortcuts

Docs