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

The database keeps what it needs: deploy_pull, event and machine_sample have… #11978

Parked opened this in answer to
Closed without merging

scout/forge:scout/11973-the-database-keeps-what-it-needs-deploy → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +89 −2
src/http/mcp/tools/system.ts +3 −2
@@ -9,12 +9,13 @@ import { LAG_BAR_MS, overBar } from "../../../perf/lag_minutes.ts";
99 import { slowestRoutes } from "../../../perf/watch.ts";
1010 import { footing, riskLines } from "../../../system/footing.ts";
1111 import { laneWords, readOffsiteLane } from "../../../snapshot/offsite_lane.ts";
12 import { dbSize } from "../../../system/db_size.ts";
1213 import { largestDirs } from "../../../system/largest_dirs.ts";
1314 import { good, bad, type Tool } from "../shared.ts";
1415
1516 export const tool: Tool = {
1617 name: "system",
17 doc: "the machine the forge runs on, now: CPU, load, memory, disk, network, processes, `largestDirs`: the five largest directories under the forge's data as {at, dirs: [{name, bytes}]} (null while first measured; at most once a minute), `stalls`: the last hour's main-thread stalls by route (`<route> (in flight)` when still running at the wake), or `job:<name>`, as {cause, ms, count}, `readings`: the last 20 minutes' worst loop lag as {at, ms, what} beside `barMs` (100) and `over`, and `readers`: who polls the telemetry and how fast, `{ kind: \"routes\" }`: the 10 slowest budgeted routes as {route, p95Ms, budgetMs, n, slowestPhase}, over budget first; a forge admin, or an agent granted `telemetry:read`. `{ kind: \"csp\" }`: the last 24 h of Content-Security-Policy violations browsers reported, `{ directive, n, newest }` per directive (`newest` the blocked host last counted), most first, counted per UTC hour from `since`, and `scriptErrors` `{ page, where, message, n, last }`, as the security page reads them; a forge admin only. `{ kind: \"footing\" }`: what the forge stands on (#11685), as /system's \"What the forge stands on\": `forgeNode`, and per piece `{ id, need, what, machine, seen, risk, ifDies, issues }` read from the live cluster, with `risks`, one line per piece not on the forge's machine; a forge admin only. `{ kind: \"offsite\" }`: the off-site backup lane (#11805), as /system's \"Off-site backup\" and the terminal's: `{ health, says, where, sealed, lastSuccess, newest, error, drill: { at, verdict, from, offSite, reason } | null }`; a forge admin only",
18 doc: "the machine the forge runs on, now: CPU, load, memory, disk, network, processes, `db`: {fileBytes, walBytes, freeBytes, overMmapCap}, the database's size, `largestDirs`: the five largest directories under the forge's data as {at, dirs: [{name, bytes}]} (null while first measured; at most once a minute), `stalls`: the last hour's main-thread stalls by route (`<route> (in flight)` when still running at the wake), or `job:<name>`, as {cause, ms, count}, `readings`: the last 20 minutes' worst loop lag as {at, ms, what} beside `barMs` (100) and `over`, and `readers`: who polls the telemetry and how fast, `{ kind: \"routes\" }`: the 10 slowest budgeted routes as {route, p95Ms, budgetMs, n, slowestPhase}, over budget first; a forge admin, or an agent granted `telemetry:read`. `{ kind: \"csp\" }`: the last 24 h of Content-Security-Policy violations browsers reported, `{ directive, n, newest }` per directive (`newest` the blocked host last counted), most first, counted per UTC hour from `since`, and `scriptErrors` `{ page, where, message, n, last }`, as the security page reads them; a forge admin only. `{ kind: \"footing\" }`: what the forge stands on (#11685), as /system's \"What the forge stands on\": `forgeNode`, and per piece `{ id, need, what, machine, seen, risk, ifDies, issues }` read from the live cluster, with `risks`, one line per piece not on the forge's machine; a forge admin only. `{ kind: \"offsite\" }`: the off-site backup lane (#11805), as /system's \"Off-site backup\" and the terminal's: `{ health, says, where, sealed, lastSuccess, newest, error, drill: { at, verdict, from, offSite, reason } | null }`; a forge admin only",
1819 description:
1920 "The forge machine now: CPU, memory, disk, network. Admin or telemetry:read; `kind: csp`: 24 h of CSP violations (admin).",
2021 inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["csp", "routes", "footing", "offsite"] } } },
@@ -56,6 +57,6 @@ export const tool: Tool = {
5657 const readings = rows.map((r) => ({ at: new Date(r.at).toISOString(), ms: Math.round(r.ms * 10) / 10, what: r.what }));
5758 // At most 0.8 s on the walk (#11800); the last measurement, or null, when it is slower.
5859 const largest = await largestDirs.read(ctx.app.config.dataDir);
59 return good({ ...out, largestDirs: largest, stalls, barMs: LAG_BAR_MS, over: overBar(rows), readings });
60 return good({ ...out, largestDirs: largest, db: dbSize(ctx.app.db, ctx.app.config.dataDir), stalls, barMs: LAG_BAR_MS, over: overBar(rows), readings });
6061 },
6162 };
src/kernel/vitals.ts +11
@@ -28,6 +28,7 @@ import { STALE_AFTER_MS } from "../runs/lease.ts";
2828 import { ownRepoPath } from "./own_repo.ts";
2929 import { BUDGETS } from "./budgets.ts";
3030 import { openDbFiles } from "./file_modes.ts";
31 import { dbSize, MMAP_CAP_BYTES } from "../system/db_size.ts";
3132 import { backupVerdict, isWatched } from "../snapshot/bucket.ts";
3233 import { lastDrill } from "../snapshot/drills.ts";
3334 import { lastMirror, mirrorNeed } from "../snapshot/mirror.ts";
@@ -365,6 +366,16 @@ export function vitals(input: VitalsInput): Vitals {
365366 );
366367 }
367368
369 // A database past what Bun can map costs a read per page on every scan (#11973).
370 const size = dbSize(input.db, input.dataDir);
371 if (size.overMmapCap)
372 need(
373 "db-size",
374 `The database is ${(size.fileBytes / 1024 ** 3).toFixed(2)} GiB, past the ${MMAP_CAP_BYTES / 1024 ** 3} GiB Bun can map: every scan reads a page at a time.`,
375 undefined,
376 "/system",
377 );
378
368379 for (const file of openDbFiles(input.dataDir))
369380 need(`file:${file.name}`, file.sentence, undefined, "/settings/capacity");
370381
src/system/db_size.ts added +45
@@ -0,0 +1,45 @@
1 /**
2 * The forge's database, measured by the file (#11973): its size, the write-ahead
3 * log beside it, and the pages free inside it. Bun's SQLite maps at most 2 GiB
4 * (`kernel/db.ts`), so past `MMAP_CAP_BYTES` every scan costs a read per page and
5 * vitals says so. Three `stat`s and two pragmas: cheap enough for every page load.
6 * Bytes by table are not here: this SQLite is built without `dbstat`.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { statSync } from "node:fs";
11 import { join } from "node:path";
12
13 /** What Bun's SQLite can map; a database larger than this is read page by page. */
14 export const MMAP_CAP_BYTES = 2 * 1024 ** 3;
15
16 export interface DbSize {
17 /** The main file, bytes. */
18 readonly fileBytes: number;
19 /** The write-ahead log, bytes. */
20 readonly walBytes: number;
21 /** Bytes in free pages: room a vacuum would give back. */
22 readonly freeBytes: number;
23 readonly overMmapCap: boolean;
24 }
25
26 const sizeOf = (path: string): number => {
27 try {
28 return statSync(path).size;
29 } catch {
30 return 0; // absent: the log comes and goes
31 }
32 };
33
34 /** The database's size now; plain data. */
35 export function dbSize(db: Database, dataDir: string): DbSize {
36 const fileBytes = sizeOf(join(dataDir, "forge.db"));
37 const pages = db.query<{ freelist_count: number }, []>("PRAGMA freelist_count").get()?.freelist_count ?? 0;
38 const pageSize = db.query<{ page_size: number }, []>("PRAGMA page_size").get()?.page_size ?? 4096;
39 return {
40 fileBytes,
41 walBytes: sizeOf(join(dataDir, "forge.db-wal")),
42 freeBytes: pages * pageSize,
43 overMmapCap: fileBytes > MMAP_CAP_BYTES,
44 };
45 }
src/web/pages/system.ts +9
@@ -50,6 +50,7 @@ import { egressReportedLine } from "../../system/egress_line.ts";
5050 import { BREAK_STEPS, MACHINES, declaredFooting, footing, offMachine, whereWords, type Footing, type Machine } from "../../system/footing.ts";
5151 import { laneWords, readOffsiteLane, type OffsiteLane } from "../../snapshot/offsite_lane.ts";
5252 import { badge, chartBox, disclosure, meter, pill, row, time } from "../ui.ts";
53 import { dbSize, type DbSize } from "../../system/db_size.ts";
5354 import { LARGEST_DIRS, largestDirs, type LargestDirs } from "../../system/largest_dirs.ts";
5455 import { childDirOf, listChildren } from "../../actions/spawn.ts";
5556 import { childrenUse, realSelf, selfUse, shareOf, sizeWords, useWords, type ChildUseRow, type SelfUse } from "../../spawn/usage.ts";
@@ -91,6 +92,13 @@ export function largestDirsSection(found: LargestDirs | null): Html {
9192 <p class="muted small">Measured ${time(found.at)}</p>`}</section>`;
9293 }
9394
95 /** The database file, its log and the free pages inside it (#11973). */
96 export function dbSizeSection(s: DbSize): Html {
97 return html`<section class="settings-block" id="sys-db"><h2>Database</h2>
98 <ul class="list" aria-label="The database's size">${figureRow("forge.db", bytes(s.fileBytes), { bytes: String(s.fileBytes) })}${figureRow("write-ahead log", bytes(s.walBytes))}${figureRow("free pages", bytes(s.freeBytes))}</ul>
99 ${s.overMmapCap ? html`<p class="small">Past the 2 GiB Bun can map: every scan reads a page at a time.</p>` : null}</section>`;
100 }
101
94102 /** This forge's own size and use when it is a child in a cell (#10853); nothing on any other forge. */
95103 export function selfSection(self: SelfUse | null): Html {
96104 if (self === null) return html``;
@@ -487,6 +495,7 @@ export async function systemPage(ctx: Ctx): Promise<Response> {
487495 <section class="settings-block"><h2>Disks and network</h2>
488496 <ul class="list" id="sys-disks">${at("sys-disks")}</ul></section>
489497 ${largestDirsSection(largestUnder)}
498 ${dbSizeSection(dbSize(ctx.app.db, ctx.app.config.dataDir))}
490499 <section class="settings-block"><h2>Processes</h2>
491500 <div class="js-only small muted">Sort by <button class="btn" data-size="sm" type="button" data-sort="cpu" aria-pressed="true"><kbd>c</kbd> CPU</button>
492501 <button class="btn" data-size="sm" type="button" data-sort="mem" aria-pressed="false"><kbd>m</kbd> memory</button></div>
test/disk-marks.test.ts +20
@@ -12,6 +12,7 @@ import { observe, owned, type Watch } from "../src/crew/incidents.ts";
1212 import { vitals } from "../src/kernel/vitals.ts";
1313 import { largest, largestDirsCache, measureLargestDirs, type LargestDirs } from "../src/system/largest_dirs.ts";
1414 import { largestDirsSection } from "../src/web/pages/system.ts";
15 import { dbSize, MMAP_CAP_BYTES } from "../src/system/db_size.ts";
1516
1617 const tmp = mkdtempSync(join(tmpdir(), "disk-marks-"));
1718 afterAll(() => rmSync(tmp, { recursive: true, force: true }));
@@ -159,3 +160,22 @@ describe("the five largest directories under the forge's data", () => {
159160 expect(String(largestDirsSection(null))).toContain("Being measured");
160161 });
161162 });
163
164 describe("the database's size (#11973)", () => {
165 test("past Bun's 2 GiB map, vitals names it; under, it is quiet", () => {
166 const app = createApp({ dataDir: join(tmp, "dbsize"), url: "https://f.test" });
167 try {
168 const run = () => vitals({ db: app.db, signals: app.signals, dataDir: app.config.dataDir });
169 expect(run().degraded.map((d) => d.cause)).not.toContain("db-size");
170 const f = join(app.config.dataDir, "forge.db");
171 const { truncateSync, statSync } = require("node:fs");
172 const was = statSync(f).size;
173 truncateSync(f, MMAP_CAP_BYTES + 1); // sparse: no disk is spent
174 expect(run().degraded.map((d) => d.cause)).toContain("db-size");
175 expect(dbSize(app.db, app.config.dataDir).overMmapCap).toBe(true);
176 truncateSync(f, was);
177 } finally {
178 app.close();
179 }
180 });
181 });
test/system-parts.test.ts +1
@@ -52,6 +52,7 @@ test("one <h2> per part, each in a settings-block, and no card", async () => {
5252 "Machine",
5353 "Disks and network",
5454 "Largest under the forge's data",
55 "Database",
5556 "Processes",
5657 "What the forge stands on",
5758 "Off-site backup",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs