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

The restore drill restores one hosted forge from its backup file and proves its database and repositories open #14000

Closed opened this
Closed without merging

torque/forge:torque/13919-the-restore-drill-restores-one-hosted-fo → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +461 −14
docs/RECOVERY.md +5 −5
@@ -73,11 +73,9 @@ so by hand the sealed values are set again.
7373
7474 ## When the drill is red
7575
76 The weekly drill restores the newest snapshot into scratch and names where it
77 stopped: a step, and for `restore` a phase inside it. Each entry says what it
78 was doing, the likely cause, and the first thing to check. Whatever the step,
79 the next move is the same: run Route 1 by hand on a new directory and watch
80 which line it stops at.
76 The weekly drill restores the newest snapshot into scratch and names the step
77 it stopped at (for `restore`, a phase). Each entry gives the likely cause and
78 the first check; whatever the step, then run Route 1 by hand on a new directory.
8179
8280 ### Steps
8381
@@ -97,6 +95,8 @@ which line it stops at.
9795 - **health** — booting the restored forge and asking it for health. Likely a
9896 migration or config problem, or a boot slower than the limit. Boot it by
9997 hand as in Route 1 and read its log.
98 - **hosted** — restoring one hosted forge alone; the reason names it and its
99 step (`unpack`, `integrity`, `fsck`). Check: features/hosted-backup.md.
100100
101101 ### Restore phases
102102
docs/features/hosted-backup.md +9
@@ -26,3 +26,12 @@ Into an empty data directory; `children/<bodyId>/` and `spawn/<name>.json` are w
2626 bun run src/snapshot/restore.ts latest <data-dir> --forge <name>
2727
2828 A whole restore of the parent leaves `children/` out; restore each forge this way.
29
30 ## The weekly drill restores one
31
32 After the restore drill proves the parent's newest snapshot, it restores one hosted forge alone from the same snapshot into its scratch directory (#13919): the forge whose last green drill is oldest, one never drilled first (`<data>/drill/hosted.json` keeps the dates). Its database must answer `PRAGMA integrity_check` with `ok` and each repository must pass `git fsck --connectivity-only`; then the scratch is removed. It runs in the drill's own budget and only when every earlier step passed.
33
34 - Web: open `/settings/backups` and press Run a drill. Terminal: the Resilience screen, `r` then `y`; its "Last drill:" line under the verdict says the same words as the card.
35 - Green: the Backups card says "Hosted forge NAME (SIZE) restored in N.N s: its database passed integrity_check and its K repositories git fsck."
36 - Red: the drill fails at `hosted`, its reason naming the forge and the step (`unpack`, `integrity` or `fsck`) and the cause; it is paged once, like every red drill, and the same forge is tried again on the next drill. Restore it by hand with `--forge NAME` as above and check the step that failed.
37 - No hosted forge whole in the snapshot: one line says the hosted restore was skipped, and the drill stays green.
src/snapshot/drill.ts +36 −3
@@ -3,7 +3,9 @@
33 * takes the newest snapshot, restores it into a fresh directory, opens the
44 * database read-only, counts what is in it, opens one sealed value with the
55 * restored key, boots the restored directory on a side port and reads
6 * `/api/v1/health` and `/`, and removes the directory whatever happened.
6 * `/api/v1/health` and `/`, then restores one hosted forge alone from the same
7 * snapshot and checks its database and repositories (`hosted_drill.ts`,
8 * #13919), and removes the directory whatever happened.
79 *
810 * Plain data out: when it ran, which snapshot, how long, what it counted,
911 * and a verdict. A red verdict names the step that failed; a step that
@@ -20,6 +22,7 @@ import { forgetKey, open } from "../kernel/secret.ts";
2022 import { countRows, mismatched, type DrillCounts } from "./counts.ts";
2123 import { restoreSnapshot, type Progress } from "./restore.ts";
2224 import { isOffBox } from "./off_box.ts";
25 import { drillHosted, type HostedDrill } from "./hosted_drill.ts";
2326 import { listSnapshots } from "./snapshot.ts";
2427 import type { Store } from "./store.ts";
2528
@@ -133,7 +136,7 @@ export interface PhaseTime {
133136 readonly ms: number;
134137 }
135138
136 export type DrillStep = "fetch" | "restore" | "open" | "count" | "unseal" | "health";
139 export type DrillStep = "fetch" | "restore" | "open" | "count" | "unseal" | "health" | "hosted";
137140
138141 export interface DrillDeps {
139142 readonly store: Store;
@@ -182,6 +185,11 @@ export interface DrillResult {
182185 * process.
183186 */
184187 readonly cost?: DrillCost | undefined;
188 /**
189 * The hosted forge it restored alone and checked, or why none (#13919); absent when the drill
190 * failed before that step, or on drills kept before it.
191 */
192 readonly hosted?: HostedDrill | undefined;
185193 }
186194
187195 /** The drill process's wall time and peak resident memory, and the memory limit it ran under. */
@@ -243,7 +251,9 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
243251 const began: { phase: Progress["phase"]; at: number }[] = [];
244252 let restoreEnd: number | undefined;
245253 let bootStart: number | undefined;
254 let bootEnd: number | undefined;
246255 let health: DrillResult["health"] = "unreached";
256 let hosted: HostedDrill | undefined;
247257 try {
248258 // One clock for the whole drill, so a hang in any step ends it red.
249259 const left = (): number => Math.max(1, started + budgetMs - tick());
@@ -333,6 +343,27 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
333343 );
334344 health = booted.ok ? "ok" : "failed";
335345 if (!booted.ok) throw new Error(booted.reason);
346
347 // One hosted forge restored alone and checked, in the same budget; never one when the parent
348 // failed, so the first failure is the one named.
349 bootEnd = tick();
350 step = "hosted";
351 hosted = await within(
352 drillHosted({
353 store,
354 snapshot: newest.name,
355 hosted: newest.hosted,
356 dataDir: deps.dataDir,
357 scratch: join(scratch, "hosted"),
358 passphrase: deps.passphrase,
359 left,
360 ticks: tick,
361 now: clock,
362 }),
363 left(),
364 budget,
365 );
366 if (hosted.ran && hosted.failedStep !== null) throw new Error(hosted.reason ?? `hosted forge ${hosted.name}: ${hosted.failedStep} failed`);
336367 } catch (error) {
337368 reason =
338369 error instanceof StepTimeout && step === "restore" && progress !== undefined
@@ -346,6 +377,7 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
346377 } finally {
347378 if (scratch !== undefined) {
348379 forgetKey(join(scratch, "data"));
380 forgetKey(join(scratch, "hosted"));
349381 rmSync(scratch, { recursive: true, force: true });
350382 }
351383 }
@@ -361,7 +393,7 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
361393 if (restoreEnd !== undefined) {
362394 const now = tick();
363395 phases.push({ phase: "open", ms: Math.round((bootStart ?? now) - restoreEnd) });
364 if (bootStart !== undefined) phases.push({ phase: "boot", ms: Math.round(now - bootStart) });
396 if (bootStart !== undefined) phases.push({ phase: "boot", ms: Math.round((bootEnd ?? now) - bootStart) });
365397 }
366398 return {
367399 at,
@@ -377,6 +409,7 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
377409 from: deps.store.where,
378410 offSite: isOffBox(deps.store),
379411 ...(format === undefined ? {} : { format }),
412 ...(hosted === undefined ? {} : { hosted }),
380413 };
381414 }
382415 }
src/snapshot/drills.ts +13
@@ -6,6 +6,7 @@
66
77 import type { Database } from "bun:sqlite";
88 import type { DrillCost, DrillResult, DrillStep, PhaseTime } from "./drill.ts";
9 import { parseHostedDrill, type HostedDrill } from "./hosted_drill.ts";
910
1011 interface Row {
1112 at: string;
@@ -39,6 +40,16 @@ export function parseFrom(raw: string | null): { from?: string; offSite?: boolea
3940 }
4041 }
4142
43 /** A kept drill's hosted step (#13919); absent when it kept none or it is not ours. */
44 export function parseHosted(raw: string | null): { hosted?: HostedDrill } {
45 try {
46 const h = parseHostedDrill((JSON.parse(raw ?? "null") as { hosted?: unknown } | null)?.hosted);
47 return h === undefined ? {} : { hosted: h };
48 } catch {
49 return {};
50 }
51 }
52
4253 /**
4354 * A kept drill's cost (#13253); absent when it kept none, or any of it is not a whole, finite,
4455 * non-negative number.
@@ -102,6 +113,7 @@ export function recordDrill(db: Database, result: DrillResult): void {
102113 budgetMs: result.budgetMs,
103114 ...(result.from === undefined ? {} : { from: result.from, offSite: result.offSite === true }),
104115 ...(result.format === undefined ? {} : { format: result.format }),
116 ...(result.hosted === undefined ? {} : { hosted: result.hosted }),
105117 ...(result.cost === undefined
106118 ? {}
107119 : { cost: { elapsedMs: Math.round(result.cost.elapsedMs), peakBytes: Math.round(result.cost.peakBytes), limitBytes: Math.round(result.cost.limitBytes) } }),
@@ -146,5 +158,6 @@ function asResult(row: Row | null): DrillResult | undefined {
146158 budgetMs: kept.budgetMs,
147159 ...parseFrom(row.phases),
148160 ...parseCost(row.phases),
161 ...parseHosted(row.phases),
149162 };
150163 }
src/snapshot/hosted_drill.ts added +185
@@ -0,0 +1,185 @@
1 /**
2 * The restore drill's hosted step (#13919): one hosted forge a week is restored alone from the
3 * snapshot the drill just proved, the forge whose last good drill is oldest (one never drilled
4 * first), into the drill's scratch directory. Its database must answer `PRAGMA integrity_check`
5 * with `ok` (https://sqlite.org/pragma.html#pragma_integrity_check) and each repository must pass
6 * `git fsck --connectivity-only` (every ref reaches whole history; blobs are not re-hashed, which
7 * the snapshot's SHA-256 per file already did). The first step that fails ends it, named.
8 *
9 * When each forge last drilled green is kept in `<data>/drill/hosted.json`, a map of name to ISO
10 * instant. A red forge keeps its old date, so the next drill tries the same forge again until it
11 * passes.
12 */
13
14 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
15 import { join } from "node:path";
16 import { runGit } from "../git/env.ts";
17 import { forgetKey } from "../kernel/secret.ts";
18 import type { HostedEntry } from "./hosted.ts";
19 import { restoreHosted } from "./restore.ts";
20 import type { Store } from "./store.ts";
21
22 /** Where a hosted restore failed: its files coming back, its database, or a repository. */
23 export type HostedStep = "unpack" | "integrity" | "fsck";
24 export const HOSTED_STEPS: readonly HostedStep[] = ["unpack", "integrity", "fsck"];
25
26 /** The hosted step as plain data: one forge restored (green or red), or skipped and why. */
27 export type HostedDrill =
28 | { readonly ran: false; readonly says: string }
29 | {
30 readonly ran: true;
31 readonly name: string;
32 /** Its size as the snapshot kept it, bytes. */
33 readonly bytes: number;
34 /** From the start of its restore to the end of its checks, ms. */
35 readonly ms: number;
36 readonly repos: number;
37 readonly failedStep: HostedStep | null;
38 readonly reason: string | null;
39 };
40
41 const NAME = /^[a-z0-9-]{1,40}$/;
42 const drilledFile = (dataDir: string): string => join(dataDir, "drill", "hosted.json");
43
44 /** When each hosted forge last drilled green; a missing or unreadable file is none. */
45 export function readDrilled(dataDir: string): Record<string, string> {
46 try {
47 const v: unknown = JSON.parse(readFileSync(drilledFile(dataDir), "utf8"));
48 if (typeof v !== "object" || v === null || Array.isArray(v)) return {};
49 const out: Record<string, string> = {};
50 for (const [k, at] of Object.entries(v)) if (NAME.test(k) && typeof at === "string" && Number.isFinite(Date.parse(at))) out[k] = at;
51 return out;
52 } catch {
53 return {};
54 }
55 }
56
57 /** Keep `name` as drilled green at `at`. */
58 export function noteDrilled(dataDir: string, name: string, at: string): void {
59 const all = { ...readDrilled(dataDir), [name]: at };
60 mkdirSync(join(dataDir, "drill"), { recursive: true });
61 const tmp = `${drilledFile(dataDir)}.tmp`;
62 writeFileSync(tmp, JSON.stringify(all));
63 renameSync(tmp, drilledFile(dataDir));
64 }
65
66 /**
67 * The forge to drill: of those the snapshot kept whole, one never drilled, else the oldest
68 * drilled; ties go by name. Undefined when the snapshot kept none whole.
69 */
70 export function pickHosted(hosted: readonly HostedEntry[] | undefined, drilled: Readonly<Record<string, string>>): HostedEntry | undefined {
71 const whole = (hosted ?? []).filter((h) => h.why === undefined && NAME.test(h.name));
72 const when = (h: HostedEntry): number => {
73 const at = drilled[h.name];
74 return at === undefined ? -Infinity : Date.parse(at);
75 };
76 return [...whole].sort((a, b) => when(a) - when(b) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))[0];
77 }
78
79 /** The one line a drill says when it has no hosted forge to restore. */
80 export function skipWords(hosted: readonly HostedEntry[] | undefined): string {
81 const left = (hosted ?? []).filter((h) => h.why !== undefined).length;
82 return left === 0
83 ? "No hosted forges in this snapshot; the hosted restore was skipped."
84 : `No hosted forge is whole in this snapshot (${left} left out); the hosted restore was skipped.`;
85 }
86
87 /** Throws unless the database at `path` reads and `PRAGMA integrity_check` answers `ok`. */
88 export async function checkDatabase(path: string): Promise<void> {
89 const { Database } = await import("bun:sqlite");
90 let db: InstanceType<typeof Database> | undefined;
91 try {
92 db = new Database(path, { readonly: true });
93 // At most 5 problems listed: the first names the cause.
94 const rows = db.query<{ integrity_check: string }, []>("PRAGMA integrity_check(5)").all();
95 const said = rows.map((r) => r.integrity_check);
96 if (said.length !== 1 || said[0] !== "ok") throw new Error(said.join("; ").slice(0, 200) || "no answer");
97 } catch (error) {
98 throw new Error(`its database fails PRAGMA integrity_check: ${error instanceof Error ? error.message : String(error)}`);
99 } finally {
100 db?.close();
101 }
102 }
103
104 /** Throws unless `git fsck --connectivity-only` passes in the repository at `dir`. */
105 export async function checkRepo(dir: string, label: string, timeoutMs: number, git: typeof runGit = runGit): Promise<void> {
106 const r = await git(["fsck", "--connectivity-only", "--no-progress"], { cwd: dir, timeoutMs: Math.max(1_000, timeoutMs) });
107 if (!r.ok) throw new Error(`${label} fails git fsck --connectivity-only: ${r.error.stderr.trim().split("\n")[0]?.slice(0, 200) || `exit ${r.error.code}`}`);
108 }
109
110 export interface HostedDrillDeps {
111 readonly store: Store;
112 readonly snapshot: string;
113 readonly hosted: readonly HostedEntry[] | undefined;
114 readonly dataDir: string;
115 /** An empty or missing directory inside the drill's scratch; it is the caller's to remove. */
116 readonly scratch: string;
117 readonly passphrase?: string | undefined;
118 /** What is left of the drill's budget, ms. */
119 readonly left: () => number;
120 readonly ticks: () => number;
121 readonly now: () => Date;
122 readonly git?: typeof runGit | undefined;
123 }
124
125 /**
126 * Restore and check one hosted forge. Never throws: a failure is a red `HostedDrill` naming the
127 * forge, the step and its cause. The caller bounds it in time.
128 */
129 export async function drillHosted(deps: HostedDrillDeps): Promise<HostedDrill> {
130 const pick = pickHosted(deps.hosted, readDrilled(deps.dataDir));
131 if (pick === undefined) return { ran: false, says: skipWords(deps.hosted) };
132 const started = deps.ticks();
133 let step: HostedStep = "unpack";
134 let repos = 0;
135 const end = (failedStep: HostedStep | null, reason: string | null): HostedDrill => ({
136 ran: true,
137 name: pick.name,
138 bytes: pick.bytes,
139 ms: Math.round(deps.ticks() - started),
140 repos,
141 failedStep,
142 reason,
143 });
144 try {
145 const got = await restoreHosted(deps.store, deps.snapshot, pick.name, deps.scratch, { passphrase: deps.passphrase, git: deps.git });
146 repos = got.repos;
147 step = "integrity";
148 await checkDatabase(join(got.dir, "forge.db"));
149 step = "fsck";
150 for (const dir of got.repoDirs) {
151 const label = dir.slice(join(got.dir, "repos").length + 1).replace(/\.git$/, "");
152 await checkRepo(dir, label, deps.left(), deps.git);
153 }
154 } catch (error) {
155 return end(step, `hosted forge ${pick.name}: ${step} failed: ${error instanceof Error ? error.message : String(error)}`);
156 } finally {
157 forgetKey(deps.scratch);
158 }
159 noteDrilled(deps.dataDir, pick.name, deps.now().toISOString());
160 return end(null, null);
161 }
162
163 /** The card's words for the hosted step: "Hosted forge kid (1.2 MiB) restored in 3.4 s, …". */
164 export function hostedDrillWords(h: HostedDrill, size: (bytes: number) => string): string {
165 if (!h.ran) return h.says;
166 const secs = `${(h.ms / 1_000).toFixed(1)} s`;
167 const head = `Hosted forge ${h.name} (${size(h.bytes)})`;
168 if (h.failedStep === null)
169 return `${head} restored in ${secs}: its database passed integrity_check and its ${h.repos} repositor${h.repos === 1 ? "y" : "ies"} git fsck.`;
170 return `${head} failed at ${h.failedStep} after ${secs}.`;
171 }
172
173 /** A kept hosted step as plain data, or undefined when it is not one of ours. */
174 export function parseHostedDrill(v: unknown): HostedDrill | undefined {
175 if (typeof v !== "object" || v === null) return undefined;
176 const o = v as Record<string, unknown>;
177 if (o["ran"] === false) return typeof o["says"] === "string" ? { ran: false, says: o["says"].slice(0, 300) } : undefined;
178 if (o["ran"] !== true) return undefined;
179 const num = (x: unknown): x is number => typeof x === "number" && Number.isFinite(x) && x >= 0;
180 const { name, bytes, ms, repos, failedStep, reason } = o;
181 if (typeof name !== "string" || !NAME.test(name) || !num(bytes) || !num(ms) || !num(repos)) return undefined;
182 if (failedStep !== null && !HOSTED_STEPS.includes(failedStep as HostedStep)) return undefined;
183 if (reason !== null && typeof reason !== "string") return undefined;
184 return { ran: true, name, bytes, ms, repos, failedStep: failedStep as HostedStep | null, reason: reason as string | null };
185 }
src/snapshot/restore.ts +5 −1
@@ -603,6 +603,8 @@ export interface RestoredHosted {
603603 readonly ledger: string;
604604 readonly files: number;
605605 readonly repos: number;
606 /** Each repository it cloned back, as a directory under `dir` (the drill checks each; #13919). */
607 readonly repoDirs: readonly string[];
606608 readonly key: "restored" | "missing";
607609 }
608610
@@ -645,8 +647,10 @@ export async function restoreHosted(
645647 const files = mine.filter((f) => f.path !== "ledger.json" && f.path !== WRAPPED_KEY);
646648 const got = await fetchChunked(store, snapshot, files, dir, () => {});
647649 const git = options.git ?? runGit;
650 const repoDirs: string[] = [];
648651 for (const b of got.bundles) {
649652 const to = repoDir(join(dir, "repos"), b.owner, b.name);
653 repoDirs.push(to);
650654 mkdirSync(dirname(to), { recursive: true });
651655 const cloned = await git(["clone", "--quiet", "--mirror", b.file, to]);
652656 if (!cloned.ok) throw new Error(`could not restore ${b.owner}/${b.name}: ${cloned.error.stderr}`);
@@ -659,7 +663,7 @@ export async function restoreHosted(
659663 await Bun.write(join(dir, "secret.key"), key);
660664 chmodSync(join(dir, "secret.key"), 0o600);
661665 }
662 return { name: forge, dir, ledger: ledgerText, files: got.files, repos: got.bundles.length, key: key === undefined ? "missing" : "restored" };
666 return { name: forge, dir, ledger: ledgerText, files: got.files, repos: got.bundles.length, repoDirs, key: key === undefined ? "missing" : "restored" };
663667 }
664668
665669 /**
src/snapshot/verdict.ts +4 −2
@@ -9,9 +9,10 @@
99
1010 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1111 import { join } from "node:path";
12 import { describeTimes, formatMinutes, formatSpan, timeByPart, type DrillResult, type DrillStep } from "./drill.ts";
12 import { hostedDrillWords } from "./hosted_drill.ts";
13 import { describeTimes, formatBytes, formatMinutes, formatSpan, timeByPart, type DrillResult, type DrillStep } from "./drill.ts";
1314
14 const STEPS: readonly DrillStep[] = ["fetch", "restore", "open", "count", "unseal", "health"];
15 const STEPS: readonly DrillStep[] = ["fetch", "restore", "open", "count", "unseal", "health", "hosted"];
1516
1617 const lastFile = (dataDir: string): string => join(dataDir, "drill", "last.json");
1718
@@ -168,6 +169,7 @@ export function verdictComment(r: DrillResult): string {
168169 `- users: ${r.counts.users}`,
169170 `- pulls: ${r.counts.pulls}`,
170171 `- apps: ${r.counts.apps}`,
172 ...(r.hosted === undefined ? [] : [`- hosted: ${hostedDrillWords(r.hosted, formatBytes)}`]),
171173 ...(pass || !r.reason ? [] : [`- why: ${r.reason}`]),
172174 ].join("\n");
173175 }
src/tui/screens/resilience.ts +13 −1
@@ -42,7 +42,10 @@ import { nightlyLines } from "../../nightly/says.ts";
4242 import { hostedWords, keptWords, readHosted } from "../../snapshot/hosted.ts";
4343 import { backupsLine } from "../../snapshot/backups_line.ts";
4444 import { backupVerdict } from "../../snapshot/bucket.ts";
45 import type { Database } from "bun:sqlite";
46 import { formatBytes } from "../../snapshot/drill.ts";
4547 import { lastDrill } from "../../snapshot/drills.ts";
48 import { hostedDrillWords } from "../../snapshot/hosted_drill.ts";
4649 import { resolveSnapshots } from "../../snapshot/destination.ts";
4750 import { bodiesOf } from "../../snapshot/store.ts";
4851 import { snapshotsOf } from "../../snapshot/service.ts";
@@ -122,6 +125,15 @@ export function verdictLines(f: Session): string[] {
122125 ];
123126 }
124127
128 /**
129 * The hosted forge the last drill restored alone (#13919), in the Backups card's words: its name,
130 * size and seconds, the step it failed at, or that it was skipped; none when that drill kept none.
131 */
132 export function hostedDrillLines(db: Database): string[] {
133 const h = lastDrill(db)?.hosted;
134 return h === undefined ? [] : wrap(`Last drill: ${hostedDrillWords(h, formatBytes)}`, INNER);
135 }
136
125137 const STEPS: readonly { key: keyof DestinationInput; label: string; placeholder?: string; mask?: true }[] = [
126138 { key: "endpoint", label: "Endpoint, an http(s) URL", placeholder: "https://s3.example.com" },
127139 { key: "bucket", label: "Bucket" },
@@ -303,7 +315,7 @@ export function resilienceScreen(f: Session, ctx: Ctx): Screen {
303315 // A refusal or a result of a change stays up here too, above where a prompt opens over the
304316 // middle.
305317 if (note !== "") out.push(...wrap(note, INNER), "");
306 out.push(...wrap(backupsLine(f.app).says, INNER), ...verdictLines(f), "");
318 out.push(...wrap(backupsLine(f.app).says, INNER), ...verdictLines(f), ...hostedDrillLines(f.app.db), "");
307319 // Hosted forges in the nightly snapshot, as of the last one taken here (#13819).
308320 const kept = readHosted(f.app.config.dataDir);
309321 if (kept !== undefined) {
src/web/pages/backups.ts +5 −2
@@ -31,6 +31,7 @@ import { lastDrill } from "../../snapshot/drills.ts";
3131 import { backupVerdict } from "../../snapshot/bucket.ts";
3232 import { bodiesOf, type Store } from "../../snapshot/store.ts";
3333 import { hostedWords } from "../../snapshot/hosted.ts";
34 import { hostedDrillWords } from "../../snapshot/hosted_drill.ts";
3435 import { snapshotsOf, type SnapshotsHandle } from "../../snapshot/service.ts";
3536 import { drillStatus, mirrorNow, snapshotNow, startDrillNow } from "../../actions/backups_now.ts";
3637 import { lastSnapshotOutcome } from "../../snapshot/outcome.ts";
@@ -132,6 +133,8 @@ function drillLine(ctx: Ctx): Html {
132133 d === undefined
133134 ? ""
134135 : html`<dl class="status-rows" id="drill-cost">${costFacts(d).map((f) => html`<div class="status-row"><dt>${f.label}</dt><dd>${f.value}</dd></div>`)}</dl>`;
136 // The hosted forge it restored alone, by name, size and seconds (#13919).
137 const hosted = d?.hosted === undefined ? "" : html` <span data-drill-hosted>${hostedDrillWords(d.hosted, formatBytes)}</span>`;
135138 const line =
136139 d === undefined
137140 ? html`<p class="break">No restore drill has run yet.</p>`
@@ -139,7 +142,7 @@ function drillLine(ctx: Ctx): Html {
139142 ? html`<p class="break">
140143 ${badge("Ready", { tone: "success", icon: "check" })} Last drill: ${time(d.at)}, ${d.ms} ms, all counts matched —
141144 snapshot <code>${d.snapshotId ?? ""}</code>, key opened —
142 ${d.counts.users} users, ${d.counts.repositories} repositories, ${d.counts.issues} issues, ${d.counts.pulls} pulls, ${d.counts.apps} apps.${timing
145 ${d.counts.users} users, ${d.counts.repositories} repositories, ${d.counts.issues} issues, ${d.counts.pulls} pulls, ${d.counts.apps} apps.${hosted}${timing
143146 ? html` <span class="muted small">${timing}.</span>`
144147 : ""}
145148 </p>`
@@ -148,7 +151,7 @@ function drillLine(ctx: Ctx): Html {
148151 <code>${d.snapshotId ?? "none"}</code> failed at
149152 ${d.failedStep ?? "an unknown step"} after ${d.ms} ms${d.reason
150153 ? html`: ${d.reason}`
151 : ""}.${timing ? html` <span class="muted small">${timing}.</span>` : ""}
154 : ""}.${hosted}${timing ? html` <span class="muted small">${timing}.</span>` : ""}
152155 </p>`;
153156 const running = snapshotsOf(ctx.app)?.drillState();
154157 const says = drillStatus(ctx.app);
test/drill-hosted.test.ts added +185
@@ -0,0 +1,185 @@
1 /**
2 * The restore drill restores one hosted forge alone (#13919): from the snapshot it drilled, the
3 * forge drilled longest ago is restored into the drill's scratch, its database passes
4 * `PRAGMA integrity_check` and each repository `git fsck --connectivity-only`. A corrupted file is
5 * a red drill naming the forge and the step; no hosted forge is one line, and the drill stays
6 * green.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
10 import { rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { formatBytes, runDrill } from "../src/snapshot/drill.ts";
17 import { lastDrill, recordDrill } from "../src/snapshot/drills.ts";
18 import { checkDatabase, checkRepo, hostedDrillWords, noteDrilled, pickHosted, readDrilled, skipWords } from "../src/snapshot/hosted_drill.ts";
19 import { chunkKey } from "../src/snapshot/chunks.ts";
20 import { takeSnapshot } from "../src/snapshot/snapshot.ts";
21 import { dirStore } from "../src/snapshot/store.ts";
22 import { hostedDrillLines } from "../src/tui/screens/resilience.ts";
23 import { failedSentence, verdictComment } from "../src/snapshot/verdict.ts";
24
25 const PASS = "correct horse battery staple";
26 const AT = new Date("2026-11-16T03:00:00Z");
27
28 describe("the drill's hosted restore", () => {
29 let root: string;
30 let parent: App;
31 let lonely: App;
32 let child: App;
33 let n = 0;
34
35 beforeAll(async () => {
36 root = mkdtempSync(join(tmpdir(), "forge-drill-hosted-"));
37 parent = createApp({ dataDir: join(root, "parent"), port: 0 });
38 lonely = createApp({ dataDir: join(root, "lonely"), port: 0 });
39 child = createApp({ dataDir: join(root, "parent", "children", "body1"), port: 0 });
40 const u = await createUser(child.db, { origin: "seed", trusted: true, username: "glint", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
41 if (!u.ok) throw new Error(u.error);
42 const repo = await createRepo(child, u.value, { name: "work", visibility: "private" });
43 if (!repo.ok) throw new Error(String(repo.error));
44 const c = await commitToBranch(child, u.value, repo.value, { message: "hosted work", files: [{ path: "a.txt", content: "kept\n" }] });
45 if (!c.ok) throw new Error(JSON.stringify(c.error));
46 writeFileSync(join(child.config.dataDir, "secret.key"), "k".repeat(32), { mode: 0o600 });
47 mkdirSync(join(root, "parent", "spawn"), { recursive: true });
48 writeFileSync(join(root, "parent", "spawn", "kid.json"), JSON.stringify({ name: "kid", bodyId: "body1", done: true }));
49 });
50
51 afterAll(async () => {
52 child.close();
53 lonely.close();
54 parent.close();
55 await rm(root, { recursive: true, force: true });
56 });
57
58 /** A fresh store holding one snapshot of `of`, and a fresh drill data directory. */
59 const take = async (of: App) => {
60 const store = dirStore(join(root, `store-${++n}`));
61 const manifest = await takeSnapshot({ db: of.db, dataDir: of.config.dataDir, reposRoot: of.reposRoot, version: "t", passphrase: PASS }, store, AT);
62 return { store, manifest, dataDir: join(root, `drill-${n}`) };
63 };
64 const drill = (store: ReturnType<typeof dirStore>, dataDir: string) =>
65 runDrill({ store, dataDir, passphrase: PASS, boot: async () => ({ ok: true, reason: "" }), now: () => new Date("2026-11-16T09:00:00Z") });
66 const scratchLeft = (dataDir: string): string[] => readdirSync(join(dataDir, "drill")).filter((f) => f.startsWith("restore-"));
67
68 test("a fixture forge's file restores alone, its database and repository check, and it is green", async () => {
69 const { store, dataDir } = await take(parent);
70 const r = await drill(store, dataDir);
71 expect(r.reason).toBeNull();
72 expect(r.verdict).toBe("green");
73 expect(r.hosted).toMatchObject({ ran: true, name: "kid", repos: 1, failedStep: null, reason: null });
74 expect(r.hosted?.ran === true && r.hosted.bytes).toBeGreaterThan(0);
75 // Drilled green: kept, so the next drill takes the forge drilled longest ago.
76 expect(readDrilled(dataDir)).toEqual({ kid: "2026-11-16T09:00:00.000Z" });
77 expect(scratchLeft(dataDir)).toEqual([]);
78 // The card: name, size, seconds.
79 expect(hostedDrillWords(r.hosted!, formatBytes)).toMatch(/^Hosted forge kid \([0-9.]+ (KiB|MiB)\) restored in [0-9]+\.[0-9] s: its database passed integrity_check and its 1 repository git fsck\.$/);
80 expect(verdictComment(r)).toContain("- hosted: Hosted forge kid (");
81 });
82
83 test("a corrupted file is a red drill naming the forge and the step, and the forge is tried again next", async () => {
84 const { store, manifest, dataDir } = await take(parent);
85 // Spoil the chunks only the hosted forge's database holds.
86 const others = new Set(manifest.files.filter((f) => f.path !== "children/kid/forge.db").flatMap((f) => f.chunks ?? []));
87 const own = (manifest.files.find((f) => f.path === "children/kid/forge.db")?.chunks ?? []).filter((c) => !others.has(c));
88 expect(own.length).toBeGreaterThan(0);
89 for (const c of own) await store.put(chunkKey(c), new TextEncoder().encode("not the chunk it was"));
90 const r = await drill(store, dataDir);
91 expect(r.verdict).toBe("red");
92 expect(r.failedStep).toBe("hosted");
93 expect(r.health).toBe("ok");
94 expect(r.hosted).toMatchObject({ ran: true, name: "kid", failedStep: "unpack" });
95 expect(r.reason).toStartWith("hosted forge kid: unpack failed: ");
96 expect(failedSentence(r)).toStartWith("The restore drill failed at hosted: hosted forge kid: unpack failed: ");
97 expect(hostedDrillWords(r.hosted!, formatBytes)).toMatch(/^Hosted forge kid \(.+\) failed at unpack after [0-9]+\.[0-9] s\.$/);
98 expect(readDrilled(dataDir)).toEqual({});
99 expect(scratchLeft(dataDir)).toEqual([]);
100 });
101
102 test("with no hosted forges the step is skipped in one line and the drill stays green", async () => {
103 const { store, dataDir } = await take(lonely);
104 const r = await drill(store, dataDir);
105 expect(r.verdict).toBe("green");
106 expect(r.hosted).toEqual({ ran: false, says: "No hosted forges in this snapshot; the hosted restore was skipped." });
107 });
108
109 test("a drill that failed before it restores no hosted forge", async () => {
110 const { store, dataDir } = await take(parent);
111 const r = await runDrill({ store, dataDir, passphrase: PASS, boot: async () => ({ ok: false, reason: "it would not start" }) });
112 expect(r.failedStep).toBe("health");
113 expect(r.hosted).toBeUndefined();
114 });
115
116 test("the kept drill carries its hosted step", async () => {
117 const { store, dataDir } = await take(parent);
118 const r = await drill(store, dataDir);
119 recordDrill(parent.db, r);
120 expect(lastDrill(parent.db)?.hosted).toEqual(r.hosted);
121 // The terminal's Resilience screen says the same line the Backups card does.
122 const said = hostedDrillLines(parent.db).join(" ").replace(/\s+/g, " ");
123 expect(said).toStartWith("Last drill: Hosted forge kid (");
124 expect(said).toContain("restored in ");
125 });
126 });
127
128 describe("which forge, and the checks", () => {
129 const e = (name: string, why?: string) => ({ name, at: "2026-11-16T03:00:00Z", repos: 0, bytes: 1, key: "none" as const, ...(why ? { why } : {}) });
130
131 test("one never drilled goes first, then the oldest drilled; a forge left out is never picked", () => {
132 expect(pickHosted([e("a"), e("b")], { a: "2026-11-01T00:00:00Z" })?.name).toBe("b");
133 expect(pickHosted([e("a"), e("b")], { a: "2026-11-01T00:00:00Z", b: "2026-11-08T00:00:00Z" })?.name).toBe("a");
134 expect(pickHosted([e("b"), e("a")], {})?.name).toBe("a");
135 expect(pickHosted([e("a", "too big")], {})).toBeUndefined();
136 expect(pickHosted(undefined, {})).toBeUndefined();
137 expect(skipWords([e("a", "too big")])).toBe("No hosted forge is whole in this snapshot (1 left out); the hosted restore was skipped.");
138 expect(skipWords(undefined)).toBe("No hosted forges in this snapshot; the hosted restore was skipped.");
139 });
140
141 test("the drilled dates round-trip and an unreadable file is none", () => {
142 const d = mkdtempSync(join(tmpdir(), "forge-drilled-"));
143 try {
144 expect(readDrilled(d)).toEqual({});
145 noteDrilled(d, "a", "2026-11-01T00:00:00.000Z");
146 noteDrilled(d, "b", "2026-11-02T00:00:00.000Z");
147 expect(readDrilled(d)).toEqual({ a: "2026-11-01T00:00:00.000Z", b: "2026-11-02T00:00:00.000Z" });
148 writeFileSync(join(d, "drill", "hosted.json"), JSON.stringify({ a: "nonsense", "../x": "2026-11-01T00:00:00Z", c: "2026-11-03T00:00:00Z" }));
149 expect(readDrilled(d)).toEqual({ c: "2026-11-03T00:00:00Z" });
150 writeFileSync(join(d, "drill", "hosted.json"), "{");
151 expect(readDrilled(d)).toEqual({});
152 } finally {
153 rmSync(d, { recursive: true, force: true });
154 }
155 });
156
157 test("a file that is not a database fails integrity_check by name", async () => {
158 const d = mkdtempSync(join(tmpdir(), "forge-integrity-"));
159 try {
160 writeFileSync(join(d, "forge.db"), "SQLite format 3\0" + "x".repeat(4096));
161 await expect(checkDatabase(join(d, "forge.db"))).rejects.toThrow("its database fails PRAGMA integrity_check");
162 } finally {
163 rmSync(d, { recursive: true, force: true });
164 }
165 });
166
167 test("a repository missing an object fails git fsck by name; a whole one passes", async () => {
168 const d = mkdtempSync(join(tmpdir(), "forge-fsck-"));
169 try {
170 const git = (...args: string[]) => Bun.spawnSync(["git", "-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd: d, stderr: "pipe", stdout: "pipe" });
171 git("init", "--quiet");
172 writeFileSync(join(d, "a.txt"), "kept\n");
173 git("add", "a.txt");
174 git("commit", "--quiet", "-m", "one");
175 await checkRepo(d, "glint/work", 30_000);
176 const blob = git("rev-parse", "HEAD:a.txt").stdout.toString().trim();
177 const loose = join(d, ".git", "objects", blob.slice(0, 2), blob.slice(2));
178 expect(existsSync(loose)).toBe(true);
179 rmSync(loose, { force: true });
180 await expect(checkRepo(d, "glint/work", 30_000)).rejects.toThrow("glint/work fails git fsck --connectivity-only");
181 } finally {
182 rmSync(d, { recursive: true, force: true });
183 }
184 });
185 });
test/worker-database-opens.test.ts +1
@@ -64,6 +64,7 @@ const REACHED: Record<string, { opens: number; why: string }> = {
6464 "src/kernel/db.ts": { opens: 2, why: "the forge's own database, opened once by createApp on the thread that boots; the Workers that read it open their own handle and keep it (KEEPS)" },
6565 "src/release/rollback.ts": { opens: 1, why: "liveSchema reads the schema count once for a rollback or a swap, on the serving thread or in the release tool" },
6666 "src/snapshot/drill.ts": { opens: 1, why: "a restore drill opens the restored copy once, as a duty of the serving thread" },
67 "src/snapshot/hosted_drill.ts": { opens: 1, why: "the drill checks one restored hosted forge's database once, read-only, as a duty of the serving thread (#13919)" },
6768 "src/snapshot/restore.ts": { opens: 1, why: "a restore reads the sealed names of the restored copy once, in the restore tool or a drill on the serving thread" },
6869 "src/snapshot/snapshot.ts": { opens: 2, why: "a snapshot counts the rows of its own copy once, and reads each hosted forge's copy once, as a duty of the serving thread; the mirror Worker imports this file for the manifest only" },
6970 "src/spawn/child_runs.ts": { opens: 2, why: "called by the reader process (spawn/child_db_reader.ts), never by a thread of the forge; cell.ts re-exports the two for tests that read a file directly" },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs