runtime.spec.ts 195 KB

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