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

An evicted check on a game box loses at most one shard, and a frozen job thaws if the player leaves soon #17615

opened this

Merged 21h 47m ago, live in production

scout/forge:scout/17579-an-evicted-check-on-a-game-box-loses-at → main 0 commits fork

  • Merged. scout/17579-an-evicted-check-on-a-game-box-loses-at was merged into main as 2492b91.

Review

Sign in to review this change.
8 files changed +216 −16
docs/features/game-box.md +1
@@ -36,3 +36,4 @@ Code: `src/games/store.ts` (the `game_box` row and its token, the games store's)
3636 - **The cell:** the agent itself only claims, fetches the commit over the job's own git door as the unprivileged user `forge-job`, and answers. Each step is its own systemd unit (`forge-job-<id>`: `MemoryMax` the job's declared memory, no swap, `CPUQuota` its cpus, 512 tasks, `timeout` its seconds) as that user, in bubblewrap with `--unshare-all`, `/usr` read-only, the checkout at `/work`, a tmpfs `/tmp` and a cleared environment (`CI` and `FORGE_*` of the job only). It sees no `/run` (the Docker socket), no `/opt/forge-game` (`agent.env`, `.auth`, `.runner.auth`, compose), no data volume. The check step has no network at all. The install step shares the network, but an iptables rule on `forge-job`'s traffic rejects every private, loopback, link-local (the cloud's metadata door) and shared-range address, so the game network is not a route (the box's own addresses too, v4 and v6; a host with IPv6 and no `ip6tables` hands the install step back). A step's output is written inside that same tmpfs and no write takes it past 1 MiB (`FORGE_GAME_LEND_OUT_KIB`): the step is killed by SIGXFSZ, and the last 64 KiB is what is read. The disk cap is the checkout's own tmpfs (the job's `diskMiB`, at most 4 GiB, which is also charged to the job's memory cap). A job that names `egress` hosts, declares no memory, or whose step is missing a tool on the box (exit 126 or 127) is handed back (`abandon`): the forge runs it, and it is never red for the box's lack; after a missing tool the box claims nothing for 10 minutes. `/opt/forge-job-tools` is mounted read-only at `/opt/tools` (on `PATH`) when it exists: the toolchain a repository's check needs (bun, say) is put there by the box's owner.
3737 - **A join:** `docker events` (a container starting) is read by the agent, and in that reader: claiming stops (`.wake`), every `forge-job-*` cgroup is frozen at once (`cgroup.freeze`), and nothing waits on the job. While a step runs, a guard looks twice a second: still frozen and `MemAvailable` under the floor, or frozen for 5 minutes (`FORGE_GAME_LEND_FROZEN_S`), and the job is killed (`cgroup.kill`, then the unit stopped) and answered `interrupted`; a quiet box (90 s, memory above the floor) thaws it. `interrupted` puts the job back in the queue with no result: it is never red, and its claim is not counted, so it is never a try of that check's `MAX_CLAIMS` (the check's log says "stopped the job … not a try, nor a result"). The guard also renews the lease every 10 s, frozen or not.
3838 - **Not done, and not proved yet:** nothing here has run on a real box (it waits for the owner's go): tps and mspt of an awake server with and without a job, and the wake time on a join with one running, are still to be measured from `src/games/metrics.ts`'s samples. The cell was checked against stand-ins (`test/game-lend-box.test.ts`), not against a real kernel's bubblewrap.
39 - **What an eviction keeps (#17579):** a stopped check loses at most the shard that was running. The agent reads the check's output for the shards that ended green (`── shard N/M done (exit 0`) and sends their test files with `interrupted` (`kept`). The forge puts them on the job's own env as `FORGE_CHECK_DONE` (a bounded set; a second stop adds to it), the job is queued again, and `scripts/test-shards.ts` leaves those files out of the next run ("FORGE_CHECK_DONE keeps N finished file(s)"). A frozen job that is not stopped needs none of this: it thaws when the box is quiet again within `FORGE_GAME_LEND_FROZEN_S` (300 s), else it is stopped and queued as interrupted.
scripts/test-shards.ts +15
@@ -143,6 +143,7 @@ import { shardHome, spaceLine } from "../src/checks/disk_full.ts";
143143 import { blindLine, fastSet, duration, PAGE_BUDGET_TESTS, reasonLine, RULE_TESTS } from "../src/checks/tiers.ts";
144144 import { CHECK_CACHE } from "../src/checks/cache.ts";
145145 import { parseCheck } from "../src/apps/manifest.ts";
146 import { DONE_ENV, doneFiles } from "../src/checks/shard_event.ts";
146147 import { FLAKY_ALONE, onlyFiles } from "../src/checks/verify.ts";
147148 import { crashFlakeLine } from "../src/checks/flake.ts";
148149 import { DROPPED_FILE, dropDisagreed, droppedLine, finalCode, formatKept, keptLine, mergeKept, parseKept, type KeptEntry } from "../src/checks/kept.ts";
@@ -482,6 +483,20 @@ if (only !== undefined) {
482483 console.log(`test-shards: FORGE_CHECK_ONLY keeps ${files.length} of ${only.length} named file(s)`);
483484 }
484485
486 // A runner stopped mid-check (a game box's server woke) names the files whose shards had finished
487 // green: they are not run again, only what was running (#17579).
488 const finished = doneFiles(process.env[DONE_ENV]);
489 if (finished.length > 0) {
490 const before = files.length;
491 const skip = new Set(finished);
492 files = files.filter((file) => !skip.has(file.replace(/^\.\//, "")));
493 console.log(`test-shards: ${DONE_ENV} keeps ${before - files.length} finished file(s) from an earlier run; ${files.length} left`);
494 if (files.length === 0) {
495 console.log("test-shards: every file finished before the stop; nothing to run");
496 process.exit(0);
497 }
498 }
499
485500 if (files.length === 0) {
486501 console.error("test-shards: name the test files to run, or --gate");
487502 process.exit(2);
src/checks/runner_jobs.ts +24 −11
@@ -23,6 +23,7 @@ import { sha256 } from "../kernel/hash.ts";
2323 import { boxAuthors, boxSpareMiB } from "../games/lend_fit.ts";
2424 import { id, secret } from "../kernel/id.ts";
2525 import { during } from "../perf/jobs.ts";
26 import { DONE_ENV, keepDone } from "./shard_event.ts";
2627 import { canaryCommand, canaryDue, coreMs, lentName, outOfScope, readScope, scopeFrom, utcDay, type LendInput, type LentScope } from "./lent_scope.ts";
2728
2829 export const RUNNER_TOKEN_PREFIX = "forge_runner_";
@@ -669,19 +670,31 @@ export function settleJob(
669670 * #17578): back to queued, its token dead, and the claim not counted once, so a join is not a try;
670671 * a job interrupted again keeps its claim, so a runner that interrupts forever brings the check to
671672 * `MAX_CLAIMS` and the forge runs it itself. Never a result: the runner's reason is kept as
672 * `interrupted: …` for the check's log (a lapsed lease clears it). False, and nothing written, when
673 * `interrupted: …` for the check's log (a lapsed lease clears it). `kept` names the test files of
674 * shards that finished green: the job's next run skips them. False, and nothing written, when
673675 * the claim is no longer this token's.
674676 */
675 export function interruptJob(db: Database, jobId: string, presented: string, why: string): boolean {
676 return (
677 db
678 .query(
679 `UPDATE check_job SET state = 'queued', runner_id = NULL, token_hash = NULL, lease_until = 0,
680 claims = CASE WHEN COALESCE(result, '') LIKE 'interrupted: %' THEN claims ELSE MAX(claims - 1, 0) END,
681 result = ?3 WHERE id = ?1 AND token_hash = ?2 AND state = 'claimed'`,
682 )
683 .run(jobId, sha256(presented), `interrupted: ${why.slice(0, 200)}`).changes > 0
684 );
677 export function interruptJob(db: Database, jobId: string, presented: string, why: string, kept: readonly unknown[] = []): boolean {
678 return db.transaction(() => {
679 // The test files whose shards finished green before the stop ride on the job's own env, so the
680 // next runner skips them: only the shard that was running is run again (#17579).
681 const row = db
682 .query<{ spec: string }, [string, string]>("SELECT spec FROM check_job WHERE id = ?1 AND token_hash = ?2 AND state = 'claimed'")
683 .get(jobId, sha256(presented));
684 if (row === null) return false;
685 const spec = JSON.parse(row.spec) as RunnerJob;
686 const done = keepDone(spec.env[DONE_ENV], kept);
687 const next = done === "" ? spec : { ...spec, env: { ...spec.env, [DONE_ENV]: done } };
688 return (
689 db
690 .query(
691 `UPDATE check_job SET state = 'queued', runner_id = NULL, token_hash = NULL, lease_until = 0, spec = ?4,
692 claims = CASE WHEN COALESCE(result, '') LIKE 'interrupted: %' THEN claims ELSE MAX(claims - 1, 0) END,
693 result = ?3 WHERE id = ?1 AND token_hash = ?2 AND state = 'claimed'`,
694 )
695 .run(jobId, sha256(presented), `interrupted: ${why.slice(0, 200)}`, JSON.stringify(next)).changes > 0
696 );
697 })();
685698 }
686699
687700 /**
src/checks/shard_event.ts +35
@@ -8,6 +8,7 @@
88 */
99 import type { App } from "../app.ts";
1010 import type { Run } from "../core/runs.ts";
11 import { safeFile } from "./verify.ts";
1112
1213 const LIVE_DONE = /^── shard (\d+)\/(\d+) done \(exit \d+, [0-9.]+s\)$/;
1314 const BATCHED = /^── shard (\d+)\/(\d+) \(exit \d+, [0-9.]+s\): /;
@@ -35,3 +36,37 @@ export function announceShard(app: App, run: Run, line: string): void {
3536 },
3637 });
3738 }
39
40 /**
41 * The most test files a job keeps as finished, and the most bytes of their names in one variable.
42 */
43 const DONE_FILES_MAX = 4000;
44 const DONE_BYTES_MAX = 60_000;
45
46 /**
47 * `FORGE_CHECK_DONE`: test files whose shard finished green on a runner that was stopped,
48 * comma-separated.
49 */
50 export const DONE_ENV = "FORGE_CHECK_DONE";
51
52 /** The files `FORGE_CHECK_DONE` names, the unsafe left out; empty when unset. */
53 export function doneFiles(value: string | undefined): string[] {
54 if (value === undefined) return [];
55 return [...new Set(value.split(",").map((f) => f.trim().replace(/^\.\//, "")).filter((f) => f !== "" && safeFile(f)))].slice(0, DONE_FILES_MAX);
56 }
57
58 /**
59 * What `FORGE_CHECK_DONE` holds once `more` is kept beside `before`: a set, bounded, the unsafe
60 * left out (#17579).
61 */
62 export function keepDone(before: string | undefined, more: readonly unknown[]): string {
63 const all = [...doneFiles(before), ...more.filter((f): f is string => typeof f === "string" && safeFile(f.replace(/^\.\//, ""))).map((f) => f.replace(/^\.\//, ""))];
64 const kept: string[] = [];
65 let bytes = 0;
66 for (const f of new Set(all)) {
67 if (kept.length >= DONE_FILES_MAX || bytes + f.length + 1 > DONE_BYTES_MAX) break;
68 kept.push(f);
69 bytes += f.length + 1;
70 }
71 return kept.join(",");
72 }
src/games/agent.sh +14 −2
@@ -1181,6 +1181,16 @@ lend_guard() {
11811181 done
11821182 }
11831183
1184 # The test files of the shards a step's output says finished green (exit 0), as a JSON array: what
1185 # an evicted check keeps, so only the shard that was running is run again. The forge checks each name.
1186 lend_kept() {
1187 awk '
1188 /^── shard [0-9]+\/[0-9]+: / { n = $3; sub(/:$/, "", n); sub(/^── shard [0-9]+\/[0-9]+: /, ""); f[n] = $0; next }
1189 /^── shard [0-9]+\/[0-9]+ done \(exit 0,/ { if ($3 in f) print f[$3]; next }
1190 /^── shard [0-9]+\/[0-9]+ \(exit 0, [0-9.]+s\): / { sub(/^.*s\): /, ""); print }
1191 ' "$1" 2>/dev/null | tr ' ' '\n' | jq -R 'select(. != "")' 2>/dev/null | jq -cs '.[0:4000]' 2>/dev/null || echo '[]'
1192 }
1193
11841194 # The job's claim file to its answer. Anything the box cannot or may not do is handed back, never red.
11851195 lend_job() {
11861196 local f="$1" id tok commit base depth secs mem cpus disk work out name cmd rc t0 ms err steps='[]' net
@@ -1238,8 +1248,8 @@ lend_job() {
12381248 rc=$?
12391249 ms=$((($(date +%s%N) - t0) / 1000000))
12401250 if [ "$EVICTED" = 1 ]; then
1251 lend_give "$id" interrupted "a server woke on this box and needs its memory" "$(lend_kept "$out")"
12411252 lend_clean "$id" "$work"
1242 lend_give "$id" interrupted "a server woke on this box and needs its memory"
12431253 return 0
12441254 fi
12451255 if [ "$EVICTED" = 2 ]; then
@@ -1290,9 +1300,11 @@ lend_clean() {
12901300 # The job's end: `done` with its steps, `abandon` (the forge runs the check itself) or `interrupted`
12911301 # (back in the queue, not red, not a try).
12921302 lend_give() {
1293 local id="$1" kind="$2" what="$3" body
1303 local id="$1" kind="$2" what="$3" kept="${4:-[]}" body
12941304 if [ "$kind" = done ]; then
12951305 body="$(jq -cn --argjson s "$what" '{done: {steps: $s, contained: true, note: ""}}')"
1306 elif [ "$kind" = interrupted ]; then
1307 body="$(jq -cn --arg w "$what" --argjson k "$kept" '{interrupted: $w, kept: $k}')"
12961308 else
12971309 body="$(jq -cn --arg k "$kind" --arg w "$what" '{($k): $w}')"
12981310 fi
src/http/api/runners.ts +1 −1
@@ -279,7 +279,7 @@ export function runnerRoutes(router: Router<Handler>): void {
279279 : [];
280280 if (lines.length > 0) mine.ear.lines(str(input.step), lines);
281281 if (typeof input.interrupted === "string") {
282 if (!interruptJob(ctx.app.db, mine.job.id, token, input.interrupted)) return notFound();
282 if (!interruptJob(ctx.app.db, mine.job.id, token, input.interrupted, Array.isArray(input.kept) ? input.kept : [])) return notFound();
283283 wakeClaimers(ctx.app);
284284 return json({ ended: true });
285285 }
test/game-lend-box.test.ts +39 −2
@@ -81,7 +81,7 @@ exec "$@"`,
8181 join(bin, "docker"),
8282 `if [ "\${1:-}" = events ]; then
8383 [ -n "\${EVENT_AFTER:-}" ] || exit 0
84 sleep "$EVENT_AFTER"; printf 'MemTotal: 8000000 kB\\nMemAvailable: 200000 kB\\n' >"$MEMINFO"; echo abc123; sleep 1
84 sleep "$EVENT_AFTER"; printf 'MemTotal: 8000000 kB\\nMemAvailable: %s kB\\n' "\${EVENT_MEM_KIB:-200000}" >"$MEMINFO"; echo abc123; sleep 1
8585 fi
8686 exit 0`,
8787 );
@@ -283,7 +283,7 @@ describe("a join meets the job in order", () => {
283283 await b.run();
284284 expect(Date.now() - started).toBeLessThan(15_000);
285285 const ends = b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1" && Object.keys(s.body).some((k) => k !== "step" && k !== "lines"));
286 expect(ends.map((e) => Object.keys(e.body))).toEqual([["interrupted"]]);
286 expect(ends.map((e) => Object.keys(e.body))).toEqual([["interrupted", "kept"]]);
287287 // Frozen when it was stopped: the freeze came first.
288288 expect(readFileSync(join(b.cg, "forge-job-job1.service", "cgroup.freeze"), "utf8").trim()).toBe("1");
289289 expect(b.read("systemctl")).toContain("stop forge-job-job1.service freeze=1");
@@ -291,4 +291,41 @@ describe("a join meets the job in order", () => {
291291 expect(existsSync(join(b.dir, ".wake"))).toBe(true);
292292 },
293293 );
294
295 test.skipIf(lacks.length > 0)("an eviction keeps the files of every shard that finished and names none of the one that was running (#17579)", async () => {
296 const shards = [
297 "echo '── shard 1/3: test/a.test.ts test/b.test.ts'",
298 "echo '── shard 1/3 done (exit 0, 1.0s)'",
299 "echo '── shard 2/3: test/c.test.ts'",
300 "echo '── shard 2/3 done (exit 1, 1.0s)'",
301 "echo '── shard 3/3: test/d.test.ts'",
302 "sleep 30",
303 ].join("; ");
304 const b = await box({ steps: [{ name: "check", command: shards }] }, { eventAfter: 1.5 });
305 await b.run();
306 const ended = b.seen.find((s) => s.path === "/api/v1/runner/jobs/job1" && "interrupted" in s.body)!;
307 // Green shard 1 is kept; red shard 2 and the running shard 3 are not.
308 expect(ended.body["kept"]).toEqual(["test/a.test.ts", "test/b.test.ts"]);
309 });
310
311 test.skipIf(lacks.length > 0)("a job frozen while the woken server sleeps again within the window thaws and finishes (#17579)", async () => {
312 const b = await box(
313 { steps: [{ name: "check", command: "sleep 6; echo finished" }] },
314 { eventAfter: 1, env: { EVENT_MEM_KIB: "4000000", FORGE_GAME_LEND_FROZEN_S: "60" } },
315 );
316 await b.run();
317 const last = b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1").at(-1)!;
318 expect(last.body).toMatchObject({ done: { steps: [{ name: "check", ok: true }] } });
319 expect(readFileSync(join(b.cg, "forge-job-job1.service", "cgroup.freeze"), "utf8").trim()).toBe("0");
320 }, 30_000);
321
322 test.skipIf(lacks.length > 0)("a job frozen past the window is stopped and handed back as interrupted, memory or not (#17579)", async () => {
323 const b = await box(
324 { steps: [{ name: "check", command: "sleep 30" }] },
325 { eventAfter: 1, env: { EVENT_MEM_KIB: "4000000", FORGE_GAME_LEND_FROZEN_S: "2", FORGE_GAME_LEND_QUIET: "60" } },
326 );
327 await b.run();
328 const last = b.seen.filter((s) => s.path === "/api/v1/runner/jobs/job1").at(-1)!;
329 expect(Object.keys(last.body)).toContain("interrupted");
330 }, 30_000);
294331 });
test/runner-interrupt-keeps.test.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * #17579: a check stopped on a game box keeps what its finished shards proved. The files of the
3 * shards that ended green ride on the job's env (`FORGE_CHECK_DONE`), the next runner is handed
4 * them, and `scripts/test-shards.ts` runs only the rest.
5 */
6 import { expect, test } from "bun:test";
7 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { claimJob, enrolRunner, interruptJob, offerJob, viewJob, type RunnerJob } from "../src/checks/runner_jobs.ts";
11 import { DONE_ENV, doneFiles, keepDone } from "../src/checks/shard_event.ts";
12 import { checksForge } from "./helpers/checks-forge.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16 const f = checksForge("forge-interrupt-keeps-");
17
18 const job: Omit<RunnerJob, "id"> = {
19 run: "run1",
20 repo: "alice/lib",
21 commit: "a".repeat(40),
22 depth: 1,
23 steps: [{ name: "check", command: "bun scripts/test-shards.ts --gate" }],
24 env: { CI: "1" },
25 limits: { memoryMiB: 512, cpus: 1 },
26 timeoutS: 60,
27 egress: [],
28 egressMode: "enforce",
29 cell: "preferred",
30 cache: { repo: "r", tree: "", base: "" },
31 };
32
33 test("an interrupted job is queued with its finished files kept, once, and its next claim carries them", () => {
34 const { runner } = enrolRunner(f.app.db, "box", f.alice.id);
35 const offered = offerJob(f.app.db, { runId: "run1", repoId: "r", dir: "/nowhere", job });
36 const first = claimJob(f.app.db, { id: runner.id, cells: true }, 1_000)!;
37 expect(first.job.env[DONE_ENV]).toBeUndefined();
38 expect(interruptJob(f.app.db, offered.id, first.token, "a server woke", ["test/a.test.ts", "../escape", "-flag.ts", 7, "./test/b.test.ts"])).toBe(true);
39 expect(viewJob(f.app.db, offered.id)?.state).toBe("queued");
40 const second = claimJob(f.app.db, { id: runner.id, cells: true }, 2_000)!;
41 expect(second.job.env[DONE_ENV]).toBe("test/a.test.ts,test/b.test.ts");
42 // Stopped again: what the first stop kept stays, and what the second finished joins it.
43 expect(interruptJob(f.app.db, offered.id, second.token, "a server woke", ["test/c.test.ts", "test/a.test.ts"])).toBe(true);
44 expect(claimJob(f.app.db, { id: runner.id, cells: true }, 3_000)!.job.env[DONE_ENV]).toBe("test/a.test.ts,test/b.test.ts,test/c.test.ts");
45 });
46
47 test("a stale token interrupts nothing and keeps nothing", () => {
48 const { runner } = enrolRunner(f.app.db, "box2", f.alice.id);
49 const offered = offerJob(f.app.db, { runId: "run2", repoId: "r", dir: "/nowhere", job });
50 claimJob(f.app.db, { id: runner.id, cells: true }, 1_000);
51 expect(interruptJob(f.app.db, offered.id, "forge_job_wrong", "x", ["test/a.test.ts"])).toBe(false);
52 });
53
54 test("the kept names are a bounded set and the unsafe are left out", () => {
55 expect(doneFiles(undefined)).toEqual([]);
56 expect(doneFiles("a.test.ts, ,../x,b.test.ts,a.test.ts")).toEqual(["a.test.ts", "b.test.ts"]);
57 const many = Array.from({ length: 5000 }, (_, i) => `test/file-${i}.test.ts`);
58 expect(doneFiles(keepDone(undefined, many)).length).toBeLessThanOrEqual(4000);
59 expect(keepDone(undefined, many).length).toBeLessThanOrEqual(60_000);
60 });
61
62 test("test-shards runs only the files a stopped run had not finished", async () => {
63 const dir = mkdtempSync(join(tmpdir(), "shards-done-"));
64 // The finished file would be red if it ran again: only a skip keeps the run green.
65 writeFileSync(join(dir, "done.test.ts"), `import { expect, test } from "bun:test";\ntest("again", () => expect(true).toBe(false));\n`);
66 writeFileSync(join(dir, "rest.test.ts"), `import { expect, test } from "bun:test";\ntest("left", () => expect(true).toBe(true));\n`);
67 const script = new URL("../scripts/test-shards.ts", import.meta.url).pathname;
68 const run = async (done: string): Promise<{ code: number; out: string }> => {
69 const child = Bun.spawn(["bun", script, "done.test.ts", "rest.test.ts"], {
70 cwd: dir,
71 env: { ...process.env, FORGE_CHECK_SHARDS: "1", [DONE_ENV]: done },
72 stdin: "ignore",
73 stdout: "pipe",
74 stderr: "pipe",
75 });
76 const [out] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);
77 return { code: await child.exited, out };
78 };
79 const kept = await run("done.test.ts");
80 expect(kept.code).toBe(0);
81 expect(kept.out).toContain(`${DONE_ENV} keeps 1 finished file(s)`);
82 expect((await run("")).code).not.toBe(0);
83 const all = await run("done.test.ts,rest.test.ts");
84 expect(all.code).toBe(0);
85 expect(all.out).toContain("nothing to run");
86 rmSync(dir, { recursive: true, force: true });
87 }, 60_000);

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

Keyboard shortcuts

Docs