1
0

runtime.spec.ts 169 KB

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