index.ts 123 KB

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