import { requireEnvironment, requires } from"./requires";/** * `scripts/ci/build-slot.sh` — one build slot per cargo job. * * The slot replaces the per-branch cargo target directory on the Linux lanes: * a fixed path (so sccache's cwd-keyed hashes hit for the workspace's own * crates), a bounded target directory (wiped past a budget, sccache re-links), * and ONE holder for the whole of a job's cargo work (so no second job writes * the directory between this job's phases — the corruption #404 met). These * tests drive the script against a scratch root with a fake checkout, and they * hold the properties the workflows lean on. */import { spawn, spawnSync } from"node:child_process";import { chmodSync, cpSync, existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from"node:fs";import { tmpdir } from"node:os";import { dirname, join } from"node:path";import { afterAll, describe, expect, it } from"vitest";import { linuxHostPath, publishDiskReading } from"./helpers/disk-reading";// The low-disk sweep runs only where flock(1) exists (Linux, where CI runs); a Mac has none, so its cases skip there.const HAS_FLOCK = spawnSync("bash", ["-c", "command -v flock"]).status === 0;const ROOT = join(__dirname, "..", "..");const SCRIPT = join(ROOT, "scripts", "ci", "build-slot.sh");const temps: string[] = [];afterAll(() => {for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true });});function scratch(): { checkout: string; slots: string } {const dir = mkdtempSync(join(tmpdir(), "build-slot-")); temps.push(dir);const checkout = join(dir, "work", "hostexecutor"); mkdirSync(join(checkout, "crates", "cotton-core"), { recursive: true }); writeFileSync(join(checkout, "crates", "Cargo.toml"), "[workspace]\n"); writeFileSync(join(checkout, "crates", "cotton-core", "lib.rs"), "// core\n"); writeFileSync(join(checkout, "README.md"), "a checkout\n");return { checkout, slots: join(dir, "slots") };}function env(slots: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {// A scratch HOME beside the slots, never the person's: on a Mac `run` admits// through the device policy, which reads and may reclaim under HOME.const home = join(dirname(slots), "home"); publishDiskReading(home, { volumeOf: dirname(slots) });return { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: home, COTTON_BUILD_SLOTS_ROOT: slots, COTTON_BUILD_SLOTS: "2", COTTON_BUILD_SLOT_WAIT_S: "20", COTTON_BUILD_SLOT_POLL_S: "1",// Off unless a case turns it on: the low-disk sweep reads the REAL disk, and// a test must not pass or fail by how full the machine running it is. COTTON_BUILD_SLOT_SWEEP_BELOW_GB: "0", ...extra, };}function run(args: string[], cwd: string, slots: string, extra: NodeJS.ProcessEnv = {}) {return spawnSync("bash", [SCRIPT, ...args], { cwd, encoding: "utf8", env: env(slots, extra) });}describe("build-slot.sh run — the lease, the copy and the environment", () => {// RULE: A leased slot runs the command inside a copy of the checkout at a fixed path, with CARGO_TARGET_DIR under the slot and the lease named in COTTON_CARGO_LOCK_HELD. it("copies the checkout into the slot, runs the command there, and exports the slot's target directory", () => {const { checkout, slots } = scratch();const r = run( ["run", "--label", "probe", "--", "bash", "-c", 'printf "%s\\n%s\\n%s\\n%s\\n" "$PWD" "$CARGO_TARGET_DIR" "$COTTON_CARGO_LOCK_HELD" "$COTTON_BUILD_SLOT"; cat README.md; cat crates/cotton-core/lib.rs'], checkout, slots, ); expect(r.status, r.stderr).toBe(0);const [pwd, target, held, slot, readme, core] = r.stdout.trim().split("\n"); expect(slot).toBe(join(slots, "1")); expect(pwd).toBe(join(slots, "1", "src")); expect(target).toBe(join(slots, "1", "target")); expect(held).toBe(join(slots, "1", ".lease")); expect(readme).toBe("a checkout"); expect(core).toBe("// core"); expect(r.stderr).toMatch(/leased .*\/slots\/1of2for'probe'/); expect(r.stderr).toMatch(/released .*\/slots\/1for'probe' \(exit 0/); });// RULE: The slot's target directory carries CACHEDIR.TAG and survives the command; the copy of the checkout does not. it("keeps the target directory (tagged) and removes the copy when the command ends", () => {const { checkout, slots } = scratch();const r = run(["run", "--", "bash", "-c", 'mkdir -p "$CARGO_TARGET_DIR/debug" && echo built > "$CARGO_TARGET_DIR/debug/a.rlib"'], checkout, slots); expect(r.status, r.stderr).toBe(0); expect(readFileSync(join(slots, "1", "target", "CACHEDIR.TAG"), "utf8")).toMatch(/^Signature: 8a477f597d28d172789f06886806bc55/); expect(readFileSync(join(slots, "1", "target", "debug", "a.rlib"), "utf8")).toBe("built\n"); expect(existsSync(join(slots, "1", "src"))).toBe(false); });// RULE: build-slot.sh carries the command's own exit status back, so a red phase is a red step. it("carries the command's exit status back", () => {const { checkout, slots } = scratch(); expect(run(["run", "--", "bash", "-c", "exit 42"], checkout, slots).status).toBe(42); });// RULE: The copy is made with hard links, so a slot's copy of the checkout costs no disk and is made in seconds. it("hard-links the copy rather than duplicating bytes", () => {const { checkout, slots } = scratch();const r = run(["run", "--", "bash", "-c", 'stat -c %i README.md 2>/dev/null || stat -f %i README.md'], checkout, slots); expect(r.status, r.stderr).toBe(0);const original = statSync(join(checkout, "README.md")).ino; expect(Number(r.stdout.trim())).toBe(original); });// RULE: Every file in the slot's copy is stamped with the lease time, so a job checked out BEFORE another branch built in the slot still finds all its sources newer than that branch's artifacts — cargo rebuilds them instead of calling them fresh. it("stamps every copied file later than an artifact a newer build left in the slot's target", () => {const { checkout, slots } = scratch();// This job checked out two hours ago and then waited for a slot.const twoHoursAgo = Math.floor(Date.now() / 1000) - 2 * 3600;for (const rel of ["README.md", "crates/Cargo.toml", "crates/cotton-core/lib.rs"]) { utimesSync(join(checkout, rel), twoHoursAgo, twoHoursAgo); }// Meanwhile another branch built in slot 1: its artifact is one hour old — NEWER than our checkout.const target = join(slots, "1", "target"); mkdirSync(join(target, "debug", "deps"), { recursive: true });const artifact = join(target, "debug", "deps", "libcotton_core.rlib"); writeFileSync(artifact, "the other branch's cotton-core\n");const oneHourAgo = twoHoursAgo + 3600; utimesSync(artifact, oneHourAgo, oneHourAgo);const before = Math.floor(Date.now() / 1000);const r = run( ["run", "--label", "late", "--", "bash", "-c", 'find . -exec stat -c "%Y %n" {} + 2>/dev/null || find . -exec stat -f "%m %N" {} +'], checkout, slots, { COTTON_BUILD_SLOTS: "1" }, ); expect(r.status, r.stderr).toBe(0);const stamped = r.stdout.trim().split("\n").map((line) => line.split(" ", 1)[0]).map(Number); expect(stamped.length).toBeGreaterThanOrEqual(5); // ., README.md, crates, Cargo.toml, cotton-core, lib.rsfor (const mtime of stamped) { expect(mtime).toBeGreaterThanOrEqual(before); expect(mtime).toBeGreaterThan(statSync(artifact).mtimeMs / 1000); } expect(r.stderr).toMatch(/every file stamped \d{12}\.\d{2}, later than anything the slot's target holds/); });// RULE: The lease stamp is strictly later than an artifact the previous holder wrote a fraction of a second before the lease — `touch -t` has whole seconds and cargo compares nanoseconds, so the stamp is the NEXT whole second (UTC), never the current one truncated. it("stamps later than an artifact written within the same second as the lease", () => {const { checkout, slots } = scratch();const target = join(slots, "1", "target"); mkdirSync(join(target, "debug", "deps"), { recursive: true });const artifact = join(target, "debug", "deps", "libcotton_core.rlib"); writeFileSync(artifact, "written a moment ago\n");// Just now, to the millisecond, the way the last holder's rustc left it.const now = Date.now() / 1000; utimesSync(artifact, now, now);const r = run( ["run", "--", "bash", "-c", 'stat -c "%.9Y" crates/cotton-core/lib.rs 2>/dev/null || stat -f "%Fm" crates/cotton-core/lib.rs'], checkout, slots, { COTTON_BUILD_SLOTS: "1" }, ); expect(r.status, r.stderr).toBe(0);const stamped = Number(r.stdout.trim()); expect(stamped).toBeGreaterThan(statSync(artifact).mtimeMs / 1000);// And the command starts no earlier than the stamp, so its own outputs are never older than its sources. expect(Date.now() / 1000).toBeGreaterThanOrEqual(stamped); });// RULE: Identical source bytes on the same immutable CI commit keep their// source stamp so a warm Cargo target is actually warm; pnpm pruning clocks// are not source inputs. A backdated edit or a dependency-layout change,// a different commit, or mutation during a command invalidates that reuse. it("reuses a real Cargo binary for identical inputs despite pnpm pruning clocks", (ctx) => {const { checkout, slots } = scratch();const cargo = spawnSync("bash", ["-c", "command -v cargo"], { encoding: "utf8" }).stdout.trim(); requires(ctx, { probe: () => !!cargo, reason: "cargo is required to prove build-slot freshness" }); mkdirSync(join(checkout, "crates/src"), { recursive: true }); writeFileSync(join(checkout, "crates/Cargo.toml"), '[package]\nname="slot-freshness"\nversion="0.1.0"\nedition="2021"\n[workspace]\n');const source = join(checkout, "crates/src/main.rs"); writeFileSync(source, 'fn main() { println!("original"); }\n');// Cargo creates this on its first invocation; pre-create it so the source// tree itself stays immutable during the guarded command.const lock = spawnSync(cargo, ["generate-lockfile", "--offline"], { cwd: join(checkout, "crates"), encoding: "utf8" }); expect(lock.status, lock.stderr).toBe(0);const command = '"$1" build --offline --manifest-path crates/Cargo.toml && "$CARGO_TARGET_DIR/debug/slot-freshness"';const invoke = (extra = "", sha = "synthetic-commit", cwd = checkout) => run(["run", "--", "bash", "-c", command + extra, "slot-freshness", cargo, dependency, nestedDependency], cwd, slots,// The real toolchain's homes beside the scratch HOME: rustup's proxy puts $CARGO_HOME/bin on cargo's PATH, where// it finds rustc, so a scratch CARGO_HOME leaves a Mac whose PATH carries no ~/.cargo/bin with no rustc at all. { COTTON_BUILD_SLOTS: "1", GITHUB_SHA: sha, RUSTUP_HOME: process.env.RUSTUP_HOME ?? join(process.env.HOME!, ".rustup"), CARGO_HOME: process.env.CARGO_HOME ?? join(process.env.HOME!, ".cargo") });// pnpm rewrites this bookkeeping timestamp for every fresh CI job,// even when its dependency layout and every source byte are identical. mkdirSync(join(checkout, "node_modules"), { recursive: true }); writeFileSync(join(checkout, "node_modules/.modules.yaml"), "layoutVersion: 5\nprunedAt: first-job\n");const workspaceState = (root: string, clock: number, name = "synthetic-app") => JSON.stringify({ lastValidatedTimestamp: clock, projects: { [root]: { name: "cache-test" }, [join(root, "apps/cotton")]: { name } }, }); writeFileSync(join(checkout, "node_modules/.pnpm-workspace-state.json"), workspaceState(checkout, 1));// pnpm store entries are shared inodes across CI checkouts. A Rust lease// must not restamp them or reject its own success when another job does.const dependency = join(checkout, "node_modules/shared/index.js"); mkdirSync(dirname(dependency), { recursive: true }); writeFileSync(dependency, "module.exports = 'stable';\n"); utimesSync(dependency, 1, 1);const nestedDependency = join(checkout, "packages/synthetic/node_modules/shared/index.js"); mkdirSync(dirname(nestedDependency), { recursive: true }); linkSync(dependency, nestedDependency);const dependencyTime = statSync(dependency).mtimeMs;const first = invoke(); expect(first.status, first.stderr).toBe(0); expect(first.stdout.trim()).toBe("original"); expect(statSync(dependency).mtimeMs).toBe(dependencyTime);const binary = join(slots, "1/target/debug/slot-freshness");const built = statSync(binary).mtimeMs;const otherCheckout = checkout + "-new"; cpSync(checkout, otherCheckout, { recursive: true });const sharedDependency = join(otherCheckout, "node_modules/shared/index.js"); rmSync(sharedDependency); linkSync(dependency, sharedDependency);const nestedShared = join(otherCheckout, "packages/synthetic/node_modules/shared/index.js"); rmSync(nestedShared); linkSync(nestedDependency, nestedShared);const modules = join(otherCheckout, "node_modules/.modules.yaml"); writeFileSync(modules, "layoutVersion: 5\nprunedAt: second-job\n");const workspace = join(otherCheckout, "node_modules/.pnpm-workspace-state.json"); writeFileSync(workspace, workspaceState(otherCheckout, 2));const same = invoke('; touch "$2" "$3"', "synthetic-commit", otherCheckout); expect(same.status, same.stderr).toBe(0); expect(same.stdout.trim()).toBe("original"); expect(statSync(binary).mtimeMs).toBe(built); expect(same.stderr).toContain("unchanged checkout bytes");const afterAnotherJob = invoke("", "synthetic-commit", otherCheckout); expect(afterAnotherJob.status, afterAnotherJob.stderr).toBe(0); expect(afterAnotherJob.stderr).toContain("unchanged checkout bytes"); expect(statSync(binary).mtimeMs).toBe(built);// Dependency content still participates in the complete input fingerprint. writeFileSync(sharedDependency, "module.exports = 'changed';\n");const dependencyEdit = invoke("", "synthetic-commit", otherCheckout); expect(dependencyEdit.status, dependencyEdit.stderr).toBe(0); expect(dependencyEdit.stderr).not.toContain("unchanged checkout bytes");const afterDependencyEdit = statSync(binary).mtimeMs; expect(afterDependencyEdit).toBeGreaterThan(built);// No dependency-layout field gets the timestamp exemption. writeFileSync(modules, "layoutVersion: 6\nprunedAt: third-job\n");const layout = invoke("", "synthetic-commit", otherCheckout); expect(layout.status, layout.stderr).toBe(0); expect(statSync(binary).mtimeMs).toBeGreaterThan(afterDependencyEdit); expect(layout.stderr).not.toContain("unchanged checkout bytes");const afterLayout = statSync(binary).mtimeMs; writeFileSync(workspace, workspaceState(otherCheckout, 3, "changed-app"));const project = invoke("", "synthetic-commit", otherCheckout); expect(project.status, project.stderr).toBe(0); expect(statSync(binary).mtimeMs).toBeGreaterThan(afterLayout); expect(project.stderr).not.toContain("unchanged checkout bytes"); writeFileSync(source, 'fn main() { println!("changed!"); }\n'); utimesSync(source, 1, 1);const changed = invoke(); expect(changed.status, changed.stderr).toBe(0); expect(changed.stdout.trim()).toBe("changed!"); expect(statSync(binary).mtimeMs).toBeGreaterThan(built);const mutation = invoke('; echo "// changed during build" >> crates/src/main.rs'); expect(mutation.status, mutation.stderr).toBe(0); expect(existsSync(join(slots, "1/.source-stamp.json"))).toBe(false);const next = invoke(); expect(next.status, next.stderr).toBe(0); expect(next.stderr).not.toContain("unchanged checkout bytes");const failed = invoke("; exit 42"); expect(failed.status).toBe(42); expect(existsSync(join(slots, "1/.source-stamp.json"))).toBe(false);const other = invoke("", "another-commit"); expect(other.status, other.stderr).toBe(0); expect(other.stderr).not.toContain("unchanged checkout bytes"); }, 30000);// RULE: Two jobs never share a leased slot: the second takes the next free slot, and with none free it waits and exits 75 at the deadline. it("hands two concurrent runs two different slots, and a third waits — then times out with exit 75", async () => {const { checkout, slots } = scratch();const hold = (label: string) => spawn("bash", [SCRIPT, "run", "--label", label, "--", "bash", "-c", 'echo "$COTTON_BUILD_SLOT"; sleep 6'], { cwd: checkout, env: env(slots), stdio: ["ignore", "pipe", "pipe"], });const a = hold("a");const b = hold("b");const out = (p: ReturnType<typeof spawn>) =>newPromise<{ code: number | null; stdout: string; stderr: string }>((resolve) => {let stdout = "";let stderr = ""; p.stdout!.on("data", (d) => (stdout += d)); p.stderr!.on("data", (d) => (stderr += d)); p.on("close", (code) => resolve({ code, stdout, stderr })); });awaitnewPromise((r) => setTimeout(r, 1500));const third = run(["run", "--label", "c", "--", "true"], checkout, slots, { COTTON_BUILD_SLOT_WAIT_S: "2" }); expect(third.status).toBe(75); expect(third.stderr).toMatch(/all 2 slots are leased — 'c' is waiting/); expect(third.stderr).toMatch(/TIMEOUT after 2s/);const [ra, rb] = awaitPromise.all([out(a), out(b)]); expect(ra.code).toBe(0); expect(rb.code).toBe(0);const taken = [ra.stdout.trim(), rb.stdout.trim()].sort(); expect(taken).toEqual([join(slots, "1"), join(slots, "2")]); }, 30_000);// RULE: A killed holder releases its slot at once — the kernel drops the flock with the process, so a cancelled job never wedges a slot. it("a slot whose holder was killed is free for the next comer", async () => {const { checkout, slots } = scratch();const holder = spawn("bash", [SCRIPT, "run", "--", "bash", "-c", "exec -a build-slot-probe-holder sleep 30"], { cwd: checkout, env: env(slots, { COTTON_BUILD_SLOTS: "1" }), stdio: ["ignore", "pipe", "pipe"], });// Wait until the holder actually holds the lease: a fixed pause read 0// instead of 75 on a loaded runner (run 6361), because the holder had not// leased yet when the comer asked. The comer itself is the probe.let blocked = run(["run", "--", "true"], checkout, slots, { COTTON_BUILD_SLOTS: "1", COTTON_BUILD_SLOT_WAIT_S: "1" });for (const deadline = Date.now() + 12_000; blocked.status !== 75 && Date.now() < deadline; ) {awaitnewPromise((r) => setTimeout(r, 250)); blocked = run(["run", "--", "true"], checkout, slots, { COTTON_BUILD_SLOTS: "1", COTTON_BUILD_SLOT_WAIT_S: "1" }); } expect(blocked.status, blocked.stderr).toBe(75);// Kill the whole process group the way a cancelled runner step is killed. holder.kill("SIGKILL"); spawnSync("bash", ["-c", `pkill -KILL -f build-slot-probe-holder || true`]);awaitnewPromise((r) => setTimeout(r, 500));const next = run(["run", "--", "true"], checkout, slots, { COTTON_BUILD_SLOTS: "1", COTTON_BUILD_SLOT_WAIT_S: "3" }); expect(next.status, next.stderr).toBe(0); }, 30_000);// RULE: A daemon the command starts must not inherit the lease descriptor, or the slot is held for ever (run 2413 did this to the cargo lock). it("does not leak the lease to a daemon the command starts", async () => {const { checkout, slots } = scratch();const r = run( ["run", "--", "bash", "-c", 'nohup bash -c "exec -a build-slot-probe-daemon sleep 8" >/dev/null 2>&1 & echo started'], checkout, slots, { COTTON_BUILD_SLOTS: "1" }, ); expect(r.status, r.stderr).toBe(0);// The daemon is alive; the slot must be free anyway.const next = run(["run", "--", "true"], checkout, slots, { COTTON_BUILD_SLOTS: "1", COTTON_BUILD_SLOT_WAIT_S: "2" }); expect(next.status, next.stderr).toBe(0); spawnSync("bash", ["-c", `pkill -KILL -f build-slot-probe-daemon || true`]); }, 20_000);// RULE: A slot's target directory is wiped at lease when it is over its budget, so N slots bound the disk by rule rather than by sweep. it("wipes a target directory that is over the budget, and keeps one that is not", () => {const { checkout, slots } = scratch(); mkdirSync(join(slots, "1", "target", "debug"), { recursive: true }); writeFileSync(join(slots, "1", "target", "debug", "big.rlib"), Buffer.alloc(2 * 1024 * 1024));// 2 MB against a budget of 0 GB → over → wiped.// The budget is the Linux body's rule: a Mac's slot is bounded by the device policy instead.const linux = { PATH: linuxHostPath() };const wiped = run(["run", "--", "true"], checkout, slots, { ...linux, COTTON_BUILD_SLOTS: "1", COTTON_BUILD_SLOT_BUDGET_GB: "0" }); expect(wiped.status, wiped.stderr).toBe(0); expect(wiped.stderr).toMatch(/past the 0 GB budget — wiping it; sccache re-links/); expect(existsSync(join(slots, "1", "target", "debug", "big.rlib"))).toBe(false); expect(existsSync(join(slots, "1", "target", "CACHEDIR.TAG"))).toBe(true);// The same file against a 40 GB budget → kept. writeFileSync(join(slots, "1", "target", "debug2.rlib"), Buffer.alloc(1024));const kept = run(["run", "--", "true"], checkout, slots, { ...linux, COTTON_BUILD_SLOTS: "1" }); expect(kept.status, kept.stderr).toBe(0); expect(kept.stderr).toMatch(/\(budget 40 GB\)/); expect(existsSync(join(slots, "1", "target", "debug2.rlib"))).toBe(true); });// RULE: Under the low-disk mark a lease empties the target of every other slot no job holds, and never one a job holds — 28 Sep 2026, three idle slots held 120 GB while the host fell under the 60 GB build floor. it("on a low disk empties the other idle slots' targets and keeps a held one", async (ctx) => { requires(ctx, { probe: () => HAS_FLOCK, reason: "flock is unavailable on this runner" });const { checkout, slots } = scratch();for (const k of ["2", "3"]) { mkdirSync(join(slots, k, "target", "debug"), { recursive: true }); writeFileSync(join(slots, k, "target", "debug", "big.rlib"), "x"); }// Slot 2 is held by a job for the whole run.const holder = spawn("bash", ["-c", `exec 9>"${join(slots, "2", ".lease")}"; flock 9; exec -a build-slot-probe-sweep sleep 20`], { stdio: "ignore", });awaitnewPromise((r) => setTimeout(r, 800));// A mark no real disk is under, so "low" is always true here.const r = run(["run", "--", "true"], checkout, slots, { COTTON_BUILD_SLOTS: "3", COTTON_BUILD_SLOT_OS: "Linux", COTTON_BUILD_SLOT_SWEEP_BELOW_GB: "999999999", COTTON_CI_MIN_FREE_GB: "0", }); holder.kill("SIGKILL");// The holder execs sleep, so its exact PID above is the complete fixture process. expect(r.status, r.stderr).toBe(0); expect(r.stderr).toMatch(/emptying the targets of slots no job holds/); expect(r.stderr).toMatch(/slot 2: held by a job — kept/); expect(r.stderr).toMatch(/slot 3: idle — target emptied/); expect(existsSync(join(slots, "2", "target", "debug", "big.rlib"))).toBe(true); expect(existsSync(join(slots, "3", "target"))).toBe(false); }, 30_000);// RULE: Above the low-disk mark a lease leaves every other slot's target alone — the next job on that slot wants its warm build. it("above the mark touches no other slot, and 0 turns the sweep off", () => {const { checkout, slots } = scratch(); mkdirSync(join(slots, "2", "target"), { recursive: true }); writeFileSync(join(slots, "2", "target", "warm.rlib"), "x");for (const mark of ["1", "0"]) {const r = run(["run", "--", "true"], checkout, slots, { COTTON_BUILD_SLOT_OS: "Linux", COTTON_BUILD_SLOT_SWEEP_BELOW_GB: mark }); expect(r.status, r.stderr).toBe(0); expect(r.stderr).not.toMatch(/emptying the targets/); expect(existsSync(join(slots, "2", "target", "warm.rlib"))).toBe(true); } });// RULE: If the disk is still under the build floor after the idle slots are emptied, the lease empties its own slot's target too, rather than let the build start and fail on disk. it("under the build floor after the sweep empties its own target as well", (ctx) => { requires(ctx, { probe: () => HAS_FLOCK, reason: "flock is unavailable on this runner" });const { checkout, slots } = scratch(); mkdirSync(join(slots, "1", "target", "debug"), { recursive: true }); writeFileSync(join(slots, "1", "target", "debug", "own.rlib"), "x");const r = run(["run", "--", "true"], checkout, slots, { COTTON_BUILD_SLOTS: "1", COTTON_BUILD_SLOT_OS: "Linux", COTTON_BUILD_SLOT_SWEEP_BELOW_GB: "999999999", COTTON_CI_MIN_FREE_GB: "999999999", }); expect(r.status, r.stderr).toBe(0); expect(r.stderr).toMatch(/under the 999999999 GB build floor — emptying this slot's own target/); expect(existsSync(join(slots, "1", "target", "debug", "own.rlib"))).toBe(false); expect(existsSync(join(slots, "1", "target", "CACHEDIR.TAG"))).toBe(true); });// RULE: The device floor reclaims shared caches before idle targets; a Mac never clears a leased target while admitting its owner (architect, 14 Oct 2026). it("preserves a Mac's leased target while admitting its command", () => {const { checkout, slots } = scratch();for (const k of ["1", "2"]) { mkdirSync(join(slots, k, "target"), { recursive: true }); writeFileSync(join(slots, k, "target", "warm.rlib"), "cached build"); }const r = run(["run", "--", "bash", "-c", 'test -f "$CARGO_TARGET_DIR/warm.rlib"'], checkout, slots, { COTTON_BUILD_SLOT_OS: "Darwin", COTTON_BUILD_SLOTS: "1", COTTON_BUILD_SLOT_SWEEP_BELOW_GB: "999999999", COTTON_CI_MIN_FREE_GB: "999999999", }); expect(r.status, r.stderr).toBe(0); expect(r.stderr).not.toContain("emptying this slot's own target"); expect(existsSync(join(slots, "2", "target", "warm.rlib"))).toBe(true); expect(existsSync(join(slots, "1", "target", "CACHEDIR.TAG"))).toBe(true); });// RULE: build-slot.sh refuses a run whose slots root lies inside the checkout, because the copy would then contain itself. it("refuses a slots root inside the checkout", () => {const { checkout } = scratch();const r = run(["run", "--", "true"], checkout, join(checkout, "slots")); expect(r.status).toBe(2); expect(r.stderr).toMatch(/copy would contain itself/); });// RULE: build-slot.sh refuses to lease a slot around no command, and refuses a count or a budget that is not a whole number. it("refuses an empty command and a count that is not a number", () => {const { checkout, slots } = scratch(); expect(run(["run", "--"], checkout, slots).status).toBe(2); expect(run(["run"], checkout, slots).status).toBe(2); expect(run(["run", "--", "true"], checkout, slots, { COTTON_BUILD_SLOTS: "three" }).status).toBe(2); expect(run(["lease"], checkout, slots).status).toBe(2); });// RULE: Without a slot count, a Linux host gets three slots and a Mac gets one — the Mac's RAM is the machine mutex's business, not a slot's. it("defaults to three slots on Linux and one on Darwin", () => {const source = readFileSync(SCRIPT, "utf8"); expect(source).toMatch(/elif \[ "\$os" = Darwin \]; then\n\s+N=1\nelse\n\s+N=3/); }); it("list says what each slot holds", () => {const { checkout, slots } = scratch(); expect(run(["list"], checkout, slots).stdout).toMatch(/no slots under/); run(["run", "--", "bash", "-c", 'echo x > "$CARGO_TARGET_DIR/x"'], checkout, slots);const r = run(["list"], checkout, slots); expect(r.status).toBe(0); expect(r.stdout).toMatch(/slot 1: free — target \d+ MB/); expect(r.stdout).toMatch(/slot 2: free — target empty/); });});describe("build-slot.sh run — the share: what the slot's command may ask of the host", () => {// Why: on 28 Sep 2026 the Linux host read load 31 on 16 threads, 863% of it the runner's// own check jobs — each cargo job sized itself and nothing added them up. The lease knows// how many slots are busy, so a job sharing the host is cut to cores / (busy + 1), the// `+ 1` for everything outside a slot. A job ALONE is not cut: review of 29 Sep 2026// refused a fixed cores / (slots + 1) because it gave a lone job 4 threads, half the bottom// of rust-job-sizing.sh's measured 8-16, and so twice the wall time for nothing.const probe ='printf "%s %s %s %s\\n" "${CARGO_BUILD_JOBS-unset}" "${NEXTEST_TEST_THREADS-unset}" "${RUST_TEST_THREADS-unset}" "${COTTON_BUILD_SLOT_THREADS-unset}"';const ASKED = { CARGO_BUILD_JOBS: "12", NEXTEST_TEST_THREADS: "16", RUST_TEST_THREADS: "16" };/** Hold slots 1..busy the way a live Mac job does: a lease directory naming a live pid. */function holdByMkdir(slots: string, busy: number): void {for (let k = 1; k <= busy; k += 1) { mkdirSync(join(slots, String(k), ".lease.d"), { recursive: true }); writeFileSync(join(slots, String(k), ".lease.d", "pid"), `${process.pid}\n`); } }/** Run the probe in a slot with `others` slots already busy (mkdir leases, the macOS path). */const share = (others: number, extra: NodeJS.ProcessEnv) => {const { checkout, slots } = scratch(); holdByMkdir(slots, others);const r = run(["run", "--label", "share", "--", "bash", "-c", probe], checkout, slots, { COTTON_BUILD_SLOT_OS: "Darwin", ...extra, }); expect(r.status, r.stderr).toBe(0);return { values: r.stdout.trim().split(" "), stderr: r.stderr }; };// RULE: A slot's command that runs ALONE keeps the threads it asked for — rust-job-sizing.sh's measured range — and Gradle gets no --max-workers. it("leaves a job alone on the host at what it asked for", () => {const { values, stderr } = share(0, { COTTON_BUILD_SLOTS: "3", COTTON_BUILD_SLOT_CORES: "16", ...ASKED }); expect(values).toEqual(["12", "16", "16", "unset"]); expect(stderr).toMatch(/share: alone \(1of3 slots busy\) — running as asked, jobs=12 nextest=16 test=16/); });// RULE: A slot's command that shares the host with B-1 other busy slots gets CARGO_BUILD_JOBS, NEXTEST_TEST_THREADS and RUST_TEST_THREADS of at most cores / (B + 1). it("divides the Linux host's 16 threads by the slots busy when the job starts", () => {const two = share(1, { COTTON_BUILD_SLOTS: "3", COTTON_BUILD_SLOT_CORES: "16", ...ASKED }); expect(two.values).toEqual(["5", "5", "5", "5"]); expect(two.stderr).toMatch(/share: 16 cores \/ \(2of3 slots busy \+ 1\) = 5/);const three = share(2, { COTTON_BUILD_SLOTS: "3", COTTON_BUILD_SLOT_CORES: "16", ...ASKED }); expect(three.values).toEqual(["4", "4", "4", "4"]); expect(three.stderr).toMatch(/share: 16 cores \/ \(3of3 slots busy \+ 1\) = 4/); });// RULE: A lease whose holder is dead does not count as busy. it("does not count a slot whose holder is dead", () => {const { checkout, slots } = scratch(); mkdirSync(join(slots, "1", ".lease.d"), { recursive: true });const dead = spawnSync("bash", ["-c", "echo $$"], { encoding: "utf8" }).stdout.trim(); writeFileSync(join(slots, "1", ".lease.d", "pid"), `${dead}\n`); mkdirSync(join(slots, "2", ".lease.d"), { recursive: true }); writeFileSync(join(slots, "2", ".lease.d", "pid"), `${dead}\n`);const r = run(["run", "--", "bash", "-c", probe], checkout, slots, { COTTON_BUILD_SLOT_OS: "Darwin", COTTON_BUILD_SLOTS: "3", COTTON_BUILD_SLOT_CORES: "16", ...ASKED, }); expect(r.status, r.stderr).toBe(0); expect(r.stdout.trim()).toBe("12 16 16 unset"); });// RULE: The flock path (Linux) counts the busy slots too. it("counts a slot another job holds by flock", () => {// A Mac has no flock(1); the mkdir cases above hold the rule there.if (!HAS_FLOCK) return;const { checkout, slots } = scratch(); mkdirSync(join(slots, "1"), { recursive: true });const holder = spawn("bash", ["-c", `exec 9>"${join(slots, "1", ".lease")}"; flock 9; echo held; exec -a build-slot-probe-share sleep 20`], { stdio: ["ignore", "pipe", "ignore"], });try { spawnSync("bash", ["-c", `for i in $(seq 50); do flock -n "${join(slots, "1", ".lease")}" true || exit 0; sleep 0.1; done; exit 1`]);const r = run(["run", "--", "bash", "-c", probe], checkout, slots, { COTTON_BUILD_SLOT_OS: "Linux", COTTON_BUILD_SLOTS: "3", COTTON_BUILD_SLOT_CORES: "16", ...ASKED, }); expect(r.status, r.stderr).toBe(0); expect(r.stdout.trim()).toBe("5 5 5 5"); expect(r.stderr).toMatch(/leased .*\/slots\/2of3/); } finally { holder.kill("SIGKILL"); }const alone = run(["run", "--", "bash", "-c", probe], checkout, slots, { COTTON_BUILD_SLOT_OS: "Linux", COTTON_BUILD_SLOTS: "3", COTTON_BUILD_SLOT_CORES: "16", ...ASKED, }); expect(alone.stdout.trim()).toBe("12 16 16 unset"); });// RULE: The share is a ceiling, never a floor — a smaller ask (a Mac sized by its memory) is kept. it("keeps a smaller ask and lowers a larger one", () => {const { values, stderr } = share(2, { COTTON_BUILD_SLOTS: "3", COTTON_BUILD_SLOT_CORES: "16", CARGO_BUILD_JOBS: "2", NEXTEST_TEST_THREADS: "16", RUST_TEST_THREADS: "12", }); expect(values).toEqual(["2", "4", "4", "4"]); expect(stderr).toMatch(/asked jobs=2 nextest=16 test=12; running with jobs=2 nextest=4 test=4/); });// RULE: However the numbers fall, the busy slots' shares summed never exceed the cores. it("never hands the busy slots together more than the cores, and never less than one each", () => {for (const cores of [2, 4, 16, 64]) {for (const busy of [2, 3, 4]) {const [jobs] = share(busy - 1, { COTTON_BUILD_SLOTS: "4", COTTON_BUILD_SLOT_CORES: String(cores) }).values.map(Number); expect(jobs).toBeGreaterThanOrEqual(1);if (cores >= busy + 1) expect(jobs * busy).toBeLessThanOrEqual(cores); } } });// RULE: A core count that cannot be read is cut as four, not as unbounded. it("cuts an unreadable core count as four", () => {const stubs = mkdtempSync(join(tmpdir(), "build-slot-nocores-")); temps.push(stubs);for (const tool of ["nproc", "sysctl"]) { writeFileSync(join(stubs, tool), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); }const { values, stderr } = share(1, { COTTON_BUILD_SLOTS: "2", COTTON_BUILD_SLOT_CORES: "lots", PATH: `${stubs}:${process.env.PATH ?? "/usr/bin:/bin"}`, }); expect(stderr).toMatch(/cannot read the core count/); expect(values).toEqual(["1", "1", "1", "1"]); });// RULE: android-check.sh hands Gradle the slot's share as --max-workers only when there is one. it("hands Gradle the share inside a shared slot", () => {const src = readFileSync(join(ROOT, "scripts", "android-check.sh"), "utf8"); expect(src).toMatch(/--max-workers="\$COTTON_BUILD_SLOT_THREADS"/); expect(src).toMatch(/''\|\*\[!0-9\]\*\) ;;/); expect(src).toMatch(/\$\{gradle_workers\[@\]\+"\$\{gradle_workers\[@\]\}"\}/); });});describe("Linux build-slot train priority", () => { requireEnvironment({ probe: () => HAS_FLOCK, reason: "flock is unavailable on this runner" });asyncfunction locked(file: string) { mkdirSync(join(file, ".."), { recursive: true });const child = spawn("bash", ["-c", 'exec 7>>"$1"; flock 7; echo ready; read -r release', "hold", file], { stdio: ["pipe", "pipe", "pipe"] });awaitnewPromise<void>((resolve) => child.stdout!.once("data", () => resolve()));const done = newPromise<void>((resolve) => child.once("close", () => resolve()));let released = false;returnasync () => { if (released) return; released = true; child.stdin!.end("release\n"); await done; }; }asyncfunction waiter(slots: string, order: number, event: string) {const file = join(slots, ".waiters", `${String(order).padStart(12, "0")}.waiter`); mkdirSync(join(slots, ".waiters"), { recursive: true }); writeFileSync(file, `${event}\nsynthetic-${order}\n${Math.floor(Date.now() / 1000)}\n`); writeFileSync(join(slots, ".waiter-sequence"), String(order));return locked(file); }// RULE: A waiting train takes the next freed Linux slot before an older pull check, because only the train moves main. it("admits a train ahead of an older pull waiter", async () => {const { checkout, slots } = scratch();const release = await waiter(slots, 1, "pull_request");try {const r = run(["run", "--label", "train", "--", "true"], checkout, slots, { GITHUB_EVENT_NAME: "merge_group", COTTON_BUILD_SLOT_OS: "Linux" }); expect(r.status, r.stderr).toBe(0); } finally { await release(); } });// RULE: On a real release, a train overtakes an already polling pull check; merely checking a queue snapshot would miss an admission race. it("hands a released slot to a train before the pull that was already waiting", async () => {const { checkout, slots } = scratch();const release = await locked(join(slots, "1", ".lease"));const order = join(checkout, "..", "order");const start = (label: string, event: string) => {const child = spawn("bash", [SCRIPT, "run", "--label", label, "--", "bash", "-c", 'echo "$1" >> "$2"', "write", label, order], { cwd: checkout, env: env(slots, { GITHUB_EVENT_NAME: event, COTTON_BUILD_SLOT_OS: "Linux", COTTON_BUILD_SLOTS: "1" }), stdio: ["ignore", "pipe", "pipe"], });let stderr = "";let ready!: () => void;const waiting = newPromise<void>((resolve) => { ready = resolve; }); child.stderr!.on("data", (data) => { stderr += data; if (stderr.includes("is waiting")) ready(); });const done = newPromise<void>((resolve, reject) => child.once("close", (code) => { ready();if (code === 0) resolve(); else reject(newError(`${label}: ${code}: ${stderr}`)); }));return { child, waiting, done }; };const pull = start("pull", "pull_request");await pull.waiting;const train = start("train", "merge_group");await train.waiting;try {await release();awaitPromise.all([pull.done, train.done]); expect(readFileSync(order, "utf8").trim().split("\n")).toEqual(["train", "pull"]); } finally { pull.child.kill(); train.child.kill();await release(); } }, 15000);// RULE: While a train waits, a pull check cannot consume the last free slot; otherwise a slow-polling train starves again. it("reserves the last free slot until the waiting train takes it", async () => {const { checkout, slots } = scratch();const freeHolder = await locked(join(slots, "1", ".lease"));const release = await waiter(slots, 1, "merge_group");try {const r = run(["run", "--label", "pull", "--", "true"], checkout, slots, { GITHUB_EVENT_NAME: "pull_request", COTTON_BUILD_SLOT_OS: "Linux", COTTON_BUILD_SLOT_WAIT_S: "1" }); expect(r.status, r.stderr).toBe(75); expect(existsSync(join(slots, "2", "src"))).toBe(false); } finally { await release(); await freeHolder(); } });// RULE: Trains are admitted oldest first, so a newer train cannot repeatedly steal the next freed slot from its predecessor. it("keeps a newer train behind the oldest train waiter", async () => {const { checkout, slots } = scratch();const release = await waiter(slots, 1, "merge_group");try {const r = run(["run", "--", "true"], checkout, slots, { GITHUB_EVENT_NAME: "merge_group", COTTON_BUILD_SLOT_OS: "Linux", COTTON_BUILD_SLOT_WAIT_S: "1" }); expect(r.status, r.stderr).toBe(75); } finally { await release(); } });// RULE: Train waits default to 5400 seconds and report each holder every five minutes, so a queue stall explains who is using its capacity. it("gives trains a longer default budget and reports holder names, events and ages repeatedly", async () => {const { checkout, slots } = scratch();const release1 = await locked(join(slots, "1", ".lease"));const release2 = await locked(join(slots, "2", ".lease"));const bin = join(checkout, "bin"); mkdirSync(bin);const clock = join(checkout, "clock"); writeFileSync(clock, "1000");const date = join(bin, "date");// Four reports still prove repetition; larger fake jumps avoid needless subprocesses on loaded runners. writeFileSync(date, `#!/bin/bashif [ "$1" = +%s ]; then n=$(cat '${clock}') echo "$n" echo $((n + 901)) > '${clock}'else exec /bin/date "$@"fi`); chmodSync(date, 0o755); writeFileSync(join(slots, "1", ".holder"), "rust\npull_request\n900\n"); writeFileSync(join(slots, "2", ".holder"), "rust-lint\nmerge_group\n800\n");try {const extra = { GITHUB_EVENT_NAME: "merge_group", COTTON_BUILD_SLOT_OS: "Linux", COTTON_BUILD_SLOT_WAIT_S: "", COTTON_BUILD_SLOT_POLL_S: "0", PATH: `${bin}:${process.env.PATH}` };const r = run(["run", "--label", "train", "--", "true"], checkout, slots, extra); expect(r.status, r.stderr).toBe(75); expect(r.stderr).toContain("TIMEOUT after 5400s");const reports = r.stderr.split("\n").filter((line) => line.includes("has waited")); expect(reports.length).toBeGreaterThan(2);for (const report of reports) { expect(report).toMatch(/slot 1 is held by 'rust' \(pull_request\) for \d+s/); expect(report).toMatch(/slot 2 is held by 'rust-lint' \(merge_group\) for \d+s/); } writeFileSync(clock, "1000");const pull = run(["run", "--", "true"], checkout, slots, { ...extra, GITHUB_EVENT_NAME: "pull_request" }); expect(pull.status, pull.stderr).toBe(75); expect(pull.stderr).toContain("TIMEOUT after 2700s"); } finally { await release1(); await release2(); } }, 15_000);// RULE: A cancelled train's registration cannot reserve capacity forever; the kernel drops its waiter lock even on SIGKILL. it("reclaims an unlocked stale train waiter and admits a pull", async () => {const { checkout, slots } = scratch();const release = await waiter(slots, 1, "merge_group");await release();const r = run(["run", "--", "true"], checkout, slots, { GITHUB_EVENT_NAME: "pull_request", COTTON_BUILD_SLOT_OS: "Linux" }); expect(r.status, r.stderr).toBe(0); });});