runtime.spec.ts 237 KB

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