runtime.spec.ts 204 KB

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