runtime.spec.ts 260 KB

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