// The machine-wide build mutex is RE-ENTRANT, and this is the guard.//// MEASURED. `scripts/build-xcframework.sh` and `scripts/ios-test.sh` take// /tmp/tinmen-build.lock THEMSELVES. Anything that wrapped one of them in// `scripts/with-build-lock.sh` — a verification script did, and the `ios` CI job// easily could, since the `swift` job already wraps its whole step — deadlocked// against itself: the outer call held the lock, the inner call waited for it,// and the only symptom was the word "waiting" for two hours until the lock's own// exit-75 timeout fired. The old fix was a rule in the docs ("never wrap it").// The real fix is that wrapping is harmless, which is what these tests hold.//// THE ENVIRONMENT VARIABLE ALONE IS NOT THE ANSWER, so the tests below prove// both halves. `TINMEN_BUILD_LOCK_HELD` exported by the holder is a HINT; the// inner call believes it only after walking its own parent chain and finding// that pid there, and only when the marker names the same lock path. A bare// variable would be a skeleton key — an export left behind in a long-lived// shell, or a recycled pid — and it would wave a build past a lock somebody// else really holds, which is the swap-crash the lock exists to prevent.import { execFileSync, spawn, spawnSync, typeChildProcess } from"node:child_process";import { chmodSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from"node:fs";import { tmpdir } from"node:os";import { dirname, join, resolve } from"node:path";import { fileURLToPath } from"node:url";import { afterAll, beforeAll, describe, expect, it } from"vitest";import { publishBuildPeaks, publishDiskReading } from"./helpers/disk-reading";const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");const LOCK_SCRIPT = join(REPO_ROOT, "scripts", "with-build-lock.sh");const IOS_TEST = join(REPO_ROOT, "scripts", "ios-test.sh");/** A lock directory of this test's own — never the machine's real one. */function lockDir(): string {return join(mkdtempSync(join(tmpdir(), "build-lock-")), "lock");}typeRun = { status: number; stdout: string; stderr: string };function runLock(args: string[], env: Record<string, string>): Run {// A scratch HOME with a fresh device reading beside the lock: on a Mac the// wrapper admits through the device policy, which reads it there — never the person's HOME.const home = join(dirname(env.BUILD_LOCK_DIR), "home"); publishDiskReading(home);// A byte of RAM per build: admission must not turn on the machine's free RAM. publishBuildPeaks(home);const done = spawnSync("/bin/bash", [LOCK_SCRIPT, ...args], { cwd: REPO_ROOT, encoding: "utf8", env: { ...process.env, HOME: home, BUILD_LOCK_MEMORY_BYTES: "17179869184",// A scratch cargo target, not named shared, as build-lock-ci-first.test.ts says:// with none, a worktree's generated .cargo/config.toml hands the wrapper the// machine's real shared target, and every command here waits on that target's// cargo lock behind whatever cargo build is running on the Mac. CARGO_TARGET_DIR: join(dirname(env.BUILD_LOCK_DIR), "target"), ...env, }, });return { status: done.status ?? -1, stdout: done.stdout ?? "", stderr: done.stderr ?? "" };}/** * A live process that is NOT an ancestor of anything the tests spawn: a sibling. * `kill -0` on it succeeds, so the lock treats it as a live holder — which is * exactly the shape a stale exported marker has. */let sibling: ChildProcess;beforeAll(() => { sibling = spawn("/bin/sleep", ["120"], { stdio: "ignore" });});afterAll(() => { sibling.kill("SIGKILL");});describe("with-build-lock.sh, taken twice in one process tree", () => { it("acquires and releases when nothing holds it", () => {const lock = lockDir();const run = runLock(["bash", "-c", 'cat "$BUILD_LOCK_DIR/pid"'], { BUILD_LOCK_DIR: lock, BUILD_LOCK_LABEL: "solo", }); expect(run.status).toBe(0); expect(run.stderr).toContain("acquired by 'solo'"); expect(run.stdout.trim()).toMatch(/^\d+$/); expect(existsSync(lock), "the lock directory outlived its holder").toBe(false); }); it("runs a nested call immediately, without touching the lock", () => {const lock = lockDir();// The inner call reports the pid file it found; the outer reports it again// afterwards. If the inner had acquired (or released) anything, one of the// three readings would differ — and if it had WAITED, this test would sit// here for two hours instead of failing.const inner = `BUILD_LOCK_LABEL=inner /bin/bash "${LOCK_SCRIPT}" cat "$BUILD_LOCK_DIR/pid"`;const run = runLock( ["bash","-c",`cat "$BUILD_LOCK_DIR/pid"; ${inner}; cat "$BUILD_LOCK_DIR/pid"; test -d "$BUILD_LOCK_DIR" && echo still-there`, ], { BUILD_LOCK_DIR: lock, BUILD_LOCK_LABEL: "outer" }, ); expect(run.status).toBe(0);const lines = run.stdout.trim().split("\n");const [before, seenByInner, after, survived] = lines; expect(before).toMatch(/^\d+$/); expect(seenByInner, "the inner call saw a different holder").toBe(before); expect(after, "the inner call rewrote the pid file").toBe(before); expect(survived, "the inner call removed the lock its parent holds").toBe("still-there"); expect(existsSync(lock)).toBe(false); }, 30_000); it("says whose lock it re-entered, and never says it acquired one", () => {const lock = lockDir();const run = runLock( ["bash", "-c", `BUILD_LOCK_LABEL=inner /bin/bash "${LOCK_SCRIPT}" true`], { BUILD_LOCK_DIR: lock, BUILD_LOCK_LABEL: "ci-swift-mac" }, ); expect(run.status).toBe(0); expect(run.stderr).toContain("re-entered under 'ci-swift-mac'"); expect(run.stderr).not.toContain("acquired by 'inner'"); expect(run.stderr).not.toContain("waiting for"); }, 30_000);});describe("a marker that does not name an ancestor buys nothing", () => { it("takes the lock normally when the named pid is a live SIBLING", () => {const lock = lockDir();const run = runLock(["true"], { BUILD_LOCK_DIR: lock, BUILD_LOCK_LABEL: "fresh", TINMEN_BUILD_LOCK_HELD: String(sibling.pid), TINMEN_BUILD_LOCK_DIR: lock, TINMEN_BUILD_LOCK_LABEL: "somebody-else", }); expect(run.status).toBe(0); expect(run.stderr).toContain(`pid ${sibling.pid} is not an ancestor`); expect(run.stderr).toContain("acquired by 'fresh'"); expect(run.stderr).not.toContain("re-entered"); }); it("still waits — and times out — when that pid really holds the lock", () => {const lock = lockDir(); execFileSync("/bin/mkdir", ["-p", lock]); writeFileSync(join(lock, "pid"), `${sibling.pid}\n`); writeFileSync(join(lock, "label"), "somebody-else\n");// A zero-minute budget so the wait ends at once. Without the ancestor check// the marker would have walked this call straight past a lock another// process is holding — two heavy builds, one 16 GB Mac.const run = runLock(["echo", "THE-BUILD-RAN"], { BUILD_LOCK_DIR: lock, BUILD_LOCK_LABEL: "fresh", BUILD_LOCK_TIMEOUT_MIN: "0", TINMEN_BUILD_LOCK_HELD: String(sibling.pid), TINMEN_BUILD_LOCK_DIR: lock, TINMEN_BUILD_LOCK_LABEL: "somebody-else", }); expect(run.status, "exit 75 is EX_TEMPFAIL — the queue was stuck").toBe(75); expect(run.stdout).not.toContain("THE-BUILD-RAN"); expect(readFileSync(join(lock, "pid"), "utf8").trim()).toBe(String(sibling.pid)); }, 30_000); it("ignores a marker that names a different lock", () => {const lock = lockDir();const run = runLock( ["bash","-c",`BUILD_LOCK_DIR="${lock}-other" BUILD_LOCK_LABEL=inner /bin/bash "${LOCK_SCRIPT}" true`, ], { BUILD_LOCK_DIR: lock, BUILD_LOCK_LABEL: "outer" }, ); expect(run.status).toBe(0); expect(run.stderr).toContain("acquired by 'inner'"); expect(run.stderr).toMatch(/it holds '[^']*', not '/); }, 30_000); it("ignores a marker that is not a pid at all", () => {const lock = lockDir();const run = runLock(["true"], { BUILD_LOCK_DIR: lock, BUILD_LOCK_LABEL: "fresh", TINMEN_BUILD_LOCK_HELD: "yes", TINMEN_BUILD_LOCK_DIR: lock, }); expect(run.status).toBe(0); expect(run.stderr).toContain("that is not a pid"); expect(run.stderr).toContain("acquired by 'fresh'"); });});describe("scripts/ios-test.sh under scripts/with-build-lock.sh", () => {// The exact nesting that deadlocked. Every heavy tool is a stub on PATH, so// this proves the LOCKING, not Xcode: `xcodegen` and `npx` for the project// generation ios-test.sh runs first, `xcodebuild` for the tests themselves.let stubDir: string;let ran: string; beforeAll(() => { stubDir = mkdtempSync(join(tmpdir(), "ios-test-stubs-")); ran = join(stubDir, "xcodebuild-ran");const stub = (name: string, body: string) => {const path = join(stubDir, name); writeFileSync(path, `#!/bin/sh\n${body}\n`); chmodSync(path, 0o755); }; stub("xcodegen", "exit 0");// Exit 3 is what `ios-spec-gate.ts` answers for "every gate is on", which// leaves gen-ios-project.sh using the hand-written spec. stub("npx", "exit 3"); stub("xcodebuild", `printf '%s\\n' "$@" > "${ran}"`); }); it("re-enters instead of waiting on the lock its caller holds", () => {const lock = lockDir();const run = runLock(["bash", IOS_TEST], { PATH: `${stubDir}:${process.env.PATH ?? ""}`, BUILD_LOCK_DIR: lock, BUILD_LOCK_LABEL: "outer-ios",// Skip the simulator lookup: this test has no opinion about simulators. COTTON_SIM: "00000000-0000-0000-0000-000000000000",// And the launch smoke that follows a green run: it launches the app// on the simulator this test does not have. Its own lock re-entry is// the same script's, proved above. COTTON_SKIP_SMOKE: "1", }); expect(run.status, run.stderr).toBe(0); expect(run.stderr).toContain("acquired by 'outer-ios'"); expect(run.stderr).toContain("re-entered under 'outer-ios'"); expect(run.stderr).not.toContain("waiting for"); expect(existsSync(ran), "the wrapped xcodebuild never ran").toBe(true); expect(readFileSync(ran, "utf8")).toContain("test"); }, 120_000);});