runtime.spec.ts 196 KB

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