runtime.spec.ts 206 KB

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