runtime.spec.ts 209 KB

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