index.ts 121 KB

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