import { execFileSync } from "node:child_process"; import { resolve } from "node:path"; import { expect, it } from "vitest"; // Guards for the walk's disk need and the simulator accounting in // scripts/lib/mac_disk_policy.py (7 Nov 2026). const modulePath = resolve("scripts/lib/mac_disk_policy.py"); function python(body: string) { const isolatedBody = body.split("\n").map((line) => ` ${line}`).join("\n"); return execFileSync("python3", ["-c", `import importlib.util,tempfile,json,time,os,sys,io,contextlib,subprocess\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)\nwith tempfile.TemporaryDirectory() as policy_tmp:\n os.environ['TMPDIR']=policy_tmp\n${isolatedBody}`], { encoding: "utf8" }); } const UDID = (n: number) => `0000000${n}-AAAA-BBBB-CCCC-DDDDDDDDDDDD`; // RULE: A Mac boots at most one simulator on 16 GB and two on 24 GB and up. it("caps booted simulators by the Mac's RAM", () => { expect(python(`assert m.simulator_cap(16*m.GIB)==1 and m.simulator_cap(24*m.GIB)==2 and m.simulator_cap(64*m.GIB)==2 print('capped')`)).toContain("capped"); }); // RULE: A walk's disk need is the 90th percentile of this Mac's measured Swift growth, else the measured 8 GB; never 1 byte. it("sizes a walk's disk need from measured swift growth", () => { expect(python(`home=Path(policy_tmp) assert m.is_walk({'BUILD_LOCK_CLASS':'walk'}) and not m.is_walk({'BUILD_LOCK_CLASS':'local'}) need,said=m.walk_disk_need(home) assert need==m.WALK_DISK_NEED==8_000_000_000 and 'measured on one Mac' in said, said for n in range(1,21):m.record_disk_peak(home,'swift',n*1_000_000_000) need,said=m.walk_disk_need(home) assert need==18_000_000_000 and "this Mac's swift growth" in said, (need,said) print('walk need measured')`)).toContain("walk need measured"); }); // RULE: A walk short of disk while other builds hold reservations waits for them instead of being admitted at 1 byte and killed at the floor; once a holder finishes it is admitted with its whole need reserved. it("a walk waits for disk behind admitted builds, then reserves its whole need", () => { expect(python(`home=Path(policy_tmp);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' holder=subprocess.Popen(['sleep','30']) ledger.write_text(json.dumps([{'pid':holder.pid,'need':500,'kind':'swift','started':time.time()+5,'volume':home.stat().st_dev}])) polls=[0];original_sleep=m.time.sleep def sleep(seconds): polls[0]+=1 if polls[0]==3: holder.kill();holder.wait() m.time.sleep=sleep err=io.StringIO() try: with contextlib.redirect_stderr(err): with m.build_reservation(home,home,1000,'swift',lambda p:SimpleNamespace(free=1500),lambda p:False,[],lambda:100*m.GIB,0.01,total=64*m.GIB,disk_wait=True): rows=json.loads(ledger.read_text()) assert [r['need'] for r in rows]==[1000], rows finally:m.time.sleep=original_sleep assert polls[0]>=3 and 'WAITING for disk: walk swift needs 1000 bytes' in err.getvalue(), err.getvalue() # Without other holders a short walk is refused at once: nothing will free the room. try: with contextlib.redirect_stderr(io.StringIO()): with m.build_reservation(home,home,10_000,'swift',lambda p:SimpleNamespace(free=1500),lambda p:False,[],lambda:100*m.GIB,0.01,total=64*m.GIB,disk_wait=True):pass except RuntimeError as error:assert 'REFUSING TO START' in str(error) else:raise AssertionError('a lone short walk was admitted') print('walk waited for disk')`)).toContain("walk waited for disk"); }); // RULE: run_build gives a walk (BUILD_LOCK_CLASS=walk) that names no need the walk disk need, and says where the figure comes from. it("run_build reserves the walk need for a walk class build", () => { expect(python(`home=Path(policy_tmp);p=home/'.cottondb/disk-policy.json';p.parent.mkdir();p.write_text(json.dumps({'keepFreeBytes':100,'sampledAt':time.time(),'volumeId':home.stat().st_dev})) os.environ['BUILD_LOCK_CLASS']='walk' script="import json,pathlib,sys;rows=json.loads(pathlib.Path(sys.argv[1]).read_text());assert [r['need'] for r in rows]==[8_000_000_000],rows" err=io.StringIO() with contextlib.redirect_stderr(err): code=m.run_build([sys.executable,'-c',script,str(p.parent/'build-reservations.json')],home,home,usage=lambda p:SimpleNamespace(free=100*m.GIB),memory=lambda:100*m.GIB,interval=0.01,total=64*m.GIB) assert code==0 and 'walk disk need: 8000000000 bytes' in err.getvalue(), err.getvalue() print('walk reserved')`)).toContain("walk reserved"); }); // RULE: run_build gives a CI swift build (BUILD_LOCK_CLASS=ci) that names no need the measured swift growth, never 1 byte (verify-main #10161 was killed at the floor in its tests). it("run_build reserves the swift growth for a CI swift build", () => { expect(python(`home=Path(policy_tmp);p=home/'.cottondb/disk-policy.json';p.parent.mkdir();p.write_text(json.dumps({'keepFreeBytes':100,'sampledAt':time.time(),'volumeId':home.stat().st_dev})) os.environ['BUILD_LOCK_CLASS']='ci' assert m.is_ci() and not m.is_walk() script="import json,pathlib,sys;rows=json.loads(pathlib.Path(sys.argv[1]).read_text());assert [r['need'] for r in rows]==[int(sys.argv[2])],rows" ledger=str(p.parent/'build-reservations.json') err=io.StringIO() with contextlib.redirect_stderr(err): code=m.run_build([sys.executable,'-c',script,ledger,'8000000000'],home,home,usage=lambda p:SimpleNamespace(free=100*m.GIB),memory=lambda:100*m.GIB,interval=0.01,total=64*m.GIB,kind='swift') assert code==0 and 'ci disk need: 8000000000 bytes' in err.getvalue(), err.getvalue() # A CI rust build keeps the need it names. with contextlib.redirect_stderr(io.StringIO()): code=m.run_build([sys.executable,'-c',script,ledger,'1'],home,home,usage=lambda p:SimpleNamespace(free=100*m.GIB),memory=lambda:100*m.GIB,interval=0.01,total=64*m.GIB,kind='rust') assert code==0 print('ci reserved')`)).toContain("ci reserved"); }); // RULE: The reclaim frees the shared cargo target's stale test binaries first, oldest first and only what is short — never a cargo input, a fresh binary, or anything while a build holds the target's lock. it("reclaims the shared target's stale test binaries first, under its lock", () => { expect(python(`home=Path(policy_tmp);p=home/'.cottondb/disk-policy.json';p.parent.mkdir() shared=home/'.cache/cottondb/cargo-target/shared' old=time.time()-4*3600 def put(rel,mode=0o755,at=old,size=4096): f=shared/rel;f.parent.mkdir(parents=True,exist_ok=True);f.write_bytes(b'x'*size);f.chmod(mode);os.utime(f,(at,at));return f oldest=put('debug/deps/core_tests-aaaa',at=old-600) older=put('aarch64-apple-ios-sim/debug/deps/sync_tests-bbbb') rlib=put('debug/deps/libcore-cccc.rlib');dylib=put('debug/deps/libcotton-dddd.dylib') fresh=put('debug/deps/core_tests-eeee',at=time.time()) data=put('debug/deps/notes-ffff',mode=0o644) script=put('debug/build/x-1111/build-script-build') names=[e.name for _,_,e in m.stale_target_binaries(home)] assert names==['core_tests-aaaa','sync_tests-bbbb'], names vol=home.stat().st_dev # Held by a build: nothing goes, and it says so. (shared.parent/'shared.lock.d').mkdir() err=io.StringIO() with contextlib.redirect_stderr(err):assert m.evict_target_binaries(home,1,vol)==0 assert oldest.exists() and 'a build holds shared.lock.d' in err.getvalue(), err.getvalue() (shared.parent/'shared.lock.d').rmdir() # Free: only what is short, oldest first; the lock is given back. with contextlib.redirect_stderr(io.StringIO()):freed=m.evict_target_binaries(home,1,vol) assert freed>0 and not oldest.exists() and older.exists(), freed assert not (shared.parent/'shared.lock.d').exists() # reclaim takes them before anything else. p.write_text(json.dumps({'keepFreeBytes':100,'sampledAt':time.time(),'volumeId':vol})) free=[1000] def usage(path):return SimpleNamespace(free=free[0]+(0 if older.exists() else 10_000)) err=io.StringIO() with contextlib.redirect_stderr(err):left=m.reclaim(home,p,home,500,1000,usage=usage,idle=lambda e:True) assert not older.exists() and left>=1500, (left,err.getvalue()) assert all(f.exists() for f in (rlib,dylib,fresh,data,script)) print('stale binaries reclaimed')`)).toContain("stale binaries reclaimed"); }); // RULE: A walk takes a standing simulator under a mkdir lock and boots it under the cap: an idle standing simulator is shut down (never erased) to make room; a held one, or anyone else's booted one, is waited on and never touched. it("takes a free standing simulator under the cap, waiting on held ones", () => { expect(python(`home=Path(policy_tmp) devices=[{'udid':'${UDID(1)}','name':'standing-1','state':'Shutdown'}, {'udid':'${UDID(2)}','name':'standing-2','state':'Booted'}, {'udid':'${UDID(3)}','name':'iPhone 16','state':'Shutdown'}] calls=[] def simctl(*args): calls.append(args) for d in devices: if d['udid']==args[1]:d['state']={'boot':'Booted','shutdown':'Shutdown'}[args[0]] with contextlib.redirect_stderr(io.StringIO()) as err: assert m.take_simulator(['${UDID(1)}'],os.getpid(),home,total=16*m.GIB,devices=lambda:devices,simctl=simctl)=='${UDID(1)}' assert calls==[('shutdown','${UDID(2)}'),('boot','${UDID(1)}')], calls assert m.simulator_holder(home,'${UDID(1)}')['pid']==os.getpid() assert (m.simulator_lock(home,'${UDID(1)}')).is_dir() and 'shut down idle standing-2' in err.getvalue() # Another live walk waits on the held one and gives up at the limit; nothing is booted or shut down. other=subprocess.Popen(['sleep','30']) calls.clear() try: with contextlib.redirect_stderr(io.StringIO()): m.take_simulator(['${UDID(1)}'],other.pid,home,total=16*m.GIB,devices=lambda:devices,simctl=simctl,wait_limit=0.05,interval=0.01) except m.HeldTooLong as error:assert 'no simulator: standing-1 held by walk pid' in str(error), str(error) else:raise AssertionError('two walks shared one standing simulator') assert calls==[], calls # On a 24 GB Mac the second slot is free: it takes standing-2 beside standing-1. with contextlib.redirect_stderr(io.StringIO()): assert m.take_simulator(['${UDID(1)}','${UDID(2)}'],other.pid,home,total=24*m.GIB,devices=lambda:devices,simctl=simctl)=='${UDID(2)}' assert calls==[('boot','${UDID(2)}')], calls # Released, it is free again; a release by someone else is refused. try:m.release_simulator(home,'${UDID(1)}',other.pid) except RuntimeError:pass else:raise AssertionError('released another walk lock') assert m.release_simulator(home,'${UDID(1)}',os.getpid())==0 and m.simulator_holder(home,'${UDID(1)}') is None other.kill();other.wait() print('taken under the cap')`)).toContain("taken under the cap"); }); // RULE: Somebody's own booted simulator is never shut down to make room: at the cap the walk waits. it("waits on a simulator it did not make", () => { expect(python(`home=Path(policy_tmp) devices=[{'udid':'${UDID(1)}','name':'standing-1','state':'Shutdown'},{'udid':'${UDID(3)}','name':'iPhone 16','state':'Booted'}] calls=[] try: with contextlib.redirect_stderr(io.StringIO()): m.take_simulator(['${UDID(1)}'],os.getpid(),home,total=16*m.GIB,devices=lambda:devices,simctl=lambda *a:calls.append(a),wait_limit=0.05,interval=0.01) except m.HeldTooLong as error:assert "no simulator: 1 booted of this Mac's cap of 1" in str(error), str(error) else:raise AssertionError('booted past the cap') assert calls==[] and m.simulator_holder(home,'${UDID(1)}') is None print('waited')`)).toContain("waited"); }); // RULE: A dead walk's lock holds nothing: its standing simulator is idle again and the next walk takes it over. it("takes over a dead holder's lock", () => { expect(python(`home=Path(policy_tmp) dead=subprocess.Popen(['/usr/bin/true']);dead.wait() lock=m.simulator_lock(home,'${UDID(4)}');lock.mkdir(parents=True) (lock/'holder').write_text(json.dumps({'pid':dead.pid,'started':time.time()})) device={'udid':'${UDID(4)}','name':'standing-1','state':'Booted'} assert m.simulator_holder(home,'${UDID(4)}') is None and m.idle_standing(home,[device])==[device] with contextlib.redirect_stderr(io.StringIO()): assert m.take_simulator(['${UDID(4)}'],os.getpid(),home,total=16*m.GIB,devices=lambda:[device],simctl=lambda *a:None)=='${UDID(4)}' assert m.simulator_holder(home,'${UDID(4)}')['pid']==os.getpid() print('dead lock taken')`)).toContain("dead lock taken"); });