runtime.spec.ts 160 KB

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