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

Main's whole verification runs on a runner and hands back what it measured: releases stop cutting it #17315

opened this

Merged 39h 10m ago, live in production

verify-runners → main 0 commits

  • Merged. verify-runners was merged into main as 7256b20.

Review

Sign in to review this change.
21 files changed +895 −22
docs/features/runners.md +10 −5
@@ -151,11 +151,16 @@ on the runner, when the step ended any other way (a signal, a limit, a full
151151 disk there), and when one or two tests failed: those are re-run alone to tell
152152 a flake from a red, which a runner cannot do yet.
153153
154 Only a **pull's check** goes to a runner. The default branch's own check and a
155 verification after landing keep what they measured (the build cache, the
156 impact map, kept results) from the checkout, and a runner cannot send those
157 back yet, so they stay on the forge's machine. For the same reason a runner's
158 check starts without them: correct, and slower than the forge's own.
154 A **pull's check** goes to a runner, and so does the **default branch's whole
155 verification**: it measures the impact map, the kept results and the test times
156 every pull's check is seeded from, and its runner hands those three files back
157 through its job's hand door (`POST /api/v1/runner/jobs/{id}/hand`, the job's
158 token, only the names the job gives, at most 32 MiB each, never from a lent
159 runner, which never claims such a job either). The forge keeps them once the
160 verdict is in, green or red, as it keeps its own. A verification on a runner
161 survives a release; on the forge's machine a release cut it and it kept
162 nothing (14 of 35 on 2026-12-01). The default branch's own check and a
163 bisection step stay on the forge's machine.
159164
160165 ## What a runner can and cannot see
161166
src/checks/hand_files.ts added +14
@@ -0,0 +1,14 @@
1 /**
2 * What a runner may hand back from main's whole verification, and how big each may be: names and a
3 * bound only, imported by both the forge (`runner_hands.ts`) and the runner (`runner/hand.ts`)
4 * without either pulling in the other's machinery. The names are the stores' own
5 * (`impact-store.ts` IMPACT_FILE, `kept-store.ts` KEPT_FILE, `times-store.ts` TIMES_FILE);
6 * test/runner-hands.test.ts holds them equal.
7 */
8 import { BODY_CAPS } from "../kernel/body_caps.ts";
9
10 /** The files a verification hands back, by their names in its checkout. */
11 export const HAND_FILES: readonly string[] = [".forge-impact.json", ".forge-kept.json", ".forge-times.json"];
12
13 /** The most bytes one handed file may be (production's impact map was 3.9 MB on 2026-12-02). */
14 export const HAND_BYTES_MAX = BODY_CAPS.runnerHand.bytes;
src/checks/runner_hands.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * What a runner hands back from main's whole verification: the impact map, the kept results and
3 * the test times it measured, the three files the forge keeps after a verification of its own
4 * (`run_tier.ts`, `keepImpact` / `keepKept` / `keepTimes`). On 2026-12-01, 14 of 35 verifications
5 * were cut by a release and kept nothing (about 24 CPU-hours), all of them on the forge; a runner's
6 * job survives a release (#16991), so the verification goes to a runner and its files come back
7 * here (#17099 runner adoption).
8 *
9 * Only a job the forge named them for (`hands`, set for the default branch's whole verification
10 * alone: `handsTimesBack`) may hand them, only from a runner this forge owns (never a lent one,
11 * which serves another forge's checks), each by its own name, at most {@link HAND_BYTES_MAX}
12 * bytes, into the run's own directory. They reach the stores only when the run's verdict is in,
13 * through the same functions a verification here uses, so a file is judged as one made here is.
14 */
15
16 import { existsSync, lstatSync, mkdirSync, renameSync, rmSync } from "node:fs";
17 import { join } from "node:path";
18 import { IMPACT_FILE, keepImpact } from "./impact-store.ts";
19 import { KEPT_FILE, keepKept } from "./kept-store.ts";
20 import { TIMES_FILE, keepTimes } from "./times-store.ts";
21 import { checksRoot } from "./sweep.ts";
22 import { HAND_BYTES_MAX, HAND_FILES } from "./hand_files.ts";
23
24
25 /** Where a run's handed files wait for its verdict. */
26 export const handsDir = (dataDir: string, runId: string): string => join(checksRoot(dataDir), `${runId}.hands`);
27
28 /** Why a handed file was not taken; undefined when it was. */
29 export type HandRefusal = "not_named" | "lent" | "too_large";
30
31 /**
32 * Take one handed file for the run, or say why not. The body streams to a part file beside where
33 * it lands, counted as it comes: past the bound it stops, and the part goes; whole, it is renamed
34 * into place. Nothing is read before the job, the name and the declared length pass.
35 */
36 export async function takeHand(
37 dataDir: string,
38 job: { readonly runId: string; readonly hands: readonly string[]; readonly lent: boolean },
39 path: string,
40 body: ReadableStream<Uint8Array> | null,
41 declared: number,
42 ): Promise<HandRefusal | undefined> {
43 if (job.lent) return "lent";
44 if (!HAND_FILES.includes(path) || !job.hands.includes(path)) return "not_named";
45 if (declared > HAND_BYTES_MAX) return "too_large";
46 const dir = handsDir(dataDir, job.runId);
47 mkdirSync(dir, { recursive: true });
48 const file = join(dir, path);
49 const part = `${file}.part-${process.pid}-${Bun.nanoseconds()}`;
50 const sink = Bun.file(part).writer();
51 let size = 0;
52 let over = false;
53 try {
54 try {
55 if (body !== null)
56 for await (const chunk of body) {
57 size += chunk.byteLength;
58 if (size > HAND_BYTES_MAX) {
59 over = true;
60 break;
61 }
62 sink.write(chunk);
63 }
64 } finally {
65 await sink.end();
66 }
67 if (over) {
68 rmSync(part, { force: true });
69 return "too_large";
70 }
71 rmSync(file, { force: true });
72 renameSync(part, file);
73 return undefined;
74 } catch (error) {
75 rmSync(part, { force: true });
76 throw error;
77 }
78 }
79
80 /**
81 * Keep what the run's runner handed back, as a verification here keeps its own; says each kept
82 * store in the log. Nothing handed, nothing kept.
83 */
84 export function keepHands(dataDir: string, repoId: string, runId: string, write: (line: string) => void): void {
85 const dir = handsDir(dataDir, runId);
86 if (!lstatSync(dir, { throwIfNoEntry: false })?.isDirectory()) return;
87 try {
88 if (existsSync(join(dir, IMPACT_FILE))) {
89 const kept = keepImpact(dataDir, repoId, dir);
90 if (kept !== undefined) write(kept);
91 }
92 if (existsSync(join(dir, KEPT_FILE))) {
93 const results = keepKept(dataDir, repoId, dir, true);
94 if (results !== undefined) write(results);
95 }
96 if (existsSync(join(dir, TIMES_FILE))) {
97 const times = keepTimes(dataDir, repoId, dir, true);
98 if (times !== undefined) write(times);
99 }
100 } catch (error) {
101 write(`handed files not kept: ${String(error)}`);
102 }
103 }
104
105 /** The run's handed files go once its verdict is in. */
106 export function dropHands(dataDir: string, runId: string): void {
107 rmSync(handsDir(dataDir, runId), { recursive: true, force: true });
108 }
src/checks/runner_jobs.ts +20 −3
@@ -84,6 +84,11 @@ export interface RunnerJob {
8484 * kept yet.
8585 */
8686 readonly seeds?: readonly RunnerSeed[];
87 /**
88 * The files this job hands back when its check step ends (`runner_hands.ts`): only main's whole
89 * verification names any, so its impact map, kept results and times reach the forge's stores.
90 */
91 readonly hands?: readonly string[];
8792 }
8893
8994 /**
@@ -466,6 +471,8 @@ export function claimJob(
466471 `SELECT j.id FROM check_job j JOIN repo r ON r.id = j.repo_id
467472 WHERE j.state = 'queued' AND r.visibility = 'public' AND (j.canary_for IS NULL OR j.canary_for = ?1)
468473 AND (?3 = 0 OR j.author IN (SELECT value FROM json_each(?2)))
474 -- A job that hands files back is this forge's own verification: never a lent runner's.
475 AND json_extract(j.spec, '$.hands') IS NULL
469476 ORDER BY j.id LIMIT 8`,
470477 )
471478 .all(runner.id, JSON.stringify(scope.authors), scope.authors.length);
@@ -534,6 +541,10 @@ export interface HeldJob {
534541 readonly wants: readonly string[];
535542 /** The only files its seed door serves (`runner_seeds.ts`). */
536543 readonly seeds: readonly RunnerSeed[];
544 /** The only files its hand door takes (`runner_hands.ts`). */
545 readonly hands: readonly string[];
546 /** Whether the runner holding it is lent (`lent-…` or scoped): one never hands anything back. */
547 readonly lent: boolean;
537548 }
538549
539550 /**
@@ -544,9 +555,13 @@ export interface HeldJob {
544555 export function jobByToken(db: Database, jobId: string, presented: string, now: number): HeldJob | undefined {
545556 if (!presented.startsWith(JOB_TOKEN_PREFIX)) return undefined;
546557 const row = db
547 .query<{ id: string; run_id: string; repo_id: string; dir: string; spec: string }, [string, string, number]>(
548 `SELECT id, run_id, repo_id, dir, spec FROM check_job
549 WHERE id = ?1 AND token_hash = ?2 AND state = 'claimed' AND lease_until > ?3`,
558 .query<
559 { id: string; run_id: string; repo_id: string; dir: string; spec: string; scope: string | null; runner_name: string | null },
560 [string, string, number]
561 >(
562 `SELECT j.id, j.run_id, j.repo_id, j.dir, j.spec, r.scope, r.name AS runner_name
563 FROM check_job j LEFT JOIN check_runner r ON r.id = j.runner_id
564 WHERE j.id = ?1 AND j.token_hash = ?2 AND j.state = 'claimed' AND j.lease_until > ?3`,
550565 )
551566 .get(jobId, sha256(presented), now);
552567 if (row === null) return undefined;
@@ -562,6 +577,8 @@ export function jobByToken(db: Database, jobId: string, presented: string, now:
562577 dir: row.dir,
563578 wants: [job.commit, ...(job.base === undefined ? [] : [job.base])].map((oid) => oid.toLowerCase()),
564579 seeds: Array.isArray(job.seeds) ? job.seeds : [],
580 hands: Array.isArray(job.hands) ? job.hands.filter((h): h is string => typeof h === "string") : [],
581 lent: row.scope !== null || (row.runner_name ?? "").startsWith("lent-"),
565582 };
566583 }
567584
src/checks/runner_step.ts +6 −1
@@ -58,6 +58,9 @@ export function runnerTakes(x: {
5858 readonly isMain?: boolean | undefined;
5959 readonly only?: readonly string[] | undefined;
6060 }): boolean {
61 // Main's whole verification goes to a runner (#17099 adoption survives a release; 14 of 35 were
62 // cut here on 2026-12-01, keeping nothing): what it measures comes back (`runner_hands.ts`).
63 if (x.tier === "verify") return x.keepImpact === true && x.only === undefined;
6164 return (
6265 (x.tier === "fast" || x.tier === "run") &&
6366 x.keep !== true &&
@@ -317,6 +320,8 @@ export function runnerVerdict(
317320 end: Extract<RunnerStepEnd, { taken: true }>,
318321 lines: readonly string[],
319322 aborted: boolean,
323 /** Whether one or two failed tests may be re-run here alone; a verification's red is never. */
324 rerun = true,
320325 ): CheckOutcome | RunnerRed | string {
321326 if (aborted) return { ok: false, error: "check cancelled" };
322327 if (end.ran.ok) return { ok: true };
@@ -325,7 +330,7 @@ export function runnerVerdict(
325330 return `the ${end.failed ?? "job"} did not finish on runner ${end.runner} (${error})`;
326331 if (!VERDICT.test(error) || killedStep(error))
327332 return `runner ${end.runner} could not finish the check (${error})`;
328 if (rerunnable(lines, parseBunTestFailure(lines)) !== undefined) return { alone: true, runner: end.runner, lines, error };
333 if (rerun && rerunnable(lines, parseBunTestFailure(lines)) !== undefined) return { alone: true, runner: end.runner, lines, error };
329334 const { summary, detail } = summariseCheckFailure(lines, error);
330335 return { ok: false, error: summary, detail, stage: checkStage(error) };
331336 }
src/checks/sweep.ts +4 −3
@@ -116,9 +116,10 @@ export async function sweepCheckouts(app: App, now: number = Date.now()): Promis
116116 if (STORES.has(name)) continue;
117117 // A gate has no run row: its checkout is spared until no gate could still be using it.
118118 if (name.startsWith("gate-") && gateMayBeRunning(join(root, name), now)) continue;
119 // `<id>.home` is the home of run `<id>`, and `<id>.seeds` what its runner is seeded with
120 // (`runner_seeds.ts`): each lives and dies with it.
121 const id = name.replace(/\.(home|seeds)$/, "");
119 // `<id>.home` is the home of run `<id>`, `<id>.seeds` what its runner is seeded with
120 // (`runner_seeds.ts`) and `<id>.hands` what its runner handed back (`runner_hands.ts`): each
121 // lives and dies with it.
122 const id = name.replace(/\.(home|seeds|hands)$/, "");
122123 const gate = GATE_DIR.exec(id);
123124 if (gate !== null) {
124125 if (!gateHolding(app.db, gate[1]!, since)) await removeRunDir(join(root, name));
src/checks/tier_runner.ts +52 −5
@@ -6,8 +6,8 @@ import { recordProven } from "./proven.ts";
66 import { headDepth } from "./history.ts";
77 import { diffEnv } from "./revert_exact.ts";
88 import { clearedIn } from "./base_red.ts";
9 import { recordCrashFlakes } from "./flake.ts";
10 import { handoverEnv } from "./handover.ts";
9 import { recordCrashFlakes, recordFlakes, rerunnable } from "./flake.ts";
10 import { handoverEnv, handsTimesBack } from "./handover.ts";
1111 import { capacityEnv, checkShardCpus, egressSetting, shardsInForce, shardsLine } from "../core/capacity.ts";
1212 import { resolveLimits, STEP_HOSTS } from "../apps/contain.ts";
1313 import { HANDED_OVER, runRunnerStep, runnerTakes, runnerVerdict, type RunnerRed } from "./runner_step.ts";
@@ -21,8 +21,24 @@ import { isQuarantined } from "../core/quarantine.ts";
2121 import { installCommand } from "./install.ts";
2222 import { runsAsBaseGate, withBaseGateFrom } from "./base_gate.ts";
2323 import { dropSeeds, prepareSeeds } from "./runner_seeds.ts";
24 import { dropHands, keepHands } from "./runner_hands.ts";
25 import { HAND_FILES } from "./hand_files.ts";
26 import { failedFiles, passedFiles } from "./verify.ts";
27 import { redDetail } from "./report.ts";
28 import { parseBunTestFailure } from "./bun-test.ts";
29 import { withFlaky } from "./rerun.ts";
2430 import { withPlan } from "./plan_line.ts";
2531
32 /** The line a runner says when its verification's red was flakes alone (`runner/flake.ts`). */
33 const FLAKY_GREEN = /^flaky: .* failed in the full run and passed alone; recorded, main stays green$/;
34
35 /** The files a runner re-ran alone and saw pass (`rerun.ts` `rerunLines`). */
36 const greenAlone = (lines: readonly string[]): string[] =>
37 lines.flatMap((l) => {
38 const m = /^rerun: (\S+) green alone in /.exec(l);
39 return m === null ? [] : [m[1]!];
40 });
41
2642 /** What a check handed to a runner is made of. */
2743 export interface RunnerCheck {
2844 readonly run: { readonly id: string; readonly commitOid: string };
@@ -131,6 +147,8 @@ export async function tryRunner(
131147 cell: outside ? "required" : "preferred",
132148 cache: { repo: repo.id, tree: tree.ok ? tree.value.trim() : "", base: builtOnBase ?? "" },
133149 ...(seeds.length === 0 ? {} : { seeds }),
150 // Main's whole verification hands back what it measured (`runner_hands.ts`).
151 ...(handsTimesBack(x) ? { hands: HAND_FILES } : {}),
134152 },
135153 log: write,
136154 output: lines,
@@ -144,13 +162,20 @@ export async function tryRunner(
144162 // it back drops them when the check ends.
145163 if (sent === undefined || sent.taken || sent.why !== HANDED_OVER) await dropSeeds(app.config.dataDir, run.id);
146164 }
165 // What the runner handed back is kept with its verdict, green or red, as a verification here
166 // keeps its own; never one cut or handed over.
167 if (sent !== undefined && sent.taken && !signal.aborted && handsTimesBack(x)) keepHands(app.config.dataDir, repo.id, run.id, write);
168 if (sent === undefined || sent.taken || sent.why !== HANDED_OVER) dropHands(app.config.dataDir, run.id);
169 const verify = x.tier === "verify";
147170 if (sent === undefined) return undefined;
148171 // Handed over: no verdict here, and not run here either; the forge that comes up waits on it.
149172 if (!sent.taken && sent.why === HANDED_OVER) {
150173 write(HANDED_OVER);
151174 return { ok: false, error: HANDED_OVER };
152175 }
153 const verdict = sent.taken ? runnerVerdict(sent, lines, signal.aborted) : sent.why;
176 // A verification's red is its own verdict, named by file for the bisection: never one or two
177 // tests re-run here alone.
178 const verdict = sent.taken ? runnerVerdict(sent, lines, signal.aborted, !verify) : sent.why;
154179 if (typeof verdict === "string") write(`placement: runner; ${verdict}; running here`);
155180 else if ("alone" in verdict) {
156181 write(`placement: runner; one or two tests failed on runner ${verdict.runner}: only they are re-run here, alone, never the whole check`);
@@ -173,10 +198,32 @@ export async function tryRunner(
173198 } catch (error) {
174199 write(`crash flakes not recorded: ${String(error)}`);
175200 }
176 if (!verdict.ok) return withPlan(verdict, lines);
201 if (!verdict.ok)
202 return withPlan(
203 verify
204 ? {
205 ...verdict,
206 // The files its runner re-ran alone green are named, as a red here names them (`rerun.ts`).
207 detail: withFlaky(redDetail(verdict.detail, failedFiles(lines), lines), greenAlone(lines)),
208 passed: passedFiles(lines),
209 }
210 : verdict,
211 lines,
212 );
213 // A verification its runner settled green because its red was flakes (`runner/flake.ts`): the
214 // flakes are recorded here, as `settleFlakes` records its own.
215 if (verify && lines.some((l) => FLAKY_GREEN.test(l))) {
216 const tests = rerunnable(lines, parseBunTestFailure(lines));
217 if (tests !== undefined)
218 try {
219 recordFlakes(app.db, app.bus, repo, tests, { runId: run.id, commit: run.commitOid, pull: false });
220 } catch (error) {
221 write(`flakes not recorded: ${String(error)}`);
222 }
223 }
177224 if (key !== undefined) recordProven(app.db, key, x.id);
178225 const cleared = clearedIn(lines);
179 return withPlan({ ok: true, ...(cleared === undefined ? {} : { cleared }) }, lines);
226 return withPlan({ ok: true, ...(cleared === undefined ? {} : { cleared }), ...(verify ? { passed: passedFiles(lines) } : {}) }, lines);
180227 }
181228 }
182229 return undefined;
src/contract/openapi/routes/index.ts +1
@@ -479,6 +479,7 @@ export { route as postApiV1ReposOwnerNameUpstreamCheck } from "./postApiV1ReposO
479479 export { route as postApiV1RunnerClaim } from "./postApiV1RunnerClaim.ts";
480480 export { route as postApiV1RunnerJobsId } from "./postApiV1RunnerJobsId.ts";
481481 export { route as postApiV1RunnerJobsIdGitGitUploadPack } from "./postApiV1RunnerJobsIdGitGitUploadPack.ts";
482 export { route as postApiV1RunnerJobsIdHand } from "./postApiV1RunnerJobsIdHand.ts";
482483 export { route as postApiV1Sessions } from "./postApiV1Sessions.ts";
483484 export { route as postApiV1Share } from "./postApiV1Share.ts";
484485 export { route as postApiV1Start } from "./postApiV1Start.ts";
src/contract/openapi/routes/postApiV1RunnerJobsIdHand.ts added +14
@@ -0,0 +1,14 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/runner/jobs/{id}/hand",
6 summary:
7 "One file main's whole verification hands back from a runner",
8 detail:
9 "One file main's whole verification measured on a runner, handed back: the impact map, the kept results or the test times, by a name the job gives (?path=), as the raw body, at most 32 MiB. Takes that job's token as the bearer; a lent runner's job, a name the job does not give and any other job's token answer 404. The forge keeps the file only once the run's verdict is in",
10 auth: false,
11 role: "anonymous",
12 query: { path: "string" },
13 refuses: [404],
14 };
src/http/api/runners.ts +25
@@ -9,6 +9,8 @@
99 * stranger's header: no page, no API route and no git door knows them.
1010 */
1111
12 import { dropHands, takeHand } from "../../checks/runner_hands.ts";
13 import { HAND_BYTES_MAX } from "../../checks/hand_files.ts";
1214 import { enrol, hearCanary, list, remove, resume, revoke } from "../../actions/runners.ts";
1315 import type { LendInput } from "../../checks/lent_scope.ts";
1416 import { machineLoad, mayTakeJob, yieldThreshold } from "../../checks/lent_yield.ts";
@@ -253,6 +255,29 @@ export function runnerRoutes(router: Router<Handler>): void {
253255 });
254256 });
255257
258 // The job's hand door: a file main's whole verification measured, by a name the job gives it,
259 // from a runner this forge owns (`checks/runner_hands.ts`). Nothing else comes back this way.
260 router.add("POST", "/api/v1/runner/jobs/:id/hand", async (ctx) => {
261 const token = bearer(ctx.request);
262 const job = jobByToken(ctx.app.db, ctx.params.id!, token, Date.now());
263 if (job === undefined) return notFound();
264 // Streamed to disk, counted as it comes (`takeHand`); the claim is asked again once it is whole.
265 const refused = await takeHand(
266 ctx.app.config.dataDir,
267 job,
268 ctx.url.searchParams.get("path") ?? "",
269 ctx.request.body,
270 Number(ctx.request.headers.get("content-length") ?? "0"),
271 );
272 if (refused === undefined && !holdsClaim(ctx.app.db, job.id, token)) {
273 dropHands(ctx.app.config.dataDir, job.runId);
274 return notFound();
275 }
276 if (refused === "too_large") return apiError("too_large", 413, `at most ${HAND_BYTES_MAX} bytes`);
277 if (refused !== undefined) return notFound();
278 return json({ kept: true });
279 });
280
256281 // The job's git door: a fetch of its repository, held to the commits the job names.
257282 router.add("GET", "/api/v1/runner/jobs/:id/git/info/refs", (ctx) => {
258283 const mine = held(ctx);
src/http/lazy_lists.ts +1
@@ -1231,6 +1231,7 @@ export const API_ROUTES = [
12311231 ["POST", "/api/v1/runner/claim"],
12321232 ["POST", "/api/v1/runner/jobs/:id"],
12331233 ["GET", "/api/v1/runner/jobs/:id/seed"],
1234 ["POST", "/api/v1/runner/jobs/:id/hand"],
12341235 ["GET", "/api/v1/runner/jobs/:id/git/info/refs"],
12351236 ["POST", "/api/v1/runner/jobs/:id/git/git-upload-pack"],
12361237 ["POST", "/api/v1/games/agent/sync"],
src/kernel/body_caps.ts +4
@@ -121,6 +121,10 @@ export const BODY_CAPS = {
121121 bytes: 10 * MIB,
122122 reason: "a PDF sent to a printer: a long document fits, and the refusal names the limit",
123123 },
124 runnerHand: {
125 bytes: 32 * MIB,
126 reason: "one file main's verification hands back from its runner: the impact map, kept results or times, streamed to disk",
127 },
124128 printRaster: {
125129 bytes: 80 * MIB,
126130 reason: "PWG raster sent to a printer: uncompressed pages run large; every page is walked before anything is sent",
src/kernel/destroy_reach.ts +1
@@ -79,6 +79,7 @@ export const ALLOWED_REMOVALS: readonly { unit: string; why: string }[] = [
7979 "src/checks/kept-store.ts:seedKept",
8080 "src/checks/times-store.ts:seedTimes",
8181 "src/checks/runner_seeds.ts:prepareSeeds",
82 "src/checks/runner_hands.ts:dropHands",
8283 "src/checks/install.ts:prefillInstallCache",
8384 "src/checks/install.ts:holdFile",
8485 "src/checks/install_evict.ts:evictInstallCache",
src/runner/flake.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * A red verification of main, settled on its runner as the forge settles one of its own
3 * (`checks/tier_flake.ts` `settleFlakes`, `checks/rerun.ts` `rerunRed`): main's red costs every
4 * pull's check, and now opens the revert lane (#17236), so a flake must not count as red. One or
5 * two failed tests are re-run alone, in the same checkout and cell; if each passes alone, they
6 * are flakes and the verification is green, said in the forge's own words. A red of more is red,
7 * and each failing file is re-run alone once more so the files that pass alone are named
8 * (`flakyUnderLoad`). The forge reads both from the log (`tier_runner.ts`).
9 */
10
11 import { parseBunTestFailure } from "../checks/bun-test.ts";
12 import { passedAlone, rerunCommand, rerunnable } from "../checks/flake.ts";
13 import { rerunFileCommand, rerunRed } from "../checks/rerun.ts";
14 import { failedFiles } from "../checks/verify.ts";
15
16 /** Runs one command in the job's checkout, as its check step ran; its output and whether it passed. */
17 export type RunAlone = (command: string, timeoutMs: number) => Promise<{ ok: boolean; out: string[] }>;
18
19 /** The longest a failed test is given to pass alone, as on the forge. */
20 const RERUN_TIMEOUT_MS = 300_000;
21
22 /** Settle a red verification's `lines`; true when its red was flakes alone, so it is green. */
23 export async function settleVerifyRed(
24 lines: readonly string[],
25 run: RunAlone,
26 say: (line: string) => void,
27 aborted: () => boolean,
28 ): Promise<boolean> {
29 const tests = rerunnable(lines, parseBunTestFailure(lines));
30 if (tests !== undefined) {
31 say(`re-running ${tests.length} failed test(s) alone`);
32 let alone = true;
33 for (const test of tests) {
34 const again = await run(rerunCommand(test), RERUN_TIMEOUT_MS);
35 if (!again.ok || !passedAlone(again.out)) {
36 alone = false;
37 say(`"${test.name}" fails alone too: main is red`);
38 break;
39 }
40 }
41 if (alone) {
42 for (const t of tests) say(`flake: ${t.file} > ${t.name} passed alone`);
43 say(`flaky: ${tests.map((t) => `"${t.name}"`).join(", ")} failed in the full run and passed alone; recorded, main stays green`);
44 return true;
45 }
46 }
47 await rerunRed(
48 { files: failedFiles(lines), inJob: false, killed: false, aborted: aborted() },
49 async (file, timeoutMs) => (await run(rerunFileCommand(file), timeoutMs)).ok,
50 say,
51 );
52 return false;
53 }
src/runner/hand.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * A runner hands back what main's whole verification measured (`checks/runner_hands.ts`): each
3 * file the job names, read from its checkout when its check step ends, sent to the job's hand door
4 * with the job's token. Only names the job gives; a file that is missing, not a plain file, or over
5 * the bound is left out and said so. The forge decides what it keeps.
6 */
7
8 import { lstatSync, readFileSync } from "node:fs";
9 import { join } from "node:path";
10 import { HAND_BYTES_MAX, HAND_FILES } from "../checks/hand_files.ts";
11 import type { RunnerJob } from "../checks/runner_jobs.ts";
12
13 /** Hand `dir`'s named files back to `forge` for `job`; answers the line for the job's log. */
14 export async function handBack(forge: string, job: RunnerJob, token: string, dir: string, signal: AbortSignal): Promise<string> {
15 const named = (Array.isArray(job.hands) ? job.hands : []).filter((h) => HAND_FILES.includes(h));
16 const handed: string[] = [];
17 const missed: string[] = [];
18 for (const name of named) {
19 const path = join(dir, name);
20 const stat = lstatSync(path, { throwIfNoEntry: false });
21 if (stat === undefined || !stat.isFile() || stat.size > HAND_BYTES_MAX) {
22 missed.push(`${name} (${stat === undefined ? "not written" : !stat.isFile() ? "not a plain file" : "over the bound"})`);
23 continue;
24 }
25 try {
26 const res = await fetch(`${forge}/api/v1/runner/jobs/${job.id}/hand?path=${encodeURIComponent(name)}`, {
27 method: "POST",
28 headers: { authorization: `Bearer ${token}`, "content-type": "application/octet-stream" },
29 body: readFileSync(path),
30 signal,
31 });
32 await res.body?.cancel().catch(() => {});
33 if (res.ok) handed.push(name);
34 else missed.push(`${name} (the forge answered ${res.status})`);
35 } catch (error) {
36 missed.push(`${name} (${error instanceof Error ? error.message : String(error)})`);
37 }
38 }
39 return `runner: handed back ${handed.length} of ${named.length} files${handed.length === 0 ? "" : `: ${handed.join(", ")}`}${missed.length === 0 ? "" : `; not handed: ${missed.join(", ")}`}`;
40 }
src/runner/main.ts +36 −2
@@ -37,10 +37,12 @@ import {
3737 resolveLimits,
3838 type CellSpec,
3939 } from "../apps/contain.ts";
40 import { childEnv, runStep } from "../apps/process.ts";
40 import { childEnv, killedStep, runStep } from "../apps/process.ts";
4141 import { scratchEnv } from "../checks/disk_full.ts";
4242 import { giveHistory } from "../checks/history.ts";
4343 import { seedCheckout } from "./seed.ts";
44 import { handBack } from "./hand.ts";
45 import { settleVerifyRed } from "./flake.ts";
4446 import { cellInstall, prefillInstallCache } from "../checks/install.ts";
4547 import { startFromSnapshots, type Start } from "../checks/snapshot.ts";
4648 import type {
@@ -438,7 +440,11 @@ export async function runRunner(options: RunnerOptions): Promise<RunnerEnd> {
438440 for (const step of job.steps) {
439441 if (step.name !== "install" && step.name !== "check") continue;
440442 const from = Date.now();
441 const log = (text: string): void => line(step.name, text);
443 const said: string[] = [];
444 const log = (text: string): void => {
445 if (step.name === "check") said.push(text);
446 line(step.name, text);
447 };
442448 let ran;
443449 if (step.name === "install") {
444450 // The last green check's disk, when it can be verified: then the install is a no-op.
@@ -489,6 +495,31 @@ export async function runRunner(options: RunnerOptions): Promise<RunnerEnd> {
489495 });
490496 }
491497 if (step.name === "install") setupMs = Date.now() - from;
498 // Main's whole verification (the job hands files back) settles its own red here, as the
499 // forge settles one of its own: a flake is not main's red (`flake.ts`).
500 if (step.name === "check" && !ran.ok && Array.isArray(job.hands) && job.hands.length > 0 && !killedStep(ran.error) && !stop.signal.aborted) {
501 const flaky = await settleVerifyRed(
502 said,
503 async (command, ms) => {
504 const out: string[] = [];
505 const again = await runStep("flake", command, {
506 cwd: dir,
507 env,
508 log: (text) => {
509 out.push(text);
510 line("check", text);
511 },
512 signal: stop.signal,
513 timeoutMs: Math.min(ms, timeoutMs),
514 cell,
515 });
516 return { ok: again.ok, out };
517 },
518 (text) => line("check", text),
519 () => stop.signal.aborted,
520 );
521 if (flaky) ran = { ok: true as const, value: undefined };
522 }
492523 steps.push({
493524 name: step.name,
494525 ok: ran.ok,
@@ -499,6 +530,9 @@ export async function runRunner(options: RunnerOptions): Promise<RunnerEnd> {
499530 }
500531 if (stopping.aborted && !dropped)
501532 return await end({ abandon: "the runner is stopping" });
533 // Main's whole verification hands back what it measured, green or red, before it ends.
534 if (Array.isArray(job.hands) && job.hands.length > 0 && steps.some((s) => s.name === "check") && !dropped)
535 line("runner", await handBack(forge, job, token, dir, stop.signal));
502536 await end({
503537 done: {
504538 steps,
test/checks-runner-placement.test.ts +2 −3
@@ -138,9 +138,8 @@ describe("the setting", () => {
138138 expect(
139139 runnerTakes({ tier: "run", keep: true, keepImpact: true, isMain: true }),
140140 ).toBe(false);
141 expect(runnerTakes({ tier: "verify", keep: false, keepImpact: true })).toBe(
142 false,
143 );
141 // Main's whole verification goes to a runner and hands back what it measured (`runner_hands.ts`).
142 expect(runnerTakes({ tier: "verify", keep: false, keepImpact: true })).toBe(true);
144143 expect(runnerTakes({ tier: "full" })).toBe(false);
145144 expect(runnerTakes({ tier: "fast", only: ["a.test.ts"] })).toBe(false);
146145 });
test/outbound-sweep.test.ts +1
@@ -49,6 +49,7 @@ const ALLOWED: Record<string, { count: number; why: string }> = {
4949 "src/spawn/live.ts": { count: 1, why: "a child forge's own URL, minted by this forge" },
5050 "src/runner/main.ts": { count: 1, why: "the forge a runner was enrolled with, from its own configuration" },
5151 "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" },
52 "src/runner/hand.ts": { count: 1, why: "the forge a runner was enrolled with: main's verification hands its measured files back with the job's token" },
5253 "src/release/smoke.ts": { count: 5, why: "the operator's release target" },
5354 "src/release/small_forge.ts": { count: 1, why: "a forge the release check started itself" },
5455 "src/snapshot/verdict.ts": { count: 1, why: "the forge URL from operator configuration" },
test/runner-flake.test.ts added +89
@@ -0,0 +1,89 @@
1 /**
2 * A red verification of main is settled on its runner as the forge settles its own
3 * (`runner/flake.ts`, `checks/tier_flake.ts`): with verifications on runners (#17315) a flake would
4 * otherwise go straight to the bisection and the revert lane (#17236). One or two failed tests
5 * that pass alone are flakes, and main stays green; a red of more stays red, its files that pass
6 * alone named.
7 */
8 import { expect, test } from "bun:test";
9 import { runnerVerdict } from "../src/checks/runner_step.ts";
10 import { settleVerifyRed, type RunAlone } from "../src/runner/flake.ts";
11
12 /** A full run with one failed test, as `bun test` prints it. */
13 const oneRed = ["t/a.test.ts:", "(fail) grp > flaky", " 41 pass", " 1 fail", "Ran 42 tests across 9 files."];
14
15 /** A stand-in for the runner's re-run: what each command prints and whether it exits 0. */
16 const runs = (answer: (command: string) => { ok: boolean; out: string[] }): { run: RunAlone; asked: string[] } => {
17 const asked: string[] = [];
18 return {
19 asked,
20 run: async (command) => {
21 asked.push(command);
22 return answer(command);
23 },
24 };
25 };
26
27 test("a test red in the full run and green alone is a flake: the verification is green, said in the forge's words", async () => {
28 const { run, asked } = runs(() => ({ ok: true, out: [" 1 pass", " 0 fail"] }));
29 const said: string[] = [];
30 const green = await settleVerifyRed(
31 oneRed,
32 run,
33 (l) => said.push(l),
34 () => false,
35 );
36 expect(green).toBe(true);
37 expect(asked).toHaveLength(1);
38 expect(asked[0]).toContain("t/a.test.ts");
39 expect(said).toContain("flake: t/a.test.ts > grp > flaky passed alone");
40 // The line the forge reads to record the flake (`tier_runner.ts` FLAKY_GREEN).
41 expect(said.at(-1)).toMatch(/^flaky: "grp > flaky" failed in the full run and passed alone; recorded, main stays green$/);
42 // So the runner reports its check step green, and the forge's verdict is not red.
43 const verdict = runnerVerdict({ taken: true, ran: { ok: true, value: undefined }, runner: "vx-1", contained: true, note: "" },
44 [...oneRed, ...said],
45 false,
46 false,
47 );
48 expect(verdict).toEqual({ ok: true });
49 });
50
51 test("a test red alone too stays red, and says so", async () => {
52 const { run } = runs(() => ({ ok: false, out: [" 0 pass", " 1 fail"] }));
53 const said: string[] = [];
54 expect(
55 await settleVerifyRed(
56 oneRed,
57 run,
58 (l) => said.push(l),
59 () => false,
60 ),
61 ).toBe(false);
62 expect(said).toContain(`"grp > flaky" fails alone too: main is red`);
63 });
64
65 test("a red of more than two tests stays red; each failing file is re-run alone and the green ones are named", async () => {
66 const manyRed = [
67 "t/a.test.ts:",
68 "(fail) one > x",
69 "t/b.test.ts:",
70 "(fail) two > y",
71 "t/c.test.ts:",
72 "(fail) three > z",
73 " 39 pass",
74 " 3 fail",
75 "Ran 42 tests across 9 files.",
76 ];
77 const { run, asked } = runs((command) => ({ ok: command.includes("t/b.test.ts"), out: [] }));
78 const said: string[] = [];
79 expect(
80 await settleVerifyRed(
81 manyRed,
82 run,
83 (l) => said.push(l),
84 () => false,
85 ),
86 ).toBe(false);
87 expect(asked.map((c) => /t\/\w\.test\.ts/.exec(c)?.[0])).toEqual(["t/a.test.ts", "t/b.test.ts", "t/c.test.ts"]);
88 expect(said.filter((l) => / green alone in /.test(l))).toEqual([expect.stringMatching(/^rerun: t\/b\.test\.ts green alone in /)]);
89 });
test/runner-hands.test.ts added +238
@@ -0,0 +1,238 @@
1 /**
2 * Main's whole verification runs on a runner and hands back what it measured
3 * (`checks/runner_hands.ts`): on 2026-12-01, 14 of 35 verifications ran on the forge and were cut
4 * by a release, keeping nothing. A runner's job survives a release; its impact map, kept results
5 * and times come back through the job's hand door. Only a job the forge named them for, only
6 * from a runner this forge owns, only by the names given, only within the bound; and they reach
7 * the stores the way a verification here keeps its own.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11 import { BODY_CAPS } from "../src/kernel/body_caps.ts";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { formatImpact } from "../src/checks/impact.ts";
15 import { IMPACT_FILE } from "../src/checks/impact-store.ts";
16 import { formatKept } from "../src/checks/kept.ts";
17 import { KEPT_FILE } from "../src/checks/kept-store.ts";
18 import { handsDir, keepHands, takeHand } from "../src/checks/runner_hands.ts";
19 import { HAND_BYTES_MAX, HAND_FILES } from "../src/checks/hand_files.ts";
20 import { claimJob, enrolRunner, offerJob, type RunnerJob } from "../src/checks/runner_jobs.ts";
21 import { runnerTakes } from "../src/checks/runner_step.ts";
22 import { formatTimes } from "../src/checks/test_times.ts";
23 import { TIMES_FILE } from "../src/checks/times-store.ts";
24 import { createRun } from "../src/core/runs.ts";
25 import { handBack } from "../src/runner/hand.ts";
26 import { sweepCheckouts } from "../src/checks/sweep.ts";
27 import { checksForge } from "./helpers/checks-forge.ts";
28 import { quietLogs } from "./helpers/globals.ts";
29
30 quietLogs();
31
32 const f = checksForge("forge-runner-hands-");
33 const scratch = mkdtempSync(join(tmpdir(), "runner-hands-"));
34 // No checks service: these runs are driven by hand, and nothing else may end them.
35 beforeAll(async () => {
36 await f.checks.stop();
37 });
38 afterAll(() => rmSync(scratch, { recursive: true, force: true }));
39
40 /** A job offered for a fresh run and claimed at once by a runner named `name`; its token. */
41 function claimed(name: string, hands?: readonly string[]): { job: RunnerJob; token: string; runId: string } {
42 const run = createRun(f.app.db, { repoId: f.repo.id, kind: "check", env: "verify", commitOid: "a".repeat(40) });
43 const runner = enrolRunner(f.app.db, name, "admin");
44 offerJob(f.app.db, {
45 runId: run.id,
46 repoId: f.repo.id,
47 dir: join(f.dataDir, "repos"),
48 job: {
49 run: run.id,
50 repo: "alice/game",
51 commit: "a".repeat(40),
52 depth: 1,
53 steps: [{ name: "check", command: "true" }],
54 env: {},
55 limits: {},
56 timeoutS: 60,
57 egress: [],
58 egressMode: "report",
59 cell: "preferred",
60 cache: { repo: f.repo.id, tree: "", base: "" },
61 ...(hands === undefined ? {} : { hands }),
62 },
63 });
64 const claim = claimJob(f.app.db, { id: runner.runner.id, cells: true }, Date.now());
65 if (claim === undefined) throw new Error("not claimed");
66 // The run the claimed job serves (a runner takes the oldest job it may), running with a live
67 // lease as a verification on a runner is: the sweep spares its directories.
68 f.app.db.query("UPDATE run SET state = 'running', heartbeat_at = ?2, started_at = ?2 WHERE id = ?1").run(claim.job.run, new Date().toISOString());
69 return { job: claim.job, token: claim.token, runId: claim.job.run };
70 }
71
72 const hand = (jobId: string, token: string, path: string, body: Uint8Array | string): Promise<Response> =>
73 fetch(`${f.servers.url}/api/v1/runner/jobs/${jobId}/hand?path=${encodeURIComponent(path)}`, {
74 method: "POST",
75 headers: { authorization: `Bearer ${token}` },
76 body,
77 });
78
79 /** The forge's own store of `kind` for the repository. */
80 const store = (kind: string): string => join(f.dataDir, "checks", kind, `${f.repo.id.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
81
82 describe("which runs a runner takes", () => {
83 test("main's whole verification now goes to a runner; a bisection step, and a verification of nothing kept, stay here", () => {
84 expect(runnerTakes({ tier: "verify", keepImpact: true, isMain: true })).toBe(true);
85 expect(runnerTakes({ tier: "verify", keepImpact: true, isMain: true, only: ["test/a.test.ts"] })).toBe(false);
86 expect(runnerTakes({ tier: "verify", keepImpact: false })).toBe(false);
87 // Unchanged: a pull's fast tier goes, main's own check does not.
88 expect(runnerTakes({ tier: "fast" })).toBe(true);
89 expect(runnerTakes({ tier: "run", keep: true, isMain: true })).toBe(false);
90 });
91 });
92
93 describe("the hand door", () => {
94 test("takes each named file from the job's own runner, into the run's directory", async () => {
95 const { job, token, runId } = claimed("own-1", HAND_FILES);
96 const res = await hand(job.id, token, IMPACT_FILE, "{}");
97 expect(res.status).toBe(200);
98 expect(readFileSync(join(handsDir(f.dataDir, runId), IMPACT_FILE), "utf8")).toBe("{}");
99 });
100
101 test("refuses a name the job does not give, a job that names none, another job's token and a lent runner", async () => {
102 const only = claimed("own-2", [TIMES_FILE]);
103 expect((await hand(only.job.id, only.token, IMPACT_FILE, "{}")).status).toBe(404);
104 expect((await hand(only.job.id, only.token, ".forge-cache/tsc.tsbuildinfo", "x")).status).toBe(404);
105 expect((await hand(only.job.id, only.token, "../../forge.db", "x")).status).toBe(404);
106 const pull = claimed("own-3");
107 expect((await hand(pull.job.id, pull.token, IMPACT_FILE, "{}")).status).toBe(404);
108 expect((await hand(only.job.id, pull.token, TIMES_FILE, "{}")).status).toBe(404);
109 // A runner that became lent after it claimed (a lent runner never claims such a job: below).
110 const lent = claimed("own-4", HAND_FILES);
111 f.app.db.query("UPDATE check_runner SET name = 'lent-own-4' WHERE id = (SELECT runner_id FROM check_job WHERE id = ?1)").run(lent.job.id);
112 expect((await hand(lent.job.id, lent.token, IMPACT_FILE, "{}")).status).toBe(404);
113 for (const refused of [only, pull, lent]) expect(existsSync(join(handsDir(f.dataDir, refused.runId), IMPACT_FILE))).toBe(false);
114 });
115
116 test("refuses a file over the bound", async () => {
117 const { job, token, runId } = claimed("own-5", HAND_FILES);
118 expect((await hand(job.id, token, TIMES_FILE, new Uint8Array(HAND_BYTES_MAX + 1))).status).toBe(413);
119 expect(existsSync(join(handsDir(f.dataDir, runId), TIMES_FILE))).toBe(false);
120 });
121 });
122
123 describe("what comes back reaches the stores", () => {
124 test("the real runner hands its checkout's three files, and keepHands keeps them as a verification here would", async () => {
125 const { job, token, runId } = claimed("own-6", HAND_FILES);
126 const tree = join(scratch, "tree");
127 mkdirSync(tree, { recursive: true });
128 writeFileSync(join(tree, IMPACT_FILE), formatImpact(new Map([["test/a.test.ts", ["src/a.ts"]]])));
129 writeFileSync(join(tree, KEPT_FILE), formatKept(new Map()));
130 writeFileSync(join(tree, TIMES_FILE), formatTimes(new Map([["test/a.test.ts", 1.5]])));
131 const said = await handBack(f.servers.url, job, token, tree, AbortSignal.timeout(10_000));
132 expect(said).toStartWith("runner: handed back 3 of 3 files");
133 const lines: string[] = [];
134 keepHands(f.dataDir, f.repo.id, runId, (l) => lines.push(l));
135 expect(readFileSync(store("impact"), "utf8")).toContain("src/a.ts");
136 expect(readFileSync(store("times"), "utf8")).toContain("test/a.test.ts");
137 expect(lines.length).toBeGreaterThan(0);
138 });
139
140 test("a runner says what it could not hand", async () => {
141 const { job, token } = claimed("own-7", HAND_FILES);
142 const empty = join(scratch, "empty");
143 mkdirSync(empty, { recursive: true });
144 expect(await handBack(f.servers.url, job, token, empty, AbortSignal.timeout(10_000))).toContain(
145 "not handed: .forge-impact.json (not written)",
146 );
147 });
148 });
149
150 describe("the sweep", () => {
151 test("spares what a live run's runner handed back, and takes it once the run is over", async () => {
152 const { job, token, runId } = claimed("own-8", HAND_FILES);
153 expect((await hand(job.id, token, TIMES_FILE, "{}")).status).toBe(200);
154 await sweepCheckouts(f.app);
155 expect(existsSync(handsDir(f.dataDir, runId))).toBe(true);
156 f.app.db.query("UPDATE run SET state = 'ok' WHERE id = ?1").run(runId);
157 await sweepCheckouts(f.app);
158 expect(existsSync(handsDir(f.dataDir, runId))).toBe(false);
159 });
160 });
161
162 describe("a lent runner", () => {
163 test("never claims a job that hands files back: that is this forge's own verification", () => {
164 f.app.db.query("DELETE FROM check_job WHERE state = 'queued'").run();
165 const run = createRun(f.app.db, { repoId: f.repo.id, kind: "check", env: "verify", commitOid: "b".repeat(40) });
166 f.app.db.query("UPDATE repo SET visibility = 'public' WHERE id = ?1").run(f.repo.id);
167 offerJob(f.app.db, {
168 runId: run.id,
169 repoId: f.repo.id,
170 dir: join(f.dataDir, "repos"),
171 job: {
172 run: run.id,
173 repo: "alice/game",
174 commit: "b".repeat(40),
175 depth: 1,
176 steps: [{ name: "check", command: "true" }],
177 env: {},
178 limits: {},
179 timeoutS: 60,
180 egress: [],
181 egressMode: "report",
182 cell: "preferred",
183 cache: { repo: f.repo.id, tree: "", base: "" },
184 hands: HAND_FILES,
185 },
186 });
187 const lent = enrolRunner(f.app.db, "lent-9", "admin", {});
188 expect(claimJob(f.app.db, { id: lent.runner.id, cells: true }, Date.now())).toBeUndefined();
189 const own = enrolRunner(f.app.db, "own-9", "admin");
190 expect(claimJob(f.app.db, { id: own.runner.id, cells: true }, Date.now())?.job.run).toBe(run.id);
191 });
192 });
193
194 describe("the bound is counted, not declared", () => {
195 test("the names a runner hands are the stores' own", () => {
196 expect(HAND_FILES).toEqual([IMPACT_FILE, KEPT_FILE, TIMES_FILE]);
197 });
198
199 /** A body of `bytes` bytes, in 1 MiB chunks, that says nothing of its length. */
200 const stream = (bytes: number): ReadableStream<Uint8Array> => {
201 const chunk = new Uint8Array(1024 * 1024);
202 let left = bytes;
203 return new ReadableStream<Uint8Array>({
204 pull(c) {
205 if (left <= 0) return c.close();
206 const n = Math.min(left, chunk.length);
207 c.enqueue(n === chunk.length ? chunk : chunk.subarray(0, n));
208 left -= n;
209 },
210 });
211 };
212
213 test("past the bound with no declared length it is refused as it streams, and no part file is left", async () => {
214 const job = { runId: "01handstream00000000000001", hands: HAND_FILES, lent: false };
215 expect(await takeHand(f.dataDir, job, TIMES_FILE, stream(HAND_BYTES_MAX + 1), 0)).toBe("too_large");
216 expect(readdirSync(handsDir(f.dataDir, job.runId))).toEqual([]);
217 // At the bound exactly, it is taken whole.
218 expect(await takeHand(f.dataDir, job, TIMES_FILE, stream(HAND_BYTES_MAX), 0)).toBeUndefined();
219 expect(readdirSync(handsDir(f.dataDir, job.runId))).toEqual([TIMES_FILE]);
220 });
221
222 test("no body-wide guard refuses the door first: a file over the general body cap but within the bound is taken, and a chunked body past the bound is 413", async () => {
223 expect(BODY_CAPS.body.bytes).toBeLessThan(HAND_BYTES_MAX);
224 const { job, token, runId } = claimed("own-10", HAND_FILES);
225 // A declared length above the general body cap, under the door's own bound.
226 expect((await hand(job.id, token, KEPT_FILE, new Uint8Array(BODY_CAPS.body.bytes + 1))).status).toBe(200);
227 expect(readFileSync(join(handsDir(f.dataDir, runId), KEPT_FILE)).length).toBe(BODY_CAPS.body.bytes + 1);
228 // No declared length at all: the door counts what arrives.
229 const res = await fetch(`${f.servers.url}/api/v1/runner/jobs/${job.id}/hand?path=${encodeURIComponent(IMPACT_FILE)}`, {
230 method: "POST",
231 headers: { authorization: `Bearer ${token}` },
232 body: stream(HAND_BYTES_MAX + 1),
233 duplex: "half",
234 } as RequestInit);
235 expect(res.status).toBe(413);
236 expect(existsSync(join(handsDir(f.dataDir, runId), IMPACT_FILE))).toBe(false);
237 });
238 });
test/tier-runner-verify.test.ts added +176
@@ -0,0 +1,176 @@
1 /**
2 * Main's whole verification on a runner, at `tryRunner` (`checks/tier_runner.ts`), with the runner
3 * stood in: what it handed back is kept with the verdict, green or red, and never when the run was
4 * cut or handed over; the handed files go once the verdict is in; a red verification is its own
5 * verdict (never one or two tests re-run here), names its files and its green-alone ones, and says
6 * what passed; a red its runner settled as flakes is green here, and the flakes are recorded.
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import type { CheckManifest } from "../src/apps/manifest.ts";
15 import { HAND_FILES } from "../src/checks/hand_files.ts";
16 import type { LaneState } from "../src/checks/lane_state.ts";
17 import type { Execution } from "../src/checks/local_runner.ts";
18 import { handsDir } from "../src/checks/runner_hands.ts";
19 import { HANDED_OVER, type runRunnerStep } from "../src/checks/runner_step.ts";
20 import { tryRunner } from "../src/checks/tier_runner.ts";
21 import { formatTimes } from "../src/checks/test_times.ts";
22 import { TIMES_FILE } from "../src/checks/times-store.ts";
23 import type { Repo } from "../src/core/repos.ts";
24 import { createRun } from "../src/core/runs.ts";
25 import { createUser } from "../src/core/users.ts";
26
27 let dir = "";
28 let app: App;
29 let repo: Repo;
30 beforeAll(async () => {
31 dir = mkdtempSync(join(tmpdir(), "tier-runner-verify-"));
32 app = createApp({ dataDir: dir, port: 0 });
33 const u = await createUser(app.db, {
34 origin: "seed",
35 trusted: true,
36 username: "alice",
37 email: "[email protected]",
38 password: "a-good-passphrase",
39 adminIfFirst: true,
40 });
41 if (!u.ok) throw new Error(u.error);
42 const made = await createRepo(app, u.value, { name: "game", visibility: "private" });
43 if (!made.ok) throw new Error(String(made.error));
44 repo = made.value;
45 });
46 afterAll(() => {
47 app.close();
48 rmSync(dir, { recursive: true, force: true });
49 });
50
51 const lane = (): LaneState =>
52 ({ app, options: { forgeUrl: "http://forge.test" }, placement: { mode: "runner", waitMs: 300 }, stopped: false }) as unknown as LaneState;
53
54 const manifest: CheckManifest = {
55 run: "true",
56 install: null,
57 fast: null,
58 full: "true",
59 verify: "true",
60 timeout: 600,
61 egress: [],
62 limits: {},
63 };
64
65 /** The times store a kept hand-back writes. */
66 const timesStore = (): string => join(dir, "checks", "times", `${repo.id.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
67
68 /**
69 * `tryRunner` for main's whole verification, its runner answering `end` and printing `said`, having
70 * handed back a times file first, as its hand door would have taken it.
71 */
72 async function verifyOnRunner(
73 said: readonly string[],
74 end: Awaited<ReturnType<typeof runRunnerStep>>,
75 signal: AbortSignal = new AbortController().signal,
76 ) {
77 rmSync(timesStore(), { force: true });
78 const run = createRun(app.db, { repoId: repo.id, kind: "check", env: "verify", commitOid: "a".repeat(40) });
79 const log: string[] = [];
80 const write = (l: string): void => void log.push(l);
81 let named: readonly string[] | undefined;
82 const send: typeof runRunnerStep = async (_app, input) => {
83 named = input.job.hands;
84 mkdirSync(handsDir(dir, run.id), { recursive: true });
85 writeFileSync(join(handsDir(dir, run.id), TIMES_FILE), formatTimes(new Map([["t/a.test.ts", 2]])));
86 input.output.push(...said);
87 return end;
88 };
89 const bare = join(app.reposRoot, "alice", "game.git");
90 const x: Execution = { id: run.id, runId: run.id, repo, bare, commitOid: run.commitOid, tier: "verify", keepImpact: true, isMain: true, write, signal };
91 const verdict = await tryRunner(
92 lane(),
93 x,
94 {
95 run,
96 repo,
97 bare: join(app.reposRoot, "alice", "game.git"),
98 manifest,
99 command: "true",
100 base: undefined,
101 builtOnBase: undefined,
102 learned: "",
103 reverts: {},
104 tree: { ok: true, value: "b".repeat(40) },
105 key: undefined,
106 outside: false,
107 write,
108 signal,
109 },
110 send,
111 );
112 return { verdict, run, log, named, handsLeft: existsSync(handsDir(dir, run.id)), kept: existsSync(timesStore()) };
113 }
114
115 const taken = (ok: boolean): Awaited<ReturnType<typeof runRunnerStep>> =>
116 ok
117 ? { taken: true, ran: { ok: true, value: undefined }, runner: "vx-1", contained: true, note: "" }
118 : { taken: true, ran: { ok: false, error: "check exited with code 1" }, failed: "check", runner: "vx-1", contained: true, note: "" };
119
120 test("a red verification is its own verdict: one failed test is not re-run here, its files and green-alone files are named, what passed is said, and what it handed back is kept and then dropped", async () => {
121 const said = [
122 "t/a.test.ts:",
123 "(pass) a > fine [1.00ms]",
124 "t/b.test.ts:",
125 "(fail) b > broken [1.00ms]",
126 "rerun: t/b.test.ts green alone in 1.0 s",
127 " 1 pass",
128 " 1 fail",
129 "Ran 2 tests across 2 files.",
130 ];
131 const r = await verifyOnRunner(said, taken(false));
132 expect(r.named).toEqual(HAND_FILES);
133 expect(r.verdict).toBeDefined();
134 expect(r.verdict !== undefined && "alone" in r.verdict).toBe(false);
135 expect(r.verdict).toMatchObject({ ok: false });
136 if (r.verdict === undefined || "alone" in r.verdict || r.verdict.ok) throw new Error("not a red");
137 expect(r.verdict.detail?.files).toContain("t/b.test.ts");
138 expect(r.verdict.detail?.flakyUnderLoad).toEqual(["t/b.test.ts"]);
139 expect(r.verdict.passed).toBeDefined();
140 expect(r.kept).toBe(true);
141 expect(r.handsLeft).toBe(false);
142 });
143
144 test("a red its runner settled as flakes is green here, says what passed, and records the flakes", async () => {
145 const said = [
146 "t/a.test.ts:",
147 "(fail) grp > flaky [1.00ms]",
148 " 41 pass",
149 " 1 fail",
150 "Ran 42 tests across 9 files.",
151 "flake: t/a.test.ts > grp > flaky passed alone",
152 'flaky: "grp > flaky" failed in the full run and passed alone; recorded, main stays green',
153 ];
154 const r = await verifyOnRunner(said, taken(true));
155 expect(r.verdict).toMatchObject({ ok: true });
156 if (r.verdict === undefined || "alone" in r.verdict || !r.verdict.ok) throw new Error("not green");
157 expect(r.verdict.passed).toBeDefined();
158 expect(app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM check_flake WHERE run_id = ?1").get(r.run.id)?.n).toBe(1);
159 expect(r.kept).toBe(true);
160 expect(r.handsLeft).toBe(false);
161 });
162
163 test("a cut verification keeps nothing it was handed, and drops it", async () => {
164 const cut = new AbortController();
165 cut.abort();
166 const r = await verifyOnRunner([" 1 pass", " 0 fail"], taken(true), cut.signal);
167 expect(r.kept).toBe(false);
168 expect(r.handsLeft).toBe(false);
169 });
170
171 test("a verification handed over in a release keeps nothing here and leaves its files for the forge that takes it back", async () => {
172 const r = await verifyOnRunner([], { taken: false, why: HANDED_OVER });
173 expect(r.verdict).toEqual({ ok: false, error: HANDED_OVER });
174 expect(r.kept).toBe(false);
175 expect(r.handsLeft).toBe(true);
176 });

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

Keyboard shortcuts

Docs