runtime.spec.ts 182 KB

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