1
0

runtime.spec.ts 157 KB

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