index.ts 110 KB

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