1
0

runtime.spec.ts 153 KB

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