/** * CHECK JOBS GO FIRST — A BUILDER'S LOCAL RUN YIELDS THE MAC OR WAITS. * * On 28 Sep 2026 a pull request's `rust` job waited 35 minutes on a Mac's * `/tmp/tinmen-build.lock`, held by a builder's local `rust:verify` for its * whole run: the lock was first come, first served, and nothing in it knew a * check job from an agent's second opinion. `scripts/with-build-lock.sh` now * reads the caller's rank (`scripts/lib/caller-class.sh`) and: * * - a waiting check job files a claim beside the lock; * - a local HOLDER sees it, stops its whole process group, releases the lock * and starts again from the top once the check job is done; * - a local WAITER never takes the lock while a live claim exists; * - `BUILD_LOCK_YIELD=never` keeps a local run from being cut in half (the * Mac release lane) — it still queues behind claims; * - a check job is never interrupted; * - a local command runs at nice 19, behind the runner's +15. * * Every case runs the real script against a scratch lock, with the intervals * shortened through the script's own seams — nothing touches the machine's lock. */ import { spawn, spawnSync, type ChildProcess } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { publishBuildPeaks, publishDiskReading } from "./helpers/disk-reading"; const ROOT = resolve(__dirname, "../.."); const SCRIPT = join(ROOT, "scripts/with-build-lock.sh"); let scratch = ""; const children: ChildProcess[] = []; afterEach(() => { for (const child of children.splice(0)) { if (child.exitCode === null) child.kill("SIGKILL"); } if (scratch) rmSync(scratch, { recursive: true, force: true }); scratch = ""; }); function paths() { scratch ||= mkdtempSync(join(tmpdir(), "build-lock-ci-first-")); return { lock: join(scratch, "lock"), claims: join(scratch, "lock.ci-waiting"), log: join(scratch, "wait.log"), trace: join(scratch, "trace"), }; } function env(cls: "ci" | "local", label: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { const p = paths(); // A scratch HOME with a fresh device reading: on a Mac the wrapper admits // through the device policy, which reads it there — never the person's HOME. const home = join(scratch, "home"); publishDiskReading(home); // A byte of RAM per build: admission must not turn on the machine's free RAM. publishBuildPeaks(home); return { ...process.env, HOME: home, BUILD_LOCK_MEMORY_BYTES: "17179869184", BUILD_LOCK_DIR: p.lock, BUILD_LOCK_LOG: p.log, BUILD_LOCK_LABEL: label, BUILD_LOCK_CLASS: cls, BUILD_LOCK_POLL_SECONDS: "1", BUILD_LOCK_CI_POLL_SECONDS: "1", BUILD_LOCK_YIELD_POLL_SECONDS: "1", BUILD_LOCK_YIELD_GRACE_SECONDS: "2", BUILD_LOCK_YIELD: "", // Never inherit a real holder's marker into the child. TINMEN_BUILD_LOCK_HELD: "", TINMEN_BUILD_LOCK_DIR: "", // A scratch cargo target, not named shared: with none, the wrapper takes the // target this checkout's .cargo/config.toml names (a worktree's: the machine's // real shared target) and runs every holder under that target's cargo lock, // so the holders queue on the machine's cargo lock instead of the build lock. CARGO_TARGET_DIR: join(scratch, "target"), ...extra, }; } type Done = { status: number | null; stderr: string }; function start(command: string, e: NodeJS.ProcessEnv): { child: ChildProcess; done: Promise } { const child = spawn("bash", [SCRIPT, "bash", "-c", command], { env: e, stdio: ["ignore", "pipe", "pipe"] }); children.push(child); let stderr = ""; child.stderr!.on("data", (b) => (stderr += String(b))); child.stdout!.resume(); const done = new Promise((ok) => child.on("close", (status) => ok({ status, stderr }))); return { child, done }; } async function until(what: string, test: () => boolean, ms = 20_000): Promise { const end = Date.now() + ms; while (!test()) { if (Date.now() > end) throw new Error(`timed out waiting for: ${what}`); await new Promise((r) => setTimeout(r, 100)); } } const trace = () => (existsSync(paths().trace) ? readFileSync(paths().trace, "utf8").trim().split("\n") : []); describe("with-build-lock.sh — a check job outranks a local run", () => { it("a LOCAL HOLDER yields to a waiting check job, and then starts again from the top", async () => { const p = paths(); const marker = join(scratch, "second-attempt"); const pgidFile = join(scratch, "first-pgid"); // The first attempt records its process group and sleeps for a minute; the // second, which only happens after a yield, finishes at once. const local = start( [ `echo local-start >> ${p.trace}`, `if [ -f ${marker} ]; then echo local-end >> ${p.trace}; exit 0; fi`, `touch ${marker}`, `python3 -c 'import os;print(os.getpgrp())' > ${pgidFile}`, "sleep 60 & wait", ].join("; "), env("local", "local-rust-verify"), ); await until("the local run holds the lock", () => existsSync(pgidFile)); const ci = start(`echo ci >> ${p.trace}`, env("ci", "ci-rust-mac")); const [l, c] = await Promise.all([local.done, ci.done]); expect(c.status, c.stderr).toBe(0); expect(l.status, l.stderr).toBe(0); expect(trace()).toEqual(["local-start", "ci", "local-start", "local-end"]); expect(l.stderr).toContain("YIELDED: check job 'ci-rust-mac'"); expect(c.stderr).toContain("claimed as a check job"); // The WHOLE group went, the `sleep` included — a yield that leaves the // test binaries running has yielded nothing. const pgid = readFileSync(pgidFile, "utf8").trim(); const left = spawnSync("pgrep", ["-g", pgid], { encoding: "utf8" }); expect(left.stdout.trim(), "a process of the yielded run outlived the yield").toBe(""); // The lock and the claim are both gone, and the wait log says the check // job waited on the local run and the local run then waited on it. expect(existsSync(p.lock)).toBe(false); expect(existsSync(p.claims) ? readdirSync(p.claims) : []).toEqual([]); const log = readFileSync(p.log, "utf8"); expect(log).toMatch(/\tci-rust-mac\t\d+\tlocal-rust-verify\n/); expect(log).toMatch(/\tlocal-rust-verify\t\d+\tci-rust-mac\n/); }, 60_000); it("a LOCAL WAITER never takes a free lock while a check job's claim is live", async () => { const p = paths(); mkdirSync(p.claims, { recursive: true }); // This test's own process stands in for a waiting check job: alive, and not // the wrapper itself. writeFileSync(join(p.claims, String(process.pid)), "ci-swift-mac\n"); const local = start(`echo local >> ${p.trace}`, env("local", "local-verify-fast")); await new Promise((r) => setTimeout(r, 2500)); expect(trace(), "the local run went ahead of a waiting check job").toEqual([]); rmSync(join(p.claims, String(process.pid))); const l = await local.done; expect(l.status, l.stderr).toBe(0); expect(trace()).toEqual(["local"]); expect(l.stderr).toContain("check job 'ci-swift-mac' goes first"); expect(readFileSync(p.log, "utf8")).toMatch(/\tlocal-verify-fast\t\d+\tci-swift-mac\n/); }, 30_000); it("a claim whose check job is gone is removed, not obeyed", () => { const p = paths(); mkdirSync(p.claims, { recursive: true }); const dead = spawnSync("bash", ["-c", "echo $$"], { encoding: "utf8" }).stdout.trim(); writeFileSync(join(p.claims, dead), "ci-cancelled\n"); const r = spawnSync("bash", [SCRIPT, "true"], { env: env("local", "local-x"), encoding: "utf8", timeout: 20_000 }); expect(r.status, r.stderr).toBe(0); expect(r.stderr).not.toContain("goes first"); expect(readdirSync(p.claims)).toEqual([]); }); it("BUILD_LOCK_YIELD=never: a local run that must not be cut in half runs to the end, and the check job waits", async () => { const p = paths(); const local = start( `echo local-start >> ${p.trace}; sleep 4; echo local-end >> ${p.trace}`, env("local", "cotton-mac-release", { BUILD_LOCK_YIELD: "never" }), ); await until("the release holds the lock", () => trace().includes("local-start")); const ci = start(`echo ci >> ${p.trace}`, env("ci", "ci-rust-mac")); const [l, c] = await Promise.all([local.done, ci.done]); expect(l.status, l.stderr).toBe(0); expect(c.status, c.stderr).toBe(0); expect(trace()).toEqual(["local-start", "local-end", "ci"]); expect(l.stderr).not.toContain("YIELDED"); }, 30_000); it("a CHECK JOB holding the lock is never interrupted by another's claim", async () => { const p = paths(); const first = start( `echo first-start >> ${p.trace}; sleep 3; echo first-end >> ${p.trace}`, env("ci", "ci-swift-mac"), ); await until("the first check job holds the lock", () => trace().includes("first-start")); const second = start(`echo second >> ${p.trace}`, env("ci", "ci-rust-mac")); const [a, b] = await Promise.all([first.done, second.done]); expect(a.status, a.stderr).toBe(0); expect(b.status, b.stderr).toBe(0); expect(trace()).toEqual(["first-start", "first-end", "second"]); }, 30_000); }); describe("with-build-lock.sh — the rank on the CPU", () => { const probe = "python3 -c 'import os;print(os.getpriority(os.PRIO_PROCESS,0))'"; const parentNice = spawnSync("python3", ["-c", "import os;print(os.getpriority(os.PRIO_PROCESS," + process.pid + "))"], { encoding: "utf8" }).stdout.trim(); it("runs a local command at nice 19 — behind the Mac runner's jobs at +15", () => { const r = spawnSync("bash", [SCRIPT, "bash", "-c", probe], { env: env("local", "local-x"), encoding: "utf8" }); expect(r.status, r.stderr).toBe(0); expect(r.stdout.trim()).toBe("19"); }); it("runs a check job's command at the niceness it came with", () => { const r = spawnSync("bash", [SCRIPT, "bash", "-c", probe], { env: env("ci", "ci-x"), encoding: "utf8" }); expect(r.status, r.stderr).toBe(0); expect(r.stdout.trim()).toBe(parentNice); }); it("reads the rank from the runner's CI variables when nothing overrides it", () => { const asJob = spawnSync("bash", [SCRIPT, "bash", "-c", probe], { env: env("ci", "x", { BUILD_LOCK_CLASS: "", CI: "true" }), encoding: "utf8", }); expect(asJob.stdout.trim()).toBe(parentNice); const asBuilder = spawnSync("bash", [SCRIPT, "bash", "-c", probe], { env: env("local", "x", { BUILD_LOCK_CLASS: "", CI: "", GITHUB_ACTIONS: "" }), encoding: "utf8", }); expect(asBuilder.stdout.trim()).toBe("19"); }); it("records the holder's class in the lock, beside its pid and label", async () => { const p = paths(); const run = start(`cat ${p.lock}/class > ${p.trace}; sleep 0`, env("local", "local-x")); const r = await run.done; expect(r.status, r.stderr).toBe(0); expect(trace()).toEqual(["local"]); }); });