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

A check starts from the last green check's disk, so a warm check takes seconds #16528

Merged opened this in answer to

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

Merged

scout/forge:scout/16380-a-check-starts-from-the-last-green-check → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/16380-a-check-starts-from-the-last-green-check was merged into main as 1e9295f.

Review

Sign in to review this change.
23 files changed +695 −11
docs/features/check-starts.md added +31
@@ -0,0 +1,31 @@
1 ---
2 topic: When something is wrong
3 row: A check starts from the last green check's disk
4 ---
5 # A check starts from the last green check's disk (#16380)
6
7 A green check of the default branch keeps its installed packages
8 (`node_modules`) as the repository's snapshot, one per install command. The
9 next check of the same repository clones them into its fresh checkout and
10 skips its install, when the snapshot can be verified. Source files always come
11 from the check's own commit.
12
13 ## When a check starts warm
14
15 It starts warm only when the lockfiles and `package.json` hash to what the
16 snapshot was made from, and the snapshot's files match the entries, bytes and
17 newest mtime it recorded. Anything else starts cold and runs `install` as
18 before; the log says why (`snapshot: cold (inputs differ from …)`).
19
20 Only a green default-branch check writes a snapshot. A pull's check reads
21 one, never writes one. Restoring copies the files (copy-on-write where the
22 filesystem has it, a plain copy otherwise), so nothing a check runs shares a
23 file with the snapshot.
24
25 ## Where to see it
26
27 - **Web**: a run page's line "Started warm; setup took 1.2s", and under
28 `/system`, Maintenance's disclosure: "Check starts, last 7 days" with the
29 warm and cold counts and each median setup.
30 - **Terminal**: the System screen's "Check starts, last 7 days" lines (for
31 anyone who can read telemetry), and the same line under a check's log.
src/checks/placement.ts +10
@@ -116,3 +116,13 @@ export function jobSandboxWords(note: string): string {
116116 const rest = note.replace(/[^\x20-\x7e]/g, "").trim();
117117 return rest === "" ? "Held by the cluster: the check ran as a Job." : `Held by the cluster: the check ran as a Job. ${rest}`;
118118 }
119
120 /**
121 * How a check began, for the run page and the log: warm from a snapshot or cold, and its setup
122 * time.
123 */
124 export function startWords(run: { start: string; setupMs: number }): string {
125 if (run.start !== "warm" && run.start !== "cold") return "";
126 const took = run.setupMs < 0 ? "" : `; setup took ${(run.setupMs / 1000).toFixed(1)}s`;
127 return `started ${run.start}${took}`;
128 }
src/checks/run_tier.ts +6 −1
@@ -10,6 +10,7 @@ import { checkKey, provenBy, recordProven } from "./proven.ts";
1010 import { giveHistory } from "./history.ts";
1111 import { readLearned } from "./learned.ts";
1212 import { keepCache, restoreCache } from "./cache.ts";
13 import { keepAfterGreen, setupFromSnapshot } from "./tier_snapshot.ts";
1314 import { clearedIn } from "./base_red.ts";
1415 import { scratchEnv } from "./disk_full.ts";
1516 import { keepImpact, seedImpact } from "./impact-store.ts";
@@ -292,7 +293,9 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco
292293 gate?.value.close();
293294 }
294295 } else {
295 const installed = await runInstall(lane, { dir, env, cell, repo, runId: run.id, manifest, write, signal });
296 const installed = await setupFromSnapshot(app, x, repo.id, dir, manifest.install, write, () =>
297 runInstall(lane, { dir, env, cell, repo, runId: run.id, manifest, write, signal }),
298 );
296299 if (installed !== undefined) return installed;
297300 // The check step's own lines are kept beside what `write` already
298301 // logs, so a failure can be summarised once here — never by reading
@@ -394,6 +397,8 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco
394397 keepCache(app.config.dataDir, repo.id, run.commitOid, dir)
395398 )
396399 write(`cache kept for ${run.commitOid.slice(0, 7)}`);
400 // Only a green check of the default branch becomes the snapshot (#16380).
401 if (x.keep === true && job === undefined) await keepAfterGreen(app, repo.id, dir, manifest.install, run.commitOid, write);
397402 if (x.tier === "full" || x.keepImpact === true) {
398403 try {
399404 const kept = keepImpact(app.config.dataDir, repo.id, dir);
src/checks/runner_jobs.ts +3
@@ -93,6 +93,9 @@ export interface RunnerResult {
9393 /** Whether the steps ran in a cell, and why not when they did not. */
9494 readonly contained: boolean;
9595 readonly note: string;
96 /** How the job began (`checks/snapshot.ts`, #16380) and how long its install step took. */
97 readonly start?: "warm" | "cold";
98 readonly setupMs?: number;
9699 }
97100
98101 export interface Enrolled {
src/checks/runner_pool.ts +3
@@ -147,6 +147,8 @@ export interface PoolOptions {
147147 readonly size: number;
148148 /** Where each runner keeps its scratch and store: a directory under the forge's data. */
149149 readonly dir: string;
150 /** Where the forge keeps repository snapshots; its runners read them (`checks/snapshot.ts`). */
151 readonly snapshots?: string | undefined;
150152 /** The runner's entry. */
151153 readonly entry: string;
152154 readonly spawn?: Spawn | undefined;
@@ -189,6 +191,7 @@ export function startLocalPool(app: App, options: PoolOptions): Pool {
189191 FORGE_URL: options.forgeUrl,
190192 FORGE_RUNNER_TOKEN: token,
191193 FORGE_RUNNER_DIR: dir,
194 ...(options.snapshots === undefined ? {} : { FORGE_RUNNER_SNAPSHOTS: options.snapshots }),
192195 });
193196 live.add(child);
194197 await child.exited.catch(() => 1);
src/checks/runner_step.ts +5
@@ -74,6 +74,8 @@ export type RunnerStepEnd =
7474 readonly runner: string;
7575 readonly contained: boolean;
7676 readonly note: string;
77 readonly start?: "warm" | "cold";
78 readonly setupMs?: number;
7779 }
7880 | { readonly taken: false; readonly why: string };
7981
@@ -211,6 +213,9 @@ export async function runRunnerStep(
211213 contained: result.contained === true,
212214 note:
213215 typeof result.note === "string" ? result.note.slice(0, 200) : "",
216 ...(result.start === "warm" || result.start === "cold"
217 ? { start: result.start, setupMs: Number.isFinite(result.setupMs) ? Number(result.setupMs) : 0 }
218 : {}),
214219 };
215220 }
216221 if (view.state === "returned")
src/checks/snapshot.ts added +233
@@ -0,0 +1,233 @@
1 /**
2 * The last green check's disk, kept for the next (#16380). After a check of the default branch
3 * passes, what its setup produced (the installed packages, `node_modules`) is kept beside the
4 * repository's data: one snapshot per repository and recipe (the install command), replaced
5 * whole by the next green one, bounded in bytes. A later check of the same repository clones it
6 * into its fresh checkout (a copy-on-write clone where the filesystem has one, a plain copy
7 * otherwise: never a hard link, so the code a check runs cannot write into what the next one
8 * restores) and skips its install, since the install's inputs are the ones the snapshot was
9 * made from.
10 *
11 * Source files are never taken from a snapshot: every check exports its own commit, so only what
12 * git does not hold is cloned. A snapshot is trusted only after it is verified: it records the
13 * commit and a hash of its inputs (the recipe and the lockfiles), and a fingerprint of the
14 * directory it holds (entries, bytes, newest mtime), so a mismatch of any kind starts the check
15 * cold. Only a green default-branch check writes one; a pull's code never fills what another
16 * check reads.
17 */
18
19 import { createHash } from "node:crypto";
20 import {
21 existsSync,
22 lstatSync,
23 mkdirSync,
24 readFileSync,
25 renameSync,
26 rmSync,
27 writeFileSync,
28 } from "node:fs";
29 import { lstat, readdir } from "node:fs/promises";
30 import { join } from "node:path";
31 import { isSafeOid } from "../git/guard.ts";
32
33 /** What a snapshot holds: the directories a setup step produces. */
34 export const SNAPSHOT_DIRS = ["node_modules"] as const;
35 /** The files whose content decides whether setup would produce the same thing. */
36 export const INPUT_FILES = ["package.json", "bun.lock", "bun.lockb"] as const;
37 /** A snapshot larger than this is not kept. */
38 export const SNAPSHOT_BYTES = 2 * 1024 * 1024 * 1024;
39 /** A walk over more entries than this is not a snapshot either. */
40 export const SNAPSHOT_ENTRIES = 250_000;
41
42 export interface Fingerprint {
43 readonly entries: number;
44 readonly bytes: number;
45 readonly newestMs: number;
46 }
47
48 export interface SnapshotMeta {
49 readonly commit: string;
50 readonly recipe: string;
51 readonly inputs: string;
52 readonly fingerprint: Fingerprint;
53 readonly madeAt: number;
54 }
55
56 /** How a check began: from a snapshot, or from nothing; with the words for the log. */
57 export type Start =
58 | { readonly state: "warm"; readonly commit: string }
59 | { readonly state: "cold"; readonly why: string };
60
61 const sha = (text: string): string => createHash("sha256").update(text).digest("hex").slice(0, 32);
62
63 /** The recipe a snapshot is one-per: the install command. */
64 export const recipeOf = (install: string): string => sha(`install\0${install}`);
65
66 /** A hash of the recipe and every input file the tree has; the files' absence counts too. */
67 export function inputsOf(tree: string, install: string): string {
68 const hash = createHash("sha256").update(install);
69 for (const name of INPUT_FILES) {
70 const path = join(tree, name);
71 const stat = lstatSync(path, { throwIfNoEntry: false });
72 hash.update(`\0${name}\0`);
73 if (stat?.isFile()) hash.update(readFileSync(path));
74 else hash.update(stat === undefined ? "absent" : "not-a-file");
75 }
76 return hash.digest("hex").slice(0, 32);
77 }
78
79 /**
80 * Entries, bytes and newest mtime under `dir`, symlinks counted and never followed; undefined past
81 * a bound.
82 */
83 export async function fingerprint(dir: string): Promise<Fingerprint | undefined> {
84 let entries = 0;
85 let bytes = 0;
86 let newestMs = 0;
outdated

The walk is synchronous: up to 400,000 lstat calls on the main process, run on every restore and on every keep (twice per keep). That stalls every request while it runs. The pull says it takes about 0.2 s on a large tree, but the bound allows much more, and the forge must not lock up. Fix: use async readdir and lstat with yields, or run the walk in the check's own process, and lower the entry bound.

87 const walk = async (path: string): Promise<boolean> => {
88 for (const name of await readdir(path)) {
89 const child = join(path, name);
90 const stat = await lstat(child);
91 entries++;
92 bytes += stat.size;
93 newestMs = Math.max(newestMs, Math.trunc(stat.mtimeMs));
94 if (entries > SNAPSHOT_ENTRIES || bytes > SNAPSHOT_BYTES) return false;
95 if (stat.isDirectory() && !(await walk(child))) return false;
96 }
97 return true;
98 };
99 try {
100 return (await walk(dir)) ? { entries, bytes, newestMs } : undefined;
101 } catch {
102 return undefined;
103 }
104 }
105
106 const same = (a: Fingerprint, b: Fingerprint): boolean =>
107 a.entries === b.entries && a.bytes === b.bytes && a.newestMs === b.newestMs;
108
109 /** Where a repository's snapshots live under the data directory. */
110 export const snapshotRoot = (dataDir: string, repoId: string): string =>
111 join(dataDir, "check-snapshot", repoId.replace(/[^A-Za-z0-9_-]/g, "_"));
112
113 /** `cp` clones `from` into `to`: copy-on-write where the filesystem has it, else a plain copy. */
114 export async function clone(from: string, to: string): Promise<boolean> {
outdated

HIGH. The cp -a -l fallback hard-links the snapshot's files into the checkout, so both names share one inode. Any check can restore a snapshot, including a pull's check, and the pull's code can then write to a file in node_modules in place. That edit lands in the stored snapshot. The check can then reset the mtime with utimes. The fingerprint is only entries, bytes and newest mtime, never file content, so it still matches. A later green default-branch check restores that poisoned code. This breaks the stated rule that a pull's code never fills what another check reads. Fix: drop the hard-link fallback and copy the files (cp -a without -l) when reflink is unavailable, or make the restored tree read-only. Also verify content, for example by hashing the files, rather than size and mtime. The snapshot must never share inodes with a tree that runs untrusted code.

115 for (const flags of [["-a", "--reflink=always"], ["-a"]]) {
116 rmSync(to, { recursive: true, force: true });
117 const ran = Bun.spawn(["cp", ...flags, "--", from, to], { stdout: "ignore", stderr: "ignore" });
118 if ((await ran.exited) === 0) return true;
119 }
120 rmSync(to, { recursive: true, force: true });
121 return false;
122 }
123
124 function readMeta(dir: string): SnapshotMeta | undefined {
125 try {
126 const m = JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")) as SnapshotMeta;
127 const f = m.fingerprint;
128 return isSafeOid(m.commit) &&
129 typeof m.recipe === "string" &&
130 typeof m.inputs === "string" &&
131 typeof f?.entries === "number" &&
132 typeof f.bytes === "number" &&
133 typeof f.newestMs === "number"
134 ? m
135 : undefined;
136 } catch {
137 return undefined;
138 }
139 }
140
141 /**
142 * Seed `tree` from the repository's snapshot for this recipe, if it can be verified: made from
143 * the same inputs, its files as it recorded them. Anything else leaves `tree` as it was.
144 */
145 export async function restoreSnapshot(root: string, tree: string, install: string): Promise<Start> {
146 const dir = join(root, recipeOf(install));
147 if (!existsSync(dir)) return { state: "cold", why: "no snapshot yet" };
148 const meta = readMeta(dir);
149 if (meta === undefined) return { state: "cold", why: "snapshot has no readable record" };
150 if (meta.recipe !== recipeOf(install)) return { state: "cold", why: "recipe changed" };
151 if (meta.inputs !== inputsOf(tree, install))
152 return { state: "cold", why: `inputs differ from ${meta.commit.slice(0, 7)}'s (lockfile or package.json)` };
153 const held = await fingerprint(join(dir, "tree"));
154 if (held === undefined || !same(held, meta.fingerprint))
155 return { state: "cold", why: "snapshot does not match what it recorded" };
156 for (const name of SNAPSHOT_DIRS) {
157 if (!lstatSync(join(dir, "tree", name), { throwIfNoEntry: false })?.isDirectory()) continue;
158 if (!(await clone(join(dir, "tree", name), join(tree, name)))) {
159 for (const n of SNAPSHOT_DIRS) rmSync(join(tree, n), { recursive: true, force: true });
160 return { state: "cold", why: "snapshot could not be cloned" };
161 }
162 }
163 return { state: "warm", commit: meta.commit };
164 }
165
166 /**
167 * A runner's start: from the snapshots directory the forge shares with it, or cold when it has
168 * none or reading fails. A runner only reads; the forge writes.
169 */
170 export async function startFromSnapshots(
171 snapshots: string | undefined,
172 repoDir: string,
173 tree: string,
174 install: string,
175 ): Promise<Start> {
176 if (snapshots === undefined) return { state: "cold", why: "this runner keeps no snapshots" };
177 try {
178 return await restoreSnapshot(join(snapshots, repoDir), tree, install);
179 } catch (error) {
180 return { state: "cold", why: `snapshot not read: ${String(error)}` };
181 }
182 }
183
184 /**
185 * Keep `tree`'s setup products as the snapshot of `commit`, replacing the recipe's last one
186 * whole. Answers the bytes kept, or undefined when there was nothing to keep or it was too big.
187 */
188 export async function keepSnapshot(
189 root: string,
190 tree: string,
191 install: string,
192 commit: string,
193 now: number = Date.now(),
194 ): Promise<number | undefined> {
195 if (!isSafeOid(commit)) return undefined;
196 const staging = join(root, `.${recipeOf(install)}.${process.pid}`);
197 rmSync(staging, { recursive: true, force: true });
198 mkdirSync(join(staging, "tree"), { recursive: true });
199 try {
200 let kept = false;
201 for (const name of SNAPSHOT_DIRS) {
202 const from = join(tree, name);
203 if (!lstatSync(from, { throwIfNoEntry: false })?.isDirectory()) continue;
204 if ((await fingerprint(from)) === undefined) return undefined;
205 if (!(await clone(from, join(staging, "tree", name)))) return undefined;
206 kept = true;
207 }
208 if (!kept) return undefined;
209 const held = await fingerprint(join(staging, "tree"));
210 if (held === undefined) return undefined;
211 const meta: SnapshotMeta = {
212 commit,
213 recipe: recipeOf(install),
214 inputs: inputsOf(tree, install),
215 fingerprint: held,
216 madeAt: now,
217 };
218 writeFileSync(join(staging, "meta.json"), JSON.stringify(meta));
219 const final = join(root, recipeOf(install));
220 rmSync(final, { recursive: true, force: true });
221 renameSync(staging, final);
222 return held.bytes;
223 } catch {
224 return undefined;
225 } finally {
226 rmSync(staging, { recursive: true, force: true });
227 }
228 }
229
230 /** The snapshot's record for a recipe, for display. */
231 export function snapshotOf(root: string, install: string): SnapshotMeta | undefined {
232 return readMeta(join(root, recipeOf(install)));
233 }
src/checks/starts.ts added +42
@@ -0,0 +1,42 @@
1 import type { Database } from "bun:sqlite";
2
3 /** How checks began over a window: warm from a snapshot, or cold, and the median setup of each. */
4 export interface StartStats {
5 readonly warm: number;
6 readonly cold: number;
7 readonly warmMedianMs: number | null;
8 readonly coldMedianMs: number | null;
9 }
10
11 const median = (xs: readonly number[]): number | null => {
12 if (xs.length === 0) return null;
13 const s = [...xs].sort((a, b) => a - b);
14 return s[Math.floor((s.length - 1) / 2)]!;
15 };
16
17 /** The checks since `sinceIso` that recorded a start (#16380). */
18 export function startStats(db: Database, sinceIso: string): StartStats {
19 const rows = db
20 .query<{ start: string; setup_ms: number }, [string]>(
21 "SELECT start, setup_ms FROM run WHERE kind = 'check' AND start != '' AND setup_ms >= 0 AND created_at >= ?1",
22 )
23 .all(sinceIso);
24 const ms = (s: string): number[] => rows.filter((r) => r.start === s).map((r) => r.setup_ms);
25 return {
26 warm: ms("warm").length,
27 cold: ms("cold").length,
28 warmMedianMs: median(ms("warm")),
29 coldMedianMs: median(ms("cold")),
30 };
31 }
32
33 const secs = (ms: number | null): string => (ms === null ? "none" : `${(ms / 1000).toFixed(1)} s`);
34
35 /** The week's count in one line, for the page and the terminal: "3 warm, 1 cold". */
36 export const startCount = (s: StartStats): string => `${String(s.warm)} warm, ${String(s.cold)} cold`;
37
38 /** The median setup of each start, as label and value rows. */
39 export const startMedians = (s: StartStats): { label: string; value: string }[] => [
40 { label: "Warm median setup", value: secs(s.warmMedianMs) },
41 { label: "Cold median setup", value: secs(s.coldMedianMs) },
42 ];
src/checks/tier_runner.ts +1
@@ -116,6 +116,7 @@ export async function tryRunner(
116116 placement: "runner",
117117 node: sent.runner,
118118 sandbox: { enforced: sent.contained, note: sent.note },
119 ...(sent.start === undefined ? {} : { start: sent.start, setupMs: sent.setupMs }),
119120 });
120121 try {
121122 recordCrashFlakes(app.db, app.bus, repo, lines, { runId: run.id, commit: run.commitOid, pull: true }, verdict.ok);
src/checks/tier_snapshot.ts added +59
@@ -0,0 +1,59 @@
1 import type { App } from "../app.ts";
2 import { noteRunProgress } from "../core/runs.ts";
3 import type { CheckOutcome } from "./runner.ts";
4 import { keepSnapshot, restoreSnapshot, snapshotRoot } from "./snapshot.ts";
5 import { startWords } from "./placement.ts";
6
7 /**
8 * A check's setup, started from the repository's snapshot when one can be verified (#16380): a
9 * warm start clones the installed packages in and the install step is a no-op; a cold one runs
10 * `install` as before. Either way the start and the setup's milliseconds are written to the run
11 * and the log, so the gain is measured.
12 */
13 export async function setupFromSnapshot(
14 app: App,
15 x: { readonly runId?: string | undefined },
16 repoId: string,
17 dir: string,
18 install: string | null,
19 write: (line: string) => void,
20 runInstall: () => Promise<CheckOutcome | undefined>,
21 ): Promise<CheckOutcome | undefined> {
22 if (install === null) return runInstall();
23 const from = Date.now();
24 let start;
25 try {
26 start = await restoreSnapshot(snapshotRoot(app.config.dataDir, repoId), dir, install);
27 } catch (error) {
28 start = { state: "cold" as const, why: `snapshot not read: ${String(error)}` };
29 }
30 let failed: CheckOutcome | undefined;
31 if (start.state === "warm") write(`snapshot: warm from ${start.commit.slice(0, 7)}; install skipped, its inputs are unchanged`);
32 else {
33 write(`snapshot: cold (${start.why})`);
34 failed = await runInstall();
35 }
36 const setupMs = Date.now() - from;
37 const words = startWords({ start: start.state, setupMs });
38 write(`setup: ${words.replace("started ", "")}`);
39 if (x.runId !== undefined) noteRunProgress(app.db, x.runId, { start: start.state, setupMs });
40 return failed;
41 }
42
43 /** After a green check of the default branch: keep what its setup made for the next check. */
44 export async function keepAfterGreen(
45 app: App,
46 repoId: string,
47 dir: string,
48 install: string | null,
49 commit: string,
50 write: (line: string) => void,
51 ): Promise<void> {
52 if (install === null) return;
53 try {
54 const bytes = await keepSnapshot(snapshotRoot(app.config.dataDir, repoId), dir, install, commit);
55 if (bytes !== undefined) write(`snapshot kept for ${commit.slice(0, 7)} (${Math.round(bytes / 1048576)} MiB)`);
56 } catch (error) {
57 write(`snapshot not kept: ${String(error)}`);
58 }
59 }
src/core/migration-pins/20261127100000-check-start.pin added +1
@@ -0,0 +1,1 @@
1 3267b75420e3dedb21d0f484635fd43493e17a47f303783d435d9bd0c8b8e400
src/core/migrations/20261127100000-check-start.ts added +6
@@ -0,0 +1,6 @@
1 // How a check began (#16380): `warm` from the last green check's disk, `cold` from nothing, and
2 // the milliseconds its setup took (-1: not recorded). Additive: two columns.
3 export default `
4 ALTER TABLE run ADD COLUMN start TEXT NOT NULL DEFAULT '';
5 ALTER TABLE run ADD COLUMN setup_ms INTEGER NOT NULL DEFAULT -1;
6 `;
src/core/runs.ts +19 −1
@@ -122,6 +122,13 @@ export interface Run {
122122 readonly placement: string;
123123 /** The node a `job` check's pod ran on; empty otherwise. */
124124 readonly node: string;
125 /**
126 * How a check began: `warm` from the last green check's disk, `cold` from nothing; empty when
127 * unrecorded.
128 */
129 readonly start: string;
130 /** Milliseconds its setup took; -1 when unrecorded. */
131 readonly setupMs: number;
125132 /** A failed check's own detail, when its output was recognised; null otherwise. */
126133 readonly checkDetail: CheckDetail | null;
127134 /** The base tip a pull's check merged the head with; empty when it merged nothing. */
@@ -171,6 +178,8 @@ interface RunRow {
171178 combined_oid: string;
172179 placement: string;
173180 node: string;
181 start: string;
182 setup_ms: number;
174183 variant_group: string | null;
175184 created_at: string;
176185 started_at: string | null;
@@ -207,6 +216,8 @@ const toRun = (r: RunRow): Run => ({
207216 sandboxNote: r.sandbox_note,
208217 placement: r.placement,
209218 node: r.node,
219 start: r.start,
220 setupMs: r.setup_ms,
210221 checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null,
211222 baseOid: r.base_oid,
212223 combinedOid: r.combined_oid,
@@ -491,6 +502,9 @@ export function noteRunProgress(
491502 /** Where a check ran, and the node when a cluster Job did. */
492503 placement?: string | undefined;
493504 node?: string | undefined;
505 /** How a check began and how long its setup took (#16380). */
506 start?: "warm" | "cold" | undefined;
507 setupMs?: number | undefined;
494508 /** The model an agent run ran on (empty: the runner's default), and its prompt version. */
495509 model?: string | undefined;
496510 /** Why that model: the agent's own, or what escalated the run to Opus. */
@@ -507,7 +521,9 @@ export function noteRunProgress(
507521 node = COALESCE(?9, node),
508522 model = COALESCE(?10, model),
509523 prompt_version = COALESCE(?11, prompt_version),
510 model_reason = COALESCE(?12, model_reason)
524 model_reason = COALESCE(?12, model_reason),
525 start = COALESCE(?13, start),
526 setup_ms = COALESCE(?14, setup_ms)
511527 WHERE id = ?1`,
512528 ).run(
513529 runId,
@@ -522,6 +538,8 @@ export function noteRunProgress(
522538 progress.model?.slice(0, 100) ?? null,
523539 progress.promptVersion?.slice(0, 40) ?? null,
524540 progress.modelReason?.slice(0, 60) ?? null,
541 progress.start ?? null,
542 progress.setupMs === undefined ? null : Math.max(0, Math.trunc(progress.setupMs)),
525543 );
526544 }
527545
src/kernel/destroy_reach.ts +3
@@ -72,6 +72,9 @@ export const ALLOWED_REMOVALS: readonly { unit: string; why: string }[] = [
7272 "src/checks/sweep.ts:removeRunDir",
7373 "src/checks/cache.ts:restoreCache",
7474 "src/checks/cache.ts:keepCache",
75 "src/checks/snapshot.ts:clone",
76 "src/checks/snapshot.ts:restoreSnapshot",
77 "src/checks/snapshot.ts:keepSnapshot",
7578 "src/checks/impact-store.ts:seedImpact",
7679 "src/checks/kept-store.ts:seedKept",
7780 "src/checks/times-store.ts:seedTimes",
src/main.ts +1
@@ -698,6 +698,7 @@ const localRunners = (() => {
698698 forgeUrl: servers.url,
699699 size,
700700 dir: join(app.config.dataDir, "runners"),
701 snapshots: join(app.config.dataDir, "check-snapshot"),
701702 entry: join(import.meta.dir, "runner", "main.ts"),
702703 });
703704 })();
src/runner/main.ts +24 −1
@@ -14,6 +14,9 @@
1414 *
1515 * FORGE_RUNNER_DIR where its scratch and store live. @default $TMPDIR/forge-runner
1616 * FORGE_RUNNER_JOBS how many jobs it runs at once. @default 1
17 * FORGE_RUNNER_SNAPSHOTS where the last green check's disk is kept (`checks/snapshot.ts`); the
18 * forge's own runners share its directory. A runner only reads it: the forge
19 * writes it after a green check of the default branch. Unset: every job is cold.
1720 * FORGE_RUNNER_ONCE `1`: one claim, then exit (a test, a cron line)
1821 * FORGE_CELLS `off`: never use cells here; jobs that require one go back to the forge
1922 */
@@ -32,6 +35,7 @@ import { childEnv, runStep } from "../apps/process.ts";
3235 import { scratchEnv } from "../checks/disk_full.ts";
3336 import { giveHistory } from "../checks/history.ts";
3437 import { cellInstall, prefillInstallCache } from "../checks/install.ts";
38 import { startFromSnapshots, type Start } from "../checks/snapshot.ts";
3539 import type {
3640 Claim,
3741 RunnerStepResult,
@@ -56,6 +60,8 @@ export interface RunnerOptions {
5660 /** Where the scratch and the store live. */
5761 readonly root: string;
5862 readonly jobs?: number | undefined;
63 /** The repository snapshots to start from, by repository id; none: every job starts cold. */
64 readonly snapshots?: string | undefined;
5965 readonly once?: boolean | undefined;
6066 /** Stops it: no new claim, and a job in flight is handed back. */
6167 readonly signal?: AbortSignal | undefined;
@@ -315,12 +321,26 @@ export async function runRunner(options: RunnerOptions): Promise<void> {
315321 dirName(job.cache.repo),
316322 );
317323 const steps: RunnerStepResult[] = [];
324 let start: Start | undefined;
325 let setupMs = 0;
318326 for (const step of job.steps) {
319327 if (step.name !== "install" && step.name !== "check") continue;
320328 const from = Date.now();
321329 const log = (text: string): void => line(step.name, text);
322330 let ran;
323 if (step.name === "install" && cell !== undefined) {
331 if (step.name === "install") {
332 // The last green check's disk, when it can be verified: then the install is a no-op.
333 start = await startFromSnapshots(options.snapshots, dirName(job.cache.repo), dir, step.command);
334 line(
335 "runner",
336 start.state === "warm"
337 ? `snapshot: warm from ${start.commit.slice(0, 7)}; install skipped, its inputs are unchanged`
338 : `snapshot: cold (${start.why})`,
339 );
340 }
341 if (step.name === "install" && start?.state === "warm") {
342 ran = { ok: true as const, value: undefined };
343 } else if (step.name === "install" && cell !== undefined) {
324344 // As on the forge: this machine fills the repository's cache without running scripts,
325345 // and the cell installs from it read-only, so no job writes what the next one installs.
326346 const fill = await prefillInstallCache({
@@ -356,6 +376,7 @@ export async function runRunner(options: RunnerOptions): Promise<void> {
356376 cell,
357377 });
358378 }
379 if (step.name === "install") setupMs = Date.now() - from;
359380 steps.push({
360381 name: step.name,
361382 ok: ran.ok,
@@ -371,6 +392,7 @@ export async function runRunner(options: RunnerOptions): Promise<void> {
371392 steps,
372393 contained: cell !== undefined,
373394 note: cells.ok ? "" : cells.reason,
395 ...(start === undefined ? {} : { start: start.state, setupMs }),
374396 },
375397 });
376398 const failed = steps.find((s) => !s.ok);
@@ -444,6 +466,7 @@ if (import.meta.main) {
444466 token,
445467 root: process.env["FORGE_RUNNER_DIR"] ?? join(tmpdir(), "forge-runner"),
446468 jobs: Number(process.env["FORGE_RUNNER_JOBS"] ?? "1") || 1,
469 snapshots: process.env["FORGE_RUNNER_SNAPSHOTS"] || undefined,
447470 once: process.env["FORGE_RUNNER_ONCE"] === "1",
448471 signal: stopping.signal,
449472 });
src/tui/screens/runlog.ts +6 −3
@@ -24,7 +24,7 @@ import { Scroll, live, openOnWeb } from "./common.ts";
2424 import { costText, envLabel, runTone } from "./runwords.ts";
2525 import { priceWords } from "../../core/run_price.ts";
2626 import { getUsage } from "../../core/usage.ts";
27 import { jobSandboxWords } from "../../checks/placement.ts";
27 import { jobSandboxWords, startWords } from "../../checks/placement.ts";
2828
2929 const LOG_LINES = 200;
3030
@@ -120,8 +120,11 @@ export function runLogScreen(
120120 const run = view.run;
121121 // A Job's wall rests on the cluster as well as the forge: the terminal says so, as the page
122122 // does. One sentence a row, so a narrow terminal cuts neither.
123 const wall =
124 run.placement === "job" && run.sandboxEnforced === true ? jobSandboxWords(run.sandboxNote).split(/(?<=\.) /) : [];
123 const began = startWords(run);
124 const wall = [
125 ...(run.placement === "job" && run.sandboxEnforced === true ? jobSandboxWords(run.sandboxNote).split(/(?<=\.) /) : []),
126 ...(began === "" ? [] : [`${began[0]!.toUpperCase()}${began.slice(1)}.`]),
127 ];
125128 const rows = split(area, "v", [
126129 len(1),
127130 ...(price === "" ? [] : [len(1)]),
src/tui/screens/system.ts +11
@@ -57,6 +57,7 @@ import { dbSize, dbSizeNeed, type DbSize } from "../../system/db_size.ts";
5757 import { footprintVerdict, lastFootprint, smallWords } from "../../system/footprint.ts";
5858 import { lastProof } from "../../release/prove.ts";
5959 import { leastUsed, routeUsage, WINDOW_DAYS } from "../../core/usage_report.ts";
60 import { startCount, startMedians, startStats } from "../../checks/starts.ts";
6061 import { slowestRoutes } from "../../perf/history.ts";
6162 import { budgetFor } from "../../perf/budgets.ts";
6263 import { knownPatterns } from "../../http/server.ts";
@@ -218,6 +219,14 @@ export function footprintLines(session: Session, f = lastFootprint() ?? lastProo
218219 return [head, ...wrap(footprintVerdict(f), inner), ...small, ...(off.length === 0 ? [] : [truncate(`off: ${off.join(", ")}`, inner)])];
219220 }
220221
222 /** /system's check starts (#16380): the week's warm and cold count and each median setup. */
223 export function startLines(session: Session, inner = WIDTH - 6): string[] {
224 if (!telemetryReader(session.app, session.user)) return [];
225 const s = startStats(session.app.db, new Date(Date.now() - 7 * 86_400_000).toISOString());
226 const med = startMedians(s).map((f) => `${f.label} ${f.value}`).join(" · ");
227 return [truncate(`Check starts, last 7 days: ${startCount(s)}`, inner), truncate(med, inner)];
228 }
229
221230 /**
222231 * /system's "Least used pages and tools" (#15073), the three least used route patterns seen; the
223232 * page and /settings/usage list more.
@@ -418,6 +427,7 @@ export function systemScreen(ctx: Ctx, lines: readonly string[], session: Sessio
418427 // and only for a reader.
419428 const db = reads ? dbSizeLines(session, dbSize.peek(session.app.db, session.app.config.dataDir, session.app.log), true) : [];
420429 const footprint = footprintLines(session);
430 const starts = startLines(session);
421431 const routes = routeUseLines(session);
422432 const slow = slowRouteLines(session);
423433 const buttons = dialog(s, area, ctx.theme.c, {
@@ -430,6 +440,7 @@ export function systemScreen(ctx: Ctx, lines: readonly string[], session: Sessio
430440 // Under the largest directories with no blank between: the dialog does not scroll.
431441 ...db,
432442 ...(footprint.length === 0 ? [] : ["", ...footprint]),
443 ...(starts.length === 0 ? [] : ["", ...starts]),
433444 ...(routes.length === 0 ? [] : ["", ...routes]),
434445 ...(slow.length === 0 ? [] : ["", ...slow]),
435446 ...(offered ? ["", ...readerLines(session)] : []),
src/web/pages/system.ts +4 −3
@@ -56,6 +56,7 @@ import { flashTo, page } from "../layout.ts";
5656 import { systemLiveJs } from "../system-live.ts";
5757 import { RECENT_BYTES, recentEncodings } from "../../http/compress.ts";
5858 import { KEPT_PAGE_BYTES, keptPageStats } from "./kept_page.ts";
59 import { startCount, startMedians, startStats, type StartStats } from "../../checks/starts.ts";
5960 import { COLUMN_BYTES, PARTS_BYTES, keptPartsStats, treeCacheStats } from "./tree_cache.ts";
6061 import { featureHealth, type FeatureHealth } from "../../system/feature_health.ts";
6162 import { egressReportedLine } from "../../system/egress_line.ts";
@@ -161,10 +162,10 @@ export function dbSizeSection(size: DbSize): Html {
161162
162163 /** One line per maintenance worker: what it found this week, what it did, when it last ran
outdated

Principles 1, 3 and 7. The disclosure holds a sentence that explains the heading again (1). A two-row table is boxed where dl rows are what the design asks for a fact (7). A new first-view section needs the budget raised by 9 words and 2 blocks, which is a cap loosened where removing something would do. Fix: show "Check starts, last 7 days: 3 warm, 1 cold" as a line in an existing section, such as Maintenance. Put the median setup as dl rows behind that section's disclosure, drop the explanatory sentence, and leave the budget as it was.

163164 * (#12436). */
164 export function maintenanceSection(rows: readonly WeekRow[]): Html {
165 export function maintenanceSection(rows: readonly WeekRow[], starts?: StartStats): Html {
165166 // First sight: the heading and one sentence; the rows open behind one disclosure.
166167 return html`<section class="settings-block" id="sys-maintenance"><h2>Maintenance, last 7 days</h2>
167 ${disclosure(weekWords(rows), html`<ul class="list" aria-label="Each maintenance worker: found, acted, last run">${rows.map((r) =>
168 ${disclosure(weekWords(rows), html`${starts === undefined ? null : html`<dl class="row-facts" id="sys-starts"><div><dt>Check starts, last 7 days</dt><dd>${startCount(starts)}</dd></div>${startMedians(starts).map((f) => html`<div><dt>${f.label}</dt><dd>${f.value}</dd></div>`)}</dl>`}<ul class="list" aria-label="Each maintenance worker: found, acted, last run">${rows.map((r) =>
168169 row({
169170 title: r.name,
170171 meta: html`${r.last === null ? null : html`found ${String(r.found)} · acted ${String(r.acted)}`}`,
@@ -824,7 +825,7 @@ export async function systemPage(ctx: Ctx, patterns: () => readonly string[]): P
824825 ${routeUseSection(timePhase(ctx.request, "routes", () => {
825826 return leastUsed(routeUsage(ctx.app.db, patterns(), new Date()));
826827 }))}
827 ${maintenanceSection(timePhase(ctx.request, "maintenance", () => weekRows(ctx.app.db, duties.map((d) => d.name))))}
828 ${maintenanceSection(timePhase(ctx.request, "maintenance", () => weekRows(ctx.app.db, duties.map((d) => d.name))), timePhase(ctx.request, "starts", () => startStats(ctx.app.db, new Date(Date.now() - 7 * 86_400_000).toISOString())))}
828829 ${footprintSection(lastFootprint() ?? lastProof(ctx.app.config.dataDir)?.footprint ?? null)}
829830 ${footingSection(standsOn)}
830831 ${restoreSection(timePhase(ctx.request, "restore", () => restoreLine(lastPass(ctx.app.db), lastDrill(ctx.app.db), Date.now())))}
src/web/studio/run.ts +2 −1
@@ -39,7 +39,7 @@ import { page } from "../layout.ts";
3939 import { badge, btn, card, disclosure, listCard, row as stepRow, sha, type Tone } from "../ui.ts";
4040 import { previewBlock } from "../pages/apps.ts";
4141 import { costText, durationText, RUN_PAGE_CSS, runTitle, runTokens } from "../pages/runs.ts";
42 import { placementLine, sandboxLine } from "./sandbox.ts";
42 import { placementLine, sandboxLine, startLine } from "./sandbox.ts";
4343 import { logBox, runVoice, RUN_TRANSCRIPT_CAP } from "./log.ts";
4444 import { changeHref, tellHref } from "./nouns.ts";
4545 import { crewFace } from "../pixel.ts";
@@ -249,6 +249,7 @@ export async function runView(
249249 )}
250250 ${sandboxLine(run)}
251251 ${placementLine(run)}
252 ${startLine(run)}
252253 ${when(
253254 held.length > 0,
254255 () =>
src/web/studio/sandbox.ts +7 −1
@@ -6,7 +6,7 @@
66 */
77
88 import type { Run } from "../../core/runs.ts";
9 import { jobSandboxWords, placementWords } from "../../checks/placement.ts";
9 import { jobSandboxWords, placementWords, startWords } from "../../checks/placement.ts";
1010 import { html, type Html } from "../html.ts";
1111 import { badge } from "../ui.ts";
1212
@@ -16,6 +16,12 @@ export function placementLine(run: Run): Html | null {
1616 return words === "" ? null : html`<p class="muted small" id="run-placement">${words[0]!.toUpperCase() + words.slice(1)}.</p>`;
1717 }
1818
19 /** Whether the check began from the last green check's disk, and what its setup cost (#16380). */
20 export function startLine(run: Run): Html | null {
21 const words = startWords(run);
22 return words === "" ? null : html`<p class="muted small" id="run-start">${words[0]!.toUpperCase() + words.slice(1)}.</p>`;
23 }
24
1925 export function sandboxLine(run: Run): Html | null {
2026 if (run.sandboxEnforced === null) return null;
2127 const agent = run.kind === "agent";
test/check-snapshot.test.ts added +216
@@ -0,0 +1,216 @@
1 import { describe, expect, test } from "bun:test";
2 import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, utimesSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { fingerprint, keepSnapshot, restoreSnapshot, snapshotOf, startFromSnapshots } from "../src/checks/snapshot.ts";
6 import { startWords } from "../src/checks/placement.ts";
7 import { startCount, startMedians, startStats } from "../src/checks/starts.ts";
8 import { createApp } from "../src/app.ts";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { createRun, getRun, noteRunProgress } from "../src/core/runs.ts";
12 import { rm } from "node:fs/promises";
13 import { keepAfterGreen, setupFromSnapshot } from "../src/checks/tier_snapshot.ts";
14 import { startLine } from "../src/web/studio/sandbox.ts";
15 import { maintenanceSection } from "../src/web/pages/system.ts";
16 import { startLines } from "../src/tui/screens/system.ts";
17 import { Session } from "../src/tui/forge.ts";
18
19 const OID = "a".repeat(40);
20 const INSTALL = "bun install --frozen-lockfile";
21
22 function tree(lock = "lock-1"): string {
23 const dir = mkdtempSync(join(tmpdir(), "snap-tree-"));
24 writeFileSync(join(dir, "package.json"), "{}");
25 writeFileSync(join(dir, "bun.lock"), lock);
26 mkdirSync(join(dir, "node_modules", "pkg"), { recursive: true });
27 writeFileSync(join(dir, "node_modules", "pkg", "index.js"), "module.exports = 1");
28 return dir;
29 }
30
31 function fresh(lock: string): string {
32 const dir = mkdtempSync(join(tmpdir(), "snap-fresh-"));
33 writeFileSync(join(dir, "package.json"), "{}");
34 writeFileSync(join(dir, "bun.lock"), lock);
35 return dir;
36 }
37
38 describe("a check starts from the last green check's disk", () => {
39 test("no snapshot is cold", async () => {
40 const root = mkdtempSync(join(tmpdir(), "snap-root-"));
41 expect((await restoreSnapshot(root, fresh("lock-1"), INSTALL)).state).toBe("cold");
42 });
43
44 test("same inputs start warm and bring the packages; changed lockfile starts cold", async () => {
45 const root = mkdtempSync(join(tmpdir(), "snap-root-"));
46 const bytes = await keepSnapshot(root, tree("lock-1"), INSTALL, OID);
47 expect(bytes).toBeGreaterThan(0);
48 expect(snapshotOf(root, INSTALL)?.commit).toBe(OID);
49
50 const warm = fresh("lock-1");
51 const started = performance.now();
52 const start = await restoreSnapshot(root, warm, INSTALL);
53 expect(performance.now() - started).toBeLessThan(10_000);
54 expect(start).toEqual({ state: "warm", commit: OID });
55 expect(readFileSync(join(warm, "node_modules", "pkg", "index.js"), "utf8")).toBe("module.exports = 1");
56
57 const cold = fresh("lock-2");
58 const changed = await restoreSnapshot(root, cold, INSTALL);
59 expect(changed.state).toBe("cold");
60 expect(existsSync(join(cold, "node_modules"))).toBe(false);
61 // A different recipe has no snapshot of its own.
62 expect((await restoreSnapshot(root, fresh("lock-1"), "bun install")).state).toBe("cold");
63 });
64
65 test("a snapshot that does not match its record is never trusted", async () => {
66 const root = mkdtempSync(join(tmpdir(), "snap-root-"));
67 await keepSnapshot(root, tree(), INSTALL, OID);
68 const dir = join(root, readdirSync(root)[0]!, "tree", "node_modules", "pkg");
69 writeFileSync(join(dir, "extra.js"), "evil");
70 const start = await restoreSnapshot(root, fresh("lock-1"), INSTALL);
71 expect(start.state).toBe("cold");
72 // An edit in place that keeps the size is caught by its mtime.
73 const root2 = mkdtempSync(join(tmpdir(), "snap-root-"));
74 await keepSnapshot(root2, tree(), INSTALL, OID);
75 const file = join(root2, readdirSync(root2)[0]!, "tree", "node_modules", "pkg", "index.js");
76 writeFileSync(file, "module.exports = 2");
77 utimesSync(file, new Date(), new Date(Date.now() + 5000));
78 expect((await restoreSnapshot(root2, fresh("lock-1"), INSTALL)).state).toBe("cold");
79 });
80
81 test("a restored file shares no inode with the snapshot: writing it in place leaves the snapshot whole", async () => {
82 const root = mkdtempSync(join(tmpdir(), "snap-root-"));
83 await keepSnapshot(root, tree(), INSTALL, OID);
84 const held = join(root, readdirSync(root)[0]!, "tree", "node_modules", "pkg", "index.js");
85 const warm = fresh("lock-1");
86 expect((await restoreSnapshot(root, warm, INSTALL)).state).toBe("warm");
87 const mine = join(warm, "node_modules", "pkg", "index.js");
88 expect(statSync(mine).ino).not.toBe(statSync(held).ino);
89 const then = statSync(held).mtime;
90 writeFileSync(mine, "module.exports = 'poisoned'");
91 utimesSync(mine, then, then);
92 expect(readFileSync(held, "utf8")).toBe("module.exports = 1");
93 expect((await restoreSnapshot(root, fresh("lock-1"), INSTALL)).state).toBe("warm");
94 });
95
96 test("the walk counts entries without blocking, and refuses a missing directory", async () => {
97 const dir = tree();
98 expect(await fingerprint(join(dir, "node_modules"))).toMatchObject({ entries: 2, bytes: expect.any(Number) });
99 expect(await fingerprint(join(dir, "nowhere"))).toBeUndefined();
100 });
101
102 test("a runner starts warm from the shared directory, and cold with none or a stranger's", async () => {
103 const root = mkdtempSync(join(tmpdir(), "snap-root-"));
104 const repoDir = "repo1";
105 await keepSnapshot(join(root, repoDir), tree(), INSTALL, OID);
106 const warm = fresh("lock-1");
107 expect(await startFromSnapshots(root, repoDir, warm, INSTALL)).toEqual({ state: "warm", commit: OID });
108 expect(existsSync(join(warm, "node_modules", "pkg", "index.js"))).toBe(true);
109 expect((await startFromSnapshots(undefined, repoDir, fresh("lock-1"), INSTALL)).state).toBe("cold");
110 expect((await startFromSnapshots(root, "repo2", fresh("lock-1"), INSTALL)).state).toBe("cold");
111 expect((await startFromSnapshots(root, repoDir, fresh("lock-2"), INSTALL)).state).toBe("cold");
112 });
113
114 test("a snapshot that cannot be made leaves the last one untouched", async () => {
115 const root = mkdtempSync(join(tmpdir(), "snap-root-"));
116 await keepSnapshot(root, tree(), INSTALL, OID);
117 expect(await keepSnapshot(root, tree(), INSTALL, "not-a-commit")).toBeUndefined();
118 expect(await keepSnapshot(root, fresh("lock-1"), INSTALL, "b".repeat(40))).toBeUndefined();
119 expect(snapshotOf(root, INSTALL)?.commit).toBe(OID);
120 expect((await restoreSnapshot(root, fresh("lock-1"), INSTALL)).state).toBe("warm");
121 });
122
123 test("the next green one replaces it", async () => {
124 const root = mkdtempSync(join(tmpdir(), "snap-root-"));
125 await keepSnapshot(root, tree("lock-1"), INSTALL, OID);
126 await keepSnapshot(root, tree("lock-2"), INSTALL, "c".repeat(40));
127 expect(snapshotOf(root, INSTALL)?.commit).toBe("c".repeat(40));
128 expect((await restoreSnapshot(root, fresh("lock-1"), INSTALL)).state).toBe("cold");
129 expect((await restoreSnapshot(root, fresh("lock-2"), INSTALL)).state).toBe("warm");
130 });
131 });
132
133 describe("how a check began is measured", () => {
134 test("words", () => {
135 expect(startWords({ start: "warm", setupMs: 1200 })).toBe("started warm; setup took 1.2s");
136 expect(startWords({ start: "", setupMs: -1 })).toBe("");
137 });
138
139 test("the week's warm and cold, with median setup, as the run records them", async () => {
140 const dir = mkdtempSync(join(tmpdir(), "snap-app-"));
141 const app = createApp({ dataDir: dir, port: 0 });
142 try {
143 const u = await createUser(app.db, {
144 origin: "seed", trusted: true, username: "carol", email: "[email protected]",
145 password: "a-good-passphrase", adminIfFirst: true,
146 });
147 if (!u.ok) throw new Error(u.error);
148 const repo = await createRepo(app, u.value, { name: "r", visibility: "private", description: "" });
149 if (!repo.ok) throw new Error(JSON.stringify(repo.error));
150 expect(startStats(app.db, "2000-01-01T00:00:00Z")).toEqual({ warm: 0, cold: 0, warmMedianMs: null, coldMedianMs: null });
151 const note = (start: "warm" | "cold", setupMs: number): string => {
152 const run = createRun(app.db, { repoId: repo.value.id, kind: "check", reason: "t" });
153 noteRunProgress(app.db, run.id, { start, setupMs });
154 return run.id;
155 };
156 const warm = note("warm", 900);
157 note("warm", 1100);
158 note("warm", 1300);
159 note("cold", 40_000);
160 expect(getRun(app.db, warm)).toMatchObject({ start: "warm", setupMs: 900 });
161 // The run page's line, the terminal's lines and the System page's rows say the same.
162 expect(startLine(getRun(app.db, warm)!)?.text).toContain("Started warm; setup took 0.9s.");
163 expect(startLine({ ...getRun(app.db, warm)!, start: "" })).toBeNull();
164 const stats = startStats(app.db, "2000-01-01T00:00:00Z");
165 expect(startCount(stats)).toBe("3 warm, 1 cold");
166 expect(startMedians(stats)[0]).toEqual({ label: "Warm median setup", value: "1.1 s" });
167 const page = maintenanceSection([], stats).text;
168 expect(page).toContain("Check starts, last 7 days");
169 expect(page).toContain("3 warm, 1 cold");
170 expect(page).toContain("40.0 s");
171 const lines = startLines(new Session(app, { sshUsername: "carol", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: u.value }));
172 expect(lines[0]).toBe("Check starts, last 7 days: 3 warm, 1 cold");
173 expect(lines[1]).toContain("Cold median setup 40.0 s");
174 expect(startStats(app.db, "2000-01-01T00:00:00Z")).toEqual({ warm: 3, cold: 1, warmMedianMs: 1100, coldMedianMs: 40_000 });
175 } finally {
176 app.db.close();
177 await rm(dir, { recursive: true, force: true });
178 }
179 });
180
181 test("setup keeps and restores through the tier: cold runs the install, warm skips it, both are recorded", async () => {
182 const dir = mkdtempSync(join(tmpdir(), "snap-tier-"));
183 const app = createApp({ dataDir: dir, port: 0 });
184 try {
185 const u = await createUser(app.db, {
186 origin: "seed", trusted: true, username: "dana", email: "[email protected]",
187 password: "a-good-passphrase", adminIfFirst: true,
188 });
189 if (!u.ok) throw new Error(u.error);
190 const repo = await createRepo(app, u.value, { name: "t", visibility: "private", description: "" });
191 if (!repo.ok) throw new Error(JSON.stringify(repo.error));
192 const log: string[] = [];
193 let installs = 0;
194 const install = async (): Promise<undefined> => { installs++; return undefined; };
195 const first = createRun(app.db, { repoId: repo.value.id, kind: "check", reason: "t" });
196 const coldTree = tree();
197 expect(await setupFromSnapshot(app, { runId: first.id }, repo.value.id, coldTree, INSTALL, (l) => log.push(l), install)).toBeUndefined();
198 expect(installs).toBe(1);
199 expect(getRun(app.db, first.id)).toMatchObject({ start: "cold" });
200 await keepAfterGreen(app, repo.value.id, coldTree, INSTALL, OID, (l) => log.push(l));
201 expect(log.some((l) => l.startsWith(`snapshot kept for ${OID.slice(0, 7)}`))).toBe(true);
202 const second = createRun(app.db, { repoId: repo.value.id, kind: "check", reason: "t" });
203 const warmTree = fresh("lock-1");
204 await setupFromSnapshot(app, { runId: second.id }, repo.value.id, warmTree, INSTALL, (l) => log.push(l), install);
205 expect(installs).toBe(1);
206 expect(getRun(app.db, second.id)).toMatchObject({ start: "warm" });
207 expect(existsSync(join(warmTree, "node_modules", "pkg", "index.js"))).toBe(true);
208 // No install command: nothing is recorded and the step runs as it was.
209 await setupFromSnapshot(app, {}, repo.value.id, fresh("lock-1"), null, (l) => log.push(l), install);
210 expect(installs).toBe(2);
211 } finally {
212 app.db.close();
213 await rm(dir, { recursive: true, force: true });
214 }
215 });
216 });
test/spawn-sites.test.ts +2
@@ -29,6 +29,8 @@ const SITES: Record<string, string> = {
2929 "a fixed argv, `bun install --frozen-lockfile --ignore-scripts`, in the check's checkout",
3030 "src/checks/runner_pool.ts":
3131 "starts `bun` on the forge's own runner entry, a path the forge builds, with an environment it builds (its URL, a token it made, a directory); no request text",
32 "src/checks/snapshot.ts":
33 "a fixed argv, `cp` with fixed flags, between two directories the forge made (the check cache and the checkout); no request text",
3234 "src/cli/commands/open.ts":
3335 "the CLI hands a forge URL it built to open/xdg-open as one argv element, never through a shell",
3436 "src/cli/config.ts":

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs