Public: anyone can read this; the crew can change it.
The restore drill restores within its budget, and its red card says plainly what to do #2669
mason/forge:mason/2667-the-restore-drill-restores-within-its-bu → main 2 commits fork
9 files
changed +369
−13
docs/RECOVERY.md +4
| @@ -77,6 +77,10 @@ was doing, the likely cause, and the first thing to check. Whatever the step, | ||
| 77 | 77 | the next move is the same: run Route 1 by hand on a new directory and watch |
| 78 | 78 | which line it stops at. |
| 79 | 79 | |
| 80 | The card says what failed, how old the newest backup is, and one next step: | |
| 81 | past 36 hours, fix the nightly on Backups (the next snapshot to land is | |
| 82 | drilled at once, and green clears the card); otherwise, drill again. | |
| 83 | ||
| 80 | 84 | ### Steps |
| 81 | 85 | |
| 82 | 86 | - **fetch** — listing the store for the newest snapshot. Likely the store is |
docs/SNAPSHOT.md +5 −1
| @@ -106,7 +106,11 @@ The store is `Bun.S3Client` or a directory behind one small interface | ||
| 106 | 106 | is tried five times; an attempt that has not answered by its deadline counts |
| 107 | 107 | as failed. A put's deadline follows its size: its bytes at a floor of |
| 108 | 108 | 5 Mbit/s, plus 60 s. A fixed 180 s once failed every attempt at a 334 MB |
| 109 | database behind a 15 Mbit/s uplink (#2536). | |
| 109 | database behind a 15 Mbit/s uplink (#2536). A get the restore makes knows | |
| 110 | its size from the manifest, and its deadline follows it the same way, never | |
| 111 | less than 180 s: a snapshot from before the parts holds its database as one | |
| 112 | object, and a fixed 180 s cut every read of it short behind a slow link until | |
| 113 | the drill's ten minutes were gone (#2667). | |
| 110 | 114 | |
| 111 | 115 | ## When a snapshot fails |
| 112 | 116 |
src/snapshot/restore.ts +1 −1
| @@ -135,7 +135,7 @@ async function fetchAll( | ||
| 135 | 135 | if (failure !== undefined) break; |
| 136 | 136 | held += entry.bytes; |
| 137 | 137 | const run: Promise<void> = (async () => { |
| 138 | const body = await store.get(prefix + entry.path); | |
| 138 | const body = await store.get(prefix + entry.path, entry.bytes); | |
| 139 | 139 | if (body === undefined) |
| 140 | 140 | throw new Error(`snapshot ${name} is missing ${entry.path}`); |
| 141 | 141 | if (body.byteLength !== entry.bytes) |
src/snapshot/service.ts +11
| @@ -178,6 +178,7 @@ export function startSnapshots( | ||
| 178 | 178 | last = { manifest: m, at: m.finishedAt }; |
| 179 | 179 | keep({ landed: m.name }); |
| 180 | 180 | arm(untilNightly()); |
| 181 | drillNewer(m.name); | |
| 181 | 182 | return m; |
| 182 | 183 | }, |
| 183 | 184 | (error) => { |
| @@ -254,6 +255,16 @@ export function startSnapshots( | ||
| 254 | 255 | return drilling; |
| 255 | 256 | }; |
| 256 | 257 | |
| 258 | // A red drill of an older snapshot is about that snapshot; the one that | |
| 259 | // just landed is drilled at once, so the card clears the night a nightly | |
| 260 | // lands, not three hours after (#2667). | |
| 261 | const drillNewer = (landed: string): void => { | |
| 262 | if (options.nightly === false || stopped) return; | |
| 263 | const newest = lastDrill(app.db); | |
| 264 | if (newest?.verdict !== "red" || newest.snapshotId === landed) return; | |
| 265 | void drill().catch((error) => log.error("restore drill failed to run", { error: String(error) })); | |
| 266 | }; | |
| 267 | ||
| 257 | 268 | const keep = (result: { landed: string } | { error: string }): void => { |
| 258 | 269 | try { |
| 259 | 270 | recordSnapshotOutcome(app.config.dataDir, result); |
src/snapshot/store.ts +31 −6
| @@ -15,7 +15,8 @@ export interface Store { | ||
| 15 | 15 | /** The directory it writes under, when it is one; a bucket has none. */ |
| 16 | 16 | readonly dir?: string; |
| 17 | 17 | put(key: string, body: Uint8Array | string): Promise<void>; |
| 18 | get(key: string): Promise<Uint8Array | undefined>; | |
| 18 | /** `bytes`, when the caller knows it from a manifest, lets the read's deadline follow its size. */ | |
| 19 | get(key: string, bytes?: number): Promise<Uint8Array | undefined>; | |
| 19 | 20 | /** Every key under `prefix`, in no particular order. */ |
| 20 | 21 | list(prefix: string): Promise<string[]>; |
| 21 | 22 | /** The next path segment under `prefix`: the "directories", not the keys. */ |
| @@ -57,6 +58,8 @@ export const FLOOR_BYTES_PER_S = 5_000_000 / 8; | ||
| 57 | 58 | export const SLACK_MS = 60_000; |
| 58 | 59 | /** How long a read, a listing or a delete may go unanswered. */ |
| 59 | 60 | export const CALL_DEADLINE_MS = 180_000; |
| 61 | /** The slowest download a read of a known size may assume: 5 Mbit/s, a thirtieth of the ~150 Mbit/s home line. */ | |
| 62 | export const READ_FLOOR_BYTES_PER_S = 5_000_000 / 8; | |
| 60 | 63 | |
| 61 | 64 | /** How long a put of `bytes` may take before it counts as failed: its bytes at the floor rate, plus slack. */ |
| 62 | 65 | export const deadlineFor = ( |
| @@ -65,6 +68,23 @@ export const deadlineFor = ( | ||
| 65 | 68 | slackMs = SLACK_MS, |
| 66 | 69 | ): number => slackMs + Math.ceil((bytes / floorBytesPerS) * 1000); |
| 67 | 70 | |
| 71 | /** | |
| 72 | * How long a read of `bytes` may take before it counts as failed: never | |
| 73 | * less than `CALL_DEADLINE_MS`, and more when its bytes at the floor rate | |
| 74 | * need more. A fixed 180 s once cut off every attempt at a 334 MB database | |
| 75 | * read whole from a snapshot older than the parts (2026-10-18), until the | |
| 76 | * drill's ten minutes were gone. | |
| 77 | */ | |
| 78 | export const readDeadlineFor = ( | |
| 79 | bytes: number, | |
| 80 | floorBytesPerS = READ_FLOOR_BYTES_PER_S, | |
| 81 | slackMs = SLACK_MS, | |
| 82 | callMs = CALL_DEADLINE_MS, | |
| 83 | ): number => | |
| 84 | Number.isFinite(bytes) && bytes > 0 | |
| 85 | ? Math.max(callMs, deadlineFor(bytes, floorBytesPerS, slackMs)) | |
| 86 | : callMs; | |
| 87 | ||
| 68 | 88 | const sizeOf = (body: Uint8Array | string): number => |
| 69 | 89 | typeof body === "string" ? Buffer.byteLength(body) : body.byteLength; |
| 70 | 90 | |
| @@ -83,8 +103,10 @@ const sizeOf = (body: Uint8Array | string): number => | ||
| 83 | 103 | * A put's deadline follows its size (`deadlineFor`): a fixed 180 s once |
| 84 | 104 | * failed every attempt at a 334 MB database behind a 15 Mbit/s uplink |
| 85 | 105 | * (2026-10-17). `deadlineMs` fixes every deadline instead, for tests; |
| 86 | * `floorBytesPerS` and `slackMs` scale the size rule, for tests that run a | |
| 87 | * slow link at a thousand times its speed. | |
| 106 | * `floorBytesPerS`, `slackMs` and `callDeadlineMs` scale the size rule, | |
| 107 | * for tests that run a slow link at a thousand times its speed. A get told its size gets the | |
| 108 | * same treatment (`readDeadlineFor`); one that is not keeps the fixed | |
| 109 | * `CALL_DEADLINE_MS`. | |
| 88 | 110 | */ |
| 89 | 111 | export function withRetries( |
| 90 | 112 | inner: Store, |
| @@ -94,15 +116,18 @@ export function withRetries( | ||
| 94 | 116 | deadlineMs?: number; |
| 95 | 117 | floorBytesPerS?: number; |
| 96 | 118 | slackMs?: number; |
| 119 | callDeadlineMs?: number; | |
| 97 | 120 | sleep?: (ms: number) => Promise<void>; |
| 98 | 121 | } = {}, |
| 99 | 122 | ): Store { |
| 100 | 123 | const attempts = Math.max(1, options.attempts ?? 5); |
| 101 | 124 | const baseMs = options.baseMs ?? 500; |
| 102 | 125 | const fixed = options.deadlineMs; |
| 103 | const callMs = fixed ?? CALL_DEADLINE_MS; | |
| 126 | const callMs = fixed ?? options.callDeadlineMs ?? CALL_DEADLINE_MS; | |
| 104 | 127 | const putMs = (body: Uint8Array | string): number => |
| 105 | 128 | fixed ?? deadlineFor(sizeOf(body), options.floorBytesPerS, options.slackMs); |
| 129 | const getMs = (bytes: number | undefined): number => | |
| 130 | fixed ?? (bytes === undefined ? callMs : readDeadlineFor(bytes, options.floorBytesPerS, options.slackMs, callMs)); | |
| 106 | 131 | const sleep = options.sleep ?? ((ms) => Bun.sleep(ms)); |
| 107 | 132 | async function tried<T>( |
| 108 | 133 | what: string, |
| @@ -127,7 +152,7 @@ export function withRetries( | ||
| 127 | 152 | ...(inner.dir === undefined ? {} : { dir: inner.dir }), |
| 128 | 153 | put: (key, body) => |
| 129 | 154 | tried(`put ${key}`, putMs(body), () => inner.put(key, body)), |
| 130 | get: (key) => tried(`get ${key}`, callMs, () => inner.get(key)), | |
| 155 | get: (key, bytes) => tried(`get ${key}`, getMs(bytes), () => inner.get(key, bytes)), | |
| 131 | 156 | list: (prefix) => tried(`list ${prefix}`, callMs, () => inner.list(prefix)), |
| 132 | 157 | names: (prefix) => |
| 133 | 158 | tried(`names ${prefix}`, callMs, () => inner.names(prefix)), |
| @@ -141,7 +166,7 @@ export function withRetries( | ||
| 141 | 166 | */ |
| 142 | 167 | function answered<T>(attempt: Promise<T>, ms: number): Promise<T> { |
| 143 | 168 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 144 | const shown = ms >= 1000 ? `${Math.round(ms / 1000)} s` : `${ms} ms`; | |
| 169 | const shown = ms >= 1000 ? `${Math.round(ms / 1000)} s` : `${Math.round(ms)} ms`; | |
| 145 | 170 | const deadline = new Promise<never>((_, reject) => { |
| 146 | 171 | timer = setTimeout(() => reject(new Error(`no answer in ${shown}`)), ms); |
| 147 | 172 | }); |
src/snapshot/verdict.ts +53 −4
| @@ -35,10 +35,59 @@ export function lastVerdict(dataDir: string): DrillResult | undefined { | ||
| 35 | 35 | } |
| 36 | 36 | } |
| 37 | 37 | |
| 38 | /** The inbox card's sentence for a red drill; undefined for a green one. */ | |
| 39 | export function failedSentence(r: DrillResult | undefined): string | undefined { | |
| 38 | /** A span as a person says it: "about 10 minutes", "about 40 seconds"; never a fraction of a ms. */ | |
| 39 | export function aboutSpan(ms: number): string { | |
| 40 | if (!Number.isFinite(ms) || ms < 0) return "no time"; | |
| 41 | if (ms < 1_000) return `${Math.round(ms)} ms`; | |
| 42 | const plural = (n: number, unit: string): string => `about ${n} ${unit}${n === 1 ? "" : "s"}`; | |
| 43 | if (ms < 60_000) return plural(Math.round(ms / 1_000), "second"); | |
| 44 | if (ms < 90 * 60_000) return plural(Math.max(1, Math.round(ms / 60_000)), "minute"); | |
| 45 | return plural(Math.round(ms / 3_600_000), "hour"); | |
| 46 | } | |
| 47 | ||
| 48 | /** An age as a person says it: "5 days", "7 hours", "less than an hour". */ | |
| 49 | export function formatAge(ms: number): string { | |
| 50 | if (!Number.isFinite(ms) || ms < 3_600_000) return "less than an hour"; | |
| 51 | const hours = Math.floor(ms / 3_600_000); | |
| 52 | if (hours < 48) return `${hours} hour${hours === 1 ? "" : "s"}`; | |
| 53 | return `${Math.floor(hours / 24)} days`; | |
| 54 | } | |
| 55 | ||
| 56 | /** | |
| 57 | * A kept reason, for a person: any count of milliseconds in it (an older | |
| 58 | * drill kept "no answer in 596591.192678988 ms") reads as about how long. | |
| 59 | */ | |
| 60 | export function plainReason(reason: string): string { | |
| 61 | return reason.replace(/\b(\d+(?:\.\d+)?)\s*ms\b/g, (_, n: string) => aboutSpan(Number(n))).replace(/\.$/, ""); | |
| 62 | } | |
| 63 | ||
| 64 | /** When a snapshot was taken, from its name (`2026-10-14T08-00-00Z`); NaN when the name is not one. */ | |
| 65 | export function snapshotTime(name: string | null): number { | |
| 66 | const m = name?.match(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})Z$/); | |
| 67 | return m ? Date.parse(`${m[1]}T${m[2]}:${m[3]}:${m[4]}Z`) : NaN; | |
| 68 | } | |
| 69 | ||
| 70 | /** A newest backup older than this means the nightly is not landing; that is the thing to fix first. */ | |
| 71 | export const BACKUP_STALE_MS = 36 * 3_600_000; | |
| 72 | ||
| 73 | /** | |
| 74 | * The inbox card's sentence for a red drill; undefined for a green one. | |
| 75 | * Three things for a person: what failed, how old the newest backup is, | |
| 76 | * and the one next step. | |
| 77 | */ | |
| 78 | export function failedSentence(r: DrillResult | undefined, now: number = Date.now()): string | undefined { | |
| 40 | 79 | if (r === undefined || r.verdict !== "red") return undefined; |
| 41 | return `The restore drill failed at ${r.failedStep ?? "an unknown step"}${r.reason ? `: ${r.reason}` : ""}. Snapshot ${r.snapshotId ?? "none"}; docs/RECOVERY.md says what to do.`; | |
| 80 | const what = `The restore drill failed at ${r.failedStep ?? "an unknown step"}${r.reason ? `: ${plainReason(r.reason)}` : ""}.`; | |
| 81 | const taken = snapshotTime(r.snapshotId); | |
| 82 | if (!Number.isFinite(taken)) | |
| 83 | return `${what} It found no backup to restore. Next: check the snapshot store on /settings/backups; docs/RECOVERY.md says what to do.`; | |
| 84 | const age = Math.max(0, now - taken); | |
| 85 | const newest = `The newest backup is ${formatAge(age)} old (${r.snapshotId}).`; | |
| 86 | const next = | |
| 87 | age > BACKUP_STALE_MS | |
| 88 | ? "Next: get a nightly snapshot to land (/settings/backups says why they fail); the drill restores the new one on its own and this card clears." | |
| 89 | : "Next: run the drill again from /settings/backups; if it fails the same way, docs/RECOVERY.md says what to do."; | |
| 90 | return `${what} ${newest} ${next}`; | |
| 42 | 91 | } |
| 43 | 92 | |
| 44 | 93 | /** A green drill that used more than this share of its budget is a warning. */ |
| @@ -100,7 +149,7 @@ export function drillNeed( | ||
| 100 | 149 | now: number, |
| 101 | 150 | forgeSince?: () => string | undefined, |
| 102 | 151 | ): DrillNeed | undefined { |
| 103 | const red = failedSentence(r); | |
| 152 | const red = failedSentence(r, now); | |
| 104 | 153 | if (r !== undefined && red !== undefined) return { key: `red:${r.at}`, sentence: red, since: r.at }; |
| 105 | 154 | const days = Math.floor(DRILL_STALE_MS / 86_400_000); |
| 106 | 155 | if (r === undefined) { |
src/web/pages/backups.ts +2 −1
| @@ -20,6 +20,7 @@ import { resolveDestination, sealedSet } from "../../snapshot/destination.ts"; | ||
| 20 | 20 | import { keyOf } from "../../snapshot/snapshot.ts"; |
| 21 | 21 | import { formatBudget, formatSpan, type DrillResult } from "../../snapshot/drill.ts"; |
| 22 | 22 | import { lastDrill } from "../../snapshot/drills.ts"; |
| 23 | import { plainReason } from "../../snapshot/verdict.ts"; | |
| 23 | 24 | import { snapshotsOf } from "../../snapshot/service.ts"; |
| 24 | 25 | import { lastSnapshotOutcome } from "../../snapshot/outcome.ts"; |
| 25 | 26 | import type { Ctx } from "../../http/context.ts"; |
| @@ -117,7 +118,7 @@ function drillLine(ctx: Ctx): Html { | ||
| 117 | 118 | ${icon("alert")} Last drill ${time(d.at)}: snapshot |
| 118 | 119 | <code>${d.snapshotId ?? "none"}</code> failed at |
| 119 | 120 | ${d.failedStep ?? "an unknown step"} after ${d.ms} ms${d.reason |
| 120 | ? html`: ${d.reason}` | |
| 121 | ? html`: ${plainReason(d.reason)}` | |
| 121 | 122 | : ""}.${timing ? html` <span class="backups-timing">${timing}.</span>` : ""} |
| 122 | 123 | </p>`; |
| 123 | 124 | return html`${line} |
test/drill-card.test.ts added +118
| @@ -0,0 +1,118 @@ | ||
| 1 | /** | |
| 2 | * The red drill's card is for a person (#2667): what failed, how old the | |
| 3 | * newest backup is, and the one next step, never a raw float of ms. It | |
| 4 | * stood on the home screen as "restore timed out: no answer in | |
| 5 | * 596591.192678988 ms"; a drill kept like that still reads as minutes. And | |
| 6 | * the card clears by itself: a snapshot that lands after a red drill of an | |
| 7 | * older one is drilled at once. | |
| 8 | */ | |
| 9 | import { expect, test } from "bun:test"; | |
| 10 | import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; | |
| 11 | import { rm } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { createApp } from "../src/app.ts"; | |
| 15 | import type { DrillResult } from "../src/snapshot/drill.ts"; | |
| 16 | import { lastDrill, recordDrill } from "../src/snapshot/drills.ts"; | |
| 17 | import { startSnapshots } from "../src/snapshot/service.ts"; | |
| 18 | import { dirStore } from "../src/snapshot/store.ts"; | |
| 19 | import { | |
| 20 | aboutSpan, | |
| 21 | drillNeed, | |
| 22 | failedSentence, | |
| 23 | formatAge, | |
| 24 | lastVerdict, | |
| 25 | plainReason, | |
| 26 | recordVerdict, | |
| 27 | } from "../src/snapshot/verdict.ts"; | |
| 28 | ||
| 29 | const OLD = "2026-10-14T08-00-00Z"; | |
| 30 | const NOW = Date.parse("2026-10-19T14:42:00Z"); | |
| 31 | ||
| 32 | const red = (over: Partial<DrillResult> = {}): DrillResult => ({ | |
| 33 | at: "2026-10-18T09:11:45.853Z", | |
| 34 | snapshotId: OLD, | |
| 35 | ms: 596_600, | |
| 36 | counts: { repositories: 0, issues: 0, users: 0, pulls: 0, apps: 0 }, | |
| 37 | health: "unreached", | |
| 38 | verdict: "red", | |
| 39 | failedStep: "restore", | |
| 40 | phases: [], | |
| 41 | budgetMs: 600_000, | |
| 42 | reason: "restore timed out: no answer in 596591.192678988 ms", | |
| 43 | ...over, | |
| 44 | }); | |
| 45 | ||
| 46 | test("the owner's card reads in minutes, says how old the backup is, and names one next step", () => { | |
| 47 | const s = failedSentence(red(), NOW)!; | |
| 48 | expect(s).toStartWith("The restore drill failed at restore: restore timed out: no answer in about 10 minutes."); | |
| 49 | expect(s).toContain(`The newest backup is 5 days old (${OLD}).`); | |
| 50 | expect(s).toContain("Next: get a nightly snapshot to land"); | |
| 51 | expect(s).not.toContain("596591"); | |
| 52 | expect(s).not.toMatch(/\d\.\d+ ms/); | |
| 53 | expect(s.match(/Next:/g)?.length).toBe(1); | |
| 54 | }); | |
| 55 | ||
| 56 | test("a red drill of last night's backup says to run it again", () => { | |
| 57 | const s = failedSentence(red({ snapshotId: "2026-10-19T08-00-00Z", reason: "health answered 503" }), NOW)!; | |
| 58 | expect(s).toContain("The newest backup is 6 hours old"); | |
| 59 | expect(s).toContain("Next: run the drill again from /settings/backups"); | |
| 60 | }); | |
| 61 | ||
| 62 | test("a drill that found no snapshot says so and points at the store", () => { | |
| 63 | const s = failedSentence(red({ snapshotId: null, failedStep: "fetch", reason: "the store holds no snapshot" }), NOW)!; | |
| 64 | expect(s).toContain("It found no backup to restore."); | |
| 65 | expect(s).toContain("Next: check the snapshot store"); | |
| 66 | }); | |
| 67 | ||
| 68 | test("spans and ages read as a person says them", () => { | |
| 69 | expect(aboutSpan(596591.192678988)).toBe("about 10 minutes"); | |
| 70 | expect(aboutSpan(60_000)).toBe("about 1 minute"); | |
| 71 | expect(aboutSpan(42_400)).toBe("about 42 seconds"); | |
| 72 | expect(aboutSpan(3 * 3_600_000)).toBe("about 3 hours"); | |
| 73 | expect(aboutSpan(250.7)).toBe("251 ms"); | |
| 74 | expect(formatAge(5 * 86_400_000 + 6 * 3_600_000)).toBe("5 days"); | |
| 75 | expect(formatAge(30 * 60_000)).toBe("less than an hour"); | |
| 76 | expect(plainReason("get x failed after 5 attempts: no answer in 180000 ms.")).toBe( | |
| 77 | "get x failed after 5 attempts: no answer in about 3 minutes", | |
| 78 | ); | |
| 79 | }); | |
| 80 | ||
| 81 | test("the board's line is the same sentence", () => { | |
| 82 | expect(drillNeed(red(), NOW)?.sentence).toBe(failedSentence(red(), NOW)!); | |
| 83 | }); | |
| 84 | ||
| 85 | test("a snapshot that lands after a red drill of an older one is drilled at once, and the card clears", async () => { | |
| 86 | const root = mkdtempSync(join(tmpdir(), "forge-drill-card-")); | |
| 87 | mkdirSync(join(root, "drill"), { recursive: true }); | |
| 88 | writeFileSync(join(root, "drill", "first-seen"), new Date(Date.now() - 30 * 86_400_000).toISOString()); | |
| 89 | const app = createApp({ dataDir: root, port: 0 }); | |
| 90 | const before = red({ at: new Date().toISOString() }); | |
| 91 | recordDrill(app.db, before); | |
| 92 | recordVerdict(root, before); | |
| 93 | const drilled: string[] = []; | |
| 94 | const svc = startSnapshots(app, dirStore(join(root, "store")), { | |
| 95 | version: "t", | |
| 96 | // Nothing but the landing may drill within the test. | |
| 97 | catchUpMs: 3_600_000, | |
| 98 | redRetryMs: 3_600_000, | |
| 99 | mirrorEveryMs: 3_600_000, | |
| 100 | drill: async (deps) => { | |
| 101 | const newest = (await deps.store.names("snapshots/")).sort().at(-1)!; | |
| 102 | drilled.push(newest); | |
| 103 | return { ...red(), ms: 1_000, at: new Date().toISOString(), snapshotId: newest, verdict: "green", failedStep: null, reason: null, health: "ok" }; | |
| 104 | }, | |
| 105 | }); | |
| 106 | try { | |
| 107 | expect(drillNeed(lastVerdict(root), Date.now())?.sentence).toContain("failed at restore"); | |
| 108 | const m = await svc.now(); | |
| 109 | for (let i = 0; i < 50 && lastDrill(app.db)?.verdict !== "green"; i++) await Bun.sleep(20); | |
| 110 | expect(drilled).toEqual([m.name]); | |
| 111 | expect(lastDrill(app.db)?.snapshotId).toBe(m.name); | |
| 112 | expect(drillNeed(lastVerdict(root), Date.now())).toBeUndefined(); | |
| 113 | } finally { | |
| 114 | await svc.stop(); | |
| 115 | app.close(); | |
| 116 | await rm(root, { recursive: true, force: true }); | |
| 117 | } | |
| 118 | }); |
test/snapshot-restore-throttled.test.ts added +144
| @@ -0,0 +1,144 @@ | ||
| 1 | /** | |
| 2 | * The restore drill fits its budget on a slow link (#2667). A snapshot from | |
| 3 | * before the parts (2026-10-14) holds its database as one object of a few | |
| 4 | * hundred MB; every get had a fixed 180 s to answer, so behind a link | |
| 5 | * slower than 15 Mbit/s each attempt was cut off and tried again until the | |
| 6 | * drill's ten minutes were gone. A get told its size from the manifest | |
| 7 | * now has a deadline that follows it. | |
| 8 | * | |
| 9 | * The link and every deadline run `SCALE` times faster than life: 400 MB | |
| 10 | * behind 10 Mbit/s (320 s, inside the 10.4 min budget a 400 MB snapshot | |
| 11 | * gets) is 1.6 s here, against a fixed deadline of 0.9 s. | |
| 12 | */ | |
| 13 | ||
| 14 | import { Database } from "bun:sqlite"; | |
| 15 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 16 | import { mkdtempSync, readFileSync } from "node:fs"; | |
| 17 | import { rm } from "node:fs/promises"; | |
| 18 | import { tmpdir } from "node:os"; | |
| 19 | import { join } from "node:path"; | |
| 20 | import { drillBudgetMs, runDrill } from "../src/snapshot/drill.ts"; | |
| 21 | import { | |
| 22 | CALL_DEADLINE_MS, | |
| 23 | READ_FLOOR_BYTES_PER_S, | |
| 24 | readDeadlineFor, | |
| 25 | SLACK_MS, | |
| 26 | withRetries, | |
| 27 | type Store, | |
| 28 | } from "../src/snapshot/store.ts"; | |
| 29 | ||
| 30 | const SCALE = 200; | |
| 31 | const LINK_BYTES_PER_S = (10_000_000 / 8) * SCALE; | |
| 32 | const NAME = "2026-10-14T08-00-00Z"; | |
| 33 | const prefix = `snapshots/${NAME}/`; | |
| 34 | const BIG = 400_000_000; | |
| 35 | const BIG_PATH = "attic/old-uploads.bin"; | |
| 36 | ||
| 37 | let root: string; | |
| 38 | let objects: Map<string, Uint8Array>; | |
| 39 | const big = new Uint8Array(BIG); | |
| 40 | ||
| 41 | /** A bucket behind a 10 Mbit/s link: every get takes its bytes' time, and the big object is one shared buffer. */ | |
| 42 | const throttled: Store = { | |
| 43 | where: "throttled", | |
| 44 | async put() { | |
| 45 | throw new Error("read only"); | |
| 46 | }, | |
| 47 | async get(key) { | |
| 48 | const body = key === prefix + BIG_PATH ? big : objects.get(key); | |
| 49 | if (body !== undefined) await Bun.sleep((body.byteLength / LINK_BYTES_PER_S) * 1000); | |
| 50 | return body; | |
| 51 | }, | |
| 52 | async list(p) { | |
| 53 | return [...objects.keys(), prefix + BIG_PATH].filter((k) => k.startsWith(p)); | |
| 54 | }, | |
| 55 | async names(p) { | |
| 56 | return p === "snapshots/" ? [NAME] : []; | |
| 57 | }, | |
| 58 | async delete() {}, | |
| 59 | }; | |
| 60 | ||
| 61 | const retrying = (): Store => | |
| 62 | withRetries(throttled, { | |
| 63 | baseMs: 1, | |
| 64 | floorBytesPerS: READ_FLOOR_BYTES_PER_S * SCALE, | |
| 65 | slackMs: SLACK_MS / SCALE, | |
| 66 | callDeadlineMs: CALL_DEADLINE_MS / SCALE, | |
| 67 | }); | |
| 68 | ||
| 69 | beforeAll(() => { | |
| 70 | root = mkdtempSync(join(tmpdir(), "forge-throttled-")); | |
| 71 | // A forge.db the drill can open and count: the five tables, empty. | |
| 72 | const dbFile = join(root, "forge.db"); | |
| 73 | const db = new Database(dbFile); | |
| 74 | for (const t of ["repo", "issue", "user", "pull", "app"]) db.run(`CREATE TABLE ${t} (id TEXT)`); | |
| 75 | db.run("CREATE TABLE secret (name TEXT, scope TEXT, value_enc TEXT)"); | |
| 76 | db.run("CREATE TABLE app_env (app_id TEXT, name TEXT, value_enc TEXT)"); | |
| 77 | db.close(); | |
| 78 | const forgeDb = new Uint8Array(readFileSync(dbFile)); | |
| 79 | const files = [ | |
| 80 | { path: "forge.db", bytes: forgeDb.byteLength }, | |
| 81 | { path: BIG_PATH, bytes: BIG }, | |
| 82 | ]; | |
| 83 | objects = new Map([ | |
| 84 | [prefix + "forge.db", forgeDb], | |
| 85 | [ | |
| 86 | prefix + "manifest.json", | |
| 87 | new TextEncoder().encode( | |
| 88 | JSON.stringify({ | |
| 89 | name: NAME, | |
| 90 | startedAt: "2026-10-14T08:00:00.000Z", | |
| 91 | finishedAt: "2026-10-14T08:01:00.000Z", | |
| 92 | version: "t", | |
| 93 | repos: 0, | |
| 94 | apps: 0, | |
| 95 | files, | |
| 96 | bytes: files.reduce((s, f) => s + f.bytes, 0), | |
| 97 | key: "raw", | |
| 98 | }), | |
| 99 | ), | |
| 100 | ], | |
| 101 | ]); | |
| 102 | }); | |
| 103 | ||
| 104 | afterAll(async () => { | |
| 105 | await rm(root, { recursive: true, force: true }); | |
| 106 | }); | |
| 107 | ||
| 108 | test("a read told its size waits for its bytes at the floor; one not told keeps the fixed deadline", () => { | |
| 109 | expect(readDeadlineFor(16 * 1_048_576)).toBe(CALL_DEADLINE_MS); | |
| 110 | // 334 MB at 5 Mbit/s is 534.4 s, plus a minute of slack. | |
| 111 | expect(readDeadlineFor(334_000_000)).toBe(594_400); | |
| 112 | for (const b of [0, -1, NaN]) expect(readDeadlineFor(b)).toBe(CALL_DEADLINE_MS); | |
| 113 | }); | |
| 114 | ||
| 115 | test("a 400 MB snapshot behind a throttled link restores within its budget", async () => { | |
| 116 | const budgetMs = drillBudgetMs(BIG) / SCALE; | |
| 117 | const r = await runDrill({ | |
| 118 | store: retrying(), | |
| 119 | dataDir: join(root, "green"), | |
| 120 | timeoutMs: budgetMs, | |
| 121 | boot: async () => ({ ok: true, reason: "" }), | |
| 122 | }); | |
| 123 | expect(r.reason).toBeNull(); | |
| 124 | expect(r.verdict).toBe("green"); | |
| 125 | expect(r.ms).toBeLessThan(budgetMs); | |
| 126 | expect(r.phases.map((p) => p.phase)).toContain("files"); | |
| 127 | }, 30_000); | |
| 128 | ||
| 129 | test("the same restore with every read held to the fixed deadline runs out of its budget", async () => { | |
| 130 | const store = retrying(); | |
| 131 | // What every get was before #2667: no size, so the fixed deadline. | |
| 132 | const blind: Store = { ...store, get: (key) => store.get(key) }; | |
| 133 | const budgetMs = drillBudgetMs(BIG) / SCALE; | |
| 134 | const r = await runDrill({ | |
| 135 | store: blind, | |
| 136 | dataDir: join(root, "red"), | |
| 137 | timeoutMs: budgetMs, | |
| 138 | boot: async () => ({ ok: true, reason: "" }), | |
| 139 | }); | |
| 140 | expect(r.verdict).toBe("red"); | |
| 141 | expect(r.failedStep).toBe("restore"); | |
| 142 | expect(r.reason).toContain("files"); | |
| 143 | expect(r.reason).not.toMatch(/\d\.\d+ ms/); | |
| 144 | }, 30_000); |
new above
offline