runtime.spec.ts 176 KB

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