1
0

runtime.spec.ts 294 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138
  1. import { execFileSync } from 'node:child_process'
  2. import { existsSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
  3. import { mkdtemp, writeFile } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { basename, dirname, join, relative, resolve } from 'node:path'
  6. import { afterEach, describe, expect, it, vi } from 'vitest'
  7. import { Context } from '@deepseek-ai/cordis'
  8. import { PythonCodeRuntime, hostFrameParseCeiling, readProcessStart, resolvePythonBin } from '../src/index.ts'
  9. import { logTruncationMarker } from '../src/protocol.ts'
  10. import type { Config } from '../src/index.ts'
  11. // Absolute supported interpreter path for shell wrappers. The runtime gives a
  12. // child only TMPDIR, so a bare `python3` inside a wrapper would resolve against
  13. // /bin/sh's default PATH rather than the caller's selected interpreter.
  14. const PYABS = resolvePythonBin('python3') ?? 'python3'
  15. import type { CodeBindingFunction, CodeJsonValue, CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
  16. /**
  17. * Names one `py/` script whose `copyFileSync` must fail, for the partial-staging
  18. * case. A real disk-full or missing-asset failure mid-copy cannot be produced
  19. * from a test, and the leak only shows when `mkdtempSync` has already succeeded.
  20. *
  21. * `stagedDirs` records every staging directory THIS test file creates, so the
  22. * leak assertions check the exact paths instead of a global tmpdir diff: a
  23. * parallel vitest worker running the same prefix could create or remove
  24. * `dsh-code-runtime-python-*` directories inside the sampling window, which a
  25. * readdir diff would misattribute to this test. `boot-write-failure.spec.ts`
  26. * records the same race and solves it with argv-based identity; recording the
  27. * mkdtempSync results is the fs-mock equivalent.
  28. */
  29. const { failNextCopyOf, stagedDirs, tempDirs, tempFiles, splitStdout } = vi.hoisted(() => ({
  30. failNextCopyOf: { value: undefined as string | undefined },
  31. stagedDirs: [] as string[],
  32. // Test-created temp dirs/files, registered by the helpers below and removed
  33. // after each test: a suite run over real python3 subprocesses must not
  34. // permanently accumulate `dsh-*` fixtures in the shared tmpdir (the runtime
  35. // cleans its own per-run staging dir; these are the stubs and wrappers the
  36. // tests themselves build).
  37. tempDirs: [] as string[],
  38. tempFiles: [] as string[],
  39. splitStdout: { value: false },
  40. }))
  41. vi.mock('node:child_process', async (importOriginal) => {
  42. const actual = await importOriginal<typeof import('node:child_process')>()
  43. return {
  44. ...actual,
  45. spawn(...args: Parameters<typeof actual.spawn>) {
  46. const child = actual.spawn(...args)
  47. if (splitStdout.value && child.stdout !== null) {
  48. // The kernel may coalesce writes; this case owns the data-event boundaries.
  49. const emit = child.stdout.emit.bind(child.stdout)
  50. child.stdout.emit = (event: string | symbol, ...values: unknown[]): boolean => {
  51. const chunk = values[0]
  52. if (event !== 'data' || !Buffer.isBuffer(chunk)) return emit(event, ...values)
  53. for (let index = 0; index < chunk.length; index += 1) emit('data', chunk.subarray(index, index + 1))
  54. return true
  55. }
  56. }
  57. return child
  58. },
  59. }
  60. })
  61. vi.mock('node:fs', async (importOriginal) => {
  62. const actual = await importOriginal<typeof import('node:fs')>()
  63. return {
  64. ...actual,
  65. copyFileSync(source: string, destination: string): void {
  66. if (failNextCopyOf.value !== undefined && basename(source) === failNextCopyOf.value) {
  67. failNextCopyOf.value = undefined
  68. throw Object.assign(new Error('simulated ENOSPC on copy'), { code: 'ENOSPC' })
  69. }
  70. actual.copyFileSync(source, destination)
  71. },
  72. mkdtempSync(prefix: string): string {
  73. const dir = actual.mkdtempSync(prefix)
  74. if (basename(prefix).startsWith('dsh-code-runtime-python-')) stagedDirs.push(dir)
  75. return dir
  76. },
  77. }
  78. })
  79. /**
  80. * Integration suite over real python3 subprocesses. The staging-failure cases
  81. * mock `copyFileSync`; the fragment-count case controls stdout data-event boundaries.
  82. * Each test builds a fresh runtime so budgets can be tuned per case.
  83. */
  84. async function setup(config: Config = {}) {
  85. const ctx = new Context()
  86. const fiber = await ctx.plugin(PythonCodeRuntime, config)
  87. const runtime = ctx.codeRuntime as PythonCodeRuntime
  88. return { ctx, fiber, runtime }
  89. }
  90. /** Convenience: one namespace `tools` with the given functions. */
  91. function tools(functions: Record<string, CodeBindingFunction>) {
  92. return [{ global: 'tools', functions }]
  93. }
  94. /** Create a test temp dir registered for afterEach removal. */
  95. async function makeTempDir(prefix: string): Promise<string> {
  96. const dir = await mkdtemp(join(tmpdir(), prefix))
  97. tempDirs.push(dir)
  98. return dir
  99. }
  100. /** Synchronous variant of {@link makeTempDir} for the PATH-stub fixtures. */
  101. function makeTempDirSync(prefix: string): string {
  102. const dir = mkdtempSync(join(tmpdir(), prefix))
  103. tempDirs.push(dir)
  104. return dir
  105. }
  106. // Remove every fixture this file created, so repeated runs do not accumulate
  107. // `dsh-*` directories and wrappers in the shared tmpdir.
  108. afterEach(() => {
  109. splitStdout.value = false
  110. for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
  111. for (const file of tempFiles.splice(0)) rmSync(file, { force: true })
  112. })
  113. describe('PythonCodeRuntime — seam descriptors and misuse', () => {
  114. it('registers the seam descriptors', async () => {
  115. const { runtime } = await setup()
  116. expect(runtime.language).toBe('python')
  117. expect(runtime.isolation).toBe('process')
  118. })
  119. it('rejects non-positive config as seam misuse', async () => {
  120. const ctx = new Context()
  121. await expect(ctx.plugin(PythonCodeRuntime, { cpuSeconds: 0 }))
  122. .rejects.toThrow(/cpuSeconds must be a positive number/)
  123. await expect(ctx.plugin(PythonCodeRuntime, { maxWallMs: -1 }))
  124. .rejects.toThrow(/maxWallMs must be a positive number/)
  125. })
  126. it('rejects a non-integer cpuSeconds at load (setrlimit needs an int)', async () => {
  127. const ctx = new Context()
  128. await expect(ctx.plugin(PythonCodeRuntime, { cpuSeconds: 1.5 }))
  129. .rejects.toThrow(/cpuSeconds must be a positive integer, got 1.5/)
  130. })
  131. it('rejects a non-integer byte budget at load (the child int()-truncates it)', async () => {
  132. // maxLogBytes/maxValueBytes cross to the child, which reads them through
  133. // int(...): a float would floor there while the host meters the fraction, so
  134. // the two sides would enforce different public config. Reject at load.
  135. const ctxLog = new Context()
  136. await expect(ctxLog.plugin(PythonCodeRuntime, { maxLogBytes: 3.5 }))
  137. .rejects.toThrow(/maxLogBytes must be a positive integer/)
  138. const ctxValue = new Context()
  139. await expect(ctxValue.plugin(PythonCodeRuntime, { maxValueBytes: 1024.5 }))
  140. .rejects.toThrow(/maxValueBytes must be a positive integer/)
  141. })
  142. it('rejects finite numeric config that cannot cross as an exact rlimit integer', async () => {
  143. // `Number.isFinite` and `Number.isInteger` both admit values that cannot
  144. // round-trip. `addressSpaceMb: 1e308` overflows to `Infinity` once multiplied
  145. // by 1 MiB, and `encodeJsonPlain` renders that as `null`, so the child gets no
  146. // limit at all; `cpuSeconds: 1e100` clears `Number.isInteger` while sitting
  147. // far past the safe range, so `setrlimit` receives a different number than was
  148. // configured. Both used to end every run in a bootstrap exception instead of
  149. // failing at load, where a self-contained configuration error belongs.
  150. const ctx = new Context()
  151. await expect(ctx.plugin(PythonCodeRuntime, { addressSpaceMb: 1e308 }))
  152. .rejects.toThrow(/addressSpaceMb must be at most \d+ .*exact integer/)
  153. await expect(ctx.plugin(PythonCodeRuntime, { cpuSeconds: 1e100 }))
  154. .rejects.toThrow(/cpuSeconds must be at most \d+ .*exact integers/)
  155. // The boundary values still load: the bound rejects what cannot be encoded,
  156. // not everything large.
  157. const okMb = await ctx.plugin(PythonCodeRuntime, { addressSpaceMb: Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024)) })
  158. await okMb.dispose()
  159. const okCpu = await ctx.plugin(PythonCodeRuntime, { cpuSeconds: Number.MAX_SAFE_INTEGER - 1 })
  160. await okCpu.dispose()
  161. })
  162. it('rejects an output cap whose payload could not cross the frame ceiling', async () => {
  163. // The caps budget a payload that must arrive inside ONE fd-3 frame, and the
  164. // 64 MiB frame parse cap is fixed. A larger cap is unsatisfiable rather
  165. // than generous: a completion the cap admits arrives as an over-ceiling
  166. // frame and fails the run as `worker-exit`, inverting the `output-limit`
  167. // the cap describes. Both budgets are metered in already-escaped serialized
  168. // bytes, so a payload occupies at most `cap + envelope` on the wire; the
  169. // bound is `parse-cap - envelope`, not `(ceiling - envelope) / 6` (that
  170. // divided in escape expansion the charge already counts). The receive path
  171. // rejects raw frames past the 64 MiB parse cap (the run settles as a
  172. // worker-exit), so a budget above it would admit a config whose honest
  173. // child frames the host then rejects.
  174. const admissible = 64 * 1024 * 1024 - 64
  175. const ctx = new Context()
  176. await expect(ctx.plugin(PythonCodeRuntime, { maxLogBytes: admissible + 1 }))
  177. .rejects.toThrow(/maxLogBytes must not exceed 67108800/)
  178. await expect(ctx.plugin(PythonCodeRuntime, { maxValueBytes: admissible + 1 }))
  179. .rejects.toThrow(/maxValueBytes must not exceed 67108800/)
  180. // The boundary value itself loads: the bound is the largest cap a frame can
  181. // still carry, not one below it. It needs an address space large enough to
  182. // clear the separate maxValueBytes/addressSpaceMb worst-case gate (the cap
  183. // times the 12x Unicode expansion must fit), so this pairs it with a 4 GiB
  184. // addressSpaceMb — the two load-time bounds are independent.
  185. const boundary = await ctx.plugin(PythonCodeRuntime, { maxValueBytes: admissible, addressSpaceMb: 4096 })
  186. await boundary.dispose()
  187. })
  188. it('rejects a completion budget whose frame a constrained host heap cannot safely parse', async () => {
  189. // The load gate bounds the CHILD's build-and-encode under RLIMIT_AS; it
  190. // does not bound the HOST's JSON.parse, which materializes several times a
  191. // wide frame's raw bytes in property storage. In a child node with a
  192. // 128 MiB old space the heap-derived frame cap is ~7 MiB, so a 50 MiB
  193. // budget is rejected at load even though the address-space gate alone
  194. // would admit it (50 MiB * 12 = 600 MiB < 1 GiB - 64 MiB).
  195. const script = [
  196. "import { Context } from '@deepseek-ai/cordis'",
  197. "import { PythonCodeRuntime } from './packages/experimental/code-runtime-python/src/index.ts'",
  198. 'const ctx = new Context()',
  199. 'try {',
  200. ' await ctx.plugin(PythonCodeRuntime, { maxValueBytes: 50 * 1024 * 1024, addressSpaceMb: 1024 })',
  201. " console.log('LOADED')",
  202. ' process.exit(1)',
  203. '} catch (error) {',
  204. " console.log('REJECTED:' + (error instanceof Error ? error.message : String(error)))",
  205. ' process.exit(0)',
  206. '}',
  207. ].join('\n')
  208. const out = execFileSync(process.execPath, ['--max-old-space-size=128', '--import', 'tsx', '-e', script], {
  209. cwd: resolve(import.meta.dirname, '../../../..'),
  210. encoding: 'utf8',
  211. timeout: 60_000,
  212. env: { ...process.env, TSX_TSCONFIG_PATH: resolve(import.meta.dirname, '../../../../tsconfig.json') },
  213. })
  214. expect(out).toContain('REJECTED:')
  215. expect(out).toContain('must not exceed')
  216. }, 60_000)
  217. it('parses a worst-shape frame at the derived cap on a constrained heap', async () => {
  218. // The host-heap frame cap must be measured against the WORST parse shape —
  219. // a dict of many short unique keys, which forces dictionary-mode property
  220. // storage plus interned keys (~6.4x at 3M keys, trending up), not the ~3x
  221. // of a repeated-key dict. A child node with a 128 MiB old space (~176 MiB
  222. // heap limit) derives a cap of floor((176 - 64) / 16) = 7 MiB; the
  223. // subprocess builds a unique-key dict whose frame is AT that cap and
  224. // parses it, which must survive. Verified fail-before: with the multiple
  225. // at 8 the derived cap doubles to 14 MiB and the same subprocess OOMs
  226. // during the parse (plain JS, no tsx — the frame and parse are builtins).
  227. const cap = hostFrameParseCeiling(176 * 1024 * 1024)
  228. const script = [
  229. `const cap = ${cap}`,
  230. // Each entry "k<base36>:1," is ~9-12 raw bytes; a few hundred thousand
  231. // unique keys put the frame just at the cap.
  232. 'const count = Math.floor(cap / 12)',
  233. 'const obj = {}',
  234. 'for (let i = 0; i < count; i++) obj[`k${i.toString(36)}`] = 1',
  235. 'const frame = JSON.stringify(obj)',
  236. "if (Buffer.byteLength(frame, 'utf8') > cap) throw new Error('frame over cap: ' + frame.length)",
  237. 'JSON.parse(frame)',
  238. "console.log('SURVIVED:' + Buffer.byteLength(frame, 'utf8'))",
  239. ].join('\n')
  240. const out = execFileSync(process.execPath, ['--max-old-space-size=128', '-e', script], {
  241. encoding: 'utf8',
  242. timeout: 60_000,
  243. })
  244. expect(out).toContain('SURVIVED:')
  245. }, 60_000)
  246. it('rejects a pythonBin that spawn() would throw on, at load', async () => {
  247. // Both values pass the string schema and both make `spawn` throw
  248. // SYNCHRONOUSLY from inside run() — ERR_INVALID_ARG_VALUE for the empty
  249. // path, ERR_INVALID_ARG_TYPE for the NUL — so run() would REJECT instead of
  250. // resolving the worker-exit the seam promises for a child that cannot
  251. // start. Both are self-contained configuration errors, so they fail here.
  252. const ctx = new Context()
  253. await expect(ctx.plugin(PythonCodeRuntime, { pythonBin: '' }))
  254. .rejects.toThrow(/pythonBin must be a non-empty path without NUL bytes/)
  255. await expect(ctx.plugin(PythonCodeRuntime, { pythonBin: 'py\u0000thon3' }))
  256. .rejects.toThrow(/pythonBin must be a non-empty path without NUL bytes/)
  257. })
  258. it('rejects an explicit pythonBin that is not an executable regular file, at load', async () => {
  259. // An explicit path (absolute, or containing a slash) bypasses PATH lookup,
  260. // so it must be validated directly: missing, non-executable, or directory
  261. // paths are self-contained configuration errors that used to slip through
  262. // load and surface only at the first run() as a misleading worker-exit.
  263. // The message distinguishes the explicit-path failure from a basename that
  264. // simply does not resolve on PATH.
  265. const nodePath = await import('node:path')
  266. const { writeFileSync, mkdirSync } = await import('node:fs')
  267. const dir = makeTempDirSync('dsh-bad-bin-')
  268. const notExecutable = nodePath.join(dir, 'not-executable')
  269. writeFileSync(notExecutable, '#!/bin/sh\nexit 0\n') // Regular file, but no X bit.
  270. const directory = nodePath.join(dir, 'is-a-directory')
  271. mkdirSync(directory)
  272. try {
  273. const missing = new Context()
  274. await expect(missing.plugin(PythonCodeRuntime, { pythonBin: nodePath.join(dir, 'missing') }))
  275. .rejects.toThrow(/is not an executable regular file/)
  276. const noX = new Context()
  277. await expect(noX.plugin(PythonCodeRuntime, { pythonBin: notExecutable }))
  278. .rejects.toThrow(/is not an executable regular file/)
  279. const isDir = new Context()
  280. await expect(isDir.plugin(PythonCodeRuntime, { pythonBin: directory }))
  281. .rejects.toThrow(/is not an executable regular file/)
  282. // A relative explicit path fails the same way, resolved against the host
  283. // CWD: `dir` is absolute, so a slash-containing relative form of it is
  284. // the dirname prefix plus the file, which does not exist as such.
  285. const rel = new Context()
  286. await expect(rel.plugin(PythonCodeRuntime, { pythonBin: './definitely-not-there-python' }))
  287. .rejects.toThrow(/is not an executable regular file/)
  288. } finally {
  289. const { rmSync } = await import('node:fs')
  290. rmSync(dir, { recursive: true, force: true })
  291. }
  292. })
  293. it('rejects a non-CPython, outdated, or probe-failing interpreter at load', async () => {
  294. const nonPython = new Context()
  295. await expect(nonPython.plugin(PythonCodeRuntime, { pythonBin: '/bin/echo' }))
  296. .rejects.toThrow(/did not report a CPython version/)
  297. const dir = await mkdtemp(join(tmpdir(), 'dsh-python-probe-'))
  298. const oldMajor = join(dir, 'python-old-major')
  299. const old = join(dir, 'python-old')
  300. const future = join(dir, 'python-future')
  301. const pypy = join(dir, 'pypy')
  302. const failed = join(dir, 'python-failed')
  303. await writeFile(oldMajor, '#!/bin/sh\nprintf \'cpython 2 99 0\\n\'\n', { mode: 0o755 })
  304. await writeFile(old, '#!/bin/sh\nprintf \'cpython 3 9 6\\n\'\n', { mode: 0o755 })
  305. await writeFile(future, '#!/bin/sh\nprintf \'cpython 4 0 0\\n\'\n', { mode: 0o755 })
  306. await writeFile(pypy, '#!/bin/sh\nprintf \'pypy 3 10 0\\n\'\n', { mode: 0o755 })
  307. await writeFile(failed, '#!/bin/sh\nexit 7\n', { mode: 0o755 })
  308. try {
  309. expect(resolvePythonBin(relative(process.cwd(), old))).toBe(old)
  310. const obsolete = new Context()
  311. await expect(obsolete.plugin(PythonCodeRuntime, { pythonBin: oldMajor }))
  312. .rejects.toThrow(/must be CPython 3\.10 or newer, got cpython 2\.99\.0/)
  313. const outdated = new Context()
  314. await expect(outdated.plugin(PythonCodeRuntime, { pythonBin: old }))
  315. .rejects.toThrow(/must be CPython 3\.10 or newer, got cpython 3\.9\.6/)
  316. const forwardCompatible = new Context()
  317. const fiber = await forwardCompatible.plugin(PythonCodeRuntime, { pythonBin: future })
  318. await fiber.dispose()
  319. const alternative = new Context()
  320. await expect(alternative.plugin(PythonCodeRuntime, { pythonBin: pypy }))
  321. .rejects.toThrow(/must be CPython, got pypy/)
  322. const probeFailure = new Context()
  323. await expect(probeFailure.plugin(PythonCodeRuntime, { pythonBin: failed }))
  324. .rejects.toThrow(/failed the CPython version probe/)
  325. } finally {
  326. rmSync(dir, { recursive: true, force: true })
  327. }
  328. })
  329. it('keeps an explicit executable pythonBin working through load and run', async () => {
  330. // The same validation that rejects bad explicit paths must admit a good
  331. // one: an absolute path to the real interpreter (or a wrapper around it)
  332. // is the deployment form the validation exists to serve.
  333. const pyAbs = resolvePythonBin('python3') ?? 'python3'
  334. const { runtime, fiber } = await setup({ pythonBin: pyAbs, maxWallMs: 30_000 })
  335. const result = await runtime.run({ program: 'return 1', bindings: [] })
  336. expect(result.error).toBeUndefined()
  337. expect(result.value).toBe(1)
  338. await fiber.dispose()
  339. })
  340. it('rejects a binding member accessor that throws, as seam misuse', async () => {
  341. // `namespace.functions` is caller-supplied, so its members may come from a
  342. // getter or Proxy. Reading one of them inside the fd-3 `data` callback used
  343. // to throw OUTSIDE the dispatcher's try and terminate the host; the
  344. // validation now snapshots the callables synchronously, so the throw
  345. // surfaces as the seam-misuse rejection run() reserves for malformed
  346. // bindings — the child is never spawned.
  347. const { runtime } = await setup()
  348. const exploding = {
  349. get explode(): CodeBindingFunction {
  350. throw new Error('getter blew up')
  351. },
  352. }
  353. await expect(runtime.run({
  354. program: 'return 1',
  355. bindings: [{ global: 'tools', functions: exploding }],
  356. })).rejects.toThrow(/getter blew up/)
  357. })
  358. it('snapshots binding callables once, so a getter is read exactly once', async () => {
  359. // The snapshot also fixes the key set the boot frame advertises: the child
  360. // learns the namespace names from the SAME record dispatch reads, so a
  361. // getter whose keys differ between reads cannot desynchronize the two.
  362. let reads = 0
  363. const countReads = {
  364. get first(): CodeBindingFunction {
  365. reads += 1
  366. return async () => 1
  367. },
  368. }
  369. const { runtime, fiber } = await setup()
  370. const result = await runtime.run({
  371. program: 'return 1',
  372. bindings: [{ global: 'tools', functions: countReads }],
  373. })
  374. expect(result.error).toBeUndefined()
  375. // One read for the validation snapshot; the boot frame and every dispatch
  376. // read the snapshot, not the getter.
  377. expect(reads).toBe(1)
  378. await fiber.dispose()
  379. })
  380. it('keeps a __proto__ binding member dispatchable', async () => {
  381. // The seam contract treats member names like `__proto__` or `constructor`
  382. // as ordinary own properties (null-prototype construction). The binding
  383. // snapshot must preserve that: a plain `{}` record would hit the prototype
  384. // setter on assignment and drop the member, so the child would never learn
  385. // the name and a call to it would fail with KeyError.
  386. const { runtime, fiber } = await setup()
  387. const result = await runtime.run({
  388. program: 'return await tools["__proto__"]({})',
  389. bindings: [{
  390. global: 'tools',
  391. functions: { ['__proto__']: async () => 'proto-callable' },
  392. }],
  393. })
  394. expect(result.error).toBeUndefined()
  395. expect(result.value).toBe('proto-callable')
  396. await fiber.dispose()
  397. })
  398. it('resolves pythonBin once so a later PATH change cannot switch interpreters', async () => {
  399. const firstDir = await mkdtemp(join(tmpdir(), 'dsh-python-first-'))
  400. const secondDir = await mkdtemp(join(tmpdir(), 'dsh-python-second-'))
  401. const wrapper = (marker: string): string => `#!/bin/sh\nDSH_TEST_PYTHON=${marker}\nexport DSH_TEST_PYTHON\nexec "${PYABS}" "$@"\n`
  402. await writeFile(join(firstDir, 'python3'), wrapper('first'), { mode: 0o755 })
  403. await writeFile(join(secondDir, 'python3'), wrapper('second'), { mode: 0o755 })
  404. vi.stubEnv('PATH', firstDir)
  405. let fiber: Awaited<ReturnType<typeof setup>>['fiber'] | undefined
  406. try {
  407. const mounted = await setup({ pythonBin: 'python3' })
  408. fiber = mounted.fiber
  409. vi.stubEnv('PATH', secondDir)
  410. const result = await mounted.runtime.run({
  411. program: 'import os\nreturn os.environ.get("DSH_TEST_PYTHON")',
  412. bindings: [],
  413. })
  414. expect(result.error).toBeUndefined()
  415. expect(result.value).toBe('first')
  416. } finally {
  417. await fiber?.dispose()
  418. vi.unstubAllEnvs()
  419. rmSync(firstDir, { recursive: true, force: true })
  420. rmSync(secondDir, { recursive: true, force: true })
  421. }
  422. })
  423. it('skips relative PATH entries when resolving a basename pythonBin', async () => {
  424. // resolvePythonBin must return an absolute path: a RELATIVE PATH entry
  425. // ('.' here) would otherwise resolve the basename against the host CWD.
  426. // This run's CWD holds no executable named python3, so both the relative
  427. // skip and the accessSync-miss fall through to the absolute entry — the
  428. // case pins the contract (absolute candidate wins over a relative PATH
  429. // prefix), not a worker-exit distinction, which would need an executable
  430. // named python3 in the test CWD.
  431. const cp = await import('node:child_process')
  432. const nodePath = await import('node:path')
  433. const pythonDir = nodePath.dirname(cp.execFileSync('which', ['python3'], { encoding: 'utf8' }).trim())
  434. vi.stubEnv('PATH', `.:${pythonDir}`)
  435. try {
  436. const { runtime, fiber } = await setup({ pythonBin: 'python3', maxWallMs: 30_000 })
  437. const result = await runtime.run({ program: 'return 1', bindings: [] })
  438. expect(result.error).toBeUndefined()
  439. expect(result.value).toBe(1)
  440. await fiber.dispose()
  441. } finally {
  442. vi.unstubAllEnvs()
  443. }
  444. }, 45_000)
  445. it('ignores a forged second boot-ack without re-sending the run frame', async () => {
  446. // The run frame is sent once, from the first boot-ack; a program that
  447. // forges an extra boot-ack frame on fd 3 must not re-enter the gate (a
  448. // second run frame would confuse the child's frame reader). The honest
  449. // child sends exactly one ack; the forged one exercises the re-entry
  450. // guard.
  451. const { runtime } = await setup()
  452. const result = await runtime.run({
  453. program: [
  454. 'import os',
  455. // One forged boot-ack after the program starts; the run already went
  456. // out on the real ack.
  457. "os.write(3, b'{\"type\":\"boot-ack\"}\\n')",
  458. 'return "done"',
  459. ].join('\n'),
  460. bindings: [],
  461. })
  462. expect(result.error).toBeUndefined()
  463. expect(result.value).toBe('done')
  464. }, 15_000)
  465. it('skips a PATH entry that is an executable DIRECTORY named like the interpreter', async () => {
  466. // accessSync(X_OK) succeeds on directories, so without the isFile guard a
  467. // PATH entry like a `python3` directory would be chosen over a later real
  468. // interpreter. The stub PATH puts such a directory first and asserts the
  469. // real interpreter is used.
  470. const cp = await import('node:child_process')
  471. const nodePath = await import('node:path')
  472. const { mkdirSync } = await import('node:fs')
  473. const realPythonDir = nodePath.dirname(cp.execFileSync('which', ['python3'], { encoding: 'utf8' }).trim())
  474. const fakeDir = makeTempDirSync('dsh-fake-bin-')
  475. mkdirSync(nodePath.join(fakeDir, 'python3')) // A directory named python3, executable by default.
  476. vi.stubEnv('PATH', `${fakeDir}:${realPythonDir}`)
  477. try {
  478. const { runtime, fiber } = await setup({ pythonBin: 'python3', maxWallMs: 30_000 })
  479. const result = await runtime.run({ program: 'return 1', bindings: [] })
  480. expect(result.error).toBeUndefined()
  481. expect(result.value).toBe(1)
  482. await fiber.dispose()
  483. } finally {
  484. vi.unstubAllEnvs()
  485. }
  486. }, 45_000)
  487. it('rejects a timer budget setTimeout would silently clamp to 1 ms', async () => {
  488. // Node stores a setTimeout delay as a signed 32-bit value and substitutes
  489. // 1 ms for anything larger, inverting the knob's meaning: a huge maxWallMs
  490. // would time every run out at once, and a huge graceMs would SIGKILL one
  491. // millisecond after SIGTERM. Both must fail at load instead.
  492. const ctx = new Context()
  493. await expect(ctx.plugin(PythonCodeRuntime, { maxWallMs: 2_147_483_648 }))
  494. .rejects.toThrow(/maxWallMs must not exceed 2147483647/)
  495. // graceMs is bounded by the close deadline's added margin, not by the raw
  496. // timer maximum, because that sum is what gets armed.
  497. await expect(ctx.plugin(PythonCodeRuntime, { graceMs: 2_147_481_648 }))
  498. .rejects.toThrow(/graceMs must not exceed 2147481647/)
  499. // The exact maxima still load.
  500. await expect(ctx.plugin(PythonCodeRuntime, { maxWallMs: 2_147_483_647, graceMs: 2_147_481_647 }))
  501. .resolves.toBeDefined()
  502. })
  503. it('rejects loading this Unix-only backend on Windows', async () => {
  504. // The bootstrap needs the POSIX `resource` module, a positional fd 3, and
  505. // negative-PID process-group signals — none on Windows. The constructor
  506. // must throw at load rather than register ctx.codeRuntime and defer the
  507. // failure to the first run.
  508. const original = process.platform
  509. Object.defineProperty(process, 'platform', { value: 'win32', configurable: true })
  510. try {
  511. const ctx = new Context()
  512. await expect(ctx.plugin(PythonCodeRuntime, {})).rejects.toThrow(/requires a Unix platform/)
  513. } finally {
  514. Object.defineProperty(process, 'platform', { value: original, configurable: true })
  515. }
  516. })
  517. it('rejects a binding global that is not a Python identifier or is reserved', async () => {
  518. const { runtime } = await setup()
  519. await expect(runtime.run({
  520. program: 'return 1',
  521. bindings: [{ global: '1bad', functions: {} }],
  522. })).rejects.toThrow(/is not a usable Python identifier/)
  523. await expect(runtime.run({
  524. program: 'return 1',
  525. bindings: [{ global: 'class', functions: {} }],
  526. })).rejects.toThrow(/is not a usable Python identifier/)
  527. })
  528. it('rejects duplicate binding namespaces', async () => {
  529. const { runtime } = await setup()
  530. await expect(runtime.run({
  531. program: 'return 1',
  532. bindings: [
  533. { global: 'tools', functions: {} },
  534. { global: 'tools', functions: {} },
  535. ],
  536. })).rejects.toThrow(/duplicate binding global/)
  537. })
  538. it('rejects run() after disposal, and unregisters ctx.codeRuntime', async () => {
  539. const { ctx, fiber, runtime } = await setup()
  540. await fiber.dispose()
  541. await expect(runtime.run({ program: 'return 1', bindings: [] }))
  542. .rejects.toThrow(/after disposal/)
  543. expect(ctx.get('codeRuntime')).toBeUndefined()
  544. })
  545. it('short-circuits when the request signal is already aborted', async () => {
  546. const { runtime } = await setup()
  547. const signal = AbortSignal.abort('already-cancelled')
  548. const result = await runtime.run({ program: 'return 1', bindings: [], signal })
  549. expect(result.error?.kind).toBe('abort')
  550. expect(result.error?.message).toContain('already-cancelled')
  551. expect(result.logs).toEqual([])
  552. })
  553. it('short-circuits on an already-aborted signal whose reason cannot be converted', async () => {
  554. // The pre-flight arm converted the reason with a bare `String()`, so a
  555. // hostile reason threw out of `run()` — the seam promises to reject only for
  556. // misuse, and a caller's cancellation token is not misuse.
  557. const { runtime } = await setup()
  558. const signal = AbortSignal.abort({
  559. [Symbol.toPrimitive]() { throw new Error('reason blew up') },
  560. })
  561. const result = await runtime.run({ program: 'return 1', bindings: [], signal })
  562. expect(result.error?.kind).toBe('abort')
  563. expect(result.error?.message).toBe('<unrenderable rejection value>')
  564. expect(result.logs).toEqual([])
  565. })
  566. it('runs the interpreter from materialized scripts outside the package, and removes them per run', async () => {
  567. // The interpreter is an EXTERNAL process, so it can only open paths the OS
  568. // resolves. Inside the single-file Python-SDK executable the packaged `py/`
  569. // directory lives in pkg's virtual filesystem, which Node reads through its
  570. // patched `fs` but `python3` cannot see, so spawning from that path fails
  571. // with ENOENT. The scripts are therefore copied to a real directory first.
  572. //
  573. // The path is read from the child's own `__main__` module, so it proves
  574. // where the interpreter actually loaded the entry script — asserting on a
  575. // host-side constant would only restate the source. The program namespace
  576. // seeds `__name__` but no `__file__`, hence the module lookup.
  577. // `protocol.py` must land in the SAME directory, since `bootstrap.py` puts
  578. // its own directory on `sys.path` to import it; the run completing at all
  579. // already exercises that import.
  580. const { runtime } = await setup()
  581. const entryOf = async (): Promise<string> => {
  582. const result = await runtime.run({ program: 'import sys\nreturn sys.modules["__main__"].__file__', bindings: [] })
  583. expect(result.error).toBeUndefined()
  584. return result.value as string
  585. }
  586. const entry = await entryOf()
  587. expect(entry.endsWith('/bootstrap.py')).toBe(true)
  588. const dir = dirname(entry)
  589. expect(realpathSync(dirname(dir))).toBe(realpathSync(tmpdir()))
  590. expect(basename(dir)).toMatch(/^dsh-code-runtime-python-/)
  591. expect(dir).not.toContain('/packages/')
  592. // Staging is per RUN and removed at settlement, so by the time `run()`
  593. // resolved the directory is already gone — nothing survives to be rewritten
  594. // by a later run. `protocol.py` had to be beside the entry script for the run
  595. // to complete at all, since `bootstrap.py` imports it off `sys.path`.
  596. expect(existsSync(dir)).toBe(false)
  597. // A second run stages its own copy rather than reusing the first.
  598. expect(dirname(await entryOf())).not.toBe(dir)
  599. })
  600. it('contains a program that rewrites its own bootstrap to the run that did it', async () => {
  601. // The child runs as the same UID as the host, so `0o700` does not stop model
  602. // code from rewriting the scripts it was started from —
  603. // `sys.modules['__main__'].__file__` names them. While all runs shared one
  604. // staged copy, a program that overwrote `bootstrap.py` broke the NEXT run
  605. // (measured: it settled as `worker-exit`), and substituted code would have
  606. // run before the resource limits were applied.
  607. const { runtime } = await setup({ maxWallMs: 10_000 })
  608. const sabotage = await runtime.run({
  609. program: [
  610. 'import sys',
  611. 'path = sys.modules["__main__"].__file__',
  612. 'open(path, "w").write("raise SystemExit(1)\\n")',
  613. 'return path',
  614. ].join('\n'),
  615. bindings: [],
  616. })
  617. expect(sabotage.error).toBeUndefined()
  618. // The damage stayed inside the run that caused it.
  619. const after = await runtime.run({ program: 'return 1 + 1', bindings: [] })
  620. expect(after.error).toBeUndefined()
  621. expect(after.value).toBe(2)
  622. }, 20_000)
  623. it('leaves no subprocess or scripts behind when disposal races the first run', async () => {
  624. // Staging runs SYNCHRONOUSLY so no async boundary opens between `run()` and
  625. // the point where `execute` registers the run in `live` and installs the
  626. // abort listener. With an `await` there, a disposal landing in that window
  627. // saw an empty `live`, returned, removed the script directory, and let the
  628. // continuation spawn a subprocess after the fiber was gone.
  629. //
  630. // `dispose()` is called in the same synchronous turn as `run()`, with no
  631. // `await` between them, so it lands exactly in that window.
  632. //
  633. // The leak assertion checks the EXACT paths this test file staged (recorded
  634. // by the mocked mkdtempSync) rather than diffing a global tmpdir: a
  635. // parallel vitest worker can create or remove same-prefix directories
  636. // inside the sampling window, which a readdir diff would misattribute to
  637. // this test (boot-write-failure.spec.ts records the same race).
  638. const stagedBefore = stagedDirs.length
  639. const { fiber, runtime } = await setup({ maxWallMs: 8_000 })
  640. const pending = runtime.run({ program: 'import time\nwhile True: time.sleep(0.1)', bindings: [] })
  641. const disposed = fiber.dispose()
  642. const result = await pending
  643. await disposed
  644. // Whatever the run reports, it must be terminal and must not be a success.
  645. expect(result.value).toBeUndefined()
  646. expect(['abort', 'worker-exit', 'timeout']).toContain(result.error?.kind)
  647. // Disposal is to quiescence, so every directory this run staged is gone.
  648. const created = stagedDirs.slice(stagedBefore)
  649. for (const dir of created) expect(existsSync(dir)).toBe(false)
  650. }, 15_000)
  651. it('settles as abort when the signal fires in the same turn as the first run', async () => {
  652. // Same window, the other listener. `addEventListener('abort')` does not
  653. // replay an event that already fired, so an abort landing before the
  654. // listener was installed used to be missed entirely and the program ran to
  655. // success or the wall ceiling instead of resolving as `abort`. Synchronous
  656. // staging keeps the pre-flight check and the listener in one turn, leaving
  657. // no gap for the signal to slip through.
  658. const { runtime } = await setup({ maxWallMs: 4_000, graceMs: 200 })
  659. const controller = new AbortController()
  660. const pending = runtime.run({
  661. program: 'import time\nwhile True: time.sleep(0.1)',
  662. bindings: [],
  663. signal: controller.signal,
  664. })
  665. controller.abort('same-turn-abort')
  666. const result = await pending
  667. expect(result.error?.kind).toBe('abort')
  668. expect(result.error?.message).toContain('same-turn-abort')
  669. }, 15_000)
  670. it('reports a staging failure as worker-exit instead of rejecting run()', async () => {
  671. // Staging touches the filesystem, so it can fail for reasons that are not
  672. // the caller's doing: a full or read-only temp filesystem, or a deployment
  673. // that failed to ship the packaged scripts. Those are SUBSTRATE failures,
  674. // the same class as a child that cannot start, and the seam reserves
  675. // rejection for misuse — so `run()` must resolve, not throw.
  676. //
  677. // `TMPDIR` is the honest lever: `mkdtempSync` builds its path from
  678. // `os.tmpdir()`, so pointing it at a path that is not a directory makes the
  679. // real call fail without stubbing the module under test.
  680. const previous = process.env.TMPDIR
  681. const notADirectory = join(await makeTempDir('dsh-staging-'), 'file')
  682. await writeFile(notADirectory, '')
  683. process.env.TMPDIR = notADirectory
  684. try {
  685. const { runtime } = await setup()
  686. const result = await runtime.run({ program: 'return 1', bindings: [] })
  687. expect(result.error?.kind).toBe('worker-exit')
  688. expect(result.error?.message).toContain('failed to stage the python bootstrap')
  689. expect(result.logs).toEqual([])
  690. } finally {
  691. if (previous === undefined) delete process.env.TMPDIR
  692. else process.env.TMPDIR = previous
  693. }
  694. })
  695. it('leaves no staging directory behind when a script copy fails', async () => {
  696. // `mkdtempSync` succeeding and a later `copyFileSync` failing is its own
  697. // case: the directory exists but is only partially populated. Recording it
  698. // before the copies would leak it, because `run` retries staging on the next
  699. // call and overwrites the single recorded path — teardown could then remove
  700. // only the newest attempt. Staging must clean up its own partial directory.
  701. //
  702. // Only `copyFileSync` is stubbed, and only for the second script, so
  703. // `mkdtempSync` really runs and the directory under assertion is real.
  704. // The assertion checks the exact paths this test staged (see the sibling
  705. // disposal-race test for why a global tmpdir diff races parallel workers).
  706. const stagedBefore = stagedDirs.length
  707. failNextCopyOf.value = 'protocol.py'
  708. try {
  709. const { runtime } = await setup()
  710. const result = await runtime.run({ program: 'return 1', bindings: [] })
  711. expect(result.error?.kind).toBe('worker-exit')
  712. expect(result.error?.message).toContain('failed to stage the python bootstrap')
  713. // The partial directory is gone, so nothing accumulates across retries.
  714. for (const dir of stagedDirs.slice(stagedBefore)) expect(existsSync(dir)).toBe(false)
  715. } finally {
  716. failNextCopyOf.value = undefined
  717. }
  718. }, 15_000)
  719. })
  720. describe('PythonCodeRuntime — process identity', () => {
  721. it('reads a live process start time and distinguishes it from an absent pid', () => {
  722. // The teardown guard signals `-child.pid` with a RAW `process.kill`, which
  723. // (unlike `child.kill()`) has no handle check, so it would reach a recycled
  724. // pgid during the window between the leader being reaped and `close` firing.
  725. // A pid alone cannot separate the original from its replacement -- both
  726. // answer `kill(pid, 0)` -- so the guard compares START TIME, and this pins
  727. // that the reading is stable for one process and absent for a pid that
  728. // cannot be read.
  729. const own = readProcessStart(process.pid)
  730. if (process.platform === 'linux') {
  731. // Same process, two reads: the identity must be stable, or the guard would
  732. // refuse to signal its own live group.
  733. expect(own).toBeDefined()
  734. expect(readProcessStart(process.pid)).toBe(own)
  735. // Pid 0 is never a readable /proc entry, so the guard degrades to
  736. // undefined rather than throwing on a teardown path. This is also the
  737. // reading a REAPED leader produces -- its /proc entry is gone while the
  738. // group it led can still hold survivors -- so `undefined` must NOT be
  739. // treated as an identity mismatch. Reading it as one refused the SIGKILL
  740. // that the same-group survivor tests depend on, which is why they went red
  741. // on Linux while passing on Darwin (where the reader always returns
  742. // undefined and the guard is inert).
  743. expect(readProcessStart(0)).toBeUndefined()
  744. } else {
  745. // Darwin has no /proc: the reader reports undefined, and `killGroup`
  746. // signals the pgid without the identity re-check instead of paying a `ps`
  747. // fork per signal.
  748. expect(own).toBeUndefined()
  749. }
  750. })
  751. })
  752. describe('PythonCodeRuntime — inherited resource limits', () => {
  753. // Darwin deliberately does not apply RLIMIT_AS, and its shell rejects `ulimit -v`.
  754. it.skipIf(process.platform === 'darwin')('runs under an inherited hard limit tighter than addressSpaceMb', async () => {
  755. // An unprivileged process may lower a hard rlimit but never raise it. Under
  756. // a harness started with `ulimit -v` below `addressSpaceBytes`, requesting
  757. // the configured cap made `setrlimit` raise `ValueError` and every run
  758. // returned a bootstrap exception — even though the inherited limit is
  759. // STRONGER than the one asked for. The bootstrap clamps to the inherited
  760. // hard limit instead, so the run proceeds under the stricter bound.
  761. //
  762. // `pythonBin` is the honest lever: a wrapper that lowers RLIMIT_AS and then
  763. // execs the real interpreter reproduces the inherited-limit condition
  764. // without touching this test process's own limits.
  765. const dir = await makeTempDir('dsh-rlimit-')
  766. const wrapper = join(dir, 'python3-capped')
  767. // 256 MiB, half the 512 MiB addressSpaceMb default, so the requested cap is
  768. // unambiguously above the inherited ceiling.
  769. await writeFile(wrapper, `#!/bin/sh\nulimit -v 262144\nexec "${PYABS}" "$@"\n`, { mode: 0o755 })
  770. const { runtime } = await setup({ pythonBin: wrapper })
  771. const result = await runtime.run({
  772. program: 'import resource\nreturn resource.getrlimit(resource.RLIMIT_AS)[1]',
  773. bindings: [],
  774. })
  775. expect(result.error).toBeUndefined()
  776. // The applied hard limit is the inherited one, not the configured 512 MiB.
  777. expect(result.value).toBe(256 * 1024 * 1024)
  778. }, 15_000)
  779. it('rejects at boot when an inherited RLIMIT_AS is too tight for the output budgets', async () => {
  780. // The host gate validates the output budgets against the CONFIGURED
  781. // addressSpaceMb, but a launch environment can inherit a STRICTER RLIMIT_AS
  782. // (a `ulimit -v` wrapper below addressSpaceMb), which the bootstrap clamps the
  783. // effective limit down to — leaving the budgets sized for a ceiling the child
  784. // never gets, so a near-budget output would OOM mid-run as an opaque
  785. // worker-exit. The bootstrap re-checks both budgets against the EFFECTIVE
  786. // clamped limit and fails loud at boot instead. A 128 MiB inherited limit
  787. // leaves 64 MiB budgetable (~5 MiB admissible under the 12x multiple), under
  788. // which a 32 MiB maxLogBytes — admitted by the 512 MiB configured default — is
  789. // rejected. The rejection surfaces as an 'exception' (bootstrap's
  790. // setrlimit-phase failure class), not a mid-run OOM. The repro is Linux-only
  791. // (macOS ignores `ulimit -v`); there the run proceeds.
  792. const dir = await makeTempDir('dsh-rlimit-')
  793. const wrapper = join(dir, 'python3-tight')
  794. await writeFile(wrapper, `#!/bin/sh\nulimit -v 131072\nexec "${PYABS}" "$@"\n`, { mode: 0o755 })
  795. const { runtime } = await setup({ pythonBin: wrapper, maxLogBytes: 32 * 1024 * 1024, addressSpaceMb: 512 })
  796. const result = await runtime.run({ program: 'return 1', bindings: [] })
  797. if (process.platform === 'darwin') {
  798. expect(result.error).toBeUndefined()
  799. } else {
  800. // The re-check raises inside bootstrap's resource-limit block, which
  801. // reports every setrlimit-phase failure as kind 'exception'; the message
  802. // discriminates this config rejection from a generic setrlimit error.
  803. expect(result.error?.kind).toBe('exception')
  804. expect(result.error?.message).toContain('too large for the inherited RLIMIT_AS')
  805. }
  806. }, 15_000)
  807. // The expected tuple includes RLIMIT_AS, which the backend deliberately skips on Darwin.
  808. it.skipIf(process.platform === 'darwin')('applies the configured limits when nothing tighter is inherited', async () => {
  809. // The clamp must not weaken the normal path: with an infinite inherited hard
  810. // limit there is nothing to clamp against, and RLIM_INFINITY compares as -1,
  811. // so treating it as a numeric bound would collapse every limit to -1.
  812. const { runtime } = await setup({ cpuSeconds: 42, addressSpaceMb: 400 })
  813. const result = await runtime.run({
  814. // `getrlimit` returns a tuple, which the lossless-JSON completion check
  815. // rejects; the pair is listed explicitly rather than converted.
  816. program: [
  817. 'import resource, sys',
  818. 'cpu = resource.getrlimit(resource.RLIMIT_CPU)',
  819. 'address_space = None if sys.platform == "darwin" else resource.getrlimit(resource.RLIMIT_AS)[1]',
  820. 'return {"cpu": [cpu[0], cpu[1]], "addressSpace": address_space}',
  821. ].join('\n'),
  822. bindings: [],
  823. })
  824. expect(result.error).toBeUndefined()
  825. // Darwin deliberately skips RLIMIT_AS; every other Unix host applies the
  826. // configured bytes alongside the CPU soft/hard pair.
  827. expect(result.value).toEqual({
  828. cpu: [42, 43],
  829. addressSpace: process.platform === 'darwin' ? null : 400 * 1024 * 1024,
  830. })
  831. }, 15_000)
  832. it('preserves an inherited soft limit stricter than the configured cap', async () => {
  833. // Clamping reads BOTH inherited bounds, not just the hard one. A deployment
  834. // that inherited a soft rlimit below the configured cap must keep that
  835. // stricter soft: returning the configured value would RAISE the effective
  836. // soft limit, loosening containment. The wrapper lowers only the SOFT CPU
  837. // limit (`ulimit -S -t`) and leaves the hard limit unlimited, so the
  838. // requested soft (`cpuSeconds`) sits above the inherited soft — the case that
  839. // exposed the bug. RLIMIT_CPU is used because macOS ignores `ulimit -v`
  840. // (RLIMIT_AS), which is exactly why the backend skips address space there.
  841. const dir = await makeTempDir('dsh-rlimit-soft-')
  842. const wrapper = join(dir, 'python3-soft-capped')
  843. // Soft CPU 5 s, well below the configured 30 s, hard left unlimited.
  844. await writeFile(wrapper, `#!/bin/sh\nulimit -S -t 5\nexec "${PYABS}" "$@"\n`, { mode: 0o755 })
  845. const { runtime } = await setup({ pythonBin: wrapper, cpuSeconds: 30 })
  846. const result = await runtime.run({
  847. program: 'import resource\nreturn resource.getrlimit(resource.RLIMIT_CPU)[0]',
  848. bindings: [],
  849. })
  850. expect(result.error).toBeUndefined()
  851. // The applied SOFT limit is the inherited 5 s, not the configured 30 s.
  852. expect(result.value).toBe(5)
  853. }, 15_000)
  854. it('reports a CPU overrun under a dual-limit ulimit as a timeout, not a worker-exit', async () => {
  855. // `ulimit -t N` sets BOTH the soft and hard CPU limit to N. The kernel
  856. // checks the hard limit and SIGKILLs a busy loop directly, so with
  857. // soft == hard the SIGXCPU signal is never delivered — and the host
  858. // classifies a CPU overrun ONLY on `signal === 'SIGXCPU'`, so the overrun
  859. // would be misreported as a `worker-exit` instead of a timeout. `_clamped`
  860. // now lowers a clamped soft==hard result by one unit (when hard >= 2), so
  861. // the SIGXCPU signal fires at the softer limit and the run reports a
  862. // timeout. This uses `ulimit -t 2` (hard == 2, so the soft is lowered to 1)
  863. // and leaves SIGXCPU unhandled, so the kernel terminates the busy loop at
  864. // 1 s with SIGXCPU and the host classifies it as a timeout.
  865. const dir = await makeTempDir('dsh-rlimit-dual-')
  866. const wrapper = join(dir, 'python3-dual-capped')
  867. // Both soft and hard CPU 2 s; configured cpuSeconds 30 s.
  868. await writeFile(wrapper, `#!/bin/sh\nulimit -t 2\nexec "${PYABS}" "$@"\n`, { mode: 0o755 })
  869. const { runtime } = await setup({ pythonBin: wrapper, cpuSeconds: 30, maxWallMs: 12_000 })
  870. const result = await runtime.run({
  871. program: [
  872. 'while True:',
  873. ' pass',
  874. 'return "unreachable"',
  875. ].join('\n'),
  876. bindings: [],
  877. })
  878. expect(result.error?.kind).toBe('timeout')
  879. expect(result.error?.message).toContain('CPU time exhausted')
  880. }, 15_000)
  881. it('reports a timeout when a program masks SIGXCPU and returns past the soft limit', async () => {
  882. // A program can mask SIGXCPU (pthread_sigmask SIG_BLOCK), burn past the
  883. // soft CPU limit, and return during the soft-to-hard gap. The settlement
  884. // recheck (`die_if_cpu_exhausted`) must UNBLOCK the signal before
  885. // re-delivering it, or the SIGXCPU stays pending and the child exits
  886. // normally with a success result. With the unblock, the re-delivered
  887. // SIGXCPU (default disposition) terminates the child and the host
  888. // classifies the run as a timeout. Fail-before: without the unblock the
  889. // run reports `value: "escaped"` and no error. The masking is guarded by
  890. // hasattr so the case is a no-op on platforms without pthread_sigmask.
  891. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 12_000 })
  892. const result = await runtime.run({
  893. program: [
  894. 'import signal, time',
  895. 'if hasattr(signal, "pthread_sigmask"):',
  896. ' signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGXCPU})',
  897. 'end = time.process_time() + 1.05',
  898. 'while time.process_time() < end:',
  899. ' pass',
  900. 'return "escaped"',
  901. ].join('\n'),
  902. bindings: [],
  903. })
  904. expect(result.error?.kind).toBe('timeout')
  905. expect(result.value).toBeUndefined()
  906. }, 20_000)
  907. it('reports a timeout when the interpreter was started with SIGXCPU ignored (inherited state)', async () => {
  908. // The child inherits the host's SIGXCPU disposition: a wrapper that
  909. // ignores SIGXCPU before exec'ing python3 hands the child a soft
  910. // RLIMIT_CPU that cannot stop it. The bootstrap resets SIGXCPU to SIG_DFL
  911. // before model code runs, so a busy loop still ends as a timeout rather
  912. // than running to the hard limit and being misclassified as worker-exit.
  913. const wrapper = join(tmpdir(), `dsh-xcpu-ignore-${process.pid}.sh`)
  914. tempFiles.push(wrapper)
  915. writeFileSync(wrapper, `#!/bin/sh\ntrap "" XCPU\nexec "${PYABS}" "$@"\n`, { mode: 0o755 })
  916. try {
  917. const { runtime } = await setup({ maxWallMs: 30_000, cpuSeconds: 1, pythonBin: wrapper })
  918. const result = await runtime.run({
  919. program: ['while True: pass'].join('\n'),
  920. bindings: [],
  921. })
  922. expect(result.error?.kind).toBe('timeout')
  923. } finally {
  924. rmSync(wrapper, { force: true })
  925. }
  926. }, 20_000)
  927. it('reports a timeout when a program traps AND masks SIGXCPU and returns past the soft limit', async () => {
  928. // The mask-only case exercises the unblock; the trap+mask combination is
  929. // the harder one: a program that installed a custom handler AND masked the
  930. // signal has that PENDING handler run the moment the signal is unblocked
  931. // (CPython delivers it at the next eval-breaker checkpoint in model code),
  932. // and the handler re-masks — so the settlement recheck must restore the
  933. // default disposition BEFORE unblocking. With SIG_DFL restored first, the
  934. // pending signal kills the process inside the kernel with no bytecode
  935. // window; without it, the handler re-blocks and the child exits normally
  936. // with a success value. Fail-before: the run reports `value: "escaped"`.
  937. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 12_000 })
  938. const result = await runtime.run({
  939. program: [
  940. 'import signal, time',
  941. 'if hasattr(signal, "pthread_sigmask"):',
  942. ' def h(signum, frame):',
  943. ' signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGXCPU})',
  944. ' signal.signal(signal.SIGXCPU, h)',
  945. ' signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGXCPU})',
  946. ' end = time.process_time() + 1.05',
  947. ' while time.process_time() < end:',
  948. ' pass',
  949. 'return "escaped"',
  950. ].join('\n'),
  951. bindings: [],
  952. })
  953. expect(result.error?.kind).toBe('timeout')
  954. expect(result.value).toBeUndefined()
  955. }, 20_000)
  956. it('rechecks CPU at settlement against the effective inherited soft limit', async () => {
  957. // The settlement-time CPU recheck must compare against the EFFECTIVE soft
  958. // limit (`_clamped` may have lowered it to a stricter inherited value), not
  959. // the configured `cpuSeconds`. A program that traps SIGXCPU, burns past the
  960. // inherited soft, and returns inside the soft-to-hard gap would otherwise be
  961. // compared to the configured value and falsely reported successful, bypassing
  962. // the inherited limit. The wrapper sets a 1 s soft CPU limit; the program
  963. // traps SIGXCPU and busy-loops past it, then returns — the recheck must
  964. // re-deliver SIGXCPU so the host classifies the run as a timeout.
  965. const dir = await makeTempDir('dsh-cpu-recheck-')
  966. const wrapper = join(dir, 'python3-cpu-capped')
  967. await writeFile(wrapper, `#!/bin/sh\nulimit -S -t 1\nexec "${PYABS}" "$@"\n`, { mode: 0o755 })
  968. const { runtime } = await setup({ pythonBin: wrapper, cpuSeconds: 30, maxWallMs: 12_000 })
  969. const result = await runtime.run({
  970. program: [
  971. 'import signal, time',
  972. // Trap SIGXCPU so the soft limit does not terminate the program; burn
  973. // CPU well past the inherited 1 s soft, then return normally.
  974. 'signal.signal(signal.SIGXCPU, lambda *a: None)',
  975. 'end = time.process_time() + 2.5',
  976. 'while time.process_time() < end:',
  977. ' pass',
  978. 'return "returned"',
  979. ].join('\n'),
  980. bindings: [],
  981. })
  982. // The recheck compares spent CPU against the effective 1 s soft, not 30 s, so
  983. // the run is a timeout rather than a false success.
  984. expect(result.error?.kind).toBe('timeout')
  985. }, 20_000)
  986. })
  987. describe('PythonCodeRuntime — programs and bindings', () => {
  988. it('runs a top-level script, captures print output, and returns `result`', async () => {
  989. const { runtime } = await setup()
  990. const result = await runtime.run({
  991. program: [
  992. 'x = 40',
  993. 'y = 2',
  994. 'print("hello", x + y)',
  995. 'return {"answer": x + y}',
  996. ].join('\n'),
  997. bindings: [],
  998. })
  999. expect(result.error).toBeUndefined()
  1000. expect(result.value).toEqual({ answer: 42 })
  1001. // `print` in Python emits: text, ' ', text, '\n'. Concat the captured
  1002. // fragments and assert the model-visible message survives.
  1003. expect(result.logs.join('')).toContain('hello 42')
  1004. // 15s: this is usually the suite's first real subprocess — a cold python3
  1005. // start (interpreter + asyncio import) on a loaded CI runner can exceed
  1006. // the 5s default alone; later tests reuse the warm page cache.
  1007. }, 15_000)
  1008. it('exposes only the platform temp directory from the host environment', async () => {
  1009. const { runtime } = await setup()
  1010. const result = await runtime.run({
  1011. program: [
  1012. 'import os',
  1013. 'return {',
  1014. ' "tmpdir": os.environ.get("TMPDIR"),',
  1015. ' "path": os.environ.get("PATH"),',
  1016. ' "home": os.environ.get("HOME"),',
  1017. ' "token": os.environ.get("DEEPSEEK_API_KEY"),',
  1018. '}',
  1019. ].join('\n'),
  1020. bindings: [],
  1021. })
  1022. expect(result.error).toBeUndefined()
  1023. expect(result.value).toEqual({ tmpdir: tmpdir(), path: null, home: null, token: null })
  1024. expect(result.logs).toEqual([])
  1025. })
  1026. it('bridges binding calls both ways and rejects the program-side call on a host rejection', async () => {
  1027. const { runtime } = await setup()
  1028. const calls: unknown[] = []
  1029. const result = await runtime.run({
  1030. program: [
  1031. 'first = await tools.echo({"n": 1})',
  1032. 'caught = ""',
  1033. 'try:',
  1034. ' await tools.fail({})',
  1035. 'except RuntimeError as e:',
  1036. ' caught = str(e)',
  1037. 'return {"first": first, "caught": caught}',
  1038. ].join('\n'),
  1039. bindings: tools({
  1040. echo: async (args) => { calls.push(args); return { echoed: args as CodeJsonValue } },
  1041. fail: async () => { throw new Error('nope') },
  1042. }),
  1043. })
  1044. expect(result.error).toBeUndefined()
  1045. expect(result.value).toEqual({ first: { echoed: { n: 1 } }, caught: 'nope' })
  1046. expect(calls).toEqual([{ n: 1 }])
  1047. })
  1048. it('keeps decoding binding replies when _decode_json_plain is rebound', async () => {
  1049. // read_frame_async resolves _decode_json_plain at call time; a program that
  1050. // rebinds __main__._decode_json_plain would otherwise kill the reply pump
  1051. // (a broken decode strands every pending Future to the wall clock). The
  1052. // decode primitives are def-time captures on the channel methods, so a
  1053. // rebind cannot break reply delivery.
  1054. const { runtime } = await setup()
  1055. const result = await runtime.run({
  1056. program: [
  1057. 'import __main__',
  1058. '__main__._decode_json_plain = None',
  1059. 'first = await tools.echo({"n": 1})',
  1060. 'return first',
  1061. ].join('\n'),
  1062. bindings: tools({
  1063. echo: async args => ({ echoed: args as CodeJsonValue }),
  1064. }),
  1065. })
  1066. expect(result.error).toBeUndefined()
  1067. expect(result.value).toEqual({ echoed: { n: 1 } })
  1068. }, 15_000)
  1069. it('keeps dispatch working when _lossless_json_violation, asyncio, and send_sync are rebound', async () => {
  1070. // dispatch binds _lossless_json_violation, asyncio.get_event_loop, and the
  1071. // channel's send method into _run locals before the program runs, so a
  1072. // rebind of __main__._lossless_json_violation/__main__.asyncio/
  1073. // __main__.ProtocolChannel.send_sync cannot turn a legitimate binding call
  1074. // into an exception or a wall-clock timeout.
  1075. const { runtime } = await setup()
  1076. const result = await runtime.run({
  1077. program: [
  1078. 'import __main__',
  1079. 'def boom(*a, **k):',
  1080. ' raise RuntimeError("hijacked")',
  1081. '__main__._lossless_json_violation = boom',
  1082. '__main__.asyncio = boom',
  1083. '__main__.ProtocolChannel.send_sync = boom',
  1084. '__main__._encode_json_plain = boom',
  1085. '__main__.ProtocolChannel.write_encoded = boom',
  1086. 'first = await tools.echo({"n": 1})',
  1087. 'return first',
  1088. ].join('\n'),
  1089. bindings: tools({
  1090. echo: async args => ({ echoed: args as CodeJsonValue }),
  1091. }),
  1092. })
  1093. expect(result.error).toBeUndefined()
  1094. expect(result.value).toEqual({ echoed: { n: 1 } })
  1095. }, 15_000)
  1096. it('keeps the reply pump reading when the read_frame_async class attribute is rebound', async () => {
  1097. // _pump_replies' frame reader is a bound method captured by _run before the
  1098. // program runs and passed in as an explicit argument, so a program rebinding
  1099. // `__main__.ProtocolChannel.read_frame_async` cannot redirect the pump (a
  1100. // body-local `channel.read_frame_async` lookup would resolve the rebound
  1101. // class attribute, since the pump starts after the program's top-level
  1102. // statements).
  1103. const { runtime } = await setup()
  1104. const result = await runtime.run({
  1105. program: [
  1106. 'import __main__',
  1107. 'async def boom(*a, **k):',
  1108. ' raise RuntimeError("hijacked reader")',
  1109. '__main__.ProtocolChannel.read_frame_async = boom',
  1110. 'first = await tools.echo({"n": 1})',
  1111. 'return first',
  1112. ].join('\n'),
  1113. bindings: tools({
  1114. echo: async args => ({ echoed: args as CodeJsonValue }),
  1115. }),
  1116. })
  1117. expect(result.error).toBeUndefined()
  1118. expect(result.value).toEqual({ echoed: { n: 1 } })
  1119. }, 15_000)
  1120. it('keeps the rejection contract when _BindingRejection is rebound', async () => {
  1121. // `dispatch`'s except clause resolves `_BindingRejection` at call time; a
  1122. // program that rebinds `__main__._BindingRejection = ValueError` would
  1123. // otherwise let the internal marker type leak into model code (the program
  1124. // would catch a `ValueError` for a host rejection). The class is now bound
  1125. // into `_run` locals before the program runs, so a host rejection still
  1126. // surfaces as the declared `RuntimeError`.
  1127. const { runtime } = await setup()
  1128. const result = await runtime.run({
  1129. program: [
  1130. 'import __main__',
  1131. '__main__._BindingRejection = ValueError',
  1132. 'caught = ""',
  1133. 'try:',
  1134. ' await tools.fail({})',
  1135. 'except RuntimeError as e:',
  1136. ' caught = e.args[0] if e.args else ""',
  1137. 'except Exception as e:',
  1138. ' caught = "WRONG TYPE: " + type(e).__name__',
  1139. 'return caught',
  1140. ].join('\n'),
  1141. bindings: tools({
  1142. fail: async () => { throw new Error('nope') },
  1143. }),
  1144. })
  1145. expect(result.error).toBeUndefined()
  1146. expect(result.value).toBe('nope')
  1147. }, 15_000)
  1148. it('still answers the call when the rejection value cannot be converted to a string', async () => {
  1149. // `messageOf` calls `String(error)`, which runs the value's own conversion,
  1150. // and this call site is a DETACHED async reply callback. A rejection whose
  1151. // `Symbol.toPrimitive` throws therefore escaped as an unhandled rejection:
  1152. // the reply frame was never written, the program stayed blocked on `await`,
  1153. // and the run degraded to a `maxWallMs` timeout (observed) — a host with no
  1154. // `unhandledRejection` listener would exit instead. The rejection must reach
  1155. // the program as an ordinary error carrying a fixed placeholder.
  1156. const { runtime } = await setup({ maxWallMs: 8_000 })
  1157. const result = await runtime.run({
  1158. program: [
  1159. 'try:',
  1160. ' await tools.hostile({})',
  1161. 'except RuntimeError as e:',
  1162. ' return "rejected: " + str(e)',
  1163. 'return "no rejection"',
  1164. ].join('\n'),
  1165. bindings: tools({
  1166. hostile: async () => {
  1167. throw { [Symbol.toPrimitive]() { throw new Error('toPrimitive blew up') } }
  1168. },
  1169. }),
  1170. })
  1171. expect(result.error).toBeUndefined()
  1172. expect(result.value).toBe('rejected: <unrenderable rejection value>')
  1173. }, 15_000)
  1174. it('still answers the call when an Error carries a cyclic value in place of its message', async () => {
  1175. // `Error.message` is typed `string` but is a plain writable property, so a
  1176. // rejection can carry any value there. Returning it verbatim handed a
  1177. // non-string to `sendReply`, breaching `encodeJsonPlain`'s JSON-plain
  1178. // precondition: a cyclic object grew the encoder stack until the host threw
  1179. // RangeError from the detached reply callback, so no reply frame was written
  1180. // and the run degraded to a `maxWallMs` timeout (observed). The conversion
  1181. // must contain it — `String()` on a cycle throws inside the guard and lands
  1182. // on the placeholder, so the program sees an ordinary error.
  1183. const { runtime } = await setup({ maxWallMs: 8_000 })
  1184. const result = await runtime.run({
  1185. program: [
  1186. 'try:',
  1187. ' await tools.hostile({})',
  1188. 'except RuntimeError as e:',
  1189. ' return "rejected: " + str(e)',
  1190. 'return "no rejection"',
  1191. ].join('\n'),
  1192. bindings: tools({
  1193. hostile: async () => {
  1194. const cyclic: { self?: unknown; [Symbol.toPrimitive]: () => string } = {
  1195. // A cycle alone is inert for `String()`; the throwing conversion is
  1196. // what proves the guard runs rather than the encoder.
  1197. [Symbol.toPrimitive]: () => { throw new Error('cyclic message') },
  1198. }
  1199. cyclic.self = cyclic
  1200. const error = new Error('placeholder')
  1201. // Writable per spec, so no cast is needed to install a non-string.
  1202. ;(error as unknown as { message: unknown }).message = cyclic
  1203. throw error
  1204. },
  1205. }),
  1206. })
  1207. expect(result.error).toBeUndefined()
  1208. expect(result.value).toBe('rejected: <unrenderable rejection value>')
  1209. }, 15_000)
  1210. it('renders an Error whose message is a value with no JSON form', async () => {
  1211. // The non-cyclic arm. A number would not discriminate: `scalarJson` renders
  1212. // it as digits and the child `str()`s the field back, so it survives the
  1213. // wire either way. `undefined` is the value that separates the two orders —
  1214. // `scalarJson` emits a bare `undefined` token, so the reply line is not JSON
  1215. // at all, the child's parse drops the frame, and the program stays blocked
  1216. // on `await` until the wall ceiling (observed). Converting first sends the
  1217. // string "undefined", which the program receives as an ordinary rejection.
  1218. const { runtime } = await setup({ maxWallMs: 8_000 })
  1219. const result = await runtime.run({
  1220. program: [
  1221. 'try:',
  1222. ' await tools.absent({})',
  1223. 'except RuntimeError as e:',
  1224. ' return "rejected: " + str(e)',
  1225. 'return "no rejection"',
  1226. ].join('\n'),
  1227. bindings: tools({
  1228. absent: async () => {
  1229. const error = new Error('placeholder')
  1230. ;(error as unknown as { message: unknown }).message = undefined
  1231. throw error
  1232. },
  1233. }),
  1234. })
  1235. expect(result.error).toBeUndefined()
  1236. expect(result.value).toBe('rejected: undefined')
  1237. }, 15_000)
  1238. it('runs a program with no await', async () => {
  1239. const { runtime } = await setup()
  1240. const result = await runtime.run({
  1241. program: 'return 2 + 2',
  1242. bindings: [],
  1243. })
  1244. expect(result.error).toBeUndefined()
  1245. expect(result.value).toBe(4)
  1246. })
  1247. it('returns JSON null whether the program returns None or falls off the end', async () => {
  1248. // Python has no `undefined`: an async body that returns None and one that
  1249. // never returns both yield None, so both complete as an exact JSON null.
  1250. // (The worker/TS backend can tell `return undefined` from `return null`;
  1251. // Python cannot, and reporting null for both is the honest rendering.)
  1252. const { runtime } = await setup()
  1253. const explicit = await runtime.run({ program: 'return None', bindings: [] })
  1254. expect(explicit.error).toBeUndefined()
  1255. expect(explicit.value).toBeNull()
  1256. const noReturn = await runtime.run({ program: 'x = 1', bindings: [] })
  1257. expect(noReturn.error).toBeUndefined()
  1258. expect(noReturn.value).toBeNull()
  1259. })
  1260. it('settles with no value on a forged valueless done frame', async () => {
  1261. // The child always sends a value now (return None → JSON null), so a done
  1262. // frame with no value key can only be forged; the host settles it as a
  1263. // value-less completion rather than crashing on the absent field.
  1264. const { runtime } = await setup()
  1265. const result = await runtime.run({
  1266. program: [
  1267. 'import os',
  1268. 'os.write(3, b\'{"type":"done"}\\n\')',
  1269. 'import time',
  1270. 'time.sleep(5)',
  1271. ].join('\n'),
  1272. bindings: [],
  1273. })
  1274. expect(result.error).toBeUndefined()
  1275. expect(result.value).toBeUndefined()
  1276. })
  1277. it('coalesces print arguments into one log line, not per-write fragments', async () => {
  1278. // print("a","b") calls write() per arg/sep/newline; the stream must emit
  1279. // one logical line "a b" so PTC mode's join(newline) does not insert
  1280. // spurious blank lines. Two prints → exactly two entries, no empties.
  1281. const { runtime } = await setup()
  1282. const result = await runtime.run({
  1283. program: ['print("a", "b")', 'print("c")', 'return None'].join('\n'),
  1284. bindings: [],
  1285. })
  1286. expect(result.error).toBeUndefined()
  1287. expect(result.logs).toEqual(['a b', 'c'])
  1288. })
  1289. it('flushes a print with no trailing newline', async () => {
  1290. const { runtime } = await setup()
  1291. const result = await runtime.run({
  1292. program: ['print("partial", end="")', 'return None'].join('\n'),
  1293. bindings: [],
  1294. })
  1295. expect(result.error).toBeUndefined()
  1296. expect(result.logs).toEqual(['partial'])
  1297. })
  1298. it('aggregates a large newline-free native write into one log entry, not one per pipe chunk', async () => {
  1299. // A single `os.write` larger than one pipe read arrives as several Node
  1300. // `data` chunks. `logs` entries are joined with `\n` downstream, so pushing
  1301. // one entry per transport chunk would insert model-visible newlines at
  1302. // arbitrary pipe boundaries inside one native write. Stray capture holds a
  1303. // per-stream residual and admits only on a real `\n`, so a 200 KiB blast
  1304. // with no newline reads back as exactly one entry with no interior breaks.
  1305. const { runtime } = await setup({ maxLogBytes: 300_000 })
  1306. const size = 200_000
  1307. const result = await runtime.run({
  1308. program: ['import os', `os.write(1, b"A" * ${size})`, 'return None'].join('\n'),
  1309. bindings: [],
  1310. })
  1311. expect(result.error).toBeUndefined()
  1312. expect(result.logs).toEqual(['A'.repeat(size)])
  1313. })
  1314. it('splits native output on its own newlines, one entry per line', async () => {
  1315. // The complement of the aggregation case: real newlines in a native write
  1316. // still delimit entries, matching the child's line-granular `log` frames.
  1317. const { runtime } = await setup()
  1318. const result = await runtime.run({
  1319. program: ['import os', 'os.write(1, b"one\\ntwo\\nthree")', 'return None'].join('\n'),
  1320. bindings: [],
  1321. })
  1322. expect(result.error).toBeUndefined()
  1323. expect(result.logs).toEqual(['one', 'two', 'three'])
  1324. })
  1325. it('preserves each native stream order while allowing backend-dependent interleaving', async () => {
  1326. const { runtime } = await setup()
  1327. const result = await runtime.run({
  1328. program: [
  1329. 'import os',
  1330. 'os.write(1, b"stdout-one\\n")',
  1331. 'os.write(2, b"stderr-one\\n")',
  1332. 'os.write(1, b"stdout-two\\n")',
  1333. 'os.write(2, b"stderr-two\\n")',
  1334. 'return None',
  1335. ].join('\n'),
  1336. bindings: [],
  1337. })
  1338. expect(result.error).toBeUndefined()
  1339. expect(result.logs.indexOf('stdout-one')).toBeLessThan(result.logs.indexOf('stdout-two'))
  1340. expect(result.logs.indexOf('stderr-one')).toBeLessThan(result.logs.indexOf('stderr-two'))
  1341. })
  1342. it('bounds a newline-free native flood by the ledger instead of buffering it whole', async () => {
  1343. // A newline-free write far larger than maxLogBytes must not accumulate in
  1344. // the host-side residual: when the pending residual would cross the budget
  1345. // it is admitted (and truncated) immediately, and once the ledger has
  1346. // truncated, later chunks stop buffering entirely. The run still completes
  1347. // and the captured output ends at the truncation marker rather than
  1348. // retaining the whole flood.
  1349. const { runtime } = await setup({ maxLogBytes: 4096 })
  1350. const result = await runtime.run({
  1351. program: ['import os', 'os.write(1, b"A" * 2_000_000)', 'return None'].join('\n'),
  1352. bindings: [],
  1353. })
  1354. expect(result.error).toBeUndefined()
  1355. expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
  1356. // The retained output is bounded by the budget, not the 2 MB flood.
  1357. expect(result.logs.join('').length).toBeLessThan(4096)
  1358. })
  1359. it('bounds a newline-free single-character Python write drip by the fragment cap, not OOM', async () => {
  1360. // The child-side `_LogStream` buffers one fragment per `write` (so
  1361. // `print("x", end="")` does not concatenate quadratically). A newline-free
  1362. // drip of one character per call past a large `maxLogBytes` would otherwise
  1363. // accumulate one list slot (and one str object) per call — 25 M calls =
  1364. // ~25 M slots, which OOMs the host on its own accounting before the byte
  1365. // budget is reached. The stream seals the fragment list past
  1366. // `_PENDING_MAX_CHUNKS` into one joined block (character count unchanged),
  1367. // bounding the live fragment count exactly as the host-side `captureStray`
  1368. // seal does. This drives well past the cap and asserts the run still
  1369. // completes with a truncation marker rather than a MemoryError.
  1370. const { runtime } = await setup({ maxLogBytes: 4096 })
  1371. const result = await runtime.run({
  1372. program: [
  1373. 'import sys',
  1374. 'for _ in range(200_000):',
  1375. ' sys.stdout.write("x")',
  1376. 'return None',
  1377. ].join('\n'),
  1378. bindings: [],
  1379. })
  1380. expect(result.error).toBeUndefined()
  1381. expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
  1382. })
  1383. it('bounds a control-char-dense native residual by serialized cost, not raw length', async () => {
  1384. // A newline-free NUL flood passes the cheap `length + 3` lower bound at a
  1385. // raw length well under the budget, but each NUL serializes to `\u0000` (6
  1386. // bytes), so the true JSON cost is ~6x. The ledger must charge that
  1387. // serialized cost — and `jsonStringCostUpTo` must measure it WITHOUT
  1388. // allocating the escaped copy, so a near-budget line under a large
  1389. // maxLogBytes cannot momentarily allocate a multi-gigabyte `JSON.stringify`
  1390. // result. Under a small budget the residual is truncated once the serialized
  1391. // cost crosses it.
  1392. const { runtime } = await setup({ maxLogBytes: 4096 })
  1393. const result = await runtime.run({
  1394. program: ['import os', 'os.write(1, b"\\x00" * 4000)', 'return None'].join('\n'),
  1395. bindings: [],
  1396. })
  1397. expect(result.error).toBeUndefined()
  1398. expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
  1399. })
  1400. it('rejects an output budget that could breach addressSpaceMb during encode at load', async () => {
  1401. // The child builds, charges, and encodes a `maxLogBytes` log entry or a
  1402. // `maxValueBytes` completion value under RLIMIT_AS, and both trigger on
  1403. // character count against a serialized-byte budget — an astral character is
  1404. // one character but ~4 bytes stored and ~4 encoded, and THREE such copies are
  1405. // live at the peak (the caller's write argument, the slice/join handed to
  1406. // push, and the encode copy), so a budget approaching the address space lets a
  1407. // legitimate near-budget output breach it and die as worker-exit. The
  1408. // incompatible pair is rejected at load: each budget times the worst-case
  1409. // multiple (12) must fit the address space LEFT after the fixed interpreter
  1410. // baseline. Against a 256 MiB address space that leaves 192 MiB budgetable
  1411. // (~16 MiB admissible), so a 50 MB cap is far over; the default caps against
  1412. // 512 MiB are not. Both budgets are gated symmetrically — the value case sets
  1413. // a default-fitting maxLogBytes so the maxValueBytes check is what fires.
  1414. const ctxLog = new Context()
  1415. await expect(ctxLog.plugin(PythonCodeRuntime, { maxLogBytes: 50_000_000, addressSpaceMb: 256 }))
  1416. .rejects.toThrow(/maxLogBytes times the 12x worst-case Unicode expansion must fit/)
  1417. const ctxValue = new Context()
  1418. await expect(ctxValue.plugin(PythonCodeRuntime, { maxValueBytes: 50_000_000, addressSpaceMb: 256 }))
  1419. .rejects.toThrow(/maxValueBytes times the 12x worst-case Unicode expansion must fit/)
  1420. // Discriminates 12 from 8: a 48 MiB maxLogBytes against a 512 MiB address
  1421. // space leaves 448 MiB budgetable. 48*8 = 384 MiB fits (the old 8x multiple
  1422. // wrongly ADMITTED this), but 48*12 = 576 MiB does not. The ~12x peak this
  1423. // guards is the NEWLINE path's single near-budget write — the caller's own
  1424. // string, the line slice, and the encode copy live at once. The settlement
  1425. // flush is no longer the binding case: `flush_line` drops the pending chunks
  1426. // before its push, so it holds two copies, not three.
  1427. const ctxTwelve = new Context()
  1428. await expect(ctxTwelve.plugin(PythonCodeRuntime, { maxLogBytes: 48 * 1024 * 1024, addressSpaceMb: 512 }))
  1429. .rejects.toThrow(/maxLogBytes times the 12x worst-case Unicode expansion must fit/)
  1430. // An addressSpaceMb at or below the interpreter baseline leaves nothing
  1431. // budgetable, so no budget value can pass. It is rejected on its own terms:
  1432. // the budget loop would otherwise report "a limit of -1" (or -2796203 at
  1433. // 32 MiB) while naming maxLogBytes, sending the operator to the wrong knob.
  1434. const ctxBaseline = new Context()
  1435. await expect(ctxBaseline.plugin(PythonCodeRuntime, { addressSpaceMb: 64 }))
  1436. .rejects.toThrow(/addressSpaceMb must exceed the 67108864-byte interpreter baseline/)
  1437. const ctxBelow = new Context()
  1438. await expect(ctxBelow.plugin(PythonCodeRuntime, { addressSpaceMb: 32 }))
  1439. .rejects.toThrow(/addressSpaceMb must exceed the 67108864-byte interpreter baseline/)
  1440. // The default caps against the default 512 MiB address space load.
  1441. const ok = new Context()
  1442. const fiber = await ok.plugin(PythonCodeRuntime, { maxLogBytes: 65536, maxValueBytes: 32768, addressSpaceMb: 512 })
  1443. await fiber.dispose()
  1444. })
  1445. it('bounds an illegal-UTF-8 native residual by its U+FFFD-decoded cost', async () => {
  1446. // Every 0xFF byte is illegal in any UTF-8 sequence, so `toString('utf8')`
  1447. // renders each as U+FFFD (3 serialized bytes). `accrueStrayCost` must charge
  1448. // that 3, not the raw 1: otherwise the newline-free residual grows to a full
  1449. // budget's worth of RAW bytes before flushing — a ~3x undercount that near a
  1450. // large maxLogBytes retains hundreds of MiB then expands toward a ~1 GiB peak
  1451. // in flushStray's concat + toString. Paced single-byte writes (each its own
  1452. // `data` chunk, like the sealing case) expose the sub-chunk accrual: charged
  1453. // at 3 the residual crosses a 3072-byte budget after ~1024 bytes and flushes;
  1454. // charged at 1 it would need ~3072 bytes, so the peak residual triples. The
  1455. // largest merged buffer is the discriminator.
  1456. const realConcat = Buffer.concat.bind(Buffer)
  1457. let maxConcat = 0
  1458. Buffer.concat = (list: readonly Uint8Array[], total?: number): Buffer<ArrayBuffer> => {
  1459. const merged = realConcat(list, total)
  1460. if (merged.length > maxConcat) maxConcat = merged.length
  1461. return merged
  1462. }
  1463. let result: CodeRunResult
  1464. try {
  1465. const { runtime } = await setup({ maxLogBytes: 3072, maxWallMs: 30_000 })
  1466. result = await runtime.run({
  1467. program: [
  1468. 'import os, time',
  1469. // One byte per chunk on every host: a plain yield lets a loaded
  1470. // reader coalesce, and the coalesced chunk is what the bound below
  1471. // measures. The payload stays above the 2048 discriminator, so a
  1472. // raw-byte undercount still flushes the whole residual at EOF.
  1473. 'for _ in range(3200):',
  1474. ' os.write(1, b"\\xff")',
  1475. ' time.sleep(0.001)',
  1476. 'return None',
  1477. ].join('\n'),
  1478. bindings: [],
  1479. })
  1480. } finally {
  1481. Buffer.concat = realConcat
  1482. }
  1483. expect(result.error).toBeUndefined()
  1484. expect(result.logs.at(-1)).toBe(logTruncationMarker(3072))
  1485. // Charged at 3, the residual flushes around 1024 raw bytes; the largest
  1486. // merged buffer stays well under 2048. A raw-byte undercount would let it
  1487. // reach ~3072 before flushing, so 2048 discriminates.
  1488. expect(maxConcat).toBeLessThan(2048)
  1489. // The paced payload costs ~3.2s deterministically, which is above the
  1490. // 5000ms default the local unit entry grants, so the case carries its own
  1491. // bound instead of relying on the lane to widen it.
  1492. }, 20_000)
  1493. it('charges a structurally-valid but illegal UTF-8 sequence its U+FFFD-decoded cost', async () => {
  1494. // A CESU-8 lone surrogate `ED A0 80` is structurally well-formed (a 3-byte
  1495. // lead plus two 0x80–0xBF continuations) but ILLEGAL: `toString('utf8')`
  1496. // renders each of the three bytes as its own U+FFFD (serialized cost 9), not
  1497. // one width-3 character. The newline-free flush trigger weighs the residual
  1498. // through `accrueStrayCost`, which must validate each lead's
  1499. // first-continuation range (ED excludes A0–BF) and charge the true 9 — else a
  1500. // CESU flood undercounts 3x and the residual grows toward a full budget's raw
  1501. // bytes before flushing, the same peak-memory vector as the 0xFF case. The
  1502. // bytes are written one at a time (each its own `data` chunk, no pipe
  1503. // coalescing) and `Buffer.concat` is wrapped to measure the peak residual.
  1504. const realConcat = Buffer.concat.bind(Buffer)
  1505. let maxConcat = 0
  1506. Buffer.concat = (list: readonly Uint8Array[], total?: number): Buffer<ArrayBuffer> => {
  1507. const merged = realConcat(list, total)
  1508. if (merged.length > maxConcat) maxConcat = merged.length
  1509. return merged
  1510. }
  1511. let result: CodeRunResult
  1512. try {
  1513. const { runtime } = await setup({ maxLogBytes: 3072, maxWallMs: 30_000 })
  1514. result = await runtime.run({
  1515. program: [
  1516. 'import os, time',
  1517. 'seq = (0xed, 0xa0, 0x80)',
  1518. // 1100 sequences are 3300 raw bytes, past the 3072-byte budget a
  1519. // raw-byte undercount reaches, so the undercount flushes above the
  1520. // 2048 discriminator instead of only at EOF.
  1521. 'for _ in range(1100):',
  1522. ' for b in seq:',
  1523. ' os.write(1, bytes((b,)))',
  1524. ' time.sleep(0.001)',
  1525. 'return None',
  1526. ].join('\n'),
  1527. bindings: [],
  1528. })
  1529. } finally {
  1530. Buffer.concat = realConcat
  1531. }
  1532. expect(result.error).toBeUndefined()
  1533. expect(result.logs.at(-1)).toBe(logTruncationMarker(3072))
  1534. // Each 3-byte sequence costs 9 (three U+FFFD), so single-byte-paced the
  1535. // residual crosses the 3072 budget after ~342 raw bytes and flushes; the
  1536. // largest merged buffer stays well under 2048. Charging the structural width
  1537. // 3 would need ~1024 raw bytes, tripling the peak past 2048.
  1538. expect(maxConcat).toBeLessThan(2048)
  1539. // The paced payload costs ~3.3s deterministically, which is above the
  1540. // 5000ms default the local unit entry grants, so the case carries its own
  1541. // bound instead of relying on the lane to widen it.
  1542. }, 20_000)
  1543. it('charges a lone surrogate its full six escaped bytes, not three', async () => {
  1544. // A forged `log` frame carrying `\ud800` escapes materializes lone
  1545. // surrogates after JSON.parse. `Buffer.byteLength` of U+FFFD is 3, but
  1546. // ES2019 well-formed `JSON.stringify` emits `\ud800` at 6 bytes, so charging
  1547. // the raw width would admit ~2x the configured budget of serialized bytes
  1548. // (the same family as the NUL-flood undercount, at 2x rather than 6x). The
  1549. // cost walker charges surrogates the full 6, so a flood truncates at budget.
  1550. // Forged on fd 3 because Python stdout will not emit lone surrogates.
  1551. const { runtime } = await setup({ maxLogBytes: 4096 })
  1552. const result = await runtime.run({
  1553. program: [
  1554. 'import os',
  1555. // 1000 \ud800 escapes: charged at the buggy raw width 1000 * 3 = 3000
  1556. // bytes fits under 4096 (wrongly admitted), but the correct serialized
  1557. // width 1000 * 6 = 6000 bytes is over budget — so the ledger must
  1558. // truncate. The count sits in the 683..1365 window where the two
  1559. // chargings disagree, making the test discriminate.
  1560. String.raw`frame = b'{"type":"log","text":"' + b'\\ud800' * 1000 + b'"}\n'`,
  1561. 'os.write(3, frame)',
  1562. 'return None',
  1563. ].join('\n'),
  1564. bindings: [],
  1565. })
  1566. expect(result.error).toBeUndefined()
  1567. expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
  1568. })
  1569. it('drops a second stray line in the same chunk once the first truncated the ledger', async () => {
  1570. // One `os.write` carrying two newline-terminated lines where the first
  1571. // exhausts maxLogBytes: the first line's admit truncates and marks the
  1572. // ledger, and the second line's admit — reached in the same `data` callback
  1573. // — must be the post-truncation no-op. Proves that branch is exercised, so
  1574. // it carries no v8-ignore. Kept to 108 bytes (< the smallest PIPE_BUF, 512 on
  1575. // macOS) so the whole payload lands in ONE atomic write and one `data`
  1576. // callback — the two newlines cannot split across callbacks and leave the
  1577. // branch un-exercised, which would be a hard-to-attribute per-file coverage
  1578. // flake. The first line's 100 bytes already exceed the 64-byte budget, so it truncates.
  1579. const { runtime } = await setup({ maxLogBytes: 64 })
  1580. const result = await runtime.run({
  1581. program: ['import os', 'os.write(1, b"A" * 100 + b"\\nSECOND\\n")', 'return None'].join('\n'),
  1582. bindings: [],
  1583. })
  1584. expect(result.error).toBeUndefined()
  1585. expect(result.logs.at(-1)).toBe(logTruncationMarker(64))
  1586. expect(result.logs.join('\n')).not.toContain('SECOND')
  1587. })
  1588. it('charges a broken multibyte sequence its U+FFFD bytes, split across pipe chunks', async () => {
  1589. // A 3-byte lead (0xE4) whose continuation never arrives — the next byte is a
  1590. // fresh ASCII 'A' — must be costed as U+FFFD (3) for the orphaned lead, not
  1591. // folded into a phantom character. Driven byte-by-byte so the lead and the
  1592. // breaking byte land in separate `data` chunks, exercising accrueStrayCost's
  1593. // cross-chunk broken-sequence branch. The run completes and the bytes are
  1594. // captured (rendered U+FFFD by toString), proving the walk resynchronizes.
  1595. const { runtime } = await setup({ maxLogBytes: 1024 })
  1596. const result = await runtime.run({
  1597. program: [
  1598. 'import os',
  1599. 'os.write(1, b"\\xe4")',
  1600. 'os.sched_yield()',
  1601. 'os.write(1, b"A\\n")',
  1602. 'return None',
  1603. ].join('\n'),
  1604. bindings: [],
  1605. })
  1606. expect(result.error).toBeUndefined()
  1607. expect(result.logs.join('')).toContain('A')
  1608. expect(result.logs.join('')).toContain('�')
  1609. })
  1610. it('charges the exact serialized cost of short-escape and quote/backslash characters', async () => {
  1611. // Exercises every branch of jsonStringCostUpTo's per-character cost: a tab
  1612. // and other C0 controls with short JSON forms (\t etc., 2 bytes), a quote
  1613. // and backslash (2 bytes each), a `\uXXXX` control (6 bytes), a multibyte
  1614. // BMP character (raw UTF-8 width), and plain ASCII. Under a budget large
  1615. // enough to admit it, the line survives verbatim — proving the cost walker
  1616. // does not over- or under-charge and the string round-trips unescaped.
  1617. const { runtime } = await setup({ maxLogBytes: 4096 })
  1618. const result = await runtime.run({
  1619. program: ['import os', String.raw`os.write(1, "\ta\"b\\c\x01é\n".encode("utf-8"))`, 'return None'].join('\n'),
  1620. bindings: [],
  1621. })
  1622. expect(result.error).toBeUndefined()
  1623. expect(result.logs).toEqual(['\ta"b\\c\x01é'])
  1624. })
  1625. it('fails a completion dict with a non-string key as invalid-output (no key coercion)', async () => {
  1626. // json.dumps would coerce {1: "a", "1": "b"} to a single "1" key, silently
  1627. // dropping data. The shape validator rejects it before encoding.
  1628. const { runtime } = await setup()
  1629. const result = await runtime.run({
  1630. program: 'return {1: "first", "1": "second"}',
  1631. bindings: [],
  1632. })
  1633. expect(result.value).toBeUndefined()
  1634. expect(result.error?.kind).toBe('invalid-output')
  1635. expect(result.error?.message).toContain('non-string dict key')
  1636. })
  1637. it('rejects a binding argument with a non-string dict key before dispatch', async () => {
  1638. const { runtime } = await setup()
  1639. let called = false
  1640. const result = await runtime.run({
  1641. program: [
  1642. 'caught = ""',
  1643. 'try:',
  1644. ' await tools.sink({1: "x"})',
  1645. 'except RuntimeError as e:',
  1646. ' caught = str(e)',
  1647. 'return caught',
  1648. ].join('\n'),
  1649. bindings: tools({ sink: async () => { called = true; return null } }),
  1650. })
  1651. expect(result.error).toBeUndefined()
  1652. expect(result.value).toContain('lossless JSON')
  1653. expect(called).toBe(false)
  1654. })
  1655. it('fails a non-JSON completion value as invalid-output (no repr substitution)', async () => {
  1656. // A set is not lossless JSON. The old draft substituted repr(); the seam
  1657. // now requires refusing the run instead.
  1658. const { runtime } = await setup()
  1659. const result = await runtime.run({
  1660. program: 'return {1, 2, 3}',
  1661. bindings: [],
  1662. })
  1663. expect(result.value).toBeUndefined()
  1664. expect(result.error?.kind).toBe('invalid-output')
  1665. expect(result.error?.message).toContain('lossless JSON')
  1666. expect(result.error?.message).toContain('set')
  1667. })
  1668. it('fails a negative-zero completion value as invalid-output (sign bit is lossy over JSON)', async () => {
  1669. // JSON serialization turns -0.0 into 0 (or JS -0), silently changing the
  1670. // sign bit; the canonical lossless-JSON boundary rejects it, so the
  1671. // Python side must too — as a completion and as a binding argument.
  1672. const { runtime } = await setup()
  1673. const completion = await runtime.run({
  1674. program: 'return -0.0',
  1675. bindings: [],
  1676. })
  1677. expect(completion.error?.kind).toBe('invalid-output')
  1678. expect(completion.error?.message).toContain('negative zero')
  1679. const argument = await runtime.run({
  1680. program: [
  1681. 'try:',
  1682. ' await tools.echo(-0.0)',
  1683. ' return "accepted"',
  1684. 'except RuntimeError as e:',
  1685. ' return str(e)',
  1686. ].join('\n'),
  1687. bindings: tools({ echo: async args => args as never }),
  1688. })
  1689. expect(argument.error).toBeUndefined()
  1690. expect(argument.value).toContain('negative zero')
  1691. })
  1692. it('fails a NaN completion value as invalid-output (allow_nan=False)', async () => {
  1693. // json.dumps would happily emit NaN by default, but NaN is not JSON; the
  1694. // bootstrap passes allow_nan=False so it fails as invalid-output.
  1695. const { runtime } = await setup()
  1696. const result = await runtime.run({
  1697. program: 'return float("nan")',
  1698. bindings: [],
  1699. })
  1700. expect(result.error?.kind).toBe('invalid-output')
  1701. })
  1702. it('fails an over-budget completion value as output-limit (child-side check)', async () => {
  1703. const { runtime } = await setup({ maxValueBytes: 64 })
  1704. const result = await runtime.run({
  1705. program: 'return "V" * 5000',
  1706. bindings: [],
  1707. })
  1708. expect(result.value).toBeUndefined()
  1709. expect(result.error?.kind).toBe('output-limit')
  1710. expect(result.error?.message).toContain('exceeded 64 bytes')
  1711. })
  1712. it('meters a control-heavy completion value without materializing its escaped form', async () => {
  1713. // The child's lower bound admits a string by CHARACTER count, then the meter
  1714. // charged what `_dump_string(current).encode()` returned -- building the
  1715. // escaped copy plus its encode. Each NUL escapes to six bytes, so metering a
  1716. // value the budget then REJECTS allocated ~6x the original twice over:
  1717. // measured at 228.9 MiB of peak for a 20M-NUL string, against 19.1 MiB for
  1718. // the counting path that returns the identical 120,000,002 bytes. Past
  1719. // RLIMIT_AS the meter died as `exception: MemoryError`, inverting the
  1720. // `output-limit` this seam promises for an over-budget value.
  1721. //
  1722. // 8M NULs is 8,000,002 raw but 48,000,002 escaped: over the 16 MiB budget
  1723. // only when charged the escaped cost, so this also pins that the cheap
  1724. // character bound alone does not decide the verdict.
  1725. const { runtime } = await setup({ maxValueBytes: 16 * 1024 * 1024, maxWallMs: 60_000 })
  1726. const result = await runtime.run({
  1727. program: 'return "\\x00" * 8_000_000',
  1728. bindings: [],
  1729. })
  1730. expect(result.value).toBeUndefined()
  1731. expect(result.error?.kind).toBe('output-limit')
  1732. }, 90_000)
  1733. it('rejects a wide completion as output-limit before materializing its traversal state', async () => {
  1734. // `[0] * 2000000` sits far above maxValueBytes but well below the frame
  1735. // ceiling. The folded checker must reject it via the pre-enqueue bound —
  1736. // BEFORE pushing two million elements onto the walk — so a small
  1737. // addressSpaceMb does not turn the check itself into an RLIMIT_AS death.
  1738. const { runtime } = await setup({ maxValueBytes: 64, addressSpaceMb: 256, maxWallMs: 15_000 })
  1739. const result = await runtime.run({
  1740. program: 'return [0] * 2000000',
  1741. bindings: [],
  1742. })
  1743. expect(result.value).toBeUndefined()
  1744. expect(result.error?.kind).toBe('output-limit')
  1745. expect(result.error?.message).toContain('exceeded 64 bytes')
  1746. }, 20_000)
  1747. it('rejects a wide dict as output-limit without materializing its items list', async () => {
  1748. // Same pre-enqueue bound on the dict branch: `len(current)` replaces
  1749. // `list(current.items())`, which allocated one tuple per member before the
  1750. // bound could reject the value. Two million entries under a 64-byte cap
  1751. // fits the 256 MiB address space as a dict but not as a dict PLUS a
  1752. // two-million-tuple list.
  1753. const { runtime } = await setup({ maxValueBytes: 64, addressSpaceMb: 256, maxWallMs: 15_000 })
  1754. const result = await runtime.run({
  1755. program: 'return {str(i): 0 for i in range(2000000)}',
  1756. bindings: [],
  1757. })
  1758. expect(result.value).toBeUndefined()
  1759. expect(result.error?.kind).toBe('output-limit')
  1760. expect(result.error?.message).toContain('exceeded 64 bytes')
  1761. }, 20_000)
  1762. it('meters a float completion in the host\'s number spelling', async () => {
  1763. // CPython's repr disagrees with the host's String(number): `1.0` is three
  1764. // bytes here and one there, `1e-07` pads the exponent the host writes as
  1765. // `1e-7`. Both sides meter the SAME budget, so the child must count the
  1766. // bytes the host will receive — otherwise a boundary-sized value is
  1767. // falsely reported as output-limit.
  1768. const { runtime } = await setup({ maxValueBytes: 1 })
  1769. const integral = await runtime.run({ program: 'return 1.0', bindings: [] })
  1770. expect(integral.error).toBeUndefined()
  1771. expect(integral.value).toBe(1)
  1772. const exponent = await setup({ maxValueBytes: 4 })
  1773. const small = await exponent.runtime.run({ program: 'return 1e-7', bindings: [] })
  1774. expect(small.error).toBeUndefined()
  1775. expect(small.value).toBe(1e-7)
  1776. // The spelling is a meter input, not a licence to overshoot: `1.5` is three
  1777. // bytes on both sides and still fails a two-byte budget.
  1778. const tight = await setup({ maxValueBytes: 2 })
  1779. const over = await tight.runtime.run({ program: 'return 1.5', bindings: [] })
  1780. expect(over.error?.kind).toBe('output-limit')
  1781. })
  1782. it('carries floats across the wire in the host\'s number spelling', async () => {
  1783. // The child ENCODES with the same speller it meters with, so the frame the
  1784. // host parses must reproduce every double exactly — including the branches
  1785. // where CPython and ECMAScript disagree (integral floats, sub-1e-6
  1786. // exponents, >= 1e21, and beyond-safe-range integral doubles whose exact
  1787. // digits differ from the shortest round-trip form).
  1788. const { runtime } = await setup()
  1789. const result = await runtime.run({
  1790. program: 'return [1.0, 100.0, 1.5, 0.1, 1e-7, 1e-6, 1e-5, 123.456, -2.5e-8, 1e21, float(2**60), 5e-324, 1.7976931348623157e308]',
  1791. bindings: [],
  1792. })
  1793. expect(result.error).toBeUndefined()
  1794. expect(result.value).toEqual([1, 100, 1.5, 0.1, 1e-7, 1e-6, 1e-5, 123.456, -2.5e-8, 1e21, 2 ** 60, 5e-324, 1.7976931348623157e308])
  1795. })
  1796. it('rejects a forged non-lossless done value host-side as invalid-output', async () => {
  1797. // A forged done frame bypasses the child's _check_done_value. JSON.parse
  1798. // turns 1e400 into Infinity; validateChildFrame no longer scans done.value,
  1799. // so the host's own checkDoneValue must catch the non-lossless number.
  1800. const { runtime } = await setup()
  1801. const result = await runtime.run({
  1802. program: [
  1803. 'import os',
  1804. String.raw`os.write(3, b'{"type":"done","value":1e400}' + b'\n')`,
  1805. 'import time',
  1806. 'time.sleep(5)',
  1807. ].join('\n'),
  1808. bindings: [],
  1809. })
  1810. expect(result.value).toBeUndefined()
  1811. expect(result.error?.kind).toBe('invalid-output')
  1812. expect(result.error?.message).toContain('non-lossless number')
  1813. })
  1814. it('reports a syntax error as an exception without settling with a value', async () => {
  1815. const { runtime } = await setup()
  1816. const result = await runtime.run({
  1817. program: '$$invalid python$$',
  1818. bindings: [],
  1819. })
  1820. expect(result.error?.kind).toBe('exception')
  1821. expect(result.error?.message).toContain('SyntaxError')
  1822. // The parse-time diagnostic must carry the same source label as compile and
  1823. // runtime tracebacks (ast.parse passes filename="<model>"); a stale
  1824. // "<unknown>" label would leak an inconsistent origin to the model.
  1825. expect(result.error?.message).toContain('File \"<model>\"')
  1826. expect(result.value).toBeUndefined()
  1827. })
  1828. it('reports a runtime raise as an exception with the traceback', async () => {
  1829. const { runtime } = await setup()
  1830. const result = await runtime.run({
  1831. program: 'raise ValueError("intentional")',
  1832. bindings: [],
  1833. })
  1834. expect(result.error?.kind).toBe('exception')
  1835. expect(result.error?.message).toContain('ValueError')
  1836. expect(result.error?.message).toContain('intentional')
  1837. })
  1838. it('bounds a deep exception cause chain instead of burning the wall budget formatting it', async () => {
  1839. // A chain thousands of links deep would make the rendering walk and
  1840. // format() linear in its length, consuming maxWallMs. Rendering is capped
  1841. // at 100 links with a marker; the run reports the exception well within
  1842. // budget rather than timing out.
  1843. const { runtime } = await setup({ maxValueBytes: 1024 * 1024, maxWallMs: 20_000 })
  1844. const start = Date.now()
  1845. const result = await runtime.run({
  1846. program: [
  1847. 'err = None',
  1848. 'for i in range(3000):',
  1849. ' try:',
  1850. ' raise ValueError(i) from err',
  1851. ' except ValueError as e:',
  1852. ' err = e',
  1853. 'raise err',
  1854. ].join('\n'),
  1855. bindings: [],
  1856. })
  1857. expect(result.error?.kind).toBe('exception')
  1858. expect(result.error?.message).toContain('exception chain truncated at 100 links')
  1859. expect(Date.now() - start).toBeLessThan(15_000)
  1860. }, 25_000)
  1861. it('bounds an over-cap chain without assigning to the live exception', async () => {
  1862. // The cap used to be applied by severing the over-cap link ON the live
  1863. // exception. An exception class overriding __setattr__ to raise turned that
  1864. // assignment into model code running inside the bootstrap's failure
  1865. // handler; the throw skipped the `done` send that sits after the handler,
  1866. // so the host blocked on fd 3 and reported a maxWallMs timeout instead of
  1867. // the model's own exception. Cutting the chain on the TracebackException
  1868. // COPY touches no model hook, so the marker still appears and the run
  1869. // reports `exception`.
  1870. const { runtime } = await setup({ maxValueBytes: 1024 * 1024, maxWallMs: 15_000 })
  1871. const start = Date.now()
  1872. const result = await runtime.run({
  1873. program: [
  1874. 'class Sealed(Exception):',
  1875. ' def __setattr__(self, name, value):',
  1876. ' raise RuntimeError("live mutation refused")',
  1877. 'err = None',
  1878. 'for i in range(150):',
  1879. ' try:',
  1880. ' raise Sealed(i) from err',
  1881. ' except Sealed as e:',
  1882. ' err = e',
  1883. 'raise err',
  1884. ].join('\n'),
  1885. bindings: [],
  1886. })
  1887. expect(result.error?.kind).toBe('exception')
  1888. expect(result.error?.message).toContain('Sealed')
  1889. expect(result.error?.message).toContain('exception chain truncated at 100 links')
  1890. // The sever attempt is what used to leak: its message must not appear, and
  1891. // the run must settle well inside the wall budget rather than timing out.
  1892. expect(result.error?.message).not.toContain('live mutation refused')
  1893. expect(Date.now() - start).toBeLessThan(10_000)
  1894. }, 20_000)
  1895. it('still sends done when rendering the diagnostic itself raises', async () => {
  1896. // format() reaches the exception's own __str__, so a model class whose
  1897. // __str__ raises can throw from inside the failure handler. CPython's
  1898. // _safe_string absorbs a raising __str__ during formatting, but the
  1899. // fallback must hold for any throw on that path (a raising __repr__ of an
  1900. // argument, a MemoryError under RLIMIT_AS), so the assertion is the
  1901. // invariant that matters: a `done` frame carrying `exception`, never a
  1902. // timeout, and never the failing renderer's own message.
  1903. const { runtime } = await setup({ maxWallMs: 10_000 })
  1904. const result = await runtime.run({
  1905. program: [
  1906. 'class Unprintable(Exception):',
  1907. ' def __str__(self):',
  1908. ' raise RuntimeError("str refused")',
  1909. ' def __repr__(self):',
  1910. ' raise RuntimeError("repr refused")',
  1911. 'raise Unprintable()',
  1912. ].join('\n'),
  1913. bindings: [],
  1914. })
  1915. expect(result.error?.kind).toBe('exception')
  1916. expect(result.error?.message).toContain('Unprintable')
  1917. expect(result.error?.message).not.toContain('str refused')
  1918. expect(result.error?.message).not.toContain('repr refused')
  1919. }, 15_000)
  1920. it('sends done with an inert diagnostic when the whole rendering path raises', async () => {
  1921. // Drive the fallback itself. `TracebackException.format` reads the
  1922. // exception class's `__module__` to decide whether to qualify the name, and
  1923. // a metaclass property can raise there — a throw INSIDE the formatter,
  1924. // reached with no rebinding of anything the bootstrap owns. Without the
  1925. // wrapper it escapes the handler, the `done` send never runs, and the host
  1926. // times out at maxWallMs.
  1927. const { runtime } = await setup({ maxWallMs: 10_000 })
  1928. const result = await runtime.run({
  1929. program: [
  1930. 'class Meta(type):',
  1931. ' @property',
  1932. ' def __module__(cls):',
  1933. ' raise RuntimeError("renderer refused")',
  1934. 'class Hostile(ValueError, metaclass=Meta):',
  1935. ' pass',
  1936. 'raise Hostile("original failure")',
  1937. ].join('\n'),
  1938. bindings: [],
  1939. })
  1940. expect(result.error?.kind).toBe('exception')
  1941. // The inert fallback names the class and a fixed literal; it must not carry
  1942. // the renderer's message, and must not have become a timeout. `__name__` is
  1943. // still a plain str here, so the class name survives.
  1944. expect(result.error?.message).toBe('Hostile: <diagnostic rendering failed>')
  1945. }, 15_000)
  1946. it('falls back to a placeholder class name when __name__ itself raises', async () => {
  1947. // The fallback reads type(exc).__name__, which a metaclass property can
  1948. // hijack. It must neither run that override's failure into the handler nor
  1949. // format a non-str __name__ into the message. The hostile `__module__` is
  1950. // what drives execution into the fallback in the first place.
  1951. const { runtime } = await setup({ maxWallMs: 10_000 })
  1952. const result = await runtime.run({
  1953. program: [
  1954. 'class Meta(type):',
  1955. ' @property',
  1956. ' def __module__(cls):',
  1957. ' raise RuntimeError("renderer refused")',
  1958. ' @property',
  1959. ' def __name__(cls):',
  1960. ' raise RuntimeError("name refused")',
  1961. 'class Nameless(Exception, metaclass=Meta):',
  1962. ' pass',
  1963. 'raise Nameless()',
  1964. ].join('\n'),
  1965. bindings: [],
  1966. })
  1967. expect(result.error?.kind).toBe('exception')
  1968. expect(result.error?.message).toBe('<unknown>: <diagnostic rendering failed>')
  1969. }, 15_000)
  1970. it('reports the real exception when the program rebinds every name the failure path uses', async () => {
  1971. // The bootstrap IS __main__, so `import __main__; __main__._X = ...` reaches
  1972. // any module global a call-time lookup would read. The failure path is the
  1973. // worst place for that: the reporter, the byte cap, the traceback formatter,
  1974. // the settlement flush and the `done` send all run AFTER the `except` block,
  1975. // so a replacement that raises skips the send, leaves the host blocked on
  1976. // fd 3, and the run reports a maxWallMs timeout instead of the model's own
  1977. // exception. Rebind all of them at once; the run must still carry the real
  1978. // ValueError.
  1979. const { runtime } = await setup({ maxWallMs: 10_000 })
  1980. const result = await runtime.run({
  1981. program: [
  1982. 'import __main__',
  1983. 'def boom(*a, **k):',
  1984. ' raise RuntimeError("hijacked")',
  1985. '__main__._SAFE_MODEL_TRACEBACK = boom',
  1986. '__main__._cap_message = boom',
  1987. '__main__._model_traceback = boom',
  1988. '__main__._UNRENDERABLE_DIAGNOSTIC = boom',
  1989. '__main__._LogStream.flush_line = boom',
  1990. // `send_done` writes via LOCALLY-BOUND `_encode_json_plain` +
  1991. // `ProtocolChannel.write_encoded`; rebinding these at call time must not
  1992. // redirect the done frame (a late lookup would be `boom` -> worker-exit).
  1993. '__main__.ProtocolChannel.send_sync = boom',
  1994. '__main__.ProtocolChannel.write_encoded = boom',
  1995. '__main__._encode_json_plain = boom',
  1996. 'raise ValueError("real failure")',
  1997. ].join('\n'),
  1998. bindings: [],
  1999. })
  2000. expect(result.error?.kind).toBe('exception')
  2001. expect(result.error?.message).toContain('ValueError: real failure')
  2002. expect(result.error?.message).not.toContain('hijacked')
  2003. }, 15_000)
  2004. it('still delivers a done frame when a transitive encode name is rebound', async () => {
  2005. // `send_done` binds `_encode_json_plain` and `ProtocolChannel.write_encoded`
  2006. // into locals, but those callables' BODIES still resolve transitive module
  2007. // globals at call time: `_encode_json_plain` reaches `_dump_scalar`/`_dump_string`/
  2008. // `json.dumps`, and `write_encoded` reaches `os.write`. This bootstrap is
  2009. // `__main__`, so rebinding `__main__._dump_scalar` to a raising function makes
  2010. // the error-frame encode throw AFTER the `except` block. `send_done` catches
  2011. // that and writes a fixed literal done frame (kind `exception`) with the
  2012. // LOCALLY-BOUND `_os_write`/`_memoryview`/`_FALLBACK_DONE_FRAME` captured
  2013. // before the program runs, so the host still gets a verdict — the run must be an
  2014. // `exception`, never a `worker-exit`. The real message is lost (the literal
  2015. // carries a fixed `<unrenderable>` text), which is acceptable: the verdict
  2016. // outranks the diagnostic detail.
  2017. const { runtime } = await setup({ maxWallMs: 10_000 })
  2018. const result = await runtime.run({
  2019. program: [
  2020. 'import __main__',
  2021. 'def boom(*a, **k):',
  2022. ' raise RuntimeError("hijacked")',
  2023. '__main__._dump_scalar = boom',
  2024. '__main__.os = boom',
  2025. // The fallback must also survive a rebind of its own primitives.
  2026. '__main__._os_write = boom',
  2027. '__main__._memoryview = boom',
  2028. '__main__._FALLBACK_DONE_FRAME = boom',
  2029. 'raise ValueError("real failure")',
  2030. ].join('\n'),
  2031. bindings: [],
  2032. })
  2033. expect(result.error?.kind).toBe('exception')
  2034. expect(result.error?.kind).not.toBe('worker-exit')
  2035. }, 15_000)
  2036. it('still reports a model exception when the program rebinds BaseException', async () => {
  2037. // `_run`'s outer try/except catches the program's failure and builds a
  2038. // `done` frame. The clause previously used the module-global `BaseException`,
  2039. // which the program (running as `__main__`) can rebind: `__main__.BaseException
  2040. // = RuntimeError` makes the `except BaseException` resolve to `RuntimeError`,
  2041. // so a subsequent `ValueError` does not match and escapes `_run` with no
  2042. // `done` frame — misreporting the run as a `worker-exit`. The exception class
  2043. // is now bound into a `_run` LOCAL before the program runs, so the rebind
  2044. // cannot change which class the clause catches; the run must still report an
  2045. // `exception`, not a `worker-exit`.
  2046. const { runtime } = await setup({ maxWallMs: 10_000 })
  2047. const result = await runtime.run({
  2048. program: [
  2049. 'import __main__',
  2050. '__main__.BaseException = RuntimeError',
  2051. 'raise ValueError("real failure")',
  2052. ].join('\n'),
  2053. bindings: [],
  2054. })
  2055. expect(result.error?.kind).toBe('exception')
  2056. expect(result.error?.kind).not.toBe('worker-exit')
  2057. }, 15_000)
  2058. it('still reports the exception when BaseException and the traceback reporter are rebound together', async () => {
  2059. // The two rebind families compose: `__main__.BaseException = ValueError`
  2060. // must not change which class the `_run` catch resolves (it is a pre-program
  2061. // local), and a rebound reporter (`_SAFE_MODEL_TRACEBACK`/`_cap_message`/
  2062. // `_model_traceback`/`_UNRENDERABLE_DIAGNOSTIC`) must not break the done
  2063. // frame — `safe_model_traceback` holds its primitives as import-time closure
  2064. // cells. A `KeyError` (not a `ValueError` subclass) escapes a catch that
  2065. // resolves to the rebound class, so without the local binding the run would
  2066. // misreport as `worker-exit`; with it, the run reports the exception and the
  2067. // fallback reporter still produces the fixed literal.
  2068. const { runtime } = await setup({ maxWallMs: 10_000 })
  2069. const result = await runtime.run({
  2070. program: [
  2071. 'import __main__',
  2072. 'def boom(*a, **k):',
  2073. ' raise RuntimeError("hijacked")',
  2074. '__main__.BaseException = ValueError',
  2075. '__main__._SAFE_MODEL_TRACEBACK = boom',
  2076. '__main__._cap_message = boom',
  2077. '__main__._model_traceback = boom',
  2078. '__main__._UNRENDERABLE_DIAGNOSTIC = boom',
  2079. 'raise KeyError("real failure")',
  2080. ].join('\n'),
  2081. bindings: [],
  2082. })
  2083. expect(result.error?.kind).toBe('exception')
  2084. expect(result.error?.kind).not.toBe('worker-exit')
  2085. }, 15_000)
  2086. it('rejects an fd-3 frame whose raw length exceeds the parse cap before joining it', async () => {
  2087. // The 64 MiB frame parse cap bounds the RAW frame bytes, not the decoded
  2088. // structure; a compact wide frame near that ceiling could decode to far
  2089. // more host memory. The unframed-buffer counter is checked against
  2090. // FRAME_PARSE_CAP_BYTES BEFORE the Buffer.concat join, so an oversized
  2091. // frame is dropped at one copy of its wire bytes instead of being fully
  2092. // joined (a second copy) and only then discarded in the line loop — the
  2093. // peak-memory doubling the pre-join check exists to prevent. Fail-before:
  2094. // without the check the frame is joined whole and parsed (its log text
  2095. // admitted, truncating the ledger), and the run completes normally.
  2096. const { runtime } = await setup({ maxWallMs: 60_000 })
  2097. const result = await runtime.run({
  2098. program: [
  2099. 'import os',
  2100. // One frame just past the 64 MiB parse cap.
  2101. 'os.write(3, b"{\\"type\\":\\"log\\",\\"text\\":\\"" + b"a" * (65 * 1024 * 1024) + b"\\"}\\n")',
  2102. 'return "done"',
  2103. ].join('\n'),
  2104. bindings: [],
  2105. })
  2106. expect(result.error?.kind).toBe('worker-exit')
  2107. expect(result.error?.message).toContain('protocol frame exceeded')
  2108. }, 90_000)
  2109. it('caps an oversized rejection diagnostic so an invalid completion stays invalid-output', async () => {
  2110. // _done_with_value caps its rejection diagnostic through _cap_message: a
  2111. // hostile class name (huge type(value).__name__) would otherwise push the
  2112. // done frame past the host's 64 MiB parse cap, misreporting an
  2113. // invalid-output run as a worker-exit. The diagnostic is capped to the
  2114. // value budget, so the frame always crosses the parser.
  2115. const { runtime } = await setup({ maxWallMs: 60_000 })
  2116. const result = await runtime.run({
  2117. program: [
  2118. 'return type("N" * (70 * 1024 * 1024), (), {})()',
  2119. ].join('\n'),
  2120. bindings: [],
  2121. })
  2122. expect(result.error?.kind).toBe('invalid-output')
  2123. expect(result.error?.kind).not.toBe('worker-exit')
  2124. }, 90_000)
  2125. it('appends a flushed unterminated line to the next entry without a fake newline', async () => {
  2126. // An explicit flush of an unterminated line (print(..., end='', flush=True))
  2127. // used to push a full log frame, so the following print() landed in a
  2128. // SECOND entry and logs.join('\n') rendered 'a\nb' for what the program
  2129. // printed as one line. The flush frame now carries `open: true` and the
  2130. // host appends the next frame to the same entry.
  2131. const { runtime } = await setup()
  2132. const result = await runtime.run({
  2133. program: [
  2134. "print('a', end='', flush=True)",
  2135. "print('b')",
  2136. 'return "done"',
  2137. ].join('\n'),
  2138. bindings: [],
  2139. })
  2140. expect(result.error).toBeUndefined()
  2141. expect(result.logs).toEqual(['ab'])
  2142. }, 15_000)
  2143. it('keeps a SEALED open hold when the run ends with it still open', async () => {
  2144. // The finish-residual's sealed side: an open hold past MAX_PENDING_CHUNKS
  2145. // lands in openSealed, and the run ends without a closing frame — finish()
  2146. // must commit the SEALED prefix, not only the current fragments.
  2147. const { runtime } = await setup({ maxLogBytes: 65536 })
  2148. const result = await runtime.run({
  2149. program: [
  2150. 'import os',
  2151. "os.write(3, b'{\"type\":\"log\",\"text\":\"x\",\"open\":true}\\n')",
  2152. 'for _ in range(3000):',
  2153. " os.write(3, b'{\"type\":\"log\",\"text\":\"a\",\"open\":true}\\n')",
  2154. 'return "done"',
  2155. ].join('\n'),
  2156. bindings: [],
  2157. })
  2158. expect(result.error).toBeUndefined()
  2159. expect(result.logs).toEqual(['x' + 'a'.repeat(3000)])
  2160. }, 15_000)
  2161. it('keeps a flushed unterminated line when the run ends with it still open', async () => {
  2162. // The settlement flush pushes the residual with `open: true`; finish()
  2163. // admits it so a program that commits a partial line and returns does not
  2164. // lose it from logs.
  2165. const { runtime } = await setup()
  2166. const result = await runtime.run({
  2167. program: [
  2168. "print('committed', end='', flush=True)",
  2169. 'return "done"',
  2170. ].join('\n'),
  2171. bindings: [],
  2172. })
  2173. expect(result.error).toBeUndefined()
  2174. expect(result.logs).toEqual(['committed'])
  2175. }, 15_000)
  2176. it('skips the hold for a zero-content open continuation', async () => {
  2177. // An empty open continuation bills 0 and is NOT pushed into the held
  2178. // fragment array (an empty fragment contributes nothing to the merged
  2179. // entry, and holding it would let a forged empty-open flood grow host
  2180. // memory without touching the ledger).
  2181. const { runtime } = await setup({ maxLogBytes: 64 })
  2182. const result = await runtime.run({
  2183. program: [
  2184. 'import os',
  2185. "os.write(3, b'{\"type\":\"log\",\"text\":\"x\",\"open\":true}\\n')",
  2186. "os.write(3, b'{\"type\":\"log\",\"text\":\"\",\"open\":true}\\n')",
  2187. "os.write(3, b'{\"type\":\"log\",\"text\":\"y\"}\\n')",
  2188. 'return "done"',
  2189. ].join('\n'),
  2190. bindings: [],
  2191. })
  2192. expect(result.error).toBeUndefined()
  2193. expect(result.logs).toEqual(['xy'])
  2194. }, 15_000)
  2195. it('seals the open hold past MAX_PENDING_CHUNKS without changing the merged entry', async () => {
  2196. // A budget-sized single-character open flood would otherwise accumulate
  2197. // thousands of fragment array slots (each a slot plus string header, ~30x
  2198. // overhead the byte cap cannot see). The hold seals into one block past
  2199. // MAX_PENDING_CHUNKS; the merged entry is byte-identical.
  2200. const { runtime } = await setup({ maxLogBytes: 65536 })
  2201. const result = await runtime.run({
  2202. program: [
  2203. 'import os',
  2204. "os.write(3, b'{\"type\":\"log\",\"text\":\"x\",\"open\":true}\\n')",
  2205. // 3000 single-character open continuations (over MAX_PENDING_CHUNKS).
  2206. 'for _ in range(3000):',
  2207. " os.write(3, b'{\"type\":\"log\",\"text\":\"a\",\"open\":true}\\n')",
  2208. "os.write(3, b'{\"type\":\"log\",\"text\":\"y\"}\\n')",
  2209. 'return "done"',
  2210. ].join('\n'),
  2211. bindings: [],
  2212. })
  2213. expect(result.error).toBeUndefined()
  2214. expect(result.logs).toEqual(['x' + 'a'.repeat(3000) + 'y'])
  2215. }, 15_000)
  2216. it('bounds a forged open-frame flood against the log budget', async () => {
  2217. // The open hold must be bounded by the ledger: without the exact-cost check
  2218. // a forged open flood would grow the held fragment without touching
  2219. // logBudget — unbounded host retention under a small budget. The flood now
  2220. // truncates to the marker like any over-budget log traffic.
  2221. const { runtime } = await setup({ maxLogBytes: 64 })
  2222. const result = await runtime.run({
  2223. program: [
  2224. 'import os',
  2225. // 2000 forged open frames, each under the frame parse cap.
  2226. 'for _ in range(2000):',
  2227. " os.write(3, b'{\"type\":\"log\",\"text\":\"a\",\"open\":true}\\n')",
  2228. 'return "done"',
  2229. ].join('\n'),
  2230. bindings: [],
  2231. })
  2232. expect(result.error).toBeUndefined()
  2233. expect(result.logs).toEqual(['a'.repeat(60), logTruncationMarker(64)])
  2234. }, 15_000)
  2235. it('commits a sealed open hold before the truncation marker', async () => {
  2236. // The sealed variant of the prefix-commit case: an open flood past
  2237. // MAX_PENDING_CHUNKS lands in openSealed, then an over-budget line
  2238. // truncates — truncateLogs must commit the SEALED prefix (not only the
  2239. // current fragments) before the marker.
  2240. const { runtime } = await setup({ maxLogBytes: 65536 })
  2241. const result = await runtime.run({
  2242. program: [
  2243. 'import os',
  2244. "os.write(3, b'{\"type\":\"log\",\"text\":\"x\",\"open\":true}\\n')",
  2245. // 3000 single-character open continuations seal the hold, then a
  2246. // forged over-budget open frame trips the ledger: truncateLogs must
  2247. // commit the SEALED prefix before the marker.
  2248. 'for _ in range(3000):',
  2249. " os.write(3, b'{\"type\":\"log\",\"text\":\"a\",\"open\":true}\\n')",
  2250. "os.write(3, ('{\"type\":\"log\",\"text\":\"' + 'z' * 70000 + '\",\"open\":true}\\n').encode())",
  2251. 'return "done"',
  2252. ].join('\n'),
  2253. bindings: [],
  2254. })
  2255. expect(result.error).toBeUndefined()
  2256. expect(result.logs[0]).toBe('x' + 'a'.repeat(3000))
  2257. expect(result.logs[result.logs.length - 1]).toBe(logTruncationMarker(65536))
  2258. }, 15_000)
  2259. it('commits a flushed open prefix before the truncation marker', async () => {
  2260. // A flushed unterminated line is billed and committed; when a later
  2261. // over-budget write truncates, the committed prefix must appear BEFORE the
  2262. // marker — the ledger charged for it, so it cannot vanish.
  2263. const { runtime } = await setup({ maxLogBytes: 64 })
  2264. const result = await runtime.run({
  2265. program: [
  2266. "print('committed', end='', flush=True)",
  2267. "print('x' * 100)",
  2268. 'return "done"',
  2269. ].join('\n'),
  2270. bindings: [],
  2271. })
  2272. expect(result.error).toBeUndefined()
  2273. expect(result.logs).toEqual(['committed', logTruncationMarker(64)])
  2274. }, 15_000)
  2275. it('drops a forged fd-3 frame with illegal UTF-8 instead of accepting a mangled value', async () => {
  2276. // toString('utf8') would replace the illegal 0xFF with U+FFFD, so a forged
  2277. // done frame could land a corrupted completion value; the fatal decode
  2278. // throws and the frame is dropped. The program's real return still settles
  2279. // the run with the honest value.
  2280. const { runtime } = await setup()
  2281. const result = await runtime.run({
  2282. program: [
  2283. 'import os',
  2284. "os.write(3, b'{\"type\":\"done\",\"value\":\"bad' + bytes([0xFF]) + b'\"}\\n')",
  2285. 'return "ok"',
  2286. ].join('\n'),
  2287. bindings: [],
  2288. })
  2289. expect(result.error).toBeUndefined()
  2290. expect(result.value).toBe('ok')
  2291. }, 15_000)
  2292. it('no-ops a closing frame once an open flood already truncated the ledger', async () => {
  2293. // The closing-frame branch's post-truncation arm: an open flood exhausts
  2294. // the ledger (logsTruncated set, marker pushed), then a closing frame
  2295. // arrives — it must be a no-op, not append content past the marker.
  2296. const { runtime } = await setup({ maxLogBytes: 64 })
  2297. const result = await runtime.run({
  2298. program: [
  2299. 'import os',
  2300. 'for _ in range(2000):',
  2301. " os.write(3, b'{\"type\":\"log\",\"text\":\"a\",\"open\":true}\\n')",
  2302. "os.write(3, b'{\"type\":\"log\",\"text\":\"b\"}\\n')",
  2303. 'return "done"',
  2304. ].join('\n'),
  2305. bindings: [],
  2306. })
  2307. expect(result.error).toBeUndefined()
  2308. expect(result.logs).toEqual(['a'.repeat(60), logTruncationMarker(64)])
  2309. }, 15_000)
  2310. it('bills a merged open entry once, not per fragment', async () => {
  2311. // A merged entry's wire cost is billed ONCE, split across its fragments
  2312. // (first fragment pays quotes+separator, continuations pay only content).
  2313. // Under maxLogBytes: 64, 16 single-character flushes merge to one 16-char
  2314. // entry (2 quotes + 16 content + 1 separator = 19), which fits; per-
  2315. // fragment billing (each charged quotes+separator, ~4 bytes) would truncate
  2316. // at 16 x 4 = 64.
  2317. const { runtime } = await setup({ maxLogBytes: 64 })
  2318. const result = await runtime.run({
  2319. program: [
  2320. 'for _ in range(16):',
  2321. " print('x', end='', flush=True)",
  2322. "print('')",
  2323. 'return "done"',
  2324. ].join('\n'),
  2325. bindings: [],
  2326. })
  2327. expect(result.error).toBeUndefined()
  2328. expect(result.logs).toEqual(['x'.repeat(16)])
  2329. }, 15_000)
  2330. it('admits a compliant merged entry whose closing frame fits the remaining budget', async () => {
  2331. // The review's arithmetic check: print('a'*30, flush); print('b'*25) under
  2332. // maxLogBytes: 64 has a merged wire cost of 2 quotes + 55 content + 1
  2333. // separator = 58 <= 63, so it MUST be admitted as one entry. The earlier
  2334. // cap math (logBudget - openCost) made the closing frame's walk see a
  2335. // negative cap and truncate a compliant entry.
  2336. const { runtime } = await setup({ maxLogBytes: 64 })
  2337. const result = await runtime.run({
  2338. program: [
  2339. "print('a' * 30, end='', flush=True)",
  2340. "print('b' * 25)",
  2341. 'return "done"',
  2342. ].join('\n'),
  2343. bindings: [],
  2344. })
  2345. expect(result.error).toBeUndefined()
  2346. expect(result.logs).toEqual(['a'.repeat(30) + 'b'.repeat(25)])
  2347. }, 15_000)
  2348. it('rejects an open frame that would overflow the ledger by one byte', async () => {
  2349. // The review's arithmetic check: an open frame whose full JSON cost is 63
  2350. // (maxLogBytes: 64 -> ledger 63) must be rejected by the first-fragment
  2351. // cap logBudget - 1 (62), not admitted with a bill of 64 that pushes the
  2352. // ledger negative. The frame is FORGED on fd 3 so the child ledger cannot
  2353. // truncate first: a reverted cap of logBudget (63) would admit the frame,
  2354. // hold it, and flush it at settlement, so the marker assertion fails.
  2355. const { runtime } = await setup({ maxLogBytes: 64 })
  2356. const result = await runtime.run({
  2357. program: [
  2358. 'import os',
  2359. "os.write(3, ('{\"type\":\"log\",\"text\":\"' + 'x' * 61 + '\",\"open\":true}\\n').encode())",
  2360. 'return "done"',
  2361. ].join('\n'),
  2362. bindings: [],
  2363. })
  2364. expect(result.error).toBeUndefined()
  2365. expect(result.logs).toEqual([logTruncationMarker(64)])
  2366. }, 15_000)
  2367. it('bills the closing frame as the merged tail under an exact-fit budget', async () => {
  2368. // The child's split billing: a 30-char open + a 30-char closing frame cost
  2369. // 2 + 60 + 1 = 63 = ledger 63 exactly; the closing frame must be billed as
  2370. // the merged tail (content only), not as a fresh entry (which would
  2371. // double-charge the quotes+separator and truncate an exact-fit entry).
  2372. const { runtime } = await setup({ maxLogBytes: 64 })
  2373. const result = await runtime.run({
  2374. program: [
  2375. "print('a' * 30, end='', flush=True)",
  2376. "print('b' * 30)",
  2377. 'return "done"',
  2378. ].join('\n'),
  2379. bindings: [],
  2380. })
  2381. expect(result.error).toBeUndefined()
  2382. expect(result.logs).toEqual(['a'.repeat(30) + 'b'.repeat(30)])
  2383. }, 15_000)
  2384. it('does not over-reject an exact-fit closing line while an open entry accumulates', async () => {
  2385. // The write-path pre-check's cheap bound used +3 (quotes + separator) even
  2386. // while an open entry was accumulating, so an exact-fit merged TAIL was
  2387. // truncated. The recipe below goes through the SCAN pre-check (the
  2388. // newline-terminated write arrives with an empty pending buffer, so the
  2389. // buffered-chunks branch is skipped): 'a'*29 flush bills 32 (ledger 31
  2390. // left), then one write of 'b'*30 + newline merges 30 more chars whose
  2391. // cheap bound is 30, not 33 — the +3 form saw 30 + 3 = 33 > 31, sliced to
  2392. // a budget prefix, and pushed past the ledger, emitting the marker for a
  2393. // line that fits (merged cost 2 + 59 + 1 = 62 <= 63).
  2394. const { runtime } = await setup({ maxLogBytes: 64 })
  2395. const result = await runtime.run({
  2396. program: [
  2397. 'import sys',
  2398. "sys.stdout.write('a' * 29)",
  2399. 'sys.stdout.flush()',
  2400. "sys.stdout.write('b' * 30 + chr(10))",
  2401. 'return "done"',
  2402. ].join('\n'),
  2403. bindings: [],
  2404. })
  2405. expect(result.error).toBeUndefined()
  2406. expect(result.logs).toEqual(['a'.repeat(29) + 'b'.repeat(30)])
  2407. }, 15_000)
  2408. it('rejects a new open entry once the ledger has only two bytes left', async () => {
  2409. // The jsonStringCostUpTo sub-2-byte guard: forged open frames drive the
  2410. // host ledger down to 1 byte, then a new open entry's first-fragment cap
  2411. // (logBudget - 1 = 0) trips the guard and truncates.
  2412. const { runtime } = await setup({ maxLogBytes: 64 })
  2413. const result = await runtime.run({
  2414. program: [
  2415. 'import os',
  2416. "os.write(3, ('{\"type\":\"log\",\"text\":\"' + 'a' * 28 + '\",\"open\":true}\\n').encode())",
  2417. "os.write(3, ('{\"type\":\"log\",\"text\":\"' + 'a' * 31 + '\"}\\n').encode())",
  2418. "os.write(3, b'{\"type\":\"log\",\"text\":\"x\",\"open\":true}\\n')",
  2419. 'return "done"',
  2420. ].join('\n'),
  2421. bindings: [],
  2422. })
  2423. expect(result.error).toBeUndefined()
  2424. expect(result.logs).toEqual(['a'.repeat(59), logTruncationMarker(64)])
  2425. }, 15_000)
  2426. it('truncates when the closing frame of a merged entry overflows the budget', async () => {
  2427. // The merged entry's billed-once cost: an open fragment that nearly
  2428. // exhausts the budget, then a closing frame whose content no longer fits —
  2429. // the closing frame's exact-cost walk trips and the marker replaces the
  2430. // entry, exactly like any other over-budget log traffic.
  2431. const { runtime } = await setup({ maxLogBytes: 64 })
  2432. const result = await runtime.run({
  2433. program: [
  2434. "print('x' * 40, end='', flush=True)",
  2435. "print('y' * 40)",
  2436. 'return "done"',
  2437. ].join('\n'),
  2438. bindings: [],
  2439. })
  2440. expect(result.error).toBeUndefined()
  2441. expect(result.logs).toEqual(['x'.repeat(40), logTruncationMarker(64)])
  2442. }, 15_000)
  2443. it('keeps a float completion exact when the program mutates the decimal context', async () => {
  2444. // The float encoder's Decimal(repr(value)).normalize() used the process
  2445. // GLOBAL decimal context: a legitimate program setting
  2446. // `getcontext().prec = 2` silently rounded the completion value's digits,
  2447. // and `traps[Inexact] = True` made the encode raise, misclassifying a
  2448. // successful run as an exception. A fixed module-level Context(prec=28)
  2449. // makes the spelling decision context-independent.
  2450. const { runtime } = await setup()
  2451. const result = await runtime.run({
  2452. program: [
  2453. 'from decimal import getcontext',
  2454. 'getcontext().prec = 2',
  2455. 'getcontext().traps[__import__("decimal").Inexact] = True',
  2456. 'return 1.2345678901234567',
  2457. ].join('\n'),
  2458. bindings: [],
  2459. })
  2460. expect(result.error).toBeUndefined()
  2461. expect(result.value).toBe(1.2345678901234567)
  2462. }, 15_000)
  2463. it('bounds an over-cap exception-group nesting on the copy', async () => {
  2464. // Exception groups link through `exceptions`, not the cause/context
  2465. // dunders, so the cap has to count that edge too — otherwise a deeply
  2466. // nested group walks past the bound the marker claims to enforce.
  2467. const { runtime } = await setup({ maxValueBytes: 1024 * 1024, maxWallMs: 15_000 })
  2468. const result = await runtime.run({
  2469. program: [
  2470. 'import sys',
  2471. // ExceptionGroup is a 3.11+ builtin; on 3.10 the NameError is the
  2472. // failure mode being probed, so skip to keep the assertion meaningful.
  2473. 'if sys.version_info < (3, 11):',
  2474. ' raise ValueError("skip-old <model>")',
  2475. 'group = ValueError("leaf")',
  2476. 'for i in range(150):',
  2477. ' group = ExceptionGroup(f"g{i}", [group])',
  2478. 'raise group',
  2479. ].join('\n'),
  2480. bindings: [],
  2481. })
  2482. expect(result.error?.kind).toBe('exception')
  2483. // The version guard skips on Python < 3.11 (ExceptionGroup is a 3.11+
  2484. // builtin) with a distinct message; the truncation assertion applies on
  2485. // 3.11+ where the group nesting is what is being probed.
  2486. expect(result.error?.message).toMatch(/exception chain truncated at 100 links|skip-old/)
  2487. }, 20_000)
  2488. it('filters every bootstrap frame from the traceback of an uncaught binding rejection', async () => {
  2489. // A rejection re-raised by the bootstrap's dispatch adds bootstrap frames
  2490. // AFTER the model's own; only <model> frames may reach model-visible,
  2491. // durable output — a bootstrap.py path would leak host absolutes and make
  2492. // transcripts machine-dependent.
  2493. const { runtime } = await setup()
  2494. const result = await runtime.run({
  2495. program: 'await tools.boom({})',
  2496. bindings: tools({ boom: async () => { throw new Error('exploded') } }),
  2497. })
  2498. expect(result.error?.kind).toBe('exception')
  2499. expect(result.error?.message).toContain('exploded')
  2500. expect(result.error?.message).toContain('<model>')
  2501. expect(result.error?.message).not.toContain('bootstrap.py')
  2502. })
  2503. it('renders a non-Error thrown value from a host binding as its String form', async () => {
  2504. const { runtime } = await setup()
  2505. const result = await runtime.run({
  2506. program: [
  2507. 'caught = ""',
  2508. 'try:',
  2509. ' await tools.failRaw({})',
  2510. 'except RuntimeError as e:',
  2511. ' caught = str(e)',
  2512. 'return caught',
  2513. ].join('\n'),
  2514. bindings: tools({
  2515. failRaw: async () => { throw 'raw-nope' },
  2516. }),
  2517. })
  2518. expect(result.error).toBeUndefined()
  2519. expect(result.value).toContain('raw-nope')
  2520. })
  2521. it('reassembles a frame split across writes behind a completed one', async () => {
  2522. // One os.write carrying "<frame>\n<partial...>" leaves a non-empty
  2523. // residual after the newline loop; the tail must survive until its own
  2524. // newline arrives and then parse as a normal frame.
  2525. const { runtime } = await setup()
  2526. const result = await runtime.run({
  2527. program: [
  2528. 'import os, json',
  2529. 'head = json.dumps({"type":"log","text":"first"}).encode()',
  2530. 'tail = json.dumps({"type":"log","text":"second"}).encode()',
  2531. 'import time',
  2532. 'os.write(3, head + b"\\n" + tail[:5])',
  2533. 'time.sleep(0.2)',
  2534. 'os.write(3, tail[5:] + b"\\n")',
  2535. 'return "ok"',
  2536. ].join('\n'),
  2537. bindings: [],
  2538. })
  2539. expect(result.error).toBeUndefined()
  2540. expect(result.value).toBe('ok')
  2541. expect(result.logs).toContain('first')
  2542. expect(result.logs).toContain('second')
  2543. })
  2544. it('raises the declared errorClass with the member name on rejection', async () => {
  2545. // PTC mode declares { name: ToolCallError, memberNameProperty: toolName };
  2546. // a host rejection must surface as that class, carrying the failed tool.
  2547. const { runtime } = await setup()
  2548. const result = await runtime.run({
  2549. program: [
  2550. 'caught = ""',
  2551. 'try:',
  2552. ' await tools.fail({})',
  2553. 'except ToolCallError as e:',
  2554. ' caught = f"{type(e).__name__}:{e.toolName}:{e}"',
  2555. 'return caught',
  2556. ].join('\n'),
  2557. bindings: [{
  2558. global: 'tools',
  2559. functions: { fail: async () => { throw new Error('typed-nope') } },
  2560. errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' },
  2561. }],
  2562. })
  2563. expect(result.error).toBeUndefined()
  2564. expect(result.value).toBe('ToolCallError:fail:typed-nope')
  2565. })
  2566. it('keeps the declared error class catching when Exception and setattr are rebound', async () => {
  2567. // _make_error_class's minted __init__ def-time captures Exception and
  2568. // setattr, so a program rebinding __main__.Exception/__main__.setattr
  2569. // cannot break the rejection constructor: `except ToolCallError` must still
  2570. // catch and read the member property.
  2571. const { runtime } = await setup()
  2572. const result = await runtime.run({
  2573. program: [
  2574. 'import __main__',
  2575. 'def boom(*a, **k):',
  2576. ' raise RuntimeError("hijacked")',
  2577. '__main__.Exception = boom',
  2578. '__main__.setattr = boom',
  2579. 'caught = ""',
  2580. 'try:',
  2581. ' await tools.fail({})',
  2582. 'except ToolCallError as e:',
  2583. ' caught = f"{type(e).__name__}:{e.toolName}"',
  2584. 'return caught',
  2585. ].join('\n'),
  2586. bindings: [{
  2587. global: 'tools',
  2588. functions: { fail: async () => { throw new Error('typed-nope') } },
  2589. errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' },
  2590. }],
  2591. })
  2592. expect(result.error).toBeUndefined()
  2593. expect(result.value).toBe('ToolCallError:fail')
  2594. }, 15_000)
  2595. it('runs when errorClass metadata is exposed through one-read getters', async () => {
  2596. // Validation reads errorClass.name and errorClass.memberNameProperty, and
  2597. // the ORIGINAL object used to ride along to the boot frame, whose
  2598. // JSON.stringify re-read it after validation: a getter that throws or
  2599. // changes on a second read turned the seam-misuse rejection into a
  2600. // worker-exit (or injected a different name than validation approved).
  2601. // The snapshot reads each field exactly once into a plain copy, so a
  2602. // getter that only tolerates one read must boot and run cleanly.
  2603. let nameReads = 0
  2604. let memberReads = 0
  2605. const errorClass = {
  2606. get name(): string {
  2607. nameReads += 1
  2608. if (nameReads > 1) throw new Error(`errorClass.name read ${nameReads} times`)
  2609. return 'ToolCallError'
  2610. },
  2611. get memberNameProperty(): string {
  2612. memberReads += 1
  2613. if (memberReads > 1) throw new Error(`errorClass.memberNameProperty read ${memberReads} times`)
  2614. return 'toolName'
  2615. },
  2616. }
  2617. const { runtime } = await setup()
  2618. const result = await runtime.run({
  2619. program: 'return "ok"',
  2620. bindings: [{ global: 'tools', functions: {}, errorClass }],
  2621. })
  2622. expect(result.error).toBeUndefined()
  2623. expect(result.value).toBe('ok')
  2624. expect(nameReads).toBe(1)
  2625. expect(memberReads).toBe(1)
  2626. }, 15_000)
  2627. it('runs when the binding global is exposed through a one-read getter', async () => {
  2628. // Validation reads namespace.global several times (identifier check, map
  2629. // key, claim, boot frame), and the map key came from a fresh read each
  2630. // time: a getter returning a different name on a later read injected a
  2631. // global validation never approved, and the program referencing the
  2632. // approved name died with NameError. Snapshotting reads it exactly once,
  2633. // so the child must receive the name the program was written against.
  2634. let globalReads = 0
  2635. const namespace = {
  2636. get global(): string {
  2637. globalReads += 1
  2638. return globalReads === 1 ? 'tools' : 'evil'
  2639. },
  2640. functions: { echo: async (args: unknown) => args as CodeJsonValue },
  2641. }
  2642. const { runtime } = await setup()
  2643. const result = await runtime.run({
  2644. program: 'return await tools.echo(41)',
  2645. bindings: [namespace],
  2646. })
  2647. expect(result.error).toBeUndefined()
  2648. expect(result.value).toBe(41)
  2649. expect(globalReads).toBe(1)
  2650. }, 15_000)
  2651. it('rejects an errorClass name colliding with its namespace global at the seam', async () => {
  2652. const { runtime } = await setup()
  2653. await expect(runtime.run({
  2654. program: 'return 1',
  2655. bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'tools', memberNameProperty: 'toolName' } }],
  2656. })).rejects.toThrow(/collides with another injected global/)
  2657. })
  2658. it('rejects a namespace global colliding with a runtime-owned name at the seam', async () => {
  2659. // `__dsh_main__` passes the identifier check, but exec()ing the generated
  2660. // wrapper would silently overwrite the binding after injection. `console`
  2661. // is the WORKER backend's slot — refused here too so a namespace list
  2662. // valid on one backend is valid on all.
  2663. const { runtime } = await setup()
  2664. // `__debug__` is refused for a different reason than a collision: CPython
  2665. // compiles a bare `__debug__` reference to the constant True and refuses to
  2666. // assign the name at compile time, so an injected global under it is
  2667. // unreachable from the program — accepted by the seam, unusable here.
  2668. for (const global of ['__dsh_main__', 'console', '__debug__']) {
  2669. await expect(runtime.run({
  2670. program: 'x = 1',
  2671. bindings: [{ global, functions: {} }],
  2672. })).rejects.toThrow(/collides with a runtime-owned global/)
  2673. }
  2674. })
  2675. it('accepts a non-identifier memberNameProperty and rejects only an empty one', async () => {
  2676. // The seam permits any non-empty own property except the reserved
  2677. // members; Python setattr/getattr carry exotic names like `tool-name`,
  2678. // and the worker backend accepts them, so this backend must too.
  2679. const { runtime } = await setup()
  2680. const result = await runtime.run({
  2681. program: [
  2682. 'try:',
  2683. ' await tools.boom({})',
  2684. 'except ToolCallError as e:',
  2685. ' return getattr(e, "tool-name")',
  2686. ].join('\n'),
  2687. bindings: [{
  2688. global: 'tools',
  2689. functions: { boom: async () => { throw new Error('nope') } },
  2690. errorClass: { name: 'ToolCallError', memberNameProperty: 'tool-name' },
  2691. }],
  2692. })
  2693. expect(result.error).toBeUndefined()
  2694. expect(result.value).toBe('boom')
  2695. await expect(runtime.run({
  2696. program: 'return 1',
  2697. bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'ToolCallError', memberNameProperty: '' } }],
  2698. })).rejects.toThrow(/memberNameProperty must be a non-empty attribute name/)
  2699. })
  2700. it('resolves a basename pythonBin to an absolute path (runs a real program)', async () => {
  2701. // A bare `python3` basename must resolve against PATH and actually launch
  2702. // under the empty-env spawn — exercises the accessSync success branch.
  2703. const { runtime } = await setup({ pythonBin: 'python3' })
  2704. const result = await runtime.run({ program: 'return 7', bindings: [] })
  2705. expect(result.error).toBeUndefined()
  2706. expect(result.value).toBe(7)
  2707. })
  2708. it('rejects at load a basename pythonBin with no PATH match', async () => {
  2709. // resolvePythonBin turns a basename into an absolute path before the
  2710. // empty-env spawn; a basename with no PATH match must fail at load (like an
  2711. // empty or NUL pythonBin) rather than silently falling to execvp's
  2712. // platform default PATH and starting a system interpreter the caller never
  2713. // asked for.
  2714. const ctx = new Context()
  2715. await expect(ctx.plugin(PythonCodeRuntime, { pythonBin: 'definitely-no-such-python-xyz' }))
  2716. .rejects.toThrow(/does not resolve on PATH/)
  2717. })
  2718. it('rejects a memberNameProperty naming a constrained BaseException attribute', async () => {
  2719. // `__dict__`/`__class__` are constrained descriptors alongside
  2720. // `__traceback__` — setattr of a string raises TypeError while
  2721. // constructing the rejection — so every dunder is refused at the seam.
  2722. const { runtime } = await setup()
  2723. // name/message/stack are the seam's own exclusions (CodeBindingErrorClass
  2724. // forbids replacing them; the worker backend rejects them identically).
  2725. for (const member of ['__traceback__', '__dict__', '__class__', 'args', 'name', 'message', 'stack']) {
  2726. await expect(runtime.run({
  2727. program: 'return 1',
  2728. bindings: [{ global: 'tools', functions: {}, errorClass: { name: 'ToolCallError', memberNameProperty: member } }],
  2729. })).rejects.toThrow(/reserved error member/)
  2730. }
  2731. })
  2732. it('rejects a lossy binding resolution (NaN) instead of coercing it to null', async () => {
  2733. // JSON.stringify would turn NaN into null and drop undefined fields; the
  2734. // seam requires a descriptive rejection so data cannot silently corrupt.
  2735. const { runtime } = await setup()
  2736. const result = await runtime.run({
  2737. program: [
  2738. 'caught = ""',
  2739. 'try:',
  2740. ' await tools.bad({})',
  2741. 'except RuntimeError as e:',
  2742. ' caught = str(e)',
  2743. 'return caught',
  2744. ].join('\n'),
  2745. bindings: tools({ bad: async () => Number.NaN }),
  2746. })
  2747. expect(result.error).toBeUndefined()
  2748. expect(result.value).toContain('lossless JSON')
  2749. })
  2750. it('contains a forged pathological done value without crashing the host', async () => {
  2751. // A ~20k-deep nested array forged onto fd 3 would overflow a recursive
  2752. // JSON.stringify; the host's iterative encoder measures it stack-safely
  2753. // and fails it deterministically on the byte budget (40 kB > 32 KiB).
  2754. const { runtime } = await setup()
  2755. const result = await runtime.run({
  2756. program: [
  2757. 'import os, json',
  2758. 'depth = 20000',
  2759. 'payload = "[" * depth + "]" * depth',
  2760. 'os.write(3, b\'{"type":"done","value":\' + payload.encode() + b\'}\\n\')',
  2761. 'import time',
  2762. 'time.sleep(5)',
  2763. ].join('\n'),
  2764. bindings: [],
  2765. })
  2766. expect(result.value).toBeUndefined()
  2767. expect(result.error?.kind).toBe('output-limit')
  2768. })
  2769. it('preserves a deeply nested completion value below the byte budget', async () => {
  2770. // CodeJsonValue has no depth limit: a 10000-deep nested list is only
  2771. // ~20 kB — under maxValueBytes — and must cross intact. That depth
  2772. // overflows BOTH recursive serializers the pipeline used to rely on
  2773. // (CPython's json.dumps recursion limit ~1000s, V8's JSON.stringify), so
  2774. // it proves the child-side _encode_json_plain and the host-side
  2775. // encodeJsonPlain together. The host JSON.parse of the frame is iterative
  2776. // in V8 for arrays, so only the two encoders were at risk.
  2777. const { runtime } = await setup()
  2778. const result = await runtime.run({
  2779. program: [
  2780. 'v = None',
  2781. 'for _ in range(10000):',
  2782. ' v = [v]',
  2783. 'return v',
  2784. ].join('\n'),
  2785. bindings: [],
  2786. })
  2787. expect(result.error).toBeUndefined()
  2788. // Walk down iteratively (a recursive toEqual would itself overflow).
  2789. let depth = 0
  2790. let cursor: unknown = result.value
  2791. while (Array.isArray(cursor)) {
  2792. expect(cursor).toHaveLength(1)
  2793. cursor = cursor[0]
  2794. depth++
  2795. }
  2796. expect(depth).toBe(10000)
  2797. expect(cursor).toBeNull()
  2798. })
  2799. it('bridges a deeply nested binding resolution back into the program stack-safely', async () => {
  2800. // A binding resolution has no seam-level depth or byte cap; neither the
  2801. // host's reply serialization nor the CHILD's reply decode may die on
  2802. // recursion (json.loads raises RecursionError ~10k levels deep; the
  2803. // bootstrap decodes frames iteratively). 12000 levels sits past that
  2804. // limit while staying tiny in bytes.
  2805. const { runtime } = await setup()
  2806. const deep = ((): unknown => {
  2807. let v: unknown = null
  2808. for (let i = 0; i < 12000; i++) v = [v]
  2809. return v
  2810. })()
  2811. const result = await runtime.run({
  2812. program: [
  2813. 'v = await tools.deep({})',
  2814. 'depth = 0',
  2815. 'while isinstance(v, list):',
  2816. ' v = v[0]',
  2817. ' depth += 1',
  2818. 'return depth',
  2819. ].join('\n'),
  2820. bindings: tools({ deep: async () => deep as never }),
  2821. })
  2822. expect(result.error).toBeUndefined()
  2823. expect(result.value).toBe(12000)
  2824. })
  2825. it('rejects a reserved errorClass name at the seam', async () => {
  2826. const { runtime } = await setup()
  2827. await expect(runtime.run({
  2828. program: 'return 1',
  2829. bindings: [{
  2830. global: 'tools',
  2831. functions: {},
  2832. errorClass: { name: 'class', memberNameProperty: 'toolName' },
  2833. }],
  2834. })).rejects.toThrow(/errorClass.name "class" is not a usable Python identifier/)
  2835. })
  2836. it('routes a declared inherited-attribute name through the bridge via subscript', async () => {
  2837. // __class__ resolves on `object` before any fallback hook; the proxy's
  2838. // __getattribute__ intercepts declared names first, and subscript access
  2839. // is the SDK-advertised route for underscore names.
  2840. const { runtime } = await setup()
  2841. const seen: string[] = []
  2842. const result = await runtime.run({
  2843. program: [
  2844. 'a = await tools["__class__"]({"via": "subscript"})',
  2845. 'b = await tools.__class__({"via": "dot"})',
  2846. 'return [a, b]',
  2847. ].join('\n'),
  2848. bindings: tools({
  2849. '__class__': async () => { seen.push('called'); return 'bridged' },
  2850. }),
  2851. })
  2852. expect(result.error).toBeUndefined()
  2853. expect(result.value).toEqual(['bridged', 'bridged'])
  2854. expect(seen).toEqual(['called', 'called'])
  2855. })
  2856. it('rejects NaN binding arguments immediately instead of hanging', async () => {
  2857. // Default json.dumps would emit a non-standard NaN token that the host
  2858. // JSON.parse drops silently, hanging the call until the wall clock;
  2859. // allow_nan=False raises in-program right away.
  2860. const { runtime } = await setup({ maxWallMs: 8000 })
  2861. const start = Date.now()
  2862. const result = await runtime.run({
  2863. program: [
  2864. 'caught = ""',
  2865. 'try:',
  2866. ' await tools.echo({"x": float("nan")})',
  2867. 'except RuntimeError as e:',
  2868. ' caught = str(e)',
  2869. 'return caught',
  2870. ].join('\n'),
  2871. bindings: tools({ echo: async args => args as CodeJsonValue }),
  2872. })
  2873. expect(result.error).toBeUndefined()
  2874. expect(result.value).toContain('lossless JSON')
  2875. expect(Date.now() - start).toBeLessThan(5000)
  2876. })
  2877. it('carries large binding arguments well past maxValueBytes', async () => {
  2878. // Binding traffic has no seam byte cap: a call frame far larger than the
  2879. // completion budget must reach the host intact (the fd-3 ceiling is a
  2880. // fixed memory-safety bound, not an output budget).
  2881. const maxValueBytes = 4096
  2882. const { runtime } = await setup({ maxValueBytes })
  2883. let receivedLength = 0
  2884. const result = await runtime.run({
  2885. program: [
  2886. `big = "B" * ${maxValueBytes * 50}`,
  2887. 'r = await tools.measure({"payload": big})',
  2888. 'return r',
  2889. ].join('\n'),
  2890. bindings: tools({
  2891. measure: async (args) => {
  2892. receivedLength = ((args as { payload: string }).payload).length
  2893. return receivedLength
  2894. },
  2895. }),
  2896. })
  2897. expect(result.error).toBeUndefined()
  2898. expect(receivedLength).toBe(maxValueBytes * 50)
  2899. expect(result.value).toBe(maxValueBytes * 50)
  2900. })
  2901. it('rejects an unknown binding name inside the program with a matching error', async () => {
  2902. const { runtime } = await setup()
  2903. const result = await runtime.run({
  2904. program: [
  2905. 'caught = ""',
  2906. 'try:',
  2907. ' await tools.nope({})',
  2908. 'except (AttributeError, RuntimeError) as e:',
  2909. ' caught = str(e)',
  2910. 'return caught',
  2911. ].join('\n'),
  2912. bindings: tools({ known: async () => 'ok' }),
  2913. })
  2914. expect(result.error).toBeUndefined()
  2915. expect(result.value).toContain('nope')
  2916. })
  2917. it('bounds an unknown-binding diagnostic built from a forged call frame', async () => {
  2918. // `call.global` and `call.name` carry no byte cap of their own, only the
  2919. // 64 MiB fd-3 frame parse cap, and the reply interpolated them raw: one copy
  2920. // into the template result, one into the `JSON.stringify` escape, one into
  2921. // the `encodeJsonPlain` frame, one into the pipe write. Slicing each field
  2922. // to `maxValueBytes` code units first makes an 8 MiB forged name a
  2923. // 128-byte reply. The observable effect is the reply the child then has to
  2924. // READ: its fd-3 reader is unbuffered, so `readline` consumes an oversized
  2925. // reply one `read(2)` per byte and the run's own legitimate call never gets
  2926. // answered — measured under a 60 s ceiling, the 8 MiB case timed out and a
  2927. // 64 MiB case cost the host 509.9 MiB of heap against 120.3 MiB with the
  2928. // slices in place. The child's address space stays generous enough to BUILD
  2929. // the forgery, which is not what is under test.
  2930. const { runtime } = await setup({ maxValueBytes: 128, addressSpaceMb: 1024, maxWallMs: 20_000 })
  2931. const result = await runtime.run({
  2932. program: [
  2933. 'import os',
  2934. 'frame = b\'{"type":"call","id":9001,"global":"tools","name":"\' + b"n" * (8 * 1024 * 1024) + b\'","args":{}}\\n\'',
  2935. // One os.write returns short past the pipe buffer, and a partial frame
  2936. // would glue itself to the next one and be dropped as malformed, so the
  2937. // forgery goes out through a drain loop.
  2938. 'view = memoryview(frame)',
  2939. 'while view:',
  2940. ' view = view[os.write(3, view):]',
  2941. // A legitimate call after the forgery: its reply can only arrive once
  2942. // the child has read past whatever the forged frame was answered with.
  2943. 'await tools.known({})',
  2944. 'return "settled"',
  2945. ].join('\n'),
  2946. bindings: tools({ known: async () => 'ok' }),
  2947. })
  2948. expect(result.error).toBeUndefined()
  2949. expect(result.value).toBe('settled')
  2950. }, 40_000)
  2951. it('bridges a binding call reached via subscript access (tools["name"])', async () => {
  2952. // The SDK tells the model `await tools["my-tool"](args)` works for exotic
  2953. // names; the proxy's __getitem__ must route it through the bridge.
  2954. const { runtime } = await setup()
  2955. const result = await runtime.run({
  2956. program: [
  2957. 'r = await tools["my-tool"]({"n": 7})',
  2958. 'return r',
  2959. ].join('\n'),
  2960. bindings: tools({ 'my-tool': async args => ({ got: args as CodeJsonValue }) }),
  2961. })
  2962. expect(result.error).toBeUndefined()
  2963. expect(result.value).toEqual({ got: { n: 7 } })
  2964. })
  2965. it('raises KeyError for an undeclared subscript name', async () => {
  2966. const { runtime } = await setup()
  2967. const result = await runtime.run({
  2968. program: [
  2969. 'caught = ""',
  2970. 'try:',
  2971. ' await tools["absent"]({})',
  2972. 'except KeyError as e:',
  2973. ' caught = str(e)',
  2974. 'return caught',
  2975. ].join('\n'),
  2976. bindings: tools({ known: async () => 'ok' }),
  2977. })
  2978. expect(result.error).toBeUndefined()
  2979. expect(result.value).toContain('absent')
  2980. })
  2981. })
  2982. describe('PythonCodeRuntime — budgets, termination, disposal', () => {
  2983. it('kills a wall-clock runaway program via SIGTERM/SIGKILL and reports timeout', async () => {
  2984. const { runtime } = await setup({ maxWallMs: 500, graceMs: 200 })
  2985. const start = Date.now()
  2986. const result = await runtime.run({
  2987. program: 'import time\nwhile True: time.sleep(1)',
  2988. bindings: [],
  2989. })
  2990. const elapsed = Date.now() - start
  2991. // The wall timer may fire first or the exit-after-signal may resolve; both are ok.
  2992. expect(['timeout', 'worker-exit']).toContain(result.error?.kind)
  2993. // We got somewhere in the neighborhood of maxWallMs, not the underlying `sleep(1)`.
  2994. expect(elapsed).toBeLessThan(2000)
  2995. }, 5000)
  2996. it('aborts a run when the outer signal fires mid-flight', async () => {
  2997. const { runtime } = await setup({ maxWallMs: 10_000 })
  2998. const controller = new AbortController()
  2999. const settled: Promise<CodeRunResult> = runtime.run({
  3000. program: 'import time\nwhile True: time.sleep(0.1)',
  3001. bindings: [],
  3002. signal: controller.signal,
  3003. })
  3004. setTimeout(() => { controller.abort('outer-abort') }, 200)
  3005. const result = await settled
  3006. expect(['abort', 'worker-exit']).toContain(result.error?.kind)
  3007. }, 5000)
  3008. it('settles the run when a mid-flight abort reason cannot be converted', async () => {
  3009. // The listener converted the reason before calling `finish()`, so a hostile
  3010. // reason threw from inside an `AbortSignal` listener. Node reports that as an
  3011. // uncaught exception — it can terminate the host — and `finish()` never ran,
  3012. // so the run stayed live until the wall ceiling and misreported as `timeout`
  3013. // (observed) instead of the caller's cancellation. `maxWallMs` is short so
  3014. // that misreport is a fast assertion failure rather than a suite timeout.
  3015. const uncaught: unknown[] = []
  3016. const record = (error: unknown): void => { uncaught.push(error) }
  3017. process.on('uncaughtException', record)
  3018. try {
  3019. const { runtime } = await setup({ maxWallMs: 4_000, graceMs: 200 })
  3020. const controller = new AbortController()
  3021. const settled: Promise<CodeRunResult> = runtime.run({
  3022. program: 'import time\nwhile True: time.sleep(0.1)',
  3023. bindings: [],
  3024. signal: controller.signal,
  3025. })
  3026. setTimeout(() => {
  3027. controller.abort({ [Symbol.toPrimitive]() { throw new Error('reason blew up') } })
  3028. }, 200)
  3029. const result = await settled
  3030. expect(result.error?.kind).toBe('abort')
  3031. expect(result.error?.message).toBe('<unrenderable rejection value>')
  3032. expect(uncaught).toEqual([])
  3033. } finally {
  3034. process.off('uncaughtException', record)
  3035. }
  3036. }, 15_000)
  3037. it('disposes to quiescence: an in-flight run resolves as abort and the child exits', async () => {
  3038. const { fiber, runtime } = await setup({ maxWallMs: 10_000 })
  3039. const pending = runtime.run({
  3040. program: 'import time\nwhile True: time.sleep(0.1)',
  3041. bindings: [],
  3042. })
  3043. // Give the process time to spawn and start running.
  3044. await new Promise(resolve => setTimeout(resolve, 200))
  3045. await fiber.dispose()
  3046. const result = await pending
  3047. expect(['abort', 'worker-exit']).toContain(result.error?.kind)
  3048. }, 5000)
  3049. it('reports an interpreter removed after load as worker-exit', async () => {
  3050. const dir = await mkdtemp(join(tmpdir(), 'dsh-python-removed-'))
  3051. const pythonBin = join(dir, 'python3')
  3052. await writeFile(pythonBin, `#!/bin/sh\nexec "${PYABS}" "$@"\n`, { mode: 0o755 })
  3053. const { runtime, fiber } = await setup({ pythonBin, maxWallMs: 3000 })
  3054. rmSync(pythonBin)
  3055. try {
  3056. const result = await runtime.run({ program: 'return 1', bindings: [] })
  3057. expect(result.error?.kind).toBe('worker-exit')
  3058. } finally {
  3059. await fiber.dispose()
  3060. rmSync(dir, { recursive: true, force: true })
  3061. }
  3062. }, 8000)
  3063. it('applies the strictest of the configured and inherited resource limits', async () => {
  3064. // This case used to drive the bootstrap's `applying resource limits failed`
  3065. // handler with `cpuSeconds: 2 ** 63`, asserting that a cap the child cannot
  3066. // apply fails the run rather than running it uncapped. That premise no longer
  3067. // holds, for two independent reasons, so the test now pins what is actually
  3068. // guaranteed instead of a path no admissible input reaches.
  3069. //
  3070. // First, `2 ** 63` is not a safe integer, so it is now rejected at LOAD as a
  3071. // configuration error — it can never reach the child at all. Second, even the
  3072. // largest admissible values are applied successfully, because `_clamped`
  3073. // bounds every requested pair by the inherited hard limit: an unprivileged
  3074. // process may lower a hard limit but never raise one, so the child keeps the
  3075. // stricter of the two rather than asking for something `setrlimit` refuses.
  3076. // The failure handler remains as a substrate guard (a platform whose kernel
  3077. // refuses the call for its own reasons), but it is no longer reachable from
  3078. // configuration, and a test that pretends otherwise documents a contract the
  3079. // code does not have.
  3080. //
  3081. // What is observable: a very large cap still yields a working run, and the
  3082. // containment it promises is met by the inherited ceiling.
  3083. const { runtime } = await setup({ cpuSeconds: Number.MAX_SAFE_INTEGER - 1, maxWallMs: 10_000 })
  3084. const result = await runtime.run({ program: 'return 1', bindings: [] })
  3085. expect(result.error).toBeUndefined()
  3086. expect(result.value).toBe(1)
  3087. }, 20_000)
  3088. it('settles as worker-exit when the child exits before sending done (no hang)', async () => {
  3089. // Regression: settlement must key off `close` (process reaped AND stdio
  3090. // drained), not `exit`. With `exit`, finish() re-armed a second exit
  3091. // listener that never fired — run() hung forever whenever the exit event
  3092. // beat the final fd-3 data (deterministic on macOS, a lost race elsewhere).
  3093. const { runtime } = await setup({ maxWallMs: 10_000 })
  3094. const result = await runtime.run({
  3095. program: 'import os\nos._exit(7)',
  3096. bindings: [],
  3097. })
  3098. expect(result.error?.kind).toBe('worker-exit')
  3099. expect(result.error?.message).toContain('code=7')
  3100. }, 5000)
  3101. it('classifies RLIMIT_CPU soft-limit expiry (SIGXCPU) as a timeout', async () => {
  3102. // A CPU hot loop burns the soft limit; the kernel delivers SIGXCPU, whose
  3103. // close signal the host maps to `timeout`. macOS re-delivers SIGXCPU
  3104. // differently, so we assert only kind/message here — CI's darwin leg
  3105. // validates real delivery. cpuSeconds must be an integer for setrlimit.
  3106. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 20_000 })
  3107. const result = await runtime.run({
  3108. program: 'while True: pass',
  3109. bindings: [],
  3110. })
  3111. expect(result.error?.kind).toBe('timeout')
  3112. expect(result.error?.message).toContain('CPU time exhausted')
  3113. }, 8000)
  3114. it('keeps an early self-inflicted SIGKILL a worker-exit, not a CPU timeout', async () => {
  3115. // The unsolicited-SIGKILL-as-timeout classification applies only when the
  3116. // CPU budget could have expired (wall time >= cpuSeconds). A SIGKILL
  3117. // seconds before that (cgroup OOM, an operator, os.kill) is substrate
  3118. // death and stays worker-exit per the orthogonal taxonomy.
  3119. const { runtime } = await setup({ cpuSeconds: 60, maxWallMs: 10_000 })
  3120. const result = await runtime.run({
  3121. program: [
  3122. 'import os, signal',
  3123. 'os.kill(os.getpid(), signal.SIGKILL)',
  3124. ].join('\n'),
  3125. bindings: [],
  3126. })
  3127. expect(result.error?.kind).toBe('worker-exit')
  3128. expect(result.error?.message).toContain('SIGKILL')
  3129. })
  3130. it('charges a forked descendant against the run CPU budget', async () => {
  3131. // RLIMIT_CPU is per-process and every child inherits a FRESH budget, so a
  3132. // program that shells out multiplies `cpuSeconds` by the number of
  3133. // descendants it starts. Measured before the aggregate meter existed: with
  3134. // cpuSeconds 1, two sequential busy children burned 2.0 CPU-seconds
  3135. // (RUSAGE_CHILDREN) and the run still returned a SUCCESS completion. The
  3136. // settle-time check meters RUSAGE_SELF + RUSAGE_CHILDREN and converts the
  3137. // overrun into the same SIGXCPU the untrapped soft limit sends.
  3138. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 30_000 })
  3139. const result = await runtime.run({
  3140. program: [
  3141. 'import subprocess, sys',
  3142. 'for _ in range(2):',
  3143. ' subprocess.run([sys.executable, "-c", "import time\\nt=time.time()\\nwhile time.time()-t<1.2: pass"])',
  3144. 'return "escaped the cpu budget"',
  3145. ].join('\n'),
  3146. bindings: [],
  3147. })
  3148. // Darwin's SIGXCPU re-delivery differs, so accept either terminal
  3149. // classification; what must NOT happen is the completion crossing.
  3150. expect(['timeout', 'worker-exit']).toContain(result.error?.kind)
  3151. expect(result.value).toBeUndefined()
  3152. }, 40_000)
  3153. it('does not charge wall time or a cheap descendant against the CPU budget', async () => {
  3154. // The meter is CPU, not wall clock, and it must not fire on a child that
  3155. // burns almost nothing: a sleeping program and a trivial subprocess both
  3156. // have to complete normally, or the check would reject every program that
  3157. // shells out.
  3158. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 30_000 })
  3159. const slept = await runtime.run({
  3160. program: 'import time\ntime.sleep(1.5)\nreturn "slept"',
  3161. bindings: [],
  3162. })
  3163. expect(slept.error).toBeUndefined()
  3164. expect(slept.value).toBe('slept')
  3165. const cheap = await runtime.run({
  3166. program: [
  3167. 'import subprocess, sys',
  3168. 'subprocess.run([sys.executable, "-c", "pass"])',
  3169. 'return "cheap child"',
  3170. ].join('\n'),
  3171. bindings: [],
  3172. })
  3173. expect(cheap.error).toBeUndefined()
  3174. expect(cheap.value).toBe('cheap child')
  3175. }, 40_000)
  3176. it('spends no part of addressSpaceMb on bootstrap machinery', async () => {
  3177. // RLIMIT_AS counts RESERVED address space, so anything the bootstrap maps
  3178. // for its own accounting is subtracted from the program's `addressSpaceMb`.
  3179. // A sampling thread for the descendant-CPU meter cost 72 MiB here (an 8 MiB
  3180. // stack plus a 64 MiB glibc per-thread malloc arena reservation) and turned
  3181. // the 2-million-entry dict rejection below into a MemoryError under a
  3182. // 256 MiB cap on a slower runner. Assert the child's own mappings directly
  3183. // rather than inferring the budget from a near-cap allocation, so the bound
  3184. // is read from /proc instead of from how much headroom one machine happens
  3185. // to have; 48 MiB is well above the ~30 MiB a bare interpreter maps and
  3186. // well below the 102 MiB the thread produced. `addressSpaceMb` itself is
  3187. // skipped on darwin (the dyld shared cache makes any practical cap
  3188. // unsettable) and /proc/self/maps does not exist there, so the mapping
  3189. // assertion is Linux-only; the completion path is checked everywhere.
  3190. const { runtime } = await setup({ maxValueBytes: 4096, addressSpaceMb: 256 })
  3191. const mapped = await runtime.run({
  3192. program: [
  3193. 'import sys',
  3194. 'if sys.platform != "linux":',
  3195. ' return 0',
  3196. 'total = 0',
  3197. 'with open("/proc/self/maps") as handle:',
  3198. ' for line in handle:',
  3199. ' low, high = (int(part, 16) for part in line.split(" ", 1)[0].split("-"))',
  3200. ' total += high - low',
  3201. 'return total // (1024 * 1024)',
  3202. ].join('\n'),
  3203. bindings: [],
  3204. })
  3205. expect(mapped.error).toBeUndefined()
  3206. expect(mapped.value).toBeLessThan(48)
  3207. }, 20_000)
  3208. it('spends no part of addressSpaceMb on the reply pump, across a binding await', async () => {
  3209. // The test above measures BEFORE the program yields, so it could not see the
  3210. // reply pump's cost: `loop.run_in_executor(None, read_frame)` created the
  3211. // default executor's first thread on the first `await tools.*`, and that
  3212. // thread's 8 MiB stack plus a 64 MiB glibc per-thread malloc arena are
  3213. // charged to RLIMIT_AS while the limit is already in force — measured, the
  3214. // child went from 30.34 MiB to 102.39 MiB across one binding call. Under a
  3215. // small `addressSpaceMb` the thread cannot start and a legitimate call hangs
  3216. // to `maxWallMs`; under a larger one an allocation that should have fit dies
  3217. // as MemoryError. `loop.add_reader` watches the fd with no thread at all.
  3218. //
  3219. // Measuring both sides inside one run is what discriminates: a single
  3220. // after-the-fact number cannot separate the pump's cost from the
  3221. // interpreter's own footprint. Linux-only for the same reason as above.
  3222. const { runtime } = await setup({ addressSpaceMb: 256, maxWallMs: 20_000 })
  3223. const result = await runtime.run({
  3224. program: [
  3225. 'import sys',
  3226. 'def mapped():',
  3227. ' if sys.platform != "linux":',
  3228. ' return 0',
  3229. ' total = 0',
  3230. ' with open("/proc/self/maps") as handle:',
  3231. ' for line in handle:',
  3232. ' low, high = (int(part, 16) for part in line.split(" ", 1)[0].split("-"))',
  3233. ' total += high - low',
  3234. ' return total // (1024 * 1024)',
  3235. 'before = mapped()',
  3236. 'echoed = await tools.echo({"ping": True})',
  3237. 'return {"before": before, "after": mapped(), "echoed": echoed}',
  3238. ].join('\n'),
  3239. bindings: tools({ echo: async args => args as CodeJsonValue }),
  3240. })
  3241. expect(result.error).toBeUndefined()
  3242. const value = result.value as { before: number; after: number; echoed: unknown }
  3243. // The binding call really happened, so the pump really ran.
  3244. expect(value.echoed).toEqual({ ping: true })
  3245. // Awaiting a binding maps nothing extra. The 8 MiB allowance absorbs ordinary
  3246. // heap growth while staying far below the 72 MiB a pump thread cost.
  3247. expect(value.after - value.before).toBeLessThan(8)
  3248. }, 30_000)
  3249. it('still terminates a program that ignores SIGXCPU (hard-limit backstop)', async () => {
  3250. // A hot loop under SIG_IGN burns through the soft limit; the kernel's
  3251. // hard limit (cpuSeconds + 1) SIGKILLs it. Only a kernel-authoritative
  3252. // SIGXCPU close classifies as the CPU timeout — a bare SIGKILL is
  3253. // indistinguishable from a cgroup OOM kill, so it reports worker-exit
  3254. // (Darwin re-delivers SIGXCPU instead, where the wall clock settles it
  3255. // as timeout). Either way the run TERMINATES within the budget — the
  3256. // backstop holds even when the classification is the opaque one.
  3257. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 6_000 })
  3258. const result = await runtime.run({
  3259. program: [
  3260. 'import signal',
  3261. 'signal.signal(signal.SIGXCPU, signal.SIG_IGN)',
  3262. 'while True: pass',
  3263. ].join('\n'),
  3264. bindings: [],
  3265. })
  3266. expect(['timeout', 'worker-exit']).toContain(result.error?.kind)
  3267. }, 12_000)
  3268. it('enforces the CPU budget even when the program monkeypatches the enforcement primitives', async () => {
  3269. // The check uses import-time-captured references, so replacing
  3270. // resource.getrusage / signal.signal / os.kill on the modules cannot
  3271. // defang it: a trapping program that also swaps the callables and burns
  3272. // past the budget still dies by the authoritative SIGXCPU.
  3273. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 15_000 })
  3274. const result = await runtime.run({
  3275. program: [
  3276. 'import signal, os, resource, time',
  3277. 'signal.signal(signal.SIGXCPU, lambda *a: None)',
  3278. 'resource.getrusage = lambda *a: (_ for _ in ()).throw(RuntimeError("nope"))',
  3279. 'os.kill = lambda *a: None',
  3280. 'signal.signal = lambda *a: None',
  3281. 'deadline = time.process_time() + 1.05',
  3282. 'while time.process_time() < deadline: pass',
  3283. 'return "escaped"',
  3284. ].join('\n'),
  3285. bindings: [],
  3286. })
  3287. expect(result.error?.kind).toBe('timeout')
  3288. expect(result.value).toBeUndefined()
  3289. }, 15_000)
  3290. it('re-delivers SIGXCPU when a trapping program returns inside the soft-to-hard gap', async () => {
  3291. // A program can trap SIGXCPU and settle during the one-second gap; the
  3292. // bootstrap re-checks the kernel CPU meter (getrusage) after settlement
  3293. // and dies by SIGXCPU with the default disposition restored, so the host
  3294. // still classifies the exhausted budget as a timeout instead of success.
  3295. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 15_000 })
  3296. const result = await runtime.run({
  3297. program: [
  3298. 'import signal, time',
  3299. 'fired = []',
  3300. 'signal.signal(signal.SIGXCPU, lambda *a: fired.append(1))',
  3301. 'deadline = time.process_time() + 1.05',
  3302. 'while time.process_time() < deadline: pass',
  3303. 'return "escaped"',
  3304. ].join('\n'),
  3305. bindings: [],
  3306. })
  3307. expect(result.error?.kind).toBe('timeout')
  3308. expect(result.error?.message).toContain('CPU time exhausted')
  3309. expect(result.value).toBeUndefined()
  3310. }, 15_000)
  3311. it('enforces the CPU budget when the program rebinds the enforcer on __main__', async () => {
  3312. // The bootstrap IS `__main__`, so `import __main__` reaches its globals.
  3313. // The enforcement callable holds its primitives in closure cells (not
  3314. // module attributes) and `_run` reads the callable into a frame local
  3315. // before the program starts, so neither replacing the global nor swapping
  3316. // the module's captured names changes what runs after settlement.
  3317. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 15_000 })
  3318. const result = await runtime.run({
  3319. program: [
  3320. 'import signal, time, __main__',
  3321. 'signal.signal(signal.SIGXCPU, lambda *a: None)',
  3322. '__main__._DIE_IF_CPU_EXHAUSTED = lambda *_: None',
  3323. 'deadline = time.process_time() + 1.05',
  3324. 'while time.process_time() < deadline: pass',
  3325. 'return "escaped"',
  3326. ].join('\n'),
  3327. bindings: [],
  3328. })
  3329. expect(result.error?.kind).toBe('timeout')
  3330. expect(result.value).toBeUndefined()
  3331. }, 15_000)
  3332. it('bounds a program that defeats the post-check by writing its closure cell', async () => {
  3333. // The closure-cell capture raises the cost of defeating the post-check; it
  3334. // does NOT make it unreachable, and nothing in-process could: a cell is
  3335. // writable through `fn.__closure__[i].cell_contents`, and `sys._getframe`
  3336. // reads _run's frame locals. This program does exactly that — walks to
  3337. // _run's frame, takes the enforcement callable, and replaces its captured
  3338. // `getrusage` with one reporting zero CPU used — then burns past cpuSeconds
  3339. // with SIGXCPU trapped. The run must still fail, because the bound that
  3340. // model code cannot forge is outside the interpreter: the RLIMIT_CPU HARD
  3341. // limit at cpuSeconds + 1, whose SIGKILL admits no handler. No success is
  3342. // reportable either way.
  3343. const { runtime } = await setup({ cpuSeconds: 1, maxWallMs: 20_000 })
  3344. const start = Date.now()
  3345. const result = await runtime.run({
  3346. program: [
  3347. 'import signal, sys, time',
  3348. 'signal.signal(signal.SIGXCPU, lambda *a: None)',
  3349. // Walk out of __dsh_main__ to _run's frame and take its local.
  3350. 'die = None',
  3351. 'depth = 1',
  3352. 'while depth < 12:',
  3353. ' frame = sys._getframe(depth)',
  3354. ' if "die_if_cpu_exhausted" in frame.f_locals:',
  3355. ' die = frame.f_locals["die_if_cpu_exhausted"]',
  3356. ' break',
  3357. ' depth += 1',
  3358. 'assert die is not None, "enforcer not reachable from the frame chain"',
  3359. 'class Zero:',
  3360. ' ru_utime = 0.0',
  3361. ' ru_stime = 0.0',
  3362. 'names = die.__code__.co_freevars',
  3363. 'die.__closure__[names.index("getrusage")].cell_contents = lambda *a: Zero()',
  3364. // Burn well past the soft limit into the hard limit's SIGKILL.
  3365. 'while True: pass',
  3366. ].join('\n'),
  3367. bindings: [],
  3368. })
  3369. // What holds on EVERY platform: the tampering bought no success. The run
  3370. // failed, carried no value, and the reported kind is one of the two
  3371. // kernel-level outcomes — never a completion.
  3372. expect(result.value).toBeUndefined()
  3373. expect(result.error?.kind === 'worker-exit' || result.error?.kind === 'timeout').toBe(true)
  3374. if (process.platform === 'linux') {
  3375. // Linux enforces the RLIMIT_CPU HARD limit at cpuSeconds + 1 promptly, so
  3376. // the CPU bound — not the 20 s wall ceiling — is what stops the program.
  3377. // Its SIGKILL is not SIGXCPU, so the orthogonal-failure taxonomy reports
  3378. // `worker-exit`: a bare SIGKILL is not evidence of CPU burn.
  3379. expect(result.error?.kind).toBe('worker-exit')
  3380. expect(Date.now() - start).toBeLessThan(15_000)
  3381. } else {
  3382. // Darwin does not deliver the hard limit's SIGKILL on the same schedule;
  3383. // observed on the macOS lane, a program that patches the post-check runs
  3384. // to the WALL ceiling instead. The CPU budget is therefore not the
  3385. // binding constraint against a tampering program there — the wall clock
  3386. // is. Asserted rather than skipped so the difference stays visible.
  3387. expect(result.error?.kind).toBe('timeout')
  3388. }
  3389. }, 30_000)
  3390. it('keeps a finished-but-not-closed run live so dispose awaits the child\'s death', async () => {
  3391. // finish() no longer drops the run from `live`; settle() (at close) does.
  3392. // A SIGTERM-trapping program with a small graceMs sits in the grace window
  3393. // after finish() fires — dispose() must not resolve until the SIGKILL
  3394. // backstop actually reaps the child. The program prints its pid (captured
  3395. // as a log even on abort); once dispose() resolves, that pid must be dead
  3396. // (process.kill(pid, 0) throws ESRCH).
  3397. const { fiber, runtime } = await setup({ maxWallMs: 10_000, graceMs: 400 })
  3398. // Deterministic readiness: the program reports its pid through a binding
  3399. // AFTER installing the trap, so dispose cannot race the spawn (a fixed
  3400. // sleep lost that race on slow CI runners — SIGTERM landed pre-trap).
  3401. let reportedPid!: (pid: number) => void
  3402. const trapReady = new Promise<number>((resolve) => { reportedPid = resolve })
  3403. const pending = runtime.run({
  3404. program: [
  3405. 'import signal, time, os',
  3406. 'signal.signal(signal.SIGTERM, lambda *a: None)',
  3407. 'await tools.ready({"pid": os.getpid()})',
  3408. 'while True: time.sleep(0.05)',
  3409. ].join('\n'),
  3410. bindings: tools({
  3411. ready: async (args) => {
  3412. reportedPid((args as { pid: number }).pid)
  3413. return 'ok'
  3414. },
  3415. }),
  3416. })
  3417. const pid = await trapReady
  3418. const start = Date.now()
  3419. await fiber.dispose()
  3420. const elapsed = Date.now() - start
  3421. const result = await pending
  3422. expect(['abort', 'worker-exit', 'timeout']).toContain(result.error?.kind)
  3423. // dispose() returned only after the grace window elapsed (the SIGTERM trap
  3424. // forces the SIGKILL backstop path), proving the run stayed live past finish().
  3425. expect(elapsed).toBeGreaterThanOrEqual(300)
  3426. expect(Number.isInteger(pid) && pid > 0).toBe(true)
  3427. // The child is fully reaped by the time dispose() resolved.
  3428. expect(() => process.kill(pid, 0)).toThrow(/ESRCH/)
  3429. }, 8000)
  3430. it('settles on the decided result even when a setsid-escaped orphan holds stdio open past close', async () => {
  3431. // `close` only fires once every inherited stdio stream drains. A descendant
  3432. // started with start_new_session=True escapes the child's process group, so
  3433. // the SIGTERM/SIGKILL aimed at that group never reaches it; if it inherited
  3434. // our stdout/stderr/fd 3 and outlives the run, `close` would never fire and
  3435. // run() would hang forever. The close-deadline backstop (graceMs + margin)
  3436. // must force settlement on the value the `done` frame already decided.
  3437. const { runtime } = await setup({ graceMs: 100 })
  3438. const start = Date.now()
  3439. const result = await runtime.run({
  3440. program: [
  3441. 'import subprocess, sys',
  3442. // Orphan in a fresh session, inheriting our stdout/stderr/fd 3, alive
  3443. // past the close-deadline so `close` cannot fire on its own. Its own
  3444. // 5 s self-exit is the leak ceiling AND the discriminator: it must stay
  3445. // ABOVE the < 4000 ms upper-bound assertion below, so if the deadline
  3446. // backstop failed to settle, settlement could only come from this
  3447. // self-exit at ~5 s and blow the bound — a sharper signal than the wall
  3448. // ceiling would give.
  3449. 'subprocess.Popen([sys.executable, "-c", "import time; time.sleep(5)"],',
  3450. ' start_new_session=True)',
  3451. 'return "escaped"',
  3452. ].join('\n'),
  3453. bindings: [],
  3454. })
  3455. const elapsed = Date.now() - start
  3456. // The done frame decided the value; the deadline settled it despite the
  3457. // orphan pinning the pipes open.
  3458. expect(result.error).toBeUndefined()
  3459. expect(result.value).toBe('escaped')
  3460. // Settlement waited for the backstop (graceMs + CLOSE_REAP_MARGIN_MS ≈ 2.1s),
  3461. // not the orphan's 5 s self-exit — proving the deadline, not a fallback, fired.
  3462. expect(elapsed).toBeGreaterThanOrEqual(1_500)
  3463. expect(elapsed).toBeLessThan(4_000)
  3464. }, 8000)
  3465. it('flushes a newline-free diagnostic when the closeDeadline forces settlement', async () => {
  3466. // A leader that writes an unterminated diagnostic via `os.write(1, ...)` and
  3467. // then exits, leaving a setsid orphan holding the pipes open, settles through
  3468. // the closeDeadline destroy() path — which fires no `end`. The residual must
  3469. // be flushed before destroy() drops it, or the diagnostic is lost from
  3470. // `logs`. The value is decided by the done frame; the diagnostic must survive.
  3471. const { runtime } = await setup({ graceMs: 100 })
  3472. const result = await runtime.run({
  3473. program: [
  3474. 'import os, subprocess, sys',
  3475. 'os.write(1, b"leader-diagnostic-no-newline")',
  3476. 'subprocess.Popen([sys.executable, "-c", "import time; time.sleep(5)"],',
  3477. ' start_new_session=True)',
  3478. 'return "escaped"',
  3479. ].join('\n'),
  3480. bindings: [],
  3481. })
  3482. expect(result.error).toBeUndefined()
  3483. expect(result.value).toBe('escaped')
  3484. expect(result.logs).toContain('leader-diagnostic-no-newline')
  3485. }, 8000)
  3486. it('closes the child stdin so a program read sees EOF instead of blocking', async () => {
  3487. // The host closes the child's stdin write handle immediately after spawn
  3488. // (the program is an async body that reads nothing from fd 0; a live pipe
  3489. // would hold a host-side handle open past the run). A program that DOES
  3490. // read fd 0 therefore sees EOF at once. Fail-before: with the handle left
  3491. // open and no data written, `sys.stdin.read()` blocks and the run would
  3492. // hang to maxWallMs as a timeout.
  3493. const { runtime } = await setup({ maxWallMs: 8_000 })
  3494. const result = await runtime.run({
  3495. program: [
  3496. 'import sys',
  3497. 'data = sys.stdin.read()',
  3498. 'return "read: " + repr(data)',
  3499. ].join('\n'),
  3500. bindings: [],
  3501. })
  3502. expect(result.error).toBeUndefined()
  3503. expect(result.value).toBe("read: ''")
  3504. }, 15_000)
  3505. it('keeps runtime type annotations as live classes, not PEP 563 strings, when the program reads them', async () => {
  3506. // bootstrap.py imports `from __future__ import annotations`; without
  3507. // dont_inherit=True on compile(), that PEP 563 flag leaks into the program's
  3508. // compiled code and stringifies its type annotations, changing the semantics
  3509. // of a legal program that reads `f.__annotations__` at runtime.
  3510. const { runtime } = await setup()
  3511. const result = await runtime.run({
  3512. program: [
  3513. 'def f(x: int) -> int:',
  3514. ' return x',
  3515. 'return f.__annotations__["x"].__name__',
  3516. ].join('\n'),
  3517. bindings: [],
  3518. })
  3519. expect(result.error).toBeUndefined()
  3520. expect(result.value).toBe('int')
  3521. }, 15_000)
  3522. it('reaps a same-group child that ignores SIGTERM and releases the pipes before close', async () => {
  3523. // The same-group counterpart to the setsid-orphan case above. A descendant
  3524. // left in the child's OWN process group (no setsid, so `kill(-pid)` reaches
  3525. // it) can ignore SIGTERM yet still release the inherited stdout/stderr/fd 3
  3526. // it does not hold — here by giving the Popen child DEVNULL streams and
  3527. // letting close_fds drop fd 3. The leader then writes `done` and exits, its
  3528. // `close` fires because the pipes drained, and settle() runs while that
  3529. // descendant is still alive. settle() then keeps a REF'd poll alive until the
  3530. // grace-window SIGKILL has emptied the whole process group, so the host cannot
  3531. // exit and reparent the survivor to init: no subprocess outlives the fiber.
  3532. //
  3533. // The descendant must have SIG_IGN installed BEFORE the host sends SIGTERM,
  3534. // or it dies from the default SIGTERM whether the fix is present or not — so
  3535. // it writes a readiness marker after trapping and the leader waits for that
  3536. // marker before returning. While alive it bumps a heartbeat file every 50 ms;
  3537. // the test asserts the heartbeat STOPS, which is what "no longer executing"
  3538. // means whether the killed descendant is reaped or lingers as a zombie (a
  3539. // SIGKILL'd process runs no more code either way). It sleeps 30 s as a safety
  3540. // net so a broken fix cannot leak it forever.
  3541. const handoff = await makeTempDir('dsh-samegroup-')
  3542. const readyMarker = join(handoff, 'ready')
  3543. const heartbeat = join(handoff, 'heartbeat')
  3544. const { runtime } = await setup({ maxWallMs: 10_000, graceMs: 300 })
  3545. const result = await runtime.run({
  3546. program: [
  3547. 'import subprocess, sys, os, time',
  3548. `marker = ${JSON.stringify(readyMarker)}`,
  3549. `heartbeat = ${JSON.stringify(heartbeat)}`,
  3550. // Same group (no start_new_session); ignores SIGTERM; holds none of the
  3551. // leader's pipes (DEVNULL std streams, close_fds drops fd 3). It writes
  3552. // the marker (argv[1]) only AFTER the trap is installed — so the leader
  3553. // cannot return, and the host cannot send SIGTERM, before it is ignored —
  3554. // then rewrites the heartbeat (argv[2]) every 50 ms for up to 30 s.
  3555. 'code = ("import signal, sys, time\\n"',
  3556. ' "signal.signal(signal.SIGTERM, signal.SIG_IGN)\\n"',
  3557. ' "open(sys.argv[1], \'w\').close()\\n"',
  3558. ' "end = time.time() + 30\\n"',
  3559. ' "while time.time() < end:\\n"',
  3560. ' " open(sys.argv[2], \'w\').close()\\n"',
  3561. ' " time.sleep(0.05)\\n")',
  3562. 'child = subprocess.Popen([sys.executable, "-c", code, marker, heartbeat],',
  3563. ' stdin=subprocess.DEVNULL,',
  3564. ' stdout=subprocess.DEVNULL,',
  3565. ' stderr=subprocess.DEVNULL)',
  3566. 'deadline = time.time() + 5',
  3567. 'while not os.path.exists(marker) and time.time() < deadline:',
  3568. ' time.sleep(0.02)',
  3569. 'return "spawned"',
  3570. ].join('\n'),
  3571. bindings: [],
  3572. })
  3573. expect(result.error).toBeUndefined()
  3574. expect(result.value).toBe('spawned')
  3575. // The trap really installed before the leader returned, so this is the
  3576. // SIGTERM-ignoring descendant, not one that would have died to the default.
  3577. expect(existsSync(readyMarker)).toBe(true)
  3578. // The grace-window SIGKILL (graceMs 300 + reap margin) empties the group. Once
  3579. // it has, the descendant stops bumping the heartbeat. Poll the heartbeat's
  3580. // mtime: two consecutive reads far enough apart with no change means it is no
  3581. // longer executing — true whether it was reaped or lingers as a zombie, so
  3582. // the assertion holds in a container whose init does not wait() orphans. The
  3583. // window (well under the 30 s self-timeout) proves the SIGKILL did the work.
  3584. const mtime = (): number => { try { return statSync(heartbeat).mtimeMs } catch { return 0 } }
  3585. const stopDeadline = Date.now() + 8_000
  3586. let last = mtime()
  3587. let still = false
  3588. while (Date.now() < stopDeadline) {
  3589. await new Promise(resolve => setTimeout(resolve, 400))
  3590. const now = mtime()
  3591. if (now === last && now !== 0) { still = true; break }
  3592. last = now
  3593. }
  3594. expect(still).toBe(true)
  3595. }, 20_000)
  3596. it('dispose awaits reaping of a same-group survivor from a completed run', async () => {
  3597. // The quiescence contract also holds for a run that ALREADY resolved: the run
  3598. // stays tracked in `live` until its process group is reaped, so a `dispose()`
  3599. // that races a just-returned run() still awaits the survivor rather than
  3600. // snapshotting an empty `live` and returning while it lives. Here the run
  3601. // completes (leaving a SIGTERM-ignoring same-group descendant), then dispose()
  3602. // is called; the heartbeat must be stale BY THE TIME dispose() resolves —
  3603. // proving teardown waited for the reap, not merely that the reap eventually
  3604. // happened.
  3605. const handoff = await makeTempDir('dsh-dispose-quiesce-')
  3606. const readyMarker = join(handoff, 'ready')
  3607. const heartbeat = join(handoff, 'heartbeat')
  3608. const { runtime, fiber } = await setup({ maxWallMs: 10_000, graceMs: 300 })
  3609. const result = await runtime.run({
  3610. program: [
  3611. 'import subprocess, sys, os, time',
  3612. `marker = ${JSON.stringify(readyMarker)}`,
  3613. `heartbeat = ${JSON.stringify(heartbeat)}`,
  3614. 'code = ("import signal, sys, time\\n"',
  3615. ' "signal.signal(signal.SIGTERM, signal.SIG_IGN)\\n"',
  3616. ' "open(sys.argv[1], \'w\').close()\\n"',
  3617. ' "end = time.time() + 30\\n"',
  3618. ' "while time.time() < end:\\n"',
  3619. ' " open(sys.argv[2], \'w\').close()\\n"',
  3620. ' " time.sleep(0.05)\\n")',
  3621. 'child = subprocess.Popen([sys.executable, "-c", code, marker, heartbeat],',
  3622. ' stdin=subprocess.DEVNULL,',
  3623. ' stdout=subprocess.DEVNULL,',
  3624. ' stderr=subprocess.DEVNULL)',
  3625. 'deadline = time.time() + 5',
  3626. 'while not os.path.exists(marker) and time.time() < deadline:',
  3627. ' time.sleep(0.02)',
  3628. 'return "spawned"',
  3629. ].join('\n'),
  3630. bindings: [],
  3631. })
  3632. expect(result.error).toBeUndefined()
  3633. expect(existsSync(readyMarker)).toBe(true)
  3634. // dispose() must not return until the group is reaped. After it resolves, the
  3635. // heartbeat must already be stale: read its mtime, wait past the heartbeat
  3636. // interval, and confirm it did not advance — the descendant is no longer
  3637. // executing (reaped or zombie), so teardown was genuinely quiescent.
  3638. await fiber.dispose()
  3639. const mtime = (): number => { try { return statSync(heartbeat).mtimeMs } catch { return 0 } }
  3640. const afterDispose = mtime()
  3641. // Pin the assertion to a heartbeat that actually ran: mtime() returns 0 when
  3642. // the file never existed, so without this the `toBe` below would pass
  3643. // vacuously (0 === 0) if the survivor never wrote a heartbeat at all.
  3644. expect(afterDispose).toBeGreaterThan(0)
  3645. await new Promise(resolve => setTimeout(resolve, 500))
  3646. expect(mtime()).toBe(afterDispose)
  3647. }, 20_000)
  3648. it('sends SIGKILL at the poll deadline when the event loop was blocked past both timers', async () => {
  3649. // If the host event loop is blocked (a big synchronous computation) from
  3650. // before the group-reap poll was scheduled until after the deadline, both the
  3651. // poll timer and the grace-window SIGKILL timer are overdue when the loop
  3652. // resumes. Node runs the earlier-scheduled poll first, so the SIGKILL timer
  3653. // may not have fired yet. The deadline arm must then send SIGKILL ITSELF
  3654. // rather than cancel the unfired escalation — otherwise a SIGTERM-ignoring
  3655. // same-group survivor is released for good. A synchronous busy-loop after
  3656. // run() resolves reproduces the block deterministically.
  3657. const handoff = await makeTempDir('dsh-deadline-')
  3658. const readyMarker = join(handoff, 'ready')
  3659. const heartbeat = join(handoff, 'heartbeat')
  3660. const graceMs = 300
  3661. const { runtime } = await setup({ maxWallMs: 10_000, graceMs })
  3662. const result = await runtime.run({
  3663. program: [
  3664. 'import subprocess, sys, os, time',
  3665. `marker = ${JSON.stringify(readyMarker)}`,
  3666. `heartbeat = ${JSON.stringify(heartbeat)}`,
  3667. 'code = ("import signal, sys, time\\n"',
  3668. ' "signal.signal(signal.SIGTERM, signal.SIG_IGN)\\n"',
  3669. ' "open(sys.argv[1], \'w\').close()\\n"',
  3670. ' "end = time.time() + 30\\n"',
  3671. ' "while time.time() < end:\\n"',
  3672. ' " open(sys.argv[2], \'w\').close()\\n"',
  3673. ' " time.sleep(0.05)\\n")',
  3674. 'child = subprocess.Popen([sys.executable, "-c", code, marker, heartbeat],',
  3675. ' stdin=subprocess.DEVNULL,',
  3676. ' stdout=subprocess.DEVNULL,',
  3677. ' stderr=subprocess.DEVNULL)',
  3678. 'deadline = time.time() + 5',
  3679. 'while not os.path.exists(marker) and time.time() < deadline:',
  3680. ' time.sleep(0.02)',
  3681. 'return "spawned"',
  3682. ].join('\n'),
  3683. bindings: [],
  3684. })
  3685. expect(result.error).toBeUndefined()
  3686. expect(existsSync(readyMarker)).toBe(true)
  3687. // Block the event loop synchronously past graceMs + CLOSE_REAP_MARGIN_MS
  3688. // (2000) with margin, so both timers are overdue when the loop resumes.
  3689. const blockUntil = Date.now() + graceMs + 2_000 + 800
  3690. while (Date.now() < blockUntil) { /* busy-wait, no yield */ }
  3691. // Yield: the overdue poll runs (group still non-empty, deadline passed) and
  3692. // must send SIGKILL itself. The survivor then stops bumping the heartbeat.
  3693. const mtime = (): number => { try { return statSync(heartbeat).mtimeMs } catch { return 0 } }
  3694. const stopDeadline = Date.now() + 5_000
  3695. let last = mtime()
  3696. let stopped = false
  3697. while (Date.now() < stopDeadline) {
  3698. await new Promise(resolve => setTimeout(resolve, 400))
  3699. const now = mtime()
  3700. if (now === last && now !== 0) { stopped = true; break }
  3701. last = now
  3702. }
  3703. expect(stopped).toBe(true)
  3704. }, 20_000)
  3705. })
  3706. describe('PythonCodeRuntime — hostile peer', () => {
  3707. it('drops garbage bytes and unknown-shape frames posted directly to fd 3', async () => {
  3708. // The model program can reach fd 3 and write anything. We inject a
  3709. // non-JSON line, a valid JSON but unknown-shape frame, and a broken done
  3710. // frame; the host must not crash, and the real `done` still settles the run.
  3711. const { runtime } = await setup()
  3712. const result = await runtime.run({
  3713. program: [
  3714. 'import os',
  3715. 'os.write(3, b"not-json\\n")',
  3716. 'os.write(3, b\'{"type":"unknown"}\\n\')',
  3717. 'os.write(3, b\'{"type":"done","error":{"message":42}}\\n\')',
  3718. 'return "survived"',
  3719. ].join('\n'),
  3720. bindings: [],
  3721. })
  3722. expect(result.error).toBeUndefined()
  3723. expect(result.value).toBe('survived')
  3724. })
  3725. it('answers a forged call frame for an unknown binding and never crashes', async () => {
  3726. // The unknown-binding reply path, driven through the id the host expects:
  3727. // the program lets its own first call claim id 0 and forges id 1, which the
  3728. // host answers with the `unknown binding` rejection the honest call would
  3729. // have received. A forged id out of sequence is dropped instead — that is
  3730. // the id-bound test below, not this one.
  3731. const { runtime } = await setup({ maxWallMs: 8_000 })
  3732. let seenLegitCall = false
  3733. const result = await runtime.run({
  3734. program: [
  3735. 'import os, json',
  3736. 'x = await tools.echo({"ping": True})',
  3737. 'os.write(3, json.dumps({"type":"call","id":1,"global":"tools","name":"forged","args":{}}).encode() + b"\\n")',
  3738. // The forged frame is answered, but nothing in the child awaits id 1, so
  3739. // the reply is ignored and the run completes on its own value.
  3740. 'return x',
  3741. ].join('\n'),
  3742. bindings: tools({
  3743. echo: async (args) => { seenLegitCall = true; return args as CodeJsonValue },
  3744. }),
  3745. })
  3746. expect(result.error).toBeUndefined()
  3747. expect(result.value).toEqual({ ping: true })
  3748. expect(seenLegitCall).toBe(true)
  3749. }, 15_000)
  3750. it('caps the unknown-binding preview for a huge forged name', async () => {
  3751. // The unknown-binding reply's JSON.stringify ran on the WHOLE capped
  3752. // target, allocating the escaped form — up to ~6x under control-heavy
  3753. // input. The preview is now built from a 1 KiB prefix, so a forged call
  3754. // with a huge global/name cannot spike host memory near the value ceiling;
  3755. // the reply still identifies the binding.
  3756. const { runtime } = await setup({ maxWallMs: 8_000, maxValueBytes: 1024 * 1024 })
  3757. const result = await runtime.run({
  3758. program: [
  3759. 'import os, json',
  3760. 'x = await tools.echo({"ping": True})',
  3761. 'name = "n" * 100000',
  3762. 'os.write(3, json.dumps({"type":"call","id":1,"global":"tools","name":name,"args":{}}).encode() + b"\\n")',
  3763. 'return x',
  3764. ].join('\n'),
  3765. bindings: tools({
  3766. echo: async args => args as CodeJsonValue,
  3767. }),
  3768. })
  3769. expect(result.error).toBeUndefined()
  3770. expect(result.value).toEqual({ ping: true })
  3771. }, 15_000)
  3772. it('drops forged call frames whose ids are not the next in sequence, retaining no per-id state', async () => {
  3773. // The host used to remember every answered id in a Set, so a program could
  3774. // write an unbounded run of unique forged ids — each frame far below the
  3775. // 64 MiB cap, so nothing rejected them — and grow host memory for the
  3776. // whole run. Ids are consecutive from 0, so one counter replaces the set.
  3777. //
  3778. // The discriminator is that the forgeries must not be answered. Each names a
  3779. // binding that does exist, so a host answering them would run `echo` once
  3780. // per forgery; the count proves only the legitimate call was dispatched.
  3781. // Ids also run DESCENDING, so a high-water-mark test would drop the honest
  3782. // call that follows rather than the forgeries.
  3783. const { runtime } = await setup()
  3784. let echoCalls = 0
  3785. const result = await runtime.run({
  3786. program: [
  3787. 'import os, json',
  3788. 'for i in range(2000, 0, -1):',
  3789. ' os.write(3, json.dumps({"type":"call","id":i,"global":"tools","name":"echo","args":{"forged":i}}).encode() + b"\\n")',
  3790. 'x = await tools.echo({"ping": True})',
  3791. 'return x',
  3792. ].join('\n'),
  3793. bindings: tools({
  3794. echo: async (args) => { echoCalls += 1; return args as CodeJsonValue },
  3795. }),
  3796. })
  3797. expect(result.error).toBeUndefined()
  3798. expect(result.value).toEqual({ ping: true })
  3799. expect(echoCalls).toBe(1)
  3800. }, 15_000)
  3801. it('keeps answering calls a program makes after one with unserializable arguments', async () => {
  3802. // The child claims an id only once its write succeeds, so a call rejected
  3803. // child-side for non-lossless arguments leaves no gap. Were a gap possible,
  3804. // the host's exact-successor test would drop every later call and the run
  3805. // would hang to the wall ceiling instead of completing.
  3806. const { runtime } = await setup({ maxWallMs: 8_000 })
  3807. const seen: unknown[] = []
  3808. const result = await runtime.run({
  3809. program: [
  3810. 'caught = ""',
  3811. 'try:',
  3812. ' await tools.echo({"bad": float("inf")})',
  3813. 'except RuntimeError as e:',
  3814. ' caught = str(e)',
  3815. 'after = await tools.echo({"ok": True})',
  3816. 'return {"caught": caught, "after": after}',
  3817. ].join('\n'),
  3818. bindings: tools({
  3819. echo: async (args) => { seen.push(args); return args as CodeJsonValue },
  3820. }),
  3821. })
  3822. expect(result.error).toBeUndefined()
  3823. const value = result.value as { caught: string; after: unknown }
  3824. expect(value.caught).toContain('lossless JSON')
  3825. expect(value.after).toEqual({ ok: true })
  3826. // The rejected call never reached the host; the one after it did.
  3827. expect(seen).toEqual([{ ok: true }])
  3828. }, 15_000)
  3829. it('drops a forged frame carrying an integer outside JavaScript safe range', async () => {
  3830. // JSON.parse would silently round 9007199254740993 to ...992 BEFORE any
  3831. // validation, corrupting a dispatched argument or completion. The host
  3832. // scans the raw line and drops such frames as hostile traffic; the honest
  3833. // child cannot produce one (its validator rejects unsafe ints).
  3834. const { runtime } = await setup()
  3835. let dispatched: unknown
  3836. const result = await runtime.run({
  3837. program: [
  3838. 'import os',
  3839. // Forged call frame with an unsafe int argument, then a forged done
  3840. // frame with an unsafe int value — both must be dropped whole.
  3841. 'os.write(3, b\'{"type":"call","id":7,"global":"tools","name":"echo","args":9007199254740993}\\n\')',
  3842. 'os.write(3, b\'{"type":"done","value":9007199254740993}\\n\')',
  3843. 'x = await tools.echo({"ok": True})',
  3844. 'return x',
  3845. ].join('\n'),
  3846. bindings: tools({
  3847. echo: async (args) => { dispatched = args; return args as CodeJsonValue },
  3848. }),
  3849. })
  3850. expect(result.error).toBeUndefined()
  3851. // The forged done did not settle the run; the legit call and completion did.
  3852. expect(result.value).toEqual({ ok: true })
  3853. expect(dispatched).toEqual({ ok: true })
  3854. })
  3855. it('truncates host-side logs once the budget is exhausted and emits the marker', async () => {
  3856. // Set a tiny host-side budget; the Python side has a much larger one, so
  3857. // its LogBuffer will not truncate — the host ledger fires first.
  3858. const { runtime } = await setup({ maxLogBytes: 128 })
  3859. const result = await runtime.run({
  3860. program: [
  3861. 'for _ in range(50):',
  3862. ' print("aaaaaaaaaa")',
  3863. 'return "done"',
  3864. ].join('\n'),
  3865. bindings: [],
  3866. })
  3867. expect(result.error).toBeUndefined()
  3868. const markers = result.logs.filter(line => line.includes('log capture truncated at 128 bytes'))
  3869. expect(markers.length).toBeGreaterThanOrEqual(1)
  3870. })
  3871. it('reports an exception whose message holds an unpaired surrogate instead of stranding to the wall clock', async () => {
  3872. // A strict UTF-8 encode of "\ud800" throws while BUILDING the failure
  3873. // frame; the run would then hang to maxWallMs and misreport as timeout.
  3874. const { runtime } = await setup({ maxWallMs: 8_000 })
  3875. const result = await runtime.run({
  3876. program: String.raw`raise Exception("bad \ud800 surrogate")`,
  3877. bindings: [],
  3878. })
  3879. expect(result.error?.kind).toBe('exception')
  3880. expect(result.error?.message).toContain('bad')
  3881. expect(result.error?.message).toContain('surrogate')
  3882. })
  3883. it('carries a lone-surrogate completion string across the wire as its JSON escape', async () => {
  3884. // UTF-8 has no encoding for a lone surrogate, but JSON does: the ASCII
  3885. // `\ud800` escape, which JSON.parse reads back as the same UTF-16 code
  3886. // unit. `CodeJsonValue`, `snapshotJsonValue`, and the worker backend all
  3887. // accept such a string, so this backend must not narrow the shared seam.
  3888. const { runtime } = await setup()
  3889. const result = await runtime.run({
  3890. program: String.raw`return {"lone": "a\ud800b", "spelled": "😀"}`,
  3891. bindings: [],
  3892. })
  3893. expect(result.error).toBeUndefined()
  3894. // The lone half survives as the code unit itself; a spelled-out high-low
  3895. // PAIR folds into the astral character the host would hold for it.
  3896. expect(result.value).toEqual({ lone: 'a\ud800b', spelled: '\u{1f600}' })
  3897. })
  3898. it('meters a lone surrogate at its six escaped bytes, matching the host', async () => {
  3899. // The child and the host share maxValueBytes, so the child must charge the
  3900. // escape's six ASCII bytes (plus two quotes): eight fits, nine does not.
  3901. const { runtime } = await setup({ maxValueBytes: 8 })
  3902. const ok = await runtime.run({ program: String.raw`return "\ud800"`, bindings: [] })
  3903. expect(ok.error).toBeUndefined()
  3904. expect(ok.value).toBe('\ud800')
  3905. const over = await setup({ maxValueBytes: 7 })
  3906. const result = await over.runtime.run({ program: String.raw`return "\ud800"`, bindings: [] })
  3907. expect(result.error?.kind).toBe('output-limit')
  3908. })
  3909. it('meters a surrogate-dense completion by counting, not by materializing a match list', async () => {
  3910. // `_json_str_cost` counted lone surrogates with `_SURROGATE.findall`,
  3911. // which materializes one single-character string PER surrogate: a
  3912. // surrogate-dense value near the budget (each surrogate serializes to six
  3913. // bytes, so a budget-sized value holds millions of them) would allocate
  3914. // millions of objects before the meter returned — an O(N)-objects spike
  3915. // that defeats the meter's documented contract of counting without
  3916. // building. The count is now a length difference over the removal `sub`
  3917. // already performs. Three million lone surrogates pin the boundary at
  3918. // scale: 18,000,002 serialized bytes succeed at an 18,000,002 budget and
  3919. // report output-limit one byte under, proving the meter counts every
  3920. // surrogate exactly rather than dropping or over-charging any.
  3921. const { runtime } = await setup({ maxValueBytes: 18_000_002 })
  3922. const ok = await runtime.run({ program: 'return "\\ud800" * 3000000', bindings: [] })
  3923. expect(ok.error).toBeUndefined()
  3924. expect(ok.value).toBe('\ud800'.repeat(3_000_000))
  3925. const over = await setup({ maxValueBytes: 18_000_001 })
  3926. const result = await over.runtime.run({ program: 'return "\\ud800" * 3000000', bindings: [] })
  3927. expect(result.error?.kind).toBe('output-limit')
  3928. }, 60_000)
  3929. it('passes a lone-surrogate binding argument through instead of failing the call', async () => {
  3930. // The argument validator shared the same over-narrow rejection; a host
  3931. // binding must receive the code unit the program passed.
  3932. const seen: unknown[] = []
  3933. const { runtime } = await setup()
  3934. const result = await runtime.run({
  3935. program: String.raw`return await tools.echo({"text": "x\udfff"})`,
  3936. bindings: tools({ echo: async (args: unknown) => { seen.push(args); return args as CodeJsonValue } }),
  3937. })
  3938. expect(result.error).toBeUndefined()
  3939. expect(seen).toEqual([{ text: 'x\udfff' }])
  3940. expect(result.value).toEqual({ text: 'x\udfff' })
  3941. })
  3942. it('meters a non-ASCII completion in UTF-8 JSON bytes, matching the host', async () => {
  3943. // json.dumps' default \uXXXX escaping would count "é" as 8 bytes while
  3944. // the host meter counts its UTF-8 JSON form (4); the shared budget must
  3945. // agree, so a 4-byte-fitting value passes a maxValueBytes of 4.
  3946. const { runtime } = await setup({ maxValueBytes: 4 })
  3947. const ok = await runtime.run({ program: 'return "é"', bindings: [] })
  3948. expect(ok.error).toBeUndefined()
  3949. expect(ok.value).toBe('é')
  3950. const over = await runtime.run({ program: 'return "éx"', bindings: [] })
  3951. expect(over.error?.kind).toBe('output-limit')
  3952. })
  3953. it('filters bootstrap frames from exception-group members (TaskGroup)', async () => {
  3954. // Python 3.11+ stores member stacks under TracebackException.exceptions;
  3955. // the <model>-frame filter must recurse into them too.
  3956. const { runtime } = await setup()
  3957. const result = await runtime.run({
  3958. program: [
  3959. 'import asyncio, sys',
  3960. 'if sys.version_info < (3, 11):',
  3961. ' raise ValueError("skip-old <model>")',
  3962. 'async def boom():',
  3963. ' raise ValueError("group-member")',
  3964. 'async with asyncio.TaskGroup() as tg:',
  3965. ' tg.create_task(boom())',
  3966. ].join('\n'),
  3967. bindings: [],
  3968. })
  3969. expect(result.error?.kind).toBe('exception')
  3970. expect(result.error?.message).toContain('<model>')
  3971. expect(result.error?.message).not.toContain('bootstrap.py')
  3972. })
  3973. it('keeps frames intact when a model thread floods logs while a large frame drains', async () => {
  3974. // os.write releases the GIL and a frame beyond PIPE_BUF is not atomic:
  3975. // without the writer lock + full-write loop, the printing thread could
  3976. // interleave bytes mid-frame and the host would drop the malformed JSON,
  3977. // hanging the run to the wall clock (or losing the completion).
  3978. const { runtime } = await setup({ maxValueBytes: 1024 * 1024, maxLogBytes: 4 * 1024 * 1024, maxWallMs: 15_000 })
  3979. const result = await runtime.run({
  3980. program: [
  3981. 'import threading',
  3982. 'stop = False',
  3983. 'def spam():',
  3984. ' while not stop:',
  3985. ' print("spam-line-" + "y" * 100)',
  3986. 't = threading.Thread(target=spam)',
  3987. 't.start()',
  3988. // A ~300 KiB completion — several PIPE_BUF units — while spam runs.
  3989. 'big = "x" * (300 * 1024)',
  3990. 'stop = True',
  3991. 't.join()',
  3992. 'return big',
  3993. ].join('\n'),
  3994. bindings: [],
  3995. })
  3996. expect(result.error).toBeUndefined()
  3997. expect(result.value).toBe('x'.repeat(300 * 1024))
  3998. }, 20_000)
  3999. it('settles cleanly while a daemon thread keeps writing unterminated log text', async () => {
  4000. // WARNING regression: the settlement `flush_out()/flush_err()` on the main
  4001. // coroutine read and clear `_LogStream._pending` and the shared LogBuffer
  4002. // ledger with NO lock, while a model daemon thread's `print`/`write` mutate
  4003. // the same state. Capturing the bound method (`out_stream.flush_line`) only
  4004. // fixes WHICH callable runs, not what it reads mid-flight: the flush could
  4005. // interleave with a concurrent write and join a `_pending` list being
  4006. // mutated under it, corrupting the ledger and costing the `done` frame — the
  4007. // run would then strand to the wall clock instead of completing. The shared
  4008. // re-entrant lock serializes them.
  4009. //
  4010. // A pure data race has no single bad input to reject deterministically, so
  4011. // this maximizes overlap: daemon threads emit UNTERMINATED writes (which
  4012. // pile into `_pending` rather than flushing per line) right up to the moment
  4013. // the body returns and settlement flushes. Repeated so the interleave lands.
  4014. for (let attempt = 0; attempt < 5; attempt++) {
  4015. const { runtime, fiber } = await setup({ maxLogBytes: 4 * 1024 * 1024, maxWallMs: 15_000 })
  4016. const result = await runtime.run({
  4017. program: [
  4018. 'import sys, threading',
  4019. 'stop = False',
  4020. 'def spam():',
  4021. ' while not stop:',
  4022. // No newline: the text accumulates in the stream's `_pending`, which is
  4023. // exactly the state the settlement flush also touches.
  4024. ' sys.stdout.write("tail-fragment-" + "z" * 64)',
  4025. 'workers = [threading.Thread(target=spam, daemon=True) for _ in range(4)]',
  4026. 'for t in workers: t.start()',
  4027. // Let the daemons build up pending writes, then return so settlement
  4028. // flushes while they are still mid-write.
  4029. 'import time; time.sleep(0.05)',
  4030. 'return "settled"',
  4031. ].join('\n'),
  4032. bindings: [],
  4033. })
  4034. expect(result.error).toBeUndefined()
  4035. expect(result.value).toBe('settled')
  4036. await fiber.dispose()
  4037. }
  4038. }, 30_000)
  4039. it('completes a binding called from a worker thread on its own event loop', async () => {
  4040. // A binding reply Future is created on the loop that ran `dispatch`. When the
  4041. // model calls a binding from a worker THREAD via `asyncio.run(tools.x(...))`,
  4042. // that Future belongs to the thread's loop, not the main loop where
  4043. // `_pump_replies` reads the reply. `asyncio.Future` is not thread-safe:
  4044. // completing it from another thread does not wake its own loop, so a direct
  4045. // `set_result` would strand the awaiting thread and the run would degrade to a
  4046. // wall-clock timeout. The pump must schedule completion on the Future's own
  4047. // loop via `call_soon_threadsafe`. The tight maxWallMs makes the pre-fix
  4048. // failure a fast timeout rather than a hang.
  4049. //
  4050. // The main coroutine yields with `await asyncio.sleep` while the worker runs,
  4051. // rather than a synchronous `t.join()`: joining would block the main thread,
  4052. // so the main loop could not run `_pump_replies` and the call would deadlock
  4053. // regardless of the fix — that blocks the pump, not the cross-loop delivery
  4054. // this test pins.
  4055. const { runtime } = await setup({ maxWallMs: 8_000 })
  4056. const seen: unknown[] = []
  4057. const result = await runtime.run({
  4058. program: [
  4059. 'import asyncio, threading',
  4060. 'result = {}',
  4061. 'def worker():',
  4062. // A fresh loop in this thread; the binding Future is created here.
  4063. ' result["value"] = asyncio.run(tools.echo({"from": "thread"}))',
  4064. 't = threading.Thread(target=worker)',
  4065. 't.start()',
  4066. 'while t.is_alive():',
  4067. ' await asyncio.sleep(0.02)',
  4068. 'return result["value"]',
  4069. ].join('\n'),
  4070. bindings: tools({
  4071. echo: async (args) => { seen.push(args); return args as CodeJsonValue },
  4072. }),
  4073. })
  4074. expect(result.error).toBeUndefined()
  4075. expect(result.value).toEqual({ from: 'thread' })
  4076. // The host binding actually ran (the reply round-tripped), not a timeout.
  4077. expect(seen).toEqual([{ from: 'thread' }])
  4078. }, 15_000)
  4079. it('keeps the reply pump alive when a late reply targets a closed thread loop', async () => {
  4080. // A binding called from a worker thread that ABANDONS the call (its
  4081. // `asyncio.run` is cancelled) leaves the pending entry holding that thread's
  4082. // loop, which `asyncio.run` closes on return. When the host later answers
  4083. // that call, `_pump_replies` schedules the completion onto the closed loop —
  4084. // `call_soon_threadsafe` raises `RuntimeError('Event loop is closed')`.
  4085. // Unguarded, that RuntimeError ends the pump task and strands every later
  4086. // reply; the guard drops the moot reply and keeps the pump serving.
  4087. //
  4088. // The ordering is a STRUCTURAL guarantee, not a timing window: the worker
  4089. // closes its loop before the main coroutine signals `closed`; the host
  4090. // answers the abandoned `slow` call (hitting the closed loop) before it
  4091. // answers `release`, because `release`'s handler only resolves `slow` first
  4092. // and then yields a microtask. So the pump provably meets the closed loop on
  4093. // `slow`'s reply before it must deliver `release`'s. Fail-before: the pump
  4094. // dies on `slow`, `release`'s reply is never read, and `await tools.release`
  4095. // hangs to the (small) maxWallMs as a timeout.
  4096. let releaseSlow!: () => void
  4097. const slowGate = new Promise<void>((resolve) => { releaseSlow = resolve })
  4098. const { runtime } = await setup({ maxWallMs: 6_000 })
  4099. const result = await runtime.run({
  4100. program: [
  4101. 'import asyncio, threading',
  4102. 'closed = threading.Event()',
  4103. 'def worker():',
  4104. ' async def body():',
  4105. // Abandon the call: wait_for cancels it, but the pending host-side entry
  4106. // survives (dispatch does not pop on cancellation), holding this loop.
  4107. ' try:',
  4108. ' await asyncio.wait_for(tools.slow({}), timeout=0.1)',
  4109. ' except asyncio.TimeoutError:',
  4110. ' pass',
  4111. ' asyncio.run(body())', // closes the thread's loop on return
  4112. ' closed.set()',
  4113. 't = threading.Thread(target=worker)',
  4114. 't.start()',
  4115. 'while not closed.is_set():',
  4116. ' await asyncio.sleep(0.02)',
  4117. // The loop is closed. Now the host answers slow (dead-loop reply) then
  4118. // release; the pump must survive the first to deliver the second.
  4119. 'after = await tools.release({})',
  4120. 'return after',
  4121. ].join('\n'),
  4122. bindings: tools({
  4123. slow: async () => {
  4124. // Answer only once the worker has closed its loop AND the main
  4125. // coroutine is awaiting release, so this reply reaches the pump against
  4126. // the closed loop.
  4127. await slowGate
  4128. return 'late'
  4129. },
  4130. release: async () => {
  4131. // Let slow's reply be written first, then yield a microtask so the
  4132. // pump processes the dead-loop reply before release's own reply lands.
  4133. releaseSlow()
  4134. await new Promise(resolve => setImmediate(resolve))
  4135. return 'released'
  4136. },
  4137. }),
  4138. })
  4139. expect(result.error).toBeUndefined()
  4140. // The pump survived the closed-loop reply and delivered the later binding.
  4141. expect(result.value).toBe('released')
  4142. }, 15_000)
  4143. it('keeps the reply pump alive when RuntimeError is rebound before the program runs', async () => {
  4144. // `_pump_replies` catches a closed-loop scheduling failure with `except
  4145. // _RuntimeError`. If that name were bound as a pump BODY local, it would be
  4146. // captured at pump-start — but `_run` reaches the model's top-level
  4147. // statements (which run before the pump's first step, since there is no
  4148. // suspension point between `create_task` and `await __dsh_main__`) with the
  4149. // rebind already applied, so `_RuntimeError` would capture the REBOUND class
  4150. // and the closed-loop `RuntimeError` would escape, killing the pump. Binding
  4151. // it as a DEF-TIME default argument captures the original before any model
  4152. // code runs. This rebinds `__main__.RuntimeError` as the very first program
  4153. // statement and drives the closed-loop worker pattern: the pump must survive
  4154. // the dead-loop reply and deliver the later binding.
  4155. let releaseSlow!: () => void
  4156. const slowGate = new Promise<void>((resolve) => { releaseSlow = resolve })
  4157. const { runtime } = await setup({ maxWallMs: 6_000 })
  4158. const result = await runtime.run({
  4159. program: [
  4160. 'import __main__',
  4161. '__main__.RuntimeError = ValueError',
  4162. 'import asyncio, threading',
  4163. 'closed = threading.Event()',
  4164. 'def worker():',
  4165. ' async def body():',
  4166. ' try:',
  4167. ' await asyncio.wait_for(tools.slow({}), timeout=0.1)',
  4168. ' except asyncio.TimeoutError:',
  4169. ' pass',
  4170. ' asyncio.run(body())',
  4171. ' closed.set()',
  4172. 't = threading.Thread(target=worker)',
  4173. 't.start()',
  4174. 'while not closed.is_set():',
  4175. ' await asyncio.sleep(0.02)',
  4176. 'after = await tools.release({})',
  4177. 'return after',
  4178. ].join('\n'),
  4179. bindings: tools({
  4180. slow: async () => { await slowGate; return 'late' },
  4181. release: async () => { releaseSlow(); await new Promise(resolve => setImmediate(resolve)); return 'released' },
  4182. }),
  4183. })
  4184. expect(result.error).toBeUndefined()
  4185. expect(result.value).toBe('released')
  4186. }, 15_000)
  4187. it('keeps a successful completion when _done_with_value is rebound', async () => {
  4188. // `_run` calls `_done_with_value(value, max_value_bytes)` after the program
  4189. // returns. The name is a module global, and this bootstrap IS `__main__`, so
  4190. // `__main__._done_with_value = boom` as a program statement would otherwise
  4191. // be resolved at call time and a legitimate success would be rewritten into
  4192. // an `exception`. `_run` now binds `done_with_value_bound = _done_with_value`
  4193. // before the program runs, so the entry name is immune; the run must still
  4194. // report the success value.
  4195. const { runtime } = await setup({ maxWallMs: 10_000 })
  4196. const result = await runtime.run({
  4197. program: [
  4198. 'import __main__',
  4199. 'def boom(*a, **k):',
  4200. ' raise RuntimeError("hijacked")',
  4201. '__main__._done_with_value = boom',
  4202. 'return 1',
  4203. ].join('\n'),
  4204. bindings: [],
  4205. })
  4206. expect(result.error).toBeUndefined()
  4207. expect(result.value).toBe(1)
  4208. }, 15_000)
  4209. it('round-trips an exactly representable large integer through a binding echo', async () => {
  4210. // The reply serializer must print BigInt digits for a beyond-safe
  4211. // integral double: String(2**60) emits a rounded form, and the child
  4212. // would receive a DIFFERENT integer than the binding resolved.
  4213. const { runtime } = await setup()
  4214. const result = await runtime.run({
  4215. program: [
  4216. 'v = await tools.echo(2**60)',
  4217. 'return v == 2**60',
  4218. ].join('\n'),
  4219. bindings: tools({ echo: async args => args as never }),
  4220. })
  4221. expect(result.error).toBeUndefined()
  4222. expect(result.value).toBe(true)
  4223. })
  4224. it('preserves an exactly representable large integer and rejects a rounding one', async () => {
  4225. // The canonical boundary accepts every JS-double-exact value: 2**53 and
  4226. // 2**60 round-trip exactly and must cross (matching the worker backend);
  4227. // 2**53+1 rounds and must fail as invalid-output.
  4228. const { runtime } = await setup()
  4229. const exact = await runtime.run({ program: 'return [2**53, 2**60]', bindings: [] })
  4230. expect(exact.error).toBeUndefined()
  4231. expect(exact.value).toEqual([2 ** 53, 2 ** 60])
  4232. const lossy = await runtime.run({ program: 'return 2**53 + 1', bindings: [] })
  4233. expect(lossy.error?.kind).toBe('invalid-output')
  4234. expect(lossy.error?.message).toContain('not exactly representable')
  4235. })
  4236. it('rejects a container subclass whose overridden methods hide its contents', async () => {
  4237. // A dict subclass returning [] from items() passes an isinstance check but
  4238. // serializes as {}, so the host would receive a value the program did not
  4239. // compute. Exact-type matching fails it as invalid-output instead. The
  4240. // worker backend rejects the prototype-equivalent shapes the same way.
  4241. const { runtime } = await setup()
  4242. const hidden = await runtime.run({
  4243. program: [
  4244. 'class Sneaky(dict):',
  4245. ' def items(self): return []',
  4246. ' def keys(self): return []',
  4247. ' def __iter__(self): return iter([])',
  4248. ' def __len__(self): return 0',
  4249. 'return Sneaky(secret="kept")',
  4250. ].join('\n'),
  4251. bindings: [],
  4252. })
  4253. expect(hidden.error?.kind).toBe('invalid-output')
  4254. expect(hidden.error?.message).toContain('unsupported type (Sneaky)')
  4255. // A list subclass is refused on the same rule.
  4256. const listish = await runtime.run({
  4257. program: ['class L(list):', ' def __iter__(self): return iter([])', 'return L([1, 2, 3])'].join('\n'),
  4258. bindings: [],
  4259. })
  4260. expect(listish.error?.kind).toBe('invalid-output')
  4261. expect(listish.error?.message).toContain('unsupported type (L)')
  4262. // The exact built-in containers still cross unchanged.
  4263. const plain = await runtime.run({ program: 'return {"secret": [1, 2]}', bindings: [] })
  4264. expect(plain.error).toBeUndefined()
  4265. expect(plain.value).toEqual({ secret: [1, 2] })
  4266. })
  4267. it('rejects a scalar subclass whose overrides disagree with what gets serialized', async () => {
  4268. // The validators checked scalars with isinstance, so a subclass passed
  4269. // every check by its real value while the ENCODER read an override — the
  4270. // host then received a value the walk never approved. Each case below is a
  4271. // distinct override reaching a distinct reader.
  4272. const { runtime } = await setup()
  4273. // _dump_float spells a float from repr(value), so an overridden __repr__
  4274. // decides the digits: F(2.5) serialized as 1.
  4275. const floated = await runtime.run({
  4276. program: [
  4277. 'class F(float):',
  4278. ' def __repr__(self): return "1.0"',
  4279. 'return F(2.5)',
  4280. ].join('\n'),
  4281. bindings: [],
  4282. })
  4283. expect(floated.error?.kind).toBe('invalid-output')
  4284. expect(floated.error?.message).toContain('unsupported type (F)')
  4285. // The JS-safe-range bound is two comparisons, so overriding them admits an
  4286. // int whose true digits (json.dumps reads the C-level value) the host's
  4287. // JSON.parse rounds: 9007199254740993 arrives as ...992.
  4288. const inted = await runtime.run({
  4289. program: [
  4290. 'class I(int):',
  4291. ' def __gt__(self, other): return False',
  4292. ' def __lt__(self, other): return False',
  4293. 'return I(2 ** 53 + 1)',
  4294. ].join('\n'),
  4295. bindings: [],
  4296. })
  4297. expect(inted.error?.kind).toBe('invalid-output')
  4298. expect(inted.error?.message).toContain('unsupported type (I)')
  4299. // The pre-encode size bound reads len(), so overriding it to 0 admits a
  4300. // string of any length past maxValueBytes.
  4301. const stringed = await runtime.run({
  4302. program: [
  4303. 'class S(str):',
  4304. ' def __len__(self): return 0',
  4305. 'return S("Q" * 100000)',
  4306. ].join('\n'),
  4307. bindings: [],
  4308. })
  4309. expect(stringed.error?.kind).toBe('invalid-output')
  4310. expect(stringed.error?.message).toContain('unsupported type (S)')
  4311. // A str-subclass dict KEY reaches the same len() bound.
  4312. const keyed = await runtime.run({
  4313. program: [
  4314. 'class S(str):',
  4315. ' def __len__(self): return 0',
  4316. 'return {S("Q" * 100000): 1}',
  4317. ].join('\n'),
  4318. bindings: [],
  4319. })
  4320. expect(keyed.error?.kind).toBe('invalid-output')
  4321. expect(keyed.error?.message).toContain('non-string dict key (S)')
  4322. // bool is an int subclass that IS lossless JSON, and the exact scalars all
  4323. // still cross unchanged.
  4324. const plain = await runtime.run({
  4325. program: 'return {"t": True, "f": False, "n": None, "i": 7, "d": 2.5, "s": "ok"}',
  4326. bindings: [],
  4327. })
  4328. expect(plain.error).toBeUndefined()
  4329. expect(plain.value).toEqual({ t: true, f: false, n: null, i: 7, d: 2.5, s: 'ok' })
  4330. })
  4331. it('rejects a scalar subclass passed as a binding argument', async () => {
  4332. // The uncapped binding-argument validator shares the exact-type rule, so
  4333. // the call fails through its rejection contract instead of dispatching a
  4334. // float whose digits come from an override.
  4335. const { runtime } = await setup()
  4336. const seen: CodeJsonValue[] = []
  4337. const result = await runtime.run({
  4338. program: [
  4339. 'class F(float):',
  4340. ' def __repr__(self): return "1.0"',
  4341. 'try:',
  4342. ' await tools.echo({"v": F(2.5)})',
  4343. 'except Exception as exc:',
  4344. ' return str(exc)',
  4345. ].join('\n'),
  4346. bindings: tools({ echo: async (args) => {
  4347. seen.push(args as CodeJsonValue)
  4348. return null
  4349. } }),
  4350. })
  4351. expect(result.error).toBeUndefined()
  4352. expect(result.value).toContain('unsupported type (F)')
  4353. expect(seen).toEqual([])
  4354. })
  4355. it('rejects a container subclass passed as a binding argument', async () => {
  4356. // Binding arguments run the uncapped validator, which must apply the same
  4357. // exact-type rule: the call fails descriptively instead of dispatching a
  4358. // value whose serialization disagrees with what was validated.
  4359. const { runtime } = await setup()
  4360. const seen: CodeJsonValue[] = []
  4361. const result = await runtime.run({
  4362. program: [
  4363. 'class Sneaky(dict):',
  4364. ' def items(self): return []',
  4365. 'try:',
  4366. ' await tools.echo(Sneaky(secret="kept"))',
  4367. 'except Exception as exc:',
  4368. ' return str(exc)',
  4369. ].join('\n'),
  4370. bindings: tools({ echo: async (args) => {
  4371. seen.push(args as CodeJsonValue)
  4372. return null
  4373. } }),
  4374. })
  4375. expect(result.error).toBeUndefined()
  4376. expect(result.value).toContain('unsupported type (Sneaky)')
  4377. expect(seen).toEqual([])
  4378. })
  4379. it('fails an oversized completion as output-limit without materializing its encoding', async () => {
  4380. // A 100 MiB string under maxValueBytes: 1024 must fail as output-limit.
  4381. // The address-space cap leaves room for the program to BUILD the string
  4382. // (one copy + interpreter) but not for the old full pre-check encode,
  4383. // which materialized chunk fragments plus the joined copy (~2 more
  4384. // copies) and died on RLIMIT_AS as MemoryError/worker-exit.
  4385. const { runtime } = await setup({ maxValueBytes: 1024, addressSpaceMb: 384, maxWallMs: 15_000 })
  4386. const result = await runtime.run({
  4387. program: 'return "x" * (100 * 1024 * 1024)',
  4388. bindings: [],
  4389. })
  4390. expect(result.error?.kind).toBe('output-limit')
  4391. expect(result.error?.message).toContain('exceeded 1024 bytes')
  4392. }, 20_000)
  4393. it('rejects a control-heavy oversized completion on its length, not its escaped copy', async () => {
  4394. // Every "\x00" escapes to the six bytes "\u0000", so the escaped form of a
  4395. // 40 MB string is ~240 MB. The walk must refuse on the cheap
  4396. // `len(current) + 2` lower bound; the 384 MiB address space holds the raw
  4397. // string but not its escaped expansion, so a pre-escape check dies on
  4398. // RLIMIT_AS instead of returning output-limit.
  4399. const { runtime } = await setup({ maxValueBytes: 1024, addressSpaceMb: 384, maxWallMs: 15_000 })
  4400. const result = await runtime.run({
  4401. program: 'return "\\x00" * (40 * 1024 * 1024)',
  4402. bindings: [],
  4403. })
  4404. expect(result.error?.kind).toBe('output-limit')
  4405. expect(result.error?.message).toContain('exceeded 1024 bytes')
  4406. }, 20_000)
  4407. it('truncates a single print far above maxLogBytes instead of dying on the encode', async () => {
  4408. // LogBuffer must reject via the cheap char-count lower bound BEFORE
  4409. // UTF-8-encoding the whole string: the full encode of a ~100 MB line
  4410. // would double the allocation and can breach RLIMIT_AS. 256 MiB
  4411. // address space comfortably holds one copy of the 100 MB string but
  4412. // not the pre-fix double allocation plus interpreter overhead spikes.
  4413. const { runtime } = await setup({ maxLogBytes: 1024, addressSpaceMb: 256, maxWallMs: 15_000 })
  4414. const result = await runtime.run({
  4415. program: [
  4416. 'print("x" * (100 * 1024 * 1024))',
  4417. 'return "done"',
  4418. ].join('\n'),
  4419. bindings: [],
  4420. })
  4421. expect(result.error).toBeUndefined()
  4422. expect(result.value).toBe('done')
  4423. expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
  4424. }, 20_000)
  4425. it('stops host capture at the child ledger truncation, keeping exactly one marker', async () => {
  4426. // The two ledgers exhaust independently. One child entry larger than
  4427. // `maxLogBytes` sends ONLY the marker, so the host budget is still nearly
  4428. // untouched — and the marker used to arrive as an ordinary `log` frame the
  4429. // host could not tell from program output. Text written afterwards was
  4430. // therefore retained AFTER the marker, contradicting the stop-after-
  4431. // truncation contract, and a later host-side exhaustion could append a
  4432. // second marker. The frame now carries `truncated: true`.
  4433. //
  4434. // `os.write(1, ...)` bypasses the child's own stream, so those bytes reach
  4435. // the host as stray stdout and take the host ledger path rather than the
  4436. // child's — which is exactly the route that leaked past the marker.
  4437. const { runtime } = await setup({ maxLogBytes: 64, maxWallMs: 10_000 })
  4438. const result = await runtime.run({
  4439. program: [
  4440. 'import os',
  4441. 'print("y" * 70000)',
  4442. 'os.write(1, b"AFTER")',
  4443. 'return "done"',
  4444. ].join('\n'),
  4445. bindings: [],
  4446. })
  4447. expect(result.error).toBeUndefined()
  4448. expect(result.value).toBe('done')
  4449. const markers = result.logs.filter(line => line.includes('log capture truncated'))
  4450. expect(markers).toHaveLength(1)
  4451. // The marker is the LAST entry: nothing was retained after truncation.
  4452. expect(result.logs.at(-1)).toBe(markers[0])
  4453. expect(result.logs.join('\n')).not.toContain('AFTER')
  4454. }, 20_000)
  4455. it('keeps one marker when a program forges repeated truncation frames', async () => {
  4456. // `truncated` is attacker-reachable: the program owns fd 3 and can write the
  4457. // flag itself, so the field is a hostile input rather than a trusted signal.
  4458. // Repeats must collapse to the single marker the contract promises, and only
  4459. // the literal `true` counts — a forged `"yes"` is rebuilt away by
  4460. // validateChildFrame, so that frame stays ordinary text.
  4461. const { runtime } = await setup({ maxLogBytes: 4096, maxWallMs: 10_000 })
  4462. const result = await runtime.run({
  4463. program: [
  4464. 'import os, json',
  4465. 'os.write(3, json.dumps({"type":"log","text":"first","truncated":"yes"}).encode() + b"\\n")',
  4466. 'os.write(3, json.dumps({"type":"log","text":"MARK-A","truncated":True}).encode() + b"\\n")',
  4467. 'os.write(3, json.dumps({"type":"log","text":"MARK-B","truncated":True}).encode() + b"\\n")',
  4468. 'return "done"',
  4469. ].join('\n'),
  4470. bindings: [],
  4471. })
  4472. expect(result.error).toBeUndefined()
  4473. expect(result.value).toBe('done')
  4474. // The non-boolean flag did not truncate, so its text was captured normally.
  4475. expect(result.logs).toContain('first')
  4476. // The first genuine flag stopped capture and emitted the HOST's own marker;
  4477. // the frame's own text is discarded, so neither payload appears.
  4478. expect(result.logs).not.toContain('MARK-A')
  4479. expect(result.logs).not.toContain('MARK-B')
  4480. expect(result.logs.at(-1)).toBe(logTruncationMarker(4096))
  4481. expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1)
  4482. }, 20_000)
  4483. it('discards the text of a forged truncation frame instead of retaining it', async () => {
  4484. // The marker branch bypasses `admit`, so retaining the frame's own text put
  4485. // attacker-controlled bytes into `logs` with no cap at all: measured, a 1 MiB
  4486. // forged text was retained whole under `maxLogBytes: 64`, and the only bound
  4487. // left was the 64 MiB frame parse cap. The host emits its own marker instead,
  4488. // so the retained size is fixed regardless of what the program sent.
  4489. const forgedBytes = 1024 * 1024
  4490. const { runtime } = await setup({ maxLogBytes: 64, maxWallMs: 20_000 })
  4491. const result = await runtime.run({
  4492. program: [
  4493. 'import os, json',
  4494. `big = "A" * ${forgedBytes}`,
  4495. 'os.write(3, json.dumps({"type":"log","truncated":True,"text":big}).encode() + b"\\n")',
  4496. 'return "done"',
  4497. ].join('\n'),
  4498. bindings: [],
  4499. })
  4500. expect(result.error).toBeUndefined()
  4501. expect(result.value).toBe('done')
  4502. // Only the host marker is kept, so the total stays orders of magnitude below
  4503. // what the forgery carried — and below the cap it was trying to escape.
  4504. expect(result.logs).toEqual([logTruncationMarker(64)])
  4505. expect(result.logs.join('').length).toBeLessThan(forgedBytes / 1000)
  4506. }, 30_000)
  4507. it('coalesces unframed fd-3 fragments without recopying the sealed prefix', async () => {
  4508. // The frame ceiling meters payload BYTES, but each retained chunk is its own
  4509. // Buffer with object and backing-store overhead the byte count cannot see:
  4510. // 5000 single-byte newline-free writes produced 5000 chunks holding 5031
  4511. // bytes, so a program pacing such writes could accumulate millions of objects
  4512. // inside the wall budget and exhaust the host heap far below 256 MiB.
  4513. //
  4514. // The observable behavior is that the run still completes normally: the
  4515. // fragments are coalesced rather than rejected, since a slow trickle of bytes
  4516. // is not itself a protocol violation.
  4517. //
  4518. // `Buffer.concat` is wrapped for the duration so the cumulative copy volume
  4519. // is measured rather than inferred: that total is what separates sealing into
  4520. // blocks from re-merging the whole buffer, and both shapes pass every
  4521. // behavioral assertion below.
  4522. //
  4523. // The trickle is terminated with its own newline before the real frame is
  4524. // written. Without that, those 5000 bytes prefix the frame on the SAME line,
  4525. // which then parses as junk and is dropped — correct framing behavior, but it
  4526. // would leave this test asserting the wrong thing.
  4527. // Bound at capture: `Buffer.concat` is a static method, and taking a bare
  4528. // reference to one trips no-unbound-method.
  4529. const realConcat = Buffer.concat.bind(Buffer)
  4530. let copied = 0
  4531. Buffer.concat = (list: readonly Uint8Array[], total?: number): Buffer<ArrayBuffer> => {
  4532. for (const part of list) copied += part.length
  4533. return realConcat(list, total)
  4534. }
  4535. const program = [
  4536. 'import os',
  4537. // Newline-free single-byte writes, spaced so each lands as its own read.
  4538. // 60000 rather than 5000: the trickle has to cross the seal threshold
  4539. // enough times for the two shapes to separate. At 5000 writes there are
  4540. // only four seals, so even the quadratic form copies well under a
  4541. // megabyte and the budget below could not tell them apart.
  4542. 'for _ in range(60000):',
  4543. ' os.write(3, b"x")',
  4544. ' os.sched_yield()',
  4545. 'os.write(3, b"\\n")',
  4546. // A real frame after the trickle proves framing still works on the
  4547. // coalesced residual.
  4548. 'print("after-trickle")',
  4549. 'return "done"',
  4550. ].join('\n')
  4551. let result: CodeRunResult
  4552. try {
  4553. const { runtime } = await setup({ maxWallMs: 30_000 })
  4554. result = await runtime.run({ program, bindings: [] })
  4555. } finally {
  4556. Buffer.concat = realConcat
  4557. }
  4558. expect(result.error).toBeUndefined()
  4559. expect(result.value).toBe('done')
  4560. expect(result.logs).toContain('after-trickle')
  4561. // Sealing appends a finished block rather than re-merging everything held, so
  4562. // each byte is copied once. Re-concatenating the whole buffer at every
  4563. // threshold made the cumulative copy volume quadratic — 10 MiB trickled a
  4564. // byte at a time copies 53.7 GB that way. A per-byte-copied budget is the
  4565. // discriminator, and it is measured rather than reasoned about: this shape
  4566. // copies about 119 KB for 60000 trickled bytes, the re-merging shape about
  4567. // 540 KB. 256 KiB sits between them with margin on both sides — most writes
  4568. // are coalesced by the pipe before they reach us, so the observed ratio is
  4569. // smaller than the asymptotic one, and the threshold has to sit where a real
  4570. // measurement lands rather than where the asymptote suggests.
  4571. expect(copied).toBeLessThan(256 * 1024)
  4572. }, 40_000)
  4573. it('seals trickled stray fragments into blocks without recopying the sealed prefix', async () => {
  4574. // One-byte data events force the fragment-count limit independently of pipe
  4575. // coalescing. The input-list bound rejects missing seals; copied bytes reject
  4576. // repeatedly merging the sealed prefix. Both regressions preserve log text.
  4577. const realConcat = Buffer.concat.bind(Buffer)
  4578. const previousSplitStdout = splitStdout.value
  4579. let copied = 0
  4580. let maxParts = 0
  4581. const concatSpy = vi.spyOn(Buffer, 'concat').mockImplementation((list: readonly Uint8Array[], total?: number): Buffer<ArrayBuffer> => {
  4582. for (const part of list) copied += part.length
  4583. maxParts = Math.max(maxParts, list.length)
  4584. return realConcat(list, total)
  4585. })
  4586. let result: CodeRunResult
  4587. try {
  4588. splitStdout.value = true
  4589. const { runtime } = await setup({ maxLogBytes: 200_000, maxWallMs: 30_000 })
  4590. result = await runtime.run({
  4591. program: [
  4592. 'import os',
  4593. 'os.write(1, b"x" * 60000 + b"\\n")',
  4594. 'return "done"',
  4595. ].join('\n'),
  4596. bindings: [],
  4597. })
  4598. } finally {
  4599. concatSpy.mockRestore()
  4600. splitStdout.value = previousSplitStdout
  4601. }
  4602. expect(result.error).toBeUndefined()
  4603. expect(result.value).toBe('done')
  4604. expect(result.logs).toEqual(['x'.repeat(60000)])
  4605. expect(maxParts).toBe(1024)
  4606. expect(copied).toBeLessThan(256 * 1024)
  4607. }, 40_000)
  4608. it('caps a huge exception diagnostic child-side before it crosses the wire', async () => {
  4609. // A program can raise with a multi-megabyte message; the child must cap
  4610. // it at maxValueBytes before formatting/sending, not ship the whole
  4611. // payload for the host to truncate after parsing.
  4612. const { runtime } = await setup({ maxValueBytes: 1024 })
  4613. const result = await runtime.run({
  4614. program: 'raise ValueError("boom-" + "x" * (8 * 1024 * 1024))',
  4615. bindings: [],
  4616. })
  4617. expect(result.error?.kind).toBe('exception')
  4618. expect(result.error?.message).toContain('boom-')
  4619. expect(result.error?.message.endsWith('… [truncated]')).toBe(true)
  4620. expect(Buffer.byteLength(result.error?.message ?? '', 'utf8')).toBeLessThan(2048)
  4621. })
  4622. it('caps a control-heavy exception diagnostic by its serialized cost, not raw bytes', async () => {
  4623. // The diagnostic crosses fd 3 inside a JSON frame where a control character
  4624. // escapes sixfold (a NUL is one raw byte, six as `\u0000`). Capping by raw
  4625. // UTF-8 length would let a NUL-heavy message near maxValueBytes serialize to
  4626. // ~6x that and breach the frame ceiling — the silent worker-exit inversion
  4627. // the load-time cap check exists to prevent. The child meters the diagnostic
  4628. // by its serialized cost, so a NUL flood is truncated to fit the frame and
  4629. // the run still reports the exception rather than a worker-exit.
  4630. const { runtime } = await setup({ maxValueBytes: 4096 })
  4631. const result = await runtime.run({
  4632. // 512 KiB of NUL: ~3 MiB once escaped, far past the 4 KiB cap.
  4633. program: 'raise ValueError("\\x00" * (512 * 1024))',
  4634. bindings: [],
  4635. })
  4636. expect(result.error?.kind).toBe('exception')
  4637. expect(result.error?.message.endsWith('… [truncated]')).toBe(true)
  4638. // The SERIALIZED form (what the frame carried) fits the budget, so its raw
  4639. // length is well under it too — a raw-byte cap would have admitted ~4 KiB of
  4640. // NULs that serialize to ~24 KiB.
  4641. const serialized = JSON.stringify(result.error?.message ?? '')
  4642. expect(Buffer.byteLength(serialized, 'utf8')).toBeLessThanOrEqual(4096 + 8)
  4643. })
  4644. it('bounds a newline-free partial-line flood while the program is still running', async () => {
  4645. // print("x", end="") never completes a line, so nothing reaches the
  4646. // Python LogBuffer until settlement — the buffered tail must still hit
  4647. // the budget mid-run instead of growing without bound to RLIMIT/timeout.
  4648. const { runtime } = await setup({ maxLogBytes: 1024, maxWallMs: 15_000 })
  4649. const result = await runtime.run({
  4650. program: [
  4651. 'for _ in range(100000):',
  4652. ' print("xxxxxxxxxx", end="")',
  4653. 'return "done"',
  4654. ].join('\n'),
  4655. bindings: [],
  4656. })
  4657. expect(result.error).toBeUndefined()
  4658. expect(result.value).toBe('done')
  4659. expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
  4660. // The retained text is bounded by the budget, not the 1 MB the program wrote.
  4661. expect(result.logs.join('\n').length).toBeLessThan(4096)
  4662. }, 20_000)
  4663. it('discards empty writes instead of buffering one list slot each', async () => {
  4664. // An empty chunk adds no character, so the mid-run budget check (which
  4665. // compares buffered CHARS against the remaining ledger) can never fire on
  4666. // it. Buffering empty strings therefore grew `_pending` without bound —
  4667. // millions of slots per CPU second — until RLIMIT_AS turned an append into
  4668. // a MemoryError, long after the log ledger was exhausted. Two million
  4669. // empty writes must instead settle normally and contribute NO log entry,
  4670. // proving the chunk was dropped rather than joined at flush_line.
  4671. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 256, maxWallMs: 20_000 })
  4672. const result = await runtime.run({
  4673. program: [
  4674. 'import sys',
  4675. 'for _ in range(2000000):',
  4676. ' sys.stdout.write("")',
  4677. 'return "done"',
  4678. ].join('\n'),
  4679. bindings: [],
  4680. })
  4681. expect(result.error).toBeUndefined()
  4682. expect(result.value).toBe('done')
  4683. expect(result.logs).toEqual([])
  4684. }, 30_000)
  4685. it('stops scanning a single-write newline flood once the log ledger truncates', async () => {
  4686. // One write carrying half a million newlines: the offset scan must exit the
  4687. // instant LogBuffer truncates rather than re-slicing and pushing every
  4688. // remaining line. If it kept scanning it would exhaust the CPU/wall budget;
  4689. // the run instead settles quickly with exactly one truncation marker.
  4690. const { runtime } = await setup({ maxLogBytes: 256, maxWallMs: 10_000 })
  4691. const start = Date.now()
  4692. const result = await runtime.run({
  4693. program: ['print("x\\n" * 500000, end="")', 'return "done"'].join('\n'),
  4694. bindings: [],
  4695. })
  4696. expect(result.error).toBeUndefined()
  4697. expect(result.value).toBe('done')
  4698. expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1)
  4699. expect(Date.now() - start).toBeLessThan(8_000)
  4700. }, 15_000)
  4701. it('bounds an oversized newline-terminated write before joining and slicing it', async () => {
  4702. // The newline branch slices the first line out of the write before
  4703. // `LogBuffer.push` can apply its cheap budget rejection, so a single
  4704. // over-budget write cost a full extra copy of itself in peak address space —
  4705. // the amplification that bound exists to avoid, applied one layer too late.
  4706. // Measured under a 400 MiB addressSpaceMb with the slice unbounded: writes
  4707. // of 200 MiB and up died on MemoryError inside `sys.stdout.write`, reported
  4708. // as the PROGRAM's own exception rather than the promised truncation marker.
  4709. // `"\\n".rjust(n, "A")` is a single allocation ending in the newline, so the
  4710. // payload itself fits and the only remaining allocation is the stream's own
  4711. // slice; 340 MiB of a 400 MiB cap cannot survive one more copy of it.
  4712. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 400, maxWallMs: 30_000 })
  4713. const result = await runtime.run({
  4714. program: [
  4715. 'import sys',
  4716. 'payload = "\\n".rjust(340 * 1024 * 1024, "A")',
  4717. 'sys.stdout.write(payload)',
  4718. 'return "done"',
  4719. ].join('\n'),
  4720. bindings: [],
  4721. })
  4722. expect(result.error).toBeUndefined()
  4723. expect(result.value).toBe('done')
  4724. expect(result.logs).toEqual([logTruncationMarker(256)])
  4725. }, 40_000)
  4726. it('bounds a newline-free write against the already-buffered chunks before joining them', async () => {
  4727. // The newline-free arm buffers the write and then compared the buffered
  4728. // CHARACTER COUNT against the ledger — correct — but paid for the comparison
  4729. // with `"".join(self._pending)`, a second full copy of everything held. One
  4730. // buffered character is enough to make that join a copy of the whole
  4731. // following write. Measured under a 400 MiB addressSpaceMb with a 340 MiB
  4732. // second write: the join raised MemoryError inside `sys.stdout.write`, and
  4733. // because the oversized chunks stayed in `_pending` the settlement
  4734. // `flush_line` raised it again — that throw sits after the `except
  4735. // BaseException` block, so it costs the `done` frame and the run came back
  4736. // `timeout: wall-clock ceiling reached (30000ms)` with no logs at all. The
  4737. // bound must be applied BEFORE the join and the chunks dropped on that path,
  4738. // so the run settles with the truncation marker it promises.
  4739. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 400, maxWallMs: 30_000 })
  4740. const result = await runtime.run({
  4741. program: [
  4742. 'import sys',
  4743. // One unterminated character first, so `_pending` is non-empty and the
  4744. // large write cannot take the "buffered text IS the write" shortcut.
  4745. 'sys.stdout.write("x")',
  4746. 'payload = "A" * (340 * 1024 * 1024)',
  4747. 'sys.stdout.write(payload)',
  4748. 'return "done"',
  4749. ].join('\n'),
  4750. bindings: [],
  4751. })
  4752. expect(result.error).toBeUndefined()
  4753. expect(result.value).toBe('done')
  4754. expect(result.logs).toEqual([logTruncationMarker(256)])
  4755. }, 40_000)
  4756. it('bounds a newline-terminated write against the already-buffered chunks before joining them', async () => {
  4757. // Same allocation, reached through the newline arm: with chunks pending, the
  4758. // whole write used to be appended and joined so the offset scan could run
  4759. // over one string. Only the FIRST line needs those chunks, so a pending
  4760. // chunk plus a 340 MiB newline-terminated write under a 400 MiB
  4761. // addressSpaceMb died on MemoryError in the join before the per-line bound
  4762. // could reject anything, and the retained chunks made the settlement flush
  4763. // die the same way: measured, `timeout: wall-clock ceiling reached
  4764. // (30000ms)`. The reconstructed first line is now checked against the ledger
  4765. // and only a budget-sized prefix of it is copied; the rest of the write is
  4766. // scanned in place.
  4767. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 400, maxWallMs: 30_000 })
  4768. const result = await runtime.run({
  4769. program: [
  4770. 'import sys',
  4771. 'sys.stdout.write("x")',
  4772. 'payload = "\\n".rjust(340 * 1024 * 1024, "A")',
  4773. 'sys.stdout.write(payload)',
  4774. 'return "done"',
  4775. ].join('\n'),
  4776. bindings: [],
  4777. })
  4778. expect(result.error).toBeUndefined()
  4779. expect(result.value).toBe('done')
  4780. expect(result.logs).toEqual([logTruncationMarker(256)])
  4781. }, 40_000)
  4782. it('emits pending text on an explicit flush, before the run can be killed', async () => {
  4783. // `_LogStream` inherits TextIOBase's no-op `flush()`, so an explicit
  4784. // `print(..., flush=True)` or `sys.stdout.flush()` left the text in
  4785. // `_pending` with nothing to drain it but `flush_line` after settlement — a
  4786. // call a hanging or killed run never reaches. Measured: printing
  4787. // "before hang" with flush=True ahead of an infinite loop returned
  4788. // `logs: []`, losing the one diagnostic the program deliberately committed.
  4789. const { runtime } = await setup({ maxWallMs: 4_000 })
  4790. const result = await runtime.run({
  4791. program: [
  4792. 'import sys',
  4793. 'print("before hang", end="", flush=True)',
  4794. 'while True: pass',
  4795. ].join('\n'),
  4796. bindings: [],
  4797. })
  4798. expect(result.error?.kind).toBe('timeout')
  4799. expect(result.logs).toContain('before hang')
  4800. }, 15_000)
  4801. it('marks a dropped tail when the ledger lands on exactly zero remaining', async () => {
  4802. // One 100-character line costs 103 serialized bytes (quotes + separator),
  4803. // consuming a 104-byte budget minus the 1-byte array-envelope reservation
  4804. // (104 - 1 = 103) EXACTLY. Landing on zero never trips
  4805. // LogBuffer's "cost > remaining" branch, so `_truncated` stays unset and the
  4806. // stream's own `remaining > 0` guard silently discarded the unscanned tail —
  4807. // the run reported a complete log while dropping text. The tail must be
  4808. // pushed so the marker is emitted. (This surfaced only after empty writes
  4809. // stopped being buffered: `print` issues a trailing `write("")` whose
  4810. // buffered-empty path used to force the marker out incidentally.) A single
  4811. // wide line is used rather than many narrow ones so the CHILD ledger is the
  4812. // one that lands on zero: the host's identical ledger truncates first when
  4813. // many small entries precede the long marker text. `["y"*100]` serializes to
  4814. // exactly 104 bytes (103 payload + 1 envelope), so 104 is the smallest
  4815. // budget that admits the entry.
  4816. const { runtime } = await setup({ maxLogBytes: 104, maxWallMs: 10_000 })
  4817. const result = await runtime.run({
  4818. program: ['print("y" * 100 + "\\n" + "z" * 10, end="")', 'return "done"'].join('\n'),
  4819. bindings: [],
  4820. })
  4821. expect(result.error).toBeUndefined()
  4822. expect(result.value).toBe('done')
  4823. expect(result.logs).toContain('y'.repeat(100))
  4824. expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1)
  4825. // The dropped tail is not retained, but its loss is now reported.
  4826. expect(result.logs.some(line => line.includes('z'))).toBe(false)
  4827. }, 15_000)
  4828. it('keeps an admitted log within the serialized array envelope at the exact limit', async () => {
  4829. // Each entry is charged its JSON-string cost plus one separator byte, and
  4830. // the serialized outer logs array adds one more byte of envelope (two
  4831. // brackets and n-1 commas). The ledgers reserve that byte, so a result that
  4832. // exactly exhausts the ledger still serializes within the configured cap.
  4833. // At the 64-byte floor (the smallest admissible maxLogBytes): ledger 63,
  4834. // a 60-character line serializes as `"aaa...a"` (62 bytes) + 1 separator
  4835. // = 63, exactly exhausting the ledger and serializing as `["aaa...a"]`
  4836. // = 64 = the cap; a 61-character line costs 64 > 63 and truncates. The
  4837. // marker rides envelope, so the serialized logs run to cap + marker.
  4838. const { runtime } = await setup({ maxLogBytes: 64, maxWallMs: 10_000 })
  4839. const result = await runtime.run({
  4840. program: ['print("a" * 60 + "\\n" + "b" * 61, end="")', 'return "done"'].join('\n'),
  4841. bindings: [],
  4842. })
  4843. expect(result.error).toBeUndefined()
  4844. expect(result.value).toBe('done')
  4845. // The 60-character line was admitted; the 61-character line was not (a
  4846. // single 'b' would also match the marker's "bytes", so check for the line).
  4847. expect(result.logs).toContain('a'.repeat(60))
  4848. expect(result.logs.some(line => line.includes('b'.repeat(61)))).toBe(false)
  4849. expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
  4850. }, 15_000)
  4851. it('rejects a log budget too small to serialize the truncation marker', async () => {
  4852. // A maxLogBytes below 64 cannot serialize the truncation marker itself;
  4853. // it is rejected at construction so a marker-only truncated run cannot
  4854. // report more than the public cap. maxValueBytes keeps no floor beyond the
  4855. // positive-integer requirement (a completion can be 1 byte).
  4856. await expect(setup({ maxLogBytes: 63, maxWallMs: 10_000 })).rejects.toThrow(/must be at least 64/)
  4857. }, 15_000)
  4858. it('charges the JSON-escaped cost of control characters against the log ledger', async () => {
  4859. // A NUL renders as \u0000 (6 bytes) in the serialized outer logs; the
  4860. // ledger must charge that expansion, or a control-character flood admits
  4861. // 6x the configured cap.
  4862. const { runtime } = await setup({ maxLogBytes: 256 })
  4863. const result = await runtime.run({
  4864. program: [
  4865. 'for _ in range(500):',
  4866. ' print("\\x00" * 10)',
  4867. 'return "done"',
  4868. ].join('\n'),
  4869. bindings: [],
  4870. })
  4871. expect(result.error).toBeUndefined()
  4872. expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
  4873. // Serialized (escaped) size of retained entries stays in the budget's
  4874. // neighborhood: well under the ~30 kB an uncharged flood would retain.
  4875. const serialized = Buffer.byteLength(JSON.stringify(result.logs), 'utf8')
  4876. expect(serialized).toBeLessThan(1024)
  4877. })
  4878. it('charges the serialized cost child-side, so a control-heavy line truncates instead of being admitted whole', async () => {
  4879. // The child's ledger must charge what the entry costs on the wire, not its
  4880. // raw UTF-8 length: a NUL is one raw byte but six as its escape. A 24 MiB NUL
  4881. // line clears the cheap char-count lower bound (24 MiB < 32 MiB budget), so
  4882. // charging raw bytes would ADMIT it and emit a ~144 MiB escaped entry;
  4883. // charging the serialized cost (~144 MiB > the 32 MiB budget) rejects it
  4884. // before any encode and emits the marker instead. The address space (512 MiB,
  4885. // clearing the 12x load gate for a 32 MiB budget) is sized so the run loads;
  4886. // the gate separately guarantees a correctly-charged near-budget entry fits.
  4887. const { runtime } = await setup({ maxLogBytes: 32 * 1024 * 1024, addressSpaceMb: 512, maxWallMs: 20_000 })
  4888. const result = await runtime.run({
  4889. program: [
  4890. 'print("\\x00" * (24 * 1024 * 1024))',
  4891. 'return "done"',
  4892. ].join('\n'),
  4893. bindings: [],
  4894. })
  4895. expect(result.error).toBeUndefined()
  4896. expect(result.value).toBe('done')
  4897. expect(result.logs.filter(line => line.includes('log capture truncated'))).toHaveLength(1)
  4898. // Nothing of the line itself was retained: the ledger refused the whole entry.
  4899. expect(result.logs.every(line => !line.includes(String.fromCharCode(0)))).toBe(true)
  4900. }, 30_000)
  4901. it('bounds a huge unterminated tail after an early newline without copying it whole', async () => {
  4902. // The newline branch of _LogStream.write buffered the whole unterminated
  4903. // tail after the last newline into `_pending` before the flush trigger could
  4904. // bound it, so an early newline followed by a huge tail made a second full
  4905. // copy of the model's own string — a MemoryError the config gate cannot
  4906. // catch (the tail far exceeds maxLogBytes). The tail is now sliced to a
  4907. // budget-sized prefix, so the run truncates and completes. Linux-only RLIMIT_AS
  4908. // repro (Darwin skips the limit); on macOS this asserts the happy path.
  4909. //
  4910. // Sizing: the model builds `tail` (N) then the `"\n" + tail` write argument
  4911. // (another ~N), so construction peaks at ~2N — kept under the 384 MiB address
  4912. // space at N = 150 MiB (~300 MiB). The pre-fix code then buffered the whole
  4913. // ~150 MiB tail again, pushing past 384 MiB; the sliced prefix does not.
  4914. const { runtime } = await setup({ maxLogBytes: 256, addressSpaceMb: 384, maxWallMs: 20_000 })
  4915. const result = await runtime.run({
  4916. program: [
  4917. 'import sys',
  4918. 'tail = "A" * (150 * 1024 * 1024)',
  4919. 'sys.stdout.write("\\n" + tail)',
  4920. 'return "done"',
  4921. ].join('\n'),
  4922. bindings: [],
  4923. })
  4924. expect(result.error).toBeUndefined()
  4925. expect(result.value).toBe('done')
  4926. expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
  4927. }, 30_000)
  4928. it('flushes logs before framing the value so their peaks do not add against RLIMIT_AS', async () => {
  4929. // The load gate bounds maxLogBytes and maxValueBytes INDEPENDENTLY against the
  4930. // address space, each at the 12x worst case. But the child framed the
  4931. // completion value (materializing its escaped form to meter it, then encoding
  4932. // the frame) while a newline-free log tail still sat unflushed in _pending.
  4933. // Those two peaks added: two budgets each admitted alone could together breach
  4934. // RLIMIT_AS, dying as worker-exit instead of settling. The flush now runs
  4935. // before the value is framed, so the log pending is freed first.
  4936. //
  4937. // Config: 32 MiB each against 512 MiB (each 32*12 = 384 MiB < 448 MiB
  4938. // budgetable, so both load). The program writes ~33M astral chars with no
  4939. // newline (buffered ~132 MB, under the char-count flush trigger) then returns
  4940. // ~33M astral chars — a ~132 MB serialized value that is itself OVER the 32 MiB
  4941. // maxValueBytes, so the correct outcome is `output-limit`. Pre-fix the
  4942. // unflushed 132 MB plus the value's build-and-encode (~396 MB) exceeded 512 MiB
  4943. // and OOM'd (reported as exception/worker-exit); flushing first lets the value
  4944. // check complete (~460 MB alone) and report output-limit. On Darwin (no
  4945. // RLIMIT_AS) the value is over budget too, so output-limit holds either way;
  4946. // the OOM the reorder prevents is the Linux-only failure.
  4947. const { runtime } = await setup({
  4948. maxLogBytes: 32 * 1024 * 1024,
  4949. maxValueBytes: 32 * 1024 * 1024,
  4950. addressSpaceMb: 512,
  4951. maxWallMs: 20_000,
  4952. })
  4953. const result = await runtime.run({
  4954. program: [
  4955. 'import sys',
  4956. 'sys.stdout.write("\\U0001F600" * 33_000_000)',
  4957. 'return "\\U0001F600" * 33_000_000',
  4958. ].join('\n'),
  4959. bindings: [],
  4960. })
  4961. expect(result.error?.kind).toBe('output-limit')
  4962. }, 30_000)
  4963. it('checks and encodes a wide completion value in O(depth), not O(width)', async () => {
  4964. // A wide flat list serializes to ~2 bytes per element but the pre-fix walk
  4965. // enqueued one traversal tuple per element (_check_done_value) and one stack
  4966. // entry plus a separator marker per element (_encode_json_plain) — ~56 bytes
  4967. // per element, ~28x the serialized size. A value the byte meter admits could
  4968. // therefore OOM on the checker's or encoder's own bookkeeping, the inversion
  4969. // the load gate exists to prevent (the gate reserves 12x, not 28x). Both now
  4970. // walk with an O(depth) cursor that pulls one child at a time, so the only
  4971. // width-proportional allocation is the output string the meter bounded.
  4972. //
  4973. // Config: maxValueBytes 20 MiB against 384 MiB (20*12 = 240 MiB < 320 MiB
  4974. // budgetable, so it loads). `[0] * 6_000_000` is ~12 MB of JSON, under the
  4975. // 20 MiB budget, so it must round-trip. Pre-fix the ~400 MB of per-element
  4976. // frames plus the interpreter exceeded 384 MiB and returned MemoryError as an
  4977. // exception. Linux-only RLIMIT_AS repro; on macOS the value round-trips
  4978. // either way, but the fixture stays within the address space so it is honest.
  4979. //
  4980. // `maxWallMs` is 60s, not the 20s the memory assertion alone needs: the O(depth)
  4981. // cursor pulls 6M elements one at a time through Python-level frames, which costs
  4982. // ~11s on an idle machine and more under the coverage lane's V8 instrumentation
  4983. // with several workers sharing a box. This budget bounds the run without letting a
  4984. // loaded runner's scheduling latency read as a `timeout` — what this test asserts
  4985. // is the O(depth) memory shape, not a speed claim.
  4986. const { runtime } = await setup({ maxValueBytes: 20 * 1024 * 1024, addressSpaceMb: 384, maxWallMs: 60_000 })
  4987. const result = await runtime.run({ program: 'return [0] * 6_000_000', bindings: [] })
  4988. expect(result.error).toBeUndefined()
  4989. expect(Array.isArray(result.value)).toBe(true)
  4990. expect((result.value as number[]).length).toBe(6_000_000)
  4991. }, 90_000)
  4992. it('validates wide binding arguments in O(depth), not O(width)', async () => {
  4993. // The completion-value walks are budgeted; this one is not. `dispatch` runs
  4994. // `_lossless_json_violation` on the arguments the MODEL built, and no
  4995. // child-side byte budget bounds them first: the frame ceiling is the host's
  4996. // and applies only after this validation returns. A per-member traversal
  4997. // frame therefore turned a legitimate call into the program's own
  4998. // MemoryError. Measured with tracemalloc on the two walk shapes over this
  4999. // exact argument (JSON ~17 MB): the cursor peaks at 0.0 MiB of auxiliary
  5000. // state, the pre-fix `stack.extend` at 459.1 MiB -- past the 384 MiB
  5001. // configured below, so the discriminating failure is real. It is Linux-only:
  5002. // Darwin skips RLIMIT_AS, so this case round-trips there either way.
  5003. //
  5004. // The binding echoes its argument's length back, so the assertion proves the
  5005. // call actually round-tripped rather than merely avoiding a crash.
  5006. const { runtime } = await setup({ addressSpaceMb: 384, maxWallMs: 60_000 })
  5007. const result = await runtime.run({
  5008. program: 'return await tools.width([0] * 6_000_000)',
  5009. bindings: [{
  5010. global: 'tools',
  5011. functions: { width: async (items: unknown) => (items as number[]).length },
  5012. }],
  5013. })
  5014. expect(result.error).toBeUndefined()
  5015. expect(result.value).toBe(6_000_000)
  5016. }, 90_000)
  5017. it('decodes a multi-megabyte binding reply without regex backtracking state', async () => {
  5018. // The child parses every host reply with `_decode_json_plain`. Its scalar
  5019. // regex matched strings with a `(?:[^"\\]|\\.)*` repetition, which makes
  5020. // CPython's backtracking engine retain state proportional to the string's
  5021. // WIDTH -- measured at ~146 MiB of engine state for a 1 MiB string and
  5022. // ~558 MiB for 4 MiB. A legitimate multi-megabyte reply therefore raised
  5023. // MemoryError inside `_pump_replies`; because that pump is the only settler
  5024. // of the call's future, the run stranded until the wall clock reported a
  5025. // `timeout` instead of returning the value the binding produced.
  5026. //
  5027. // Strings now scan chunk-to-chunk over a character class (no backtracking
  5028. // state). Measured on this exact 4 MiB reply: the pre-fix regex peaks at
  5029. // 557.8 MiB, past the default 512 MiB address space, while the scanner peaks
  5030. // at the 4.0 MiB result itself. Linux-only, like the other RLIMIT_AS repros:
  5031. // Darwin does not apply the limit, so the spike is merely allocated there.
  5032. const reply = 'A'.repeat(4 * 1024 * 1024)
  5033. const { runtime } = await setup({ maxWallMs: 60_000 })
  5034. const result = await runtime.run({
  5035. program: 'value = await tools.big({})\nreturn len(value)',
  5036. bindings: [{ global: 'tools', functions: { big: async () => reply } }],
  5037. })
  5038. expect(result.error).toBeUndefined()
  5039. expect(result.value).toBe(reply.length)
  5040. }, 90_000)
  5041. it('drops a late binding resolution before snapshotting it', async () => {
  5042. // `sendReply` checks `settled`, but only after the resolution has been walked
  5043. // and copied by `snapshotJsonValue`. Binding resolution carries no seam-level
  5044. // byte cap, so a binding that resolves a wide value AFTER the run already
  5045. // settled (here on `maxWallMs`) spent host heap building a frame that is then
  5046. // discarded. The check now runs before the snapshot.
  5047. //
  5048. // The binding resolves well after the 1s wall clock with a 2M-element array;
  5049. // the run must still report `timeout`, and the late value must not appear.
  5050. let resolvedLate = false
  5051. const { runtime } = await setup({ maxWallMs: 1_000 })
  5052. const result = await runtime.run({
  5053. program: 'return await tools.slow({})',
  5054. bindings: [{
  5055. global: 'tools',
  5056. functions: {
  5057. slow: async () => {
  5058. await new Promise(resolve => setTimeout(resolve, 2_500))
  5059. resolvedLate = true
  5060. return Array.from({ length: 2_000_000 }, () => 0)
  5061. },
  5062. },
  5063. }],
  5064. })
  5065. expect(result.error?.kind).toBe('timeout')
  5066. expect(result.value).toBeUndefined()
  5067. // Pin that the late path actually ran, so the assertion above is not vacuous.
  5068. await new Promise(resolve => setTimeout(resolve, 2_000))
  5069. expect(resolvedLate).toBe(true)
  5070. }, 90_000)
  5071. it('paces concurrent binding replies instead of queueing every frame at once', async () => {
  5072. // Binding resolution carries no seam-level byte cap. Before pacing, a program
  5073. // resolving several large values in one `asyncio.gather` round encoded them
  5074. // all in the same turn and queued every frame in fd 3's writable buffer,
  5075. // which exhausted the host heap and killed the whole process rather than
  5076. // failing the run. Replies are now encoded one at a time, waiting for
  5077. // `drain` when the pipe is full.
  5078. //
  5079. // Eight concurrent 4 MiB replies (32 MiB of frames) must all round-trip. The
  5080. // program sums the lengths, so the assertion proves every reply arrived and
  5081. // was matched to its own call -- pacing must not drop or misroute any. What
  5082. // this case cannot show is the peak itself, which lives in the stream's
  5083. // buffer: measured directly on a 64 KiB-highWaterMark pipe with this same
  5084. // 8x4 MiB shape, the unpaced writes buffered 32.0 MiB while the paced ones
  5085. // peaked at 0.0 MiB.
  5086. const chunk = 'A'.repeat(4 * 1024 * 1024)
  5087. const { runtime } = await setup({ maxWallMs: 60_000 })
  5088. const result = await runtime.run({
  5089. program: [
  5090. 'import asyncio',
  5091. 'parts = await asyncio.gather(*[tools.chunk({}) for _ in range(8)])',
  5092. 'return sum(len(p) for p in parts)',
  5093. ].join('\n'),
  5094. bindings: [{ global: 'tools', functions: { chunk: async () => chunk } }],
  5095. })
  5096. expect(result.error).toBeUndefined()
  5097. expect(result.value).toBe(8 * chunk.length)
  5098. }, 90_000)
  5099. it('drops queued binding replies when the child dies mid-drain, without hanging', async () => {
  5100. // drainReplies waits for `drain` when fd 3's buffer is full. If the child
  5101. // exits while a reply is queued, the pipe never emits `drain` again — the
  5102. // wait must also settle on `close`/`error`/destroyed, or `draining` stays
  5103. // true and the queue is pinned with the closure forever. The program fills
  5104. // the pipe with a wide binding reply and then exits without reading it, so
  5105. // the host is blocked mid-drain when the child dies; the run must still
  5106. // settle promptly (worker-exit from the close) rather than hanging on the
  5107. // drain wait.
  5108. const chunk = 'A'.repeat(4 * 1024 * 1024)
  5109. const { runtime } = await setup({ maxWallMs: 10_000 })
  5110. const result = await runtime.run({
  5111. program: [
  5112. 'import asyncio',
  5113. // Resolve a reply big enough to backpressure fd 3, then exit without
  5114. // reading it: the child's `close` lands while the host still waits for
  5115. // `drain`, exercising the destroyed-pipe branch of the reply drain.
  5116. 'pending = asyncio.create_task(tools.chunk({}))',
  5117. 'await asyncio.sleep(0.05)',
  5118. 'return "done"',
  5119. ].join('\n'),
  5120. bindings: [{ global: 'tools', functions: { chunk: async () => chunk } }],
  5121. })
  5122. // The program returned, so the completion wins over the mid-flight reply;
  5123. // whatever the result, the run must settle (no hang on the drain wait).
  5124. expect(result.error).toBeUndefined()
  5125. expect(result.value).toBe('done')
  5126. }, 30_000)
  5127. it('caps the pending reply backlog when a child floods calls without reading its replies', async () => {
  5128. // drainReplies writes one reply at a time and waits for `drain` when fd 3's
  5129. // buffer is full. A child that never reads its replies (it only writes
  5130. // call frames, never draining the reply side) leaves the pipe full, so
  5131. // every call frame it keeps sending resolves a binding and adds a reply the
  5132. // drain cannot write: without a bound, the backlog grows until the wall
  5133. // clock, pinning each binding result in host memory. The cap settles the
  5134. // run as worker-exit instead, mirroring the frame cap's treatment of an
  5135. // oversized frame. The child floods 5000 sequential valid calls and never
  5136. // reads fd 3 (its reply pump is starved by the synchronous write loop and
  5137. // the blocking sleep); the pipe buffer absorbs ~1600 tiny replies, so the
  5138. // pending backlog crosses MAX_PENDING_REPLIES long before maxWallMs, and
  5139. // the run must settle worker-exit with the reply-queue message, not a
  5140. // wall-clock timeout.
  5141. const { runtime } = await setup({ maxWallMs: 30_000 })
  5142. const result = await runtime.run({
  5143. program: [
  5144. 'import os, time',
  5145. 'frame = b\'{"type":"call","id":%d,"global":"tools","name":"echo","args":{}}\\n\'',
  5146. 'for i in range(5000):',
  5147. ' view = memoryview(frame % i)',
  5148. ' while view:',
  5149. ' view = view[os.write(3, view):]',
  5150. // Keep the child alive without reading fd 3: the run must settle via
  5151. // the reply-backlog cap, not by the child finishing or exiting.
  5152. 'time.sleep(30)',
  5153. 'return "unreachable"',
  5154. ].join('\n'),
  5155. bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as CodeJsonValue } }],
  5156. })
  5157. expect(result.error?.kind).toBe('worker-exit')
  5158. expect(result.error?.message).toContain('reply queue exceeded')
  5159. }, 30_000)
  5160. it('caps the outstanding binding-call backlog when a child floods calls against a binding that never settles', async () => {
  5161. // The reply backlog cap only counts RESOLVED calls (`pendingReplies` grows
  5162. // after the await), so a child flooding calls against a binding whose
  5163. // promise never settles would accumulate one async closure per frame until
  5164. // the wall clock without tripping it. The outstanding-call counter bounds
  5165. // the in-flight closures to MAX_PENDING_REPLIES and settles the run as
  5166. // worker-exit, mirroring the reply cap. The binding below never resolves,
  5167. // so no reply is ever produced; the flood of 5000 sequential calls must
  5168. // cross the in-flight bound long before maxWallMs.
  5169. const { runtime } = await setup({ maxWallMs: 30_000 })
  5170. const result = await runtime.run({
  5171. program: [
  5172. 'import os, time',
  5173. 'frame = b\'{"type":"call","id":%d,"global":"tools","name":"hang","args":{}}\\n\'',
  5174. 'for i in range(5000):',
  5175. ' view = memoryview(frame % i)',
  5176. ' while view:',
  5177. ' view = view[os.write(3, view):]',
  5178. 'time.sleep(30)',
  5179. 'return "unreachable"',
  5180. ].join('\n'),
  5181. bindings: [{ global: 'tools', functions: { hang: async () => await new Promise<never>(() => {}) } }],
  5182. })
  5183. expect(result.error?.kind).toBe('worker-exit')
  5184. expect(result.error?.message).toContain('call backlog exceeded')
  5185. }, 30_000)
  5186. it('runs a legitimate gather of more than 1024 concurrent binding calls', async () => {
  5187. // The in-flight call cap must not count a synchronous batch of instant
  5188. // calls: the async bodies' finallys run on the microtask queue, which
  5189. // drains only between 'data' events, so a per-frame check would trip on
  5190. // the 1025th frame of a single event even though every binding settled
  5191. // immediately — killing a valid large concurrent gather as worker-exit.
  5192. // The cap is checked at event boundaries (after the microtask queue
  5193. // drained), so this gather of 1025 instant calls completes.
  5194. const { runtime } = await setup({ maxWallMs: 30_000 })
  5195. const result = await runtime.run({
  5196. program: [
  5197. 'import asyncio',
  5198. 'return len(await asyncio.gather(*[tools.echo(i) for i in range(1025)]))',
  5199. ].join('\n'),
  5200. bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as CodeJsonValue } }],
  5201. })
  5202. expect(result.error).toBeUndefined()
  5203. expect(result.value).toBe(1025)
  5204. }, 30_000)
  5205. it('completes normally when a program returns with binding calls still outstanding', async () => {
  5206. // The in-flight call cap refuses to admit NEW calls past the bound; it must
  5207. // not reclassify a `done` frame as worker-exit just because the program
  5208. // returned with calls it started but never awaited. The child schedules
  5209. // exactly 1024 slow bindings (still pending when the program returns), so
  5210. // the done frame arrives with the outstanding count AT the cap — the event
  5211. // must complete with its value, not settle as `call backlog exceeded`.
  5212. const { runtime } = await setup({ maxWallMs: 30_000 })
  5213. const result = await runtime.run({
  5214. program: [
  5215. 'import asyncio',
  5216. 'for i in range(1024):',
  5217. ' asyncio.create_task(tools.slow(i))',
  5218. 'await asyncio.sleep(0.2)',
  5219. 'return "done"',
  5220. ].join('\n'),
  5221. bindings: [{
  5222. global: 'tools',
  5223. functions: { slow: async () => { await new Promise((resolve) => { setTimeout(resolve, 5_000) }); return 1 } },
  5224. }],
  5225. })
  5226. expect(result.error).toBeUndefined()
  5227. expect(result.value).toBe('done')
  5228. }, 30_000)
  5229. it('settles a single-batch never-settling flood as worker-exit without further frames', async () => {
  5230. // The outstanding-call cap must take effect even when the whole flood fits
  5231. // in ONE data event: a per-event admission snapshot never re-checks once no
  5232. // further frames arrive, so a single 62 KiB write of 1025 compact calls
  5233. // against a never-settling binding would otherwise wait out the full wall
  5234. // clock instead of tripping the cap. The post-macrotask check runs after
  5235. // the batch's finallys (which never run for this binding) and settles the
  5236. // run as worker-exit long before maxWallMs.
  5237. const { runtime } = await setup({ maxWallMs: 30_000 })
  5238. const result = await runtime.run({
  5239. program: [
  5240. 'import os, time',
  5241. 'frame = b\'{"type":"call","id":%d,"global":"tools","name":"hang","args":{}}\\n\'',
  5242. 'payload = b"".join(frame % i for i in range(1025))',
  5243. 'view = memoryview(payload)',
  5244. 'while view:',
  5245. ' view = view[os.write(3, view):]',
  5246. 'time.sleep(30)',
  5247. 'return "unreachable"',
  5248. ].join('\n'),
  5249. bindings: [{ global: 'tools', functions: { hang: async () => await new Promise<never>(() => {}) } }],
  5250. })
  5251. expect(result.error?.kind).toBe('worker-exit')
  5252. expect(result.error?.message).toContain('call backlog exceeded')
  5253. }, 30_000)
  5254. it('runs a burst of 1300 instant calls whose frames split across pipe reads', async () => {
  5255. // Flowing mode can fire several 'data' events within one macrotask, before
  5256. // any microtask drains, so a per-event snapshot of the outstanding count
  5257. // could see the first chunk's in-flight calls in the second chunk's check
  5258. // and false-positive on a legitimate burst. The post-macrotask check always
  5259. // sees the true count (all finallys have run), so this burst of compact
  5260. // frames — sized so the pipe read splits it — completes with all results.
  5261. const { runtime } = await setup({ maxWallMs: 30_000 })
  5262. const result = await runtime.run({
  5263. program: [
  5264. 'import asyncio',
  5265. 'return len(await asyncio.gather(*[t.e(i) for i in range(1300)]))',
  5266. ].join('\n'),
  5267. bindings: [{ global: 't', functions: { e: async (args: unknown) => args as CodeJsonValue } }],
  5268. })
  5269. expect(result.error).toBeUndefined()
  5270. expect(result.value).toBe(1300)
  5271. }, 30_000)
  5272. it('settles as worker-exit when a done frame lands in the same batch as a call flood', async () => {
  5273. // A done frame processed in the SAME data event as more than 1024 call
  5274. // frames settles the run before the post-macrotask check runs (which no-ops
  5275. // once settled), so a child could finish "successfully" while leaving the
  5276. // outstanding closures behind — one sub-64 KiB write carries 1025 compact
  5277. // calls plus a done. The done handler re-checks the count before accepting
  5278. // the frame, so the run settles as worker-exit with the call-backlog
  5279. // message instead.
  5280. const { runtime } = await setup({ maxWallMs: 30_000 })
  5281. const result = await runtime.run({
  5282. program: [
  5283. 'import os, time',
  5284. 'frame = b\'{"type":"call","id":%d,"global":"tools","name":"hang","args":{}}\\n\'',
  5285. 'payload = b"".join(frame % i for i in range(1025)) + b\'{"type":"done","value":1}\\n\'',
  5286. 'view = memoryview(payload)',
  5287. 'while view:',
  5288. ' view = view[os.write(3, view):]',
  5289. 'time.sleep(30)',
  5290. 'return "unreachable"',
  5291. ].join('\n'),
  5292. bindings: [{ global: 'tools', functions: { hang: async () => await new Promise<never>(() => {}) } }],
  5293. })
  5294. expect(result.error?.kind).toBe('worker-exit')
  5295. expect(result.error?.message).toContain('call backlog exceeded')
  5296. }, 30_000)
  5297. it('rejects a completion whose dict keys fold to one JSON member', async () => {
  5298. // `_dump_string` folds a spelled-out surrogate pair into its astral code
  5299. // point, so `"\ud83d\ude00"` and `"\U0001f600"` are DIFFERENT Python keys
  5300. // that encode to the SAME JSON member — the host's JSON.parse would
  5301. // silently drop one of them, violating the lossless-JSON completion
  5302. // contract. The child's meter rejects the collision before encoding.
  5303. const { runtime } = await setup()
  5304. const result = await runtime.run({
  5305. program: 'return {"\\ud83d\\ude00": 1, "\\U0001f600": 2}',
  5306. bindings: [],
  5307. })
  5308. expect(result.error?.kind).toBe('invalid-output')
  5309. expect(result.error?.message).toContain('duplicate dict key')
  5310. }, 30_000)
  5311. it('rejects binding arguments whose dict keys fold to one JSON member', async () => {
  5312. // The same collision on the binding-argument path: the call is rejected as
  5313. // not lossless JSON, so the program's `await` raises and the program
  5314. // surfaces the rejection message.
  5315. const { runtime } = await setup()
  5316. const result = await runtime.run({
  5317. program: [
  5318. 'try:',
  5319. ' await tools.echo({"\\ud83d\\ude00": 1, "\\U0001f600": 2})',
  5320. ' return "no-error"',
  5321. 'except Exception as e:',
  5322. ' return str(e)',
  5323. ].join('\n'),
  5324. bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as CodeJsonValue } }],
  5325. })
  5326. expect(result.error).toBeUndefined()
  5327. expect(result.value).toContain('duplicate dict key')
  5328. }, 30_000)
  5329. it('compacts the reply queue mid-drain without dropping pending frames', async () => {
  5330. // A reply larger than the writable high-water mark makes the FIRST write
  5331. // return false, suspending the drain loop; the frames queued behind it
  5332. // push the drain's consumed head past MAX_PENDING_REPLIES, so the resumed
  5333. // drain compacts the queue mid-run. The child reads fd 3 itself (blocking
  5334. // the asyncio pump, so its reads cannot race the host's pushes) and sends
  5335. // a second wave of calls AFTER reading part of the first wave's replies —
  5336. // those replies are still pending when the drain's head crosses the
  5337. // compaction bound, so a compaction that dropped pending frames would
  5338. // leave the child's reply count short and the read loop spinning to the
  5339. // wall clock. No fixed sleep: the child's reads pace at the drain's
  5340. // delivery rate (each write blocks until the child reads), and the host
  5341. // finishes pushing all of a wave within milliseconds — orders of magnitude
  5342. // before the head crosses the bound — so the queue is always full at the
  5343. // splice. Newlines are counted per chunk (each reply carries exactly one),
  5344. // never by re-scanning the accumulated total, which would be O(n²).
  5345. const { runtime } = await setup({ maxWallMs: 60_000 })
  5346. const result = await runtime.run({
  5347. program: [
  5348. 'import os',
  5349. 'frame = b\'{"type":"call","id":%d,"global":"tools","name":"big","args":{}}\\n\'',
  5350. 'for i in range(1024):',
  5351. ' view = memoryview(frame % i)',
  5352. ' while view:',
  5353. ' view = view[os.write(3, view):]',
  5354. 'seen = 0',
  5355. 'while seen < 500:',
  5356. ' chunk = os.read(3, 65536)',
  5357. ' if not chunk:',
  5358. ' break',
  5359. ' seen += chunk.count(b"\\n")',
  5360. 'for i in range(500):',
  5361. ' view = memoryview(frame % (1024 + i))',
  5362. ' while view:',
  5363. ' view = view[os.write(3, view):]',
  5364. 'while seen < 1524:',
  5365. ' chunk = os.read(3, 65536)',
  5366. ' if not chunk:',
  5367. ' break',
  5368. ' seen += chunk.count(b"\\n")',
  5369. 'return "done"',
  5370. ].join('\n'),
  5371. bindings: [{ global: 'tools', functions: { big: async () => 'x'.repeat(65 * 1024) } }],
  5372. })
  5373. expect(result.error).toBeUndefined()
  5374. expect(result.value).toBe('done')
  5375. }, 60_000)
  5376. it('bounds a flood of zero-byte log lines through the per-entry separator charge', async () => {
  5377. // Blank print() lines carry zero content bytes; without the +1 separator
  5378. // charge they would bypass maxLogBytes entirely and grow the retained
  5379. // array without bound. Each empty entry costs one byte, so a 64-byte
  5380. // budget retains at most 64 entries before the marker.
  5381. const { runtime } = await setup({ maxLogBytes: 64, maxWallMs: 10_000 })
  5382. const result = await runtime.run({
  5383. program: [
  5384. 'for _ in range(10000):',
  5385. ' print()',
  5386. 'return "done"',
  5387. ].join('\n'),
  5388. bindings: [],
  5389. })
  5390. expect(result.error).toBeUndefined()
  5391. expect(result.logs.length).toBeLessThanOrEqual(65)
  5392. expect(result.logs.some(line => line.includes('log capture truncated'))).toBe(true)
  5393. })
  5394. it('reassembles multibyte UTF-8 split across stray-output pipe chunks', async () => {
  5395. // A single os.write far past the 64 KiB pipe buffer forces multiple
  5396. // 'data' chunks; when the boundary lands inside a multibyte sequence,
  5397. // per-chunk decoding would corrupt it into replacement characters. Raw bytes
  5398. // are buffered and only decoded once a complete line (or the whole tail at
  5399. // flush) is assembled, so the split sequence is whole by the time it is
  5400. // decoded. The payload spans every valid multibyte lead class so
  5401. // accrueStrayCost's per-lead continuation ranges are all exercised: U+0900
  5402. // (E0 A4 80, the range-restricted E0 lead), U+4F60 and U+597D (E4/E5, plain
  5403. // 3-byte), U+1F600 (F0, the range-restricted F0 lead), and U+10FFFF (F4 8F
  5404. // BF BF, the range-restricted F4 lead).
  5405. const { runtime } = await setup({ maxLogBytes: 1024 * 1024 })
  5406. const result = await runtime.run({
  5407. program: [
  5408. 'import os',
  5409. // os.write is one syscall and returns a partial count on a full
  5410. // pipe, so loop until the whole payload (odd prefix -> a chunk
  5411. // boundary lands inside a multibyte sequence) is out.
  5412. String.raw`payload = b"a" * 65535 + "\u0900\u4f60\u597d\U0001f600\U0010ffff".encode("utf-8")`,
  5413. 'view = memoryview(payload)',
  5414. 'while view:',
  5415. ' view = view[os.write(1, view):]',
  5416. 'return "done"',
  5417. ].join('\n'),
  5418. bindings: [],
  5419. })
  5420. expect(result.error).toBeUndefined()
  5421. const text = result.logs.join('')
  5422. expect(text).toContain('\u0900\u4f60\u597d\u{1f600}\u{10ffff}')
  5423. expect(text).not.toContain('\ufffd')
  5424. })
  5425. it('flushes a stray-output byte sequence left incomplete when the pipe ends', async () => {
  5426. // The child writes the first two bytes of a 3-byte UTF-8 character to fd 1
  5427. // and exits, so the pipe closes with the sequence unfinished in the raw
  5428. // residual. The 'end' flush decodes the residual with `toString('utf8')`,
  5429. // which renders the stranded bytes as U+FFFD instead of dropping them.
  5430. const { runtime } = await setup({ maxLogBytes: 1024 * 1024 })
  5431. const result = await runtime.run({
  5432. program: [
  5433. 'import os',
  5434. // b"\xe4\xbd" is the leading two bytes of U+4F60; no continuation byte
  5435. // follows before exit.
  5436. String.raw`os.write(1, b"\xe4\xbd")`,
  5437. 'return "done"',
  5438. ].join('\n'),
  5439. bindings: [],
  5440. })
  5441. expect(result.error).toBeUndefined()
  5442. expect(result.logs.join('')).toContain('�')
  5443. })
  5444. it('rejects reserved words of EITHER backend language as binding globals', async () => {
  5445. // The seam's portable contract: `lambda` (Python keyword, legal JS name)
  5446. // and `typeof` (JS keyword, legal Python name) are both refused, so a
  5447. // namespace list valid on one backend is valid on every backend.
  5448. const { runtime } = await setup()
  5449. for (const global of ['lambda', 'typeof']) {
  5450. await expect(runtime.run({
  5451. program: 'return 1',
  5452. bindings: [{ global, functions: {} }],
  5453. })).rejects.toThrow(/is not a usable Python identifier/)
  5454. }
  5455. })
  5456. it('captures stray stdout bytes the child writes bypassing sys.stdout', async () => {
  5457. // Model code that writes to fd 1 via os.write() bypasses the Python-side
  5458. // LogBuffer, so the host's stray-byte capture on child.stdout is what
  5459. // records it.
  5460. const { runtime } = await setup()
  5461. const result = await runtime.run({
  5462. program: [
  5463. 'import os',
  5464. 'os.write(1, b"stray stdout\\n")',
  5465. 'os.write(2, b"stray stderr\\n")',
  5466. 'return "done"',
  5467. ].join('\n'),
  5468. bindings: [],
  5469. })
  5470. expect(result.error).toBeUndefined()
  5471. expect(result.logs.join('')).toContain('stray stdout')
  5472. expect(result.logs.join('')).toContain('stray stderr')
  5473. })
  5474. it('flushes bytes written through sys.__stdout__/sys.__stderr__ before the done frame', async () => {
  5475. // The bootstrap only replaces sys.stdout/sys.stderr with the _LogStream;
  5476. // sys.__stdout__/sys.__stderr__ are the original block-buffered wrappers
  5477. // over fd 1/2. A program that writes through them without an explicit flush
  5478. // would lose those bytes when the host SIGTERMs the child right after the
  5479. // done frame (the default SIGTERM disposition terminates without
  5480. // interpreter finalization). The settlement flush now drains the original
  5481. // std streams before sending the done frame, so the bytes land in the
  5482. // kernel pipe buffer and the host's stray capture records them.
  5483. const { runtime } = await setup()
  5484. const result = await runtime.run({
  5485. program: [
  5486. 'import sys',
  5487. // `-u` makes the streams write-through; re-enable block buffering so
  5488. // the bytes sit in the wrapper until the SETTLEMENT drain flushes them
  5489. // — the drain path, not the -u immediate write, is what this case pins.
  5490. 'if hasattr(sys.__stdout__, "reconfigure"):',
  5491. ' sys.__stdout__.reconfigure(write_through=False)',
  5492. ' sys.__stderr__.reconfigure(write_through=False)',
  5493. 'sys.__stdout__.write("orig stdout\\n")',
  5494. 'sys.__stderr__.write("orig stderr\\n")',
  5495. 'return "done"',
  5496. ].join('\n'),
  5497. bindings: [],
  5498. })
  5499. expect(result.error).toBeUndefined()
  5500. expect(result.value).toBe('done')
  5501. expect(result.logs.join('')).toContain('orig stdout')
  5502. expect(result.logs.join('')).toContain('orig stderr')
  5503. }, 15_000)
  5504. it('escalates to SIGKILL when the program traps SIGTERM and ignores the grace period', async () => {
  5505. // A program that traps SIGTERM should still die: the kill() escalation
  5506. // fires SIGKILL after graceMs. The full run reports either timeout (wall)
  5507. // or worker-exit depending on which finish reason wins the race.
  5508. const { runtime } = await setup({ maxWallMs: 400, graceMs: 200 })
  5509. const result = await runtime.run({
  5510. program: [
  5511. 'import signal, time',
  5512. 'signal.signal(signal.SIGTERM, lambda *a: None)',
  5513. 'while True: time.sleep(1)',
  5514. ].join('\n'),
  5515. bindings: [],
  5516. })
  5517. expect(['timeout', 'worker-exit']).toContain(result.error?.kind)
  5518. }, 6000)
  5519. it('bounds the fd-3 receive buffer against a newline-free flood', async () => {
  5520. // A program looping os.write(3, ...) with no newline would grow the host
  5521. // accumulator unbounded (the child's RLIMIT_AS does not cover the host
  5522. // string). The frame cap is a fixed 64 MiB memory-safety invariant —
  5523. // deliberately NOT derived from maxValueBytes, because legitimate binding
  5524. // call frames may be large. We flood slightly past it in 8 MiB writes so
  5525. // the test terminates promptly once the guard trips.
  5526. const ceiling = 64 * 1024 * 1024
  5527. const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 })
  5528. const start = Date.now()
  5529. const result = await runtime.run({
  5530. program: [
  5531. 'import os',
  5532. `for _ in range(${Math.ceil((ceiling * 1.1) / (8 * 1024 * 1024))}):`,
  5533. ' os.write(3, b"A" * (8 * 1024 * 1024))',
  5534. 'return "never"',
  5535. ].join('\n'),
  5536. bindings: [],
  5537. })
  5538. const elapsed = Date.now() - start
  5539. expect(result.error?.kind).toBe('worker-exit')
  5540. expect(result.error?.message).toContain(`protocol frame exceeded ${ceiling} bytes`)
  5541. // The breach ends the run before the wall ceiling (the run did not idle
  5542. // out); absolute pipe throughput varies too much under parallel suites
  5543. // for a tight bound.
  5544. expect(elapsed).toBeLessThan(30_000)
  5545. }, 45_000)
  5546. it('fails a forged oversized done value host-side as output-limit', async () => {
  5547. // The Python-side _done_with_value check is bypassable by writing a done
  5548. // frame straight to fd 3. The host re-enforces maxValueBytes; the seam
  5549. // forbids substituting a truncated value, so the run FAILS as output-limit
  5550. // instead of returning a lie.
  5551. const maxValueBytes = 64
  5552. const { runtime } = await setup({ maxValueBytes })
  5553. const result = await runtime.run({
  5554. program: [
  5555. 'import os, json',
  5556. 'big = "B" * 5000',
  5557. 'os.write(3, json.dumps({"type":"done","value":big}).encode() + b"\\n")',
  5558. // The real done never sends; the forged one settles the run.
  5559. 'import time',
  5560. 'time.sleep(5)',
  5561. ].join('\n'),
  5562. bindings: [],
  5563. })
  5564. expect(result.value).toBeUndefined()
  5565. expect(result.error?.kind).toBe('output-limit')
  5566. expect(result.error?.message).toContain('exceeded 64 bytes')
  5567. }, 8000)
  5568. it('drops a forged oversized log frame on its code-unit lower bound, before escaping it', async () => {
  5569. // A forged `log` frame carrying a control-heavy string: NULs escape
  5570. // several-fold (one NUL -> six bytes `\u0000`). The raw frame stays under
  5571. // the host's 64 MiB parse cap (4 MiB of `\u0000` text = 24 MiB raw) while
  5572. // the escaped form would be ~24 MiB. Charging it required building that
  5573. // escaped copy first, so a 32-byte maxLogBytes could still force a large
  5574. // host allocation. The cheap `length + 3` lower bound truncates it instead.
  5575. // The host's own heap is what is under test, so keep the child's address
  5576. // space generous enough to BUILD the frame.
  5577. const { runtime } = await setup({ maxLogBytes: 128, addressSpaceMb: 1024, maxWallMs: 60_000 })
  5578. const before = process.memoryUsage().heapUsed
  5579. const result = await runtime.run({
  5580. program: [
  5581. 'import os',
  5582. // Written as a raw frame so the child's own ledger never sees it.
  5583. 'os.write(3, b\'{"type":"log","text":"\' + b"\\\\u0000" * (4 * 1024 * 1024) + b\'"}\\n\')',
  5584. 'return "settled"',
  5585. ].join('\n'),
  5586. bindings: [],
  5587. })
  5588. expect(result.error).toBeUndefined()
  5589. expect(result.value).toBe('settled')
  5590. // The frame was dropped as one truncation marker, not retained.
  5591. expect(result.logs).toEqual([logTruncationMarker(128)])
  5592. // The escaped copy (~144 MiB) was never materialized.
  5593. expect(process.memoryUsage().heapUsed - before).toBeLessThan(256 * 1024 * 1024)
  5594. }, 90_000)
  5595. it('charges a forged log frame its escaped cost once past the code-unit lower bound', async () => {
  5596. // The cheap lower bound only rejects what cannot possibly fit; a SHORT
  5597. // control-heavy frame clears it and must still be charged what it costs on
  5598. // the wire. Eleven NULs are 14 against the 64-byte ledger's cheap bound
  5599. // (six bytes each, two quotes, one separator), so the full charge truncates.
  5600. const { runtime } = await setup({ maxLogBytes: 64 })
  5601. const result = await runtime.run({
  5602. program: [
  5603. 'import os',
  5604. 'os.write(3, b\'{"type":"log","text":"\' + b"\\\\u0000" * 11 + b\'"}\\n\')',
  5605. 'return "settled"',
  5606. ].join('\n'),
  5607. bindings: [],
  5608. })
  5609. expect(result.error).toBeUndefined()
  5610. expect(result.value).toBe('settled')
  5611. expect(result.logs).toEqual([logTruncationMarker(64)])
  5612. }, 8000)
  5613. it('caps a forged done error.message from its code-unit prefix, never encoding the whole message', async () => {
  5614. // `Buffer.from(message)` on a message near the frame ceiling allocates a
  5615. // full UTF-8 copy before maxValueBytes applies. Only the first
  5616. // maxValueBytes code units can fit the cap, so only that prefix is encoded
  5617. // — at most 3x the cap in bytes. The message here is 48 MiB of ASCII: its
  5618. // full encode would be another 48 MiB in the host.
  5619. const maxValueBytes = 64
  5620. const { runtime } = await setup({ maxValueBytes, addressSpaceMb: 1024, maxWallMs: 60_000 })
  5621. const before = process.memoryUsage().heapUsed
  5622. const result = await runtime.run({
  5623. program: [
  5624. 'import os',
  5625. 'os.write(3, b\'{"type":"done","error":{"kind":"exception","message":"\' + b"E" * (48 * 1024 * 1024) + b\'"}}\\n\')',
  5626. 'import time',
  5627. 'time.sleep(30)',
  5628. ].join('\n'),
  5629. bindings: [],
  5630. })
  5631. expect(result.error?.kind).toBe('exception')
  5632. const message = result.error?.message ?? ''
  5633. // The marker's 15 bytes come OUT of the 64-byte cap, so 49 E's precede it
  5634. // and the whole string is exactly 64 bytes — not 64 plus the marker.
  5635. expect(message).toBe(`${'E'.repeat(maxValueBytes - 15)}… [truncated]`)
  5636. expect(Buffer.byteLength(message, 'utf8')).toBe(maxValueBytes)
  5637. // JSON.parse already holds the 48 MiB string; the cap must not add a
  5638. // second full-length copy on top of it.
  5639. expect(process.memoryUsage().heapUsed - before).toBeLessThan(256 * 1024 * 1024)
  5640. }, 90_000)
  5641. it('keeps a capped diagnostic within maxValueBytes, marker included', async () => {
  5642. // The marker is part of the emitted diagnostic, so its bytes are reserved
  5643. // from the cap rather than appended past it — the host meters this same
  5644. // field downstream. Checked on BOTH producers: the child's own _cap_message
  5645. // (a raised exception) and the host's capMessage (a forged done frame).
  5646. const maxValueBytes = 40
  5647. const { runtime } = await setup({ maxValueBytes })
  5648. const raised = await runtime.run({
  5649. program: 'raise ValueError("R" * 100000)',
  5650. bindings: [],
  5651. })
  5652. expect(raised.error?.kind).toBe('exception')
  5653. const raisedMessage = raised.error?.message ?? ''
  5654. expect(raisedMessage.endsWith('… [truncated]')).toBe(true)
  5655. expect(Buffer.byteLength(raisedMessage, 'utf8')).toBeLessThanOrEqual(maxValueBytes)
  5656. const forged = await runtime.run({
  5657. program: [
  5658. 'import os, json',
  5659. 'msg = "F" * 100000',
  5660. 'os.write(3, json.dumps({"type":"done","error":{"kind":"exception","message":msg}}).encode() + b"\\n")',
  5661. 'import time',
  5662. 'time.sleep(5)',
  5663. ].join('\n'),
  5664. bindings: [],
  5665. })
  5666. expect(forged.error?.kind).toBe('exception')
  5667. const forgedMessage = forged.error?.message ?? ''
  5668. expect(forgedMessage.endsWith('… [truncated]')).toBe(true)
  5669. expect(Buffer.byteLength(forgedMessage, 'utf8')).toBe(maxValueBytes)
  5670. }, 15_000)
  5671. it('emits the marker alone when the cap is smaller than the marker itself', async () => {
  5672. // With maxValueBytes below the marker's own 15 bytes there is no room for
  5673. // message text; the marker still goes out, so the truncation stays reported
  5674. // instead of the diagnostic silently becoming empty. Both producers agree.
  5675. const { runtime } = await setup({ maxValueBytes: 4 })
  5676. const raised = await runtime.run({ program: 'raise ValueError("R" * 500)', bindings: [] })
  5677. expect(raised.error?.kind).toBe('exception')
  5678. expect(raised.error?.message).toBe('… [truncated]')
  5679. const forged = await runtime.run({
  5680. program: [
  5681. 'import os, json',
  5682. 'os.write(3, json.dumps({"type":"done","error":{"kind":"exception","message":"F" * 500}}).encode() + b"\\n")',
  5683. 'import time',
  5684. 'time.sleep(5)',
  5685. ].join('\n'),
  5686. bindings: [],
  5687. })
  5688. expect(forged.error?.kind).toBe('exception')
  5689. expect(forged.error?.message).toBe('… [truncated]')
  5690. }, 15_000)
  5691. it('caps a forged done error.message without splitting a surrogate pair', async () => {
  5692. // At exactly maxValueBytes code units the prefix can end on a high
  5693. // surrogate whose low half sits just outside it. `Buffer.from` encodes that
  5694. // orphan as U+FFFD — the same corruption a mid-sequence byte cut causes —
  5695. // and those three replacement bytes sit past the marker-reserved budget, so
  5696. // the byte trim-back drops them.
  5697. const maxValueBytes = 32
  5698. const { runtime } = await setup({ maxValueBytes })
  5699. const result = await runtime.run({
  5700. program: [
  5701. 'import os, json',
  5702. // 32 ASCII chars then astral characters: code unit 32 is the first
  5703. // character's high surrogate (Python spells it as one code point, so
  5704. // json.dumps emits the raw 4 bytes the host reads back as a pair).
  5705. 'msg = "A" * 32 + "\\U0001f600" * 4',
  5706. 'os.write(3, json.dumps({"type":"done","error":{"kind":"exception","message":msg}}).encode() + b"\\n")',
  5707. 'import time',
  5708. 'time.sleep(5)',
  5709. ].join('\n'),
  5710. bindings: [],
  5711. })
  5712. expect(result.error?.kind).toBe('exception')
  5713. // 17 A's fill the marker-reserved budget; no orphaned half, no U+FFFD.
  5714. expect(result.error?.message).toBe(`${'A'.repeat(17)}… [truncated]`)
  5715. expect(Buffer.byteLength(result.error?.message ?? '', 'utf8')).toBe(maxValueBytes)
  5716. }, 8000)
  5717. it('returns a diagnostic under a third of the cap untouched, skipping the encode', async () => {
  5718. // Under maxValueBytes/3 code units a message cannot overflow the cap
  5719. // whatever it holds (3 bytes is the per-code-unit maximum), so the fast
  5720. // path returns it without encoding anything. Non-ASCII proves the bound is
  5721. // the code-unit count, not a byte assumption: 6 characters at 3 bytes each
  5722. // is 18 bytes, inside the 64-byte cap.
  5723. const { runtime } = await setup({ maxValueBytes: 64 })
  5724. const result = await runtime.run({
  5725. program: [
  5726. 'import os, json',
  5727. 'os.write(3, json.dumps({"type":"done","error":{"kind":"exception","message":"中文中文中文"}}).encode() + b"\\n")',
  5728. 'import time',
  5729. 'time.sleep(5)',
  5730. ].join('\n'),
  5731. bindings: [],
  5732. })
  5733. expect(result.error?.kind).toBe('exception')
  5734. expect(result.error?.message).toBe('中文中文中文')
  5735. }, 8000)
  5736. it('re-caps a forged done error.message host-side on a UTF-8 boundary', async () => {
  5737. // A forged done frame can carry an arbitrarily long error message; the
  5738. // host caps it to maxValueBytes and appends the shared marker. The
  5739. // message is emoji-dense and the cap is chosen so the marker-reserved
  5740. // 51-byte cut lands INSIDE a 4-byte sequence (one ASCII byte then 4-byte
  5741. // runs, so only a cut at 1 + 4k is aligned) — the cap must trim back to a
  5742. // code-point boundary rather than decode a replacement character, which
  5743. // would also exceed the cap.
  5744. const maxValueBytes = 66
  5745. const { runtime } = await setup({ maxValueBytes })
  5746. const result = await runtime.run({
  5747. program: [
  5748. 'import os, json',
  5749. 'msg = "E" + "\\U0001f600" * 2000',
  5750. 'os.write(3, json.dumps({"type":"done","error":{"kind":"exception","message":msg}}).encode() + b"\\n")',
  5751. 'import time',
  5752. 'time.sleep(5)',
  5753. ].join('\n'),
  5754. bindings: [],
  5755. })
  5756. expect(result.error?.kind).toBe('exception')
  5757. const message = result.error?.message ?? ''
  5758. expect(message.endsWith('… [truncated]')).toBe(true)
  5759. const marker = '… [truncated]'
  5760. const body = message.slice(0, message.length - marker.length)
  5761. // The WHOLE message, marker included, honors the cap.
  5762. expect(Buffer.byteLength(message, 'utf8')).toBeLessThanOrEqual(maxValueBytes)
  5763. // 'E' plus 12 emoji is 49 bytes: the trim-back walked the 51-byte budget
  5764. // down past two continuation bytes rather than splitting the 13th.
  5765. expect(body).toBe(`E${'\u{1f600}'.repeat(12)}`)
  5766. // The cut landed on a code-point boundary — no replacement character.
  5767. expect(body).not.toContain('\ufffd')
  5768. }, 8000)
  5769. it('bounds a single oversized newline-terminated line on fd 3', async () => {
  5770. // The same cap applies to one giant framed line. Write EXACTLY the
  5771. // cap with no newline — at the limit, not past it, so nothing trips —
  5772. // then a small newline tail, which is the chunk that crosses.
  5773. const ceiling = 64 * 1024 * 1024
  5774. const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 })
  5775. const result = await runtime.run({
  5776. program: [
  5777. 'import os',
  5778. 'chunk = b"A" * (8 * 1024 * 1024)',
  5779. `for _ in range(${ceiling / (8 * 1024 * 1024)}):`,
  5780. ' os.write(3, chunk)',
  5781. 'os.write(3, b"AAAA\\n")',
  5782. 'return "never"',
  5783. ].join('\n'),
  5784. bindings: [],
  5785. })
  5786. expect(result.error?.kind).toBe('worker-exit')
  5787. expect(result.error?.message).toContain(`protocol frame exceeded ${ceiling} bytes`)
  5788. }, 90_000)
  5789. it('rejects an over-cap newline-free fd-3 buffer without first joining it into one line', async () => {
  5790. // The cap has to be enforced on the byte COUNTER before Buffer.concat,
  5791. // not on the joined line afterwards: the join is a second copy of
  5792. // everything held, so a program could force roughly twice the advertised
  5793. // 64 MiB of host memory before anything rejected it.
  5794. //
  5795. // This program writes past the cap with no newline: the counter crosses on
  5796. // the 9th 8 MiB write (72 MiB) while the buffer is still a single unframed
  5797. // line, so the pre-join check rejects it without concat-ing a second copy.
  5798. // Checking the joined line instead would have produced a 72 MiB FIRST LINE
  5799. // that the per-line bound then dropped only after the doubling had happened.
  5800. const ceiling = 64 * 1024 * 1024
  5801. const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 })
  5802. const result = await runtime.run({
  5803. program: [
  5804. 'import os',
  5805. 'chunk = b"A" * (8 * 1024 * 1024)',
  5806. `for _ in range(${ceiling / (8 * 1024 * 1024) + 1}):`,
  5807. ' os.write(3, chunk)',
  5808. 'return "never"',
  5809. ].join('\n'),
  5810. bindings: [],
  5811. })
  5812. expect(result.value).toBeUndefined()
  5813. expect(result.error?.kind).toBe('worker-exit')
  5814. expect(result.error?.message).toContain(`protocol frame exceeded ${ceiling} bytes`)
  5815. }, 120_000)
  5816. it('keeps two within-cap frames whose combined buffer crosses the cap', async () => {
  5817. // The unframed byte counter charges the WHOLE buffer, which legitimately
  5818. // holds several frames each within FRAME_PARSE_CAP_BYTES. A first frame of
  5819. // exactly the cap followed by a second frame crosses the counter without
  5820. // either frame exceeding the cap; the first-frame check (not the counter)
  5821. // must let them through, or a legitimate near-cap frame plus a trailing
  5822. // frame would be misreported as a worker-exit.
  5823. const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 })
  5824. const result = await runtime.run({
  5825. program: [
  5826. 'import os',
  5827. 'chunk = b"A" * (8 * 1024 * 1024)',
  5828. // Exactly the cap, no newline — at the limit, so nothing trips.
  5829. 'for _ in range(8):',
  5830. ' os.write(3, chunk)',
  5831. // A newline, then a small legitimate log frame.
  5832. 'os.write(3, b"\\n{\\"type\\":\\"log\\",\\"text\\":\\"after-cap-frames\\"}\\n")',
  5833. 'return "done"',
  5834. ].join('\n'),
  5835. bindings: [],
  5836. })
  5837. expect(result.error).toBeUndefined()
  5838. expect(result.value).toBe('done')
  5839. expect(result.logs).toContain('after-cap-frames')
  5840. }, 120_000)
  5841. it('rejects an oversized first frame that lands on the sealing threshold with a newline', async () => {
  5842. // The fragment-count seal runs only on newline-free chunks (the ELSE half
  5843. // of the newline branch), so a chunk that carries the first newline always
  5844. // reaches the join and its first-frame check; sealing it into a block
  5845. // would empty pendingChunks, leave sawNewline false, and skip that check.
  5846. // Whether the pipe delivers exactly 1024 chunks is timing-dependent, but
  5847. // the oversized first frame (63.9 MiB of A's + 12289 more before the
  5848. // newline) exceeds FRAME_PARSE_CAP_BYTES no matter how it arrives — the
  5849. // case pins the worker-exit settlement, not a pre/post copy-count
  5850. // distinction (both orders reject an over-cap frame).
  5851. const { runtime } = await setup({ maxWallMs: 60_000, addressSpaceMb: 2048 })
  5852. const result = await runtime.run({
  5853. program: [
  5854. 'import os',
  5855. // 4 KiB writes are <= PIPE_BUF, so each os.write is atomic and the
  5856. // host sees one chunk per write; 16384 of them accumulate 64 MiB of
  5857. // newline-free bytes (16 fragment-count seals of 1024 chunks).
  5858. 'chunk = b"A" * 4096',
  5859. 'for _ in range(16384):',
  5860. ' os.write(3, chunk)',
  5861. // 12289 more A's push the first frame past 64 MiB; drain-loop so the
  5862. // write cannot truncate, then a newline and a small legitimate frame.
  5863. "data = b'A' * 12289 + b'\\n' + b'{\"type\":\"log\",\"text\":\"after-seal\"}\\n'",
  5864. 'view = memoryview(data)',
  5865. 'while view:',
  5866. ' view = view[os.write(3, view):]',
  5867. 'return "done"',
  5868. ].join('\n'),
  5869. bindings: [],
  5870. })
  5871. expect(result.error?.kind).toBe('worker-exit')
  5872. expect(result.error?.message).toContain('protocol frame exceeded')
  5873. }, 120_000)
  5874. })