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

A hosted forge's database and git stream to its snapshot bucket every five minutes, and a restore from the stream boots and matches #16983

Merged opened this

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

Merged

scout/forge:scout/16977-a-hosted-forge-s-database-and-git-stream → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/16977-a-hosted-forge-s-database-and-git-stream was merged into main as 6dd030a.

Review

Sign in to review this change.
11 files changed +409 −36
docs/features/hosted-stream.md added +24
@@ -0,0 +1,24 @@
1 ---
2 topic: Backups and moving
3 row: Hosted forges streamed to the bucket
4 ---
5 # Hosted forges streamed to the bucket
6
7 The nightly snapshot keeps each hosted forge once a day ([hosted-backup.md](hosted-backup.md)). Between nights the stream (#16858) takes each one again every five minutes, so losing the host loses minutes, not a day.
8
9 - A pass takes one hosted forge at a time with the snapshot's own copy (database `VACUUM INTO`, repositories as bundles, history, wrapped key) and writes it to the bucket's `stream/<name>/manifest.json`, replacing the last. Chunks are the snapshot's, so a forge that did not change sends almost nothing.
10 - It uses the forge's snapshot destination; no new host, so `forge.json` `egress` is unchanged. The off-box mirror still copies the nightly snapshots only.
11 - Passes run one after another with snapshots: a snapshot's sweep never runs beside a pass, and it keeps every chunk a stream manifest names.
12 - `snapshot/stream.json` in the data directory holds each forge's last whole pass and the last failure, so the lag is read without the network. A forge more than three passes behind (15 minutes) is late.
13
14 ## Where it is read
15
16 `streamLag(dataDir)` in `src/snapshot/stream.ts` answers each forge's last whole pass, last failure and lag. No page shows it yet.
17
18 ## Restore a forge from the stream
19
20 Into an empty data directory, with the store's variables set as in [RESTORE.md](../RESTORE.md):
21
22 bun run src/snapshot/restore.ts stream <data-dir> --forge <name>
23
24 It boots and matches: `test/snapshot-stream.test.ts` restores a streamed forge elsewhere, opens it and compares its repositories and commits.
scripts/gate.ts +1
@@ -61,6 +61,7 @@ export const SLOW: readonly Exclusion[] = [
6161 { file: "test/following-incoming.test.ts", reason: "makes 52 real commits to pass the 50-line cap of the incoming list; 2.4 s under full-suite load, 0.5 s alone", issue: 13144 },
6262 { file: "test/release-sweep-safety-14784.test.ts", reason: "boots the real src/main.ts twice at once (proof and live control) to prove the outbox untouched; 4.1 s a test under full-suite load", issue: 14784 },
6363 { file: "test/spawn-cell-looks.test.ts", reason: "boots a real child forge in a cell (~30 s) and waits for its own looks job to take a picture", issue: 10620 },
64 { file: "test/snapshot-stream.test.ts", reason: "its service test takes a real stream pass and a real snapshot of a forge with a database, about 1 s each; 3.1 s a test under full-suite load", issue: 16977 },
6465 // From the breach list closing this pull's check log at e2a5c15 (#12088):
6566 // every test over the 2 s budget, its file named once with its slowest time.
6667 { file: "test/account-budget.test.ts", reason: "starts stand-in agent runs per account to reach and test spend ceilings; 10.5 s a test on the gate box", issue: 1242 },
scripts/unused-exports-allow.json +1
@@ -175,6 +175,7 @@
175175 "src/web/studio/home_cache.ts setHomeClock",
176176 "src/web/studio/home_last.ts forgetHome",
177177 "src/web/studio/review_evidence.ts rememberStat",
178 "src/snapshot/stream.ts streamLag",
178179 "src/web/sw.ts swSource",
179180 "src/spawn/machines.ts forgetMachines",
180181 "src/spawn/machines.ts registerMachine",
src/snapshot/hosted.ts +3 −5
@@ -18,7 +18,7 @@
1818 * no transport and no fetch; one that is refused is left out by name, with why, in the manifest.
1919 */
2020
21 import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
21 import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, rmSync } from "node:fs";
2222 import { lstat, readdir } from "node:fs/promises";
2323 import { dirname, join, resolve, sep } from "node:path";
2424 import { runGit } from "../git/env.ts";
@@ -26,6 +26,7 @@ import { findingWords, scanRepos } from "../spawn/move_scan.ts";
2626 import { CHILD_NAME } from "../spawn/placement.ts";
2727 import { bundleRepo } from "./bundle.ts";
2828 import type { CopyJob, CopyReply } from "./hosted_copy.ts";
29 import { keepJson } from "./kept_file.ts";
2930 import { unwrapKey, wrapKey, WRAPPED_KEY } from "./wrap.ts";
3031
3132 /** One hosted forge as a snapshot kept it. */
@@ -165,10 +166,7 @@ const keptFile = (dataDir: string): string => join(dataDir, "snapshot", "hosted.
165166 * What the last whole snapshot kept of each hosted forge, held on disk so /forges reads no store.
166167 */
167168 export function noteHosted(dataDir: string, hosted: readonly HostedEntry[]): void {
168 mkdirSync(join(dataDir, "snapshot"), { recursive: true });
169 const tmp = `${keptFile(dataDir)}.tmp`;
170 writeFileSync(tmp, JSON.stringify(hosted));
171 renameSync(tmp, keptFile(dataDir));
169 keepJson(dataDir, "hosted.json", hosted);
172170 }
173171
174172 /**
src/snapshot/kept_file.ts added +16
@@ -0,0 +1,16 @@
1 /**
2 * One small JSON file under `<dataDir>/snapshot/`, replaced whole so a reader never sees half of
3 * it.
4 */
5
6 import { mkdirSync, renameSync, writeFileSync } from "node:fs";
7 import { join } from "node:path";
8
9 /** Write `value` to `<dataDir>/snapshot/<name>` through a temporary file and a rename. */
10 export function keepJson(dataDir: string, name: string, value: unknown): void {
11 const dir = join(dataDir, "snapshot");
12 mkdirSync(dir, { recursive: true });
13 const tmp = join(dir, `${name}.${process.pid}.tmp`);
14 writeFileSync(tmp, JSON.stringify(value));
15 renameSync(tmp, join(dir, name));
16 }
src/snapshot/restore.ts +7 −4
@@ -54,6 +54,7 @@ import {
5454 keyOf,
5555 listSnapshots,
5656 SNAPSHOT_PREFIX,
57 streamManifestKey,
5758 unpackRuns,
5859 type Manifest,
5960 type SnapshotFile,
@@ -627,12 +628,14 @@ export async function restoreHosted(
627628 where: string | ((bodyId: string) => string),
628629 options: { readonly passphrase?: string | undefined; readonly git?: typeof runGit | undefined } = {},
629630 ): Promise<RestoredHosted> {
630 if (!/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}Z$/.test(snapshot)) throw new Error(`not a snapshot name: ${snapshot}`);
631 // `stream` is the forge's newest pass of the continuous stream (#16858), not a snapshot's name.
632 const streamed = snapshot === "stream";
633 if (!streamed && !/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}Z$/.test(snapshot)) throw new Error(`not a snapshot name: ${snapshot}`);
631634 if (!/^[a-z0-9-]{1,40}$/.test(forge)) throw new Error(`not a forge name: ${forge}`);
632 const raw = await store.get(`${SNAPSHOT_PREFIX}${snapshot}/manifest.json`);
633 if (raw === undefined) throw new Error(`no snapshot ${snapshot} in ${store.where}`);
635 const raw = await store.get(streamed ? streamManifestKey(forge) : `${SNAPSHOT_PREFIX}${snapshot}/manifest.json`);
636 if (raw === undefined) throw new Error(`no ${streamed ? "stream" : "snapshot"} ${streamed ? forge : snapshot} in ${store.where}`);
634637 const manifest = JSON.parse(new TextDecoder().decode(raw)) as Manifest;
635 if (manifest.format !== 2 || !Array.isArray(manifest.files)) throw new Error(`snapshot ${snapshot} holds no hosted forges`);
638 if (manifest.format !== 2 || !Array.isArray(manifest.files)) throw new Error(streamed ? `the stream of ${forge} holds no hosted forges` : `snapshot ${snapshot} holds no hosted forges`);
outdated

This message still says snapshot stream; say the stream of <forge> when streamed.

636639 const entry = manifest.hosted?.find((h) => h.name === forge);
637640 if (entry === undefined || entry.why !== undefined) throw new Error(`snapshot ${snapshot} does not hold ${forge}${entry?.why === undefined ? "" : ` (${entry.why})`}`);
638641 const prefix = `${HOSTED_PREFIX}${forge}/`;
src/snapshot/service.ts +48
@@ -16,6 +16,7 @@ import { appendSnapshot } from "../core/ledger.ts";
1616 import { createLog } from "../kernel/log.ts";
1717 import { firstSeen, reportVerdict, seedFirstSeen } from "./verdict.ts";
1818 import { noteHosted } from "./hosted.ts";
19 import { STREAM_EVERY_MS, streamPass, type StreamEntry } from "./stream.ts";
1920 import {
2021 KEEP,
2122 listSnapshots,
@@ -108,6 +109,11 @@ export interface SnapshotsHandle {
108109 readonly mirrorFresh: () => Promise<MirrorState | undefined>;
109110 /** What the last mirror pass found. */
110111 readonly mirrored: () => MirrorState | undefined;
112 /**
113 * Stream every hosted forge to the store now (#16858); waits for a snapshot in flight, and a
114 * snapshot waits for it. Answers what the pass found, and nothing when there is no store.
115 */
116 readonly streamNow: () => Promise<StreamEntry[] | undefined>;
111117 /** Forget the resolved store; the next use resolves again (a new destination was saved). */
112118 readonly forget: () => void;
113119 /** Read the bucket now, as the watch does; resolves when the read is kept. */
@@ -199,6 +205,8 @@ export function startSnapshots(
199205 readonly activeCrewRuns?: (() => number) | undefined;
200206 readonly holdRetryMs?: number | undefined;
201207 readonly holdMaxMs?: number | undefined;
208 /** Test seam: how often the stream passes (default `STREAM_EVERY_MS`). */
209 readonly streamEveryMs?: number | undefined;
202210 /** Test seam: how soon the first nightly timer fires. */
203211 readonly nightlyInMs?: number | undefined;
204212 } = {
@@ -259,6 +267,8 @@ export function startSnapshots(
259267 // was, every later run failed at once with the old error until a restart.
260268 wait.release("snapshot");
261269 const run = (inFlight ?? Promise.resolve()).catch(() => {}).then(async () => {
270 // A stream pass in flight has chunks no manifest names yet: this run's sweep waits for it.
271 await streaming?.catch(() => {});
262272 // Resolved per run, so a destination saved on the Backups page is the
263273 // very next snapshot's.
264274 const store = current();
@@ -358,6 +368,26 @@ export function startSnapshots(
358368 return inFlight;
359369 };
360370
371 // The stream (#16858): single-flight, after any snapshot in flight and before the next one's
372 // sweep, which would take the chunks of a pass whose manifest is not written yet.
373 let streaming: Promise<StreamEntry[] | undefined> | undefined;
374 const streamNow = (): Promise<StreamEntry[] | undefined> => {
375 streaming ??= (async () => {
376 await (inFlight ?? Promise.resolve()).catch(() => {});
377 const store = current();
378 if (store === undefined || stopped) return undefined;
379 return streamPass(app.config.dataDir, (name) =>
380 takeSnapshot(
381 { db: app.db, dataDir: app.config.dataDir, reposRoot: app.reposRoot, version: options.version, passphrase: options.passphrase, stream: name },
382 store,
383 ),
384 );
385 })().finally(() => {
386 streaming = undefined;
387 });
388 return streaming;
389 };
390
361391 // A restart takes the night's snapshot if the store does not hold it: a
362392 // release at 08:21 killed the one in flight and nothing took it again (#8742).
363393 // The manifest is written last, so a snapshot cut short is not one; the
@@ -584,6 +614,21 @@ export function startSnapshots(
584614 }
585615 arm(options.nightlyInMs ?? untilNightly());
586616
617 // The stream passes every few minutes; one that finds a snapshot being taken leaves it be.
618 let streamTimer: ReturnType<typeof setTimeout> | undefined;
619 const armStream = (): void => {
620 if (options.nightly === false || stopped) return;
621 streamTimer = setTimeout(() => {
622 void during("snapshot-stream", async () => {
623 if (active === 0) await streamNow();
624 }, undefined, app)
625 .catch((error) => log.error("stream pass failed", { error: String(error) }))
626 .finally(armStream);
627 }, options.streamEveryMs ?? STREAM_EVERY_MS);
628 streamTimer.unref?.();
629 };
630 armStream();
631
587632 // The board only reads; the time the forge first owed a drill is kept here.
588633 try {
589634 seedFirstSeen(app.config.dataDir);
@@ -727,6 +772,7 @@ export function startSnapshots(
727772 mirrorFresh,
728773 checkBucket: bucket.pass,
729774 takeIfDue,
775 streamNow,
730776 mirrored: () => lastMirror(app.config.dataDir),
731777 forget: () => {
732778 resolved = undefined;
@@ -735,6 +781,8 @@ export function startSnapshots(
735781 stop: async () => {
736782 stopped = true;
737783 if (timer !== undefined) clearTimeout(timer);
784 if (streamTimer !== undefined) clearTimeout(streamTimer);
785 if (streaming !== undefined) await streaming.catch(() => {});
738786 if (drillTimer !== undefined) clearTimeout(drillTimer);
739787 if (catchUp !== undefined) clearTimeout(catchUp);
740788 if (redRetry !== undefined) clearTimeout(redRetry);
src/snapshot/snapshot.ts +57 −27
@@ -331,8 +331,18 @@ export interface Snapshotter {
331331 readonly hostedGit?: HostedTools["git"];
332332 readonly hostedFilesMax?: HostedTools["filesMax"];
333333 readonly hostedHistoryMax?: HostedTools["historyMax"];
334 /**
335 * The stream's one pass (#16858): only this hosted forge is taken, and its manifest is written to
336 * `stream/<name>/manifest.json` (replacing the last) instead of a snapshot of its own. Chunks are
337 * the snapshot's, so a forge unchanged since the last pass sends nothing.
338 */
339 readonly stream?: string | undefined;
334340 }
335341
342 /** Where the stream's manifests sit: one per hosted forge, always the newest pass. */
343 export const STREAM_PREFIX = "stream/";
344 export const streamManifestKey = (forge: string): string => `${STREAM_PREFIX}${forge}/manifest.json`;
345
336346 /**
337347 * A prefix with no manifest (a snapshot from before chunks, cut short) is cleared once it began
338348 * this long ago.
@@ -385,6 +395,7 @@ export async function takeSnapshot(
385395 at = new Date(),
386396 ): Promise<Manifest> {
387397 const name = snapshotName(at);
398 const streaming = forge.stream !== undefined;
388399 const prefix = `${SNAPSHOT_PREFIX}${name}/`;
389400 const scratch = mkdtempSync(join(tmpdir(), "forge-snapshot-"));
390401 const files: SnapshotFile[] = [];
@@ -536,30 +547,32 @@ export async function takeSnapshot(
536547 there = new Set(await store.list(CHUNK_PREFIX));
537548 const heldBefore = there.size;
538549 // The database, consistently, from the live connection.
539 const dbCopy = join(scratch, "forge.db");
540 await vacuumInto(forge.db, dbCopy);
541 const copy = new Database(dbCopy, { readonly: true });
542 try {
543 dbCounts = countRows(copy);
544 } catch {
545 // A database that cannot be counted is the drill's to find; the snapshot still goes up.
546 } finally {
547 copy.close();
550 if (!streaming) {
551 const dbCopy = join(scratch, "forge.db");
552 await vacuumInto(forge.db, dbCopy);
553 const copy = new Database(dbCopy, { readonly: true });
554 try {
555 dbCounts = countRows(copy);
556 } catch {
557 // A database that cannot be counted is the drill's to find; the snapshot still goes up.
558 } finally {
559 copy.close();
560 }
561 // Cut at fixed offsets, large (`chunks.ts`): a copy is a fresh file, so a changed database
562 // goes whole.
563 await putFile("forge.db", dbCopy, "fixed");
564 const database = files[files.length - 1];
565 log.info("database copied", {
566 mb: ((database?.bytes ?? 0) / 1_048_576).toFixed(1),
567 chunks: database?.chunks?.length ?? 0,
568 sent: landed,
569 });
570 rmSync(dbCopy, { force: true });
548571 }
549 // Cut at fixed offsets, large (`chunks.ts`): a copy is a fresh file, so a changed database goes
550 // whole.
551 await putFile("forge.db", dbCopy, "fixed");
552 const database = files[files.length - 1];
553 log.info("database copied", {
554 mb: ((database?.bytes ?? 0) / 1_048_576).toFixed(1),
555 chunks: database?.chunks?.length ?? 0,
556 sent: landed,
557 });
558 rmSync(dbCopy, { force: true });
559572 // The key travels only wrapped. Without a passphrase it stays home.
560573 let key: Manifest["key"] = "none";
561574 const keyFile = Bun.file(join(forge.dataDir, "secret.key"));
562 if (forge.passphrase && (await keyFile.exists())) {
575 if (!streaming && forge.passphrase && (await keyFile.exists())) {
563576 const raw = new Uint8Array(await keyFile.arrayBuffer());
564577 const wrapped = wrapKey(raw, forge.passphrase);
565578 if (unwrapKey(wrapped, forge.passphrase) === undefined)
@@ -567,13 +580,13 @@ export async function takeSnapshot(
567580 await putBytes(WRAPPED_KEY, new TextEncoder().encode(wrapped));
568581 key = "wrapped";
569582 }
570 for (const f of filesUnder(join(forge.dataDir, "ssh")))
583 for (const f of streaming ? [] : filesUnder(join(forge.dataDir, "ssh")))
571584 await putFile(`ssh/${f}`, join(forge.dataDir, "ssh", f));
572585
573586 // Every repository as a bundle of every ref: one file, consistent by git's own
574587 // reading of the refs (`bundle.ts`). None is left out without the manifest saying
575588 // which and why, and a ref whose commits are missing costs that ref, not the repository.
576 const repos = listEveryRepo(forge.db);
589 const repos = streaming ? [] : listEveryRepo(forge.db);
577590 const repositories: string[] = [];
578591 const absent: AbsentRepo[] = [];
579592 const brokenRefs: BrokenRefs[] = [];
@@ -642,13 +655,13 @@ export async function takeSnapshot(
642655 }
643656 return withData;
644657 };
645 const kept = await putAppData(listApps(forge.db), forge.dataDir, "", "");
658 const kept = streaming ? 0 : await putAppData(listApps(forge.db), forge.dataDir, "", "");
646659
647660 // Every hosted forge (#13819), each under its own prefix so one restores alone, and read from
648661 // inside its own directory only (`copyHosted`). A forge that cannot be read costs that forge,
649662 // never the snapshot; the manifest says which, and names a repository it left out.
650663 const hosted: HostedEntry[] = [];
651 for (const child of hostedSources(forge.dataDir)) {
664 for (const child of hostedSources(forge.dataDir).filter((c) => forge.stream === undefined || c.name === forge.stream)) {
652665 const into = `${HOSTED_PREFIX}${child.name}/`;
653666 const from = files.length;
654667 const at = new Date().toISOString();
@@ -681,7 +694,7 @@ export async function takeSnapshot(
681694 // Every app's drop (`drop/store.ts`): reference material the owner dropped for the crew, kept
682695 // nowhere else. An upload still in flight (a dot-file) is not part of it.
683696 const dropped = join(forge.dataDir, "drop");
684 for (const f of filesUnder(dropped))
697 for (const f of streaming ? [] : filesUnder(dropped))
685698 if (!f.split("/").some((part) => part.startsWith("."))) await putFile(`drop/${f}`, join(dropped, f));
686699
687700 // The crew's run logs: history a person may want back. A day's worth to
@@ -690,7 +703,7 @@ export async function takeSnapshot(
690703 // same bytes in every later snapshot, so they go up once.
691704 const runsDir = join(forge.dataDir, "runs");
692705 const days = new Map<string, { path: string; size: number; at: number }[]>();
693 for (const f of filesUnder(runsDir)) {
706 for (const f of streaming ? [] : filesUnder(runsDir)) {
694707 const age = statSync(join(runsDir, f), { throwIfNoEntry: false });
695708 if (age === undefined) continue;
696709 const day = age.mtime.toISOString().slice(0, 10);
@@ -746,13 +759,17 @@ export async function takeSnapshot(
746759 hosted,
747760 sent: { chunks: landed, bytes: landedBytes, held: found },
748761 };
762 // The stream keeps its last whole pass: a forge the copy refused is a failure, not an empty
763 // pass.
764 const refused = streaming ? hosted.find((h) => h.why !== undefined) : undefined;
765 if (refused !== undefined) throw new Error(`the stream of ${refused.name} was not written: ${refused.why}`);
outdated

In stream mode, do not write the stream manifest when the forge's hosted entry carries why: it would replace the last good manifest with an empty one.

749766 // Announced only when whole: every chunk it names, seen in the store now.
750767 const named = chunksNamed(manifest);
751768 const missing = await missingChunks(store, named);
752769 if (missing.length > 0)
753770 throw new Error(`${missing.length} of the ${named.length} chunks this snapshot names are not in ${store.where} (first ${missing[0]}); no manifest written`);
754771 await store.put(
755 `${prefix}manifest.json`,
772 forge.stream === undefined ? `${prefix}manifest.json` : streamManifestKey(forge.stream),
756773 JSON.stringify(manifest, null, 2),
757774 );
758775 log.info("snapshot taken", {
@@ -881,6 +898,19 @@ export async function sweepChunks(store: Store): Promise<number | undefined> {
881898 }
882899 for (const id of ids) marked.add(await storedChunk(store, id));
883900 }
901 // The stream's manifests name chunks too (#16858): each forge's newest pass is kept whole.
902 const streamed = await store.names(STREAM_PREFIX);
903 for (const forgeName of streamed) {
904 const body = await store.get(streamManifestKey(forgeName));
905 if (body === undefined) continue;
906 try {
907 const m = JSON.parse(new TextDecoder().decode(body)) as Manifest;
908 if (typeof m !== "object" || m === null || !Array.isArray(m.files)) return refuse(`the stream manifest of ${forgeName} does not read`);
909 for (const id of chunksNamed(m)) marked.add(await storedChunk(store, id));
910 } catch (error) {
911 return refuse(`the stream manifest of ${forgeName} does not read: ${error instanceof Error ? error.message : String(error)}`);
912 }
913 }
884914 const doomed = (await store.list(CHUNK_PREFIX)).filter((key) => !marked.has(key));
885915 if (doomed.length === 0) return 0;
886916 const seen = new Set(names);
src/snapshot/stream.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * The stream (#16858): each hosted forge's database and git go to the forge's bucket every few
3 * minutes, between the nightly snapshots, so losing the host loses minutes and not a day. A pass
4 * takes one hosted forge at a time through `takeSnapshot` with `stream` set (the same copy, the
5 * same chunks: a forge that did not change sends nothing) and writes its manifest to
6 * `stream/<name>/manifest.json`, replacing the last. `restoreHosted` reads it as the snapshot name
7 * `stream`. What each pass found is kept in one small file under the data directory, so a page
8 * reads the lag with `streamLag` without touching the network. Plain data in, plain
9 * data out.
10 */
11
12 import { readFileSync } from "node:fs";
13 import { join } from "node:path";
14 import { hostedSources } from "./hosted.ts";
15 import { keepJson } from "./kept_file.ts";
16
17 /** How often a pass runs. */
18 export const STREAM_EVERY_MS = 5 * 60_000;
19 /** A forge whose newest pass is older than this is late: three passes missed. */
20 export const STREAM_LATE_MS = 3 * STREAM_EVERY_MS;
21
22 /** One hosted forge as the stream last found it. */
23 export interface StreamEntry {
24 readonly name: string;
25 /** When its newest whole pass finished; undefined when none has. */
26 readonly at?: string;
27 readonly bytes?: number;
28 /** Why the latest attempt failed, when it did. */
29 readonly error?: string;
30 }
31
32 /** A stream entry with its lag worked out at a moment. */
33 export interface StreamLag extends StreamEntry {
34 /** Ms since the newest whole pass; undefined when there is none. */
35 readonly lagMs?: number;
36 readonly late: boolean;
37 }
38
39 const stateFile = (dataDir: string): string => join(dataDir, "snapshot", "stream.json");
40
41 /** Keep what a pass found. */
42 export function noteStream(dataDir: string, entries: readonly StreamEntry[]): void {
43 keepJson(dataDir, "stream.json", entries);
44 }
45
46 /** What the last pass kept; entries that do not read whole are dropped, no file is `[]`. */
47 export function readStream(dataDir: string): StreamEntry[] {
48 try {
49 const v: unknown = JSON.parse(readFileSync(stateFile(dataDir), "utf8"));
50 if (!Array.isArray(v)) return [];
51 const out: StreamEntry[] = [];
52 for (const e of v as Record<string, unknown>[]) {
53 if (typeof e?.["name"] !== "string") continue;
54 const at = typeof e["at"] === "string" && Number.isFinite(Date.parse(e["at"])) ? e["at"] : undefined;
55 out.push({
56 name: e["name"],
57 ...(at === undefined ? {} : { at }),
58 ...(typeof e["bytes"] === "number" ? { bytes: e["bytes"] } : {}),
59 ...(typeof e["error"] === "string" ? { error: e["error"].slice(0, 200) } : {}),
60 });
61 }
62 return out;
63 } catch {
64 return [];
65 }
66 }
67
68 /** Each streamed forge with its lag at `now`, by name. */
69 export function streamLag(dataDir: string, now = Date.now()): StreamLag[] {
70 return readStream(dataDir)
71 .map((e) => {
72 const lagMs = e.at === undefined ? undefined : Math.max(0, now - Date.parse(e.at));
73 return { ...e, ...(lagMs === undefined ? {} : { lagMs }), late: lagMs === undefined || lagMs > STREAM_LATE_MS };
74 })
75 .sort((a, b) => (a.name < b.name ? -1 : 1));
76 }
77
78 /**
79 * One pass over every hosted forge, one after another. `take` stores one forge and answers the
80 * bytes it holds, or throws; a forge that throws costs that forge, never the pass. A forge that is
81 * gone from the host leaves the file; one that failed keeps the time of its last whole pass.
82 */
83 export async function streamPass(
84 dataDir: string,
85 take: (name: string) => Promise<{ readonly bytes: number; readonly hosted?: readonly { readonly why?: string | undefined }[] | undefined }>,
86 now: () => Date = () => new Date(),
87 ): Promise<StreamEntry[]> {
88 const before = new Map(readStream(dataDir).map((e) => [e.name, e]));
89 const out: StreamEntry[] = [];
90 for (const { name } of hostedSources(dataDir)) {
91 try {
92 const m = await take(name);
93 const why = m.hosted?.[0]?.why;
94 if (why !== undefined) throw new Error(why);
95 out.push({ name, at: now().toISOString(), bytes: m.bytes });
96 } catch (error) {
outdated

A take that returns because the forge was left out of the manifest (why set) lands here as a whole pass. Throw on that, so the last good pass and its at stay and error is set.

97 const was = before.get(name);
98 out.push({ name, ...(was?.at === undefined ? {} : { at: was.at }), ...(was?.bytes === undefined ? {} : { bytes: was.bytes }), error: String(error instanceof Error ? error.message : error).slice(0, 200) });
99 }
100 noteStream(dataDir, [...out, ...[...before.values()].filter((e) => !out.some((o) => o.name === e.name))]);
101 }
102 noteStream(dataDir, out);
103 return out;
104 }
test/job-slices.test.ts +1
@@ -314,6 +314,7 @@ const UNTIMED: Record<string, string> = {
314314 "outsider-status-prune": "frees outsider status links past 90 days, one indexed delete an hour (core/outsider_status.ts); the fixture has no links",
315315 snapshot: "copies the database file to disk (VACUUM INTO): I/O off the loop, nightly",
316316 "snapshot-mirror": "uploads a snapshot to the mirror: network, nightly",
317 "snapshot-stream": "streams the hosted forges' databases to the bucket every few minutes: network and file reads off the loop, one pass at a time; the stream tests drive streamNow",
317318 drill: "restores a snapshot into a scratch forge: nightly, I/O",
318319 "release-behind": "reads the forge's own release tags with git; needs FORGE_REPO and its repository",
319320 "release-keeper": "cluster only (FORGE_RELEASE_KEEPER=on): talks to the cluster's API",
test/snapshot-stream.test.ts added +147
@@ -0,0 +1,147 @@
1 /**
2 * Hosted forges stream to the bucket between nightlies (#16858): a pass stores each forge under
3 * `stream/<name>/`, a restore into another directory boots and matches, the nightly's sweep keeps
4 * what the stream names, and the lag is what `streamLag` answers.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
8 import { rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { dirStore } from "../src/blob/store.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { commitLog } from "../src/git/read.ts";
16 import { repoDir } from "../src/git/repos.ts";
17 import { restoreHostedInto } from "../src/snapshot/restore.ts";
18 import { startSnapshots } from "../src/snapshot/service.ts";
19 import { pruneSnapshots, streamManifestKey, takeSnapshot } from "../src/snapshot/snapshot.ts";
20 import { readStream, STREAM_LATE_MS, streamLag, streamPass } from "../src/snapshot/stream.ts";
21 import { pollUntil } from "./helpers/poll.ts";
22
23 const PASS = "correct horse battery staple";
24
25 describe("the stream of hosted forges", () => {
26 let root: string;
27 let parent: App;
28 let child: App;
29 let n = 0;
30 const BODY = "body1";
31
32 beforeAll(async () => {
33 root = mkdtempSync(join(tmpdir(), "forge-stream-"));
34 parent = createApp({ dataDir: join(root, "parent"), port: 0 });
35 child = createApp({ dataDir: join(root, "parent", "children", BODY), port: 0 });
36 const u = await createUser(child.db, { origin: "seed", trusted: true, username: "glint", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
37 if (!u.ok) throw new Error(u.error);
38 const repo = await createRepo(child, u.value, { name: "work", visibility: "private" });
39 if (!repo.ok) throw new Error(String(repo.error));
40 const c = await commitToBranch(child, u.value, repo.value, { message: "streamed work", files: [{ path: "a.txt", content: "kept\n" }] });
41 if (!c.ok) throw new Error(JSON.stringify(c.error));
42 writeFileSync(join(child.config.dataDir, "secret.key"), "k".repeat(32), { mode: 0o600 });
43 mkdirSync(join(root, "parent", "spawn"), { recursive: true });
44 writeFileSync(join(root, "parent", "spawn", "kid.json"), JSON.stringify({ name: "kid", bodyId: BODY, done: true }));
45 });
46
47 afterAll(async () => {
48 child.close();
49 parent.close();
50 await rm(root, { recursive: true, force: true });
51 });
52
53 const shape = () => ({ db: parent.db, dataDir: parent.config.dataDir, reposRoot: parent.reposRoot, version: "t", passphrase: PASS });
54 const pass = (store: ReturnType<typeof dirStore>, now = new Date()) => streamPass(parent.config.dataDir, (name) => takeSnapshot({ ...shape(), stream: name }, store), () => now);
55
56 test("a pass stores the forge alone under stream/, and a restore elsewhere boots and matches", async () => {
57 const store = dirStore(join(root, `store-${n++}`));
58 const got = await pass(store);
59 expect(got.map((e) => e.name)).toEqual(["kid"]);
60 expect(await store.names("snapshots/")).toEqual([]);
61 const m = JSON.parse(new TextDecoder().decode((await store.get(streamManifestKey("kid")))!));
62 expect(m.files.every((f: { path: string }) => f.path.startsWith("children/kid/"))).toBe(true);
63 const dir = join(root, "elsewhere");
64 const one = await restoreHostedInto(store, "stream", "kid", dir, { passphrase: PASS });
65 expect(one.repos).toBe(1);
66 expect(one.key).toBe("restored");
67 expect(readFileSync(join(dir, "children", BODY, "secret.key"), "utf8")).toBe("k".repeat(32));
68 const log = await commitLog(repoDir(join(dir, "children", BODY, "repos"), "glint", "work"), "refs/heads/main", { limit: 5 });
69 expect(log.ok && log.value.map((c) => c.subject)).toContain("streamed work");
70 const opened = createApp({ dataDir: join(dir, "children", BODY), port: 0 });
71 try {
72 expect(opened.db.query("SELECT username FROM user").all()).toEqual([{ username: "glint" }]);
73 expect(opened.db.query("SELECT name FROM repo").all()).toEqual(child.db.query("SELECT name FROM repo").all());
74 } finally {
75 opened.close();
76 }
77 });
78
79 test("a second pass of an unchanged forge sends almost nothing", async () => {
80 const store = dirStore(join(root, `store-${n++}`));
81 await pass(store);
82 const second = await takeSnapshot({ ...shape(), stream: "kid" }, store);
83 expect(second.sent?.chunks).toBeLessThan(3);
84 });
85
86 test("the nightly's sweep keeps the chunks the stream names", async () => {
87 const store = dirStore(join(root, `store-${n++}`));
88 await pass(store);
89 await takeSnapshot(shape(), store, new Date("2026-11-16T03:00:00Z"));
90 await pruneSnapshots(store, 0, Date.now(), true);
91 const dir = join(root, "after-sweep");
92 expect((await restoreHostedInto(store, "stream", "kid", dir, { passphrase: PASS })).repos).toBe(1);
93 });
94
95 test("a restore of a forge the stream does not hold refuses", async () => {
96 const store = dirStore(join(root, `store-${n++}`));
97 await pass(store);
98 await expect(restoreHostedInto(store, "stream", "nobody", join(root, "x"), {})).rejects.toThrow("no stream nobody");
99 });
100
101 test("a failed forge keeps the time of its last whole pass and says why", async () => {
102 const store = dirStore(join(root, `store-${n++}`));
103 await pass(store, new Date("2026-11-30T10:00:00Z"));
104 await streamPass(parent.config.dataDir, async () => { throw new Error("bucket said no"); }, () => new Date("2026-11-30T10:05:00Z"));
105 const [e] = readStream(parent.config.dataDir);
106 expect(e).toMatchObject({ name: "kid", at: "2026-11-30T10:00:00.000Z", error: "bucket said no" });
107 const [row] = streamLag(parent.config.dataDir, Date.parse("2026-11-30T10:07:00Z"));
108 expect(row).toMatchObject({ lagMs: 420_000, late: false });
109 expect(row?.error).toBe("bucket said no");
110 const [late] = streamLag(parent.config.dataDir, Date.parse("2026-11-30T10:00:00Z") + STREAM_LATE_MS + 1);
111 expect(late?.late).toBe(true);
112 });
113
114 test("a refused copy keeps the last good manifest and its time, and says why (#16977)", async () => {
115 const store = dirStore(join(root, `store-${n++}`));
116 await pass(store, new Date("2026-11-30T10:00:00Z"));
117 const good = await store.get(streamManifestKey("kid"));
118 const refuse: NonNullable<Parameters<typeof takeSnapshot>[0]["hostedCopy"]> = async () => {
119 throw new Error("copy refused");
120 };
121 await streamPass(parent.config.dataDir, (name) => takeSnapshot({ ...shape(), stream: name, hostedCopy: refuse }, store), () => new Date("2026-11-30T10:05:00Z"));
122 expect(new TextDecoder().decode((await store.get(streamManifestKey("kid")))!)).toBe(new TextDecoder().decode(good!));
123 const [row] = streamLag(parent.config.dataDir, Date.parse("2026-11-30T10:07:00Z"));
124 expect(row?.at).toBe("2026-11-30T10:00:00.000Z");
125 expect(row?.error).toContain("copy refused");
126 const dir = join(root, "after-refusal");
127 expect((await restoreHostedInto(store, "stream", "kid", dir, { passphrase: PASS })).repos).toBe(1);
128 });
129
130 test("the service streams on its own timer and on request, never beside a snapshot", async () => {
131 const store = dirStore(join(root, `store-${n++}`));
132 const handle = startSnapshots(parent, store, { version: "t", passphrase: PASS, streamEveryMs: 40, nightlyInMs: 3_600_000 });
133 try {
134 const before = Date.now();
135 const streamedAt = (): string | undefined => readStream(parent.config.dataDir).find((e) => e.name === "kid")?.at;
136 await pollUntil(() => Date.parse(streamedAt() ?? "") >= before, "the timer's first pass", 5_000);
137 const seen = streamedAt();
138 expect(Date.parse(seen!)).toBeGreaterThanOrEqual(before);
139 const [now, snap] = await Promise.all([handle.streamNow(), handle.now()]);
140 expect(now?.[0]?.error).toBeUndefined();
141 expect(snap.hosted?.[0]?.name).toBe("kid");
142 expect((await restoreHostedInto(store, "stream", "kid", join(root, "svc"), { passphrase: PASS })).repos).toBe(1);
143 } finally {
144 await handle.stop();
145 }
146 });
147 });

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

Keyboard shortcuts

Docs