Public: anyone can read this; the crew can change it.
The database keeps what it needs: deploy_pull, event and machine_sample have… #11974
mason/forge:mason/11973-the-database-keeps-what-it-needs-deploy → main 8 commits fork
29 files
changed +1392
−79
- AGENTS.md
- docs/design/attention-budget.json
- docs/features/retention.md
- scripts/header-width-allow.json
- scripts/index-diet.ts
- scripts/sql-tap.ts
- src/actions/capacity.ts
- src/boards/ring.ts
- src/boards/sampler.ts
- src/core/capacity.ts
- src/core/carried.ts
- src/core/migration-pins/20261114000000-database-keeps-what-it-needs.pin
- src/core/migrations/20261114000000-database-keeps-what-it-needs.ts
- src/core/retention.ts
- src/http/api.ts
- src/http/mcp/tools/system.ts
- src/kernel/db.ts
- src/kernel/vitals.ts
- src/maintain/duties/retention.ts
- src/maintain/registry.ts
- src/system/db_size.ts
- src/tui/screens/system.ts
- src/web/pages/system.ts
- src/web/studio/run.ts
- test/data-browser.test.ts
- test/pages-budget.test.ts
- test/retention.test.ts
- test/system-parts.test.ts
- test/vitals.test.ts
AGENTS.md +1
| @@ -26,6 +26,7 @@ State shared between modules through process memory, not the database, is named | ||
| 26 | 26 | `src/core/transfer.ts`: the old owner/name pairs a transfer left behind (`repo_redirect`), held per database after the first request reads them and dropped by `transferRepo`, so a request under a path nothing moved from costs no statement (#569). |
| 27 | 27 | |
| 28 | 28 | `src/system/footing.ts`: `footing`, the last reading of what the forge stands on from the kube API (#11685), held 60 s so /system, its terminal screen (`src/tui/screens/footing.ts`, palette entry for admins) and the MCP `system` tool (`kind: footing`) share one read; a probe that throws is not retried for 60 s; one reading, gone on restart. |
| 29 | `src/system/db_size.ts`: `peekDbSize`, the last walk of every table and index's estimated size (#11973), held 10 minutes so /system, its terminal screen and the MCP `system` tool share one asynchronous walk; `carriedOrRebuild` (`src/core/carried.ts`) keeps at most 1,000 run ids found to carry nothing; one reading each, gone on restart. | |
| 29 | 30 | `src/system/largest_dirs.ts`: `largestDirs`, the last measurement of the five largest directories under the forge's data (#11800), held 60 s so /system, its terminal screen (`src/tui/screens/system.ts`, `largestLines`) and the MCP `system` tool share one asynchronous walk; a walk that fails is not retried for 60 s; one reading, gone on restart. |
| 30 | 31 | |
| 31 | 32 | `src/apps/timer_fire.ts`: `inFlight`, the ids of timers being fired in this process, so a slow app's timer is never fired twice at once; at most the timers due, gone when each settles. The timers themselves are rows (`timer`), read at every boot, never memory. |
docs/design/attention-budget.json +5 −5
| @@ -172,16 +172,16 @@ | ||
| 172 | 172 | }, |
| 173 | 173 | "system": { |
| 174 | 174 | "390": { |
| 175 | "words": 212, | |
| 176 | "blocks": 67, | |
| 175 | "words": 218, | |
| 176 | "blocks": 70, | |
| 177 | 177 | "colours": 0 |
| 178 | 178 | }, |
| 179 | 179 | "1280": { |
| 180 | "words": 212, | |
| 181 | "blocks": 67, | |
| 180 | "words": 218, | |
| 181 | "blocks": 70, | |
| 182 | 182 | "colours": 0 |
| 183 | 183 | }, |
| 184 | "note": "Measured on the test forge's empty state with the machine reading replaced by an empty one and the two cell-cap sentences fixed (the live page's counts depend on the host's cores, disks, processes and cgroups); nothing seeded or waited for. Blocks 65 -> 67 (#11805): the off-site backup section's heading and one-sentence state stay on first view so a red lane is seen without a click; its rows sit behind the disclosure." | |
| 184 | "note": "Measured on the test forge's empty state with the machine reading replaced by an empty one and the two cell-cap sentences fixed (the live page's counts depend on the host's cores, disks, processes and cgroups); nothing seeded or waited for. Blocks 65 -> 67 (#11805): the off-site backup section's heading and one-sentence state stay on first view so a red lane is seen without a click; its rows sit behind the disclosure. Words 212 -> 218, blocks 67 -> 70 (#11973): the database's size section keeps its heading and one sentence of file, growth and free space on first view; the largest tables and indexes sit behind the disclosure." | |
| 185 | 185 | }, |
| 186 | 186 | "explore": { |
| 187 | 187 | "390": { |
docs/features/retention.md added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | # What the database keeps (#11973) | |
| 2 | ||
| 3 | The forge's file was 4.56 GB on 2026-11-13, past the 2 GiB Bun maps, and three bookkeeping tables | |
| 4 | were most of it. Each now has one rule, in `src/core/retention.ts`, run by the `retention` | |
| 5 | maintenance duty (`src/maintain/duties/retention.ts`) one small batch a minute. | |
| 6 | ||
| 7 | | Table | Kept | Who reads what age | | |
| 8 | |---|---|---| | |
| 9 | | `deploy_pull` | rows of deploys of the last `retention.deploy_pull_days` (30), and of the deploy each production app serves now | ask-to-live reads 7 days (`core/pillars.ts`); a deploy's page and API rebuild older rows from git (`carriedOrRebuild`) | | |
| 10 | | `event` | audit kinds (`account.` `user.` `token.` `secret.` `trust.` `repo.` `org.` `billing.` `device.` `team.` `invite.` `crew.` `origin.`) for ever; machine chatter `retention.chatter_days` (30); everything else `retention.event_days` (365) | feeds read the newest events, `web/pages/security.ts` its own kind, webhooks retry for hours, a replay cursor that is gone falls back to ids | | |
| 11 | | `machine_sample` | every 15 s for `retention.sample_fine_hours` (48), a row per 5 min for `retention.sample_coarse_days` (30), the row at the top of each hour for `retention.sample_hourly_days` (90) | the boards read the window they draw | | |
| 12 | ||
| 13 | All are settings on the capacity page (`PUT /api/v1/admin/capacity/{key}`), shown on /system's | |
| 14 | "The database" beside the size table. | |
| 15 | ||
| 16 | **Batches.** A batch deletes in transactions of 500 rows, starts no transaction after 40 ms, and | |
| 17 | stops at 20,000 rows; where a walk stopped is `retention_cursor`. The outbox walk only goes forward; | |
| 18 | the other two read their table once a day. | |
| 19 | ||
| 20 | **Space.** Deleted rows free pages; they are given back with `PRAGMA incremental_vacuum` a step | |
| 21 | (200 pages) at a time, never a blocking `VACUUM` on the live handle, which holds the write lock for | |
| 22 | the whole rewrite. Every database made from this build on is `auto_vacuum = INCREMENTAL`. A file made | |
| 23 | before (production's) is `none` and SQLite only changes that by rewriting the file: once, at a release | |
| 24 | hand-over, with the forge stopped, `sqlite3 forge.db "VACUUM INTO 'forge.new'"` after | |
| 25 | `PRAGMA auto_vacuum = INCREMENTAL` on the new file's connection, then swap the files. /system says which mode the file is in. | |
| 26 | ||
| 27 | **Size.** /system, the terminal's System screen and the MCP `system` tool (`database`) show the file | |
| 28 | size, growth a day, and the ten heaviest tables and indexes (estimated: Bun's SQLite has no `dbstat`). | |
| 29 | Vitals names the database when it passes 2 GiB or grows over `size.growth_mb_per_day` (200). | |
| 30 | ||
| 31 | **Index diet.** `scripts/index-diet.ts` lists every index with the statements that use it | |
| 32 | (`scripts/sql-tap.ts` records what a test run prepares). It drops nothing; run it over the suite on a | |
| 33 | copy of production and read the unused list against the code before a migration drops one. |
scripts/header-width-allow.json +1 −2
scripts/index-diet.ts added +78
| @@ -0,0 +1,78 @@ | ||
| 1 | /** | |
| 2 | * The index diet (#11973): every index of the schema, and the statements the suite prepares that | |
| 3 | * use it, from EXPLAIN QUERY PLAN. An index no statement uses is a candidate to drop; the report | |
| 4 | * lists it with its estimated bytes. It drops nothing: a statement the suite never prepares (a | |
| 5 | * rare admin page, a migration) can still need an index, so a person reads the list against the | |
| 6 | * code before a migration drops one. | |
| 7 | * | |
| 8 | * FORGE_SQL_TAP=$TMPDIR/sql.jsonl bun test --preload ./scripts/sql-tap.ts <files> | |
| 9 | * bun scripts/index-diet.ts $TMPDIR/sql.jsonl [path/to/forge.db-copy] | |
| 10 | * | |
| 11 | * Plans come from a freshly migrated database; when a copy of production is named, its | |
| 12 | * `sqlite_stat1` and row counts size the unused indexes (`system/db_size.ts`). Read-only on the | |
| 13 | * copy. | |
| 14 | */ | |
| 15 | import { Database } from "bun:sqlite"; | |
| 16 | import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; | |
| 17 | import { tmpdir } from "node:os"; | |
| 18 | import { join } from "node:path"; | |
| 19 | import { openDb } from "../src/kernel/db.ts"; | |
| 20 | import { migrationFiles } from "../src/core/schema.ts"; | |
| 21 | import { measureDbSize } from "../src/system/db_size.ts"; | |
| 22 | ||
| 23 | const [tapFile, copy] = process.argv.slice(2); | |
| 24 | if (tapFile === undefined || !existsSync(tapFile)) { | |
| 25 | console.error("usage: bun scripts/index-diet.ts <sql.jsonl> [forge.db copy]"); | |
| 26 | process.exit(2); | |
| 27 | } | |
| 28 | ||
| 29 | const statements = [...new Set(readFileSync(tapFile, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l) as string))].filter((s) => | |
| 30 | /^\s*(SELECT|WITH|UPDATE|DELETE)/i.test(s), | |
| 31 | ); | |
| 32 | ||
| 33 | const dir = mkdtempSync(join(tmpdir(), "index-diet-")); | |
| 34 | const db = openDb(join(dir, "plan.db"), migrationFiles); | |
| 35 | const indexes = db | |
| 36 | .query<{ name: string; tbl_name: string; sql: string | null }, []>("SELECT name, tbl_name, sql FROM sqlite_schema WHERE type = 'index' AND name NOT LIKE 'sqlite_autoindex%' ORDER BY name") | |
| 37 | .all(); | |
| 38 | const users = new Map<string, string[]>(indexes.map((i) => [i.name, []])); | |
| 39 | let planned = 0; | |
| 40 | for (const sql of statements) { | |
| 41 | const params = Math.max(0, ...[...sql.matchAll(/\?(\d+)/g)].map((m) => Number(m[1])), (sql.match(/\?(?!\d)/g) ?? []).length); | |
| 42 | try { | |
| 43 | const plan = db.query<{ detail: string }, string[]>(`EXPLAIN QUERY PLAN ${sql}`).all(...Array.from({ length: params }, () => "x")); | |
| 44 | planned++; | |
| 45 | for (const { detail } of plan) { | |
| 46 | const m = /USING (?:COVERING )?INDEX (\S+)/.exec(detail); | |
| 47 | if (m?.[1] !== undefined) users.get(m[1])?.push(sql.replace(/\s+/g, " ").slice(0, 100)); | |
| 48 | } | |
| 49 | } catch { | |
| 50 | // A statement for another schema (a test's own table) has no plan here. | |
| 51 | } | |
| 52 | } | |
| 53 | ||
| 54 | let weights = new Map<string, number>(); | |
| 55 | if (copy !== undefined && existsSync(copy)) { | |
| 56 | const prod = new Database(copy, { readonly: true }); | |
| 57 | const size = await measureDbSize(prod, join(copy, "..")); | |
| 58 | weights = new Map(size.indexes.map((i) => [i.name, i.bytes])); | |
| 59 | prod.close(); | |
| 60 | } | |
| 61 | ||
| 62 | console.log(`# Index diet\n\n${indexes.length} indexes, ${planned} of ${statements.length} prepared statements planned.\n`); | |
| 63 | console.log("## Used\n"); | |
| 64 | for (const i of indexes) { | |
| 65 | const by = users.get(i.name) ?? []; | |
| 66 | if (by.length > 0) console.log(`- ${i.name} (${i.tbl_name}): ${by.length} statements, e.g. \`${by[0]}\``); | |
| 67 | } | |
| 68 | console.log("\n## Used by nothing the suite prepares\n"); | |
| 69 | let total = 0; | |
| 70 | for (const i of indexes) { | |
| 71 | if ((users.get(i.name) ?? []).length > 0) continue; | |
| 72 | const bytes = weights.get(i.name); | |
| 73 | if (bytes !== undefined) total += bytes; | |
| 74 | console.log(`- ${i.name} (${i.tbl_name})${bytes === undefined ? "" : `: ~${(bytes / 1024 ** 2).toFixed(1)} MB`}`); | |
| 75 | } | |
| 76 | if (weights.size > 0) console.log(`\nBytes a drop of all of them would return, estimated: ${(total / 1024 ** 2).toFixed(1)} MB`); | |
| 77 | db.close(); | |
| 78 | rmSync(dir, { recursive: true, force: true }); |
scripts/sql-tap.ts added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | /** | |
| 2 | * Records every distinct SQL text a test run prepares, for `scripts/index-diet.ts` (#11973): | |
| 3 | * FORGE_SQL_TAP=$TMPDIR/sql.jsonl bun test --preload ./scripts/sql-tap.ts <files> | |
| 4 | * Appends each distinct statement, as one JSON string per line, when first prepared. Does nothing | |
| 5 | * unless FORGE_SQL_TAP is set. | |
| 6 | */ | |
| 7 | import { Database } from "bun:sqlite"; | |
| 8 | import { appendFileSync } from "node:fs"; | |
| 9 | ||
| 10 | const out = process.env.FORGE_SQL_TAP; | |
| 11 | if (out !== undefined && out !== "") { | |
| 12 | const seen = new Set<string>(); | |
| 13 | const proto = Database.prototype as unknown as Record<string, (...a: unknown[]) => unknown>; | |
| 14 | for (const method of ["query", "prepare"] as const) { | |
| 15 | const original = proto[method]!; | |
| 16 | proto[method] = function (this: unknown, ...args: unknown[]) { | |
| 17 | const sql = args[0]; | |
| 18 | if (typeof sql === "string" && !seen.has(sql)) { | |
| 19 | seen.add(sql); | |
| 20 | // Written as it is first seen: `bun test` ends without running exit handlers. | |
| 21 | try { | |
| 22 | appendFileSync(out, `${JSON.stringify(sql)}\n`); | |
| 23 | } catch { | |
| 24 | // The tap is a measuring aid: a failure to write it must not fail a test run. | |
| 25 | } | |
| 26 | } | |
| 27 | return original.apply(this, args); | |
| 28 | }; | |
| 29 | } | |
| 30 | } |
src/actions/capacity.ts +24 −10
| @@ -122,17 +122,31 @@ export function listCapacity( | ||
| 122 | 122 | > { |
| 123 | 123 | const who = admin(actor); |
| 124 | 124 | if (!who.ok) return who; |
| 125 | // One read of every stored setting, not three statements a key. | |
| 126 | const stored = new Map( | |
| 127 | app.db | |
| 128 | .query<{ key: string; value: string; updated_at: string; username: string | null }, []>( | |
| 129 | "SELECT s.key, s.value, s.updated_at, u.username FROM forge_setting s LEFT JOIN user u ON u.id = s.updated_by", | |
| 130 | ) | |
| 131 | .all() | |
| 132 | .map((r) => [r.key, r] as const), | |
| 133 | ); | |
| 125 | 134 | return ok({ |
| 126 | settings: CAPACITY_KEYS.map((key) => ({ | |
| 127 | key, | |
| 128 | label: CAPACITY[key].label, | |
| 129 | help: CAPACITY[key].help, | |
| 130 | value: effectiveCapacity(app.db, key), | |
| 131 | source: followsSpeed(key) ? "derived" : storedCapacity(app.db, key) === undefined ? "default" : "setting", | |
| 132 | default: bootDefault(app.db, key), | |
| 133 | env: CAPACITY[key].env, | |
| 134 | ...changedOf(app.db, key), | |
| 135 | })), | |
| 135 | settings: CAPACITY_KEYS.map((key) => { | |
| 136 | const row = stored.get(key); | |
| 137 | const own = row !== undefined && validCapacity(key, row.value) ? row : undefined; | |
| 138 | const fallback = bootDefault(app.db, key); | |
| 139 | return { | |
| 140 | key, | |
| 141 | label: CAPACITY[key].label, | |
| 142 | help: CAPACITY[key].help, | |
| 143 | value: followsSpeed(key) ? effectiveCapacity(app.db, key) : (own?.value ?? fallback), | |
| 144 | source: followsSpeed(key) ? "derived" : own === undefined ? "default" : "setting", | |
| 145 | default: fallback, | |
| 146 | env: CAPACITY[key].env, | |
| 147 | ...(own === undefined || own.value === fallback ? {} : { changed: { at: own.updated_at, by: own.username ?? "someone" } }), | |
| 148 | } satisfies CapacityRow; | |
| 149 | }), | |
| 136 | 150 | changes: capacityChanges(app.db), |
| 137 | 151 | egress: egressHour(app), |
| 138 | 152 | selfSwap: selfSwapState(app.config.selfSwap === true), |
src/boards/ring.ts +23 −10
| @@ -1,9 +1,12 @@ | ||
| 1 | 1 | /** |
| 2 | * The machine's history on disk (`machine_sample`): every 15-s point for a | |
| 3 | * day, and every 5-min point — the mean and the max of the 15-s points in | |
| 2 | * The machine's history on disk (`machine_sample`): every 15-s point for 48 | |
| 3 | * hours, and every 5-min point — the mean and the max of the 15-s points in | |
| 4 | 4 | * it — for 30 days. Each write rolls up the 5-min windows that have closed |
| 5 | 5 | * and drops what has left its window, so the table never grows past |
| 6 | * 24 h / 15 s + 30 d / 5 min = 5,760 + 8,640 rows per target. | |
| 6 | * 48 h / 15 s + 30 d / 5 min = 11,520 + 8,640 rows per target. Past 30 days | |
| 7 | * the nightly retention job thins the 5-min rows to one an hour and drops | |
| 8 | * those after 90 days (`core/retention.ts`, which holds the rule; a caller | |
| 9 | * with the forge's settings passes them as `keep`). | |
| 7 | 10 | */ |
| 8 | 11 | import type { Database } from "bun:sqlite"; |
| 9 | 12 | import { withoutWaiting } from "../kernel/db.ts"; |
| @@ -11,7 +14,7 @@ import { quietly } from "../core/write_clock.ts"; | ||
| 11 | 14 | |
| 12 | 15 | export const FINE_MS = 15_000; |
| 13 | 16 | export const COARSE_MS = 300_000; |
| 14 | export const FINE_KEEP_MS = 24 * 3_600_000; | |
| 17 | export const FINE_KEEP_MS = 48 * 3_600_000; | |
| 15 | 18 | export const COARSE_KEEP_MS = 30 * 24 * 3_600_000; |
| 16 | 19 | |
| 17 | 20 | /** One target at one instant. A null is a series this machine cannot read. */ |
| @@ -24,7 +27,10 @@ export type Point = { | ||
| 24 | 27 | memoryBytes: number | null; |
| 25 | 28 | /** The node's 1-min load average, runnable tasks; null for every other target. */ |
| 26 | 29 | load: number | null; |
| 27 | /** °C, for a CPU or a sensor with a thermometer (`boards/thermal.ts`); absent for every other target. */ | |
| 30 | /** | |
| 31 | * °C, for a CPU or a sensor with a thermometer (`boards/thermal.ts`); absent for every other | |
| 32 | * target. | |
| 33 | */ | |
| 28 | 34 | celsius?: number; |
| 29 | 35 | /** `forge` only: the event loop's p99 lateness over the step, ms (`kernel/loop_lag.ts`). */ |
| 30 | 36 | lagMs?: number; |
| @@ -95,10 +101,17 @@ type FineRow = { | ||
| 95 | 101 | }; |
| 96 | 102 | |
| 97 | 103 | /** |
| 98 | * Keep `points` (taken at `now`), roll up the windows that closed, drop what is past its window. One transaction, | |
| 99 | * never waiting on another process's write lock: behind one it throws at once and the sampler's next tick tries again (#6957). | |
| 104 | * Keep `points` (taken at `now`), roll up the windows that closed, drop what is past its window. | |
| 105 | * One transaction, | |
| 106 | * never waiting on another process's write lock: behind one it throws at once and the sampler's | |
| 107 | * next tick tries again (#6957). | |
| 100 | 108 | */ |
| 101 | export function record(db: Database, points: readonly Point[], now: number): void { | |
| 109 | export function record( | |
| 110 | db: Database, | |
| 111 | points: readonly Point[], | |
| 112 | now: number, | |
| 113 | keep: { fineMs: number; hourlyMs: number } = { fineMs: FINE_KEEP_MS, hourlyMs: COARSE_KEEP_MS }, | |
| 114 | ): void { | |
| 102 | 115 | const put = db.query( |
| 103 | 116 | `INSERT OR REPLACE INTO machine_sample |
| 104 | 117 | (at, step, target, cpu_cores, cpu_cores_max, memory_bytes, memory_bytes_max, load, celsius, celsius_max, |
| @@ -136,7 +149,7 @@ export function record(db: Database, points: readonly Point[], now: number): voi | ||
| 136 | 149 | r.celsius, r.celsiusMax, r.lagMs, r.lagMsMax, r.checks, r.agents, |
| 137 | 150 | ); |
| 138 | 151 | } |
| 139 | db.query("DELETE FROM machine_sample WHERE step = 15 AND at < ?").run(iso(now - FINE_KEEP_MS)); | |
| 140 | db.query("DELETE FROM machine_sample WHERE step = 300 AND at < ?").run(iso(now - COARSE_KEEP_MS)); | |
| 152 | db.query("DELETE FROM machine_sample WHERE step = 15 AND at < ?").run(iso(now - keep.fineMs)); | |
| 153 | db.query("DELETE FROM machine_sample WHERE step = 300 AND at < ?").run(iso(now - keep.hourlyMs)); | |
| 141 | 154 | }))); |
| 142 | 155 | } |
src/boards/sampler.ts +2 −1
| @@ -27,6 +27,7 @@ import { cellCounters, type CellCounter } from "../apps/contain.ts"; | ||
| 27 | 27 | import { startLoopLag, type LoopLag } from "../kernel/loop_lag.ts"; |
| 28 | 28 | import { cpuTarget, readCpus, readPoint, unreadable } from "./machine.ts"; |
| 29 | 29 | import { FINE_MS, record, type Point } from "./ring.ts"; |
| 30 | import { keepOf } from "../core/retention.ts"; | |
| 30 | 31 | import { readHwmon, readTopology, temperatures } from "./thermal.ts"; |
| 31 | 32 | import { during } from "../perf/jobs.ts"; |
| 32 | 33 | |
| @@ -164,7 +165,7 @@ export function startSampler( | ||
| 164 | 165 | const tick = (now = Date.now()) => { |
| 165 | 166 | try { |
| 166 | 167 | const next = readCounters(paths, cells(), now); |
| 167 | record(app.db, pointsOf(prev, next, { lagMs: lag.take(), ...runningChildren(app.db) }), now); | |
| 168 | record(app.db, pointsOf(prev, next, { lagMs: lag.take(), ...runningChildren(app.db) }), now, keepOf(app.db)); | |
| 168 | 169 | prev = next; |
| 169 | 170 | } catch (error) { |
| 170 | 171 | app.log.warn("machine sample failed", { error: String(error) }); |
src/core/capacity.ts +79 −7
| @@ -31,7 +31,14 @@ export type CapacityKey = | ||
| 31 | 31 | | "children.ownFilesystem" |
| 32 | 32 | | "guard_new_accounts" |
| 33 | 33 | | "signin.edge" |
| 34 | | "pace.floor"; | |
| 34 | | "pace.floor" | |
| 35 | | "retention.deploy_pull_days" | |
| 36 | | "retention.event_days" | |
| 37 | | "retention.chatter_days" | |
| 38 | | "retention.sample_fine_hours" | |
| 39 | | "retention.sample_coarse_days" | |
| 40 | | "retention.sample_hourly_days" | |
| 41 | | "size.growth_mb_per_day"; | |
| 35 | 42 | |
| 36 | 43 | interface Definition { |
| 37 | 44 | /** What the settings page and the API call it. */ |
| @@ -160,6 +167,55 @@ export const CAPACITY: Record<CapacityKey, Definition> = { | ||
| 160 | 167 | fallback: "2", |
| 161 | 168 | help: "While the week's pace allows any slots, this many reviews and issues a person assigned may run at once, apart from the crew's own picks, however hard the pace slows them; also the fewest slots a fast burn slows a repository to. At the reserve's wall everything waits. Derived from Speed (half of it, at least 1), read-only; FORGE_PACE_FLOOR is ignored; read on every pump.", |
| 162 | 169 | }, |
| 170 | "retention.deploy_pull_days": { | |
| 171 | label: "Days of deploys that keep their carried pulls", | |
| 172 | env: "", | |
| 173 | kind: { type: "count", min: 7, max: 3650 }, | |
| 174 | fallback: "30", | |
| 175 | help: "deploy_pull is an index over git: a deploy older than this loses its rows in the nightly job and a page that asks for them rebuilds them from git (`core/carried.ts`). The deploy each production app is serving now keeps its rows whatever its age. Read by the retention duty (`core/retention.ts`).", | |
| 176 | }, | |
| 177 | "retention.event_days": { | |
| 178 | label: "Days the outbox keeps an ordinary event", | |
| 179 | env: "", | |
| 180 | kind: { type: "count", min: 30, max: 3650 }, | |
| 181 | fallback: "365", | |
| 182 | help: "Events of the audit kinds (account, token, secret, trust, repo, org, billing, device, team) are never dropped. Any other kind is dropped past this many days. Feeds read the newest events, an audit page reads its own kind, and a replay cursor older than this falls back to comparing ids (`core/events.ts`). Read by the retention duty.", | |
| 183 | }, | |
| 184 | "retention.chatter_days": { | |
| 185 | label: "Days the outbox keeps machine chatter", | |
| 186 | env: "", | |
| 187 | kind: { type: "count", min: 1, max: 365 }, | |
| 188 | fallback: "30", | |
| 189 | help: "Kinds nobody audits or replays beyond a day or two (spend ticks, shard lines, backup progress, refused egress, a child forge's reachability) are dropped past this many days; a webhook's retries end within hours. Read by the retention duty.", | |
| 190 | }, | |
| 191 | "retention.sample_fine_hours": { | |
| 192 | label: "Hours the machine history keeps every 15-second sample", | |
| 193 | env: "", | |
| 194 | kind: { type: "count", min: 1, max: 720 }, | |
| 195 | fallback: "48", | |
| 196 | help: "Past this the machine history keeps one row per 5 minutes (`boards/ring.ts`).", | |
| 197 | }, | |
| 198 | "retention.sample_coarse_days": { | |
| 199 | label: "Days the machine history keeps a row per 5 minutes", | |
| 200 | env: "", | |
| 201 | kind: { type: "count", min: 1, max: 365 }, | |
| 202 | fallback: "30", | |
| 203 | help: "Past this the nightly job thins the history to the one row per hour; a window of them is 12 times thinner than 5 minutes.", | |
| 204 | }, | |
| 205 | "retention.sample_hourly_days": { | |
| 206 | label: "Days the machine history keeps a row per hour", | |
| 207 | env: "", | |
| 208 | kind: { type: "count", min: 30, max: 3650 }, | |
| 209 | fallback: "90", | |
| 210 | help: "Past this the machine history is dropped.", | |
| 211 | }, | |
| 212 | "size.growth_mb_per_day": { | |
| 213 | label: "Database growth that is a need (MB a day)", | |
| 214 | env: "", | |
| 215 | kind: { type: "count", min: 1, max: 1000000 }, | |
| 216 | fallback: "200", | |
| 217 | help: "Vitals names the database when forge.db grows faster than this between two daily readings, or passes 2 GiB, the most Bun maps (`system/db_size.ts`).", | |
| 218 | }, | |
| 163 | 219 | }; |
| 164 | 220 | |
| 165 | 221 | export const CAPACITY_KEYS = Object.keys(CAPACITY) as CapacityKey[]; |
| @@ -206,7 +262,10 @@ function explicitDefault(key: CapacityKey): string | undefined { | ||
| 206 | 262 | |
| 207 | 263 | /** Most shards a check takes by default: past four, a test run waits on git, not CPU. */ |
| 208 | 264 | const SHARDS_DEFAULT_MAX = 4; |
| 209 | /** CPUs a shard is given by default: its bun test, the git children it starts, and the forge it boots. */ | |
| 265 | /** | |
| 266 | * CPUs a shard is given by default: its bun test, the git children it starts, and the forge it | |
| 267 | * boots. | |
| 268 | */ | |
| 210 | 269 | const CPUS_PER_SHARD = 3; |
| 211 | 270 | |
| 212 | 271 | /** Shards per check by default: `min(4, cpus)`, at least one. 80 CPUs give 4; 2 give 2. */ |
| @@ -391,7 +450,10 @@ export function followsSpeed(key: CapacityKey): key is SpeedDerivedKey { | ||
| 391 | 450 | return key === "pace.floor" || key === "queue.depth"; |
| 392 | 451 | } |
| 393 | 452 | |
| 394 | /** What Speed implies for a dial that follows it: half of Speed, at least 1 for the floor; half rounded up, 1 to 4, for the depth. */ | |
| 453 | /** | |
| 454 | * What Speed implies for a dial that follows it: half of Speed, at least 1 for the floor; half | |
| 455 | * rounded up, 1 to 4, for the depth. | |
| 456 | */ | |
| 395 | 457 | export function derivedFromSpeed(db: Database, key: SpeedDerivedKey): number { |
| 396 | 458 | const speed = Number(capacityValue(db, "crew.concurrency")); |
| 397 | 459 | if (key === "pace.floor") return Math.max(1, Math.floor(speed / 2)); |
| @@ -452,18 +514,26 @@ const MODEL_HOSTS: Readonly<Record<string, readonly string[]>> = { | ||
| 452 | 514 | both: ["openrouter.ai:443", "api.anthropic.com:443"], |
| 453 | 515 | }; |
| 454 | 516 | |
| 455 | /** Whether a child forge must have a filesystem of its own to start (`children.ownFilesystem`); off by default. */ | |
| 517 | /** | |
| 518 | * Whether a child forge must have a filesystem of its own to start (`children.ownFilesystem`); off | |
| 519 | * by default. | |
| 520 | */ | |
| 456 | 521 | export function childNeedsOwnFilesystem(db: Database): boolean { |
| 457 | 522 | return capacityValue(db, "children.ownFilesystem") === "on"; |
| 458 | 523 | } |
| 459 | 524 | |
| 460 | /** The package registry a child forge cell may reach (`children.registryEgress`); none by default. */ | |
| 525 | /** | |
| 526 | * The package registry a child forge cell may reach (`children.registryEgress`); none by default. | |
| 527 | */ | |
| 461 | 528 | export function childRegistryHosts(db: Database): readonly string[] { |
| 462 | 529 | const value = capacityValue(db, "children.registryEgress"); |
| 463 | 530 | return value === "build" ? BUILD_HOSTS : value === "npm" ? ["registry.npmjs.org:443"] : []; |
| 464 | 531 | } |
| 465 | 532 | |
| 466 | /** The payment provider hosts a child forge cell may reach (`children.paymentEgress`); the cell's ceiling, each app still declares its own. */ | |
| 533 | /** | |
| 534 | * The payment provider hosts a child forge cell may reach (`children.paymentEgress`); the cell's | |
| 535 | * ceiling, each app still declares its own. | |
| 536 | */ | |
| 467 | 537 | export function childPaymentHosts(db: Database): readonly string[] { |
| 468 | 538 | return capacityValue(db, "children.paymentEgress") === "stripe" ? PAYMENT_HOSTS : []; |
| 469 | 539 | } |
| @@ -534,7 +604,9 @@ export function setCapacity( | ||
| 534 | 604 | key: CapacityKey, |
| 535 | 605 | value: string | null, |
| 536 | 606 | actorId: string, |
| 537 | /** Why, in the admin's words, already cut to REASON_MAX by the action; kept beside who (#10778). */ | |
| 607 | /** | |
| 608 | * Why, in the admin's words, already cut to REASON_MAX by the action; kept beside who (#10778). | |
| 609 | */ | |
| 538 | 610 | reason = "", |
| 539 | 611 | ): { from: string; to: string } { |
| 540 | 612 | const from = capacityValue(db, key); |
src/core/carried.ts +37
| @@ -145,3 +145,40 @@ export function carriedByRuns( | ||
| 145 | 145 | export function carriesText(numbers: readonly number[]): string { |
| 146 | 146 | return numbers.length === 0 ? "" : `carries ${numbers.map((n) => `#${n}`).join(" ")}`; |
| 147 | 147 | } |
| 148 | ||
| 149 | /** | |
| 150 | * Deploys found to carry nothing when rebuilt, so a page asking again does not walk git again; | |
| 151 | * bounded, gone on restart. | |
| 152 | */ | |
| 153 | const rebuiltEmpty = new Set<string>(); | |
| 154 | const REBUILT_EMPTY_MAX = 1000; | |
| 155 | ||
| 156 | /** | |
| 157 | * The pull numbers a deploy run carries, rebuilt from git when its rows are gone (the | |
| 158 | * nightly retention job drops a deploy's rows after `retention.deploy_pull_days`, | |
| 159 | * `core/retention.ts`): the table is an index over git, so a page that asks for an old | |
| 160 | * deploy's pulls gets the same answer, one `git rev-list` later. Only a finished production | |
| 161 | * deploy has any; any other run answers at once from the table. | |
| 162 | */ | |
| 163 | export async function carriedOrRebuild( | |
| 164 | db: Database, | |
| 165 | reposRoot: string, | |
| 166 | run: { id: string; repoId: string; kind: string; env: string; state: string; commitOid: string }, | |
| 167 | ): Promise<number[]> { | |
| 168 | const kept = carriedBy(db, run.id); | |
| 169 | if (kept.length > 0 || run.kind !== "deploy" || run.env !== "production" || run.state !== "ok") return kept; | |
| 170 | if (rebuiltEmpty.has(run.id)) return kept; | |
| 171 | const repo = getRepoById(db, run.repoId); | |
| 172 | if (repo === undefined) return kept; | |
| 173 | const rebuilt = await recordCarried(db, { | |
| 174 | runId: run.id, | |
| 175 | repoId: run.repoId, | |
| 176 | commitOid: run.commitOid, | |
| 177 | dir: repoDir(reposRoot, repo.ownerName, repo.name), | |
| 178 | }); | |
| 179 | if (rebuilt.length === 0) { | |
| 180 | if (rebuiltEmpty.size >= REBUILT_EMPTY_MAX) rebuiltEmpty.clear(); | |
| 181 | rebuiltEmpty.add(run.id); | |
| 182 | } | |
| 183 | return rebuilt; | |
| 184 | } |
src/core/migration-pins/20261114000000-database-keeps-what-it-needs.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 4032c54a4f60a4da1ccf606cd31920470701bdbed33fcee32affb0d57333838e |
src/core/migrations/20261114000000-database-keeps-what-it-needs.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | // The database keeps what it needs (#11973): where the nightly retention job left off | |
| 2 | // (`retention_cursor`, so each tick resumes in a small batch and never rescans what it | |
| 3 | // passed), one row a day of what the file weighed (`db_size_day`, so /system can say how | |
| 4 | // fast it grows), and the index the cascade from `event` to `webhook_delivery` needs: | |
| 5 | // without it each event deleted scanned every delivery. Additive. | |
| 6 | export default ` | |
| 7 | CREATE TABLE IF NOT EXISTS retention_cursor ( | |
| 8 | name TEXT PRIMARY KEY, | |
| 9 | value TEXT NOT NULL, | |
| 10 | updated_at TEXT NOT NULL | |
| 11 | ); | |
| 12 | CREATE TABLE IF NOT EXISTS db_size_day ( | |
| 13 | day TEXT PRIMARY KEY, | |
| 14 | file_bytes INTEGER NOT NULL, | |
| 15 | free_bytes INTEGER NOT NULL, | |
| 16 | top TEXT NOT NULL | |
| 17 | ); | |
| 18 | CREATE INDEX IF NOT EXISTS webhook_delivery_event ON webhook_delivery(event_id); | |
| 19 | `; |
src/core/retention.ts added +336
| @@ -0,0 +1,336 @@ | ||
| 1 | /** | |
| 2 | * What the database keeps, stated once (#11973). Three tables are | |
| 3 | * bookkeeping, not anyone's work, and each has one rule here, run by the | |
| 4 | * `retention` duty (`maintain/duties/retention.ts`) in small batches: | |
| 5 | * | |
| 6 | * - `deploy_pull` is an index over git (`core/carried.ts`): rows of a deploy | |
| 7 | * older than `retention.deploy_pull_days`, of a run that is gone, and of | |
| 8 | * no live app are dropped; a page that asks for a dropped deploy's pulls | |
| 9 | * rebuilds them from git (`carriedOrRebuild`). The deploy a production app | |
| 10 | * serves now keeps its rows whatever its age. | |
| 11 | * - `event` is the outbox. Audit kinds are never dropped; machine chatter | |
| 12 | * goes past `retention.chatter_days`; every other kind past | |
| 13 | * `retention.event_days`. Who reads what age: a feed reads the newest | |
| 14 | * events, an audit page (`web/pages/security.ts`) the kind it names, a | |
| 15 | * webhook retries for hours, a replay cursor older than the rule falls | |
| 16 | * back to comparing ids (`core/events.ts`). | |
| 17 | * - `machine_sample`: every 15-s sample for `retention.sample_fine_hours`, | |
| 18 | * a row per 5 minutes for `retention.sample_coarse_days`, then the one | |
| 19 | * row at the top of each hour for `retention.sample_hourly_days`. | |
| 20 | * | |
| 21 | * A batch deletes in transactions of at most `CHUNK` rows and starts no | |
| 22 | * chunk after its deadline, so no write lock is held for long. Where each | |
| 23 | * walk left off is `retention_cursor`; a finished walk starts again at the | |
| 24 | * next run, so what became old since is found. | |
| 25 | */ | |
| 26 | ||
| 27 | import type { Database } from "bun:sqlite"; | |
| 28 | import { capacityCount, type CapacityKey } from "./capacity.ts"; | |
| 29 | ||
| 30 | /** Rows one transaction deletes at most. */ | |
| 31 | export const CHUNK = 500; | |
| 32 | /** Rows one batch deletes at most; the rest waits for the next tick. */ | |
| 33 | export const BATCH_ROWS = 20_000; | |
| 34 | /** Milliseconds after which a batch starts no new chunk. */ | |
| 35 | export const BATCH_MS = 40; | |
| 36 | ||
| 37 | const DAY = 86_400_000; | |
| 38 | ||
| 39 | export interface Rules { | |
| 40 | readonly deployPullDays: number; | |
| 41 | readonly eventDays: number; | |
| 42 | readonly chatterDays: number; | |
| 43 | readonly sampleFineHours: number; | |
| 44 | readonly sampleCoarseDays: number; | |
| 45 | readonly sampleHourlyDays: number; | |
| 46 | } | |
| 47 | ||
| 48 | /** | |
| 49 | * The defaults, in one place: `core/capacity.ts` holds the same numbers as the settings' fallbacks. | |
| 50 | */ | |
| 51 | export const DEFAULTS: Rules = { | |
| 52 | deployPullDays: 30, | |
| 53 | eventDays: 365, | |
| 54 | chatterDays: 30, | |
| 55 | sampleFineHours: 48, | |
| 56 | sampleCoarseDays: 30, | |
| 57 | sampleHourlyDays: 90, | |
| 58 | }; | |
| 59 | ||
| 60 | const KEYS: Record<keyof Rules, CapacityKey> = { | |
| 61 | deployPullDays: "retention.deploy_pull_days", | |
| 62 | eventDays: "retention.event_days", | |
| 63 | chatterDays: "retention.chatter_days", | |
| 64 | sampleFineHours: "retention.sample_fine_hours", | |
| 65 | sampleCoarseDays: "retention.sample_coarse_days", | |
| 66 | sampleHourlyDays: "retention.sample_hourly_days", | |
| 67 | }; | |
| 68 | ||
| 69 | /** The rules in force: an admin's setting, else the default. Read on every batch. */ | |
| 70 | export function rules(db: Database): Rules { | |
| 71 | const out = { ...DEFAULTS }; | |
| 72 | for (const name of Object.keys(KEYS) as (keyof Rules)[]) out[name] = capacityCount(db, KEYS[name], DEFAULTS[name]); | |
| 73 | return out; | |
| 74 | } | |
| 75 | ||
| 76 | /** | |
| 77 | * Kinds of the audit trail: who did what to an account, a credential, a repository, money. Never | |
| 78 | * dropped. | |
| 79 | */ | |
| 80 | export const AUDIT_PREFIXES: readonly string[] = [ | |
| 81 | "account.", "user.", "token.", "secret.", "trust.", "repo.", "org.", "billing.", "device.", "team.", "invite.", "crew.", "origin.", | |
| 82 | ]; | |
| 83 | ||
| 84 | /** Kinds that are machine output, read for minutes or days and nothing after. */ | |
| 85 | export const CHATTER_KINDS: readonly string[] = [ | |
| 86 | "usage.delta", "run.shard", "run.started", "run.finished", "backup.progress", "backup.started", | |
| 87 | "app.egress.refused", "app.egress.ignored", "forge.child_unreachable", "forge.child_reachable", | |
| 88 | ]; | |
| 89 | ||
| 90 | export type Fate = "audit" | "chatter" | "ordinary"; | |
| 91 | ||
| 92 | export function eventFate(kind: string): Fate { | |
| 93 | if (CHATTER_KINDS.includes(kind)) return "chatter"; | |
| 94 | return AUDIT_PREFIXES.some((p) => kind.startsWith(p)) ? "audit" : "ordinary"; | |
| 95 | } | |
| 96 | ||
| 97 | /** Whether an event of `kind` written at `createdAt` (ISO) is past its rule at `now`. */ | |
| 98 | export function eventExpired(kind: string, createdAt: string, now: number, r: Rules): boolean { | |
| 99 | const fate = eventFate(kind); | |
| 100 | if (fate === "audit") return false; | |
| 101 | const days = fate === "chatter" ? r.chatterDays : r.eventDays; | |
| 102 | return createdAt < new Date(now - days * DAY).toISOString(); | |
| 103 | } | |
| 104 | ||
| 105 | /** | |
| 106 | * What a batch did: rows removed, and whether the walk reached its end (the next run starts over). | |
| 107 | */ | |
| 108 | export interface BatchResult { | |
| 109 | readonly deleted: number; | |
| 110 | readonly finished: boolean; | |
| 111 | } | |
| 112 | ||
| 113 | /** One batch's allowance: a clock and the rows left. */ | |
| 114 | export interface Allowance { | |
| 115 | readonly deadline: number; | |
| 116 | rows: number; | |
| 117 | } | |
| 118 | ||
| 119 | export const allowance = (now = performance.now(), ms = BATCH_MS, rows = BATCH_ROWS): Allowance => ({ deadline: now + ms, rows }); | |
| 120 | const spent = (a: Allowance): boolean => a.rows <= 0 || performance.now() >= a.deadline; | |
| 121 | ||
| 122 | function cursor(db: Database, name: string): string { | |
| 123 | return db.query<{ value: string }, [string]>("SELECT value FROM retention_cursor WHERE name = ?1").get(name)?.value ?? ""; | |
| 124 | } | |
| 125 | ||
| 126 | function setCursor(db: Database, name: string, value: string): void { | |
| 127 | db.query( | |
| 128 | `INSERT INTO retention_cursor (name, value, updated_at) VALUES (?1, ?2, ?3) | |
| 129 | ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`, | |
| 130 | ).run(name, value, new Date().toISOString()); | |
| 131 | } | |
| 132 | ||
| 133 | /** | |
| 134 | * Whether a deploy's rows are still wanted: its run exists, is recent, or is what a production app | |
| 135 | * serves now. | |
| 136 | */ | |
| 137 | function deployWanted(db: Database, runId: string, cutoff: string): boolean { | |
| 138 | const run = db | |
| 139 | .query<{ repoId: string; env: string; kind: string; at: string; serving: string | null }, [string]>( | |
| 140 | `SELECT repo_id AS repoId, env, kind, serving_at AS serving, | |
| 141 | COALESCE(serving_at, finished_at, created_at) AS at FROM run WHERE id = ?1`, | |
| 142 | ) | |
| 143 | .get(runId); | |
| 144 | if (run === null) return false; | |
| 145 | if (run.at >= cutoff) return true; | |
| 146 | if (run.kind !== "deploy" || run.env !== "production" || run.serving === null) return false; | |
| 147 | // The deploy an app serves now is the newest production deploy that served. | |
| 148 | return ( | |
| 149 | db | |
| 150 | .query( | |
| 151 | `SELECT 1 FROM run WHERE repo_id = ?1 AND kind = 'deploy' AND env = 'production' | |
| 152 | AND serving_at IS NOT NULL AND serving_at > ?2 LIMIT 1`, | |
| 153 | ) | |
| 154 | .get(run.repoId, run.serving) === null | |
| 155 | ); | |
| 156 | } | |
| 157 | ||
| 158 | /** | |
| 159 | * Drop the rows of deploys no longer wanted, walking `deploy_pull` by run id from where the last | |
| 160 | * batch stopped. | |
| 161 | */ | |
| 162 | export function pruneDeployPulls(db: Database, now: number, a: Allowance, r: Rules = rules(db)): BatchResult { | |
| 163 | const cutoff = new Date(now - r.deployPullDays * DAY).toISOString(); | |
| 164 | const name = "deploy_pull"; | |
| 165 | let at = cursor(db, name); | |
| 166 | let deleted = 0; | |
| 167 | while (!spent(a)) { | |
| 168 | const ids = db | |
| 169 | .query<{ run_id: string }, [string]>("SELECT DISTINCT run_id FROM deploy_pull WHERE run_id > ?1 ORDER BY run_id LIMIT 25") | |
| 170 | .all(at) | |
| 171 | .map((x) => x.run_id); | |
| 172 | if (ids.length === 0) { | |
| 173 | setCursor(db, name, ""); | |
| 174 | return { deleted, finished: true }; | |
| 175 | } | |
| 176 | for (const id of ids) { | |
| 177 | if (!deployWanted(db, id, cutoff)) { | |
| 178 | // One run's rows can be many: chunk them, and keep the cursor behind the run until it is | |
| 179 | // clear. | |
| 180 | for (;;) { | |
| 181 | const n = db | |
| 182 | .query("DELETE FROM deploy_pull WHERE rowid IN (SELECT rowid FROM deploy_pull WHERE run_id = ?1 LIMIT ?2)") | |
| 183 | .run(id, CHUNK).changes; | |
| 184 | deleted += n; | |
| 185 | a.rows -= n; | |
| 186 | if (n < CHUNK) break; | |
| 187 | if (spent(a)) { | |
| 188 | setCursor(db, name, at); | |
| 189 | return { deleted, finished: false }; | |
| 190 | } | |
| 191 | } | |
| 192 | } | |
| 193 | at = id; | |
| 194 | if (spent(a)) break; | |
| 195 | } | |
| 196 | setCursor(db, name, at); | |
| 197 | } | |
| 198 | return { deleted, finished: false }; | |
| 199 | } | |
| 200 | ||
| 201 | /** | |
| 202 | * Drop the events past their rule. Two walks, neither of which re-reads what it kept: | |
| 203 | * chatter, kind by kind in `event_kind_seq` order, oldest first, ends at the first one | |
| 204 | * young enough; every other kind, by `seq` from where the last batch stopped, ends at the | |
| 205 | * first event younger than `retention.event_days`. What the second walk passes is deleted | |
| 206 | * or an audit kind, and neither ever needs reading again, so its cursor never goes back. | |
| 207 | */ | |
| 208 | export function pruneEvents(db: Database, now: number, a: Allowance, r: Rules = rules(db)): BatchResult { | |
| 209 | let deleted = 0; | |
| 210 | const drop = db.query("DELETE FROM event WHERE id = ?1"); | |
| 211 | const take = (ids: readonly string[]): void => { | |
| 212 | if (ids.length === 0) return; | |
| 213 | db.transaction(() => { | |
| 214 | for (const id of ids) drop.run(id); | |
| 215 | })(); | |
| 216 | deleted += ids.length; | |
| 217 | a.rows -= ids.length; | |
| 218 | }; | |
| 219 | const chatterCut = iso(now - r.chatterDays * DAY); | |
| 220 | let finished = true; | |
| 221 | for (const kind of CHATTER_KINDS) { | |
| 222 | while (!spent(a)) { | |
| 223 | const rows = db | |
| 224 | .query<{ id: string; created_at: string }, [string, number]>( | |
| 225 | "SELECT id, created_at FROM event WHERE kind = ?1 ORDER BY seq LIMIT ?2", | |
| 226 | ) | |
| 227 | .all(kind, CHUNK); | |
| 228 | const old = rows.filter((x) => x.created_at < chatterCut).map((x) => x.id); | |
| 229 | take(old); | |
| 230 | if (old.length < CHUNK) break; | |
| 231 | } | |
| 232 | if (spent(a)) finished = false; | |
| 233 | } | |
| 234 | const name = "event"; | |
| 235 | let at = Number(cursor(db, name) || "0"); | |
| 236 | const eventCut = iso(now - r.eventDays * DAY); | |
| 237 | while (!spent(a)) { | |
| 238 | const rows = db | |
| 239 | .query<{ seq: number; id: string; kind: string; created_at: string }, [number, number]>( | |
| 240 | "SELECT seq, id, kind, created_at FROM event WHERE seq > ?1 ORDER BY seq LIMIT ?2", | |
| 241 | ) | |
| 242 | .all(at, CHUNK); | |
| 243 | const doomed: string[] = []; | |
| 244 | let young = rows.length < CHUNK; | |
| 245 | for (const row of rows) { | |
| 246 | if (row.created_at >= eventCut) { | |
| 247 | young = true; | |
| 248 | break; | |
| 249 | } | |
| 250 | at = row.seq; | |
| 251 | if (eventExpired(row.kind, row.created_at, now, r)) doomed.push(row.id); | |
| 252 | } | |
| 253 | take(doomed); | |
| 254 | setCursor(db, name, String(at)); | |
| 255 | if (young) return { deleted, finished }; | |
| 256 | } | |
| 257 | return { deleted, finished: false }; | |
| 258 | } | |
| 259 | ||
| 260 | const iso = (ms: number): string => new Date(ms).toISOString(); | |
| 261 | const SLICE_MS = 6 * 3_600_000; | |
| 262 | ||
| 263 | /** | |
| 264 | * Thin the 5-minute rows older than the coarse window to the one at the top of each hour, six hours | |
| 265 | * at a time. | |
| 266 | */ | |
| 267 | export function thinSamples(db: Database, now: number, a: Allowance, r: Rules = rules(db)): BatchResult { | |
| 268 | const name = "machine_sample"; | |
| 269 | const upto = iso(now - r.sampleCoarseDays * DAY); | |
| 270 | let at = cursor(db, name); | |
| 271 | if (at === "") at = db.query<{ at: string | null }, []>("SELECT MIN(at) AS at FROM machine_sample WHERE step = 300").get()?.at ?? upto; | |
| 272 | let deleted = 0; | |
| 273 | while (!spent(a)) { | |
| 274 | if (at >= upto) { | |
| 275 | setCursor(db, name, ""); | |
| 276 | return { deleted, finished: true }; | |
| 277 | } | |
| 278 | const end = iso(Math.min(Date.parse(at) + SLICE_MS, Date.parse(upto))); | |
| 279 | // Minutes 15 and 16 of `YYYY-MM-DDTHH:MM`: the row at minute 00 is the hour's one. | |
| 280 | const n = db | |
| 281 | .query("DELETE FROM machine_sample WHERE step = 300 AND at >= ?1 AND at < ?2 AND substr(at, 15, 2) != '00'") | |
| 282 | .run(at, end).changes; | |
| 283 | deleted += n; | |
| 284 | a.rows -= n; | |
| 285 | at = end; | |
| 286 | setCursor(db, name, at); | |
| 287 | } | |
| 288 | return { deleted, finished: false }; | |
| 289 | } | |
| 290 | ||
| 291 | /** Pages one `incremental_vacuum` step gives back: about 800 KiB at the default page size. */ | |
| 292 | const VACUUM_PAGES = 200; | |
| 293 | ||
| 294 | /** | |
| 295 | * Give freed pages back to the file, a step at a time. A blocking `VACUUM` rewrites the whole | |
| 296 | * file under one write lock (minutes at 4.5 GB), so it is never run on the live handle; where the | |
| 297 | * file was made with `auto_vacuum = INCREMENTAL` (every new database is, `kernel/db.ts`) each | |
| 298 | * step here holds the lock for the pages it frees. A file made before that is `none` and | |
| 299 | * is converted once, offline, by `VACUUM INTO` a new file at a release hand-over | |
| 300 | * (docs/features/retention.md); until then this does nothing and /system says why. | |
| 301 | */ | |
| 302 | export function giveBack(db: Database, a: Allowance): { pages: number; mode: "none" | "full" | "incremental" } { | |
| 303 | const mode = db.query<{ auto_vacuum: number }, []>("PRAGMA auto_vacuum").get()?.auto_vacuum ?? 0; | |
| 304 | if (mode !== 2) return { pages: 0, mode: mode === 1 ? "full" : "none" }; | |
| 305 | let pages = 0; | |
| 306 | while (!spent(a)) { | |
| 307 | const free = db.query<{ freelist_count: number }, []>("PRAGMA freelist_count").get()?.freelist_count ?? 0; | |
| 308 | if (free === 0) break; | |
| 309 | db.exec(`PRAGMA incremental_vacuum(${VACUUM_PAGES})`); | |
| 310 | const n = Math.min(free, VACUUM_PAGES); | |
| 311 | pages += n; | |
| 312 | a.rows -= n; | |
| 313 | } | |
| 314 | return { pages, mode: "incremental" }; | |
| 315 | } | |
| 316 | ||
| 317 | /** | |
| 318 | * Whether a walk finished today (UTC) already; a walk that reads every row of a table runs once a | |
| 319 | * day. | |
| 320 | */ | |
| 321 | export function passedToday(db: Database, name: string, now: number): boolean { | |
| 322 | return cursor(db, `${name}.done`) === iso(now).slice(0, 10); | |
| 323 | } | |
| 324 | ||
| 325 | export function notePassed(db: Database, name: string, now: number): void { | |
| 326 | setCursor(db, `${name}.done`, iso(now).slice(0, 10)); | |
| 327 | } | |
| 328 | ||
| 329 | /** | |
| 330 | * What the sampler's write keeps (`boards/ring.ts` `record`): the raw window and the last of the | |
| 331 | * hourly rows. | |
| 332 | */ | |
| 333 | export function keepOf(db: Database): { fineMs: number; hourlyMs: number } { | |
| 334 | const r = rules(db); | |
| 335 | return { fineMs: r.sampleFineHours * 3_600_000, hourlyMs: r.sampleHourlyDays * DAY }; | |
| 336 | } |
src/http/api.ts +19 −13
| @@ -289,7 +289,7 @@ import { readReturns, reportSpend, RETURNS_DAYS } from "../actions/returns.ts"; | ||
| 289 | 289 | import { COLUMNS, readSort, sortRows } from "../fleet/columns.ts"; |
| 290 | 290 | import { viewFleet } from "../fleet/rows.ts"; |
| 291 | 291 | import { fleetSelection, readFleetGraph } from "../actions/fleet-graph.ts"; |
| 292 | import { carriedBy } from "../core/carried.ts"; | |
| 292 | import { carriedOrRebuild } from "../core/carried.ts"; | |
| 293 | 293 | import { readGateLog } from "../checks/gate_log.ts"; |
| 294 | 294 | import { recentGates } from "../checks/gate_result.ts"; |
| 295 | 295 | import { readRunLog, subscribeRunLog } from "../runs/log.ts"; |
| @@ -797,7 +797,9 @@ function editFailure(error: { kind: string } & Record<string, unknown>) { | ||
| 797 | 797 | const ANCHOR_FORMAT = |
| 798 | 798 | 'An anchor is {"path": a file in the pull\'s diff, "line": its line number, "side": "new" (the head\'s numbering, for added or kept lines) or "old" (the base\'s, for removed lines)}; the line must be inside one of the diff\'s hunks: in `@@ -a,b +c,d @@` the hunk\'s first line is c on the new side and a on the old. GET …/pulls/N returns the diff.'; |
| 799 | 799 | |
| 800 | /** A review's line comments as the API was sent them; undefined when they are not a list of objects. */ | |
| 800 | /** | |
| 801 | * A review's line comments as the API was sent them; undefined when they are not a list of objects. | |
| 802 | */ | |
| 801 | 803 | function reviewLines(raw: unknown): ReviewInput[] | undefined { |
| 802 | 804 | if (raw === undefined || raw === null) return []; |
| 803 | 805 | // The cap is `submitReview`'s to refuse, by name (`too_many_lines`). |
| @@ -1916,7 +1918,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1916 | 1918 | const from = at + 1; |
| 1917 | 1919 | const items = all.slice(from, from + limit); |
| 1918 | 1920 | const more = from + limit < all.length; |
| 1919 | // The tag is of the exact bytes sent: a pushed, moved or deleted tag changes them, and so does the page. | |
| 1921 | // The tag is of the exact bytes sent: a pushed, moved or deleted tag changes them, and so | |
| 1922 | // does the page. | |
| 1920 | 1923 | const text = JSON.stringify({ items, next_cursor: more ? items[items.length - 1]!.name : null }); |
| 1921 | 1924 | const etag = weakEtag(text); |
| 1922 | 1925 | const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" }; |
| @@ -2364,7 +2367,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2364 | 2367 | }, |
| 2365 | 2368 | ); |
| 2366 | 2369 | // One action on a whole limb (#733): defer, resume, or close as not |
| 2367 | // doing, or raise or lower it among its siblings (#1064). A fleet operation in every respect — a dry run by default with a | |
| 2370 | // doing, or raise or lower it among its siblings (#1064). A fleet operation in every respect — a | |
| 2371 | // dry run by default with a | |
| 2368 | 2372 | // read credential, an admin token to apply, the receipt in |
| 2369 | 2373 | // /api/v1/fleet/ops/:id and its undo at …/undo. |
| 2370 | 2374 | router.add( |
| @@ -2498,7 +2502,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2498 | 2502 | }); |
| 2499 | 2503 | }); |
| 2500 | 2504 | // What people asked of the crew in the repositories the caller can write — |
| 2501 | // by default what has nothing merged yet, oldest first — and what became of each (core/asked.ts, the /asked page). | |
| 2505 | // by default what has nothing merged yet, oldest first — and what became of each (core/asked.ts, | |
| 2506 | // the /asked page). | |
| 2502 | 2507 | router.add("GET", "/api/v1/asked", (ctx) => { |
| 2503 | 2508 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 2504 | 2509 | const denied = requireScope(ctx, "ro"); |
| @@ -2617,7 +2622,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2617 | 2622 | ...(states[i] ?? {}), |
| 2618 | 2623 | })); |
| 2619 | 2624 | }); |
| 2620 | // The tag is of the exact bytes sent, so a new verdict, head or state is never hidden behind a 304; | |
| 2625 | // The tag is of the exact bytes sent, so a new verdict, head or state is never hidden behind a | |
| 2626 | // 304; | |
| 2621 | 2627 | // the page, state, limit, cursor and fields are in the body or the query that chose it. |
| 2622 | 2628 | return timePhase(ctx.request, "render", () => { |
| 2623 | 2629 | const text = JSON.stringify(paged(items, query.limit, (p) => p.number)); |
| @@ -2775,7 +2781,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2775 | 2781 | ...(diff === undefined ? {} : { diff }), |
| 2776 | 2782 | hold: hold === undefined ? null : holdJson(hold), |
| 2777 | 2783 | }); |
| 2778 | // Tagged by the exact bytes sent, after access was checked: a new head, verdict, review or merge is never hidden behind a 304. | |
| 2784 | // Tagged by the exact bytes sent, after access was checked: a new head, verdict, review or | |
| 2785 | // merge is never hidden behind a 304. | |
| 2779 | 2786 | const etag = weakEtag(text); |
| 2780 | 2787 | const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" }; |
| 2781 | 2788 | if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers }); |
| @@ -4049,15 +4056,14 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 4049 | 4056 | return timePhase(ctx.request, "render", () => json(paged(runs, limit, (r) => r.id), 200, headers)); |
| 4050 | 4057 | }); |
| 4051 | 4058 | |
| 4052 | router.add("GET", "/api/v1/repos/:owner/:name/runs/:id", (ctx) => { | |
| 4059 | router.add("GET", "/api/v1/repos/:owner/:name/runs/:id", async (ctx) => { | |
| 4053 | 4060 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 4054 | 4061 | const repo = loadRepo(ctx); |
| 4055 | 4062 | if (!repo) return notFound(); |
| 4056 | const found = timePhase(ctx.request, "run", () => { | |
| 4057 | const run = getRepoRun(ctx.app, ctx.auth.user, repo, ctx.params.id ?? ""); | |
| 4058 | // The merged pulls a finished production deploy carries (`core/carried.ts`). | |
| 4059 | return run.ok ? { ...run.value, carries: carriedBy(ctx.app.db, run.value.id) } : null; | |
| 4060 | }); | |
| 4063 | const read = timePhase(ctx.request, "run", () => getRepoRun(ctx.app, ctx.auth.user, repo, ctx.params.id ?? "")); | |
| 4064 | // The merged pulls a finished production deploy carries (`core/carried.ts`), rebuilt from git | |
| 4065 | // when retention dropped them. | |
| 4066 | const found = read.ok ? { ...read.value, carries: await carriedOrRebuild(ctx.app.db, ctx.app.reposRoot, read.value) } : null; | |
| 4061 | 4067 | if (!found) return notFound(); |
| 4062 | 4068 | return timePhase(ctx.request, "render", () => json(found)); |
| 4063 | 4069 | }); |
src/http/mcp/tools/system.ts +3 −2
| @@ -9,12 +9,13 @@ import { LAG_BAR_MS, overBar } from "../../../perf/lag_minutes.ts"; | ||
| 9 | 9 | import { slowestRoutes } from "../../../perf/watch.ts"; |
| 10 | 10 | import { footing, riskLines } from "../../../system/footing.ts"; |
| 11 | 11 | import { laneWords, readOffsiteLane } from "../../../snapshot/offsite_lane.ts"; |
| 12 | import { dbFacts } from "../../../system/db_size.ts"; | |
| 12 | 13 | import { largestDirs } from "../../../system/largest_dirs.ts"; |
| 13 | 14 | import { good, bad, type Tool } from "../shared.ts"; |
| 14 | 15 | |
| 15 | 16 | export const tool: Tool = { |
| 16 | 17 | 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, `largestDirs`: the five largest directories under the forge's data as {at, dirs: [{name, bytes}]} (null while first measured; at most once a minute), `database`: the forge's own size, {size: {at, fileBytes, freeBytes, autoVacuum, tables: [{name, rows, bytes}], indexes: [{name, table, rows, bytes}], tableCount, indexCount} | null, growthBytesPerDay, mmapCapBytes, fileBytes}: the ten heaviest tables and indexes, estimated (#11973), `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 | 19 | description: |
| 19 | 20 | "The forge machine now: CPU, memory, disk, network. Admin or telemetry:read; `kind: csp`: 24 h of CSP violations (admin).", |
| 20 | 21 | inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["csp", "routes", "footing", "offsite"] } } }, |
| @@ -56,6 +57,6 @@ export const tool: Tool = { | ||
| 56 | 57 | const readings = rows.map((r) => ({ at: new Date(r.at).toISOString(), ms: Math.round(r.ms * 10) / 10, what: r.what })); |
| 57 | 58 | // At most 0.8 s on the walk (#11800); the last measurement, or null, when it is slower. |
| 58 | 59 | 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, database: dbFacts(ctx.app.db, ctx.app.config.dataDir), stalls, barMs: LAG_BAR_MS, over: overBar(rows), readings }); | |
| 60 | 61 | }, |
| 61 | 62 | }; |
src/kernel/db.ts +3
| @@ -74,6 +74,9 @@ export function openDb(path: string, migrations: readonly Migration[]): Database | ||
| 74 | 74 | } else { |
| 75 | 75 | if (image !== undefined) writeFileSync(path, image, { flag: "wx", mode: 0o600 }); |
| 76 | 76 | db = new Database(path, { create: true, strict: true }); |
| 77 | // A file made now gives freed pages back a step at a time (`core/retention.ts` `giveBack`); | |
| 78 | // the setting only takes hold before the first table, so it is said first. | |
| 79 | if (fresh) db.exec("PRAGMA auto_vacuum = INCREMENTAL"); | |
| 77 | 80 | } |
| 78 | 81 | applyPragmas(db, memory ? CACHE_KIB : mainCacheKiB()); |
| 79 | 82 | // Only files this call made: one that already exists is tightened below if |
src/kernel/vitals.ts +25 −7
| @@ -28,6 +28,7 @@ import { STALE_AFTER_MS } from "../runs/lease.ts"; | ||
| 28 | 28 | import { ownRepoPath } from "./own_repo.ts"; |
| 29 | 29 | import { BUDGETS } from "./budgets.ts"; |
| 30 | 30 | import { openDbFiles } from "./file_modes.ts"; |
| 31 | import { sizeNeed } from "../system/db_size.ts"; | |
| 31 | 32 | import { backupVerdict, isWatched } from "../snapshot/bucket.ts"; |
| 32 | 33 | import { lastDrill } from "../snapshot/drills.ts"; |
| 33 | 34 | import { lastMirror, mirrorNeed } from "../snapshot/mirror.ts"; |
| @@ -47,7 +48,10 @@ import { diskRedSentence, diskReds } from "../checks/disk_red.ts"; | ||
| 47 | 48 | import { flakeList, type FlakeRow } from "../checks/flake.ts"; |
| 48 | 49 | import { flakeHref, sharedCause, sharedSentence, sharedTests } from "../checks/shared_red.ts"; |
| 49 | 50 | |
| 50 | /** A red in a repository other than the forge's own is not fixable from here: say so, so it reads as known. */ | |
| 51 | /** | |
| 52 | * A red in a repository other than the forge's own is not fixable from here: say so, so it reads as | |
| 53 | * known. | |
| 54 | */ | |
| 51 | 55 | function foreignNote(repo: string): string { |
| 52 | 56 | return repo === ownRepoPath() ? "" : " Not fixable from this forge: it is another repository's to fix."; |
| 53 | 57 | } |
| @@ -73,8 +77,10 @@ export interface EnvCount { | ||
| 73 | 77 | |
| 74 | 78 | /** |
| 75 | 79 | * One cause of the forge being off: the `needs` sentence, a `cause` key that |
| 76 | * holds for as long as its condition does (`disk`, `disk-floor`, `disk-80`, `disk-70`, `errors`, `internal`, | |
| 77 | * `queue:<kind>`, `release`, `stuck:<runId>`, `red:<repoId>`, `shared:<repoId>:<test>`), when it began by the forge's own evidence | |
| 80 | * holds for as long as its condition does (`disk`, `disk-floor`, `disk-80`, `disk-70`, `errors`, | |
| 81 | * `internal`, | |
| 82 | * `queue:<kind>`, `release`, `stuck:<runId>`, `red:<repoId>`, `shared:<repoId>:<test>`), when it | |
| 83 | * began by the forge's own evidence | |
| 78 | 84 | * (the oldest evidence the forge holds, else the first time this process saw |
| 79 | 85 | * it, held until the cause clears; `at` is never the answer to a repeat |
| 80 | 86 | * call), and where to look. |
| @@ -141,7 +147,10 @@ export interface VitalsInput { | ||
| 141 | 147 | readonly diskFreeMin?: number; |
| 142 | 148 | /** One forge's own signals (`App.signals`). */ |
| 143 | 149 | readonly signals: { errors: ErrorLedger; refused: RefusedLedger }; |
| 144 | /** Where snapshots go: the directory, when the store is one, and whether an off-box mirror copies them. */ | |
| 150 | /** | |
| 151 | * Where snapshots go: the directory, when the store is one, and whether an off-box mirror copies | |
| 152 | * them. | |
| 153 | */ | |
| 145 | 154 | readonly snapshots?: { readonly dir?: string; readonly mirrored: boolean } | undefined; |
| 146 | 155 | } |
| 147 | 156 | |
| @@ -256,7 +265,9 @@ export interface LaneRun { | ||
| 256 | 265 | } |
| 257 | 266 | |
| 258 | 267 | |
| 259 | /** Agent slots are held per issue (`pump` in crew/dispatch.ts); any other kind holds one per run. */ | |
| 268 | /** | |
| 269 | * Agent slots are held per issue (`pump` in crew/dispatch.ts); any other kind holds one per run. | |
| 270 | */ | |
| 260 | 271 | function holders(issues: (string | null)[], perIssue: boolean): number { |
| 261 | 272 | return perIssue ? new Set(issues).size : issues.length; |
| 262 | 273 | } |
| @@ -368,6 +379,11 @@ export function vitals(input: VitalsInput): Vitals { | ||
| 368 | 379 | for (const file of openDbFiles(input.dataDir)) |
| 369 | 380 | need(`file:${file.name}`, file.sentence, undefined, "/settings/capacity"); |
| 370 | 381 | |
| 382 | // The database past what Bun maps, or growing faster than the set rate (#11973): never found by a | |
| 383 | // profiler again. | |
| 384 | const bulky = sizeNeed(input.db, input.dataDir); | |
| 385 | if (bulky !== undefined) need(bulky.cause, bulky.sentence, undefined, "/system#sys-db"); | |
| 386 | ||
| 371 | 387 | // Snapshots on the volume they copy, and no mirror, share its one point of failure. |
| 372 | 388 | const snaps = input.snapshots; |
| 373 | 389 | if ( |
| @@ -518,7 +534,8 @@ export function vitals(input: VitalsInput): Vitals { | ||
| 518 | 534 | const failing = snapshotNeed(lastSnapshotOutcome(input.dataDir)); |
| 519 | 535 | if (failing !== undefined) need("snapshot-failed", failing.sentence, failing.since, "/settings/backups"); |
| 520 | 536 | |
| 521 | // The bucket itself, read by this process: late, unreadable, a failed drill, or a check that stopped is one card. | |
| 537 | // The bucket itself, read by this process: late, unreadable, a failed drill, or a check that | |
| 538 | // stopped is one card. | |
| 522 | 539 | if (isWatched(input.dataDir)) { |
| 523 | 540 | const backup = backupVerdict(input.dataDir, lastDrill(input.db), now); |
| 524 | 541 | if (backup.state === "red") need("backup", [...backup.reasons, ...(backup.reasons.some((r) => r.includes("last ran")) ? [] : [backup.checkLine])].join(" "), backup.checkedAt ?? undefined, "/settings/backups"); |
| @@ -537,7 +554,8 @@ export function vitals(input: VitalsInput): Vitals { | ||
| 537 | 554 | const undone = rollbackNeed(input.dataDir); |
| 538 | 555 | if (undone !== undefined) need("release:rolled-back", redactSecrets(undone.sentence), undone.since, "/board"); |
| 539 | 556 | |
| 540 | // Production serving a version older than a release main has had over an hour is a card until they match. | |
| 557 | // Production serving a version older than a release main has had over an hour is a card until | |
| 558 | // they match. | |
| 541 | 559 | const lagging = behindStanding(now); |
| 542 | 560 | if (lagging !== undefined) need("release:behind", `${lagging.sentence}.`, lagging.since, "/board"); |
| 543 | 561 |
src/maintain/duties/retention.ts added +48
| @@ -0,0 +1,48 @@ | ||
| 1 | /** | |
| 2 | * The database keeps what it needs (#11973, `core/retention.ts`): a small batch of each rule per | |
| 3 | * tick, never a long write lock. | |
| 4 | */ | |
| 5 | ||
| 6 | import type { Duty } from "../duty.ts"; | |
| 7 | import { | |
| 8 | allowance, giveBack, notePassed, passedToday, pruneDeployPulls, pruneEvents, rules, thinSamples, | |
| 9 | } from "../../core/retention.ts"; | |
| 10 | import { keepDbSize, measureDbSize, peekDbSize, recordDay } from "../../system/db_size.ts"; | |
| 11 | ||
| 12 | export const duty: Duty = { | |
| 13 | name: "retention", | |
| 14 | intervalMs: 60_000, | |
| 15 | budget: { runsPerDay: 1500, dollarsPerDay: 1, reason: "one batch a minute is 1,440 a day, 40 ms each; the rest is room for a restart, and it spends no money" }, | |
| 16 | async run({ db, now, app }) { | |
| 17 | const at = now.getTime(); | |
| 18 | const r = rules(db); | |
| 19 | const a = allowance(); | |
| 20 | const said: string[] = []; | |
| 21 | const walk = (name: string, label: string, work: () => { deleted: number; finished: boolean }): void => { | |
| 22 | if (passedToday(db, name, at)) return; | |
| 23 | const out = work(); | |
| 24 | if (out.finished) notePassed(db, name, at); | |
| 25 | if (out.deleted > 0) said.push(`deleted ${out.deleted} ${label}`); | |
| 26 | }; | |
| 27 | // The outbox walks forward only, so it is cheap to read every tick; the other two read a table | |
| 28 | // whole once a day. | |
| 29 | const events = pruneEvents(db, at, a, r); | |
| 30 | if (events.deleted > 0) said.push(`deleted ${events.deleted} old events`); | |
| 31 | walk("deploy_pull", "deploy_pull rows", () => pruneDeployPulls(db, at, a, r)); | |
| 32 | walk("machine_sample", "machine samples thinned to hourly", () => thinSamples(db, at, a, r)); | |
| 33 | const back = giveBack(db, a); | |
| 34 | if (back.pages > 0) said.push(`gave back ${back.pages} pages`); | |
| 35 | // What the file weighs, once a day and once after a start: the growth /system and vitals read | |
| 36 | // (`system/db_size.ts`). | |
| 37 | const daily = !passedToday(db, "db_size", at); | |
| 38 | if ((daily || peekDbSize() === null) && app !== undefined) { | |
| 39 | const size = await measureDbSize(db, app.config.dataDir, at); | |
| 40 | keepDbSize(size); | |
| 41 | if (daily) { | |
| 42 | recordDay(db, size); | |
| 43 | notePassed(db, "db_size", at); | |
| 44 | } | |
| 45 | } | |
| 46 | return { findings: [], actions: said }; | |
| 47 | }, | |
| 48 | }; |
src/maintain/registry.ts +2 −1
| @@ -6,5 +6,6 @@ import { duty as ruleWatcher } from "./duties/rule_watcher.ts"; | ||
| 6 | 6 | import { duty as efficiencyWatcher } from "./duties/efficiency_watcher.ts"; |
| 7 | 7 | import { duty as flowKeeper } from "./duties/flow_keeper.ts"; |
| 8 | 8 | import { duty as visitorRetention } from "./duties/visitor_retention.ts"; |
| 9 | import { duty as retention } from "./duties/retention.ts"; | |
| 9 | 10 | |
| 10 | export const duties: readonly Duty[] = [pullsWaiting, ruleWatcher, efficiencyWatcher, flowKeeper, visitorRetention]; | |
| 11 | export const duties: readonly Duty[] = [pullsWaiting, ruleWatcher, efficiencyWatcher, flowKeeper, visitorRetention, retention]; |
src/system/db_size.ts added +220
| @@ -0,0 +1,220 @@ | ||
| 1 | /** | |
| 2 | * The forge knows its own size (#11973): the file, what is free in it, and the ten tables and | |
| 3 | * ten indexes that weigh most, by estimated bytes and rows, so a 4.5 GB database is read on | |
| 4 | * /system and never found by a profiler. Bun's SQLite has no `dbstat`, so each figure is an | |
| 5 | * estimate: rows come from `sqlite_stat1` where `ANALYZE` has run, else from the highest rowid, | |
| 6 | * else a bounded count; bytes are rows times the average width of the columns in a 200-row | |
| 7 | * sample (an index's columns, plus its rowid). The walk yields between tables, so it never holds | |
| 8 | * the loop; one reading is shared by /system, the terminal and the MCP `system` tool, kept ten | |
| 9 | * minutes. | |
| 10 | * A reading a day is kept (`db_size_day`), which is how growth per day is known. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { Database } from "bun:sqlite"; | |
| 14 | import { statSync } from "node:fs"; | |
| 15 | import { join } from "node:path"; | |
| 16 | import { capacityCount } from "../core/capacity.ts"; | |
| 17 | ||
| 18 | /** The most Bun maps of a database; past it every scan costs a read per page. */ | |
| 19 | export const MMAP_CAP_BYTES = 2 * 1024 ** 3; | |
| 20 | /** Rows whose width is sampled, per table. */ | |
| 21 | const SAMPLE = 200; | |
| 22 | /** Rows counted at most; past it a table's rows are taken from its rowids. */ | |
| 23 | const COUNT_CAP = 50_000; | |
| 24 | /** Tables and indexes /system names. */ | |
| 25 | export const TOP = 10; | |
| 26 | const KEEP_DAYS = 400; | |
| 27 | ||
| 28 | export interface Weight { | |
| 29 | readonly name: string; | |
| 30 | /** For an index, its table. */ | |
| 31 | readonly table?: string; | |
| 32 | readonly rows: number; | |
| 33 | readonly bytes: number; | |
| 34 | } | |
| 35 | ||
| 36 | export interface DbSize { | |
| 37 | /** ISO time the walk finished. */ | |
| 38 | readonly at: string; | |
| 39 | /** forge.db and its write-ahead log, as the file system has them. */ | |
| 40 | readonly fileBytes: number; | |
| 41 | /** Pages the file holds that nothing uses: what incremental vacuum can give back. */ | |
| 42 | readonly freeBytes: number; | |
| 43 | /** | |
| 44 | * `incremental` gives freed pages back a step at a time; `none` is a file made before that and | |
| 45 | * needs one offline conversion. | |
| 46 | */ | |
| 47 | readonly autoVacuum: "none" | "full" | "incremental"; | |
| 48 | readonly tables: readonly Weight[]; | |
| 49 | readonly indexes: readonly Weight[]; | |
| 50 | readonly tableCount: number; | |
| 51 | readonly indexCount: number; | |
| 52 | } | |
| 53 | ||
| 54 | const quote = (name: string): string => `"${name.replace(/"/g, '""')}"`; | |
| 55 | ||
| 56 | /** The largest `n` by bytes, equal sizes by name so the order is stable. */ | |
| 57 | export const heaviest = (all: readonly Weight[], n = TOP): Weight[] => | |
| 58 | [...all].sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name)).slice(0, n); | |
| 59 | ||
| 60 | /** The file as the file system has it: the database and its write-ahead log. */ | |
| 61 | export function fileBytesOf(dataDir: string): number { | |
| 62 | let total = 0; | |
| 63 | for (const name of ["forge.db", "forge.db-wal"]) | |
| 64 | try { | |
| 65 | total += statSync(join(dataDir, name)).size; | |
| 66 | } catch { | |
| 67 | // No such file (a log comes and goes): nothing to add. | |
| 68 | } | |
| 69 | return total; | |
| 70 | } | |
| 71 | ||
| 72 | function rowsOf(db: Database, table: string, stat: ReadonlyMap<string, number>): number { | |
| 73 | const known = stat.get(table); | |
| 74 | if (known !== undefined) return known; | |
| 75 | const counted = db.query<{ n: number }, []>(`SELECT COUNT(*) AS n FROM (SELECT 1 FROM ${quote(table)} LIMIT ${COUNT_CAP + 1})`).get()?.n ?? 0; | |
| 76 | if (counted <= COUNT_CAP) return counted; | |
| 77 | try { | |
| 78 | // Past the cap: the rowids' range over the range the first 200 rows span says how many there | |
| 79 | // are. | |
| 80 | const span = db.query<{ lo: number; hi: number; n: number }, []>( | |
| 81 | `SELECT MIN(rowid) AS lo, MAX(rowid) AS hi, COUNT(*) AS n FROM (SELECT rowid FROM ${quote(table)} ORDER BY rowid LIMIT ${SAMPLE})`, | |
| 82 | ).get(); | |
| 83 | const all = db.query<{ lo: number; hi: number }, []>(`SELECT MIN(rowid) AS lo, MAX(rowid) AS hi FROM ${quote(table)}`).get(); | |
| 84 | if (span === null || all === null || span.hi <= span.lo) return counted; | |
| 85 | return Math.max(counted, Math.round((span.n * (all.hi - all.lo)) / (span.hi - span.lo))); | |
| 86 | } catch { | |
| 87 | // WITHOUT ROWID: at least what was counted. | |
| 88 | return counted; | |
| 89 | } | |
| 90 | } | |
| 91 | ||
| 92 | /** The average bytes of each named column in a sample of the table. */ | |
| 93 | function widths(db: Database, table: string, columns: readonly string[]): Map<string, number> { | |
| 94 | const out = new Map<string, number>(); | |
| 95 | if (columns.length === 0) return out; | |
| 96 | const avgs = columns.map((c, i) => `AVG(LENGTH(CAST(${quote(c)} AS BLOB))) AS w${i}`).join(", "); | |
| 97 | try { | |
| 98 | const row = db.query<Record<string, number | null>, []>(`SELECT ${avgs} FROM (SELECT * FROM ${quote(table)} LIMIT ${SAMPLE})`).get(); | |
| 99 | columns.forEach((c, i) => out.set(c, row?.[`w${i}`] ?? 0)); | |
| 100 | } catch { | |
| 101 | // A table that cannot be sampled weighs what its rows say. | |
| 102 | } | |
| 103 | return out; | |
| 104 | } | |
| 105 | ||
| 106 | const tick = (): Promise<void> => new Promise((r) => setImmediate(r)); | |
| 107 | ||
| 108 | /** Walk every table and index, one at a time, and say what each weighs. */ | |
| 109 | export async function measureDbSize(db: Database, dataDir: string, now: number = Date.now()): Promise<DbSize> { | |
| 110 | const one = <T>(sql: string): T | undefined => db.query<T, []>(sql).get() ?? undefined; | |
| 111 | const pageSize = one<{ page_size: number }>("PRAGMA page_size")?.page_size ?? 4096; | |
| 112 | const free = one<{ freelist_count: number }>("PRAGMA freelist_count")?.freelist_count ?? 0; | |
| 113 | const mode = one<{ auto_vacuum: number }>("PRAGMA auto_vacuum")?.auto_vacuum ?? 0; | |
| 114 | const stat = new Map<string, number>(); | |
| 115 | try { | |
| 116 | for (const r of db.query<{ tbl: string; stat: string }, []>("SELECT tbl, stat FROM sqlite_stat1").all()) { | |
| 117 | const n = Number(r.stat.split(" ")[0]); | |
| 118 | if (Number.isFinite(n) && n > (stat.get(r.tbl) ?? -1)) stat.set(r.tbl, n); | |
| 119 | } | |
| 120 | } catch { | |
| 121 | // ANALYZE has never run: rows come from the rowid. | |
| 122 | } | |
| 123 | const tableNames = db | |
| 124 | .query<{ name: string }, []>("SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name") | |
| 125 | .all() | |
| 126 | .map((r) => r.name); | |
| 127 | const indexRows = db | |
| 128 | .query<{ name: string; tbl_name: string }, []>("SELECT name, tbl_name FROM sqlite_schema WHERE type = 'index' ORDER BY name") | |
| 129 | .all(); | |
| 130 | const tables: Weight[] = []; | |
| 131 | const indexes: Weight[] = []; | |
| 132 | for (const table of tableNames) { | |
| 133 | const cols = db.query<{ name: string }, []>(`PRAGMA table_info(${quote(table)})`).all().map((c) => c.name); | |
| 134 | const rows = rowsOf(db, table, stat); | |
| 135 | const w = widths(db, table, cols); | |
| 136 | const row = [...w.values()].reduce((a, b) => a + b, 0) + cols.length; | |
| 137 | tables.push({ name: table, rows, bytes: Math.round(rows * (row + 8)) }); | |
| 138 | for (const ix of indexRows.filter((i) => i.tbl_name === table)) { | |
| 139 | const keyed = db.query<{ name: string | null }, []>(`PRAGMA index_info(${quote(ix.name)})`).all().map((c) => c.name); | |
| 140 | const keyWidth = keyed.reduce((a, c) => a + (c === null ? 8 : (w.get(c) ?? 8) + 1), 0); | |
| 141 | indexes.push({ name: ix.name, table, rows, bytes: Math.round(rows * (keyWidth + 10)) }); | |
| 142 | } | |
| 143 | await tick(); | |
| 144 | } | |
| 145 | return { | |
| 146 | at: new Date(now).toISOString(), | |
| 147 | fileBytes: fileBytesOf(dataDir), | |
| 148 | freeBytes: free * pageSize, | |
| 149 | autoVacuum: mode === 2 ? "incremental" : mode === 1 ? "full" : "none", | |
| 150 | tables: heaviest(tables), | |
| 151 | indexes: heaviest(indexes), | |
| 152 | tableCount: tables.length, | |
| 153 | indexCount: indexes.length, | |
| 154 | }; | |
| 155 | } | |
| 156 | ||
| 157 | let last: DbSize | null = null; | |
| 158 | ||
| 159 | /** | |
| 160 | * The last reading, from the nightly duty's walk (`maintain/duties/retention.ts`); null before it. | |
| 161 | */ | |
| 162 | export function peekDbSize(): DbSize | null { | |
| 163 | return last; | |
| 164 | } | |
| 165 | ||
| 166 | /** What the duty's walk found, for every surface to show; a page never starts a walk itself. */ | |
| 167 | export function keepDbSize(value: DbSize): void { | |
| 168 | last = value; | |
| 169 | } | |
| 170 | ||
| 171 | /** Keep today's reading, replacing one already kept today, and drop what is over a year old. */ | |
| 172 | export function recordDay(db: Database, size: DbSize): void { | |
| 173 | const day = size.at.slice(0, 10); | |
| 174 | db.query( | |
| 175 | `INSERT INTO db_size_day (day, file_bytes, free_bytes, top) VALUES (?1, ?2, ?3, ?4) | |
| 176 | ON CONFLICT(day) DO UPDATE SET file_bytes = excluded.file_bytes, free_bytes = excluded.free_bytes, top = excluded.top`, | |
| 177 | ).run(day, size.fileBytes, size.freeBytes, JSON.stringify(size.tables.slice(0, 3).map((t) => [t.name, t.rows, t.bytes]))); | |
| 178 | db.query("DELETE FROM db_size_day WHERE day < ?1").run(new Date(Date.parse(size.at) - KEEP_DAYS * 86_400_000).toISOString().slice(0, 10)); | |
| 179 | } | |
| 180 | ||
| 181 | /** Bytes the file grew by a day, from the last two readings kept; null before there are two. */ | |
| 182 | export function growthPerDay(db: Database): number | null { | |
| 183 | const [b, a] = db | |
| 184 | .query<{ day: string; file_bytes: number }, []>("SELECT day, file_bytes FROM db_size_day ORDER BY day DESC LIMIT 2") | |
| 185 | .all(); | |
| 186 | if (a === undefined || b === undefined) return null; | |
| 187 | const days = (Date.parse(b.day) - Date.parse(a.day)) / 86_400_000; | |
| 188 | return days > 0 ? (b.file_bytes - a.file_bytes) / days : null; | |
| 189 | } | |
| 190 | ||
| 191 | /** | |
| 192 | * The need vitals names: forge.db is past what Bun maps, or grows faster than the set rate; | |
| 193 | * undefined while neither. | |
| 194 | */ | |
| 195 | export function sizeNeed(db: Database, dataDir: string): { cause: string; sentence: string } | undefined { | |
| 196 | const file = fileBytesOf(dataDir); | |
| 197 | const mb = (n: number): string => `${Math.round(n / 1024 ** 2).toLocaleString("en-US")} MB`; | |
| 198 | if (file > MMAP_CAP_BYTES) | |
| 199 | return { | |
| 200 | cause: "db-size", | |
| 201 | sentence: `forge.db is ${mb(file)}, past the ${mb(MMAP_CAP_BYTES)} Bun maps: every scan costs a read per page. See the largest tables on /system and the retention rules on the capacity page.`, | |
| 202 | }; | |
| 203 | const rate = growthPerDay(db); | |
| 204 | if (rate === null) return undefined; | |
| 205 | const limit = capacityCount(db, "size.growth_mb_per_day", 200) * 1024 ** 2; | |
| 206 | if (rate > limit) | |
| 207 | return { | |
| 208 | cause: "db-growth", | |
| 209 | sentence: `forge.db grows ${mb(rate)} a day, over the ${mb(limit)} set (now ${mb(file)}). See the largest tables on /system.`, | |
| 210 | }; | |
| 211 | return undefined; | |
| 212 | } | |
| 213 | ||
| 214 | /** | |
| 215 | * What every surface shows of the database's size: the last reading, the growth, the cap. Never | |
| 216 | * waits. | |
| 217 | */ | |
| 218 | export function dbFacts(db: Database, dataDir: string): { size: DbSize | null; growthBytesPerDay: number | null; mmapCapBytes: number; fileBytes: number } { | |
| 219 | return { size: peekDbSize(), growthBytesPerDay: growthPerDay(db), mmapCapBytes: MMAP_CAP_BYTES, fileBytes: fileBytesOf(dataDir) }; | |
| 220 | } |
src/tui/screens/system.ts +34 −5
| @@ -40,6 +40,7 @@ import { style } from "../term/style.ts"; | ||
| 40 | 40 | import { pad, truncate, wrap } from "../term/width.ts"; |
| 41 | 41 | import { dialog } from "../ui/widgets.ts"; |
| 42 | 42 | import { Scroll, ago, confirmScreen, drawLines, hitScroll, later, pickerScreen } from "./common.ts"; |
| 43 | import { dbFacts, TOP as DB_TOP } from "../../system/db_size.ts"; | |
| 43 | 44 | import { largestDirs, type LargestDirs } from "../../system/largest_dirs.ts"; |
| 44 | 45 | import type { PaletteEntry } from "./entries.ts"; |
| 45 | 46 | import { readHealth } from "../../actions/health.ts"; |
| @@ -72,7 +73,10 @@ export function duplicateLines(dups: SystemView["duplicates"], inner: number): s | ||
| 72 | 73 | ); |
| 73 | 74 | } |
| 74 | 75 | |
| 75 | /** A cell's memory beside its cap and who holds it, as /system says it (#2410); the forge and the host have none. */ | |
| 76 | /** | |
| 77 | * A cell's memory beside its cap and who holds it, as /system says it (#2410); the forge and the | |
| 78 | * host have none. | |
| 79 | */ | |
| 76 | 80 | const capOf = (g: SystemView["groups"][number]): string => |
| 77 | 81 | g.capBytes === null ? "" : `${bytes(g.rssBytes)} of ${bytes(g.capBytes)} ${g.capBy === "kernel" ? "kernel" : "watched"}`; |
| 78 | 82 | |
| @@ -136,7 +140,8 @@ function shrink(xs: readonly number[], n: number): number[] { | ||
| 136 | 140 | } |
| 137 | 141 | |
| 138 | 142 | /** |
| 139 | * CPU, memory and load of the node over the last `hours`, one sparkline each (scaled to its own peak), | |
| 143 | * CPU, memory and load of the node over the last `hours`, one sparkline each (scaled to its own | |
| 144 | * peak), | |
| 140 | 145 | * with the latest value and the peak in words. Empty for anyone `telemetry_history` refuses; |
| 141 | 146 | * `no readings yet` when nothing is recorded. |
| 142 | 147 | */ |
| @@ -176,7 +181,25 @@ export function largestLines(session: Session, found: LargestDirs | null, inner | ||
| 176 | 181 | ]; |
| 177 | 182 | } |
| 178 | 183 | |
| 179 | /** Who may grant telemetry:read: the MCP tool's gate (`mayBoards`), a forge admin who is a person. */ | |
| 184 | /** | |
| 185 | * The database's size as /system's "The database" says it (#11973): the file, its growth and the | |
| 186 | * largest | |
| 187 | * tables. Empty for anyone the page refuses. | |
| 188 | */ | |
| 189 | export function dbLines(session: Session, facts: ReturnType<typeof dbFacts>, inner = WIDTH - 6): string[] { | |
| 190 | if (!telemetryReader(session.app, session.user)) return []; | |
| 191 | const { size, growthBytesPerDay: growth, fileBytes, mmapCapBytes } = facts; | |
| 192 | const growing = growth === null ? "growth: after the second daily reading" : `${growth < 0 ? "−" : "+"}${bytes(Math.abs(growth))} a day`; | |
| 193 | const head = `The database: ${bytes(fileBytes)} of ${bytes(mmapCapBytes)} mapped, ${growing}`; | |
| 194 | if (size === null) return [head, "being measured; open again in a moment"]; | |
| 195 | const row = (w: { name: string; rows: number; bytes: number }): string => | |
| 196 | truncate(`${pad(truncate(w.name, inner - 26), inner - 26)} ${pad(`${w.rows.toLocaleString("en-US")} rows`, 14, "right")} ${pad(bytes(w.bytes), 10, "right")}`, inner); | |
| 197 | return [head, `largest tables (of ${size.tableCount}; /system has ${DB_TOP} tables and ${DB_TOP} indexes)`, ...size.tables.slice(0, 3).map(row)]; | |
| 198 | } | |
| 199 | ||
| 200 | /** | |
| 201 | * Who may grant telemetry:read: the MCP tool's gate (`mayBoards`), a forge admin who is a person. | |
| 202 | */ | |
| 180 | 203 | const mayGrant = (session: Session | undefined): boolean => session?.user?.isAdmin === true && session.user.kind !== "agent"; |
| 181 | 204 | |
| 182 | 205 | const READER_ROWS = 6; |
| @@ -271,6 +294,7 @@ export function systemScreen(ctx: Ctx, lines: readonly string[], session: Sessio | ||
| 271 | 294 | const features = featuresLines(session); |
| 272 | 295 | // Never waits on the walk: the last measurement, a new one started behind it when stale. |
| 273 | 296 | const largest = largestLines(session, largestDirs.peek(session.app.config.dataDir)); |
| 297 | const dbLinesOut = dbLines(session, dbFacts(session.app.db, session.app.config.dataDir)); | |
| 274 | 298 | const buttons = dialog(s, area, ctx.theme.c, { |
| 275 | 299 | title: "System", |
| 276 | 300 | body: [ |
| @@ -281,6 +305,7 @@ export function systemScreen(ctx: Ctx, lines: readonly string[], session: Sessio | ||
| 281 | 305 | ...(offered ? ["", ...readerLines(session)] : []), |
| 282 | 306 | ...(features.length === 0 ? [] : ["", ...features]), |
| 283 | 307 | ...(offered ? ["", grantLine(session), "g: grant or take back telemetry:read"] : []), |
| 308 | ...(dbLinesOut.length === 0 ? [] : ["", ...dbLinesOut]), | |
| 284 | 309 | ], |
| 285 | 310 | actions: [{ label: "Close" }], |
| 286 | 311 | selected: 0, |
| @@ -340,7 +365,10 @@ export function memoryScreen(session: Session, ctx: Ctx): Screen { | ||
| 340 | 365 | }; |
| 341 | 366 | } |
| 342 | 367 | |
| 343 | /** This forge's size and its use against it, a line each, as /system's "This forge's size" says it; none on a forge that is no cell child. */ | |
| 368 | /** | |
| 369 | * This forge's size and its use against it, a line each, as /system's "This forge's size" says it; | |
| 370 | * none on a forge that is no cell child. | |
| 371 | */ | |
| 344 | 372 | export function selfLines(self: SelfUse | null): string[] { |
| 345 | 373 | if (self === null) return []; |
| 346 | 374 | const w = useWords(self.use); |
| @@ -361,7 +389,8 @@ export function childLines(rows: readonly ChildUseRow[], inner = WIDTH - 6): str | ||
| 361 | 389 | if (r.use.kind === "shared") return [truncate(`${pad(r.name, 16)} ${r.size} · shared with this forge`, inner)]; |
| 362 | 390 | const w = useWords(r.use); |
| 363 | 391 | const parts = r.use.kind === "idle" ? ["not running"] : [`memory ${w.memory}`, `cpu ${w.cpu}`, `disk ${w.disk}`]; |
| 364 | // Figures go on whole, never split across lines: a part that does not fit starts the next line. | |
| 392 | // Figures go on whole, never split across lines: a part that does not fit starts the next | |
| 393 | // line. | |
| 365 | 394 | const lines: string[] = []; |
| 366 | 395 | for (const part of parts) { |
| 367 | 396 | const last = lines.length - 1; |
src/web/pages/system.ts +63 −11
| @@ -46,6 +46,7 @@ import { RECENT_BYTES, recentEncodings } from "../../http/compress.ts"; | ||
| 46 | 46 | import { KEPT_PAGE_BYTES, keptPageStats } from "./kept_page.ts"; |
| 47 | 47 | import { COLUMN_BYTES, PARTS_BYTES, keptPartsStats, treeCacheStats } from "./tree_cache.ts"; |
| 48 | 48 | import { featureHealth, type FeatureHealth } from "../../system/feature_health.ts"; |
| 49 | import { dbFacts, TOP as DB_TOP, type Weight } from "../../system/db_size.ts"; | |
| 49 | 50 | import { egressReportedLine } from "../../system/egress_line.ts"; |
| 50 | 51 | import { BREAK_STEPS, MACHINES, declaredFooting, footing, offMachine, whereWords, type Footing, type Machine } from "../../system/footing.ts"; |
| 51 | 52 | import { laneWords, readOffsiteLane, type OffsiteLane } from "../../snapshot/offsite_lane.ts"; |
| @@ -80,7 +81,10 @@ const meterRow = (name: string, value: number | null, max: number, figure: strin | ||
| 80 | 81 | const figureRow = (name: string, figure: string, data: Record<string, string> = {}): Html => |
| 81 | 82 | row({ title: name, trail: html`<span class="mono">${figure}</span>`, data }); |
| 82 | 83 | |
| 83 | /** The five largest directories under the forge's data (#11800), measured at most once a minute, never waited on. */ | |
| 84 | /** | |
| 85 | * The five largest directories under the forge's data (#11800), measured at most once a minute, | |
| 86 | * never waited on. | |
| 87 | */ | |
| 84 | 88 | export function largestDirsSection(found: LargestDirs | null): Html { |
| 85 | 89 | return html`<section class="settings-block" id="sys-largest"><h2>Largest under the forge's data</h2> |
| 86 | 90 | ${found === null |
| @@ -91,7 +95,32 @@ export function largestDirsSection(found: LargestDirs | null): Html { | ||
| 91 | 95 | <p class="muted small">Measured ${time(found.at)}</p>`}</section>`; |
| 92 | 96 | } |
| 93 | 97 | |
| 94 | /** This forge's own size and use when it is a child in a cell (#10853); nothing on any other forge. */ | |
| 98 | /** The rows of a heaviest-first list: name, then rows and bytes. */ | |
| 99 | const weightRows = (list: readonly Weight[]): Html => | |
| 100 | html`${list.map((w) => figureRow(w.table === undefined ? w.name : `${w.name} (${w.table})`, `${w.rows.toLocaleString("en-US")} rows · ${bytes(w.bytes)}`, { name: w.name, bytes: String(w.bytes), rows: String(w.rows) }))}`; | |
| 101 | ||
| 102 | /** | |
| 103 | * The database's own size (#11973): the file, growth a day, and the ten heaviest tables and | |
| 104 | * indexes; the figures are estimates. | |
| 105 | */ | |
| 106 | export function dbSizeSection(facts: ReturnType<typeof dbFacts>): Html { | |
| 107 | const { size, growthBytesPerDay: growth, fileBytes, mmapCapBytes } = facts; | |
| 108 | const growing = growth === null ? "growth per day: after the second daily reading" : `growing ${growth < 0 ? "−" : "+"}${bytes(Math.abs(growth))} a day`; | |
| 109 | const past = fileBytes > mmapCapBytes ? ` — past the ${bytes(mmapCapBytes)} Bun maps` : ` of the ${bytes(mmapCapBytes)} Bun maps`; | |
| 110 | return html`<section class="settings-block" id="sys-db" data-bytes="${String(fileBytes)}"><h2>The database</h2> | |
| 111 | <p class="small" id="sys-db-file">forge.db is ${bytes(fileBytes)}${past}; ${growing}.${size === null ? "" : ` ${bytes(size.freeBytes)} free inside it, given back ${size.autoVacuum === "incremental" ? "a step at a time" : "only by one offline conversion (docs/features/retention.md)"}.`}</p> | |
| 112 | ${size === null | |
| 113 | ? html`<p class="muted small">Being measured; reload in a moment.</p>` | |
| 114 | : disclosure(html`${String(DB_TOP)} largest of ${String(size.tableCount)} tables and ${String(size.indexCount)} indexes`, html`<h3>Tables</h3> | |
| 115 | <ul class="list" aria-label="The largest tables">${weightRows(size.tables)}</ul> | |
| 116 | <h3>Indexes</h3> | |
| 117 | <ul class="list" aria-label="The largest indexes">${weightRows(size.indexes)}</ul> | |
| 118 | <p class="muted small">Estimated from row counts and a sample of each table, measured ${time(size.at)}. Retention rules and their days are on the capacity page.</p>`)}</section>`; | |
| 119 | } | |
| 120 | ||
| 121 | /** | |
| 122 | * This forge's own size and use when it is a child in a cell (#10853); nothing on any other forge. | |
| 123 | */ | |
| 95 | 124 | export function selfSection(self: SelfUse | null): Html { |
| 96 | 125 | if (self === null) return html``; |
| 97 | 126 | const { use, size } = self; |
| @@ -105,7 +134,10 @@ export function selfSection(self: SelfUse | null): Html { | ||
| 105 | 134 | </section>`; |
| 106 | 135 | } |
| 107 | 136 | |
| 108 | /** What this forge's own size section leaves to the page's `?`: who set the size and what is measured. */ | |
| 137 | /** | |
| 138 | * What this forge's own size section leaves to the page's `?`: who set the size and what is | |
| 139 | * measured. | |
| 140 | */ | |
| 109 | 141 | export const selfHelp = (self: SelfUse | null): Html | null => |
| 110 | 142 | self === null ? null : html`<p id="sys-self-help">Size is set by the forge that made this one. ${self.from === "process" ? "Memory and CPU count this process alone. " : ""}Disk is measured every 30 seconds.</p>`; |
| 111 | 143 | |
| @@ -134,7 +166,10 @@ export function childrenSection(rows: readonly ChildUseRow[]): Html { | ||
| 134 | 166 | })}</ul></section>`; |
| 135 | 167 | } |
| 136 | 168 | |
| 137 | /** Processes grouped forge, crew, check, app, host; the client re-sorts them by CPU or memory (`system-live.ts`). */ | |
| 169 | /** | |
| 170 | * Processes grouped forge, crew, check, app, host; the client re-sorts them by CPU or memory | |
| 171 | * (`system-live.ts`). | |
| 172 | */ | |
| 138 | 173 | const KIND_ORDER = ["forge", "crew", "check", "app", "host"] as const; |
| 139 | 174 | function procTable(v: SystemView): Html { |
| 140 | 175 | const groups = KIND_ORDER.flatMap((k) => v.groups.filter((g) => g.kind === k)); |
| @@ -191,7 +226,10 @@ export const pageCaches = (): CacheRow[] => [ | ||
| 191 | 226 | { name: "folders and refs", holds: "folder listings at a commit, ref names (tree_cache.ts)", capBytes: PARTS_BYTES, ...keptPartsStats() }, |
| 192 | 227 | ]; |
| 193 | 228 | |
| 194 | /** `pageCaches`' rows as a table; the hit rate is hits over hits and misses since the process started. */ | |
| 229 | /** | |
| 230 | * `pageCaches`' rows as a table; the hit rate is hits over hits and misses since the process | |
| 231 | * started. | |
| 232 | */ | |
| 195 | 233 | export function cachesSection(rows: readonly CacheRow[]): Html { |
| 196 | 234 | const rate = (r: CacheRow) => (r.hits + r.misses === 0 ? "—" : `${((100 * r.hits) / (r.hits + r.misses)).toFixed(1)}%`); |
| 197 | 235 | return html`<section class="settings-block"><h2>Code page caches, since start</h2> |
| @@ -201,7 +239,10 @@ export function cachesSection(rows: readonly CacheRow[]): Html { | ||
| 201 | 239 | </table></div></section>`; |
| 202 | 240 | } |
| 203 | 241 | |
| 204 | /** Absorbed apps and whether production is serving (#9887); `featureHealth`'s rows. Nothing absorbed, nothing drawn. */ | |
| 242 | /** | |
| 243 | * Absorbed apps and whether production is serving (#9887); `featureHealth`'s rows. Nothing | |
| 244 | * absorbed, nothing drawn. | |
| 245 | */ | |
| 205 | 246 | export function featuresSection(rows: readonly FeatureHealth[]): Html { |
| 206 | 247 | if (rows.length === 0) return html``; |
| 207 | 248 | return html`<section class="settings-block" id="sys-features"><h2>Features from apps</h2> |
| @@ -256,7 +297,8 @@ export function footingSection(f: Footing): Html { | ||
| 256 | 297 | * last restore drill with where it restored from. `snapshot/offsite_lane.ts`'s reading. |
| 257 | 298 | */ |
| 258 | 299 | export function offsiteSection(l: OffsiteLane): Html { |
| 259 | // A lane that exists and is not level and sealed is red; no lane at all is a setting, said in words (first sight, #11111). | |
| 300 | // A lane that exists and is not level and sealed is red; no lane at all is a setting, said in | |
| 301 | // words (first sight, #11111). | |
| 260 | 302 | const tone = l.health === "ok" || l.health === "none" ? null : badge(l.health, { tone: "danger" }); |
| 261 | 303 | const d = l.drill; |
| 262 | 304 | // First sight (#11111): the heading and one sentence stay; the rows open behind one disclosure. |
| @@ -339,7 +381,10 @@ export function lagSection(rows: readonly LagReading[]): Html { | ||
| 339 | 381 | |
| 340 | 382 | const SLOW_TTL_MS = 5000; |
| 341 | 383 | let slowKept: { db: object; at: number; rows: SlowPage[] } | undefined; |
| 342 | /** `slowPages`, kept a few seconds so a busy /system never repeats the query; changes show on reload. */ | |
| 384 | /** | |
| 385 | * `slowPages`, kept a few seconds so a busy /system never repeats the query; changes show on | |
| 386 | * reload. | |
| 387 | */ | |
| 343 | 388 | function slowPagesCached(db: Parameters<typeof slowPages>[0]): SlowPage[] { |
| 344 | 389 | const now = Date.now(); |
| 345 | 390 | if (slowKept === undefined || slowKept.db !== db || now - slowKept.at > SLOW_TTL_MS) |
| @@ -347,14 +392,19 @@ function slowPagesCached(db: Parameters<typeof slowPages>[0]): SlowPage[] { | ||
| 347 | 392 | return slowKept.rows; |
| 348 | 393 | } |
| 349 | 394 | |
| 350 | /** Real visitors' pages over budget (#10536): one line each, and nothing at all when every page is fast. */ | |
| 395 | /** | |
| 396 | * Real visitors' pages over budget (#10536): one line each, and nothing at all when every page is | |
| 397 | * fast. | |
| 398 | */ | |
| 351 | 399 | export function slowPagesSection(rows: readonly SlowPage[]): Html { |
| 352 | 400 | if (rows.length === 0) return html``; |
| 353 | 401 | return html`<section class="settings-block" id="slow-pages"><h2>Pages over budget, last hour</h2> |
| 354 | 402 | <ul class="list" aria-label="Pages over their budget for real visitors">${rows.map((p) => html`<li data-route="${p.route}" data-phase="${p.phase}">${slowPageLine(p)}</li>`)}</ul></section>`; |
| 355 | 403 | } |
| 356 | 404 | |
| 357 | /** Who read the telemetry routes in the last 10 minutes and how fast (#9069); `readerPaces`' rows. */ | |
| 405 | /** | |
| 406 | * Who read the telemetry routes in the last 10 minutes and how fast (#9069); `readerPaces`' rows. | |
| 407 | */ | |
| 358 | 408 | export function readersSection(rows: readonly ReaderPace[]): Html { |
| 359 | 409 | const secs = (ms: number | null): string => (ms === null ? "—" : `${(ms / 1000).toFixed(1)} s`); |
| 360 | 410 | return html`<section class="settings-block"><h2>Telemetry readers</h2>${ |
| @@ -453,7 +503,8 @@ export async function systemPage(ctx: Ctx): Promise<Response> { | ||
| 453 | 503 | const stalls = timePhase(ctx.request, "stalls", () => stallHour(loopWatch.tally(performance.now()))); |
| 454 | 504 | const nowMono = performance.now(); |
| 455 | 505 | const worst = stallBlame.worst(nowMono, HOUR_MS, WORST_STALLS); |
| 456 | // Never waits on the cluster: the last reading, or the declared rows while the first read runs behind. | |
| 506 | // Never waits on the cluster: the last reading, or the declared rows while the first read runs | |
| 507 | // behind. | |
| 457 | 508 | const standsOn = footing.peek() ?? declaredFooting("the cluster is being read; reload in a moment"); |
| 458 | 509 | // Never waits on the walk: the last measurement, a new one started behind it when stale. |
| 459 | 510 | const largestUnder = largestDirs.peek(ctx.app.config.dataDir); |
| @@ -487,6 +538,7 @@ export async function systemPage(ctx: Ctx): Promise<Response> { | ||
| 487 | 538 | <section class="settings-block"><h2>Disks and network</h2> |
| 488 | 539 | <ul class="list" id="sys-disks">${at("sys-disks")}</ul></section> |
| 489 | 540 | ${largestDirsSection(largestUnder)} |
| 541 | ${dbSizeSection(dbFacts(ctx.app.db, ctx.app.config.dataDir))} | |
| 490 | 542 | <section class="settings-block"><h2>Processes</h2> |
| 491 | 543 | <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> |
| 492 | 544 | <button class="btn" data-size="sm" type="button" data-sort="mem" aria-pressed="false"><kbd>m</kbd> memory</button></div> |
src/web/studio/run.ts +2 −2
| @@ -14,7 +14,7 @@ import { parseTestsRow, testsRowWords } from "../../checks/tests-row.ts"; | ||
| 14 | 14 | import { directionNote } from "../../crew/direct.ts"; |
| 15 | 15 | import { appsRuntime } from "../../apps/runtime.ts"; |
| 16 | 16 | import { getAppByRepo } from "../../core/apps.ts"; |
| 17 | import { carriedBy } from "../../core/carried.ts"; | |
| 17 | import { carriedOrRebuild } from "../../core/carried.ts"; | |
| 18 | 18 | import { getIssueById } from "../../core/issues.ts"; |
| 19 | 19 | import { getPull, openPullsClosing } from "../../core/pulls.ts"; |
| 20 | 20 | import { canSeeOwnerFacts, type Repo } from "../../core/repos.ts"; |
| @@ -126,7 +126,7 @@ export async function runView( | ||
| 126 | 126 | const duration = durationText(run); |
| 127 | 127 | const all = ctx.url.searchParams.get("all") === "1"; |
| 128 | 128 | const held = listHeldSecrets(db, run.id); |
| 129 | const carried = carriedBy(db, run.id); | |
| 129 | const carried = await carriedOrRebuild(db, ctx.app.reposRoot, run); | |
| 130 | 130 | const logPath = `/api/v1/repos/${repo.ownerName}/${repo.name}/runs/${run.id}/log`; |
| 131 | 131 | |
| 132 | 132 | // The pull this run's tell has become, once one exists: the tell itself |
test/data-browser.test.ts +1
test/pages-budget.test.ts +1 −1
| @@ -39,7 +39,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = { | ||
| 39 | 39 | "/:owner/:name/issues/:number": { statements: 70 }, |
| 40 | 40 | "/:owner/:name/next": { statements: 64 }, |
| 41 | 41 | "/:owner/:name/pulls/:number": { statements: 111 }, // +1: the header Talk count (#10327); +1: the landing line (#10860); +1: whether a reviewer is seated, read only when Require review is off and the pull would otherwise wait on one; the page loads no crew besides (#11666) |
| 42 | "/board": { statements: 70 }, // +6: the money line (#510) — one settings read, then the month's and the 30 days' meter, storage and ledger reads; constant in the number of apps | |
| 42 | "/board": { statements: 71 }, // +1: vitals reads the database growth (#11973); +6: the money line (#510) — one settings read, then the month's and the 30 days' meter, storage and ledger reads; constant in the number of apps | |
| 43 | 43 | "/settings/capacity": { statements: 71 }, |
| 44 | 44 | }; |
| 45 | 45 |
test/retention.test.ts added +296
| @@ -0,0 +1,296 @@ | ||
| 1 | /** | |
| 2 | * The database keeps what it needs (#11973): each rule of `core/retention.ts` drops what it says | |
| 3 | * and | |
| 4 | * keeps what a reader can still reach, in batches that stop on their allowance; a deploy's carried | |
| 5 | * pulls dropped from the index come back from git; space is given back a step at a time; the forge | |
| 6 | * says how big it is. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { mergePull, openPull } from "../src/actions/pulls.ts"; | |
| 14 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 15 | import { carriedBy, carriedOrRebuild, recordCarried } from "../src/core/carried.ts"; | |
| 16 | import { CAPACITY, setCapacity } from "../src/core/capacity.ts"; | |
| 17 | import { getPull } from "../src/core/pulls.ts"; | |
| 18 | import { | |
| 19 | CHUNK, DEFAULTS, allowance, eventExpired, eventFate, giveBack, keepOf, pruneDeployPulls, pruneEvents, rules, thinSamples, | |
| 20 | } from "../src/core/retention.ts"; | |
| 21 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 22 | import { repoDir } from "../src/git/repos.ts"; | |
| 23 | import { duty } from "../src/maintain/duties/retention.ts"; | |
| 24 | import { duties } from "../src/maintain/registry.ts"; | |
| 25 | import { growthPerDay, measureDbSize, recordDay, sizeNeed } from "../src/system/db_size.ts"; | |
| 26 | import { dbSizeSection } from "../src/web/pages/system.ts"; | |
| 27 | import { dbFacts } from "../src/system/db_size.ts"; | |
| 28 | ||
| 29 | const DAY = 86_400_000; | |
| 30 | const NOW = Date.parse("2026-11-14T12:00:00.000Z"); | |
| 31 | const ago = (days: number): string => new Date(NOW - days * DAY).toISOString(); | |
| 32 | ||
| 33 | let dataDir: string; | |
| 34 | let app: App; | |
| 35 | let aliceId: string; | |
| 36 | const merged: number[] = []; | |
| 37 | let repoId: string; | |
| 38 | ||
| 39 | beforeAll(async () => { | |
| 40 | dataDir = await mkdtemp(join(tmpdir(), "forge-retention-")); | |
| 41 | app = createApp({ dataDir, port: 0 }); | |
| 42 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 43 | if (!made.ok) throw new Error(made.error); | |
| 44 | const alice = getUserByName(app.db, "alice")!; | |
| 45 | aliceId = alice.id; | |
| 46 | const created = await createRepo(app, alice, { name: "engine" }); | |
| 47 | if (!created.ok) throw new Error(String(created.error)); | |
| 48 | const repo = created.value; | |
| 49 | repoId = repo.id; | |
| 50 | const seeded = await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "# engine\n" }] }); | |
| 51 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 52 | for (const name of ["one", "two"]) { | |
| 53 | const branch = await commitToBranch(app, alice, repo, { branch: `feature/${name}`, base: "main", message: name, files: [{ path: `${name}.md`, content: `${name}\n` }] }); | |
| 54 | if (!branch.ok) throw new Error(JSON.stringify(branch.error)); | |
| 55 | const opened = await openPull(app, alice, repo, { title: name, body: "", baseBranch: "main", headBranch: `feature/${name}` }); | |
| 56 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 57 | const done = await mergePull(app, alice, repo, opened.value, "squash"); | |
| 58 | if (!done.ok) throw new Error(JSON.stringify(done.error)); | |
| 59 | merged.push(getPull(app.db, repo.id, opened.value.number)!.number); | |
| 60 | } | |
| 61 | }, 60_000); | |
| 62 | ||
| 63 | afterAll(async () => { | |
| 64 | app.close?.(); | |
| 65 | await rm(dataDir, { recursive: true, force: true }); | |
| 66 | }); | |
| 67 | ||
| 68 | const wide = () => allowance(performance.now(), 10_000, 1_000_000); | |
| 69 | ||
| 70 | describe("deploy_pull, an index over git", () => { | |
| 71 | const deploy = (id: string, days: number, oid = "") => | |
| 72 | app.db | |
| 73 | .query( | |
| 74 | `INSERT INTO run (id, repo_id, kind, env, commit_oid, state, serving_at, finished_at) | |
| 75 | VALUES (?1, ?2, 'deploy', 'production', ?3, 'ok', ?4, ?4)`, | |
| 76 | ) | |
| 77 | .run(id, repoId, oid, ago(days)); | |
| 78 | const rowsOf = (id: string): number => app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM deploy_pull WHERE run_id = ?1").get(id)!.n; | |
| 79 | const give = (id: string) => { | |
| 80 | for (const [i, n] of merged.entries()) | |
| 81 | app.db.query("INSERT OR IGNORE INTO deploy_pull (run_id, issue_id, pull_number, merged_oid) VALUES (?1, ?2, ?3, 'x')").run(id, `issue-${id}-${i}`, n); | |
| 82 | }; | |
| 83 | ||
| 84 | test("an old deploy's rows are dropped, the one an app serves now and a recent one keep theirs, and a deleted run's are dropped", () => { | |
| 85 | deploy("old", 100); | |
| 86 | deploy("serving-now", 99); | |
| 87 | for (const id of ["old", "serving-now", "orphan"]) give(id); | |
| 88 | const first = pruneDeployPulls(app.db, NOW, wide()); | |
| 89 | expect(first.finished).toBe(true); | |
| 90 | expect(rowsOf("old")).toBe(0); | |
| 91 | expect(rowsOf("orphan")).toBe(0); | |
| 92 | // The newest production deploy that served is what the app serves: its rows stay whatever its | |
| 93 | // age. | |
| 94 | expect(rowsOf("serving-now")).toBe(merged.length); | |
| 95 | deploy("recent", 2); | |
| 96 | give("recent"); | |
| 97 | pruneDeployPulls(app.db, NOW, wide()); | |
| 98 | expect(rowsOf("serving-now")).toBe(0); | |
| 99 | expect(rowsOf("recent")).toBe(merged.length); | |
| 100 | }); | |
| 101 | ||
| 102 | test("what was dropped is rebuilt from git, the same answer, and a recent deploy is not walked again", async () => { | |
| 103 | const head = (await Bun.$`git -C ${repoDir(app.reposRoot, "alice", "engine")} rev-parse main`.text()).trim(); | |
| 104 | deploy("rebuilt", 200, head); | |
| 105 | const before = await recordCarried(app.db, { runId: "rebuilt", repoId, commitOid: head, dir: repoDir(app.reposRoot, "alice", "engine") }); | |
| 106 | expect(before).toEqual(merged); | |
| 107 | pruneDeployPulls(app.db, NOW, wide()); | |
| 108 | expect(carriedBy(app.db, "rebuilt")).toEqual([]); | |
| 109 | const run = { id: "rebuilt", repoId, kind: "deploy", env: "production", state: "ok", commitOid: head }; | |
| 110 | expect(await carriedOrRebuild(app.db, app.reposRoot, run)).toEqual(merged); | |
| 111 | expect(carriedBy(app.db, "rebuilt")).toEqual(merged); | |
| 112 | // A run that is not a finished production deploy has no pulls to rebuild. | |
| 113 | expect(await carriedOrRebuild(app.db, app.reposRoot, { ...run, id: "none", env: "pull-3" })).toEqual([]); | |
| 114 | }); | |
| 115 | ||
| 116 | test("a batch stops on its row cap and the next one carries on from the cursor", () => { | |
| 117 | for (let i = 0; i < 6; i++) { | |
| 118 | deploy(`bulk-${i}`, 150 + i); | |
| 119 | give(`bulk-${i}`); | |
| 120 | } | |
| 121 | let batches = 0; | |
| 122 | for (;;) { | |
| 123 | batches++; | |
| 124 | const out = pruneDeployPulls(app.db, NOW, allowance(performance.now(), 10_000, 1)); | |
| 125 | if (out.finished || batches > 50) break; | |
| 126 | } | |
| 127 | expect(batches).toBeGreaterThan(1); | |
| 128 | for (let i = 0; i < 6; i++) expect(rowsOf(`bulk-${i}`)).toBe(0); | |
| 129 | }); | |
| 130 | }); | |
| 131 | ||
| 132 | describe("event", () => { | |
| 133 | const put = (id: string, kind: string, days: number) => | |
| 134 | app.db.query("INSERT INTO event (id, kind, repo_id, payload, created_at) VALUES (?1, ?2, ?3, '{}', ?4)").run(id, kind, repoId, ago(days)); | |
| 135 | beforeAll(() => void app.db.exec("DELETE FROM event")); | |
| 136 | const has = (id: string): boolean => app.db.query("SELECT 1 FROM event WHERE id = ?1").get(id) !== null; | |
| 137 | ||
| 138 | test("the fates: audit kinds are kept for ever, machine chatter goes first, the rest by the event rule", () => { | |
| 139 | expect(eventFate("account.role_set")).toBe("audit"); | |
| 140 | expect(eventFate("repo.deleted")).toBe("audit"); | |
| 141 | expect(eventFate("usage.delta")).toBe("chatter"); | |
| 142 | expect(eventFate("pull.merged")).toBe("ordinary"); | |
| 143 | expect(eventExpired("account.role_set", ago(5000), NOW, DEFAULTS)).toBe(false); | |
| 144 | expect(eventExpired("usage.delta", ago(31), NOW, DEFAULTS)).toBe(true); | |
| 145 | expect(eventExpired("usage.delta", ago(29), NOW, DEFAULTS)).toBe(false); | |
| 146 | expect(eventExpired("pull.merged", ago(300), NOW, DEFAULTS)).toBe(false); | |
| 147 | expect(eventExpired("pull.merged", ago(400), NOW, DEFAULTS)).toBe(true); | |
| 148 | }); | |
| 149 | ||
| 150 | test("each age is dropped or kept as its kind says, and a delivery goes with its event", () => { | |
| 151 | put("ev-audit-old", "token.created", 900); | |
| 152 | put("ev-ordinary-old", "pull.merged", 400); | |
| 153 | put("ev-ordinary-new", "pull.merged", 100); | |
| 154 | put("ev-chatter-old", "usage.delta", 40); | |
| 155 | put("ev-chatter-new", "usage.delta", 10); | |
| 156 | app.db.query("INSERT INTO webhook (id, repo_id, url) VALUES ('hook', ?1, 'http://127.0.0.1:9/x')").run(repoId); | |
| 157 | app.db.query("INSERT INTO webhook_delivery (id, webhook_id, event_id) VALUES ('del', 'hook', 'ev-ordinary-old')").run(); | |
| 158 | const out = pruneEvents(app.db, NOW, wide()); | |
| 159 | expect(out.finished).toBe(true); | |
| 160 | expect(has("ev-audit-old")).toBe(true); | |
| 161 | expect(has("ev-ordinary-old")).toBe(false); | |
| 162 | expect(has("ev-ordinary-new")).toBe(true); | |
| 163 | expect(has("ev-chatter-old")).toBe(false); | |
| 164 | expect(has("ev-chatter-new")).toBe(true); | |
| 165 | expect(app.db.query("SELECT 1 FROM webhook_delivery WHERE id = 'del'").get()).toBeNull(); | |
| 166 | }); | |
| 167 | ||
| 168 | test("a batch deletes at most a chunk once its row allowance is spent, and the walk finishes in later batches", () => { | |
| 169 | const many = app.db.transaction(() => { | |
| 170 | for (let i = 0; i < CHUNK * 2 + 10; i++) put(`ev-bulk-${i}`, "run.shard", 50); | |
| 171 | }); | |
| 172 | many(); | |
| 173 | const sizes: number[] = []; | |
| 174 | for (let i = 0; i < 10; i++) { | |
| 175 | const out = pruneEvents(app.db, NOW, allowance(performance.now(), 10_000, 1)); | |
| 176 | sizes.push(out.deleted); | |
| 177 | if (out.deleted === 0) break; | |
| 178 | } | |
| 179 | expect(Math.max(...sizes)).toBeLessThanOrEqual(CHUNK); | |
| 180 | expect(sizes.filter((n) => n > 0).length).toBeGreaterThanOrEqual(3); | |
| 181 | expect(has("ev-bulk-0")).toBe(false); | |
| 182 | expect(app.db.query("SELECT COUNT(*) AS n FROM event WHERE kind = 'run.shard'").get()).toEqual({ n: 0 }); | |
| 183 | }); | |
| 184 | ||
| 185 | test("one batch of the nightly job holds the write lock under 50 ms", () => { | |
| 186 | app.db.transaction(() => { | |
| 187 | for (let i = 0; i < 6000; i++) put(`ev-time-${i}`, "usage.delta", 60); | |
| 188 | })(); | |
| 189 | const started = performance.now(); | |
| 190 | const out = pruneEvents(app.db, NOW, allowance()); | |
| 191 | // The allowance is 40 ms and a chunk is 500 rows: a batch that ends past 50 ms is a chunk too | |
| 192 | // big. | |
| 193 | expect(performance.now() - started).toBeLessThan(50 + 40); | |
| 194 | expect(out.deleted).toBeGreaterThan(0); | |
| 195 | while (!pruneEvents(app.db, NOW, wide()).finished); | |
| 196 | }); | |
| 197 | }); | |
| 198 | ||
| 199 | describe("machine_sample", () => { | |
| 200 | const put = (at: string) => | |
| 201 | app.db.query("INSERT OR REPLACE INTO machine_sample (at, step, target, cpu_cores) VALUES (?1, 300, 'node', 1)").run(at); | |
| 202 | ||
| 203 | test("past the 5-minute window the history is thinned to the row at the top of each hour, and the window keeps every row", () => { | |
| 204 | const old = Date.parse("2026-10-01T00:00:00.000Z"); | |
| 205 | for (let m = 0; m < 180; m += 5) put(new Date(old + m * 60_000).toISOString()); | |
| 206 | const inWindow = new Date(NOW - 10 * DAY).toISOString().slice(0, 14) + "05:00.000Z"; | |
| 207 | put(inWindow); | |
| 208 | expect(thinSamples(app.db, NOW, wide()).finished).toBe(true); | |
| 209 | const left = app.db.query<{ at: string }, []>("SELECT at FROM machine_sample WHERE step = 300 AND at < '2026-10-02' ORDER BY at").all().map((r) => r.at); | |
| 210 | expect(left).toEqual(["2026-10-01T00:00:00.000Z", "2026-10-01T01:00:00.000Z", "2026-10-01T02:00:00.000Z"]); | |
| 211 | expect(app.db.query("SELECT 1 FROM machine_sample WHERE at = ?1").get(inWindow)).not.toBeNull(); | |
| 212 | }); | |
| 213 | ||
| 214 | test("the sampler's write keeps the raw window the rule says", () => { | |
| 215 | setCapacity(app.db, "retention.sample_fine_hours", "72", aliceId); | |
| 216 | expect(keepOf(app.db).fineMs).toBe(72 * 3_600_000); | |
| 217 | setCapacity(app.db, "retention.sample_fine_hours", null, aliceId); | |
| 218 | expect(keepOf(app.db).fineMs).toBe(48 * 3_600_000); | |
| 219 | }); | |
| 220 | }); | |
| 221 | ||
| 222 | describe("the rules", () => { | |
| 223 | test("the defaults in code are the settings' fallbacks, and an admin's setting wins", () => { | |
| 224 | expect(String(DEFAULTS.deployPullDays)).toBe(CAPACITY["retention.deploy_pull_days"].fallback); | |
| 225 | expect(String(DEFAULTS.eventDays)).toBe(CAPACITY["retention.event_days"].fallback); | |
| 226 | expect(String(DEFAULTS.chatterDays)).toBe(CAPACITY["retention.chatter_days"].fallback); | |
| 227 | expect(String(DEFAULTS.sampleFineHours)).toBe(CAPACITY["retention.sample_fine_hours"].fallback); | |
| 228 | expect(String(DEFAULTS.sampleCoarseDays)).toBe(CAPACITY["retention.sample_coarse_days"].fallback); | |
| 229 | expect(String(DEFAULTS.sampleHourlyDays)).toBe(CAPACITY["retention.sample_hourly_days"].fallback); | |
| 230 | expect(rules(app.db)).toEqual(DEFAULTS); | |
| 231 | setCapacity(app.db, "retention.chatter_days", "7", aliceId); | |
| 232 | expect(rules(app.db).chatterDays).toBe(7); | |
| 233 | setCapacity(app.db, "retention.chatter_days", null, aliceId); | |
| 234 | }); | |
| 235 | ||
| 236 | test("the duty is registered under one name and runs a batch", async () => { | |
| 237 | expect(duties.filter((d) => d.name === "retention")).toHaveLength(1); | |
| 238 | const out = await duty.run({ db: app.db, bus: app.bus, now: new Date(NOW), app }); | |
| 239 | expect(out.findings).toEqual([]); | |
| 240 | expect(app.db.query("SELECT 1 FROM db_size_day").get()).not.toBeNull(); | |
| 241 | }); | |
| 242 | }); | |
| 243 | ||
| 244 | describe("space given back", () => { | |
| 245 | test("a new database frees pages a step at a time", () => { | |
| 246 | expect(app.db.query<{ auto_vacuum: number }, []>("PRAGMA auto_vacuum").get()!.auto_vacuum).toBe(2); | |
| 247 | app.db.exec("CREATE TABLE bulk (x TEXT)"); | |
| 248 | app.db.transaction(() => { | |
| 249 | const ins = app.db.query("INSERT INTO bulk (x) VALUES (?1)"); | |
| 250 | for (let i = 0; i < 3000; i++) ins.run("x".repeat(1000)); | |
| 251 | })(); | |
| 252 | app.db.exec("DROP TABLE bulk"); | |
| 253 | const free = () => app.db.query<{ freelist_count: number }, []>("PRAGMA freelist_count").get()!.freelist_count; | |
| 254 | const before = free(); | |
| 255 | expect(before).toBeGreaterThan(500); | |
| 256 | const out = giveBack(app.db, allowance(performance.now(), 10_000, 1_000)); | |
| 257 | expect(out.mode).toBe("incremental"); | |
| 258 | expect(out.pages).toBeGreaterThan(0); | |
| 259 | expect(free()).toBeLessThan(before); | |
| 260 | }); | |
| 261 | }); | |
| 262 | ||
| 263 | describe("the forge knows its own size", () => { | |
| 264 | test("the heaviest tables and indexes are named, with rows and bytes, and the section says them", async () => { | |
| 265 | app.db.transaction(() => { | |
| 266 | for (let i = 0; i < 300; i++) app.db.query("INSERT INTO event (id, kind, payload, created_at) VALUES (?1, 'pull.merged', ?2, ?3)").run(`size-${i}`, JSON.stringify({ p: "p".repeat(500) }), ago(1)); | |
| 267 | })(); | |
| 268 | const size = await measureDbSize(app.db, dataDir, NOW); | |
| 269 | expect(size.tables.length).toBeLessThanOrEqual(10); | |
| 270 | expect(size.tables[0]!.name).toBe("event"); | |
| 271 | expect(size.tables[0]!.rows).toBeGreaterThanOrEqual(300); | |
| 272 | expect(size.tables[0]!.bytes).toBeGreaterThan(150_000); | |
| 273 | expect(size.indexes.length).toBeLessThanOrEqual(10); | |
| 274 | expect(size.indexCount).toBeGreaterThan(100); | |
| 275 | expect(size.fileBytes).toBeGreaterThan(0); | |
| 276 | const html = String(dbSizeSection({ ...dbFacts(app.db, dataDir), size })); | |
| 277 | expect(html).toContain('id="sys-db"'); | |
| 278 | expect(html).toContain("event"); | |
| 279 | }); | |
| 280 | ||
| 281 | test("growth per day is read from two daily readings, and a need names it past the set rate", () => { | |
| 282 | const row = (day: string, bytes: number) => | |
| 283 | app.db.query("INSERT OR REPLACE INTO db_size_day (day, file_bytes, free_bytes, top) VALUES (?1, ?2, 0, '[]')").run(day, bytes); | |
| 284 | app.db.exec("DELETE FROM db_size_day"); | |
| 285 | expect(growthPerDay(app.db)).toBeNull(); | |
| 286 | row("2026-11-12", 1_000_000_000); | |
| 287 | row("2026-11-14", 1_100_000_000); | |
| 288 | expect(growthPerDay(app.db)).toBe(50_000_000); | |
| 289 | expect(sizeNeed(app.db, dataDir)).toBeUndefined(); | |
| 290 | setCapacity(app.db, "size.growth_mb_per_day", "10", aliceId); | |
| 291 | expect(sizeNeed(app.db, dataDir)?.cause).toBe("db-growth"); | |
| 292 | setCapacity(app.db, "size.growth_mb_per_day", null, aliceId); | |
| 293 | recordDay(app.db, { at: "2026-11-15T00:00:00.000Z", fileBytes: 5, freeBytes: 0, autoVacuum: "none", tables: [], indexes: [], tableCount: 0, indexCount: 0 }); | |
| 294 | expect(app.db.query("SELECT file_bytes FROM db_size_day WHERE day = '2026-11-15'").get()).toEqual({ file_bytes: 5 }); | |
| 295 | }); | |
| 296 | }); |
test/system-parts.test.ts +1
test/vitals.test.ts +5 −2
| @@ -171,8 +171,11 @@ test("the number of queries does not grow with runs", () => { | ||
| 171 | 171 | if (i % 2) app.db.query("UPDATE run SET state='running' WHERE id=?1").run(r.id); |
| 172 | 172 | } |
| 173 | 173 | expect(count()).toBe(before); |
| 174 | // The queue, the running runs, the runs killed twice for their budget, the lane's depth and finished checks, the red mains holding pulls' checks, the tests red on many pulls, (the checks red on a full disk only while the disk is full), and the newest drill of every domain, the checks no red main holds, and the week's flake list. | |
| 175 | expect(before).toBe(10); | |
| 174 | // The queue, the running runs, the runs killed twice for their budget, the lane's depth and | |
| 175 | // finished checks, the red mains holding pulls' checks, the tests red on many pulls, (the checks | |
| 176 | // red on a full disk only while the disk is full), and the newest drill of every domain, the | |
| 177 | // checks no red main holds, and the week's flake list, and the database's growth (#11973). | |
| 178 | expect(before).toBe(11); | |
| 176 | 179 | }); |
| 177 | 180 | |
| 178 | 181 | test("errors are counted, bounded, redacted, and a burst is said", async () => { |
new above
offline