runtime.spec.ts 189 KB

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