runtime.spec.ts 290 KB

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