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

Runner checks get the impact map, kept results, times and tsc cache: pull checks stop running ~82% of the suite #16876

Merged opened this

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

Merged

runner-seed → main 0 commits 1 thread · 1 unresolved

  • Merged. runner-seed was merged into main as 22a2cae.

Review

Sign in to review this change.
15 files changed +632 −47
src/checks/runner_jobs.ts +20
@@ -78,6 +78,23 @@ export interface RunnerJob {
7878 readonly tree: string;
7979 readonly base: string;
8080 };
81 /**
82 * What the forge seeds the checkout with before the steps, as it seeds its own (`run_tier.ts`):
83 * the impact map, the kept results, the test times and the base's build cache. Absent: none
84 * kept yet.
85 */
86 readonly seeds?: readonly RunnerSeed[];
87 }
88
89 /**
90 * A file the forge seeds the job's checkout with, read-only (`runner_seeds.ts`): its path in the
91 * checkout (`isSeedPath`), its size and its SHA-256. The runner fetches it with the job's token
92 * and writes it only when both match; nothing it writes ever comes back.
93 */
94 export interface RunnerSeed {
95 readonly path: string;
96 readonly bytes: number;
97 readonly sha256: string;
8198 }
8299
83100 /** What a runner reports of one step. */
@@ -465,6 +482,8 @@ export interface HeldJob {
465482 readonly dir: string;
466483 /** The only commits its git door serves: the job's commit, and its base when it has one. */
467484 readonly wants: readonly string[];
485 /** The only files its seed door serves (`runner_seeds.ts`). */
486 readonly seeds: readonly RunnerSeed[];
468487 }
469488
470489 /**
@@ -492,6 +511,7 @@ export function jobByToken(db: Database, jobId: string, presented: string, now:
492511 repoId: row.repo_id,
493512 dir: row.dir,
494513 wants: [job.commit, ...(job.base === undefined ? [] : [job.base])].map((oid) => oid.toLowerCase()),
514 seeds: Array.isArray(job.seeds) ? job.seeds : [],
495515 };
496516 }
497517
src/checks/runner_seeds.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * A runner's checkout is seeded as the forge's own is (#13823, item 1). The forge seeds every
3 * check it runs here with the impact map, the kept results, the test times and the base's build
4 * cache (`run_tier.ts`); a job handed to a runner had none of them, so its fast tier selected by
5 * imports alone: on production 3,722 of 4,536 test files for a three-file change, 12.8 minutes
6 * where the map picks about 130 files in two.
7 *
8 * The same seeding functions fill a directory of the run's own beside the checkouts
9 * (`<checks>/<run>.seeds`), so the same trust rules hold: every file was kept by a default-branch
10 * run, the fast tier inside the checkout still runs everything when the map cannot bound a change
11 * (`needsFull`) and guesses for what it does not reach. The job names each file with its size and
12 * SHA-256, the runner fetches them through a door its job token opens (`GET
13 * /api/v1/runner/jobs/:id/seed`), and the directory goes when the job ends.
14 *
15 * Read-only: no runner writes any of them back. A runner reports only its steps' results
16 * (`runner_step.ts`), and nothing on that path keeps a map, results, times or a cache. A lent
17 * runner gets them too: they describe the repository's own files, which the job already hands it.
18 */
19
20 import { lstatSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs";
21 import { join } from "node:path";
22 import { sha256 } from "../kernel/hash.ts";
23 import { CHECK_CACHE, restoreCache } from "./cache.ts";
24 import { seedImpact } from "./impact-store.ts";
25 import { seedKept } from "./kept-store.ts";
26 import type { RunnerSeed } from "./runner_jobs.ts";
27 import { SEED_BYTES_MAX, SEED_FILES, isSeedPath } from "./seed_paths.ts";
28 import { checksRoot, removeRunDir } from "./sweep.ts";
29 import { seedTimes } from "./times-store.ts";
30
31 /** The directory a run's seeds wait in while its runner may fetch them. */
32 export const seedsDir = (dataDir: string, runId: string): string => join(checksRoot(dataDir), `${runId}.seeds`);
33
34 /**
35 * Seed the run's directory from the forge's stores and list what it holds. Says one line for the
36 * log: what the runner is given, or that nothing is kept yet.
37 */
38 export function prepareSeeds(
39 dataDir: string,
40 repo: { readonly id: string; readonly defaultBranch: string },
41 runId: string,
42 builtOnBase: string | undefined,
43 write: (line: string) => void,
44 ): RunnerSeed[] {
45 const dir = seedsDir(dataDir, runId);
46 rmSync(dir, { recursive: true, force: true });
47 mkdirSync(dir, { recursive: true });
48 const given: string[] = [];
49 const seed = (what: string, fill: () => string | undefined): void => {
50 try {
51 const said = fill();
52 if (said !== undefined) given.push(said);
53 } catch (error) {
54 write(`${what} not seeded for the runner: ${String(error)}`);
55 }
56 };
57 seed("impact map", () => ((n) => (n > 0 ? `impact map (${n} tests)` : undefined))(seedImpact(dataDir, repo.id, dir)));
58 seed("kept results", () => ((n) => (n > 0 ? `kept results (${n} tests)` : undefined))(seedKept(dataDir, repo.id, dir)));
59 seed("test times", () => ((n) => (n > 0 ? `test times (${n} files)` : undefined))(seedTimes(dataDir, repo.id, dir)));
60 seed("build cache", () => {
61 const from = restoreCache(dataDir, repo.id, builtOnBase === undefined ? [] : [builtOnBase], dir);
62 return from === undefined ? undefined : `build cache from ${from.slice(0, 7)}`;
63 });
64 const seeds = listed(dir);
65 write(
66 seeds.length === 0
67 ? `runner seeds: none kept yet; the fast tier there selects by imports`
68 : `runner seeds: ${given.join(", ")}, kept by ${repo.defaultBranch}; read-only, nothing comes back`,
69 );
70 return seeds;
71 }
72
73 /**
74 * Every seed file in `dir`, with its size and hash; a file over the bound or not plain is left out.
75 */
76 function listed(dir: string): RunnerSeed[] {
77 const paths = [...SEED_FILES];
78 try {
79 for (const name of readdirSync(join(dir, CHECK_CACHE)).sort()) paths.push(`${CHECK_CACHE}/${name}`);
80 } catch {
81 // No build cache.
82 }
83 const seeds: RunnerSeed[] = [];
84 for (const path of paths) {
85 if (!isSeedPath(path)) continue;
86 const stat = lstatSync(join(dir, path), { throwIfNoEntry: false });
87 if (stat === undefined || !stat.isFile() || stat.size > SEED_BYTES_MAX) continue;
88 seeds.push({ path, bytes: stat.size, sha256: sha256(readFileSync(join(dir, path))) });
89 }
90 return seeds;
91 }
92
93 /**
94 * The bytes of the seed at `path` a job names, from its run's directory; undefined for any path the
95 * job does not name, or a file that is no longer what it named.
96 */
97 export function readSeed(dataDir: string, runId: string, seeds: readonly RunnerSeed[], path: string): Uint8Array | undefined {
98 const seed = seeds.find((s) => s.path === path);
99 if (seed === undefined || !isSeedPath(path)) return undefined;
100 const file = join(seedsDir(dataDir, runId), path);
101 const stat = lstatSync(file, { throwIfNoEntry: false });
102 if (stat === undefined || !stat.isFile() || stat.size !== seed.bytes) return undefined;
103 const bytes = readFileSync(file);
104 return sha256(bytes) === seed.sha256 ? bytes : undefined;
105 }
106
107 /** The job has ended: its seeds go. */
108 export const dropSeeds = (dataDir: string, runId: string): Promise<void> => removeRunDir(seedsDir(dataDir, runId));
src/checks/seed_paths.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * The files a runner's checkout may be seeded with (#13823, item 1), by their path in the
3 * checkout: the impact map, the kept results, the test times and the build cache's files. One
4 * list for both sides: the forge serves nothing else, and a runner writes nothing else.
5 */
6
7 import { CACHE_BYTES, CHECK_CACHE } from "./cache.ts";
8 import { IMPACT_FILE } from "./impact-store.ts";
9 import { KEPT_FILE } from "./kept-store.ts";
10 import { TIMES_FILE } from "./times-store.ts";
11
12 /** What one seed may weigh: the build cache's whole bound, which every other seed is under. */
13 export const SEED_BYTES_MAX = CACHE_BYTES;
14
15 /** The three stores' files, at the top of the checkout. */
16 export const SEED_FILES: readonly string[] = [IMPACT_FILE, KEPT_FILE, TIMES_FILE];
17 /** Every name a seed lives under in the checkout: the files and the build cache's directory. */
18 export const SEED_ROOTS: readonly string[] = [...SEED_FILES, CHECK_CACHE];
19
20 const CACHE_NAME = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}$/;
21
22 /**
23 * Whether `path` names a seed: one of the three stores' files, or a build cache file by a safe
24 * name.
25 */
26 export function isSeedPath(path: string): boolean {
27 if (SEED_FILES.includes(path)) return true;
28 const [dir, name, ...rest] = path.split("/");
29 return dir === CHECK_CACHE && name !== undefined && rest.length === 0 && CACHE_NAME.test(name);
30 }
31
32 /**
33 * At most `most` bytes of `body`, read as they come: undefined when it holds more, its stream
34 * cancelled at the first byte past the bound. A length header is never trusted (a chunked answer
35 * has none), so nothing past the bound is ever held.
36 */
37 export async function readUpTo(body: ReadableStream<Uint8Array> | null, most: number): Promise<Uint8Array | undefined> {
38 if (body === null) return most === 0 ? new Uint8Array(0) : undefined;
39 const reader = body.getReader();
40 const parts: Uint8Array[] = [];
41 let held = 0;
42 for (;;) {
43 const { done, value } = await reader.read();
44 if (done) break;
45 held += value.byteLength;
46 if (held > most) {
47 await reader.cancel().catch(() => {});
48 return undefined;
49 }
50 parts.push(value);
51 }
52 const out = new Uint8Array(held);
53 let at = 0;
54 for (const part of parts) {
55 out.set(part, at);
56 at += part.byteLength;
57 }
58 return out;
59 }
src/checks/sweep.ts +3 −2
@@ -110,8 +110,9 @@ export async function sweepCheckouts(app: App, now: number = Date.now()): Promis
110110 if (STORES.has(name)) continue;
111111 // A gate has no run row: its checkout is spared until no gate could still be using it.
112112 if (name.startsWith("gate-") && gateMayBeRunning(join(root, name), now)) continue;
113 // `<id>.home` is the home of run `<id>`: it lives and dies with it.
114 const id = name.endsWith(".home") ? name.slice(0, -5) : name;
113 // `<id>.home` is the home of run `<id>`, and `<id>.seeds` what its runner is seeded with
114 // (`runner_seeds.ts`): each lives and dies with it.
115 const id = name.replace(/\.(home|seeds)$/, "");
115116 const gate = GATE_DIR.exec(id);
116117 if (gate !== null) {
117118 if (!gateHolding(app.db, gate[1]!, since)) await removeRunDir(join(root, name));
src/checks/tier_runner.ts +53 −44
@@ -20,6 +20,7 @@ import { sampleLentGreen, type LentGreen } from "../actions/runners.ts";
2020 import { isQuarantined } from "../core/quarantine.ts";
2121 import { installCommand } from "./install.ts";
2222 import { runsAsBaseGate, withBaseGateFrom } from "./base_gate.ts";
23 import { dropSeeds, prepareSeeds } from "./runner_seeds.ts";
2324 import { withPlan } from "./plan_line.ts";
2425
2526 /** What a check handed to a runner is made of. */
@@ -86,51 +87,59 @@ export async function tryRunner(
8687 // default is sized as one run here is (`checkShardCpus`), never from the runner machine's CPUs.
8788 const shardCpus = checkShardCpus(resolveLimits("step", manifest.limits).cpus);
8889 write(shardsLine(shardsInForce(app.db, shardCpus, x.tier === "verify")));
89 const sent = await send(app, {
90 runId: x.runId,
91 repoId: repo.id,
92 dir: bare,
93 // Whose pull it is, as a lent runner's authors scope reads it: the origin's login for one
94 // mirrored from there.
95 author: x.pull === undefined ? "" : (x.pull.originAuthor ?? x.pull.authorName),
96 job: {
97 run: x.runId,
98 repo: `${repo.ownerName}/${repo.name}`,
99 commit: run.commitOid,
100 ...(base === undefined ? {} : { base }),
101 depth: base === undefined ? 1 : await headDepth(bare, base, run.commitOid),
102 steps: [
103 ...(install === null ? [] : [{ name: "install" as const, command: install }]),
104 { name: "check" as const, command: step },
105 ],
106 // Only the check's own variables cross, never the forge's; the runner adds its cell's.
107 env: {
108 ...capacityEnv(app.db, shardCpus, x.tier === "verify"),
109 CI: "1",
110 FORGE_URL: options.forgeUrl,
111 FORGE_CHECK: run.id,
112 FORGE_COMMIT: x.commitOid,
113 ...handoverEnv(),
114 ...diffEnv(base, learned, reverts),
115 FORGE_CELLS: "off",
90 // The checkout there is seeded as one here is, read-only (`runner_seeds.ts`).
91 const seeds = prepareSeeds(app.config.dataDir, repo, run.id, builtOnBase, write);
92 let sent: Awaited<ReturnType<typeof send>>;
93 try {
94 sent = await send(app, {
95 runId: x.runId,
96 repoId: repo.id,
97 dir: bare,
98 // Whose pull it is, as a lent runner's authors scope reads it: the origin's login for one
99 // mirrored from there.
100 author: x.pull === undefined ? "" : (x.pull.originAuthor ?? x.pull.authorName),
101 job: {
102 run: x.runId,
103 repo: `${repo.ownerName}/${repo.name}`,
104 commit: run.commitOid,
105 ...(base === undefined ? {} : { base }),
106 depth: base === undefined ? 1 : await headDepth(bare, base, run.commitOid),
107 steps: [
108 ...(install === null ? [] : [{ name: "install" as const, command: install }]),
109 { name: "check" as const, command: step },
110 ],
111 // Only the check's own variables cross, never the forge's; the runner adds its cell's.
112 env: {
113 ...capacityEnv(app.db, shardCpus, x.tier === "verify"),
114 CI: "1",
115 FORGE_URL: options.forgeUrl,
116 FORGE_CHECK: run.id,
117 FORGE_COMMIT: x.commitOid,
118 ...handoverEnv(),
119 ...diffEnv(base, learned, reverts),
120 FORGE_CELLS: "off",
121 },
122 limits: {
123 ...(manifest.limits.cpus === undefined ? {} : { cpus: manifest.limits.cpus }),
124 ...(manifest.limits.memoryMiB === undefined ? {} : { memoryMiB: manifest.limits.memoryMiB }),
125 ...(manifest.limits.diskMiB === undefined ? {} : { diskMiB: manifest.limits.diskMiB }),
126 },
127 timeoutS: manifest.timeout,
128 egress: [...STEP_HOSTS, ...manifest.egress],
129 egressMode: outside ? "enforce" : egressSetting(app.db),
130 // An outside contributor's code runs in a cell or not at all, there as here.
131 cell: outside ? "required" : "preferred",
132 cache: { repo: repo.id, tree: tree.ok ? tree.value.trim() : "", base: builtOnBase ?? "" },
133 ...(seeds.length === 0 ? {} : { seeds }),
116134 },
117 limits: {
118 ...(manifest.limits.cpus === undefined ? {} : { cpus: manifest.limits.cpus }),
119 ...(manifest.limits.memoryMiB === undefined ? {} : { memoryMiB: manifest.limits.memoryMiB }),
120 ...(manifest.limits.diskMiB === undefined ? {} : { diskMiB: manifest.limits.diskMiB }),
121 },
122 timeoutS: manifest.timeout,
123 egress: [...STEP_HOSTS, ...manifest.egress],
124 egressMode: outside ? "enforce" : egressSetting(app.db),
125 // An outside contributor's code runs in a cell or not at all, there as here.
126 cell: outside ? "required" : "preferred",
127 cache: { repo: repo.id, tree: tree.ok ? tree.value.trim() : "", base: builtOnBase ?? "" },
128 },
129 log: write,
130 output: lines,
131 signal,
132 waitMs: lane.placement.waitMs,
133 });
135 log: write,
136 output: lines,
137 signal,
138 waitMs: lane.placement.waitMs,
139 });
140 } finally {
141 await dropSeeds(app.config.dataDir, run.id);
142 }
134143 const verdict = sent.taken ? runnerVerdict(sent, lines, signal.aborted) : sent.why;
135144 if (typeof verdict === "string") write(`placement: runner; ${verdict}; running here`);
136145 else if (verdict.ok && sent.taken && sampleLentGreen(app, sent.runnerId, sent.jobId)) {
src/contract/openapi/routes/getApiV1RunnerJobsIdSeed.ts added +14
@@ -0,0 +1,14 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: "/api/v1/runner/jobs/{id}/seed",
6 summary:
7 "One file a job's checkout is seeded with",
8 detail:
9 "One file a job's checkout is seeded with: the impact map, the kept results, the test times or a build cache file, as the job names it (path, size, SHA-256). Takes that job's token as the bearer; ?path=. Read-only: nothing a runner writes comes back",
10 auth: false,
11 role: "anonymous",
12 query: { path: "string" },
13 refuses: [404],
14 };
src/contract/openapi/routes/index.ts +1
@@ -232,6 +232,7 @@ export { route as getApiV1ReposOwnerNameWaves } from "./getApiV1ReposOwnerNameWa
232232 export { route as getApiV1ReposOwnerNameWavesVersion } from "./getApiV1ReposOwnerNameWavesVersion.ts";
233233 export { route as getApiV1Returns } from "./getApiV1Returns.ts";
234234 export { route as getApiV1RunnerJobsIdGitInfoRefs } from "./getApiV1RunnerJobsIdGitInfoRefs.ts";
235 export { route as getApiV1RunnerJobsIdSeed } from "./getApiV1RunnerJobsIdSeed.ts";
235236 export { route as getApiV1Search } from "./getApiV1Search.ts";
236237 export { route as getApiV1SecretsScope } from "./getApiV1SecretsScope.ts";
237238 export { route as getApiV1StatusToken } from "./getApiV1StatusToken.ts";
src/http/api/runners.ts +13
@@ -26,6 +26,7 @@ import {
2626 settleJob,
2727 type RunnerResult,
2828 } from "../../checks/runner_jobs.ts";
29 import { readSeed } from "../../checks/runner_seeds.ts";
2930 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
3031 import { inFlight } from "../../perf/live.ts";
3132 import { advertiseRefs, serviceRpc } from "../../git/smart-http.ts";
@@ -235,6 +236,18 @@ export function runnerRoutes(router: Router<Handler>): void {
235236 return json({ lease });
236237 });
237238
239 // The job's seed door: the files the forge seeded its checkout with, by the path, size and hash
240 // the job names, and nothing else (`checks/runner_seeds.ts`). Only read: no route takes one back.
241 router.add("GET", "/api/v1/runner/jobs/:id/seed", (ctx) => {
242 const mine = held(ctx);
243 if (mine === undefined) return notFound();
244 const bytes = readSeed(ctx.app.config.dataDir, mine.job.runId, mine.job.seeds, ctx.url.searchParams.get("path") ?? "");
245 if (bytes === undefined) return notFound();
246 return new Response(bytes, {
247 headers: { "content-type": "application/octet-stream", "cache-control": "no-store" },
248 });
249 });
250
238251 // The job's git door: a fetch of its repository, held to the commits the job names.
239252 router.add("GET", "/api/v1/runner/jobs/:id/git/info/refs", (ctx) => {
240253 const mine = held(ctx);
src/kernel/destroy_reach.ts +1
@@ -78,6 +78,7 @@ export const ALLOWED_REMOVALS: readonly { unit: string; why: string }[] = [
7878 "src/checks/impact-store.ts:seedImpact",
7979 "src/checks/kept-store.ts:seedKept",
8080 "src/checks/times-store.ts:seedTimes",
81 "src/checks/runner_seeds.ts:prepareSeeds",
8182 "src/checks/install.ts:prefillInstallCache",
8283 "src/checks/install.ts:holdFile",
8384 "src/checks/install_evict.ts:evictInstallCache",
src/runner/main.ts +2
@@ -34,6 +34,7 @@ import {
3434 import { childEnv, runStep } from "../apps/process.ts";
3535 import { scratchEnv } from "../checks/disk_full.ts";
3636 import { giveHistory } from "../checks/history.ts";
37 import { seedCheckout } from "./seed.ts";
3738 import { cellInstall, prefillInstallCache } from "../checks/install.ts";
3839 import { startFromSnapshots, type Start } from "../checks/snapshot.ts";
3940 import type {
@@ -279,6 +280,7 @@ export async function runRunner(options: RunnerOptions): Promise<void> {
279280 "runner",
280281 `runner: ${job.commit.slice(0, 7)} fetched and checked out in ${((Date.now() - started) / 1000).toFixed(1)}s`,
281282 );
283 line("runner", await seedCheckout(forge, job, token, dir, stop.signal));
282284 const limits = resolveLimits("step", job.limits);
283285 const cell: CellSpec | undefined = cells.ok
284286 ? {
src/runner/seed.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * A runner writes what the forge seeds its job's checkout with (`checks/runner_seeds.ts`): each
3 * file only when its size and hash are what the job names, read no further than that size
4 * (`readUpTo`), after clearing whatever the tree carried at those names. What is not fetched is
5 * left out, and the check then selects by imports, as it would with none.
6 */
7
8 import { mkdirSync, rmSync, writeFileSync } from "node:fs";
9 import { dirname, join } from "node:path";
10 import type { RunnerJob } from "../checks/runner_jobs.ts";
11 import { SEED_BYTES_MAX, SEED_ROOTS, isSeedPath, readUpTo } from "../checks/seed_paths.ts";
12 import { sha256 } from "../kernel/hash.ts";
13
14 /** Seed `dir` for `job` from `forge` with the job's `token`; answers the line for the job's log. */
15 export async function seedCheckout(forge: string, job: RunnerJob, token: string, dir: string, signal: AbortSignal): Promise<string> {
16 // Whatever the tree carried at these names is not the forge's (a map of the pull's own, a
17 // link out): it goes first, whether or not the forge seeds the name.
18 for (const name of SEED_ROOTS) rmSync(join(dir, name), { recursive: true, force: true });
19 const asked = (Array.isArray(job.seeds) ? job.seeds : []).filter(
20 (s) => typeof s?.path === "string" && isSeedPath(s.path) && Number.isInteger(s.bytes) && s.bytes >= 0 && s.bytes <= SEED_BYTES_MAX,
21 );
22 if (asked.length === 0) return "runner: no seeds from the forge; the fast tier selects by imports";
23 const from = Date.now();
24 const got: string[] = [];
25 const missed: string[] = [];
26 for (const s of asked) {
27 try {
28 const res = await fetch(`${forge}/api/v1/runner/jobs/${job.id}/seed?path=${encodeURIComponent(s.path)}`, {
29 headers: { authorization: `Bearer ${token}` },
30 signal,
31 });
32 // Read no further than the job named, whatever the headers say: a chunked answer has none.
33 const bytes = res.ok ? await readUpTo(res.body, s.bytes) : undefined;
34 if (!res.ok) await res.body?.cancel().catch(() => {});
35 if (bytes === undefined || bytes.length !== s.bytes || sha256(bytes) !== s.sha256) {
36 missed.push(`${s.path} (${!res.ok ? `the forge answered ${res.status}` : bytes === undefined ? "longer than the job named" : "not what the job named"})`);
37 continue;
38 }
39 const path = join(dir, s.path);
40 rmSync(path, { recursive: true, force: true });
41 mkdirSync(dirname(path), { recursive: true });
42 writeFileSync(path, bytes, { flag: "wx" });
43 got.push(s.path);
44 } catch (error) {
45 missed.push(`${s.path} (${error instanceof Error ? error.message : String(error)})`);
46 }
47 }
48 return (
49 `runner: seeded ${got.length} of ${asked.length} files from the forge in ${((Date.now() - from) / 1000).toFixed(1)}s` +
50 (got.length === 0 ? "" : `: ${got.join(", ")}`) +
51 (missed.length === 0 ? "" : `; not used: ${missed.join(", ")}`)
52 );
53 }
test/outbound-sweep.test.ts +1
@@ -47,6 +47,7 @@ const ALLOWED: Record<string, { count: number; why: string }> = {
4747 "src/crew/decide.ts": { count: 1, why: "the model endpoint from operator configuration" },
4848 "src/spawn/live.ts": { count: 1, why: "a child forge's own URL, minted by this forge" },
4949 "src/runner/main.ts": { count: 1, why: "the forge a runner was enrolled with, from its own configuration" },
50 "src/runner/seed.ts": { count: 1, why: "the forge a runner was enrolled with, for its job's seeds, read with the job's token" },
5051 "src/release/smoke.ts": { count: 5, why: "the operator's release target" },
5152 "src/release/small_forge.ts": { count: 1, why: "a forge the release check started itself" },
5253 "src/snapshot/verdict.ts": { count: 1, why: "the forge URL from operator configuration" },
test/pages-budget.test.ts +1 −1
@@ -71,7 +71,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
7171 };
7272
7373 /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */
74 const MAX_UNFIXTURED = 162; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) // +1: /:owner/:name/settings/app/flags/:flag, a flag the fixture app does not declare (#1830) // +1: /api/v1/repos/:owner/:name/changes/:room, a change stream of an app that declares sync, which the fixture does not (#10839)
74 const MAX_UNFIXTURED = 163; // +1: /api/v1/runner/jobs/:id/seed, a seed of a runner job, readable only with a claimed job's token, which the fixture holds none of (#16881) // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) // +1: /:owner/:name/settings/app/flags/:flag, a flag the fixture app does not declare (#1830) // +1: /api/v1/repos/:owner/:name/changes/:room, a change stream of an app that declares sync, which the fixture does not (#10839)
7575
7676 /** Streams and live fragments: no page. */
7777 const NOT_PAGES = new Set([
test/runner-seeds.test.ts added +302
@@ -0,0 +1,302 @@
1 /**
2 * A runner's checkout is seeded as the forge's own is (`checks/runner_seeds.ts`, #13823 item 1):
3 * the impact map, the kept results, the test times and the build cache, read-only. Without them a
4 * runner's fast tier selected by imports alone (3,722 of 4,536 files on production for a
5 * three-file change). Here: a job names its seeds, the door serves exactly those to the job's
6 * token, the real runner writes them before the check, what it seeds selects by the map as here
7 * (a kernel or config change still runs everything, a file the map never reached is guessed), and
8 * nothing a runner's checkout does reaches the forge's stores.
9 */
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
12 import { join } from "node:path";
13 import { openPull } from "../src/actions/pulls.ts";
14 import { commitToBranch } from "../src/actions/repos.ts";
15 import { formatImpact, parseImpact, unpackImpact } from "../src/checks/impact.ts";
16 import { formatKept } from "../src/checks/kept.ts";
17 import { deskOf, enrolRunner, type RunnerJob } from "../src/checks/runner_jobs.ts";
18 import { seedsDir } from "../src/checks/runner_seeds.ts";
19 import { readUpTo } from "../src/checks/seed_paths.ts";
20 import { seedCheckout } from "../src/runner/seed.ts";
21 import { startChecks } from "../src/checks/service.ts";
22 import { fastSet } from "../src/checks/tiers.ts";
23 import { formatTimes } from "../src/checks/test_times.ts";
24 import { createToken } from "../src/core/tokens.ts";
25 import { readRunLog } from "../src/runs/log.ts";
26 import { checkJson, checksForge } from "./helpers/checks-forge.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28
29 quietLogs();
30
31 const f = checksForge("forge-runner-seeds-");
32 /**
33 * Where the check copies what it was seeded with: outside its checkout, so the test can read it.
34 */
35 let seen = "";
36 /** Copies the seeds out, then writes over every one of them in its own checkout. */
37 const checkOf = (out: string): string =>
38 [
39 `mkdir -p ${out}`,
40 `cp .forge-impact.json .forge-kept.json .forge-times.json ${out}/`,
41 `ls .forge-cache > ${out}/cache.txt`,
42 "echo tampered > .forge-impact.json",
43 "echo '{}' > .forge-kept.json",
44 "echo tampered > .forge-times.json",
45 "echo tampered > .forge-cache/tsc.tsbuildinfo",
46 ].join(" && ");
47
48 const MAP = new Map<string, string[]>([
49 ["test/a.test.ts", ["src/a.ts", "src/shared.ts"]],
50 ["test/b.test.ts", ["src/b.ts", "src/shared.ts"]],
51 ]);
52 const TESTS = ["test/a.test.ts", "test/b.test.ts", "test/c.test.ts"];
53
54 /** The forge's own stores, as a default-branch run keeps them. */
55 const store = (dir: string): string => join(f.dataDir, "checks", dir, `${f.repo.id.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
56 const cacheFile = (): string =>
57 join(f.dataDir, "check-cache", f.repo.id.replace(/[^A-Za-z0-9_-]/g, "_"), "a".repeat(40), "tsc.tsbuildinfo");
58 const stores = (): string[] => [store("impact"), store("kept"), store("times"), cacheFile()].map((p) => readFileSync(p, "utf8"));
59
60 let adminToken = "";
61 const api = (path: string, token: string, body?: unknown, method?: string): Promise<Response> =>
62 fetch(`${f.servers.url}${path}`, {
63 method: method ?? (body === undefined ? "GET" : "POST"),
64 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
65 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
66 });
67
68 async function pull(name: string, file: string): Promise<string> {
69 const made = await commitToBranch(f.app, f.alice, f.repo, {
70 branch: name,
71 message: `Add ${file}`,
72 files: [{ path: file, content: `${name}\n` }],
73 });
74 if (!made.ok) throw new Error(JSON.stringify(made.error));
75 const opened = await openPull(f.app, f.alice, f.repo, { title: name, body: "", baseBranch: "main", headBranch: name });
76 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
77 return made.value.commitOid;
78 }
79
80 const logOf = (runId: string): string => readRunLog(f.app.config.dataDir, runId).lines.join("\n");
81
82 beforeAll(async () => {
83 seen = join(f.dataDir, "seen");
84 await f.checks.stop();
85 f.checks = startChecks(f.app, { forgeUrl: f.servers.url, concurrency: 1, placement: { mode: "runner", waitMs: 300 } });
86 adminToken = createToken(f.app.db, f.alice.id, "admin", "admin").token;
87 const gate = await commitToBranch(f.app, f.alice, f.repo, {
88 message: "Declare the check",
89 files: [{ path: "forge.json", content: checkJson(checkOf(seen)) }],
90 });
91 if (!gate.ok) throw new Error(JSON.stringify(gate.error));
92 await f.settled((r) => r.commitOid === gate.value.commitOid, 30_000);
93 // What the default branch's measuring runs kept: written here as they would have been.
94 for (const dir of ["impact", "kept", "times"]) mkdirSync(join(f.dataDir, "checks", dir), { recursive: true });
95 writeFileSync(store("impact"), formatImpact(MAP));
96 writeFileSync(store("kept"), formatKept(new Map([["f".repeat(64), { test: "test/a.test.ts", commit: "b".repeat(40) }]])));
97 writeFileSync(
98 store("times"),
99 formatTimes(
100 new Map([
101 ["test/a.test.ts", 1.5],
102 ["test/b.test.ts", 2],
103 ]),
104 ),
105 );
106 mkdirSync(join(cacheFile(), ".."), { recursive: true });
107 writeFileSync(cacheFile(), "tsc build info\n");
108 });
109
110 describe("a job's seeds and their door", () => {
111 test("a job names each seed by path, size and hash; the door serves exactly those to the job's token, and takes none back", async () => {
112 const box = enrolRunner(f.app.db, "by-hand", f.alice.id);
113 const asked = api("/api/v1/runner/claim", box.token, { wait: 20, cells: true });
114 await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim");
115 const oid = await pull("by-hand", "h.txt");
116 const claim = (await (await asked).json()) as { job: RunnerJob; token: string };
117 const seeds = claim.job.seeds ?? [];
118 expect(seeds.map((s) => s.path).sort()).toEqual([
119 ".forge-cache/tsc.tsbuildinfo",
120 ".forge-impact.json",
121 ".forge-kept.json",
122 ".forge-times.json",
123 ]);
124 const door = (path: string) => `/api/v1/runner/jobs/${claim.job.id}/seed?path=${encodeURIComponent(path)}`;
125 for (const s of seeds) {
126 const res = await api(door(s.path), claim.token);
127 expect(res.status).toBe(200);
128 const bytes = new Uint8Array(await res.arrayBuffer());
129 expect(bytes.length).toBe(s.bytes);
130 expect(new Bun.CryptoHasher("sha256").update(bytes).digest("hex")).toBe(s.sha256);
131 }
132 // What the runner is handed selects by the map, as the forge's own check does.
133 const map = await (await api(door(".forge-impact.json"), claim.token)).text();
134 const parsed = parseImpact(map);
135 expect(parsed.ok).toBe(true);
136 if (!parsed.ok) throw new Error(parsed.error);
137 const impact = unpackImpact(parsed.value);
138 if (impact === undefined) throw new Error("the map's packing is broken");
139 const plan = (changed: string[]) => fastSet({ changed, tests: TESTS, imports: () => [], times: new Map(), impact });
140 expect(plan(["src/a.ts"]).files).toEqual(["test/a.test.ts"]);
141 expect(plan(["src/a.ts"]).line).toStartWith("by coverage");
142 // What the map cannot bound runs everything; a file it never reached is guessed, not trusted.
143 expect(plan(["src/kernel/db.ts"]).line).toBe("full tier, src/kernel/db.ts changed");
144 expect(plan(["src/kernel/db.ts"]).files).toEqual(TESTS);
145 expect(plan(["forge.json"]).line).toBe("full tier, forge.json changed");
146 expect(plan(["src/new.ts"]).line).toContain("imports");
147 // Nothing else crosses: no path the job does not name, no other job's token, no write.
148 expect((await api(door("../../forge.db"), claim.token)).status).toBe(404);
149 expect((await api(door(".forge-cache/../../forge.db"), claim.token)).status).toBe(404);
150 expect((await api(door("forge.json"), claim.token)).status).toBe(404);
151 expect((await api(door(".forge-impact.json"), box.token)).status).toBe(404);
152 expect((await api(door(".forge-impact.json"), adminToken)).status).toBe(404);
153 expect([404, 405]).toContain((await api(door(".forge-impact.json"), claim.token, { map: "{}" })).status);
154 expect([404, 405]).toContain((await api(door(".forge-impact.json"), claim.token, { map: "{}" }, "PUT")).status);
155 // A report carrying files of its own lands nothing in the stores.
156 const before = stores();
157 const report = `/api/v1/runner/jobs/${claim.job.id}`;
158 expect(
159 (
160 await api(report, claim.token, {
161 impact: "{}",
162 kept: "{}",
163 times: "{}",
164 done: { steps: [{ name: "check", ok: true, ms: 1 }], contained: true, note: "" },
165 })
166 ).status,
167 ).toBe(200);
168 const run = await f.settled((r) => r.commitOid === oid, 30_000);
169 expect(run.state).toBe("ok");
170 expect(stores()).toEqual(before);
171 expect(logOf(run.id)).toContain(
172 "runner seeds: impact map (2 tests), kept results (1 tests), test times (2 files), build cache from aaaaaaa",
173 );
174 // The job has ended: its seeds are gone, and so is the door.
175 expect(existsSync(seedsDir(f.dataDir, run.id))).toBe(false);
176 expect((await api(door(".forge-impact.json"), claim.token)).status).toBe(404);
177 });
178 });
179
180 describe("with a runner process connected", () => {
181 let proc: ReturnType<typeof Bun.spawn> | undefined;
182
183 beforeAll(async () => {
184 const made = await api("/api/v1/admin/runners", adminToken, { name: "seeded" });
185 expect(made.status).toBe(201);
186 const enrolled = (await made.json()) as { token: string };
187 proc = Bun.spawn([process.execPath, join(import.meta.dir, "..", "src", "runner", "main.ts")], {
188 env: {
189 PATH: process.env["PATH"] ?? "/usr/bin:/bin",
190 HOME: join(f.dataDir, "runner-home"),
191 FORGE_URL: f.servers.url,
192 FORGE_RUNNER_TOKEN: enrolled.token,
193 FORGE_RUNNER_DIR: join(f.dataDir, "runner"),
194 FORGE_CELLS: "off",
195 },
196 stdout: "ignore",
197 stderr: "ignore",
198 });
199 await f.until(() => deskOf(f.app).claimers.size > 0, "the runner process waiting in its claim");
200 });
201 afterAll(async () => {
202 proc?.kill();
203 await proc?.exited;
204 });
205
206 test("the runner writes each seed into its checkout before the check, and nothing the check writes there comes back", async () => {
207 const before = stores();
208 const oid = await pull("seeded", "s.txt");
209 const run = await f.settled((r) => r.commitOid === oid, 30_000);
210 expect(run.state).toBe("ok");
211 expect(run.placement).toBe("runner");
212 // The check saw the forge's own bytes, every one.
213 expect(readFileSync(join(seen, ".forge-impact.json"), "utf8")).toBe(before[0]!);
214 expect(readFileSync(join(seen, ".forge-kept.json"), "utf8")).toBe(before[1]!);
215 expect(readFileSync(join(seen, ".forge-times.json"), "utf8")).toBe(before[2]!);
216 expect(readFileSync(join(seen, "cache.txt"), "utf8").trim()).toBe("tsc.tsbuildinfo");
217 const log = logOf(run.id);
218 expect(log).toContain("runner seeds: impact map (2 tests)");
219 expect(log).toContain("runner: seeded 4 of 4 files from the forge");
220 // It wrote over all of them in its checkout; the forge's stores are as they were.
221 expect(stores()).toEqual(before);
222 expect(existsSync(seedsDir(f.dataDir, run.id))).toBe(false);
223 });
224
225 test("with no map kept, a map the pull ships in its own tree never reaches the check", async () => {
226 // The forge has no map to give: the check's copy of one can only be the pull's.
227 renameSync(store("impact"), `${store("impact")}.aside`);
228 try {
229 const oid = await pull("own-map", ".forge-impact.json");
230 const run = await f.settled((r) => r.commitOid === oid, 30_000);
231 expect(run.state).toBe("failed");
232 expect(logOf(run.id)).toContain("runner seeds: kept results (1 tests)");
233 expect(readFileSync(join(seen, ".forge-impact.json"), "utf8")).not.toContain("own-map");
234 } finally {
235 renameSync(`${store("impact")}.aside`, store("impact"));
236 }
237 });
238 });
239
240 describe("a seed is read no further than the job named", () => {
241 const chunked = (chunks: readonly string[], forever = false): ReadableStream<Uint8Array> => {
242 let i = 0;
243 let pulled = 0;
244 const stream = new ReadableStream<Uint8Array>({
245 pull(c) {
246 pulled++;
247 if (forever || i < chunks.length) c.enqueue(new TextEncoder().encode(forever ? "x".repeat(1024) : chunks[i++]!));
248 else c.close();
249 },
250 });
251 return Object.assign(stream, { pulls: () => pulled });
252 };
253
254 test("a body of the named size is read whole; one byte over is a miss", async () => {
255 expect(new TextDecoder().decode(await readUpTo(chunked(["ab", "cd"]), 4))).toBe("abcd");
256 expect(await readUpTo(chunked(["ab", "cde"]), 4)).toBeUndefined();
257 expect(await readUpTo(null, 0)).toEqual(new Uint8Array(0));
258 });
259
260 test("a chunked answer with no end is cut at the bound, never read to its end", async () => {
261 const endless = chunked([], true) as ReadableStream<Uint8Array> & { pulls: () => number };
262 expect(await readUpTo(endless, 4_096)).toBeUndefined();
263 // Five 1 KiB chunks pass 4 KiB: it stops there, and the stream is cancelled.
264 expect(endless.pulls()).toBeLessThanOrEqual(7);
265 });
266
267 test("a seed door answering chunked and longer than the job named is not written; the named bytes are", async () => {
268 const named = "abcd";
269 let answer = "";
270 const forge = Bun.serve({
271 port: 0,
272 fetch: () =>
273 new Response(
274 new ReadableStream({
275 start(c) {
276 c.enqueue(new TextEncoder().encode(answer.slice(0, 2)));
277 c.enqueue(new TextEncoder().encode(answer.slice(2)));
278 c.close();
279 },
280 }),
281 ),
282 });
283 const dir = join(f.dataDir, "seed-door-tree");
284 mkdirSync(dir, { recursive: true });
285 const job = {
286 id: "job-1",
287 seeds: [{ path: ".forge-impact.json", bytes: named.length, sha256: new Bun.CryptoHasher("sha256").update(named).digest("hex") }],
288 } as unknown as RunnerJob;
289 try {
290 answer = named + "y".repeat(8_192);
291 const over = await seedCheckout(`http://127.0.0.1:${forge.port}`, job, "forge_job_x", dir, new AbortController().signal);
292 expect(over).toContain(".forge-impact.json (longer than the job named)");
293 expect(existsSync(join(dir, ".forge-impact.json"))).toBe(false);
294 answer = named;
295 const right = await seedCheckout(`http://127.0.0.1:${forge.port}`, job, "forge_job_x", dir, new AbortController().signal);
296 expect(right).toContain("seeded 1 of 1 files");
297 expect(readFileSync(join(dir, ".forge-impact.json"), "utf8")).toBe(named);
298 } finally {
299 forge.stop(true);
300 }
301 });
302 });
test/security-floor-routes.test.ts +1
@@ -75,6 +75,7 @@ const UNSEEDED: Record<string, string> = {
7575 "/api/v1/repos/:owner/:name/changes/:room": "an app's change stream needs forge.json sync:true on its default branch, which the seed does not declare (test/app-changes.test.ts covers it)",
7676 "/api/v1/repos/:owner/:name/drop/:file": "a file name in an app's private drop; the seed drops none",
7777 "/api/v1/runner/jobs/:id/git/info/refs": "a job a runner holds, read with that job's own token; the seed offers none (test/checks-runner-placement.test.ts covers it)",
78 "/api/v1/runner/jobs/:id/seed": "a file a runner's job is seeded with, read with that job's own token; the seed offers none (test/runner-seeds.test.ts covers it)",
7879 "/claim/start/:token": "needs a one-time start claim token, which the seed does not mint (test/start.test.ts covers it)",
7980 "/join/:token": "needs a one-use link to work on a repository, which the seed does not mint (test/invite-contributors.test.ts covers it)",
8081 "/signin/access/:token": "needs a one-time access link an admin minted",

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

Keyboard shortcuts

Docs