runtime.spec.ts 225 KB

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