import { execFileSync } from "node:child_process"; import { resolve } from "node:path"; import { expect, it } from "vitest"; // A RESERVATION IS A FACT ABOUT A LIVE PROCESS (coordinator, 14 Oct 2026). The // 0.29.57 Mac cut on one Mac was killed and restarted; its Swift build's row in // ~/.cottondb/build-reservations.json outlived the process, and the restarted // cut sat 23 minutes in RAM admission behind it until the ledger was pruned by // hand. The ledger is scripts/lib/mac_disk_policy.py, so these guards need no Mac. const modulePath = resolve("scripts/lib/mac_disk_policy.py"); function python(body: string) { return execFileSync( "python3", [ "-c", `import importlib.util,tempfile,json,time,os,io,contextlib,subprocess,signal,sys\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfor 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)\ns=importlib.util.spec_from_file_location('policy',${JSON.stringify(modulePath)})\nm=importlib.util.module_from_spec(s);s.loader.exec_module(m)\nG=m.GIB\ndef setup(folder):\n os.environ['HOME']=folder;home=Path.home();p=home/'.cottondb/disk-policy.json';p.parent.mkdir();p.write_text(json.dumps({'keepFreeBytes':100,'sampledAt':time.time(),'volumeId':home.stat().st_dev}))\n return home,p.parent/'build-reservations.json'\ndef cut(pid,started=None):return {'pid':pid,'need':10,'kind':'swift','ram':12*G,'started':time.time() if started is None else started}\n${body}`, ], { encoding: "utf8", timeout: 60_000 }, ); } /// RULE: A reservations file holding a dead pid's row admits an arriving cut at once and the row is gone after the read — a dead pid, a zombie, or a pid reused by a process that started after the row was written holds no one, and the drop is said once — because a killed cut's leftover row held its restart 23 minutes on one Mac (coordinator, 14 Oct 2026). it("admits an arriving cut at once past a gone, a zombie and a reused pid's row", () => { expect( python(`with tempfile.TemporaryDirectory() as folder: home,ledger=setup(folder) dead=subprocess.Popen(['true']);dead.wait() zombie=subprocess.Popen(['true']) while m.process_start(zombie.pid) is not None and not m.process_start(zombie.pid)[1]:time.sleep(0.01) reused=subprocess.Popen(['sleep','30']) try: # Each row would hold a cut out: 12 GiB promised against 16 GiB available. ledger.write_text(json.dumps([cut(dead.pid),cut(zombie.pid),cut(reused.pid,started=time.time()-3600)])) 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:16*G,0.01,total=64*G,cls='cut',label='prod-cut-restart'): rows=json.loads(ledger.read_text()) assert [r['pid'] for r in rows]==[os.getpid()],rows text=err.getvalue() assert 'no wait' in text,text for pid,why in [(dead.pid,'gone'),(zombie.pid,'gone'),(reused.pid,'pid reused')]: assert text.count(f'build admission: dropped a reservation of pid {pid} ({why})')==1,text assert json.loads(ledger.read_text())==[] finally: reused.kill();reused.wait();zombie.wait() print('dead rows hold no one')`), ).toContain("dead rows hold no one"); }); /// RULE: A live row is never dropped by the prune — a running build's reservation stands through every read — because dropping it would admit a build into RAM another build already holds (coordinator, 14 Oct 2026). it("keeps a live build's row through every read", () => { expect( python(`with tempfile.TemporaryDirectory() as folder: home,ledger=setup(folder) live=subprocess.Popen(['sleep','30']) try: time.sleep(0.05) rows=[cut(live.pid),cut(os.getpid())] ledger.write_text(json.dumps(rows));err=io.StringIO() with contextlib.redirect_stderr(err): for _ in range(3): with m.reservation_ledger(home) as read:assert read==rows,read assert json.loads(ledger.read_text())==rows assert 'dropped' not in err.getvalue(),err.getvalue() finally: live.kill();live.wait() print('live rows stand')`), ).toContain("live rows stand"); }); /// RULE: A wrapper killed with TERM — mid-build or while it waits for admission — leaves no reservation row, because the wrapper releases its reservation on every exit path and a killed build must never hold the Mac (coordinator, 14 Oct 2026). it("leaves no reservation row when the wrapper is TERMed mid-build or while waiting", () => { expect( python(`with tempfile.TemporaryDirectory() as folder: home,ledger=setup(folder) def wrapper(memory,cls): script=f'''import importlib.util,sys,os from pathlib import Path from types import SimpleNamespace os.environ.pop('COTTON_DISK_MONITOR_PID',None) os.environ['BUILD_LOCK_CLASS']={'release' if cls=='cut' else 'lane'!r} s=importlib.util.spec_from_file_location('policy',{${JSON.stringify(modulePath)}!r}) m=importlib.util.module_from_spec(s);s.loader.exec_module(m) home=Path.home() sys.exit(m.run_build(['sleep','30'],home,home,10,usage=lambda p:SimpleNamespace(free=100*m.GIB),idle=None,interval=0.05,memory=lambda:{memory},kind='swift',total=64*{G}))''' return subprocess.Popen([sys.executable,'-c',script],stderr=subprocess.PIPE,text=True) def until(test): deadline=time.time()+20 while time.time() { expect(python(`with tempfile.TemporaryDirectory() as folder: home,ledger=setup(folder) import builtins said=[] # The TERM lands as the admission is said: its row taken, the build not yet started. def interrupt(*args,**kwargs): if args and str(args[0]).startswith('build admission: ') and 'RAM available' in str(args[0]): said.append(args[0]) raise SystemExit(143) return builtins.print(*args,**kwargs) m.print=interrupt try: with m.build_reservation(home,home,10,'swift',lambda p:SimpleNamespace(free=100*m.GIB),None,[],lambda:500*G,0.01,total=64*G): raise AssertionError('must exit before starting the build') except SystemExit as error:assert error.code==143 finally:del m.print assert len(said)==1,said assert json.loads(ledger.read_text())==[],ledger.read_text() print('interrupted admission releases its row')`)).toContain("interrupted admission releases its row"); });