runtime.spec.ts 214 KB

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