/** * RELEASES GO FIRST — A CHECK JOB YIELDS A MAC'S BUILD LOCK TO A RELEASE. * * On 29 Sep 2026 a TestFlight build waited 18 minutes, and a Mac release * install over 40, behind check jobs on a Mac's `/tmp/tinmen-build.lock`. * `scripts/with-build-lock.sh` now ranks a caller that says * `BUILD_LOCK_CLASS=release` above `ci` exactly as `ci` is above `local`: * * - a waiting release files a claim in `<lock>.release-waiting`; * - a HOLDING check job yields to it — its whole tree is stopped — and runs * again from the top inside the same step, whose exit is the re-run's; * - a check job or a local run never takes a free lock while a release claim * is live; * - a release is never stopped. * * 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, typeChildProcess } 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-release-first-"));return { lock: join(scratch, "lock"), claims: join(scratch, "lock.ci-waiting"), releaseClaims: join(scratch, "lock.release-waiting"), log: join(scratch, "wait.log"), trace: join(scratch, "trace"), };}function env(cls: "release" | "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);// Builds that need a byte of RAM each: whether two share the lock is the// slot rule under test, not how much RAM the machine has free right now. 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, };}typeDone = { status: number | null; stderr: string };function start(command: string, e: NodeJS.ProcessEnv): { child: ChildProcess; done: Promise<Done> } {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 = newPromise<Done>((ok) => child.on("close", (status) => ok({ status, stderr })));return { child, done };}asyncfunction until(what: string, test: () => boolean, ms = 20_000): Promise<void> {const end = Date.now() + ms;while (!test()) {if (Date.now() > end) thrownewError(`timed out waiting for: ${what}`);awaitnewPromise((r) => setTimeout(r, 100)); }}const trace = () => (existsSync(paths().trace) ? readFileSync(paths().trace, "utf8").trim().split("\n") : []);describe("with-build-lock.sh — a release outranks a check job", () => {// RULE: A check job holding a Mac's build lock yields to a waiting release and re-runs from the top in the same step, which exits with the re-run's status, never failed. it("a HOLDING check job yields to a waiting release, then runs again and exits green", async () => {const p = paths();const marker = join(scratch, "second-attempt");const pidsFile = join(scratch, "first-pids");// The first attempt records its shell and a grandchild and sleeps for a// minute; the second, which only happens after a yield, finishes at once.const ci = start( [`echo ci-start >> ${p.trace}`,`if [ -f ${marker} ]; then echo ci-end >> ${p.trace}; exit 0; fi`,`touch ${marker}`,"sleep 60 & echo $$ $! > " + pidsFile,"wait", ].join("; "), env("ci", "ci-swift-mac"), );await until("the check job holds the lock", () => existsSync(pidsFile));const release = start(`echo release >> ${p.trace}`, env("release", "ci-cotton"));const [c, r] = awaitPromise.all([ci.done, release.done]); expect(r.status, r.stderr).toBe(0); expect(c.status, c.stderr).toBe(0); expect(trace()).toEqual(["ci-start", "release", "ci-start", "ci-end"]); expect(c.stderr).toContain("YIELDED: release 'ci-cotton'"); expect(r.stderr).toContain("claimed as a release");// The whole tree went, the `sleep` grandchild included.for (const pid of readFileSync(pidsFile, "utf8").trim().split(" ")) {const alive = spawnSync("kill", ["-0", pid]).status === 0; expect(alive, `pid ${pid} of the yielded check job outlived the yield`).toBe(false); } expect(existsSync(p.lock)).toBe(false); expect(existsSync(p.releaseClaims) ? readdirSync(p.releaseClaims) : []).toEqual([]); expect(readFileSync(p.log, "utf8")).toMatch(/\tci-cotton\t\d+\tci-swift-mac\n/); }, 60_000);// RULE: A check job never takes a free build lock while a release's claim is live, and keeps its own claim so no local run slips in between. it("a WAITING check job never takes a free lock while a release claim is live", async () => {const p = paths(); mkdirSync(p.releaseClaims, { recursive: true });// This test's own process stands in for a waiting release. writeFileSync(join(p.releaseClaims, String(process.pid)), "cotton-mac-release\n");const ci = start(`echo ci >> ${p.trace}`, env("ci", "ci-rust-mac"));awaitnewPromise((r) => setTimeout(r, 2500)); expect(trace(), "the check job went ahead of a waiting release").toEqual([]);// Its own claim is filed meanwhile, so a local run still waits behind it. expect(existsSync(p.claims) ? readdirSync(p.claims) : []).toHaveLength(1); rmSync(join(p.releaseClaims, String(process.pid)));const c = await ci.done; expect(c.status, c.stderr).toBe(0); expect(trace()).toEqual(["ci"]); expect(c.stderr).toContain("release 'cotton-mac-release' goes first"); expect(readdirSync(p.claims)).toEqual([]); }, 30_000); it("a local run waits behind a release claim too", async () => {const p = paths(); mkdirSync(p.releaseClaims, { recursive: true }); writeFileSync(join(p.releaseClaims, String(process.pid)), "cotton-mac-release\n");const local = start(`echo local >> ${p.trace}`, env("local", "local-verify-fast"));awaitnewPromise((r) => setTimeout(r, 2500)); expect(trace()).toEqual([]); rmSync(join(p.releaseClaims, String(process.pid)));const l = await local.done; expect(l.status, l.stderr).toBe(0); expect(l.stderr).toContain("release 'cotton-mac-release' goes first"); }, 30_000);// RULE: A release holding the build lock is never stopped for a check job's claim; the check job waits for it. it("a HOLDING release is never stopped for a check job", async () => {const p = paths();const release = start(`echo release-start >> ${p.trace}; sleep 3; echo release-end >> ${p.trace}`, env("release", "cotton-mac-release"), );await until("the release holds the lock", () => trace().includes("release-start"));const ci = start(`echo ci >> ${p.trace}`, env("ci", "ci-rust-mac"));const [r, c] = awaitPromise.all([release.done, ci.done]); expect(r.status, r.stderr).toBe(0); expect(c.status, c.stderr).toBe(0); expect(trace()).toEqual(["release-start", "release-end", "ci"]); expect(r.stderr).not.toContain("YIELDED"); }, 30_000);});// RULE: Ordinary builds share two slots at 24 GB, but 16 GB Macs and declared archives stay serial; the wait log measures only actual queueing.it.each([16, 24])("bounds ordinary builds on a %i GB Mac", async (gb) => {const p = paths();const finish = join(scratch, "finish");const memory = { BUILD_LOCK_MEMORY_BYTES: String(gb * 1024 ** 3), BUILD_LOCK_YIELD: "never" };const first = start(`echo first >> ${p.trace}; while [ ! -f ${finish} ]; do sleep 0.1; done`, env("local", "first", memory));await until("first started", () => trace().includes("first"));const second = start(`echo second >> ${p.trace}; while [ ! -f ${finish} ]; do sleep 0.1; done`, env("local", "second", memory));if (gb === 24) {await until("second shares the lock", () => trace().includes("second"));const nested = start(`bash "${SCRIPT}" true`, env("local", "third", { ...memory, BUILD_LOCK_TIMEOUT_MIN: "0" })); expect((await nested.done).status).toBe(75);const rows = readFileSync(p.log, "utf8").trim().split("\n").map((r) => r.split("\t")); expect(rows.map((r) => r.slice(1))).toEqual([["first", "0", "-"], ["second", "0", "-"]]); } else {awaitnewPromise((r) => setTimeout(r, 1200)); expect(trace()).toEqual(["first"]); } writeFileSync(finish, "");const results = awaitPromise.all([first.done, second.done]);for (const result of results) expect(result.status, result.stderr).toBe(0);});// RULE: An exclusive caller waits for both ordinary holders, and every later caller waits for the exclusive build to finish, avoiding archive memory pressure.it("an exclusive build drains both slots and bars another holder", async () => {const p = paths();const finish = join(scratch, "finish");const archiveFinish = join(scratch, "archive-finish");const memory = { BUILD_LOCK_MEMORY_BYTES: String(24 * 1024 ** 3), BUILD_LOCK_YIELD: "never" };const holders = ["one", "two"].map((label) => start(`echo ${label} >> ${p.trace}; while [ ! -f ${finish} ]; do sleep 0.1; done`, env("local", label, memory)));await until("both holders", () => trace().length === 2);const archive = start(`echo archive >> ${p.trace}; while [ ! -f ${archiveFinish} ]; do sleep 0.1; done`, env("local", "archive", { ...memory, BUILD_LOCK_EXCLUSIVE: "1" }));awaitnewPromise((r) => setTimeout(r, 1200)); expect(trace()).not.toContain("archive"); writeFileSync(finish, "");await until("archive started", () => trace().includes("archive"));const later = start(`echo later >> ${p.trace}`, env("local", "later", memory));awaitnewPromise((r) => setTimeout(r, 1200)); expect(trace()).not.toContain("later"); writeFileSync(archiveFinish, "");for (const result ofawaitPromise.all([...holders.map((h) => h.done), archive.done, later.done])) expect(result.status, result.stderr).toBe(0);}, 20_000);// RULE: A release claim empties both build slots before it runs; CI holders yield and restart so a release never competes for archive memory.it("a release drains two CI holders", async () => {const p = paths();const memory = { BUILD_LOCK_MEMORY_BYTES: String(24 * 1024 ** 3) };const holders = ["one", "two"].map((label) => {const marker = join(scratch, label);return start(`if [ -f ${marker} ]; then echo ${label}-end >> ${p.trace}; exit 0; fi; touch ${marker}; echo ${label}-start >> ${p.trace}; sleep 60`, env("ci", label, memory)); });await until("both CI holders", () => trace().length === 2);const release = start(`echo release >> ${p.trace}`, env("release", "release", memory));for (const result ofawaitPromise.all([...holders.map((h) => h.done), release.done])) expect(result.status, result.stderr).toBe(0); expect(trace().slice(2)[0]).toBe("release");for (const holder of holders) expect((await holder.done).stderr).toContain("YIELDED:");}, 20_000);// RULE: A nested archive cannot upgrade a shared holder while another build runs; the outer caller must reserve exclusive capacity.it("refuses an exclusive re-entry under a shared holder", async () => {const nested = start(`BUILD_LOCK_EXCLUSIVE=1 bash "${SCRIPT}" true`, env("local", "shared", { BUILD_LOCK_MEMORY_BYTES: String(24 * 1024 ** 3) })); expect((await nested.done).status).toBe(2);});