import { execFileSync } from"node:child_process";import { resolve } from"node:path";import { expect, it } from"vitest";function python(body: string) {return execFileSync("python3", ["-c", `import importlib.util,tempfile,json,time,os,subprocess,sys\nfrom pathlib import Path\nfrom types import SimpleNamespace\ns=importlib.util.spec_from_file_location('policy',${JSON.stringify(resolve('scripts/lib/mac_disk_policy.py'))});m=importlib.util.module_from_spec(s);s.loader.exec_module(m)\nfor key in ['COTTON_DISK_MONITOR_PID','TINMEN_BUILD_LOCK_HELD','TINMEN_BUILD_LOCK_DIR','BUILD_LOCK_CLASS','COTTON_CUT_LEASE']:os.environ.pop(key,None)\n${body}`], {encoding: "utf8"});}/// RULE: An admitted build-lock holder keeps its disk admission across changed or missing readings and nested compiler calls; a non-holder faces the live floor, so a setting change cannot waste a running cut.it("keeps the holder admitted through a floor rise and refuses another lane", () => { expect(python(`with tempfile.TemporaryDirectory() as folder: home=Path(folder);root=home/'.cottondb';root.mkdir();policy=root/'disk-policy.json' lock=home/'build.lock';lock.mkdir() for key,value in [('pid',str(os.getpid())),('class','release')]: (lock/key).write_text(value) os.environ.update(TINMEN_BUILD_LOCK_HELD=str(os.getpid()),TINMEN_BUILD_LOCK_DIR=str(lock),BUILD_LOCK_CLASS='release') def publish(floor):policy.write_text(json.dumps({'keepFreeBytes':floor,'sampledAt':time.time(),'volumeId':home.stat().st_dev})) publish(100) # A lane's promise cannot add another floor to the cut's fixed budget. m.row_gone=lambda row:None (root/'build-reservations.json').write_text(json.dumps([{'pid':424242,'need':200*m.GIB,'kind':'rust','ram':2*m.GIB,'class':'lane','started':time.time(),'volume':home.stat().st_dev}])) script=home/'child.py' script.write_text("import importlib.util,time;from pathlib import Path;from types import SimpleNamespace;s=importlib.util.spec_from_file_location('policy',"+repr(m.__file__)+");m=importlib.util.module_from_spec(s);s.loader.exec_module(m);home=Path("+repr(str(home))+");assert m.run_build(['/usr/bin/true'],home,home,usage=lambda p:SimpleNamespace(free=0),memory=lambda:0)==0;time.sleep(0.12)") samples=[0] def usage(path): samples[0]+=1 if samples[0]>2:publish(200*m.GIB) return SimpleNamespace(free=100*m.GIB) assert m.run_build([sys.executable,str(script)],home,home,usage=usage,memory=lambda:100*m.GIB,interval=0.01,total=64*m.GIB)==0 row=json.loads((lock/'disk-admission.json').read_text()) assert row['disk_free_bytes']==100*m.GIB and row['keep_free_bytes']==100,row assert row['need']==m.CUT_DISK_NEED # A later compiler under the same lease must not re-admit on the new floor. assert m.run_build(['/usr/bin/true'],home,home,usage=usage,memory=lambda:0,total=64*m.GIB)==0 with m.build_reservation(home,home,1,'rust',lambda p:SimpleNamespace(free=0),None,[],lambda:0,0.01) as floor: assert floor==100,'reservation admission rechecked an admitted holder' assert m.admit(home,policy,home,usage=lambda p:SimpleNamespace(free=0))==100 policy.unlink() # admission also survives an app restart while it builds assert m.run_build(['/usr/bin/true'],home,home,usage=usage,memory=lambda:0,total=64*m.GIB)==0 assert json.loads((lock/'disk-admission.json').read_text())==row,'later compiler calls replaced the admission reading' publish(200*m.GIB) os.environ.pop('TINMEN_BUILD_LOCK_HELD');os.environ.pop('TINMEN_BUILD_LOCK_DIR');os.environ.pop('BUILD_LOCK_CLASS') try:m.run_build(['/usr/bin/true'],home,home,usage=usage,memory=lambda:100*m.GIB,interval=0.01,total=64*m.GIB) except RuntimeError as error:assert 'REFUSING TO START' in str(error) else:raise AssertionError('a non-holder ignored the new floor') print('holder admitted; lane refused')`)).toContain("holder admitted; lane refused");});/// RULE: Disk admission uses the recorded 90th percentile after twenty peaks, otherwise its class need; a cut's need is that measured peak plus its kept output and a quarter again (the 159 cut's measured figure before twenty peaks, never a fixed 30 GB margin, which refused the 67 GB-free mini on 20 Oct 2026); refusal happens before the command starts and reports the figures.it("uses measured disk need and refuses before starting", () => { expect(python(`with tempfile.TemporaryDirectory() as folder: home=Path(folder);root=home/'.cottondb';root.mkdir();policy=root/'disk-policy.json' policy.write_text(json.dumps({'keepFreeBytes':100,'sampledAt':time.time(),'volumeId':home.stat().st_dev})) assert m.disk_need('swift',home)==m.DISK_NEED['swift'] for peak in range(1,20):m.record_disk_peak(home,'swift',peak) assert m.disk_need('swift',home)==m.DISK_NEED['swift'] m.record_disk_peak(home,'swift',20) assert m.disk_need('swift',home)==18 need=(18+m.CUT_KEPT_OUTPUT)*5//4 assert m.cut_disk_need('swift',home)[0]==need marker=home/'started' try:m.run_build(['touch',str(marker)],home,home,cls='cut',kind='swift',usage=lambda p:SimpleNamespace(free=100+need-1),memory=lambda:100*m.GIB,total=64*m.GIB) except RuntimeError as error: assert str(need) in str(error) and 'keeps 100' in str(error),str(error) else:raise AssertionError('cut admitted below its measured need') assert not marker.exists() print('measured need')`)).toContain("measured need");});/// RULE: A cut keeps one disk admission across compilation and signing under successive build locks; only its live cut-session leader may reuse it, so a restarted cut and a lane still face fresh admission.it("keeps admission when the same cut takes its next build lock", () => { expect(python(`with tempfile.TemporaryDirectory() as folder: home=Path(folder);root=home/'.cottondb';root.mkdir();policy=root/'disk-policy.json' lock=home/'build.lock';lock.mkdir();cut=home/'cut';cut.mkdir() for key,value in [('pid',str(os.getpid())),('class','release')]: (lock/key).write_text(value) leader=m.lease_record('synthetic cut');(cut/'.stages.lock').write_text(json.dumps(leader)) m.is_cut_leader=lambda pid:pid==os.getpid() os.environ.update(TINMEN_BUILD_LOCK_HELD=str(os.getpid()),TINMEN_BUILD_LOCK_DIR=str(lock),COTTON_CUT_LEASE=str(cut),BUILD_LOCK_CLASS='release') def publish(floor):policy.write_text(json.dumps({'keepFreeBytes':floor,'sampledAt':time.time(),'volumeId':home.stat().st_dev})) publish(100) assert m.run_build(['/usr/bin/true'],home,home,usage=lambda p:SimpleNamespace(free=100*m.GIB),memory=lambda:100*m.GIB,total=64*m.GIB)==0 (lock/'disk-admission.json').unlink() # compilation releases the lock; signing acquires another publish(200*m.GIB) assert m.run_build(['/usr/bin/true'],home,home,usage=lambda p:SimpleNamespace(free=0),memory=lambda:0,total=64*m.GIB)==0 # A lane cannot borrow the cut-session cache merely by inheriting its path. for key in ['TINMEN_BUILD_LOCK_HELD','TINMEN_BUILD_LOCK_DIR','BUILD_LOCK_CLASS']:os.environ.pop(key,None) try:m.run_build(['/usr/bin/true'],home,home,usage=lambda p:SimpleNamespace(free=100*m.GIB),memory=lambda:100*m.GIB,total=64*m.GIB) except RuntimeError as error:assert 'REFUSING TO START' in str(error) else:raise AssertionError('lane borrowed a cut admission') os.environ.update(TINMEN_BUILD_LOCK_HELD=str(os.getpid()),TINMEN_BUILD_LOCK_DIR=str(lock),BUILD_LOCK_CLASS='release') leader['started']-=100 # a different/reused session cannot carry yesterday's admission (cut/'.stages.lock').write_text(json.dumps(leader)) try:m.run_build(['/usr/bin/true'],home,home,usage=lambda p:SimpleNamespace(free=100*m.GIB),memory=lambda:100*m.GIB,total=64*m.GIB) except RuntimeError as error:assert 'REFUSING TO START' in str(error) else:raise AssertionError('restarted cut borrowed an old admission') print('one cut admission across build locks')`)).toContain("one cut admission across build locks");});