index.ts 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441
  1. /**
  2. * CPython subprocess code runtime: a fresh `python3` process runs each model program under an
  3. * asyncio event loop with top-level ``await``. Binding calls travel on fd 3 as JSON-lines,
  4. * leaving stdout/stderr free for the program's own output. This is containment, not a security
  5. * boundary: model code has bash-equivalent trust, contained by a tempdir-only environment,
  6. * RLIMIT_CPU + RLIMIT_AS, wall-clock timeout, and SIGTERM→grace→SIGKILL on the process group.
  7. *
  8. * The package also owns the versionless fd-3 wire protocol itself; its host-side codec and
  9. * hostile-frame validators are re-exported so every consumer of the wire shares one vocabulary.
  10. * @module @deepseek-ai/dsh-experimental-code-runtime-python
  11. */
  12. import { execFileSync, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
  13. import { accessSync, copyFileSync, constants as fsConstants, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs'
  14. import { tmpdir } from 'node:os'
  15. import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path'
  16. import { fileURLToPath } from 'node:url'
  17. import { getHeapStatistics } from 'node:v8'
  18. import type { Duplex } from 'node:stream'
  19. import { Context } from '@deepseek-ai/cordis'
  20. import z from '@deepseek-ai/schemastery'
  21. import { CodeRuntime, DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-code-runtime'
  22. import type { CodeBindingErrorClass, CodeBindingFunction, CodeJsonValue, CodeRunFailure, CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
  23. import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values'
  24. import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
  25. import type { BootMessage, ChildToHost, ReplyMessage } from './protocol.ts'
  26. import { checkDoneValue, encodeJsonPlain, hasUnsafeIntegerToken, logTruncationMarker, validateChildFrame } from './protocol.ts'
  27. // Re-export the fd-3 wire vocabulary so the runtime and its tests share one
  28. // import surface; the protocol layer owns the definitions.
  29. export type { BootMessage, ChildToHost, ReplyMessage } from './protocol.ts'
  30. export {
  31. checkDoneValue,
  32. encodeJsonPlain,
  33. hasNonLosslessNumber,
  34. hasUnsafeIntegerToken,
  35. logTruncationMarker,
  36. validateChildFrame,
  37. } from './protocol.ts'
  38. /** Plugin config: every cap, changeable from `cordis.yml` (no hardcoded tunables). */
  39. export interface Config {
  40. /**
  41. * RLIMIT_CPU in whole seconds (a positive integer — `setrlimit` in the child
  42. * rejects a float). The child sets the soft limit to `cpuSeconds` and the
  43. * hard limit to `cpuSeconds + 1`: the kernel delivers SIGXCPU at the soft
  44. * limit, which the host classifies as a `timeout`; the +1s hard limit is a
  45. * SIGKILL backstop for a program that traps SIGXCPU. Granularity is seconds —
  46. * a coarser counterpart to the worker backend's millisecond `computeMs`.
  47. */
  48. cpuSeconds?: number
  49. /** Wall-clock ceiling in milliseconds; backstops CPU time for programs awaiting a promise nobody resolves. */
  50. maxWallMs?: number
  51. /**
  52. * RLIMIT_AS in mebibytes; caps address space so a runaway allocation fails
  53. * cleanly. Not applied on Darwin, where the dyld shared cache mapped into
  54. * every process at exec exceeds any practical cap and the kernel rejects
  55. * the call; `cpuSeconds` and `maxWallMs` still bound the run there. Bounds
  56. * `maxLogBytes`/`maxValueBytes` at load on EVERY platform (this static check
  57. * runs on Darwin too, where only the runtime `setrlimit` is skipped): each
  58. * budget times a worst-case Unicode expansion must fit this byte count minus a
  59. * fixed interpreter baseline, so a near-budget output cannot breach the address
  60. * space during the child's build-and-encode.
  61. */
  62. addressSpaceMb?: number
  63. /**
  64. * Shared byte budget for captured log text (host-side ledger). Bounded at load
  65. * against `addressSpaceMb`: the child builds and encodes a near-budget entry
  66. * under RLIMIT_AS with several copies live at once, so this cap times the
  67. * worst-case Unicode expansion must fit the address space left after the
  68. * interpreter baseline (see `addressSpaceMb`) — a load-time rejection, not a
  69. * runtime clamp. Also bounded at load by the host's configured heap like
  70. * `maxValueBytes` (see its JSDoc): the effective frame cap minus the frame
  71. * envelope.
  72. */
  73. maxLogBytes?: number
  74. /**
  75. * Byte cap for the completion value. Bounded at load against `addressSpaceMb`
  76. * the same way `maxLogBytes` is: the child builds and encodes a near-budget
  77. * value under RLIMIT_AS with several copies live at once, so this cap times the
  78. * worst-case Unicode expansion must fit the address space left after the
  79. * interpreter baseline. Both budgets are ALSO bounded at load by the host's
  80. * configured heap: the effective frame cap (the protocol cap, or a lower
  81. * heap-derived ceiling when the host heap cannot safely parse a near-cap
  82. * frame — see `hostFrameParseCeiling`) minus the frame envelope, so a budget
  83. * whose honest frame could OOM the host's own JSON.parse is rejected up
  84. * front.
  85. */
  86. maxValueBytes?: number
  87. /** SIGTERM→SIGKILL grace period on kill, matching bash-local's default. */
  88. graceMs?: number
  89. /**
  90. * Absolute path, relative path, or basename of a CPython 3.10+ interpreter.
  91. * Resolved and validated once at plugin load under a five-second force-kill
  92. * deadline; a basename searches `PATH`.
  93. */
  94. pythonBin?: string
  95. }
  96. /** {@link Config} with all defaults filled. */
  97. type ResolvedConfig = Required<Config>
  98. /**
  99. * The seam's language-portable identifier subset (see
  100. * `CodeBindingNamespace.global`) — identical to Python's identifier grammar,
  101. * so the shared contract needs no per-backend mapping here.
  102. */
  103. const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/
  104. /**
  105. * The seam's cross-language reserved-word union: the portable-identifier
  106. * contract promises a namespace list valid here is valid on every backend, so
  107. * a JS keyword like `typeof` is refused even though it is a legal Python name.
  108. */
  109. const RESERVED_NAMES = PORTABLE_RESERVED_WORDS
  110. /**
  111. * The seam's shared backend-owned globals (`console` is the worker's slot;
  112. * `__dsh_main__`/`__builtins__`/`__name__` are this bootstrap's wrapper and
  113. * seeded module globals). Shared so a namespace list valid on one backend is
  114. * valid on all — colliding with an owned slot would be silently overwritten
  115. * (or overwrite builtins), so the seam rejects them up front.
  116. */
  117. const RUNTIME_OWNED_GLOBALS = RESERVED_BINDING_GLOBALS
  118. /**
  119. * The seam's shared error-member exclusions (`RESERVED_ERROR_MEMBERS` +
  120. * dunder-form names) — enforced identically here and in the worker backend so
  121. * an errorClass valid on one backend is valid on all. Several dunders are
  122. * constrained CPython descriptors whose `setattr` raises while constructing
  123. * the very rejection it was meant to carry; the exact set is an interpreter
  124. * version detail, hence the dunder-wide rule at the seam.
  125. */
  126. const EXCEPTION_RESERVED_MEMBERS = RESERVED_ERROR_MEMBERS
  127. const DUNDER = DUNDER_MEMBER
  128. /**
  129. * The `py/` scripts the interpreter must be able to open: the entry script plus
  130. * every module it imports from its own directory. Kept beside the built JS so a
  131. * consumer package with `files: ['lib', 'py']` ships both.
  132. */
  133. const PY_SCRIPTS = ['bootstrap.py', 'protocol.py']
  134. /**
  135. * Copy the `py/` scripts to a real filesystem directory and return the entry
  136. * script's path there.
  137. *
  138. * The interpreter is an EXTERNAL process, so it can only open paths the OS
  139. * resolves. Inside the single-file Python-SDK executable, `import.meta.url`
  140. * resolves into pkg's virtual filesystem, which Node reads through its patched
  141. * `fs` but `python3` cannot see at all — the spawn fails with ENOENT on a path
  142. * that exists as far as the host is concerned. `bootstrap.py` additionally
  143. * inserts its own directory on `sys.path` to import the sibling `protocol.py`,
  144. * so both files must land in the SAME real directory.
  145. *
  146. * The copy is unconditional rather than gated on a bundled-runtime probe: the
  147. * read goes through Node's `fs` either way, and one code path means the
  148. * packaged deployment runs what the tests exercise. Placement is under
  149. * `os.tmpdir()` with `0o700` keeps the scripts off other users' reach, but NOT
  150. * the model's: the child runs as the same UID as the host, so a program can
  151. * rewrite the very files it was started from. Hence one copy per RUN, discarded
  152. * at settlement — a rewrite then damages only the run that performed it, which
  153. * is what fresh-subprocess-per-run already promises. Sharing one copy across
  154. * runs made an overwritten `bootstrap.py` break the next run.
  155. *
  156. * Deliberately SYNCHRONOUS. An `await` here would open an async boundary in
  157. * `execute` before the run is registered in `live` and before the abort
  158. * listener is installed, so a disposal or an abort landing in that window would
  159. * be missed: `teardown` would see no runs and return while the continuation
  160. * went on to spawn a subprocess, and an `addEventListener('abort')` installed
  161. * afterwards does not replay an event that already fired. Three small
  162. * filesystem operations per run are not worth that class of race, and `execute`
  163. * already runs synchronously up to `spawn`.
  164. *
  165. * A failed copy removes the directory here, so a partial attempt never outlives
  166. * the call that made it; a successful one is the caller's to remove, which it
  167. * derives from the returned path.
  168. *
  169. * @returns the absolute path of the materialized entry script.
  170. */
  171. function materializePyScripts(): string {
  172. const dir = mkdtempSync(join(tmpdir(), 'dsh-code-runtime-python-'))
  173. const source = fileURLToPath(new URL('../py/', import.meta.url))
  174. try {
  175. for (const name of PY_SCRIPTS) copyFileSync(join(source, name), join(dir, name))
  176. } catch (error: unknown) {
  177. try {
  178. rmSync(dir, { recursive: true, force: true })
  179. } catch {
  180. // Swallows only a failure to remove the partial staging directory. The
  181. // caller reports the copy failure that got us here, which is the
  182. // diagnosable one; nothing else can act on a temp dir we cannot unlink.
  183. }
  184. throw error
  185. }
  186. return join(dir, 'bootstrap.py')
  187. }
  188. /**
  189. * A frame's RAW length is capped before JSON.parse: the 64 MiB fd-3 frame
  190. * parse cap bounds the bytes, not the decoded structure, and a compact wide
  191. * frame near that ceiling (e.g. a huge array of tiny elements) could decode to
  192. * far more host memory than the wire admitted — an OOM inside the receive
  193. * path. 64 MiB raw admits every legal config (the widest in-tree completion
  194. * and binding frames are ~12 MB) while bounding decode amplification to a
  195. * roughly constant factor of the wire bytes. The unframed-buffer counter is
  196. * checked against this same cap BEFORE a `Buffer.concat` join, so an oversized
  197. * frame is dropped at one copy of its wire bytes. A hostile-peer invariant,
  198. * not a deployment choice.
  199. */
  200. const FRAME_PARSE_CAP_BYTES = 64 * 1024 * 1024
  201. /**
  202. * Fragments the unframed fd-3 buffer may hold before they are coalesced into
  203. * one Buffer, bounding retained per-chunk overhead that the byte cap cannot
  204. * see: the cap meters payload bytes, while each chunk is a distinct Buffer
  205. * with its own object and backing store. A
  206. * program writing single bytes without a newline produced one chunk per write.
  207. * 1024 keeps the overhead a small constant factor of the payload while leaving
  208. * normal pipe-sized reads (which arrive in far fewer, much larger chunks)
  209. * untouched. A framing invariant, not a deployment choice.
  210. */
  211. const MAX_PENDING_CHUNKS = 1024
  212. /**
  213. * Replies the host retains before fd 3 accepts them. The drain loop writes one
  214. * reply per iteration and waits for `drain` when the pipe is full; a child
  215. * that never reads its replies (hostile or wedged) leaves the pipe full, so
  216. * every call frame it keeps sending adds a reply the drain cannot write, and
  217. * the backlog would grow without bound until the wall clock. 1024 keeps
  218. * legitimate concurrent gathers (measured queue depths reach 11) far below
  219. * the ceiling while bounding the hostile backlog; the run settles as a
  220. * worker-exit past it, like the frame cap settles an oversized frame. A
  221. * framing invariant, not a deployment choice.
  222. */
  223. const MAX_PENDING_REPLIES = 1024
  224. /**
  225. * Bytes a frame spends on its own JSON structure around a capped payload, used
  226. * to bound `maxLogBytes`/`maxValueBytes` against {@link FRAME_PARSE_CAP_BYTES}
  227. * (the receive path rejects raw frames past that cap, settling the run as a
  228. * worker-exit).
  229. * The widest carrier is `{"type":"log","text":"","truncated":true}` at 41
  230. * bytes; 64 rounds that up so adding a field to either frame does not silently
  231. * invalidate the bound. A protocol constant, not a deployment choice.
  232. */
  233. const FRAME_ENVELOPE_BYTES = 64
  234. /**
  235. * Smallest `maxLogBytes` the backend can honor. The truncation marker alone
  236. * (`logTruncationMarker`) must serialize within the budget, or a marker-only
  237. * truncated run returns more than the configured cap: the marker text is
  238. * `[dsh-code-runtime-python] log capture truncated at <N> bytes` — 51 fixed
  239. * characters (the bracketed prefix `[dsh-code-runtime-python] log capture
  240. * truncated at ` counts both square brackets) plus the digits of N plus 6 —
  241. * and its serialized form adds 4 (two quotes, two array brackets), so the
  242. * smallest N that admits its own marker is 63 (51 + 2 + 6 + 4 = 63); 64 is the
  243. * floor with one byte of room. The marker itself remains envelope, not
  244. * payload, so a truncated run with admitted entries serializes to at most
  245. * `maxLogBytes + marker + envelope`.
  246. * `maxValueBytes` has no floor beyond the positive-integer requirement: a
  247. * completion can be as small as a single byte (`1`), and the done-frame
  248. * envelope is seam protocol cost, not the advertised completion budget.
  249. */
  250. const MIN_LOG_BYTES = 64
  251. /**
  252. * Extra time added to `graceMs` before the post-kill close-deadline force-settles
  253. * a run whose `close` never fires (a setsid-escaped orphan holds our inherited
  254. * stdio; see the `closeDeadline` arm in {@link PythonCodeRuntime.execute}). It
  255. * covers the OS reaping the killed child itself after SIGKILL — not a deployment
  256. * choice but a fixed safety margin, so it is a constant rather than a config knob.
  257. */
  258. const CLOSE_REAP_MARGIN_MS = 2_000
  259. /**
  260. * Worst-case peak child-process bytes a one-`maxLogBytes`/`maxValueBytes`-budget
  261. * output can transiently occupy while the child charges and frames it, expressed
  262. * as a multiple of the budget. The child's ledgers trigger on CHARACTER count
  263. * against a serialized-BYTE budget, and an astral character is one character but
  264. * four bytes of CPython `str` storage and four UTF-8 bytes — so a budget's worth
  265. * of astral characters is ~4x the budget in each string that holds it. The
  266. * heaviest path holds THREE such copies at once: a single
  267. * `sys.stdout.write(line + "\n")` keeps the caller's `text` argument (alive for
  268. * the whole `write` call, ~4x), the line slice `text[pos:newline]` handed to
  269. * `LogBuffer.push` (~4x), and the `text.encode("utf-8")` copy `_push_locked`
  270. * takes to charge and ship it (~4x). The settlement `flush_line` path holds only
  271. * two (its `"".join(...)` and that encode copy — it drops the pending chunks
  272. * before pushing), so the newline path is the binding worst case. Twelve covers
  273. * those three simultaneous ~4x copies. The interpreter baseline is NOT in this
  274. * multiple — it is reserved separately as {@link INTERPRETER_BASELINE_BYTES} —
  275. * because it is a fixed cost, not one that scales with the budget. Used to bound
  276. * `maxLogBytes`/`maxValueBytes` against `addressSpaceMb` at load, with a `>=` so
  277. * a budget whose worst-case peak exactly equals the room left after the baseline
  278. * is rejected (that peak plus the baseline is the whole address space, the
  279. * RLIMIT_AS edge), so a legitimate near-budget output truncates (log) or fails
  280. * as `output-limit` (value) rather than breaching `RLIMIT_AS` as `worker-exit`.
  281. * A fixed safety invariant tying the budgets to the address space, not a knob.
  282. */
  283. const OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE = 12
  284. /**
  285. * Fixed address-space headroom reserved for the CPython interpreter itself
  286. * (loaded modules, the asyncio loop, import machinery) before the output-budget
  287. * multiple claims the rest. The budget check subtracts this from `addressSpaceMb`
  288. * so a budget sized right at `addressSpaceMb / MULTIPLE` — which the multiple
  289. * alone would admit — cannot leave the peak output allocation plus the
  290. * interpreter over the limit. Sized against ADDRESS SPACE, which is what
  291. * `RLIMIT_AS` bounds, not resident set: the bootstrap's own measurement is
  292. * 30.23 MiB of mappings for a `python3 -I` child (see `_make_cpu_enforcer`,
  293. * which also records the 64 MiB glibc per-thread arena reservation that pushes
  294. * it to 102.37 MiB when threads are used). 64 MiB is roughly twice the measured
  295. * baseline, leaving room for allocator arenas and import jitter. The value is a
  296. * fixed safety margin, not a deployment knob.
  297. */
  298. const INTERPRETER_BASELINE_BYTES = 64 * 1024 * 1024
  299. /**
  300. * Worst-case peak host-heap bytes the PARSE of one inbound fd-3 frame can
  301. * transiently occupy, expressed as a multiple of the frame's raw bytes.
  302. * `JSON.parse` of a wide container materializes the object's property storage
  303. * and key strings on top of the raw text; the WORST shape is a dict of many
  304. * SHORT UNIQUE keys, which forces V8's dictionary-mode property storage
  305. * (~32-64 bytes per entry) plus one interned string per key (header + data)
  306. * plus string-table growth: measured 6.4x for a 3,000,000-key frame (~31 MB
  307. * raw) on a 1 GiB heap, trending up with key count (a flat unique-key array
  308. * is ~4x, a repeated-key dict ~3x). On a constrained heap the parse also
  309. * retains the raw frame string while the object builds, so the safety factor
  310. * is 16x — ~2.5x over the measured worst shape, ~1.6x over the claimed
  311. * GC-headroom bound. Used with the host's configured heap limit to derive the
  312. * largest frame whose parse cannot OOM the host process. This bounds the
  313. * HOST's parse; {@link OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE} bounds
  314. * the CHILD's build and encode under RLIMIT_AS, a different resource. A fixed
  315. * safety invariant, not a knob.
  316. */
  317. const HOST_PARSE_WORST_CASE_MULTIPLE = 16
  318. /**
  319. * Fixed host-heap headroom reserved for the application itself (the dsh
  320. * fiber, plugins, and this runtime's own state) before the frame-parse
  321. * multiple claims the rest: the effective frame cap is derived from
  322. * `heap_size_limit - HOST_PARSE_BASELINE_BYTES`, so a constrained host's
  323. * parse ceiling never spends the application's working set. A fixed safety
  324. * margin, not a knob.
  325. */
  326. const HOST_PARSE_BASELINE_BYTES = 64 * 1024 * 1024
  327. /**
  328. * The largest inbound fd-3 frame the HOST can parse without risking a
  329. * process-level OOM on its current heap: the configured heap limit (honoring
  330. * `--max-old-space-size`) minus the application baseline, divided by the
  331. * worst-case parse multiple, floored to the protocol frame cap. The
  332. * raw-byte cap alone does not protect the heap — `JSON.parse` of a
  333. * ≤64 MiB wide-object frame materializes several times that in property
  334. * storage — so the effective cap is the smaller of the two. A default Node
  335. * heap (~4 GiB) never binds; a constrained host (e.g.
  336. * `--max-old-space-size=256` reports a ~300 MiB limit) lowers it to ~14 MiB,
  337. * and the load gate rejects budgets that cannot cross it.
  338. * @param heapLimit - the host's configured heap limit; the live
  339. * `heap_size_limit` when omitted. A parameter so the derivation is unit
  340. * testable against simulated heap sizes.
  341. * @returns the effective frame parse cap in bytes.
  342. */
  343. export function hostFrameParseCeiling(heapLimit: number = getHeapStatistics().heap_size_limit): number {
  344. return Math.min(FRAME_PARSE_CAP_BYTES, Math.floor((heapLimit - HOST_PARSE_BASELINE_BYTES) / HOST_PARSE_WORST_CASE_MULTIPLE))
  345. }
  346. /**
  347. * Interval between process-group liveness probes while settlement waits for an
  348. * escalated SIGKILL to empty the group (see the `killing` branch in
  349. * {@link PythonCodeRuntime.execute}'s settle). A poll rather than an event
  350. * because the group members are the model's own descendants, which the host does
  351. * not `wait()` for and gets no exit signal from; the probe is a signal-0
  352. * `process.kill(-pid, 0)`, so the interval only bounds how promptly a now-empty
  353. * group is noticed, capped by `graceMs + CLOSE_REAP_MARGIN_MS`.
  354. */
  355. const GROUP_REAP_POLL_MS = 50
  356. /**
  357. * Extract a human message from an unknown thrown value.
  358. *
  359. * `String(error)` runs the value's own conversion, and a host binding may reject
  360. * with an object whose `Symbol.toPrimitive` or `toString` throws. One call site
  361. * is a detached async reply callback, where that throw escapes as an unhandled
  362. * rejection: the reply frame is never written, the program stays blocked on
  363. * `await`, and the run degrades to a `maxWallMs` timeout (a Node host without an
  364. * `unhandledRejection` listener exits outright). The conversion is therefore
  365. * wrapped, with a fixed literal as the fallback — the value already proved it
  366. * cannot be rendered, so nothing derived from it is safe to try.
  367. *
  368. * `Error.message` is typed `string` but is a plain writable property, so a
  369. * rejecting binding can hand back an `Error` carrying any value there. The
  370. * `Error` arm therefore goes through the same conversion rather than returning
  371. * `message` verbatim: the returned string crosses the wire under
  372. * `encodeJsonPlain`'s JSON-plain precondition, where a cyclic object grows the
  373. * encoder stack until the host exhausts memory and any other unsupported value
  374. * prevents the reply frame outright.
  375. *
  376. * The same conversion renders abort reasons, which reach an `AbortSignal`
  377. * listener: Node reports a throw from such a listener as an uncaught exception,
  378. * so an unwrapped conversion there can terminate the host with the run left
  379. * unsettled.
  380. *
  381. * @param error The thrown value, of unknown shape.
  382. * @returns The value's message or string form; a fixed placeholder when its own
  383. * conversion throws.
  384. */
  385. function messageOf(error: unknown): string {
  386. try {
  387. return String(error instanceof Error ? error.message : error)
  388. } catch {
  389. // Swallows only a throw from the value's own `message` getter or string
  390. // conversion. Nothing else runs inside the try, and the placeholder is a
  391. // literal, so this cannot throw again.
  392. return '<unrenderable rejection value>'
  393. }
  394. }
  395. /**
  396. * A process's start time, as the identity half of (pid, started).
  397. *
  398. * A pid is reusable the moment the kernel reaps it, so signalling one that a
  399. * later process inherited would terminate an unrelated process group. Start
  400. * time is what distinguishes the original from its replacement: `kill(pid, 0)`
  401. * answers "does this number exist", which is true for both.
  402. *
  403. * Linux reads field 22 of `/proc/<pid>/stat` (starttime in clock ticks); the
  404. * field is positional after the comm field's closing parenthesis, which is
  405. * parsed from the LAST such character because a process name may contain one.
  406. * Darwin has no `/proc`, so the caller gets `undefined` there and `killGroup`
  407. * signals the pgid without the identity re-check rather than paying a `ps`
  408. * fork on a teardown path. Any read failure is `undefined` for the same
  409. * reason: this
  410. * hardens a narrow race and must never be the thing that breaks teardown.
  411. * @param pid - the process to read.
  412. * @returns its start time, or undefined when unavailable.
  413. */
  414. export function readProcessStart(pid: number): string | undefined {
  415. /* v8 ignore next -- one arm per platform: the Linux coverage lane always takes the read path, and Darwin always this one. */
  416. if (process.platform !== 'linux') return undefined
  417. try {
  418. const stat = readFileSync(`/proc/${String(pid)}/stat`, 'utf8')
  419. const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ')
  420. // Field 22 overall; the slice above dropped pid and comm, so it is index 19.
  421. return fields[19]
  422. } catch {
  423. return undefined
  424. }
  425. }
  426. /**
  427. * Resolve `pythonBin` to one executable absolute path at plugin load. A basename
  428. * (the default `python3`) searches the current process `PATH`; the child receives
  429. * no `PATH`, so Node's own lookup would otherwise fall back to the platform
  430. * default (`/usr/bin:/bin`) and miss interpreters
  431. * that live only on the caller's `PATH` (Nix, pyenv, Homebrew, conda). An
  432. * absolute path is verified in place, and an explicitly relative path is first
  433. * resolved against the load-time working directory. When no candidate is an
  434. * executable regular file, `undefined` is returned and the load check rejects
  435. * the configuration: falling back to the bare name would let spawn's scrubbed env
  436. * execvp silently start a system interpreter from the platform default PATH
  437. * that the caller never asked for.
  438. * @param bin - the configured interpreter (absolute path, relative path, or bare command).
  439. * @returns an absolute path when resolvable, else `undefined`.
  440. */
  441. export function resolvePythonBin(bin: string): string | undefined {
  442. const executableFile = (candidate: string): string | undefined => {
  443. try {
  444. accessSync(candidate, fsConstants.X_OK)
  445. return statSync(candidate).isFile() ? candidate : undefined
  446. } catch {
  447. // Missing, inaccessible, and non-stat-able candidates are ordinary
  448. // lookup misses; the constructor reports the final load error.
  449. return undefined
  450. }
  451. }
  452. if (isAbsolute(bin)) return executableFile(bin)
  453. if (bin.includes('/')) return executableFile(resolve(bin))
  454. const path = process.env.PATH
  455. /* v8 ignore next -- PATH is set in every environment the runtime boots in; the guard is defensive. */
  456. if (path === undefined) return undefined
  457. for (const dir of path.split(delimiter)) {
  458. // An empty PATH segment (a `::`, implicitly CWD on POSIX) and a RELATIVE
  459. // segment (`bin` or `.`) are skipped: a basename must never resolve against
  460. // the working directory, and the returned candidate must be an absolute
  461. // path — spawn() resolves a relative pythonBin against the host CWD, which
  462. // is outside the seam contract.
  463. if (dir === '' || !isAbsolute(dir)) continue
  464. const executable = executableFile(join(dir, bin))
  465. if (executable !== undefined) return executable
  466. }
  467. return undefined
  468. }
  469. /** Lowest CPython version supported by the bootstrap and its traceback behavior. */
  470. const MIN_CPYTHON = { major: 3, minor: 10 } as const
  471. /** Fixed load-time probe bound; a configured executable must not hang plugin activation. */
  472. const PYTHON_PROBE_TIMEOUT_MS = 5_000
  473. /** The only host environment fact exposed to the child. */
  474. function pythonEnvironment(): NodeJS.ProcessEnv {
  475. return { TMPDIR: tmpdir() }
  476. }
  477. /** Fail load unless `bin` is a responsive CPython 3.10+ interpreter. */
  478. function validatePythonBin(bin: string): void {
  479. let output: string
  480. try {
  481. output = execFileSync(bin, [
  482. '-I',
  483. '-c',
  484. 'import sys; print(sys.implementation.name, sys.version_info.major, sys.version_info.minor, sys.version_info.micro)',
  485. ], {
  486. encoding: 'utf8',
  487. env: pythonEnvironment(),
  488. timeout: PYTHON_PROBE_TIMEOUT_MS,
  489. // The configured executable is outside our control. Force-kill it at the
  490. // deadline so a wrapper that ignores SIGTERM cannot block plugin load.
  491. killSignal: 'SIGKILL',
  492. maxBuffer: 1_024,
  493. }).trim()
  494. } catch (error: unknown) {
  495. throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(bin)} failed the CPython version probe: ${messageOf(error)}`)
  496. }
  497. const match = /^(\S+) (\d+) (\d+) (\d+)$/.exec(output)
  498. if (match === null) {
  499. throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(bin)} did not report a CPython version`)
  500. }
  501. const [, implementation, majorText, minorText, patchText] = match
  502. const major = Number(majorText)
  503. const minor = Number(minorText)
  504. if (implementation !== 'cpython') {
  505. throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(bin)} must be CPython, got ${implementation}`)
  506. }
  507. if (major < MIN_CPYTHON.major || (major === MIN_CPYTHON.major && minor < MIN_CPYTHON.minor)) {
  508. throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(bin)} must be CPython ${MIN_CPYTHON.major}.${MIN_CPYTHON.minor} or newer, got ${implementation} ${majorText}.${minorText}.${patchText}`)
  509. }
  510. }
  511. /** The marker appended when a diagnostic message is byte-capped host-side. */
  512. const TRUNCATION_MARKER = '… [truncated]'
  513. /**
  514. * The marker's own UTF-8 byte length, reserved out of the budget so a capped
  515. * message stays WITHIN `maxValueBytes` rather than exceeding it by the marker.
  516. * The ellipsis is 3 bytes, so this is 15, not the string's 13 code units.
  517. */
  518. const TRUNCATION_MARKER_BYTES = Buffer.byteLength(TRUNCATION_MARKER, 'utf8')
  519. // Fatal UTF-8 decoder for fd-3 frames: `toString('utf8')` replaces illegal
  520. // bytes with U+FFFD, which would silently corrupt a completion or binding
  521. // payload a forged frame smuggled in; a fatal decode throws instead and the
  522. // frame is dropped. Non-stream mode keeps it stateless across lines.
  523. const UTF8_FATAL = new TextDecoder('utf-8', { fatal: true })
  524. /**
  525. * Serialized JSON byte width of one character, given its code point and the
  526. * one-character string. Control characters below 0x20 escape to `\uXXXX` (6)
  527. * except the five with short forms `\b \t \n \f \r` (2); `"` and `\` escape to
  528. * 2; a LONE surrogate escapes to `\uXXXX` (6) under ES2019 well-formed
  529. * `JSON.stringify`; everything else rides at its raw UTF-8 width.
  530. * @param code - the character's code point.
  531. * @param character - the one-character (or one-code-point) string.
  532. * @returns the character's serialized JSON byte width.
  533. */
  534. function serializedCharCost(code: number, character: string): number {
  535. if (code < 0x20) return code === 0x08 || code === 0x09 || code === 0x0a || code === 0x0c || code === 0x0d ? 2 : 6
  536. if (code === 0x22 || code === 0x5c) return 2
  537. if (code >= 0xd800 && code <= 0xdfff) return 6
  538. return Buffer.byteLength(character, 'utf8')
  539. }
  540. /**
  541. * Serialized JSON-string cost of `text` (the two quotes plus each character's
  542. * escaped byte width), measured WITHOUT materializing the escaped copy, and
  543. * abandoned the instant it exceeds `maxBytes`. `JSON.stringify(text)` would
  544. * allocate the whole escaped form first — up to sixfold a control-char-dense
  545. * string — so a near-budget line under a large `maxLogBytes` could momentarily
  546. * allocate over a gigabyte just to measure it. This walks code point by code
  547. * point (a matched surrogate pair yields its combined code point ≥ 0x10000; a
  548. * lone surrogate yields a value in 0xD800–0xDFFF that {@link serializedCharCost}
  549. * charges the full six escaped bytes) and stops at the cap, allocating nothing.
  550. * @param text - the candidate string.
  551. * @param maxBytes - the largest serialized size the caller can admit.
  552. * @returns the exact serialized byte cost, or `undefined` once it exceeds `maxBytes`.
  553. */
  554. function jsonStringCostUpTo(text: string, maxBytes: number): number | undefined {
  555. if (maxBytes < 2) return undefined
  556. let bytes = 2 // the enclosing quotes
  557. for (const character of text) {
  558. bytes += serializedCharCost(character.codePointAt(0) as number, character)
  559. if (bytes > maxBytes) return undefined
  560. }
  561. return bytes
  562. }
  563. /**
  564. * Cross-chunk UTF-8 state for {@link accrueStrayCost}: `expected` continuation
  565. * bytes still needed to finish the in-progress sequence, its total `width`, and
  566. * `lowerFirst`/`upperFirst`, the valid range for the NEXT continuation byte
  567. * (only the first continuation of a 3- or 4-byte lead is range-restricted; once
  568. * consumed, later continuations accept the full 0x80–0xBF). All zero between
  569. * sequences. Carried on each {@link StrayBuffer} so a multibyte character split
  570. * across pipe `data` chunks is costed as one character.
  571. */
  572. interface Utf8CostState { expected: number; width: number; lowerFirst: number; upperFirst: number }
  573. /**
  574. * Accrue the serialized JSON cost of raw pipe bytes `buf`, decoding UTF-8 the way
  575. * `toString('utf8')` (WHATWG) would so a byte that renders as U+FFFD is charged
  576. * the three bytes that replacement character serializes to. A naive tally that
  577. * charged every byte 1 let a `b"\xff"` flood (every byte illegal → U+FFFD each)
  578. * grow the residual to a full budget's worth of raw bytes before flushing; near
  579. * a large `maxLogBytes` that retained ~256 MiB, then `flushStray`'s
  580. * `Buffer.concat` + `toString` expanded it to a ~1 GiB peak. Charging only the
  581. * structural width would leave the same gap for structurally-well-formed but
  582. * ILLEGAL sequences a flood produces just as cheaply — a CESU-8 surrogate
  583. * (`ED A0 80`) or an overlong (`E0 80 80`) decodes to THREE U+FFFD (cost 9), not
  584. * one width-3 character, so this validates each lead's first continuation range
  585. * (WHATWG: `E0`→A0-BF, `ED`→80-9F, `F0`→90-BF, `F4`→80-8F, others 80-BF) and
  586. * charges 3 per byte of any sequence that breaks. A control byte below 0x20
  587. * costs 6 (`\uXXXX`) or 2 (five short escapes); `"`/`\` cost 2; ASCII costs 1; a
  588. * fully valid multibyte sequence costs its byte width (2/3/4). `state` carries
  589. * the in-progress sequence across chunks; an unfinished tail at stream end is
  590. * decoded by the final `flushStray` and costed exactly there.
  591. * @param buf - raw bytes from a stdout/stderr pipe chunk.
  592. * @param state - the pipe's carried UTF-8 sequence state, mutated in place.
  593. * @returns the serialized cost accrued by the bytes that resolved in this call.
  594. */
  595. function accrueStrayCost(buf: Buffer, state: Utf8CostState): number {
  596. let cost = 0
  597. let index = 0
  598. while (index < buf.length) {
  599. const byte = buf[index] as number
  600. if (state.expected > 0) {
  601. // The valid range for THIS continuation: the lead-specific range applies
  602. // to the first continuation only, then reverts to the full 0x80–0xBF.
  603. const consumed = state.width - state.expected
  604. const lower = consumed === 1 ? state.lowerFirst : 0x80
  605. const upper = consumed === 1 ? state.upperFirst : 0xbf
  606. if (byte >= lower && byte <= upper) {
  607. state.expected -= 1
  608. if (state.expected === 0) {
  609. cost += state.width
  610. state.width = 0
  611. }
  612. index += 1
  613. continue
  614. }
  615. // The sequence broke. WHATWG's maximal-subpart rule folds the bytes
  616. // consumed so far into ONE U+FFFD (cost 3), then reprocesses this byte as
  617. // a fresh start (no index advance). Charging per consumed byte would
  618. // over-count, which is memory-safe but wrong; folding to one is exact.
  619. cost += 3
  620. state.expected = 0
  621. state.width = 0
  622. continue
  623. }
  624. if (byte < 0x20) {
  625. cost += byte === 0x08 || byte === 0x09 || byte === 0x0a || byte === 0x0c || byte === 0x0d ? 2 : 6
  626. } else if (byte === 0x22 || byte === 0x5c) {
  627. cost += 2
  628. } else if (byte < 0x80) {
  629. cost += 1
  630. } else if (byte >= 0xc2 && byte <= 0xdf) {
  631. state.expected = 1
  632. state.width = 2
  633. state.lowerFirst = 0x80
  634. state.upperFirst = 0xbf
  635. } else if (byte >= 0xe0 && byte <= 0xef) {
  636. state.expected = 2
  637. state.width = 3
  638. // Exclude the overlong (E0 80-9F) and CESU-8 surrogate (ED A0-BF) ranges.
  639. state.lowerFirst = byte === 0xe0 ? 0xa0 : 0x80
  640. state.upperFirst = byte === 0xed ? 0x9f : 0xbf
  641. } else if (byte >= 0xf0 && byte <= 0xf4) {
  642. state.expected = 3
  643. state.width = 4
  644. // Exclude the overlong (F0 80-8F) and out-of-range (F4 90-BF) leads.
  645. state.lowerFirst = byte === 0xf0 ? 0x90 : 0x80
  646. state.upperFirst = byte === 0xf4 ? 0x8f : 0xbf
  647. } else {
  648. // 0x80–0xc1 and 0xf5–0xff never begin a valid sequence: U+FFFD (3).
  649. cost += 3
  650. }
  651. index += 1
  652. }
  653. return cost
  654. }
  655. /**
  656. * Cap a done-frame `error.message` to `maxValueBytes` host-side: a forged done
  657. * frame can carry an arbitrarily long message, so truncate by RAW UTF-8 byte
  658. * length and append the shared marker on overflow. Completion VALUES are never
  659. * truncated — the seam forbids substitution, so an oversized value fails the run
  660. * as `output-limit` instead (see the done case in `execute`).
  661. *
  662. * This is the RECEIVE-side backstop, and it bills by raw bytes on purpose,
  663. * unlike the producing-side `_cap_message` in `py/bootstrap.py`, which bills by
  664. * SERIALIZED (JSON-escaped) cost. The split is deliberate: `_cap_message`'s
  665. * output has to cross fd 3 as a JSON string, so its escaped width is what the
  666. * frame ceiling bounds; this function's output goes straight into
  667. * `CodeRunResult.error.message` and never re-crosses a frame-bounded channel, so
  668. * the honest measure of what it retains is the raw length. An honest child has
  669. * already capped the diagnostic by serialized cost, and raw length ≤ serialized
  670. * cost, so a well-formed message passes through unchanged. A forged message with
  671. * control characters could serialize to roughly six times its raw length, but it
  672. * is not travelling any capped channel, so the raw-byte bound is the right one:
  673. * the value it protects is the model-visible size of `error.message`, not a wire
  674. * width.
  675. *
  676. * The marker's bytes are RESERVED from the budget, not added on top: the whole
  677. * returned string, marker included, is at most `maxValueBytes` bytes. Appending
  678. * the marker after retaining a full budget's worth of text would overrun the
  679. * very cap this function exists to enforce. The one exception is a configured
  680. * cap SMALLER than the marker itself, which leaves no room for message text at
  681. * all; the marker alone is returned there, so the bound is
  682. * `max(maxValueBytes, 15)`. Reporting the truncation is worth those 15 bytes,
  683. * and the default cap is 32 KiB.
  684. * @param message - the error message from an inbound (possibly forged) done frame.
  685. * @param maxValueBytes - the configured completion-value budget, reused here.
  686. * @returns the message unchanged, or its byte-capped form on overflow.
  687. */
  688. function capMessage(message: string, maxValueBytes: number): string {
  689. // Code-unit bounds BEFORE any encode, so a forged done frame carrying a
  690. // message anywhere below the 64 MiB fd-3 frame parse cap cannot force a
  691. // full-length UTF-8 copy under a 32 KiB cap. One UTF-16 code unit encodes to
  692. // at least one UTF-8 byte and at most three: three for a non-ASCII BMP
  693. // character, two apiece for the pair halves sharing an astral code point's
  694. // four bytes, and three for a LONE surrogate, which `Buffer.from` renders as
  695. // U+FFFD. So at most maxValueBytes/3 code units cannot overflow the cap and
  696. // need no encode at all...
  697. if (message.length * 3 <= maxValueBytes) return message
  698. // ...and nothing past the first maxValueBytes code units can fit inside it,
  699. // so only that prefix is ever encoded — at most 3 * maxValueBytes bytes.
  700. const keep = Math.min(message.length, maxValueBytes)
  701. const whole = keep === message.length
  702. const bytes = Buffer.from(whole ? message : message.slice(0, keep), 'utf8')
  703. // A message that fits is measured against the WHOLE cap: it gets no marker,
  704. // so reserving marker bytes here would truncate text that was within budget.
  705. if (whole && bytes.length <= maxValueBytes) return message
  706. // Past this point the message IS being truncated, so the marker WILL be
  707. // appended and its bytes come out of the cap instead of sitting on top of it.
  708. const budget = Math.max(0, maxValueBytes - TRUNCATION_MARKER_BYTES)
  709. // Trim back to the last complete UTF-8 sequence: a cut through a multibyte
  710. // character would decode as U+FFFD — corrupting the diagnostic AND
  711. // exceeding the byte cap, since the replacement character itself encodes
  712. // to three bytes. Continuation bytes are 0b10xxxxxx; at most three of them
  713. // precede a lead byte.
  714. //
  715. // This also covers a code-unit prefix ending on a HIGH SURROGATE whose low
  716. // half sits outside it, which `Buffer.from` encodes as U+FFFD: that orphan
  717. // occupies the last three bytes of `bytes`, and `bytes` is at least
  718. // `maxValueBytes + 2` long here (one byte per retained unit, three for the
  719. // orphan), so it starts past `budget` and is always cut. Reserving the
  720. // marker is what makes that hold; cutting at `maxValueBytes` itself did not,
  721. // and needed an explicit surrogate check.
  722. let end = Math.min(budget, bytes.length)
  723. while (end > 0 && ((bytes[end] as number) & 0b1100_0000) === 0b1000_0000) end--
  724. return `${bytes.subarray(0, end).toString('utf8')}${TRUNCATION_MARKER}`
  725. }
  726. /**
  727. * Copy an fd-3 line residual into a fresh, right-sized Buffer so it no longer
  728. * shares the joined-frame allocation it was sliced from.
  729. *
  730. * After the newline loop over a `Buffer.concat` of the pending chunks, the
  731. * leftover partial line is a `subarray` VIEW onto that concat's backing store.
  732. * A view keeps the ENTIRE backing allocation alive for as long as it is
  733. * retained, so carrying the view forward as the next pending chunk would pin a
  734. * whole large frame's worth of memory behind a tiny trailing fragment — and the
  735. * `pendingBytes` counter, set to the fragment's own length, would no longer
  736. * measure the memory actually held. `Buffer.from` allocates exactly
  737. * `residual.length` bytes and copies, letting the concat allocation be
  738. * collected; an empty residual carries nothing forward.
  739. * @param residual - the leftover slice after the last newline (a view).
  740. * @returns the pending-chunk list to carry forward: `[copy]`, or `[]` when empty.
  741. */
  742. export function detachResidual(residual: Buffer): Buffer[] {
  743. return residual.length > 0 ? [Buffer.from(residual)] : []
  744. }
  745. /** One namespace after seam validation: its callables plus the optional typed-rejection contract. */
  746. interface ValidatedNamespace {
  747. functions: Record<string, CodeBindingFunction>
  748. errorClass?: CodeBindingErrorClass
  749. }
  750. /**
  751. * One in-flight run's host-side state, tracked for disposal so teardown can
  752. * fail every live run as `abort` and AWAIT each child's exit.
  753. */
  754. interface LiveRun {
  755. kill(sig: NodeJS.Signals): void
  756. settle(failure: CodeRunFailure): void
  757. finished: Promise<void>
  758. }
  759. /**
  760. * The experimental {@link CodeRuntime} backend (private, not released) registering as `codeRuntime`. Every
  761. * cap is validated config; every long-running operation honors the request's
  762. * `AbortSignal`; every disposer awaits child-process exit.
  763. */
  764. export class PythonCodeRuntime extends CodeRuntime {
  765. static Config: z<Config> = z.object({
  766. cpuSeconds: z.number().default(60),
  767. maxWallMs: z.number().default(600_000),
  768. addressSpaceMb: z.number().default(512),
  769. maxLogBytes: z.number().default(65_536),
  770. maxValueBytes: z.number().default(32_768),
  771. graceMs: z.number().default(3_000),
  772. pythonBin: z.string().default('python3'),
  773. })
  774. readonly language = 'python'
  775. readonly isolation = 'process'
  776. private readonly config: ResolvedConfig
  777. private readonly pythonBin: string
  778. // The frame cap this instance enforces: the protocol cap, or the host's
  779. // heap-derived parse ceiling when a constrained heap makes the protocol cap
  780. // unsafe to parse (see {@link hostFrameParseCeiling}). Computed per
  781. // instance so the config gate and the inbound checks agree.
  782. private readonly frameParseCapBytes = hostFrameParseCeiling()
  783. private readonly live = new Set<LiveRun>()
  784. private disposed = false
  785. /* jscpd:ignore-start -- parallel to code-runtime-worker: sibling backends keep symmetric constructor/teardown/run shapes. */
  786. constructor(ctx: Context, config: Config) {
  787. super(ctx)
  788. // Reject at load on Windows: the bootstrap imports the POSIX-only `resource`
  789. // module for RLIMIT_CPU/RLIMIT_AS, spawns with a positional fd 3, and
  790. // terminates via negative-PID process-group signals — none of which exist
  791. // on Windows. Registering ctx.codeRuntime there would let assembly succeed
  792. // and defer the failure to the first run. The asymmetry with the worker
  793. // backend is intentional: that backend is cross-platform; this one is not.
  794. if (process.platform === 'win32') {
  795. throw new Error('dsh-code-runtime-python: this backend requires a Unix platform (POSIX rlimits, fd-3 stdio, process-group signals); it cannot run on Windows')
  796. }
  797. this.config = config as ResolvedConfig
  798. for (const [key, value] of Object.entries(this.config)) {
  799. if (typeof value === 'number' && !(Number.isFinite(value) && value > 0)) {
  800. throw new Error(`dsh-code-runtime-python: config.${key} must be a positive number, got ${String(value)}`)
  801. }
  802. }
  803. // cpuSeconds crosses to the child's setrlimit(RLIMIT_CPU) raw; a float
  804. // raises TypeError inside every child (a late per-run failure). Reject it
  805. // at load. maxLogBytes/maxValueBytes get their own integer gate below (the
  806. // child int()-truncates them, so a float would diverge from the host);
  807. // maxWallMs/graceMs/addressSpaceMb are consumed as numbers where a fraction
  808. // is harmless.
  809. if (!Number.isInteger(this.config.cpuSeconds)) {
  810. throw new Error(`dsh-code-runtime-python: config.cpuSeconds must be a positive integer, got ${String(this.config.cpuSeconds)}`)
  811. }
  812. // Finite is not the same as representable as an rlimit. `cpuSeconds` and its
  813. // `+ 1` hard limit both cross to `setrlimit` as integers, and `1e100` clears
  814. // `Number.isInteger` while being far past the safe range, so it cannot round
  815. // -trip: the child sees a different number than was configured. The `+ 1` is
  816. // what gets checked because that is the larger of the two values sent.
  817. if (!Number.isSafeInteger(this.config.cpuSeconds + 1)) {
  818. throw new Error(`dsh-code-runtime-python: config.cpuSeconds must be at most ${Number.MAX_SAFE_INTEGER - 1} (it and its +1 hard limit cross to setrlimit as exact integers), got ${String(this.config.cpuSeconds)}`)
  819. }
  820. // `addressSpaceMb` is multiplied by 1 MiB before it is framed, and a large
  821. // finite value overflows to `Infinity` there — which `encodeJsonPlain`
  822. // renders as `null`, so the child receives no limit at all and every run
  823. // ends in a bootstrap exception rather than a load-time configuration error.
  824. // Checking the DERIVED byte count is what catches it; the input itself looks
  825. // ordinary. Safe-integer, not merely finite, since the value must survive
  826. // the JSON round trip exactly.
  827. if (!Number.isSafeInteger(this.config.addressSpaceMb * 1024 * 1024)) {
  828. throw new Error(`dsh-code-runtime-python: config.addressSpaceMb must be at most ${Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024))} (its byte count crosses the wire as an exact integer), got ${String(this.config.addressSpaceMb)}`)
  829. }
  830. // `pythonBin` reaches `spawn` as the executable path, where values the
  831. // string schema admits fail late and unhelpfully. An empty string makes
  832. // `spawn` throw `ERR_INVALID_ARG_VALUE` synchronously, and an embedded NUL
  833. // throws `ERR_INVALID_ARG_TYPE` — both from inside `run()`, so the method
  834. // REJECTS instead of resolving the `worker-exit` the seam promises for a
  835. // child that cannot start. A basename with no `PATH` match would silently
  836. // fall to execvp's platform default `PATH` under the minimal spawn
  837. // environment (see the resolvePythonBin JSDoc), so it is rejected here
  838. // too. All three are self-contained configuration errors that fail at
  839. // load.
  840. if (this.config.pythonBin === '' || this.config.pythonBin.includes('\0')) {
  841. throw new Error(`dsh-code-runtime-python: config.pythonBin must be a non-empty path without NUL bytes, got ${JSON.stringify(this.config.pythonBin)}`)
  842. }
  843. // `maxWallMs` and `graceMs` are armed with setTimeout, which clamps any
  844. // delay past MAX_TIMER_DELAY_MS to 1 ms without a word — turning a
  845. // generous ceiling into an instant timeout and a generous grace period into
  846. // an instant SIGKILL. `graceMs` is checked against the margin the
  847. // close-deadline adds on top, since that sum is what gets armed.
  848. if (this.config.maxWallMs > MAX_TIMER_DELAY_MS) {
  849. throw new Error(`dsh-code-runtime-python: config.maxWallMs must not exceed ${MAX_TIMER_DELAY_MS} (setTimeout clamps a larger delay to 1ms), got ${String(this.config.maxWallMs)}`)
  850. }
  851. if (this.config.graceMs + CLOSE_REAP_MARGIN_MS > MAX_TIMER_DELAY_MS) {
  852. throw new Error(`dsh-code-runtime-python: config.graceMs must not exceed ${MAX_TIMER_DELAY_MS - CLOSE_REAP_MARGIN_MS} (its close deadline adds ${CLOSE_REAP_MARGIN_MS}ms, and setTimeout clamps a larger delay to 1ms), got ${String(this.config.graceMs)}`)
  853. }
  854. // The output caps are budgets for a payload that has to cross fd 3 inside
  855. // one frame, and the framing ceiling is fixed. A cap above what a frame can
  856. // carry is unsatisfiable: a completion or log entry that the cap admits
  857. // arrives as an over-ceiling frame and fails the run as `worker-exit`
  858. // instead of the `output-limit` the cap describes — a silent inversion, so
  859. // it fails at load. Both budgets are metered in SERIALIZED (JSON-escaped)
  860. // bytes — the host log ledger charges the serialized cost via
  861. // `jsonStringCostUpTo`, which walks to the cap without allocating the escaped
  862. // copy, `checkDoneValue` measures the escaped form, and the producing-side
  863. // `_cap_message` in the child also caps by serialized cost (which is why a
  864. // capped diagnostic still fits its frame) — so a payload admitted under the
  865. // cap occupies at most `cap + envelope` bytes on the wire; escaping is
  866. // already inside the charge and must not be multiplied in again. The
  867. // receive-side `capMessage` backstop is the one exception to this argument:
  868. // it bills a forged `done.error.message` by RAW bytes, but that output goes
  869. // into `CodeRunResult.error.message` and never re-crosses a frame-bounded
  870. // channel, so it is not part of the wire-width bound (see its JSDoc). The
  871. // admissible cap is therefore `parse-cap - envelope`: the receive path
  872. // rejects raw frames past the effective parse cap (`frameParseCapBytes` —
  873. // the protocol cap, or the host's heap-derived ceiling when a constrained
  874. // heap makes the protocol cap unsafe to parse; see hostFrameParseCeiling)
  875. // before decoding (the run settles as a worker-exit; a hostile
  876. // compact-wide-frame OOM guard), so a budget must not exceed what an
  877. // honest child's frame can actually carry through that parser.
  878. for (const key of ['maxLogBytes', 'maxValueBytes'] as const) {
  879. // Require an integer: the child reads these budgets through `int(...)`,
  880. // which silently floors a float, so `maxLogBytes: 3.5` would truncate at 3
  881. // bytes child-side while the host meters and marks at 3.5 — the two sides
  882. // enforcing different public config. Reject the float at load, as the
  883. // worker backend does for its byte budgets.
  884. if (!Number.isInteger(this.config[key])) {
  885. throw new Error(`dsh-code-runtime-python: config.${key} must be a positive integer (the child reads it as an int, so a float diverges from the host), got ${String(this.config[key])}`)
  886. }
  887. const limit = this.frameParseCapBytes - FRAME_ENVELOPE_BYTES
  888. if (this.config[key] > limit) {
  889. // Only a host whose heap is below the protocol cap reaches the
  890. // heap-constrained note; the constrained-heap rejection is exercised
  891. // by the subprocess load test, but subprocess runs are not
  892. // coverage-instrumented, so the note's arm is not schedulable from the
  893. // instrumented suite (whose heap never binds).
  894. /* v8 ignore next -- the heap-constrained message arm needs a host heap below the protocol cap. */
  895. const heapNote = this.frameParseCapBytes < FRAME_PARSE_CAP_BYTES ? ` — this host's heap limits the parse to ${this.frameParseCapBytes} bytes, so the protocol cap of ${FRAME_PARSE_CAP_BYTES} would be unsafe` : ''
  896. throw new Error(`dsh-code-runtime-python: config.${key} must not exceed ${limit} (a payload that large cannot cross the fd-3 frame PARSER, which rejects raw frames past ${this.frameParseCapBytes} bytes before decoding to bound host memory${heapNote} — a larger budget would admit a config whose honest child frames the host then rejects as a worker-exit), got ${String(this.config[key])}`)
  897. }
  898. // Reject a log budget too small to honor: the truncation marker alone
  899. // must serialize within the budget, or a marker-only truncated run
  900. // returns more than the configured cap. (With admitted entries the
  901. // marker is envelope, so the serialized logs run to
  902. // `maxLogBytes + marker + envelope`.)
  903. if (key === 'maxLogBytes' && this.config[key] < MIN_LOG_BYTES) {
  904. throw new Error(`dsh-code-runtime-python: config.maxLogBytes must be at least ${MIN_LOG_BYTES} (a smaller budget cannot serialize the truncation marker itself, so a marker-only truncated run would return more than the configured cap), got ${String(this.config[key])}`)
  905. }
  906. }
  907. // The child builds, charges, and frames a `maxLogBytes` log entry or a
  908. // `maxValueBytes` completion value under `RLIMIT_AS`, and both paths trigger
  909. // on CHARACTER count against a serialized-BYTE budget. An astral character is
  910. // one character but four bytes of `str` storage and four UTF-8 bytes, so a
  911. // budget's worth of them peaks at three simultaneous ~4x copies (the caller's
  912. // write argument, the line slice or joined pending handed to push, and the
  913. // encode push takes to charge and ship it). A budget approaching
  914. // `addressSpaceMb` therefore makes a LEGITIMATE near-budget output breach the
  915. // address space and die as `worker-exit` instead of truncating (log) or
  916. // failing as `output-limit` (value). Metering every child write against the
  917. // address space at runtime is the wrong fix — an exact serialized-cost check
  918. // is either a full encode (the allocation being avoided) or a per-character
  919. // Python loop that burns the CPU budget — so the incompatible pair is rejected
  920. // at load: each budget times the worst-case multiple must fit the address
  921. // space. Checked on every platform, not just where `RLIMIT_AS` is enforced:
  922. // the incompatibility is a property of the config values, and the child OOMs
  923. // on a Linux deployment regardless of the host that assembled the config, so a
  924. // uniform load-time rejection is the fail-loud contract (Darwin skips only the
  925. // runtime `setrlimit`).
  926. const addressSpaceBytes = this.config.addressSpaceMb * 1024 * 1024
  927. // Room left for the peak output allocation after the interpreter's own fixed
  928. // footprint. A budget must fit MULTIPLE times over into THIS, not the whole
  929. // address space, so a budget sized right at `addressSpaceMb / MULTIPLE` — which
  930. // the multiple alone would admit — cannot leave the peak plus the interpreter
  931. // over the limit.
  932. const budgetableBytes = addressSpaceBytes - INTERPRETER_BASELINE_BYTES
  933. // The largest budget that fits: the peak (budget * MULTIPLE) must leave room,
  934. // so a budget whose peak exactly equals `budgetableBytes` is rejected — that
  935. // peak plus the reserved baseline is the whole address space, the RLIMIT_AS
  936. // edge. `ceil(budgetableBytes / MULTIPLE) - 1` is the last integer strictly
  937. // under `budgetableBytes / MULTIPLE`.
  938. // Reject a too-small address space on its own terms FIRST. Once
  939. // `budgetableBytes` is zero or negative no budget can pass, and the loop
  940. // below would report "a limit of -1" (or -2796203 at addressSpaceMb 32) while
  941. // naming `maxLogBytes` -- pointing the operator at the knob that is not the
  942. // problem. The baseline is what `addressSpaceMb` must clear here.
  943. if (budgetableBytes <= 0) {
  944. throw new Error(`dsh-code-runtime-python: config.addressSpaceMb must exceed the ${INTERPRETER_BASELINE_BYTES}-byte interpreter baseline with room for the output budgets, so the child has address space left to build and encode them; got ${String(this.config.addressSpaceMb)} MiB (${addressSpaceBytes} bytes)`)
  945. }
  946. const admissibleBudget = Math.ceil(budgetableBytes / OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE) - 1
  947. for (const key of ['maxLogBytes', 'maxValueBytes'] as const) {
  948. if (this.config[key] * OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE >= budgetableBytes) {
  949. throw new Error(`dsh-code-runtime-python: config.${key} times the ${OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE}x worst-case Unicode expansion must fit within the ${budgetableBytes} bytes left after the ${INTERPRETER_BASELINE_BYTES}-byte interpreter baseline within the ${addressSpaceBytes}-byte addressSpaceMb, so a near-budget output truncates rather than breaching RLIMIT_AS as worker-exit; got ${String(this.config[key])} against a limit of ${admissibleBudget}`)
  950. }
  951. }
  952. // Resolve and validate the executable ONCE, after the pure config checks.
  953. // Re-resolving a basename in each run would let a later PATH change silently
  954. // switch interpreters, while an unchecked explicit path would turn
  955. // self-contained misconfiguration into a late worker-exit. A missing or
  956. // unsupported interpreter is a load failure. Later filesystem mutation is
  957. // outside config validation; a missing executable settles as worker-exit.
  958. const pythonBin = resolvePythonBin(this.config.pythonBin)
  959. if (pythonBin === undefined) {
  960. const explicit = isAbsolute(this.config.pythonBin) || this.config.pythonBin.includes('/')
  961. throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(this.config.pythonBin)} ${explicit ? 'is not an executable regular file' : 'does not resolve on PATH'}`)
  962. }
  963. validatePythonBin(pythonBin)
  964. this.pythonBin = pythonBin
  965. ctx.effect(() => () => this.teardown(), 'python code-runtime teardown')
  966. }
  967. /**
  968. * Dispose to quiescence: fail every in-flight run as aborted and AWAIT each
  969. * child's exit so no subprocess that stays in the child's process group
  970. * outlives the fiber. A descendant that escaped the group with `setsid()` /
  971. * `start_new_session=True` is unreachable by `kill(-pid)` and is the documented
  972. * exception (see the package README's Known Limitations); the process-group
  973. * teardown reaps everything that stays in the group.
  974. */
  975. private async teardown(): Promise<void> {
  976. this.disposed = true
  977. const runs = [...this.live]
  978. for (const run of runs) run.settle({ kind: 'abort', message: 'runtime disposed' })
  979. // Awaiting `finished` is also what clears staging: that promise resolves
  980. // inside the run's own `settle`, which removes its directory first. So there
  981. // is deliberately no sweep here — a second pass could only ever find an
  982. // empty set, and an unreachable cleanup path is worse than none, since it
  983. // reads as the real guarantee while never running.
  984. await Promise.all(runs.map(run => run.finished))
  985. }
  986. /**
  987. * Execute one program in a fresh Python subprocess. Success resolves with
  988. * `result.value` (and no `result.error`); failure — parse failure, thrown
  989. * exception, invalid completion, output overflow, budget expiry, abort, or
  990. * substrate death — resolves with `result.error` set (classified by
  991. * `CodeRunFailure.kind`). The method rejects only for seam misuse.
  992. */
  993. async run(request: CodeRunRequest): Promise<CodeRunResult> {
  994. if (this.disposed) throw new Error('dsh-code-runtime-python: run() after disposal')
  995. const bindings = this.validateBindings(request)
  996. if (request.signal?.aborted) {
  997. return { logs: [], error: { kind: 'abort', message: messageOf(request.signal.reason) } }
  998. }
  999. let bootstrapPath: string
  1000. try {
  1001. // The interpreter is an external process, so the entry script has to sit
  1002. // on the real filesystem; see materializePyScripts. One copy PER RUN,
  1003. // synchronously, so no async boundary opens before `execute` registers the
  1004. // run and installs the abort listener.
  1005. bootstrapPath = materializePyScripts()
  1006. } catch (error: unknown) {
  1007. // A full or read-only temp filesystem, or a packaged asset the deployment
  1008. // failed to ship, is a SUBSTRATE failure — the same class as a child that
  1009. // cannot start. The seam permits rejection only for misuse, so this
  1010. // resolves as `worker-exit` rather than throwing out of `run()`.
  1011. return { logs: [], error: { kind: 'worker-exit', message: `failed to stage the python bootstrap: ${messageOf(error)}` } }
  1012. }
  1013. return await this.execute(request, bindings, bootstrapPath)
  1014. }
  1015. /* jscpd:ignore-end */
  1016. /**
  1017. * Reject (seam misuse) malformed binding namespaces: non-identifier or
  1018. * reserved globals/error classes, duplicates, and colliding or
  1019. * runtime-owned injected globals.
  1020. */
  1021. private validateBindings(request: CodeRunRequest): Map<string, ValidatedNamespace> {
  1022. const bindings = new Map<string, ValidatedNamespace>()
  1023. // Every name the bootstrap injects into the program's one global namespace:
  1024. // namespace globals plus error-class names. They must be a collision-free
  1025. // set that avoids the runtime's own slots, or a later injection silently
  1026. // overwrites an earlier one (or the completion/builtins slot) and the run
  1027. // fails obscurely at execution time.
  1028. const injectedGlobals = new Set<string>()
  1029. const claimGlobal = (name: string, role: string): void => {
  1030. if (RUNTIME_OWNED_GLOBALS.has(name)) {
  1031. throw new Error(`dsh-code-runtime-python: ${role} ${JSON.stringify(name)} collides with a runtime-owned global`)
  1032. }
  1033. if (injectedGlobals.has(name)) {
  1034. throw new Error(`dsh-code-runtime-python: ${role} ${JSON.stringify(name)} collides with another injected global`)
  1035. }
  1036. injectedGlobals.add(name)
  1037. }
  1038. for (const namespace of request.bindings) {
  1039. // Snapshot the caller-supplied fields into plain values ONCE. The
  1040. // namespace and errorClass objects may expose `global`/`name`/
  1041. // `memberNameProperty` through getters: validation reads each several
  1042. // times, and the ORIGINAL errorClass object would otherwise be retained
  1043. // for the boot frame, whose JSON.stringify re-reads it after validation.
  1044. // A getter that changes or throws on a later read would turn the
  1045. // seam-misuse rejection into a worker-exit (or inject a different name
  1046. // than validation approved); reading each field once here and keeping
  1047. // the plain copy makes validation and the boot frame agree.
  1048. const global = namespace.global
  1049. if (!IDENTIFIER.test(global) || RESERVED_NAMES.has(global)) {
  1050. throw new Error(`dsh-code-runtime-python: binding global ${JSON.stringify(global)} is not a usable Python identifier`)
  1051. }
  1052. if (bindings.has(global)) {
  1053. throw new Error(`dsh-code-runtime-python: duplicate binding global ${JSON.stringify(global)}`)
  1054. }
  1055. claimGlobal(global, 'binding global')
  1056. // The error class becomes a program global and its member property an
  1057. // attribute name, so both face the Python identifier rules; the member
  1058. // additionally must be assignable on a BaseException instance.
  1059. const errorClass = namespace.errorClass
  1060. let validatedErrorClass: CodeBindingErrorClass | undefined
  1061. if (errorClass) {
  1062. const name = errorClass.name
  1063. const memberNameProperty = errorClass.memberNameProperty
  1064. if (!IDENTIFIER.test(name) || RESERVED_NAMES.has(name)) {
  1065. throw new Error(`dsh-code-runtime-python: errorClass.name ${JSON.stringify(name)} is not a usable Python identifier`)
  1066. }
  1067. // Any non-empty own attribute name is settable via setattr (the
  1068. // program reads exotic names like `tool-name` with getattr), matching
  1069. // the seam contract and the worker backend — only the seam-excluded
  1070. // and protocol-reserved members below are refused.
  1071. if (memberNameProperty.length === 0) {
  1072. throw new Error('dsh-code-runtime-python: errorClass.memberNameProperty must be a non-empty attribute name')
  1073. }
  1074. if (EXCEPTION_RESERVED_MEMBERS.has(memberNameProperty) || DUNDER.test(memberNameProperty)) {
  1075. throw new Error(`dsh-code-runtime-python: errorClass.memberNameProperty ${JSON.stringify(memberNameProperty)} is a reserved error member and cannot be assigned`)
  1076. }
  1077. claimGlobal(name, 'errorClass.name')
  1078. validatedErrorClass = { name, memberNameProperty }
  1079. }
  1080. // Snapshot the callables into a plain own-property record before the
  1081. // child can dispatch. `namespace.functions` is caller-supplied, so it may
  1082. // expose members through getters or a Proxy; reading one of them inside
  1083. // the fd-3 `data` callback would throw OUTSIDE the dispatcher's try and
  1084. // terminate the host (defensive-patterns contain-callback-exceptions).
  1085. // Reading every member here, in run()'s synchronous validation segment,
  1086. // turns that throw into the seam-misuse rejection run() reserves for
  1087. // malformed bindings. The snapshot is also the single key set the boot
  1088. // frame advertises AND dispatch reads, so a getter whose keys differ
  1089. // between reads cannot desynchronize the child's allowed names from what
  1090. // the host will actually call. The record is null-prototype: the seam
  1091. // contract treats member names like `__proto__` or `constructor` as
  1092. // ordinary own properties, and a plain `{}` assignment of `__proto__`
  1093. // would hit the prototype setter instead of creating the own property.
  1094. const functions = Object.create(null) as Record<string, CodeBindingFunction>
  1095. for (const name of Object.keys(namespace.functions)) {
  1096. // Only callables enter the snapshot: a getter exposing a non-function
  1097. // member would otherwise assign a value the dispatcher's `typeof fn
  1098. // !== 'function'` check rejects anyway, and keeping it out of the
  1099. // snapshot keeps the boot frame's name list and the dispatch key set
  1100. // one and the same.
  1101. const fn = namespace.functions[name]
  1102. if (typeof fn === 'function') functions[name] = fn
  1103. }
  1104. bindings.set(global, { functions, ...validatedErrorClass ? { errorClass: validatedErrorClass } : {} })
  1105. }
  1106. return bindings
  1107. }
  1108. /** Spawn the child for one validated run and drive it to settlement. */
  1109. private execute(
  1110. request: CodeRunRequest,
  1111. bindings: Map<string, ValidatedNamespace>,
  1112. bootstrapPath: string,
  1113. ): Promise<CodeRunResult> {
  1114. // This run's own staging directory, removed at settlement.
  1115. const bootstrapDir = dirname(bootstrapPath)
  1116. // Explicit pipe count of 4 puts the framed-JSON channel at fd 3 in the child.
  1117. // The constructor resolved and validated the interpreter once; runs keep that
  1118. // exact path even if the host later changes PATH.
  1119. // `spawn` can throw SYNCHRONOUSLY — a descriptor-exhausted host (EMFILE) or a
  1120. // libuv-level failure surfaces here, before the Promise executor and its
  1121. // settlement path exist. Left uncaught it would REJECT run() (the seam
  1122. // permits rejection only for misuse) and strand this run's staging directory,
  1123. // which only settle() removes. Catch it, unlink the directory, and resolve a
  1124. // `worker-exit` — the same class as the async ENOENT `error` event below.
  1125. let child: ChildProcessWithoutNullStreams
  1126. let proto: Duplex | null
  1127. try {
  1128. // `-u` keeps the interpreter's own stdout/stderr UNBUFFERED: a program
  1129. // that writes through `sys.__stdout__`/`sys.__stderr__` (or C-stdio
  1130. // layered on the same fds) must have those bytes visible to the host's
  1131. // stray capture immediately — a block-buffered wrapper would otherwise
  1132. // hold them until an explicit flush, and the host SIGTERMs the child
  1133. // right after the done frame, before any finalization-time flush could
  1134. // run. The `_LogStream` replacement of `sys.stdout`/`sys.stderr` is
  1135. // unaffected (it is a Python object, not the C-level stdio buffer).
  1136. child = spawn(this.pythonBin, ['-u', '-I', bootstrapPath], {
  1137. // Preserve only the platform temp directory. macOS system Python emits a
  1138. // startup warning when TMPDIR is absent; ambient credentials, PATH, HOME,
  1139. // and other host state remain unavailable to model code.
  1140. env: pythonEnvironment(),
  1141. detached: true, // Own process group — kill(-pid, sig) reaches subprocesses the model program spawns.
  1142. stdio: ['pipe', 'pipe', 'pipe', 'pipe'],
  1143. })
  1144. // Fd 3 is a duplex pipe carrying protocol frames. Node types extra stdio
  1145. // entries as `Stream | null`; the runtime shape with `'pipe'` is a duplex,
  1146. // so we narrow at the boundary rather than smearing casts below. Stdout
  1147. // and stderr are guaranteed non-null under `'pipe'` and typed as such.
  1148. proto = child.stdio[3] as Duplex | null
  1149. /* v8 ignore next 3 -- `'pipe'` stdio always populates fd 3; guarding Node's `Stream | null` typing widening. */
  1150. if (proto === null) {
  1151. throw new Error('dsh-code-runtime-python: python subprocess spawned without a fd-3 pipe')
  1152. }
  1153. // Close the host's stdin write handle immediately: the program is an
  1154. // async body that reads nothing from fd 0, and a live pipe here would
  1155. // hold a host-side handle open past the run — a setsid-escaped descendant
  1156. // inheriting fd 0 would keep the host process from exiting even after the
  1157. // closeDeadline forced settlement. The child (and any descendant) reads
  1158. // EOF on fd 0 instead, and no host handle survives.
  1159. // oxlint-disable-next-line typescript/no-unnecessary-condition -- the boot-write-failure fake child has no stdin.
  1160. child.stdin?.destroy()
  1161. } catch (error: unknown) {
  1162. try {
  1163. rmSync(bootstrapDir, { recursive: true, force: true })
  1164. } catch {
  1165. // Same swallow as settle()'s removal: `force` already absorbs a missing
  1166. // directory, so only a filesystem-level refusal reaches here, and the
  1167. // staging copy holds nothing but two checked-in scripts.
  1168. }
  1169. return Promise.resolve({ logs: [], error: { kind: 'worker-exit' as const, message: `python spawn error: ${messageOf(error)}` } })
  1170. }
  1171. return new Promise<CodeRunResult>((resolve) => {
  1172. let settled = false
  1173. const logs: string[] = []
  1174. // An unterminated line flushed with the `open` flag: the next log frame
  1175. // appends to it (no fake newline between entries), and finish() pushes
  1176. // the residual if the run ends with it still open. Held as a fragment
  1177. // ARRAY, so k tiny open frames cost O(k) — re-joining and re-walking the
  1178. // whole held text per frame would be O(k * budget).
  1179. let openParts: string[] = []
  1180. // Past MAX_PENDING_CHUNKS, the held fragments are coalesced into sealed
  1181. // blocks (mirroring the fd-3 reader's `blocks` and the stray capture's
  1182. // seal): each fragment is a distinct array slot plus string object
  1183. // header — ~30x overhead the byte cap cannot see — so a budget-sized
  1184. // single-character open flood would otherwise accumulate thousands of
  1185. // slots. Sealing bounds the live fragment count exactly like the
  1186. // sibling paths; the merge reads sealed + current fragments. A block
  1187. // ARRAY (not one repeated string concat) matches the sibling shape and
  1188. // avoids depending on V8 ConsString amortization.
  1189. let openSealed: string[] = []
  1190. // Every truncation arm funnels here: the committed open prefix was
  1191. // ALREADY billed, so it is pushed BEFORE the marker — a flushed line is
  1192. // never lost (only the marker stays last), and no ledger re-charge
  1193. // happens. openParts is emptied here, so no later arm or finish() sees
  1194. // it.
  1195. const truncateLogs = (): void => {
  1196. logsTruncated = true
  1197. if (openSealed.length > 0 || openParts.length > 0) {
  1198. logs.push(openSealed.join('') + openParts.join(''))
  1199. openSealed = []
  1200. openParts = []
  1201. }
  1202. logs.push(logTruncationMarker(this.config.maxLogBytes))
  1203. clearStray(strayOut)
  1204. clearStray(strayErr)
  1205. }
  1206. // One host-side ledger covers normal frames, forged frames, and stray stdout bytes.
  1207. // The ledger starts one byte below maxLogBytes: each entry is charged its
  1208. // JSON-string cost plus one separator byte, and the serialized outer logs
  1209. // array adds one more byte of envelope (two brackets and n-1 commas over n
  1210. // entries' separators), so a result that exactly exhausts the ledger
  1211. // serializes to exactly maxLogBytes; WITHOUT the reserved byte it would
  1212. // serialize to maxLogBytes + 1. Reserving that byte keeps an admitted
  1213. // result within the configured cap; the truncation-marker entry is
  1214. // envelope, not payload, and rides uncharged.
  1215. let logBudget = this.config.maxLogBytes - 1
  1216. let logsTruncated = false
  1217. // Drop a pipe's buffered stray output wholesale: once the ledger has
  1218. // truncated, every byte of it would be no-op'd by admit(), so retaining
  1219. // it (and later Buffer.concat+decoding it in flushStray) would spend host
  1220. // memory on output that can never be admitted. Called from every arm that
  1221. // marks the ledger truncated — admit()'s two ceilings and the child-marker
  1222. // frame arm — so the end-path flushStray sees empty buffers and exits.
  1223. const clearStray = (stray: StrayBuffer): void => {
  1224. stray.chunks = []
  1225. stray.blocks = []
  1226. stray.cost = 0
  1227. stray.utf8 = { expected: 0, width: 0, lowerFirst: 0, upperFirst: 0 }
  1228. }
  1229. const admit = (text: string): void => {
  1230. // Post-truncation admits are no-ops: once the ledger has truncated, the
  1231. // marker is the last entry. Reachable within one `data` callback — a
  1232. // chunk carrying two newline-terminated lines where the first exhausts
  1233. // the budget hits this on the second — so it is a measured branch.
  1234. if (logsTruncated) return
  1235. // Each entry is charged its SERIALIZED cost — JSON.stringify's quotes
  1236. // and escapes plus one separator byte — because the seam bounds the
  1237. // serialized outer logs payload, and control characters expand
  1238. // several-fold under JSON escaping (a "\x00" flood would otherwise
  1239. // admit 6x its charge). The charge also puts a floor under an empty
  1240. // entry (its two quotes plus separator), so a `while True: print()`
  1241. // flood of zero-byte lines exhausts the ledger instead of growing the
  1242. // retained array without ever touching the budget. The one fixed
  1243. // truncation-marker entry is envelope, not payload, and rides
  1244. // uncharged.
  1245. //
  1246. // Cheap lower bound FIRST, before the escaped copy exists: every
  1247. // UTF-16 code unit costs at least one serialized byte (an ASCII
  1248. // character is one byte; a control character is six as `\uXXXX`; a
  1249. // non-ASCII BMP character is two or three; each half of a surrogate
  1250. // pair contributes two of the four bytes its code point encodes to),
  1251. // and the JSON form adds two quotes on top of the separator byte. So
  1252. // `text.length + 3` never exceeds the true cost, and a forged `log`
  1253. // frame carrying a control-heavy string anywhere below the 64 MiB
  1254. // frame parse cap truncates here instead of allocating a
  1255. // hundreds-of-megabytes escaped copy under a small maxLogBytes.
  1256. if (text.length + 3 > logBudget) {
  1257. // Release the buffered stray pipes: their bytes can never be
  1258. // admitted now (see clearStray).
  1259. truncateLogs()
  1260. return
  1261. }
  1262. // Past the lower bound, measure the exact serialized cost without
  1263. // allocating the escaped copy: `jsonStringCostUpTo` walks to the cap and
  1264. // stops, so even a near-budget control-char-dense line never materializes
  1265. // a sixfold-inflated `JSON.stringify` result. `+ 1` for the separator.
  1266. const measured = jsonStringCostUpTo(text, logBudget - 1)
  1267. if (measured === undefined) {
  1268. truncateLogs()
  1269. return
  1270. }
  1271. logBudget -= measured + 1
  1272. logs.push(text)
  1273. }
  1274. // Stray-byte capture: anything the child writes to its stdout/stderr
  1275. // (native prints, C-extension writes) still counts against the ledger.
  1276. //
  1277. // Output is admitted per LINE, not per transport chunk. `logs` entries
  1278. // are joined with `\n` downstream (PTC mode), so each entry must be one
  1279. // line: pushing a raw `data` chunk would turn every arbitrary pipe-read
  1280. // boundary into a model-visible newline, so a single 200 KiB native write
  1281. // split across pipe reads would read back with spurious line breaks. The
  1282. // child's own `log` frames are already line-granular; stray capture
  1283. // matches them by splitting on `\n`.
  1284. //
  1285. // Buffered as raw `Buffer` chunks with a running SERIALIZED-cost counter,
  1286. // exactly like the fd-3 reader below and for the same reasons: a string
  1287. // `+=` accumulator re-copies the whole residual on every pipe chunk
  1288. // (quadratic on a large newline-free write), and scanning it from index 0
  1289. // each chunk is a second quadratic. Appending a chunk is O(1); the split
  1290. // happens only when a `\n` actually arrived. A newline never appears inside
  1291. // a UTF-8 multibyte sequence (continuation bytes are 0x80–0xBF), so
  1292. // splitting on the raw 0x0a byte and decoding each complete line is safe
  1293. // without a streaming decoder — a line's bytes are whole by construction.
  1294. //
  1295. // `chunks` also seals into `blocks` past MAX_PENDING_CHUNKS, mirroring the
  1296. // fd-3 reader: without it a program pacing one-byte newline-free
  1297. // `os.write`s accumulates one Buffer object per write, and the object plus
  1298. // backing-store overhead — which no byte or cost count sees — exhausts the
  1299. // host heap far below the budget. Sealing bounds the live object count.
  1300. interface StrayBuffer { chunks: Buffer[]; blocks: Buffer[]; cost: number; utf8: Utf8CostState }
  1301. const strayOut: StrayBuffer = { chunks: [], blocks: [], cost: 0, utf8: { expected: 0, width: 0, lowerFirst: 0, upperFirst: 0 } }
  1302. const strayErr: StrayBuffer = { chunks: [], blocks: [], cost: 0, utf8: { expected: 0, width: 0, lowerFirst: 0, upperFirst: 0 } }
  1303. const captureStray = (stray: StrayBuffer, chunk: Buffer): void => {
  1304. // Once the ledger has truncated, stop buffering: admit() is a no-op past
  1305. // that point, so continuing to accumulate would retain host memory for
  1306. // output that can never be admitted.
  1307. if (logsTruncated) return
  1308. stray.chunks.push(chunk)
  1309. // Track SERIALIZED cost, not raw bytes: a control-char-dense residual
  1310. // (a NUL or illegal-UTF-8 flood) serializes several-fold, so a raw-byte
  1311. // threshold would let it grow to the full budget's worth of RAW bytes
  1312. // before flushing. `accrueStrayCost` decodes UTF-8 structurally across
  1313. // chunks (via `stray.utf8`) so a byte that renders as U+FFFD is charged
  1314. // its three serialized bytes, not one.
  1315. stray.cost += accrueStrayCost(chunk, stray.utf8)
  1316. // Bound the live fragment count (see the seal rationale above), before
  1317. // any concat so an over-count payload is never copied whole first.
  1318. if (stray.chunks.length >= MAX_PENDING_CHUNKS) {
  1319. stray.blocks.push(Buffer.concat(stray.chunks))
  1320. stray.chunks = []
  1321. }
  1322. if (chunk.includes(0x0a)) {
  1323. let buffered = Buffer.concat(stray.blocks.length > 0 ? [...stray.blocks, ...stray.chunks] : stray.chunks)
  1324. stray.blocks = []
  1325. let newline: number
  1326. while ((newline = buffered.indexOf(0x0a)) >= 0) {
  1327. admit(buffered.subarray(0, newline).toString('utf8'))
  1328. buffered = buffered.subarray(newline + 1)
  1329. }
  1330. // Carry the residual as a fresh right-sized copy, not the subarray view
  1331. // (which would pin the whole concat allocation). See detachResidual.
  1332. // The residual begins at a character boundary (a newline is never
  1333. // inside a multibyte sequence), so its cost and UTF-8 state recompute
  1334. // cleanly from a fresh walk.
  1335. // A line admitted inside the loop may have exhausted the ledger and
  1336. // cleared this pipe (see clearStray); the re-retain below must not
  1337. // resurrect the doomed residual.
  1338. // oxlint-disable-next-line typescript/no-unnecessary-condition -- admit() (a closure) sets it.
  1339. if (logsTruncated) return
  1340. stray.chunks = detachResidual(buffered)
  1341. stray.utf8 = { expected: 0, width: 0, lowerFirst: 0, upperFirst: 0 }
  1342. stray.cost = accrueStrayCost(buffered, stray.utf8)
  1343. }
  1344. // Newline-free residual is bounded by the ledger, not left to grow with
  1345. // the stream: an `os.write(1, b"A"*N)` flood carrying no newline would
  1346. // otherwise accumulate N bytes in host memory before `end`. The bound is
  1347. // on the COMBINED pending cost of both pipes, not each alone: stdout and
  1348. // stderr share one `logBudget`, so checking each against the full budget
  1349. // independently would let both retain nearly a budget's worth at once —
  1350. // ~2x peak, up to ~512 MiB near the ceiling — before either flushed.
  1351. // When the sum would cross the budget, flush both now. admit() charges
  1352. // the exact serialized cost, truncates, and marks the ledger, and the
  1353. // truncation short-circuit above stops buffering on the next chunk.
  1354. // `+ 3` covers the two quotes and one separator admit adds. The two
  1355. // pipes are independent OS streams whose `data` events already interleave
  1356. // nondeterministically with each other and with the child's own fd-3
  1357. // `log` frames, so `logs` carries no cross-pipe ordering guarantee to
  1358. // preserve here; a fixed drain order is as valid as any.
  1359. // Flushing is NOT a stream end: a multibyte UTF-8 character can be split
  1360. // across pipe `data` chunks, so the residual may end mid-sequence. A
  1361. // budget-triggered flush must decode only the complete prefix and carry
  1362. // the incomplete tail forward (≤3 bytes) on the same pipe's residual —
  1363. // decoding it here would render a legal character as U+FFFD in a released
  1364. // entry (see `flushStray`). This is unlike the `end`/closeDeadline paths
  1365. // below, where a trailing incomplete sequence is genuinely truncated input
  1366. // and U+FFFD is honest.
  1367. if (strayOut.cost + strayErr.cost + 3 > logBudget) {
  1368. flushStray(strayOut, true)
  1369. flushStray(strayErr, true)
  1370. }
  1371. }
  1372. // Flush a pipe's residual into `logs`. Called on the combined-budget
  1373. // threshold above, on the pipe's `end` (normal drain), and — for the
  1374. // setsid-escapee path where destroy() forces settlement without an `end` —
  1375. // explicitly in the closeDeadline handler. Idempotent: it clears what it
  1376. // admits, so a later flush is a no-op, and it returns early on an empty
  1377. // buffer so flushing the sibling that had nothing pending is a no-op. The
  1378. // `chunks`/`blocks` guard is the only emptiness check needed — `data` never
  1379. // emits a zero-length Buffer, so a non-empty fragment list always decodes
  1380. // to a non-empty tail.
  1381. //
  1382. // `retainPartialTail` is true only on the budget-triggered path: there the
  1383. // residual can end at an ARBITRARY pipe boundary, so if the incomplete
  1384. // trailing bytes of a UTF-8 lead sequence are pending (`stray.utf8.expected
  1385. // > 0`), they are withheld from the decode and re-carried on `chunks` for a
  1386. // later chunk to complete — decoding them here would render a LEGAL,
  1387. // un-finished character as U+FFFD in an admitted entry, and the next chunk's
  1388. // bytes would then each independently break into more U+FFFD. The withheld
  1389. // tail is `stray.utf8.width - stray.utf8.expected` bytes (the lead plus the
  1390. // continuations consumed so far), at most 3; `stray.utf8` is reset and the
  1391. // withheld tail re-accrued so the next chunk continues the walk correctly.
  1392. // The `end`/closeDeadline paths pass `false`: there a trailing incomplete
  1393. // sequence is real truncated input and the U+FFFD is the honest render.
  1394. function flushStray(stray: StrayBuffer, retainPartialTail?: boolean): void {
  1395. if (stray.chunks.length === 0 && stray.blocks.length === 0) return
  1396. // Concatenate the sealed blocks and the current-chunk residual together
  1397. // unconditionally (no `blocks.length > 0` ternary): a flush can run with
  1398. // either or both present, and a branch on their presence would need a
  1399. // test that flushes exactly at a seal boundary.
  1400. let full = Buffer.concat([...stray.blocks, ...stray.chunks])
  1401. // A budget flush landing exactly between a lead byte and its
  1402. // still-pending continuation requires the combined-cost threshold to trip
  1403. // on a specific mid-multibyte pipe boundary — not deterministically
  1404. // schedulable through the black-box seam, which observes only complete
  1405. // entries. So the retention arm is v8-ignored (exercised by review
  1406. // reasoning over the `stray.utf8` state, not by an in-tree test): it
  1407. // withholds the lead-plus-consumed-continuations tail (≤3 bytes, via
  1408. // `stray.utf8.width - stray.utf8.expected`) from the decode, re-carries it
  1409. // for a later chunk, and re-accrues the pipe's cost/UTF-8 state over it;
  1410. // decoding here would render a LEGAL, unfinished character as U+FFFD in an
  1411. // admitted entry. Every retainPartialTail=false call (the `end`/closeDeadline
  1412. // paths) and a budget flush with no partial tail in flight (`expected === 0`)
  1413. // falls through with `keep` unset: the FULL residual is decoded — there a
  1414. // trailing incomplete sequence is real truncated input and the U+FFFD is the
  1415. // honest render.
  1416. let keep: Buffer | undefined
  1417. /* v8 ignore next 18 -- mid-sequence budget-flush boundary is not schedulable from a test. */
  1418. if (retainPartialTail && stray.utf8.expected > 0) {
  1419. const drop = Math.min(stray.utf8.width - stray.utf8.expected, full.length)
  1420. keep = full.subarray(full.length - drop)
  1421. full = full.subarray(0, full.length - drop)
  1422. stray.chunks = detachResidual(keep)
  1423. // Re-accrue the withheld tail from a FRESH state: `stray.utf8` still
  1424. // holds the whole-pending state (`expected > 0`, i.e. the tail is
  1425. // mid-sequence), so metering `keep` against it would charge the carried
  1426. // LEAD byte as an illegal continuation. Reset, then walk `keep` so the
  1427. // resumed sequence re-claims its own lead.
  1428. stray.utf8 = { expected: 0, width: 0, lowerFirst: 0, upperFirst: 0 }
  1429. stray.cost = accrueStrayCost(keep, stray.utf8)
  1430. stray.blocks = []
  1431. // Do not admit an EMPTY entry: when the whole residual is a single
  1432. // unfinished multibyte sequence, `full` was drained into `keep` and no
  1433. // complete byte stream remains to admit. `admit('')` would push a
  1434. // model-visible bogus empty line (logs are joined with '\n' downstream).
  1435. if (full.length > 0) admit(full.toString('utf8'))
  1436. } else {
  1437. stray.chunks = []
  1438. stray.cost = 0
  1439. stray.utf8 = { expected: 0, width: 0, lowerFirst: 0, upperFirst: 0 }
  1440. stray.blocks = []
  1441. admit(full.toString('utf8'))
  1442. }
  1443. }
  1444. child.stdout.on('data', (chunk: Buffer) => { captureStray(strayOut, chunk) })
  1445. child.stderr.on('data', (chunk: Buffer) => { captureStray(strayErr, chunk) })
  1446. child.stdout.on('end', () => { flushStray(strayOut) })
  1447. child.stderr.on('end', () => { flushStray(strayErr) })
  1448. // Line-framed JSON reader over fd 3. The unframed buffer is bounded: a
  1449. // hostile program can loop `os.write(3, b"A"*4096)` with no newline to
  1450. // exhaust HOST memory, which the child's RLIMIT_AS does not cover. It is
  1451. // a memory-safety bound only: legitimate `call` frames may be large
  1452. // (binding traffic has no seam byte cap), so it never keys off
  1453. // maxValueBytes.
  1454. // Buffered as raw chunks with a running byte counter: appending is O(1)
  1455. // per chunk (a string `+=` accumulator would re-copy the whole prefix on
  1456. // every pipe chunk — quadratic on a large frame), joins happen only when
  1457. // a newline actually arrived, and the ceiling check reads the counter.
  1458. let pendingChunks: Buffer[] = []
  1459. // Fragments already merged into finished blocks. Kept separate from
  1460. // `pendingChunks` so sealing never re-copies what earlier seals produced;
  1461. // the two together are the unframed buffer, and `pendingBytes` counts both.
  1462. let sealedBlocks: Buffer[] = []
  1463. let pendingBytes = 0
  1464. proto.on('data', (chunk: Buffer) => {
  1465. // Once settled, stop accumulating: a hostile child that keeps flooding
  1466. // fd 3 between finish() and close must not regrow the host buffer.
  1467. /* v8 ignore next -- post-settlement data needs the child to outrace close after we decided. */
  1468. if (settled) return
  1469. // Schedule ONE post-batch outstanding-call check per macrotask. The
  1470. // check must see the TRUE count — the live count is inflated by this
  1471. // batch's own frames (the finallys run on the microtask queue, which
  1472. // drains only when the macrotask ends), and a per-event snapshot is
  1473. // stale when flowing mode fires several 'data' events within one
  1474. // macrotask before any microtask drains. setImmediate runs after the
  1475. // current macrotask's microtasks, so the count is exact; the flag
  1476. // dedupes the check across the events of one macrotask. The threshold
  1477. // is STRICT: exactly MAX_PENDING_REPLIES outstanding calls are allowed,
  1478. // so a program that returns with calls it never awaited still
  1479. // completes (the done frame settles the run; the check no-ops on
  1480. // `settled`).
  1481. if (!postBatchCheckPending) {
  1482. postBatchCheckPending = true
  1483. setImmediate(() => {
  1484. postBatchCheckPending = false
  1485. /* v8 ignore next -- the done frame can settle the run between the schedule and this callback. */
  1486. if (settled) return
  1487. if (pendingCalls > MAX_PENDING_REPLIES) {
  1488. finish({ error: { kind: 'worker-exit', message: `call backlog exceeded ${MAX_PENDING_REPLIES} in-flight binding calls (a binding never settled)` } })
  1489. }
  1490. })
  1491. }
  1492. pendingChunks.push(chunk)
  1493. pendingBytes += chunk.length
  1494. // Check the counter BEFORE the join, not the joined line afterwards:
  1495. // Buffer.concat allocates a second copy of everything held, so a line
  1496. // measured after the concat had already cost twice the ceiling — the
  1497. // ceiling this check exists to enforce. The counter is exact and free,
  1498. // and the retained chunks are released here so the rejected payload is
  1499. // not still held while the run settles.
  1500. //
  1501. // The counter charges the whole unframed buffer, which over-counts by at
  1502. // most the newline-bearing chunk's own length (one pipe read): the
  1503. // residual carried in is always a partial line, so nothing but the
  1504. // current line can be larger than that. That over-count is deliberate and
  1505. // load-bounded on the OTHER side: the config cap is `parse-cap - envelope`,
  1506. // and a legitimate near-cap frame plus a following chunk's leading bytes
  1507. // could in principle nudge the counter over the cap for one read window
  1508. // — but only when maxLogBytes/maxValueBytes is configured within one
  1509. // pipe read of the 64 MiB cap, orders of magnitude past the 32/64 KiB
  1510. // defaults.
  1511. //
  1512. // The cap is enforced ONLY when the held bytes are still a single
  1513. // unframed line (this chunk carries no newline, and earlier
  1514. // newline-bearing chunks were joined immediately): a frame past the cap
  1515. // would otherwise be fully `Buffer.concat`-ed (a second copy of its
  1516. // bytes) and only then dropped in the line loop — the peak-memory
  1517. // doubling this pre-concat check exists to prevent. Dropping the
  1518. // oversized unframed buffer before the join keeps the peak at one copy
  1519. // of the wire bytes. When this chunk DOES carry a newline the buffer
  1520. // holds several frames, so the FIRST-FRAME check below (not this
  1521. // counter, which charges them all) decides.
  1522. if (pendingBytes > this.frameParseCapBytes && !chunk.includes(0x0a)) {
  1523. pendingChunks = []
  1524. sealedBlocks = []
  1525. pendingBytes = 0
  1526. finish({ error: { kind: 'worker-exit', message: `protocol frame exceeded ${this.frameParseCapBytes} bytes on fd 3` } })
  1527. return
  1528. }
  1529. // Bound the FRAGMENT COUNT as well as the byte total, but only AFTER the
  1530. // ceiling check above: sealing first would `Buffer.concat` an already
  1531. // over-ceiling payload and allocate a second copy of it before the
  1532. // rejection ran, which is the peak-memory doubling that check exists to
  1533. // prevent.
  1534. //
  1535. // Fragment count needs its own bound because the ceiling meters payload
  1536. // bytes only, while each retained chunk is a separate Buffer with object
  1537. // and backing-store overhead no byte count sees: 5000 single-byte
  1538. // newline-free writes produced 5000 chunks holding 5031 bytes, so a
  1539. // program pacing such writes could accumulate millions of objects inside
  1540. // the wall budget and exhaust the host heap far below the ceiling.
  1541. //
  1542. // Sealing appends to a list of finished blocks instead of re-merging
  1543. // everything held. Concatenating the whole buffer at each threshold
  1544. // re-copied the entire accumulated prefix every time, so the cumulative
  1545. // copy volume was quadratic, not the amortized O(1) an earlier revision
  1546. // of this comment claimed: 10 MiB trickled a byte at a time copies
  1547. // 53.7 GB that way, and 64 MiB copies 2.2 TB. Here each byte is copied
  1548. // once into its block and never again, so the total stays linear, and the
  1549. // block list is itself bounded — every block holds at least
  1550. // `MAX_PENDING_CHUNKS - 1` bytes, so reaching the 64 MiB cap admits
  1551. // at most a few hundred thousand of them.
  1552. // Sealing runs ONLY on a newline-free chunk, and after the newline
  1553. // branch below: a chunk carrying a newline must reach the join (and its
  1554. // first-frame check) rather than being sealed into a block the check
  1555. // would then not scan for newlines. That keeps the invariant
  1556. // `sealedBlocks hold newline-free prefixes only` true, so the
  1557. // first-frame scan below can charge each sealed block's whole length
  1558. // toward the first frame without missing a newline inside it.
  1559. if (chunk.includes(0x0a)) {
  1560. // First-FRAME check before the join: measure the bytes up to the
  1561. // first newline across the held chunks. The byte counter cannot
  1562. // serve here — it charges the whole buffer, which legitimately
  1563. // holds several frames each within the cap. A first frame past the
  1564. // cap is dropped before the join (one copy of its wire bytes);
  1565. // later frames in the same buffer are handled line by line in the
  1566. // loop below.
  1567. let firstFrameLen = 0
  1568. let sawNewline = false
  1569. // Sealed blocks hold newline-free prefixes only (see the sealing
  1570. // gate below), so they are entirely part of the first frame.
  1571. for (const b of sealedBlocks) firstFrameLen += b.length
  1572. for (const c of pendingChunks) {
  1573. const nl = c.indexOf(0x0a)
  1574. if (nl >= 0) {
  1575. firstFrameLen += nl
  1576. sawNewline = true
  1577. break
  1578. }
  1579. firstFrameLen += c.length
  1580. }
  1581. if (sawNewline && firstFrameLen > this.frameParseCapBytes) {
  1582. pendingChunks = []
  1583. sealedBlocks = []
  1584. pendingBytes = 0
  1585. finish({ error: { kind: 'worker-exit', message: `protocol frame exceeded ${this.frameParseCapBytes} bytes on fd 3` } })
  1586. return
  1587. }
  1588. let buffered = Buffer.concat(sealedBlocks.length > 0 ? [...sealedBlocks, ...pendingChunks] : pendingChunks)
  1589. sealedBlocks = []
  1590. let newline: number
  1591. while ((newline = buffered.indexOf(0x0a)) >= 0) {
  1592. const line = buffered.subarray(0, newline)
  1593. buffered = buffered.subarray(newline + 1)
  1594. /* v8 ignore next -- an empty line comes only from a forged `\n\n` write. */
  1595. if (line.length === 0) continue
  1596. // No per-line cap check here: the pre-join counter (single unframed
  1597. // line) and the first-frame check (newline-bearing chunk) above
  1598. // reject any frame past FRAME_PARSE_CAP_BYTES before this join, so
  1599. // every line in this loop is within the cap by construction — a
  1600. // per-line check would be dead code.
  1601. // `toString('utf8')` would silently REPLACE illegal bytes with
  1602. // U+FFFD, corrupting a completion or binding payload a forged
  1603. // frame smuggled in (the honest child's lossless encoder never
  1604. // emits non-UTF-8, so such a frame is hostile traffic). The fatal
  1605. // decode throws on them and the frame is dropped — not accepted
  1606. // with a mangled value — the same treatment as the unsafe-integer
  1607. // check below.
  1608. let text: string
  1609. try {
  1610. text = UTF8_FATAL.decode(line)
  1611. } catch {
  1612. continue
  1613. }
  1614. // JSON.parse would silently ROUND an integer token outside the
  1615. // safe range before validation could see it, so a forged frame
  1616. // could smuggle a corrupted value into a dispatch or completion.
  1617. // An honest child never emits one (its validator rejects unsafe
  1618. // ints), so such a frame is hostile traffic: drop it like any
  1619. // other junk frame.
  1620. if (hasUnsafeIntegerToken(text)) continue
  1621. let parsed: unknown
  1622. try {
  1623. parsed = JSON.parse(text) as unknown
  1624. } catch {
  1625. continue // Junk frames drop silently (hostile-peer stance).
  1626. }
  1627. const message = validateChildFrame(parsed)
  1628. if (message) handleFrame(message)
  1629. }
  1630. // Carry the residual forward as a fresh, right-sized copy, NOT the
  1631. // `subarray` view: a view keeps the whole joined-frame allocation from
  1632. // the `Buffer.concat` above alive, so a large frame followed by a tiny
  1633. // trailing fragment would pin megabytes while `pendingBytes` reported
  1634. // only the fragment's length. See {@link detachResidual}.
  1635. pendingChunks = detachResidual(buffered)
  1636. pendingBytes = buffered.length
  1637. } else if (pendingChunks.length >= MAX_PENDING_CHUNKS) {
  1638. // A newline-free run past the fragment-count bound: seal the held
  1639. // chunks into one finished block (amortized O(1) per byte, see the
  1640. // comment above the count bound) and keep accumulating. The gate on
  1641. // `chunk.includes(0x0a)` is the ELSE half of the newline branch, so a
  1642. // newline-bearing chunk never lands in a sealed block.
  1643. sealedBlocks.push(Buffer.concat(pendingChunks))
  1644. pendingChunks = []
  1645. }
  1646. })
  1647. // Duplicate-call suppression against the honest child's id SEQUENCE, not
  1648. // a set of every id seen. `dispatch` sends consecutive ids from 0 with no
  1649. // gaps — it advances its counter only after the write succeeds, so a call
  1650. // rejected before reaching the wire consumes nothing — which makes the
  1651. // next legitimate id exactly `nextCallId`.
  1652. //
  1653. // Retaining a set instead let a program write an unbounded run of unique
  1654. // forged ids, each below the 64 MiB per-frame parse cap so nothing
  1655. // rejected them, and grow host memory for the whole run. Accepting any
  1656. // id above a high-water mark would have been just as wrong in the other
  1657. // direction: one forged `{"id": 9999}` would starve every honest call
  1658. // after it. The exact successor is the only test that both bounds the
  1659. // retained state to one number and cannot be poisoned by a forgery.
  1660. let nextCallId = 0
  1661. // Set by run() when the boot frame is written; the fd-3 handler calls it
  1662. // on boot-ack to send the run frame (see the seam's boot->boot-ack->run
  1663. // order). scoped per run. An object holder so the cross-closure
  1664. // assignment is a property write (eslint's prefer-const cannot see the
  1665. // reassignment through the closure).
  1666. const bootAckGate: { run?: () => void } = {}
  1667. const handleFrame = (message: ChildToHost): void => {
  1668. /* v8 ignore next -- late frame after settlement; defensive against forged post-settlement traffic. */
  1669. if (settled) return
  1670. switch (message.type) {
  1671. case 'boot-ack':
  1672. // The child accepted the boot frame (namespaces built); the run
  1673. // frame goes out now, not with the boot frame.
  1674. bootAckGate.run?.()
  1675. return
  1676. case 'log':
  1677. if (message.truncated === true) {
  1678. // The CHILD ledger hit its cap. Its marker is the last log text
  1679. // there will be, so record it and stop host capture at the same
  1680. // point: admitting it as ordinary text left the host budget open,
  1681. // so later direct `os.write(1, ...)` bytes were retained AFTER the
  1682. // marker and a host-side exhaustion could append a second one.
  1683. // Both ledgers are keyed to the same `maxLogBytes`, so one marker
  1684. // describes the run.
  1685. if (!logsTruncated) {
  1686. // The host's OWN marker, never the frame's text. `truncated` is
  1687. // attacker-reachable, so trusting the text let a program write
  1688. // `{"type":"log","truncated":true,"text":<1 MiB>}` and land all
  1689. // of it in `logs` under a 64-byte `maxLogBytes` — measured, the
  1690. // whole megabyte was retained, bypassing `admit` and its
  1691. // ceiling. Both ledgers key off the same `maxLogBytes`, so the
  1692. // marker the host generates says the same thing the child's
  1693. // would have.
  1694. truncateLogs()
  1695. }
  1696. return
  1697. }
  1698. if (message.open === true) {
  1699. // An explicit flush of an unterminated line: hold it so the next
  1700. // frame appends to the SAME entry (print('a', end='', flush=True)
  1701. // followed by print('b') reads back as one 'ab' entry, not a fake
  1702. // newline). Billed INCREMENTALLY so k tiny frames cost O(k), not
  1703. // O(k * budget) (re-walking the whole held text per frame): the
  1704. // first fragment is charged the full JSON-string cost plus the
  1705. // separator (quotes + content + newline), each continuation only
  1706. // its content (jsonStringCostUpTo includes the two quotes), and
  1707. // the closing frame only its own content — the merged entry's
  1708. // wire cost is billed exactly once, split across the fragments.
  1709. // Caps: the first fragment's exact-cost walk uses logBudget - 1
  1710. // (the ledger's reserved byte, matching admit), a continuation's
  1711. // logBudget + 2 (a continuation is billed WITHOUT quotes, so its
  1712. // billed cost cost - 2 fits exactly when the walk's cost is at
  1713. // most logBudget + 2).
  1714. if (!logsTruncated) {
  1715. // An EMPTY first open frame (openParts empty AND text '') bills
  1716. // cost + 1 = 3 but establishes no hold (the push is skipped),
  1717. // so the next frame is billed as a new first fragment. Not
  1718. // reachable from an honest child (_LogStream.write('') returns
  1719. // early; flush_line pushes only non-empty pending); for a
  1720. // forged frame it is a bounded over-charge in the safe
  1721. // direction (a flood exhausts the ledger into truncation).
  1722. const cap = openParts.length === 0 ? logBudget - 1 : logBudget + 2
  1723. const cost = jsonStringCostUpTo(message.text, cap)
  1724. if (cost === undefined) {
  1725. truncateLogs()
  1726. } else {
  1727. const bill = openParts.length === 0 ? cost + 1 : Math.max(cost - 2, 0)
  1728. logBudget -= bill
  1729. // A zero-content continuation (text '') bills 0; holding it
  1730. // would grow the fragment array without touching the ledger,
  1731. // so a forged empty-open flood could grow host memory — skip
  1732. // the push, the merge result is unchanged.
  1733. if (message.text !== '') {
  1734. if (openParts.length >= MAX_PENDING_CHUNKS) {
  1735. openSealed.push(openParts.join(''))
  1736. openParts = []
  1737. }
  1738. openParts.push(message.text)
  1739. }
  1740. }
  1741. }
  1742. return
  1743. }
  1744. if (openParts.length > 0) {
  1745. // Closing frame: the held fragments are already billed; bill only
  1746. // this frame's own content (the quotes and separator ride on the
  1747. // first fragment) and push the merged entry once. Cap is
  1748. // logBudget + 2 for the same reason as a continuation.
  1749. /* v8 ignore next -- logsTruncated is an invariant false here: an open
  1750. * frame that would trip the ledger resets openParts, so a non-empty
  1751. * hold implies the ledger never truncated. The guard is defensive. */
  1752. if (!logsTruncated) {
  1753. const cost = jsonStringCostUpTo(message.text, logBudget + 2)
  1754. if (cost === undefined) {
  1755. truncateLogs()
  1756. } else {
  1757. logBudget -= Math.max(cost - 2, 0)
  1758. logs.push(openSealed.join('') + openParts.join('') + message.text)
  1759. }
  1760. }
  1761. openSealed = []
  1762. openParts = []
  1763. return
  1764. }
  1765. admit(message.text)
  1766. return
  1767. case 'done': {
  1768. // The call-backlog cap must also hold when the child finishes in
  1769. // the SAME batch as its flood: the post-macrotask check no-ops once
  1770. // this done frame settles the run, so a done arriving right after
  1771. // more than MAX_PENDING_REPLIES call frames in one data event would
  1772. // otherwise complete successfully with the outstanding closures
  1773. // left behind (a single sub-64 KiB write can carry 1025 compact
  1774. // calls plus a done). The strict threshold lets exactly
  1775. // MAX_PENDING_REPLIES outstanding calls — a program that returned
  1776. // without awaiting its calls — complete normally.
  1777. if (pendingCalls > MAX_PENDING_REPLIES) {
  1778. finish({ error: { kind: 'worker-exit', message: `call backlog exceeded ${MAX_PENDING_REPLIES} in-flight binding calls (a binding never settled)` } })
  1779. return
  1780. }
  1781. if (message.error) {
  1782. finish({ error: { kind: message.error.kind, message: capMessage(message.error.message, this.config.maxValueBytes) } })
  1783. return
  1784. }
  1785. if (message.value === undefined) {
  1786. finish({})
  1787. return
  1788. }
  1789. // Re-enforce the completion budget and number losslessness
  1790. // host-side: a forged done frame bypasses the Python-side
  1791. // _done_with_value check, and validateChildFrame no longer scans
  1792. // the value (an unbounded scan would push every member of a wide
  1793. // forgery before any cap ran). checkDoneValue folds both jobs into
  1794. // one bounded, iterative traversal — iterative because the seam's
  1795. // CodeJsonValue has no depth limit and an honest deep-but-small
  1796. // completion must cross intact rather than dying on stringify
  1797. // recursion; bounded because it stops at the cap without
  1798. // materializing the encoding, rejecting a forged value anywhere
  1799. // below the 64 MiB frame parse cap before it forces host-side copies.
  1800. // The seam forbids substituting a rendered/truncated value, so an
  1801. // oversized value fails the run as output-limit and a non-lossless
  1802. // number as invalid-output. The value is JSON-plain by construction
  1803. // (it came from JSON.parse of the frame), the traversal's precondition.
  1804. const check = checkDoneValue(message.value, this.config.maxValueBytes)
  1805. if (!check.ok) {
  1806. finish(check.reason === 'over-budget'
  1807. ? { error: { kind: 'output-limit', message: `completion value exceeded ${this.config.maxValueBytes} bytes` } }
  1808. : { error: { kind: 'invalid-output', message: 'completion value contained a non-lossless number' } })
  1809. return
  1810. }
  1811. finish({ value: message.value as CodeJsonValue })
  1812. return
  1813. }
  1814. case 'call': {
  1815. if (message.id !== nextCallId) return
  1816. nextCallId += 1
  1817. const record = bindings.get(message.global)?.functions
  1818. const fn = record && Object.hasOwn(record, message.name) ? record[message.name] : undefined
  1819. if (typeof fn !== 'function') {
  1820. // `call.global` and `call.name` are attacker-controlled strings
  1821. // with no byte cap of their own — only the 64 MiB fd-3 frame
  1822. // parse cap — so each is sliced to `maxValueBytes` CODE UNITS
  1823. // BEFORE it reaches the template. Interpolating them whole would
  1824. // copy them into the message, `JSON.stringify` would copy the
  1825. // escaped form, `encodeJsonPlain` the frame, and the pipe write
  1826. // again: four full-size host allocations off one below-ceiling
  1827. // forgery, past every hostile-peer bound the log and done-error
  1828. // paths apply. Nothing past the first `maxValueBytes` code units
  1829. // of either field can survive the byte cap anyway, so the slices
  1830. // lose only text `capMessage` would drop, and that final cap
  1831. // gives this reply the same budget and marker as a forged done
  1832. // error.
  1833. const cap = this.config.maxValueBytes
  1834. const target = `${message.global.slice(0, cap)}.${message.name.slice(0, cap)}`
  1835. // JSON.stringify on the WHOLE capped target would still allocate
  1836. // the escaped form — up to ~6x under control-heavy input, a
  1837. // multi-hundred-MB spike near the maxValueBytes ceiling that no
  1838. // hostile-peer bound would have admitted. The message only needs
  1839. // to identify the binding, so the escaped form is built from a
  1840. // 1 KiB prefix; capMessage then enforces the reply budget.
  1841. const preview = JSON.stringify(target.slice(0, 1024))
  1842. sendReply({ type: 'reply', id: message.id, ok: false, message: capMessage(`unknown binding ${preview}`, cap) })
  1843. return
  1844. }
  1845. // Count the outstanding binding call before dispatch and release the
  1846. // slot in the async body's finally. The CAP CHECK runs in the data
  1847. // handler's post-macrotask pass (where the finallys have drained),
  1848. // not here: a per-frame check would see every frame of one event as
  1849. // in-flight and false-positive on a legitimate gather of more than
  1850. // MAX_PENDING_REPLIES instant calls.
  1851. pendingCalls += 1
  1852. void (async () => {
  1853. try {
  1854. const resolved = await fn(message.args)
  1855. // Drop a reply the run no longer needs BEFORE snapshotting it.
  1856. // `sendReply` also checks `settled`, but only after this value has
  1857. // been walked and copied: a binding that resolves a wide value
  1858. // after `maxWallMs`, an abort, or dispose already settled the run
  1859. // would spend host heap on a frame that is then discarded, and
  1860. // binding resolution carries no seam-level byte cap to bound it.
  1861. // oxlint-disable-next-line typescript/no-unnecessary-condition -- the run can settle while this binding is awaited.
  1862. if (settled) return
  1863. // The seam requires a lossy resolution to REJECT descriptively,
  1864. // not silently coerce: a raw JSON.stringify would turn NaN/
  1865. // Infinity into null and drop undefined fields. Snapshot through
  1866. // the same lossless-JSON boundary the worker backend uses (also
  1867. // iterative, so a deeply nested value cannot overflow the stack).
  1868. const value = snapshotJsonValue(resolved)
  1869. if (value === undefined) {
  1870. sendReply({ type: 'reply', id: message.id, ok: false, message: 'binding resolution must be lossless JSON' })
  1871. return
  1872. }
  1873. sendReply({ type: 'reply', id: message.id, ok: true, value })
  1874. } catch (error: unknown) {
  1875. // Check `settled` before formatting the error: a rejection that
  1876. // arrives after `maxWallMs`, an abort, or dispose has already
  1877. // settled the run, and `messageOf(error)` runs hostile getters
  1878. // before `sendReply` peeks at `settled`. Dropping the framed
  1879. // reply early spares the host heap and time for a run whose
  1880. // outcome is already fixed.
  1881. // (oxlint block-disable so both `v8 ignore next` and the rule
  1882. // suppression land on the `if`: `settled` flips true mid-wait,
  1883. // invisible to the type-aware lint, which narrows it to false.)
  1884. /* oxlint-disable typescript/no-unnecessary-condition */
  1885. /* v8 ignore next -- a rejection arriving after settlement is not schedulable from a test. */
  1886. if (settled) return
  1887. /* oxlint-enable typescript/no-unnecessary-condition */
  1888. sendReply({ type: 'reply', id: message.id, ok: false, message: messageOf(error) })
  1889. } finally {
  1890. // Release the in-flight slot on every exit — reply written,
  1891. // resolution rejected, or the run settling mid-wait (the
  1892. // `settled` early returns above). Without this, a binding that
  1893. // never resolves would leak its slot past the cap check and the
  1894. // flood bound would erode.
  1895. pendingCalls -= 1
  1896. }
  1897. })()
  1898. return
  1899. }
  1900. }
  1901. }
  1902. // Write one reply frame with the iterative encoder: a binding
  1903. // resolution has no seam-level depth or byte cap, so a deeply nested
  1904. // value must not die on JSON.stringify's recursion. The payload is
  1905. // JSON-plain by construction (snapshotJsonValue output, or literal
  1906. // strings/numbers), which is encodeJsonPlain's precondition. A closed
  1907. // pipe (child already gone) is swallowed since the close path settles
  1908. // the run.
  1909. //
  1910. // Replies are encoded and written ONE AT A TIME, waiting for `drain`
  1911. // whenever fd 3's buffer is full. Binding resolution carries no
  1912. // seam-level byte cap, so a program that resolves several large values in
  1913. // one `asyncio.gather` round would otherwise encode them all in the same
  1914. // turn and queue every frame in the writable stream's buffer -- measured
  1915. // to exhaust a 256 MiB Node heap, which kills the whole host process
  1916. // rather than failing this one run. Pacing changes no model-visible
  1917. // behavior: the child matches each reply to its `call` by id from a pump
  1918. // that reads fd 3 continuously, so arrival order was never observable,
  1919. // and the bindings themselves still run concurrently. Only the host's peak
  1920. // memory and the flush timing change.
  1921. const replyQueue: ReplyMessage[] = []
  1922. // Replies queued but not yet written, tracked separately from
  1923. // `replyQueue.length`: the drain loop clears consumed slots to `undefined`
  1924. // but does not shrink the array until it finishes, so `length` counts
  1925. // consumed frames too. The counter is what the cap in `sendReply` reads.
  1926. let pendingReplies = 0
  1927. // Binding calls dispatched but not yet settled (the async body below
  1928. // still awaits the binding's promise). The reply backlog cap only counts
  1929. // RESOLVED calls — `pendingReplies` grows after the await — so a child
  1930. // flooding calls against a binding that never settles would accumulate
  1931. // one async closure per frame until the wall clock without tripping it.
  1932. // Counted here before dispatch and released in the body's finally; the
  1933. // data handler schedules a post-macrotask check (see there) that settles
  1934. // the run as worker-exit when the true outstanding count passes
  1935. // MAX_PENDING_REPLIES.
  1936. let pendingCalls = 0
  1937. // Dedupes the post-batch outstanding-call check across the 'data' events
  1938. // of one macrotask (see the data handler).
  1939. let postBatchCheckPending = false
  1940. let draining = false
  1941. // Resolve when fd 3 can take another frame, OR when it is gone: a pipe
  1942. // destroyed under the drain (child exited, close-deadline teardown) never
  1943. // emits 'drain' again, so waiting on that event alone would hang the
  1944. // drain forever — `draining` stays true and the unconsumed queue is
  1945. // pinned with the closure. `once` plus the manual detach removes every
  1946. // listener whichever event wins, so a long backpressure wait leaves none
  1947. // behind.
  1948. const waitForDrain = (): Promise<void> => new Promise<void>((resolvePromise) => {
  1949. const finish = (): void => {
  1950. proto.off('drain', finish)
  1951. proto.off('close', finish)
  1952. proto.off('error', finish)
  1953. resolvePromise()
  1954. }
  1955. proto.once('drain', finish)
  1956. proto.once('close', finish)
  1957. proto.once('error', finish)
  1958. })
  1959. const drainReplies = async (): Promise<void> => {
  1960. if (draining) return
  1961. draining = true
  1962. let head = 0
  1963. try {
  1964. while (head < replyQueue.length) {
  1965. // Needs the run to settle between two queued frames. Measured queue
  1966. // depths reach 11 without the wall clock landing inside that window.
  1967. /* v8 ignore next -- see above; not schedulable from a test. */
  1968. if (settled) break
  1969. // A pipe destroyed under us (child exited, close deadline) will
  1970. // never emit 'drain' again; short-circuit before the write so the
  1971. // remaining frames are dropped by the `finally` below.
  1972. if (proto.destroyed) break
  1973. // Read by index, not `shift()`: a large `asyncio.gather` of wide
  1974. // bindings awaiting fd 3's `drain` can queue many frames, and each
  1975. // `shift()` re-slices the remaining array (O(n) per pop, O(n²) over
  1976. // the whole drain). A head cursor keeps the cost linear; the `finally`
  1977. // below discards everything consumed once the drain ends. The consumed
  1978. // slot is CLEARED here (not just advanced past) so a wide payload the
  1979. // pipe has already taken is released immediately: under sustained
  1980. // backpressure the drain loop can live across many `await drain`
  1981. // ticks, and leaving the slot set would pin the written value's bytes
  1982. // in `replyQueue` for the whole busy period, making host memory grow
  1983. // with cumulative processing rather than the current backlog.
  1984. const payload = replyQueue[head] as ReplyMessage
  1985. replyQueue[head] = undefined as unknown as ReplyMessage
  1986. head += 1
  1987. pendingReplies -= 1
  1988. // Compact the consumed prefix once it reaches the backlog bound:
  1989. // the array never shrinks until the drain finishes, and a child
  1990. // that reads replies just fast enough to keep the drain alive but
  1991. // never empty would otherwise grow the backing store linearly with
  1992. // cumulative throughput (consumed slots are undefined, but `length`
  1993. // keeps counting them). The splice is O(head) once per
  1994. // MAX_PENDING_REPLIES consumed frames — amortized O(1) per reply.
  1995. if (head >= MAX_PENDING_REPLIES) {
  1996. replyQueue.splice(0, head)
  1997. head = 0
  1998. }
  1999. // Encode inside the loop, not up front: a queued reply the run no
  2000. // longer needs is dropped by the `settled` check above without ever
  2001. // being serialized.
  2002. if (!proto.write(`${encodeJsonPlain(payload)}\n`)) {
  2003. await waitForDrain()
  2004. }
  2005. }
  2006. } catch {
  2007. // Pipe closed under us (child exited), or `drain` never arrives because
  2008. // the child died. The close path settles the run either way.
  2009. } finally {
  2010. draining = false
  2011. pendingReplies = 0
  2012. replyQueue.length = 0
  2013. }
  2014. }
  2015. const sendReply = (payload: ReplyMessage): void => {
  2016. /* v8 ignore next -- `settled` covers a race where the child exits between decision and write. */
  2017. if (settled) return
  2018. // A child that stops reading fd 3 leaves the drain loop blocked on
  2019. // `drain` forever while its call frames keep resolving into replies:
  2020. // the backlog would grow without bound until the wall clock, pinning
  2021. // every binding result the child provokes. Cap the retained backlog and
  2022. // settle the run as a worker-exit, the same hostile-peer bound the
  2023. // frame cap applies to inbound bytes.
  2024. if (pendingReplies >= MAX_PENDING_REPLIES) {
  2025. finish({ error: { kind: 'worker-exit', message: `reply queue exceeded ${MAX_PENDING_REPLIES} pending frames on fd 3 (the child stopped consuming its replies)` } })
  2026. return
  2027. }
  2028. pendingReplies += 1
  2029. replyQueue.push(payload)
  2030. void drainReplies()
  2031. }
  2032. // Escalate SIGTERM → grace → SIGKILL on the entire process group. Idempotent
  2033. // via `killing`.
  2034. let killing = false
  2035. let graceTimer: NodeJS.Timeout | undefined
  2036. // A backstop for the one case `close` cannot cover: model code that starts
  2037. // a descendant with `os.setsid()`/`start_new_session=True` moves it into a
  2038. // fresh process group, so the SIGTERM/SIGKILL aimed at the child's group
  2039. // (`kill(-pid)`) never reaches it. If that orphan inherited stdout/stderr/
  2040. // fd 3 and outlives the run, those pipes stay open and `close` never fires
  2041. // — leaving run() (and a teardown awaiting `finished`) hung indefinitely.
  2042. // finish() arms this deadline; when it fires we detach our stream handles
  2043. // and settle on the already-decided result regardless of the orphan.
  2044. let closeDeadline: NodeJS.Timeout | undefined
  2045. // The leader's start time, read once while it is certainly alive. `child.pid`
  2046. // keeps its numeric value after the leader is reaped (Node clears the
  2047. // internal handle, not the field), and `close` can trail `exit` by seconds
  2048. // while a pipe-holding descendant keeps the streams open. Signalling
  2049. // `-child.pid` in that window is a RAW syscall -- `child.kill()` would
  2050. // refuse, having dropped its handle, but `process.kill` has no such guard --
  2051. // so a recycled pgid would receive this run's SIGTERM and armed SIGKILL.
  2052. // `groupEmpty()` cannot cover it: it reports whether the group has members,
  2053. // not whether they are OURS, and it runs only after the first signal.
  2054. // The repository already takes this position in
  2055. // packages/subprocess/subprocess-local (`ProcessIdentity`, "preventing
  2056. // teardown escalation after PID reuse"); this is the same guard, kept local
  2057. // because a dependency on that package would be a new architectural edge.
  2058. const leaderStarted = child.pid === undefined ? undefined : readProcessStart(child.pid)
  2059. const killGroup = (sig: NodeJS.Signals): void => {
  2060. try {
  2061. /* v8 ignore next -- undefined pid means spawn never produced a process; finish() short-circuits before reaching kill(). */
  2062. if (child.pid === undefined) return
  2063. // A pid alone cannot answer this: `process.kill(pid, 0)` succeeds just
  2064. // as well for a REPLACEMENT process holding the recycled number. Only
  2065. // the start time distinguishes the two, so a reading that DISAGREES
  2066. // means the number now belongs to another process and must not be
  2067. // signalled.
  2068. //
  2069. // An ABSENT reading is the ordinary case, not a mismatch: once the
  2070. // leader is reaped its `/proc/<pid>/stat` is gone, while the group it
  2071. // led can still hold survivors that this teardown exists to reap. So
  2072. // only a present-and-different reading blocks the signal; undefined
  2073. // falls through, which is also the behavior on platforms with no
  2074. // `/proc` to read.
  2075. const nowStarted = readProcessStart(child.pid)
  2076. // The refusal arm needs a real pid recycled into a new group leader
  2077. // between spawn and teardown, which no test can schedule; the reader
  2078. // itself is covered directly by the process-identity test.
  2079. /* v8 ignore next -- unreachable without real pid reuse; see above. */
  2080. if (leaderStarted !== undefined && nowStarted !== undefined && nowStarted !== leaderStarted) return
  2081. process.kill(-child.pid, sig)
  2082. } catch {
  2083. // ESRCH — the process already died. Nothing to do.
  2084. }
  2085. }
  2086. const kill = (): void => {
  2087. /* v8 ignore next -- kill() is idempotent; tests do not double-invoke it. */
  2088. if (killing) return
  2089. killing = true
  2090. killGroup('SIGTERM')
  2091. // Escalate to SIGKILL after the grace window. The timer is `unref`'d so a
  2092. // pending SIGKILL never keeps the host process alive on its own; the
  2093. // guarantee that a same-group survivor is actually reaped before the fiber
  2094. // goes quiescent is enforced by settle() awaiting the group's death (see
  2095. // there), NOT by this timer firing during host lifetime. A setsid-escaped
  2096. // orphan in a FRESH group is the different case `closeDeadline` in finish()
  2097. // covers, since `close` never fires there.
  2098. graceTimer = setTimeout(() => { killGroup('SIGKILL') }, this.config.graceMs)
  2099. graceTimer.unref()
  2100. }
  2101. // True once the group has no members left: a signal-0 probe to the whole
  2102. // group (`kill(-pid, 0)`) throws ESRCH when empty (EPERM would still mean a
  2103. // member exists). Only meaningful once a spawn produced a pid.
  2104. const groupEmpty = (): boolean => {
  2105. /* v8 ignore next -- pid is always defined once escalation runs; the guard narrows the type. */
  2106. if (child.pid === undefined) return true
  2107. try {
  2108. process.kill(-child.pid, 0)
  2109. return false
  2110. } catch (error: unknown) {
  2111. return (error as NodeJS.ErrnoException).code === 'ESRCH'
  2112. }
  2113. }
  2114. let finishResolve!: () => void
  2115. const finished = new Promise<void>((done) => { finishResolve = done })
  2116. let resolved = false
  2117. // The decided terminal result for a live child, recorded by finish() and
  2118. // read by the `close` handler that settles it once the pipes have drained.
  2119. let decided: Omit<CodeRunResult, 'logs'>
  2120. // The single settlement point: resolve run() with the decided result and
  2121. // mark the fiber quiescent. Idempotent — the first call wins, so a later
  2122. // `close` after done/timeout/abort is absorbed as a no-op.
  2123. const settle = (result: Omit<CodeRunResult, 'logs'>): void => {
  2124. if (resolved) return
  2125. resolved = true
  2126. if (closeDeadline !== undefined) clearTimeout(closeDeadline)
  2127. // The child has exited by now (settle runs on `close`, or on a spawn
  2128. // that produced no pid), so its staging directory is no longer read and
  2129. // this run's copy goes away with it. Removed SYNCHRONOUSLY, before
  2130. // `resolve` below: a fire-and-forget removal left the directory on disk
  2131. // when `run()` resolved, so a caller could not observe the "gone by
  2132. // settlement" contract at all. Two files cost nothing to unlink here.
  2133. try {
  2134. rmSync(bootstrapDir, { recursive: true, force: true })
  2135. } catch {
  2136. // Swallows only a failure to remove this run's staging directory —
  2137. // `force` already absorbs a missing one, so what remains is a
  2138. // filesystem-level refusal. The run's own outcome is already decided
  2139. // and must still be delivered; the directory holds no secret, only a
  2140. // copy of two checked-in scripts. teardown deliberately does not
  2141. // sweep staging (its staging is cleared inside each run's settle), so
  2142. // a removal failure here is the one case the "gone by settlement"
  2143. // contract degrades on.
  2144. }
  2145. resolve({ ...result, logs })
  2146. // Mark the fiber quiescent for THIS run: drop it from `live` and resolve
  2147. // `finished` (what teardown awaits). Deferred until the process group is
  2148. // actually empty — dropping from `live` before then would let a
  2149. // `dispose()` that races a just-resolved run() snapshot an empty `live`
  2150. // and return while a same-group survivor is still alive, making teardown's
  2151. // "no SAME-GROUP subprocess outlives the fiber" guarantee false for that
  2152. // window (a setsid escapee is the documented exception — see teardown's
  2153. // JSDoc). Keeping the run in `live` until the group is reaped is exactly
  2154. // what makes a concurrent teardown await it.
  2155. const finalize = (): void => {
  2156. this.live.delete(live)
  2157. finishResolve()
  2158. }
  2159. // `finished` is what teardown awaits to honor "no same-group subprocess
  2160. // outlives the fiber". When no escalation ran (normal completion, no
  2161. // kill) or the group is already empty, cancel the pending SIGKILL and
  2162. // finalize now. Clearing it is what bounds the PID-reuse hazard: an armed
  2163. // `kill(-pid)` left to fire up to graceMs later could hit a RECYCLED pgid
  2164. // once the kernel reused the leader's pid, SIGKILLing an unrelated group.
  2165. // So the timer stays armed only while a real survivor exists — a
  2166. // same-group descendant that ignored SIGTERM but released the pipes,
  2167. // still alive here because its `close` is what got us to settle. In that
  2168. // case withhold finalize and poll the group on REF'd timers (a
  2169. // short-lived host would otherwise exit before the unref'd SIGKILL fired,
  2170. // reparenting the survivor to init), clearing the timer the moment the
  2171. // group empties. The wait is bounded by `graceMs + CLOSE_REAP_MARGIN_MS`
  2172. // in the normal case; if the host event loop was blocked past both timers
  2173. // the deadline branch below sends SIGKILL itself and grants ONE more reap
  2174. // margin, so the outer bound is `graceMs + 2 * CLOSE_REAP_MARGIN_MS`.
  2175. if (!killing || groupEmpty()) {
  2176. if (graceTimer !== undefined) clearTimeout(graceTimer)
  2177. finalize()
  2178. return
  2179. }
  2180. const deadline = Date.now() + this.config.graceMs + CLOSE_REAP_MARGIN_MS
  2181. // Once the deadline forces us to send SIGKILL ourselves, allow one more
  2182. // reap window for the kernel to tear the group down before giving up:
  2183. // SIGKILL is asynchronous, so the group is not gone the instant it is
  2184. // sent. `finalize` only runs on a confirmed-empty group, except at this
  2185. // final hard bound where nothing more can be done.
  2186. let hardDeadline = 0
  2187. const pollGroup = (): void => {
  2188. if (groupEmpty()) {
  2189. // The group is gone; the grace SIGKILL is moot. Cancel it (it may not
  2190. // have fired yet) and finalize. graceTimer is always defined here:
  2191. // pollGroup runs only when `killing` is set, and kill() armed it.
  2192. clearTimeout(graceTimer)
  2193. finalize()
  2194. return
  2195. }
  2196. if (hardDeadline === 0 && Date.now() >= deadline) {
  2197. // Deadline reached with the group still non-empty. This is reachable
  2198. // when the host event loop was blocked past both timers: Node runs
  2199. // this poll before the grace SIGKILL timer, so that SIGKILL may never
  2200. // have fired. Send it HERE (idempotent if the timer already ran) and
  2201. // keep polling for the group to actually empty — finalizing on mere
  2202. // signal delivery would declare quiescence while the group is still
  2203. // dying. Bound the extra wait by one more reap margin.
  2204. killGroup('SIGKILL')
  2205. clearTimeout(graceTimer)
  2206. hardDeadline = Date.now() + CLOSE_REAP_MARGIN_MS
  2207. }
  2208. // Hard bound: the self-sent SIGKILL delivered but `groupEmpty()` still
  2209. // reports the group non-empty for a full extra reap margin. This is
  2210. // reachable, not a kernel quirk: a SIGKILL'd same-group survivor
  2211. // lingers as a ZOMBIE until its parent `wait()`s it, and in a
  2212. // container whose PID 1 does not reap orphans the survivor is
  2213. // reparented to init and never waited, so the signal-0 probe keeps
  2214. // succeeding — the same environment dependence the Agent Note's
  2215. // rejected "assert the reap with process.kill(pid, 0)" alternative
  2216. // documents. The ignore stays because that container cannot be built
  2217. // deterministically across CI platforms, not because the branch is
  2218. // unreachable; finalizing here bounds the wait so such a deployment
  2219. // still goes quiescent within `graceMs + 2 * CLOSE_REAP_MARGIN_MS`.
  2220. /* v8 ignore next 4 -- reachable only in a PID-1-doesn't-reap container (zombie survivor); not deterministically buildable. */
  2221. if (hardDeadline !== 0 && Date.now() >= hardDeadline) {
  2222. finalize()
  2223. return
  2224. }
  2225. setTimeout(pollGroup, GROUP_REAP_POLL_MS)
  2226. }
  2227. pollGroup()
  2228. }
  2229. const finish = (result: Omit<CodeRunResult, 'logs'>): void => {
  2230. if (settled) return
  2231. settled = true
  2232. decided = result
  2233. clearTimeout(wallTimer)
  2234. request.signal?.removeEventListener('abort', onAbort)
  2235. // A spawn failure (ENOENT, EACCES) never produced a pid, so there is no
  2236. // process to kill: settle now. Its `close` still fires later and reaches
  2237. // the idempotent settle() again as a no-op.
  2238. // An unterminated flushed line never got a closing frame; it was
  2239. // billed incrementally, so push it directly (admit would re-bill).
  2240. // logsTruncated implies the hold is already empty (truncateLogs
  2241. // committed and cleared it), so this is reachable only when the run
  2242. // ends with the hold still open and untruncated.
  2243. if (openSealed.length > 0 || openParts.length > 0) {
  2244. logs.push(openSealed.join('') + openParts.join(''))
  2245. }
  2246. openSealed = []
  2247. openParts = []
  2248. if (child.pid === undefined) {
  2249. settle(result)
  2250. return
  2251. }
  2252. // Live child: SIGTERM→grace→SIGKILL, then let `close` (below) settle the
  2253. // run so any `done` frame buffered on fd 3 is handled first and the
  2254. // process is fully reaped before the fiber goes quiescent.
  2255. kill()
  2256. // `close` awaits every stdio stream draining, which a setsid-escaped
  2257. // orphan holding our inherited pipes can prevent forever. Bound that
  2258. // wait: after SIGKILL has had the grace window plus a margin to reap the
  2259. // child itself, force settlement on the decided result. Flush any
  2260. // newline-free stray residual FIRST — a leader that wrote a diagnostic
  2261. // with `os.write(1, ...)` and exited leaves it buffered, and destroying
  2262. // the stream below drops it before an `end`/`close` flush could run, so
  2263. // the diagnostic would be lost from `logs`. Detaching the stream handles
  2264. // then lets `close` land as a no-op if it ever arrives, and stops the
  2265. // orphan's stray output from being accounted against a run that already
  2266. // finished. `unref` so the deadline never keeps the host process alive.
  2267. closeDeadline = setTimeout(() => {
  2268. flushStray(strayOut)
  2269. flushStray(strayErr)
  2270. proto.destroy()
  2271. child.stdout.destroy()
  2272. child.stderr.destroy()
  2273. settle(result)
  2274. }, this.config.graceMs + CLOSE_REAP_MARGIN_MS)
  2275. closeDeadline.unref()
  2276. }
  2277. child.on('error', (error: Error) => {
  2278. finish({ error: { kind: 'worker-exit', message: `python spawn error: ${error.message}` } })
  2279. })
  2280. // `close` (not `exit`) is the settlement trigger: it fires only after the
  2281. // process exits AND every stdio stream — including the fd-3 protocol pipe —
  2282. // has drained, so a `done` frame the child wrote just before exiting is
  2283. // always handled before we settle. macOS can deliver `exit` before that
  2284. // final fd-3 data; keying off `close` makes the ordering irrelevant.
  2285. child.on('close', (code: number | null, signal: NodeJS.Signals | null) => {
  2286. // If done/timeout/abort already decided the result, finish() is a no-op
  2287. // and `decided` holds it — a SIGXCPU that arrives after a decision does
  2288. // not override it. Otherwise the child closed before completing: a
  2289. // SIGXCPU close is the kernel's own CPU meter firing — the RLIMIT_CPU
  2290. // soft limit, or the bootstrap's post-settlement getrusage check
  2291. // re-delivering SIGXCPU when a program trapped the soft limit and
  2292. // returned inside the soft-to-hard gap. That kernel-authoritative
  2293. // signal is the ONLY basis for the timeout classification: wall time
  2294. // is not evidence of CPU burn (a sleeping child SIGKILLed by a cgroup
  2295. // OOM killer, an operator, or itself consumed none), so every other
  2296. // signal or code — including an unsolicited SIGKILL, even the
  2297. // hard-limit one — reports as an opaque worker exit.
  2298. //
  2299. // The message names `cpuSeconds` as the CONFIGURED ceiling, not "the
  2300. // budget that fired": the child clamps RLIMIT_CPU to the stricter of
  2301. // `cpuSeconds` and any inherited soft limit, so under a tighter inherited
  2302. // cap SIGXCPU arrives before `cpuSeconds` — the host cannot see the
  2303. // effective value, so it states the ceiling it set rather than a second
  2304. // count it cannot guarantee.
  2305. finish(signal === 'SIGXCPU'
  2306. ? { error: { kind: 'timeout', message: `CPU time exhausted (limit at most the configured ${this.config.cpuSeconds}s; a stricter inherited RLIMIT_CPU can fire sooner)` } }
  2307. : { error: { kind: 'worker-exit', message: `python exited (code=${String(code)}, signal=${String(signal)}) before completing` } })
  2308. settle(decided)
  2309. })
  2310. // Fd-3 and the stdout/stderr pipes emit `error` on early child death
  2311. // (ECONNRESET/EPIPE); swallow them so they do not become uncaught. The
  2312. // authoritative failure signal is `child.on('close')` above.
  2313. const silenceStreamError = (): void => {}
  2314. proto.on('error', silenceStreamError)
  2315. child.stdout.on('error', silenceStreamError)
  2316. child.stderr.on('error', silenceStreamError)
  2317. /* jscpd:ignore-start -- wall-timer/abort/live-run wiring deliberately parallels code-runtime-worker; see the constructor note. */
  2318. const wallTimer = setTimeout(() => {
  2319. finish({ error: { kind: 'timeout', message: `wall-clock ceiling reached (${this.config.maxWallMs}ms)` } })
  2320. }, this.config.maxWallMs)
  2321. const onAbort = (): void => {
  2322. finish({ error: { kind: 'abort', message: messageOf(request.signal?.reason) } })
  2323. }
  2324. request.signal?.addEventListener('abort', onAbort, { once: true })
  2325. const live: LiveRun = {
  2326. kill,
  2327. finished,
  2328. settle: (failure: CodeRunFailure) => { finish({ error: failure }) },
  2329. }
  2330. this.live.add(live)
  2331. /* jscpd:ignore-end */
  2332. // Send the boot frame once fd 3 is writable. This runs LAST in run()'s
  2333. // synchronous setup: its failure path calls finish(), which reads
  2334. // wallTimer/onAbort and (through settle) live, so those bindings must
  2335. // already be initialized — issuing the write earlier hit their
  2336. // temporal dead zone and threw a ReferenceError that rejected run()
  2337. // instead of resolving the worker-exit it constructs here.
  2338. const boot: BootMessage = {
  2339. type: 'boot',
  2340. cpuSeconds: this.config.cpuSeconds,
  2341. addressSpaceBytes: this.config.addressSpaceMb * 1024 * 1024,
  2342. maxLogBytes: this.config.maxLogBytes,
  2343. maxValueBytes: this.config.maxValueBytes,
  2344. namespaces: [...bindings].map(([global, namespace]) => ({
  2345. global,
  2346. names: Object.keys(namespace.functions),
  2347. ...namespace.errorClass ? { errorClass: namespace.errorClass } : {},
  2348. })),
  2349. }
  2350. // The run frame is sent only after the child's boot-ack: the seam
  2351. // contract puts `run` after `boot-ack` (the ack confirms the namespaces
  2352. // were accepted), and sending it earlier would let a boot failure race
  2353. // the run frame. The ack handler below writes it.
  2354. let runSent = false
  2355. try {
  2356. proto.write(`${JSON.stringify(boot)}\n`)
  2357. } catch (error: unknown) {
  2358. finish({ error: { kind: 'worker-exit', message: `failed to boot python subprocess: ${messageOf(error)}` } })
  2359. return
  2360. }
  2361. // Register the ack gate with the frame handler before any data arrives.
  2362. bootAckGate.run = (): void => {
  2363. if (runSent) return
  2364. runSent = true
  2365. try {
  2366. proto.write(`${JSON.stringify({ type: 'run', program: request.program })}\n`)
  2367. } catch (error: unknown) {
  2368. /* v8 ignore next -- the child exited between its ack and this write; the run settles as worker-exit. */
  2369. finish({ error: { kind: 'worker-exit', message: `failed to boot python subprocess: ${messageOf(error)}` } })
  2370. }
  2371. }
  2372. })
  2373. }
  2374. }
  2375. export default PythonCodeRuntime