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

A check handed to a runner runs the base commit's gate first, the same as a local check #15294

Merged opened this

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

Merged

scout/forge:scout/15291-a-check-handed-to-a-runner-runs-the-base → main 0 commits fork

  • Merged. scout/15291-a-check-handed-to-a-runner-runs-the-base was merged into main as c603804.

Review

Sign in to review this change.
4 files changed +220 −4
docs/features/gate-bypass.md +2 −1
@@ -16,5 +16,6 @@ On 2026-11-01 a bug in the live gate could not be fixed through the gate, and la
1616
1717 - **The gate's list is read from the base (#15255).** Before a pull's own check command, the forge writes the base commit's `scripts/gate.ts` into the checkout as `scripts/.gate-base.ts` and runs it with `--base-only` (`checks/base_gate.ts`, `checks/run_tier.ts`). It compares the files the base's gate runs with the ones the pull's gate runs, reading the pull's list without running the pull's code: the base's own `gateFiles` applied to the pull's test files and the `EXCLUDED` its `scripts/gate.ts` names as text (`excludedIn`). A pull whose `EXCLUDED` is not a plain list, or that changes how the list is made (`isLooksFile` through `gateFiles`, `listingCode`), is refused. It refuses every file the pull still has but no longer gates (an `EXCLUDED` entry it added), naming each: `test/x.test.ts is in the base's gate and this pull takes it out of it`. Deleting that refusal from the pull's own `scripts/gate.ts` does not help, since the base's copy runs. A pull that only adds a test file passes and its file is gated the same push. Taking a file out is the owner's to land: an owner pushes the exclusion to the default branch themselves, which no agent can, and the refusal says so. The pull's own gate runs the same comparison, so it is red locally too.
1818 - Test: `test/gate-base-list.test.ts`.
19 - **Runners are covered (#15291).** A check handed to a runner carries the base commit and the base gate's blob id; its check step writes `scripts/.gate-base.ts` with `git show`, refuses a file whose `git hash-object` is not that id, and runs it with `--base-only` before the pull's command (`withBaseGateFrom`, `checks/tier_runner.ts`). A base gate the forge cannot name keeps the check off the runner. Test: `test/check-runner-base-gate.test.ts`.
1920
20 Not done: the shard runner that runs the list (`scripts/test-shards.ts`) is the pull's, so a pull that edits it to skip files is caught only by review; a test file deleted outright is not refused, since that is how two tests fold into one and the diff shows it; a check handed to a runner (`tier_runner.ts`) runs the pull's command without the base step (#15287); the nightly quarantine pull now needs an owner to land it; and the rest of the gate (`gateVerdict`) still runs from the pull's tree, not a pinned earlier release.
21 Not done: the shard runner that runs the list (`scripts/test-shards.ts`) is the pull's, so a pull that edits it to skip files is caught only by review; a test file deleted outright is not refused, since that is how two tests fold into one and the diff shows it; the nightly quarantine pull now needs an owner to land it; and the rest of the gate (`gateVerdict`) still runs from the pull's tree, not a pinned earlier release.
src/checks/base_gate.ts +24
@@ -28,3 +28,27 @@ export const runsAsBaseGate = (source: string | undefined): source is string =>
2828 export function withBaseGate(command: string, source: string | undefined): string {
2929 return runsAsBaseGate(source) ? `bun ${BASE_GATE_FILE} --base-only && ${command}` : command;
3030 }
31
32 /** A commit or blob id: what may stand in a shell command unquoted. */
33 const OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
34
35 /**
36 * The check command for a runner (#15291): the forge cannot write into the runner's tree as
37 * `runTier` does, so the step writes the base's gate itself from the base commit the runner
38 * fetched (`git show`), refuses a file whose blob id is not the one the forge read (`blob`), and
39 * then runs `withBaseGate`'s command. Written in the check step, after install, so nothing the
40 * pull runs first can put its own copy there. The command unchanged when the base's gate does
41 * not run as the base gate, or an id is not one: the caller then keeps the check off the runner.
42 */
43 export function withBaseGateFrom(
44 command: string,
45 source: string | undefined,
46 base: string | undefined,
47 blob: string | undefined,
48 ): string {
49 if (!runsAsBaseGate(source) || base === undefined || blob === undefined) return command;
50 if (!OID.test(base) || !OID.test(blob)) return command;
51 const write = `mkdir -p scripts && git show ${base}:scripts/gate.ts > ${BASE_GATE_FILE}`;
52 const verify = `{ test "$(git hash-object ${BASE_GATE_FILE})" = ${blob} || { echo "base gate: ${BASE_GATE_FILE} is not ${base.slice(0, 7)}'s scripts/gate.ts"; exit 1; }; }`;
53 return `${write} && ${verify} && ${withBaseGate(command, source)}`;
54 }
src/checks/tier_runner.ts +20 −3
@@ -14,6 +14,8 @@ import type { CheckOutcome } from "./runner.ts";
1414 import type { LaneState } from "./lane_state.ts";
1515 import type { Execution } from "./local_runner.ts";
1616 import type { CheckManifest } from "../apps/manifest.ts";
17 import { readFileAt } from "../apps/checkout.ts";
18 import { runsAsBaseGate, withBaseGateFrom } from "./base_gate.ts";
1719
1820 /** What a check handed to a runner is made of. */
1921 export interface RunnerCheck {
@@ -37,19 +39,34 @@ export interface RunnerCheck {
3739 * verdict, or nothing when it was not taken or answered with something that is not the check's own
3840 * verdict: it then runs here as it always has.
3941 */
40 export async function tryRunner(lane: LaneState, x: Execution, c: RunnerCheck): Promise<CheckOutcome | undefined> {
42 export async function tryRunner(
43 lane: LaneState,
44 x: Execution,
45 c: RunnerCheck,
46 send: typeof runRunnerStep = runRunnerStep,
47 ): Promise<CheckOutcome | undefined> {
4148 const { app, options } = lane;
4249 const { run, repo, bare, manifest, command, base, builtOnBase, learned, tree, key, outside, write, signal } = c;
4350 // A runner that joined takes the steps (`runner_step.ts`, #13652): only a check that hands
4451 // back nothing but its log and its verdict, and only while a runner is connected. Not taken,
4552 // or an answer that is not the check's own verdict, and it runs here as it always has.
4653 if (lane.placement.mode === "runner" && x.runId !== undefined && runnerTakes(x)) {
54 // The base's gate runs first there as here (#15291): the job carries the base commit and the
55 // gate's blob id, and the check step writes the file from them (`withBaseGateFrom`).
56 const baseGate = base === undefined ? undefined : await readFileAt(bare, base, "scripts/gate.ts", 1 << 20);
57 const blob = runsAsBaseGate(baseGate) ? await runGit(["rev-parse", `${base}:scripts/gate.ts`], { cwd: bare }) : undefined;
58 const step = withBaseGateFrom(command, baseGate, base, blob?.ok ? blob.value.trim() : undefined);
59 if (runsAsBaseGate(baseGate) && step === command) {
60 write("placement: runner; the base's gate could not be named for it; running here");
61 return undefined;
62 }
63 if (step !== command) write(`gate list: read from ${base!.slice(0, 7)}'s scripts/gate.ts, on the runner`);
4764 const lines: string[] = [];
4865 // The shard count an admin set reaches a runner's check as it does one run here (#14844); the
4966 // default is sized as one run here is (`checkShardCpus`), never from the runner machine's CPUs.
5067 const shardCpus = checkShardCpus(resolveLimits("step", manifest.limits).cpus);
5168 write(shardsLine(shardsInForce(app.db, shardCpus)));
52 const sent = await runRunnerStep(app, {
69 const sent = await send(app, {
5370 runId: x.runId,
5471 repoId: repo.id,
5572 dir: bare,
@@ -61,7 +78,7 @@ export async function tryRunner(lane: LaneState, x: Execution, c: RunnerCheck):
6178 depth: base === undefined ? 1 : await headDepth(bare, base, run.commitOid),
6279 steps: [
6380 ...(manifest.install === null ? [] : [{ name: "install" as const, command: manifest.install }]),
64 { name: "check" as const, command },
81 { name: "check" as const, command: step },
6582 ],
6683 // Only the check's own variables cross, never the forge's; the runner adds its cell's.
6784 env: {
test/check-runner-base-gate.test.ts added +174
@@ -0,0 +1,174 @@
1 /**
2 * A check handed to a runner runs the base commit's gate first, as a local one does (#15291,
3 * `checks/tier_runner.ts`): the job's check step writes `scripts/.gate-base.ts` from the base
4 * commit, refuses it when its blob is not the base's, and runs it before the pull's command. A
5 * base whose gate does not know the mode leaves the command as it was.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { readFileSync } from "node:fs";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
15 import { exportTree } from "../src/apps/checkout.ts";
16 import type { CheckManifest } from "../src/apps/manifest.ts";
17 import { BASE_GATE_FILE, BASE_GATE_MARK, withBaseGateFrom } from "../src/checks/base_gate.ts";
18 import { giveHistory } from "../src/checks/history.ts";
19 import type { LaneState } from "../src/checks/lane_state.ts";
20 import type { Execution } from "../src/checks/local_runner.ts";
21 import type { RunnerJob } from "../src/checks/runner_jobs.ts";
22 import type { runRunnerStep } from "../src/checks/runner_step.ts";
23 import { tryRunner } from "../src/checks/tier_runner.ts";
24 import type { Repo } from "../src/core/repos.ts";
25 import { createUser, type User } from "../src/core/users.ts";
26 import { runGit } from "../src/git/env.ts";
27 import { repoDir } from "../src/git/repos.ts";
28
29 const BASE_SOURCE = `console.log("the base's gate ran");\n${BASE_GATE_MARK}) { return []; }\n`;
30 const PULL_SOURCE = `console.log("the pull's gate ran");\n${BASE_GATE_MARK}) { return []; }\n`;
31 const OLD_SOURCE = `console.log("a gate from before");\n`;
32
33 const manifest: CheckManifest = {
34 run: "true",
35 install: null,
36 fast: "true",
37 full: "true",
38 verify: null,
39 timeout: 60,
40 egress: [],
41 limits: {},
42 };
43
44 let dir = "";
45 let app: App;
46 let alice: User;
47
48 beforeAll(async () => {
49 dir = await mkdtemp(join(tmpdir(), "forge-runner-base-gate-"));
50 app = createApp({ dataDir: dir, port: 0 });
51 const made = await createUser(app.db, {
52 origin: "seed",
53 trusted: true,
54 username: "alice",
55 email: "[email protected]",
56 password: "a-good-passphrase",
57 adminIfFirst: true,
58 });
59 if (!made.ok) throw new Error(String(made.error));
60 alice = made.value;
61 });
62
63 afterAll(async () => {
64 app.close();
65 await rm(dir, { recursive: true, force: true });
66 });
67
68 /** A repository whose main holds `base` as its gate, and a branch on it whose gate is `head`. */
69 async function repoWith(name: string, base: string, head: string): Promise<{ repo: Repo; base: string; head: string }> {
70 const made = await createRepo(app, alice, { name, visibility: "private" });
71 if (!made.ok) throw new Error(String(made.error));
72 const repo = made.value;
73 const first = await commitToBranch(app, alice, repo, {
74 message: "Start",
75 files: [{ path: "scripts/gate.ts", content: base }],
76 });
77 if (!first.ok) throw new Error(JSON.stringify(first.error));
78 const second = await commitToBranch(app, alice, repo, {
79 branch: "loosen",
80 message: "Loosen the gate",
81 files: [{ path: "scripts/gate.ts", content: head }],
82 });
83 if (!second.ok) throw new Error(JSON.stringify(second.error));
84 return { repo, base: first.value.commitOid, head: second.value.commitOid };
85 }
86
87 /** Hand the check to a fake runner: the job it was given, and nothing taken. */
88 async function handOver(repo: Repo, base: string, head: string): Promise<{ job: Omit<RunnerJob, "id">; bare: string; log: string[] }> {
89 const bare = repoDir(app.reposRoot, repo.ownerName, repo.name);
90 const jobs: Omit<RunnerJob, "id">[] = [];
91 const log: string[] = [];
92 const fake: typeof runRunnerStep = async (_app, input) => {
93 jobs.push(input.job);
94 return { taken: false, why: "the fake runner keeps it" };
95 };
96 const lane = { app, options: { forgeUrl: "http://forge.test" }, placement: { mode: "runner", waitMs: 10 } } as unknown as LaneState;
97 const x = { bare, repo, id: "check-1", runId: "run-1", commitOid: head, tier: "fast" } as Execution;
98 const sent = await tryRunner(
99 lane,
100 x,
101 {
102 run: { id: "run-1", commitOid: head },
103 repo,
104 bare,
105 manifest,
106 command: "true",
107 base,
108 builtOnBase: base,
109 learned: "",
110 tree: await runGit(["rev-parse", `${head}^{tree}`], { cwd: bare }),
111 key: undefined,
112 outside: false,
113 write: (line) => log.push(line),
114 signal: new AbortController().signal,
115 },
116 fake,
117 );
118 expect(sent).toBeUndefined();
119 expect(jobs).toHaveLength(1);
120 return { job: jobs[0]!, bare, log };
121 }
122
123 /** Run `command` as the runner would, in the pull's tree with the base fetched beside it. */
124 async function runOnRunner(bare: string, base: string, head: string, command: string): Promise<{ code: number; out: string; tree: string }> {
125 const tree = await mkdtemp(join(dir, "runner-"));
126 const exported = await exportTree(bare, head, tree);
127 if (!exported.ok) throw new Error(exported.error);
128 const given = await giveHistory(bare, tree, base, head);
129 if (!given.ok) throw new Error(given.error);
130 const proc = Bun.spawn(["/bin/sh", "-c", command], { cwd: tree, stdout: "pipe", stderr: "pipe" });
131 const out = await new Response(proc.stdout).text();
132 return { code: await proc.exited, out, tree };
133 }
134
135 describe("a runner's check runs the base's gate first", () => {
136 test("the check step writes the base commit's gate and runs it before the pull's command", async () => {
137 const { repo, base, head } = await repoWith("weir", BASE_SOURCE, PULL_SOURCE);
138 const { job, bare, log } = await handOver(repo, base, head);
139 expect(job.base).toBe(base);
140 const check = job.steps.find((s) => s.name === "check")!;
141 expect(check.command).toContain(`git show ${base}:scripts/gate.ts > ${BASE_GATE_FILE}`);
142 expect(check.command.endsWith(`bun ${BASE_GATE_FILE} --base-only && true`)).toBe(true);
143 expect(log.some((l) => l.includes(`read from ${base.slice(0, 7)}'s scripts/gate.ts, on the runner`))).toBe(true);
144
145 const ran = await runOnRunner(bare, base, head, check.command);
146 expect(ran.code).toBe(0);
147 expect(readFileSync(join(ran.tree, BASE_GATE_FILE), "utf8")).toBe(BASE_SOURCE);
148 expect(ran.out).toContain("the base's gate ran");
149 expect(ran.out).not.toContain("the pull's gate ran");
150 }, 30_000);
151
152 test("a file that is not the base's blob is refused before anything runs", async () => {
153 const { repo, base, head } = await repoWith("sluice", BASE_SOURCE, PULL_SOURCE);
154 const bare = repoDir(app.reposRoot, repo.ownerName, repo.name);
155 const pullBlob = await runGit(["rev-parse", `${head}:scripts/gate.ts`], { cwd: bare });
156 if (!pullBlob.ok) throw new Error("no blob");
157 const command = withBaseGateFrom("echo the-check-ran", BASE_SOURCE, base, pullBlob.value.trim());
158 const ran = await runOnRunner(bare, base, head, command);
159 expect(ran.code).not.toBe(0);
160 expect(ran.out).toContain("is not");
161 expect(ran.out).not.toContain("the-check-ran");
162 }, 30_000);
163
164 test("a base whose gate does not know the mode leaves the command unchanged", async () => {
165 const { repo, base, head } = await repoWith("culvert", OLD_SOURCE, PULL_SOURCE);
166 const { job } = await handOver(repo, base, head);
167 expect(job.steps.find((s) => s.name === "check")?.command).toBe("true");
168 }, 30_000);
169
170 test("ids that are not ids leave the command for the caller to keep off the runner", () => {
171 expect(withBaseGateFrom("true", BASE_SOURCE, "main; rm -rf /", "a".repeat(40))).toBe("true");
172 expect(withBaseGateFrom("true", BASE_SOURCE, "a".repeat(40), undefined)).toBe("true");
173 });
174 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs