Cotton code
165 lines · 11.4 KB · TypeScriptRaw
import { execFileSync } from "node:child_process";import { resolve } from "node:path";import { expect, it } from "vitest";// A CUT GOES FIRST (architect, 14 Oct 2026 23:25 IST): Mac 0.29.57's cut sat in// RAM admission on one Mac behind two lane builds until the coordinator asked the// lanes by hand to hold. The owner's install is the gate, so a cut's build// (BUILD_LOCK_CLASS=release) never waits on a lane; lanes queue behind it, and a// lane build already running finishes. The arithmetic is the reservation ledger// in 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\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    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}))\n    return home,p.parent/'build-reservations.json'\ndef lane(pid,ram=6*G):return {'pid':pid,'need':10,'kind':'swift','ram':ram,'class':'lane','started':time.time()}\n${body}`,    ],    { encoding: "utf8" },  );}/// RULE: With two lane builds reserved and a cut arriving, the cut is admitted first — it counts no lane's reservation, while a lane counts the cut's claim and every admitted build — because the owner's install is the gate and a cut never waits on a lane (architect, 14 Oct 2026 23:25 IST, after Mac 0.29.57's cut waited behind two lanes on one Mac).it("admits an arriving cut ahead of two reserved lane builds", () => {  expect(    python(`with tempfile.TemporaryDirectory() as folder:    home,ledger=setup(folder);m.row_gone=lambda row:None    lanes=[lane(101),lane(102)]    # 8 GiB available: a lane counting the two reservations is far under the floor.    ok,_,_=m.admission(lanes,'lane',6*G,8*G,home,total=64*G);assert not ok,'a third lane fits only by ignoring reservations'    ok,promised,_=m.admission(lanes,'cut',6*G,8*G,home,total=64*G);assert ok and promised==0,(ok,promised)    # A cut waiting (behind nothing) holds the queue: a lane with plenty of RAM is still deferred.    claim={'pid':103,'need':10,'kind':'swift','ram':6*G,'class':'cut','waiting':True,'started':time.time()}    ok,_,behind=m.admission(lanes+[claim],'lane',2*G,500*G,home,total=64*G);assert not ok and behind is claim    ok,_,_=m.admission(lanes+[claim],'cut',6*G,8*G,home,claim=claim,total=64*G);assert ok    # Through the ledger: the cut is admitted at once beside the two lanes, no wait.    ledger.write_text(json.dumps(lanes));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:8*G,0.01,total=64*G,cls='cut',label='prod-cut-abc'):            rows=json.loads(ledger.read_text());assert [r['class'] for r in rows]==['lane','lane','cut'],rows            ok,promised,_=m.admission(rows,'lane',6*G,26*G,home,total=64*G)            assert not ok and promised==18*G,'a later lane counts the cut it would push under its need'    assert 'no wait' in err.getvalue(),err.getvalue()    print('cut first')`),  ).toContain("cut first");});/// RULE: A lane build arriving while a cut waits is deferred with a line naming the cut it waits for, so a log reader sees why it is queued (architect, 14 Oct 2026 23:25 IST: lanes queue behind a cut, a cut never waits on a lane).it("defers a lane arriving while a cut waits and names the cut", () => {  expect(    python(`with tempfile.TemporaryDirectory() as folder:    home,ledger=setup(folder);m.row_gone=lambda row:None    running={'pid':201,'need':10,'kind':'swift','ram':6*G,'class':'cut','label':'prod-cut-abc','started':time.time()}    ledger.write_text(json.dumps([running]))    waits=[];original_sleep=m.time.sleep;err=io.StringIO()    def sleep(seconds):        waits.append(seconds)        rows=json.loads(ledger.read_text())        assert [r for r in rows if r.get('waiting') and r.get('label')=='phone-archive-real'],'a waiting cut files its claim'        if len(waits)==2:raise KeyboardInterrupt    m.time.sleep=sleep    try:        with contextlib.redirect_stderr(err):            # A second cut, short of RAM beside the first cut, waits and files a claim.            with m.build_reservation(home,home,10,'swift',lambda p:SimpleNamespace(free=100*m.GIB),None,[],lambda:7*G,0.01,total=64*G,cls='cut',label='phone-archive-real'):raise AssertionError('two cuts over RAM at once')    except KeyboardInterrupt:pass    finally:m.time.sleep=original_sleep    assert 'WAITING for RAM behind cut prod-cut-abc' in err.getvalue(),err.getvalue()    assert json.loads(ledger.read_text())==[running],'a cut that stops waiting withdraws its claim'    claim={'pid':202,'need':10,'kind':'swift','ram':6*G,'class':'cut','label':'phone-archive-real','waiting':True,'started':time.time()}    ledger.write_text(json.dumps([running,claim]))    waits.clear();err=io.StringIO()    def lane_sleep(seconds):        waits.append(seconds)        if len(waits)==3:raise KeyboardInterrupt    m.time.sleep=lane_sleep    try:        with contextlib.redirect_stderr(err):            with m.build_reservation(home,home,10,'rust',lambda p:SimpleNamespace(free=100*m.GIB),None,[],lambda:500*G,0.01,wait_limit=60,total=64*G):raise AssertionError('lane admitted ahead of a waiting cut')    except KeyboardInterrupt:pass    finally:m.time.sleep=original_sleep    assert 'build admission: WAITING behind cut phone-archive-real (pid 202)' in err.getvalue(),err.getvalue()    assert json.loads(ledger.read_text())==[running,claim]    print('lane deferred behind cut')`),  ).toContain("lane deferred behind cut");});/// RULE: The admission line a cut prints says "cut" so a log reader sees the class, and the policy never kills a running lane build to make room for a cut — a lane already running finishes (architect, 14 Oct 2026 23:25 IST).it("prints the cut class and leaves running lane builds alive", () => {  expect(    python(`with tempfile.TemporaryDirectory() as folder:    home,ledger=setup(folder)    lanes=[subprocess.Popen(['/bin/sleep','30']) for _ in range(2)]    try:        ledger.write_text(json.dumps([lane(proc.pid) for proc in lanes]))        os.environ['BUILD_LOCK_CLASS']='release';os.environ['BUILD_LOCK_LABEL']='prod-cut-abc'        err=io.StringIO()        with contextlib.redirect_stderr(err):            # 1 GiB available: the RAM is the lanes', and the cut still runs.            code=m.run_build(['/usr/bin/true'],home,home,need=10,usage=lambda p:SimpleNamespace(free=100*m.GIB),memory=lambda:1*G,interval=0.01,total=64*G)        assert code==0        assert 'build admission: cut swift' in err.getvalue(),err.getvalue()        assert all(proc.poll() is None for proc in lanes),'a running lane build was killed'        assert [r['pid'] for r in json.loads(ledger.read_text())]==[proc.pid for proc in lanes]    finally:        for proc in lanes:proc.kill();proc.wait()    print('cut said; lanes alive')`),  ).toContain("cut said; lanes alive");});/// RULE: A CUT WAITS WHILE ITS HOLDER LIVES (architect, 17 Oct 2026 07:20 IST). Mac cuts 145, 146 and 147 were each refused at the ten-minute cap behind a phone archive that was still running. A cut's RAM admission with a live holder waits past ten minutes and does not refuse — the line names the holder's pid and what it is — and gives up only when the holder is dead or has outlived the ceiling it declared; a lane's admission keeps the cap.it("the admission with a live holder waits past ten minutes and does not refuse", () => {  expect(    python(`with tempfile.TemporaryDirectory() as folder:    home,ledger=setup(folder);m.row_gone=lambda row:None    clock=[1000.0]    class Clock:        # The policy's clock, fast-forwarded by the test; everything else is the real module.        def __getattr__(self,name):return getattr(original,name)        def time(self):return clock[0]        def sleep(self,seconds):clock[0]+=seconds    original=m.time;Clock=Clock();m.time=Clock    m.read_floor=lambda path,policy:100  # the floor reading is sampled on the real clock; this test's clock runs an hour ahead    try:        # The wait itself: a cut behind a live holder is not refused after the limit; a lane is.        w=m.Wait(600,clock=Clock.time);err=io.StringIO()        with contextlib.redirect_stderr(err):            for _ in range(70):                clock[0]+=60                w.tick('for RAM: held by cut phone-archive-real (pid 4242)',while_holder_lives=True)        assert 'a cut waits while its holder runs' in err.getvalue() and 'TIMEOUT' not in err.getvalue(),err.getvalue()        assert err.getvalue().count('pid 4242')>=60,'the holder is named every minute'        lane=m.Wait(600,clock=Clock.time)        try:            for _ in range(11):                clock[0]+=60;lane.tick('for RAM: held by swift build pid 4242')        except m.HeldTooLong as error:assert 'TIMEOUT after 1' in str(error)        else:raise AssertionError('a lane waited past its cap')        # Through the ledger: a LIVE holder (this very process) has the RAM; the cut polls for 61 minutes and is still waiting.        holder={'pid':os.getpid(),'need':10,'kind':'swift','ram':6*G,'class':'cut','label':'phone-archive-real','started':clock[0]}        ledger.write_text(json.dumps([holder]))        polls=[]        def sleep(seconds):            polls.append(seconds);clock[0]+=60            if len(polls)==61:raise KeyboardInterrupt        Clock.__class__.sleep=lambda self,seconds:sleep(seconds);err=io.StringIO()        try:            with contextlib.redirect_stderr(err):                with m.build_reservation(home,home,10,'swift',lambda p:SimpleNamespace(free=100*m.GIB),None,[],lambda:1*G,0.01,total=64*G,cls='cut',label='prod-cut-abc'):raise AssertionError('admitted with no RAM')        except KeyboardInterrupt:pass        assert len(polls)==61 and 'TIMEOUT' not in err.getvalue(),err.getvalue()        assert 'phone-archive-real (pid %d)'%os.getpid() in err.getvalue() and 'waits while its holder runs' in err.getvalue(),err.getvalue()        # The holder outlived the ceiling it declared: the cut now gives up (exit 75's HeldTooLong).        holder['limit']=1800;holder['started']=clock[0]-3600;ledger.write_text(json.dumps([holder]))        polls.clear();Clock.__class__.sleep=lambda self,s:clock.__setitem__(0,clock[0]+60)        try:            with contextlib.redirect_stderr(io.StringIO()):                with m.build_reservation(home,home,10,'swift',lambda p:SimpleNamespace(free=100*m.GIB),None,[],lambda:1*G,0.01,total=64*G,cls='cut',label='prod-cut-abc'):raise AssertionError('admitted with no RAM')        except m.HeldTooLong:pass        else:raise AssertionError('a cut waited on a holder past its own ceiling')        # A dead holder's row goes at the next read (build-admission-dead-reservation.test.ts), and a cut alone is admitted on the policy's own timeout.        print('cut waits while its holder lives')    finally:m.time=original`),  ).toContain("cut waits while its holder lives");});