/** * A BUILD WAITING ON THE BUILD LOCK HOLDS NO RAM FROM ITS HOLDER (lock-order, 7 Nov 2026). * * On one Mac CI swift-compile run 7966 took /tmp/tinmen-build.lock, then sat 32 * minutes in the policy's RAM admission inside it behind a red-main lane's * `swift test`: that lane's outer policy had been admitted with a 2.55 GB * reservation and was itself waiting in with-build-lock.sh for the lock the CI * job held. The policy (scripts/lib/mac_disk_policy.py) now leaves out of a lock * holder's admission every reservation whose process is, or is an ancestor of, a * live waiter on that lock, found by the marker every waiter files beside it * (scripts/with-build-lock.sh, "EVERY WAITER SAYS SO BESIDE THE LOCK"). * * The admission cases run the real module against a scratch lock and ledger; the * marker case runs the real wrapper against a scratch lock. Nothing touches the * machine's lock or ledger. */import { execFileSync, spawn, typeChildProcess } from"node:child_process";import { existsSync, mkdtempSync, readdirSync, readFileSync, renameSync, 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 modulePath = join(ROOT, "scripts/lib/mac_disk_policy.py");const SCRIPT = join(ROOT, "scripts/with-build-lock.sh");// The fixture of build-admission-cut-first.test.ts, plus a scratch build lock// (`BUILD_LOCK_DIR`) and `waiter()`: a live process R with a child W, as the// lane's policy process (the reservation's pid) is an ancestor of the// with-build-lock.sh that waits. `held(...)` runs one admission and stops it at// its second poll, answering what it printed.function python(body: string) {return execFileSync("python3", ["-c",`import importlib.util,tempfile,json,time,os,io,contextlib,subprocessfrom pathlib import Pathfrom types import SimpleNamespacefor k in ['COTTON_DISK_MONITOR_PID','BUILD_LOCK_CLASS','BUILD_LOCK_LABEL','TINMEN_BUILD_LOCK_HELD','TINMEN_BUILD_LOCK_DIR','COTTON_CUT_LEASE','BUILD_LOCK_DIR','BUILD_LOCK_CEILING_SECONDS','BUILD_LOCK_MAX_MIN']:os.environ.pop(k,None)s=importlib.util.spec_from_file_location('policy',${JSON.stringify(modulePath)})m=importlib.util.module_from_spec(s);s.loader.exec_module(m)G=m.GIBdef setup(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})) lock=home/'tinmen-build.lock';os.environ['BUILD_LOCK_DIR']=str(lock) return home,p.parent/'build-reservations.json',lockdef lane(pid,ram=2*G):return {'pid':pid,'need':10,'kind':'swift','ram':ram,'class':'lane','started':time.time()}def hold(lock,pid):lock.mkdir(exist_ok=True);(lock/'pid').write_text(f'{pid}\\n')def mark(lock,kind,pid):d=Path(f'{lock}.{kind}');d.mkdir(exist_ok=True);(d/str(pid)).write_text('label\\n')procs=[]def waiter(): # The sleep is given no pipe of ours: an orphan holding this script's stderr would hold execFileSync open. r=subprocess.Popen(['bash','-c','sleep 60 </dev/null >/dev/null 2>&1 & echo $!; wait'],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True) w=int(r.stdout.readline());procs.append((r,w));return r.pid,wdef held(home,available): err=io.StringIO();polls=[];original=m.time.sleep def sleep(seconds): polls.append(seconds) if len(polls)==2:raise KeyboardInterrupt m.time.sleep=sleep try: with contextlib.redirect_stderr(err): with m.build_reservation(home,home,10,'swift',lambda p:SimpleNamespace(free=100*G),None,[],lambda:available,0.01,total=64*G): err.write('ADMITTED\\n') except KeyboardInterrupt:pass finally:m.time.sleep=original return err.getvalue()try:${body.replace(/^/gm, " ")}finally: for proc,w in procs: try:os.kill(w,9) except ProcessLookupError:pass proc.kill();proc.wait()`, ], { encoding: "utf8" }, );}describe("mac_disk_policy.py — a build waiting on the build lock holds no RAM from its holder", () => {// RULE: A build holding the build lock is admitted although an admitted reservation would put it under the floor, when that reservation's process is an ancestor of a live waiter on the lock it holds — the one-Mac inversion, run 7966 (lock-order, 7 Nov 2026). it("admits the holder past the reservation of a lane waiting on its lock, and says so", () => { expect( python(`with tempfile.TemporaryDirectory() as folder: home,ledger,lock=setup(folder);m.row_gone=lambda row:None r,w=waiter() # The holder is this process's PARENT: it is found through the ancestor chain. hold(lock,os.getppid());mark(lock,'local-waiting',w) ledger.write_text(json.dumps([lane(r)])) ram=m.memory_need('swift',home,64*G) # Counting the lane's 2 GiB leaves 1 GiB above the need, under the 2 GiB floor. said=held(home,ram+3*G) assert 'ADMITTED' in said and 'no wait' in said,said assert 'not counting 1 reservation(s) waiting on the build lock this build holds' in said,said rows=json.loads(ledger.read_text());assert [x['pid'] for x in rows]==[r],'the holder released its row; the waiter keeps its own' print('holder admitted')`), ).toContain("holder admitted"); });// RULE: The exclusion is only for a reservation that waits on the lock: a lane holding RAM without a waiting marker in its tree still holds the lock's holder back below the floor, and the line names it (lock-order, 7 Nov 2026: keep the floor). it("still holds the holder back for a reservation that is not waiting on its lock", () => { expect( python(`with tempfile.TemporaryDirectory() as folder: home,ledger,lock=setup(folder);m.row_gone=lambda row:None r,w=waiter();other,_=waiter() # A marker for some unrelated waiter changes nothing for R. hold(lock,os.getpid());mark(lock,'ci-waiting',other) ledger.write_text(json.dumps([lane(r)])) ram=m.memory_need('swift',home,64*G) said=held(home,ram+3*G) assert 'ADMITTED' not in said,said assert f'WAITING for RAM: held by swift build pid {r}' in said,said assert 'not counting' not in said,said print('non-waiter counted')`), ).toContain("non-waiter counted"); });// RULE: A build that does not hold the build lock counts a waiter's reservation like any other, so a lane is never admitted past another lane on the strength of someone else's lock (lock-order, 7 Nov 2026). it("counts a waiter's reservation for a build that does not hold the lock", () => { expect( python(`with tempfile.TemporaryDirectory() as folder: home,ledger,lock=setup(folder);m.row_gone=lambda row:None r,w=waiter();stranger,_=waiter() hold(lock,stranger);mark(lock,'local-waiting',w) ledger.write_text(json.dumps([lane(r)])) ram=m.memory_need('swift',home,64*G) said=held(home,ram+3*G) assert 'ADMITTED' not in said and 'not counting' not in said,said print('not the holder')`), ).toContain("not the holder"); });// RULE: The floor stands after the exclusion: a holder still waits while RAM is genuinely short, and its wait line says how many reservations it left out (lock-order, 7 Nov 2026). it("keeps the floor for the holder after leaving the waiter out", () => { expect( python(`with tempfile.TemporaryDirectory() as folder: home,ledger,lock=setup(folder);m.row_gone=lambda row:None r,w=waiter();busy,_=waiter() hold(lock,os.getpid());mark(lock,'walk-waiting',w) ledger.write_text(json.dumps([lane(r),lane(busy,ram=1*G)])) ram=m.memory_need('swift',home,64*G) # Without the waiter: ram + 1 GiB (busy) + 2 GiB floor > ram + 2.5 GiB available. said=held(home,ram+int(2.5*G)) assert 'ADMITTED' not in said,said assert f'held by swift build pid {busy};' in said and f'pid {r}' not in said,said assert 'not counting 1 reservation(s) waiting on the build lock this build holds' in said,said print('floor kept')`), ).toContain("floor kept"); });// RULE: A holder that leaves a waiter's reservation out names that waiter in its own slot, `<slot>/excluded/<waiter pid>`, so on a two-slot Mac the waiter cannot take the other slot while this build runs on RAM promised to it (lock-slot, 9 Nov 2026). it("names the waiters it left out in the slot it holds", () => { expect( python(`with tempfile.TemporaryDirectory() as folder: home,ledger,lock=setup(folder);m.row_gone=lambda row:None r,w=waiter();other,_=waiter() hold(lock,os.getppid());mark(lock,'local-waiting',w);mark(lock,'ci-waiting',other) ledger.write_text(json.dumps([lane(r)])) ram=m.memory_need('swift',home,64*G) said=held(home,ram+3*G) assert 'ADMITTED' in said,said # Only the waiter whose reservation was left out is named; the other waiter holds none. assert sorted(os.listdir(lock/'excluded'))==[str(w)],os.listdir(lock/'excluded') print('waiter named')`), ).toContain("waiter named"); });// RULE: A waiter that took the other slot before the holder named it runs beside the holder, so its reservation counts again and the floor holds (lock-slot, 9 Nov 2026). it("counts a waiter that already holds the other slot", () => { expect( python(`with tempfile.TemporaryDirectory() as folder: home,ledger,lock=setup(folder);m.row_gone=lambda row:None r,w=waiter() hold(lock,os.getppid());mark(lock,'local-waiting',w);hold(Path(f'{lock}.slot-2'),w) ledger.write_text(json.dumps([lane(r)])) ram=m.memory_need('swift',home,64*G) said=held(home,ram+3*G) assert 'ADMITTED' not in said,said assert f'held by swift build pid {r}' in said,said print('slot taker counted')`), ).toContain("slot taker counted"); });// RULE: Waiters are read through the process tree: a row is waiting on the lock when its pid is a waiter or an ancestor of one, never a descendant or a sibling, and a waiting cut claim is not an admitted row (lock-order, 7 Nov 2026). it("reads waiters up through the process tree", () => { expect( python(`table=[(10,1,10),(11,10,10),(12,11,10),(20,1,20),(21,20,20),(30,12,30)]rows=[lane(10),lane(11),lane(20),lane(21),lane(30),dict(lane(12),waiting=True,**{'class':'cut'})]assert m.rows_waiting_on_lock(rows,{12},table)=={10,11},m.rows_waiting_on_lock(rows,{12},table)assert m.rows_waiting_on_lock(rows,{21},table)=={20,21}assert m.rows_waiting_on_lock(rows,set(),table)==set()print('tree read')`), ).toContain("tree read"); });});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 lockEnv(label: string): NodeJS.ProcessEnv { scratch ||= mkdtempSync(join(tmpdir(), "build-admission-lock-holder-"));const home = join(scratch, "home"); publishDiskReading(home); publishBuildPeaks(home);return { ...process.env, HOME: home, 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_POLL_SECONDS: "1", BUILD_LOCK_YIELD: "", TINMEN_BUILD_LOCK_HELD: "", TINMEN_BUILD_LOCK_DIR: "", CARGO_TARGET_DIR: join(scratch, "target"), };}function start(command: string, e: NodeJS.ProcessEnv) {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<{ status: number | null; stderr: string }>((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)); }}describe("with-build-lock.sh — every waiter says so beside the lock", () => {// RULE: A local run waiting on the build lock files `<lock>.local-waiting/<its pid>` with its label inside, and removes it when it takes the lock — the marker the policy reads to leave its reservation out of the holder's admission (lock-order, 7 Nov 2026: the lane's `swift test` on that Mac wrote none). it("files a local waiter's marker and removes it on acquire", async () => {const holderEnv = lockEnv("holder");const lock = holderEnv.BUILD_LOCK_DIR!;const markers = `${lock}.local-waiting`;const finish = join(scratch, "finish");const listed = () => (existsSync(markers) ? readdirSync(markers) : []);const holder = start(`while [ ! -f ${finish} ]; do sleep 0.1; done`, holderEnv);await until("the holder has the lock", () => existsSync(join(lock, "pid")));const waiter = start("true", lockEnv("lane-swift-test"));await until("the waiter files its marker", () => listed().length === 1); expect(listed()).toEqual([String(waiter.child.pid)]); expect(readFileSync(join(markers, String(waiter.child.pid)), "utf8").trim()).toBe("lane-swift-test"); writeFileSync(finish, "");const [h, w] = awaitPromise.all([holder.done, waiter.done]); expect(h.status).toBe(0); expect(w.status).toBe(0); expect(w.stderr).toContain("acquired by 'lane-swift-test'"); expect(w.stderr).not.toContain("claimed as"); expect(listed()).toEqual([]); }, 60_000);});// A waiter the holder left out of its RAM sum takes no slot while that holder// runs. The policy writes `<slot>/excluded/<waiter pid>` (cases above); here the// holder's command writes it by hand, as no policy runs on this host.describe("with-build-lock.sh — a waiter left out of the holder's RAM never takes the other slot", () => {const TWO_SLOTS = "34359738368";const hold = (file: string) => `until [ -f ${file} ]; do sleep 0.1; done`;asyncfunction scene(memory: string) {const lock = lockEnv("holder").BUILD_LOCK_DIR!;const name = join(scratch, "name"), finish = join(scratch, "finish");const markers = `${lock}.local-waiting`;const listed = () => (existsSync(markers) ? readdirSync(markers) : []);// The holder names the pid written to `name` as left out, then runs until `finish`.const holder = start(`${hold(name)}; mkdir -p "${lock}/excluded"; touch "${lock}/excluded/$(cat ${name})"; touch ${name}.done; ${hold(finish)}`, { ...lockEnv("holder"), BUILD_LOCK_MEMORY_BYTES: memory }, );await until("the holder has slot 1", () => existsSync(join(lock, "pid")));const name_ = (pid: number | undefined) => { writeFileSync(`${name}.tmp`, String(pid)); renameSync(`${name}.tmp`, name); };return { lock, name, nameWaiter: name_, finish, listed, holder }; }// RULE: On a two-slot Mac a waiter its holder named as left out stays waiting when the other slot frees, a third job takes that slot, and the waiter runs once the holder ends (lock-slot, 9 Nov 2026). it("keeps the named waiter out of slot 2 and lets a third job in", async () => {const { lock, name, nameWaiter, finish, listed, holder } = await scene(TWO_SLOTS);const xFinish = join(scratch, "x-finish");const x = start(hold(xFinish), { ...lockEnv("other"), BUILD_LOCK_MEMORY_BYTES: TWO_SLOTS });await until("another job has slot 2", () => existsSync(join(`${lock}.slot-2`, "pid")));const waiter = start("true", { ...lockEnv("waiter"), BUILD_LOCK_MEMORY_BYTES: TWO_SLOTS });await until("the waiter files its marker", () => listed().includes(String(waiter.child.pid))); nameWaiter(waiter.child.pid);await until("the holder names the waiter", () => existsSync(`${name}.done`)); writeFileSync(xFinish, ""); expect((await x.done).status).toBe(0);// Three of the waiter's one-second polls with slot 2 free: it must still wait.awaitnewPromise((r) => setTimeout(r, 3500)); expect(waiter.child.exitCode).toBeNull(); expect(listed()).toContain(String(waiter.child.pid));const third = start("true", { ...lockEnv("third"), BUILD_LOCK_MEMORY_BYTES: TWO_SLOTS });const t = await third.done; expect(t.status).toBe(0); expect(t.stderr).toContain("acquired by 'third'"); expect(waiter.child.exitCode).toBeNull(); writeFileSync(finish, "");const [h, w] = awaitPromise.all([holder.done, waiter.done]); expect(h.status).toBe(0); expect(w.status).toBe(0); expect(w.stderr).toContain("acquired by 'waiter'"); }, 90_000);// RULE: On a one-slot Mac a named waiter waits for the holder and takes the lock when it ends, as it always did (lock-slot, 9 Nov 2026: the one-slot Macs unchanged). it("leaves a one-slot Mac's waiter as it was", async () => {const { name, nameWaiter, finish, listed, holder } = await scene("17179869184");const waiter = start("true", lockEnv("waiter"));await until("the waiter files its marker", () => listed().includes(String(waiter.child.pid))); nameWaiter(waiter.child.pid);await until("the holder names the waiter", () => existsSync(`${name}.done`)); expect(waiter.child.exitCode).toBeNull(); writeFileSync(finish, "");const [h, w] = awaitPromise.all([holder.done, waiter.done]); expect(h.status).toBe(0); expect(w.status).toBe(0); expect(w.stderr).toContain("acquired by 'waiter'"); expect(listed()).toEqual([]); }, 60_000);});