/** * A BUILD HELD IN ADMISSION IS NEVER SILENT, AND TERM ALWAYS FREES WHAT IT HELD. * * Architect's ruling, 14 Oct 2026 23:45 IST, after cut #3 of Mac 0.29.57 sat * 28 minutes inside the build policy with no line printed, and cut #2's * wrapper kept the build lock through SIGTERM and freed it only on SIGKILL. * Every case runs the real `scripts/with-build-lock.sh` against a scratch lock * and, on a Mac, the real build policy against a synthetic HOME — nothing * touches the machine's lock or ledger. */ import { execFileSync, spawn, type ChildProcess } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { afterEach, expect, it } from "vitest"; import { publishDiskReading } from "./helpers/disk-reading"; const ROOT = resolve(__dirname, "../.."); const SCRIPT = join(ROOT, "scripts/with-build-lock.sh"); const POLICY = join(ROOT, "scripts/lib/mac_disk_policy.py"); 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 = ""; }); // A synthetic HOME the policy admits in at once: a fresh keep-free reading for // this volume and twenty tiny recorded peaks, so a build's RAM need is 1 byte. function home() { scratch ||= mkdtempSync(join(tmpdir(), "build-lock-held-")); const dir = join(scratch, "home"); mkdirSync(dir, { recursive: true }); publishDiskReading(dir, { keepFreeBytes: 100 }); const peak = (kind: string) => JSON.stringify({ at: 1, kind, peak: 1, total: 1 }); writeFileSync(join(dir, ".cottondb/build-peaks.log"), Array.from({ length: 20 }, () => `${peak("swift")}\n${peak("rust")}`).join("\n") + "\n"); return dir; } function env(label: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { const h = home(); return { ...process.env, HOME: h, BUILD_LOCK_MEMORY_BYTES: "17179869184", BUILD_LOCK_DIR: join(scratch, "lock"), BUILD_LOCK_LOG: join(scratch, "wait.log"), BUILD_LOCK_LABEL: label, BUILD_LOCK_CLASS: "local", BUILD_LOCK_YIELD: "never", BUILD_LOCK_LOCAL_NICE: "0", BUILD_LOCK_POLL_SECONDS: "1", BUILD_LOCK_TERM_GRACE_SECONDS: "3", TINMEN_BUILD_LOCK_HELD: "", TINMEN_BUILD_LOCK_DIR: "", COTTON_DISK_MONITOR_PID: "", // 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(scratch, "target"), ...extra, }; } type Done = { status: number | null; stderr: string; ms: number }; function start(command: string, e: NodeJS.ProcessEnv) { const began = Date.now(); const child = spawn("bash", [SCRIPT, "bash", "-c", command], { env: e, cwd: e.HOME, 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, ms: Date.now() - began }))); return { child, done, stderr: () => stderr }; } async function until(test: () => boolean, what: string, ms = 20_000) { const deadline = Date.now() + ms; while (Date.now() < deadline) { if (test()) return; await new Promise((r) => setTimeout(r, 50)); } throw new Error(`timed out waiting for ${what}`); } const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } }; function ledger(): { pid: number }[] { const path = join(home(), ".cottondb/build-reservations.json"); return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : []; } /// RULE: A wrapper sent TERM — its command ignoring TERM, or the wrapper itself waiting on the lock — exits within its bounded grace with the command's whole tree dead, its lock gone and no reservation row left, because cut #2's wrapper held the lock through SIGTERM until a KILL (architect, 14 Oct 2026). it("a TERMed wrapper leaves no lock, no reservation and no live tree behind", async () => { const pidFile = join(home(), "stubborn.pid"); // The command ignores TERM, as a wedged build does; its pid is written down. const holder = start(`trap '' TERM; echo $$ > ${pidFile}; while :; do sleep 0.2; done`, env("stubborn")); await until(() => existsSync(pidFile) && existsSync(join(scratch, "lock/pid")), "the stubborn build to start"); const stubborn = Number(readFileSync(pidFile, "utf8").trim()); // A second wrapper waits on the lock with a 30 s poll; its TERM is taken at once. const waiter = start("true", env("waiter", { BUILD_LOCK_POLL_SECONDS: "30" })); await until(() => waiter.stderr().includes("WAITING on 'stubborn'"), "the waiter's line"); waiter.child.kill("SIGTERM"); const w = await waiter.done; expect(w.status).toBe(143); expect(w.ms).toBeLessThan(20_000); expect(existsSync(join(scratch, "lock/pid")), "the waiter's TERM left the holder's lock alone").toBe(true); holder.child.kill("SIGTERM"); const h = await holder.done; expect(h.status).toBe(143); expect(h.stderr).toContain("stopped by TERM"); expect(alive(stubborn), "the command that ignored TERM was KILLed after the grace").toBe(false); expect(existsSync(join(scratch, "lock")), "the lock is released").toBe(false); expect(ledger(), "no reservation row is left").toEqual([]); }, 60_000); /// RULE: A wrapper waiting on the build lock says what it waits on and since when as it starts and again while it waits, and gives up at its timeout with exit 75 and the holder named, because a held cut sat 28 minutes with no line (architect, 14 Oct 2026). it("a wait on the lock is said and given up with the holder named", async () => { const holder = start("sleep 30", env("holder-cut")); await until(() => existsSync(join(scratch, "lock/pid")), "the holder to take the lock"); const holderPid = readFileSync(join(scratch, "lock/pid"), "utf8").trim(); const waiter = start("true", env("held-cut", { BUILD_LOCK_TIMEOUT_SECONDS: "4", BUILD_LOCK_SAY_SECONDS: "1" })); const w = await waiter.done; expect(w.status).toBe(75); const on = `'holder-cut' (pid ${holderPid})`; expect(w.stderr).toMatch(new RegExp(`WAITING on ${on.replace(/[()]/g, "\\$&")} for the build lock since \\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d`)); expect(w.stderr).toContain(`still WAITING on ${on}`); expect(w.stderr).toMatch(new RegExp(`TIMEOUT after 4s waiting on ${on.replace(/[()]/g, "\\$&")} since `)); holder.child.kill("SIGTERM"); await holder.done; }, 60_000); /// RULE: A cut held in RAM admission says what holds it while held, and a wait that cannot be admitted gives up at its limit naming the holder, because a cut that is late must say why (architect, 14 Oct 2026). it("a held cut says what holds it, and gives up naming the holder", () => { const out = execFileSync( "python3", [ "-c", `import importlib.util,json,os,sys,tempfile,threading,time,subprocess,io,contextlib from pathlib import Path from types import SimpleNamespace for k in ['COTTON_DISK_MONITOR_PID','BUILD_LOCK_CLASS','BUILD_LOCK_LABEL','TINMEN_BUILD_LOCK_HELD','TINMEN_BUILD_LOCK_DIR','COTTON_CUT_LEASE']:os.environ.pop(k,None) s=importlib.util.spec_from_file_location('policy',${JSON.stringify(POLICY)}) m=importlib.util.module_from_spec(s);s.loader.exec_module(m) m.WAIT_SAY_SECONDS=0.2 G=m.GIB with tempfile.TemporaryDirectory() as folder: home=Path(folder);p=home/'.cottondb/disk-policy.json';p.parent.mkdir() p.write_text(json.dumps({'keepFreeBytes':100,'sampledAt':time.time(),'volumeId':home.stat().st_dev})) ledger=p.parent/'build-reservations.json' os.environ['HOME']=str(home) holder=subprocess.Popen(['sleep','30']) time.sleep(0.05) ledger.write_text(json.dumps([{'pid':holder.pid,'need':10,'kind':'swift','ram':G,'class':'cut','label':'holder-cut','started':time.time()}])) def release(): time.sleep(1.5);holder.kill();holder.wait() threading.Thread(target=release).start() err=io.StringIO() with contextlib.redirect_stderr(err): with m.build_reservation(home,home,10,'swift',lambda p:SimpleNamespace(free=100*m.GIB),None,[],lambda:G,0.05,total=64*G,cls='cut',label='held-cut'): pass text=err.getvalue() assert f'WAITING for RAM behind cut holder-cut (pid {holder.pid})' in text,text assert 'still WAITING for RAM behind cut holder-cut' in text,text # Never admitted: a second live cut holds it past the limit — and has outlived the # ceiling it declared (a cut behind a holder still inside its ceiling waits on: # build-admission-cut-first.test.ts, 17 Oct 2026). other=subprocess.Popen(['sleep','30']) try: time.sleep(0.05) ledger.write_text(json.dumps([{'pid':other.pid,'need':10,'kind':'swift','ram':G,'class':'cut','label':'other-cut','started':time.time(),'limit':0.5}])) try: with contextlib.redirect_stderr(io.StringIO()): with m.build_reservation(home,home,10,'swift',lambda p:SimpleNamespace(free=100*m.GIB),None,[],lambda:G,0.05,wait_limit=1,total=64*G,cls='cut'): raise AssertionError('admitted behind a live cut') raise AssertionError('never gave up') except m.HeldTooLong as error: assert f'TIMEOUT after 0m — gave up waiting for RAM behind cut other-cut (pid {other.pid})' in str(error),error assert [r['pid'] for r in json.loads(ledger.read_text())]==[other.pid],ledger.read_text() finally: other.kill();other.wait() print('held cuts say why')`, ], { encoding: "utf8", timeout: 60_000 }, ); expect(out).toContain("held cuts say why"); });