1
0

runtime.spec.ts 253 KB

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