spawn.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /**
  2. * Process plumbing for the local subprocess service: detached process-tree
  3. * spawn with per-stream stdio dispositions, tail-keep collection with spill
  4. * files, tree-scoped signalling (POSIX groups; Windows taskkill), the
  5. * SIGTERM→SIGKILL escalation, and the cooperative EOF-first dispose ladder.
  6. * This layer reacts to an abort signal; callers own deadlines and classify
  7. * causes.
  8. * @module dsh-subprocess-local/spawn
  9. */
  10. import { type ChildProcess, spawn, spawnSync } from 'node:child_process'
  11. import type { Readable } from 'node:stream'
  12. import { randomBytes } from 'node:crypto'
  13. import { closeSync, mkdtempSync, openSync, unlinkSync, writeSync } from 'node:fs'
  14. import { tmpdir } from 'node:os'
  15. import { join } from 'node:path'
  16. import { setTimeout as sleepMs } from 'node:timers/promises'
  17. import { deadline } from '@deepseek-ai/dsh-timeout'
  18. import { DSH_ENV_PREFIX, scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess'
  19. import type {
  20. CollectedOutput,
  21. DshEnvironment,
  22. SubprocessCollect,
  23. SubprocessDisposeGraces,
  24. SubprocessHandle,
  25. SubprocessOutcome,
  26. SubprocessOutputMode,
  27. SubprocessSpawnSpec,
  28. } from '@deepseek-ai/dsh-subprocess'
  29. /**
  30. * Build a child environment from the scrubbed parent base, ordinary caller
  31. * entries, and a managed `DSH_*` snapshot. Ordinary and managed entries
  32. * reject the other channel's namespace before `dshEnv` merges last.
  33. * @param extra - caller entries; `DSH_*` names are rejected.
  34. * @param dshEnv - managed entries; non-`DSH_*` names are rejected.
  35. * @returns the environment to hand to `spawn` for the child process.
  36. */
  37. export function childEnv(
  38. extra?: Readonly<Record<string, string>>,
  39. dshEnv?: DshEnvironment,
  40. ): NodeJS.ProcessEnv {
  41. for (const key of Object.keys(extra ?? {})) {
  42. if (key.startsWith(DSH_ENV_PREFIX)) {
  43. throw new Error(`ordinary child env cannot set reserved variable "${key}"; use dshEnv`)
  44. }
  45. }
  46. for (const key of Object.keys(dshEnv ?? {})) {
  47. if (!key.startsWith(DSH_ENV_PREFIX)) {
  48. throw new Error(`managed child env cannot set ordinary variable "${key}"; use env`)
  49. }
  50. }
  51. return { ...scrubbedParentEnv(), ...extra, ...dshEnv }
  52. }
  53. /** Injectable knobs so tests can exercise spill and platform behavior deterministically. */
  54. export interface SpawnInternals {
  55. /** Directory for spill files (defaults to the OS temp dir). */
  56. spillDir?: string
  57. /** Windows tree-termination runner (defaults to `taskkill /PID <pid> /T /F`). */
  58. taskkill?: (pid: number) => void
  59. /** Host platform override for signalling decisions. */
  60. platform?: NodeJS.Platform
  61. }
  62. /** Timeout code marking a dispose-ladder tier bound (vs an external abort). */
  63. const DISPOSE_TIER_TIMEOUT = 'SUBPROCESS_DISPOSE_TIER'
  64. /**
  65. * Liveness-poll cadence for tree-exit waits. The timer stays ref'd: an
  66. * awaited teardown must keep the event loop alive until the tree really
  67. * exits, or the parent can exit while claiming quiescence and orphan the
  68. * survivors it promised to reap.
  69. */
  70. function sleepTick(): Promise<void> {
  71. return sleepMs(15)
  72. }
  73. let spillCounter = 0
  74. let defaultSpillDir: string | undefined
  75. /**
  76. * The default spill location: a private (0700) per-process directory under
  77. * the OS tmpdir, created lazily. Predictable world-readable paths would let
  78. * other local users read command output or pre-create symlinks.
  79. */
  80. function privateSpillDir(): string {
  81. defaultSpillDir ??= mkdtempSync(join(tmpdir(), 'dsh-subprocess-'))
  82. return defaultSpillDir
  83. }
  84. /**
  85. * Collects one stream with a bounded in-memory tail. With a spill cap, on
  86. * first overflow a spill file is created and every chunk (including those
  87. * already collected) is appended there while the full stream remains within
  88. * the cap; without one, only the in-memory tail is ever retained (the
  89. * diagnostic-tail shape — a language server's stderr).
  90. *
  91. * Tail-keep rationale (pi/OpenCode): errors and final results cluster at the
  92. * end of command output; the spill file covers the head.
  93. */
  94. export class OutputCollector {
  95. private chunks: Buffer[] = []
  96. private bytes = 0
  97. private dropped = false
  98. private spillFd: number | undefined
  99. private spillFile: string | undefined
  100. private spillDisabled: boolean
  101. /** Total bytes ever pushed (not just retained). */
  102. private total = 0
  103. constructor(
  104. private readonly maxBytes: number,
  105. private readonly maxSpillBytes: number | undefined,
  106. private readonly label: string,
  107. private readonly spillDir: string,
  108. ) {
  109. this.spillDisabled = maxSpillBytes === undefined
  110. }
  111. /**
  112. * Ingest one stream chunk, counting it toward the whole-stream total. On
  113. * first overflow of the in-memory cap a spill file is opened (when spilling
  114. * is enabled) and every chunk (already-collected ones included) is appended
  115. * there from then on; the in-memory tail then drops whole chunks from its
  116. * head (or the head of a single over-cap chunk) until it fits the cap again.
  117. * @param chunk - the raw bytes from one stream 'data' event.
  118. */
  119. push(chunk: Buffer): void {
  120. this.total += chunk.length
  121. const overflows = this.bytes + chunk.length > this.maxBytes
  122. if (!this.spillDisabled && (overflows || this.spillFd !== undefined)) this.spillAll(chunk)
  123. this.chunks.push(chunk)
  124. this.bytes += chunk.length
  125. while (this.bytes > this.maxBytes) {
  126. const head = this.chunks[0] as Buffer
  127. const excess = this.bytes - this.maxBytes
  128. if (head.length <= excess) {
  129. // Drop the whole head chunk (length ≥ 1 is guaranteed while over cap).
  130. this.chunks.shift()
  131. this.bytes -= head.length
  132. } else {
  133. // Trim the head so the retained window is byte-exact at the cap — a
  134. // diagnostic tail (an LSP server's stderr) must hold the LAST
  135. // maxBytes regardless of how the stream was chunked.
  136. this.chunks[0] = head.subarray(excess)
  137. this.bytes -= excess
  138. }
  139. this.dropped = true
  140. }
  141. }
  142. /** Open the spill file lazily and append `chunk` (and any prior chunks once). */
  143. private spillAll(chunk: Buffer): void {
  144. if (this.maxSpillBytes !== undefined && this.total > this.maxSpillBytes) {
  145. this.discardSpill()
  146. return
  147. }
  148. if (this.spillFd === undefined) {
  149. // Random suffix + O_EXCL + no-follow-equivalent ('wx' fails on any
  150. // existing path, symlink or not) + owner-only mode: defeats spill-path
  151. // prediction and symlink planting in shared tmp dirs.
  152. this.spillFile = join(
  153. this.spillDir,
  154. `dsh-subprocess-${process.pid}-${++spillCounter}-${randomBytes(6).toString('hex')}-${this.label}.log`,
  155. )
  156. this.spillFd = openSync(this.spillFile, 'wx', 0o600)
  157. for (const prior of this.chunks) writeSync(this.spillFd, prior)
  158. }
  159. writeSync(this.spillFd, chunk)
  160. }
  161. /** Stop spilling and remove the file once it can no longer hold the complete stream. */
  162. private discardSpill(): void {
  163. const fd = this.spillFd
  164. const file = this.spillFile
  165. this.spillFd = undefined
  166. this.spillFile = undefined
  167. this.spillDisabled = true
  168. if (fd !== undefined) {
  169. try {
  170. closeSync(fd)
  171. } catch {
  172. // Retain the descriptor so finalize can retry the failed close.
  173. this.spillFd = fd
  174. }
  175. }
  176. if (file !== undefined) {
  177. try {
  178. unlinkSync(file)
  179. } catch {
  180. // A failed unlink leaves at most maxSpillBytes behind, never an unbounded file.
  181. }
  182. }
  183. }
  184. /**
  185. * Incremental read in whole-stream byte coordinates: returns everything
  186. * pushed since `fromByte`. When `fromByte` has already slid out of the
  187. * in-memory tail window, the read is `lossy` — it returns the whole
  188. * retained tail and the gap is only recoverable from the spill file.
  189. * @param fromByte - whole-stream offset to resume from (a prior read's `nextOffset`; 0 for the first read).
  190. * @returns the delta text, the offset for the next read, the `lossy` flag, and the spill path when one was created.
  191. */
  192. readFrom(fromByte: number): { text: string; nextOffset: number; lossy: boolean; spillPath?: string } {
  193. const windowStart = this.total - this.bytes
  194. const buffer = Buffer.concat(this.chunks)
  195. const lossy = fromByte < windowStart
  196. const slice = lossy ? buffer : buffer.subarray(fromByte - windowStart)
  197. return {
  198. text: slice.toString('utf8'),
  199. nextOffset: this.total,
  200. lossy,
  201. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  202. }
  203. }
  204. /**
  205. * Close the spill file once the stream has ended. A failed close (delayed
  206. * writeback fault) stops advertising the spill path — the file may be
  207. * missing its tail — while every in-memory read keeps working. Idempotent;
  208. * the spawn path seals both collectors at settlement so reads after exit
  209. * never point at a still-open file.
  210. */
  211. seal(): void {
  212. if (this.spillFd === undefined) return
  213. try {
  214. closeSync(this.spillFd)
  215. } catch {
  216. // A delayed writeback failure makes the spill unreliable; keep the
  217. // in-memory result but stop advertising that file.
  218. this.spillFile = undefined
  219. }
  220. this.spillFd = undefined
  221. }
  222. /**
  223. * Seal the spill file and return the final output.
  224. * @returns the final collected output: tail text, truncation flag, and the spill path when intact.
  225. */
  226. finalize(): CollectedOutput {
  227. this.seal()
  228. return {
  229. text: Buffer.concat(this.chunks).toString('utf8'),
  230. truncated: this.dropped,
  231. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  232. }
  233. }
  234. }
  235. /**
  236. * Send `sig` to a detached POSIX process group. Never throws: delivery races
  237. * process exit and may run in a timer callback, so failures are contained and
  238. * a non-positive pid is a no-op.
  239. * @param pid - the group leader's pid; non-positive means the spawn failed and the call is a no-op.
  240. * @param sig - the signal to deliver to the whole group.
  241. */
  242. export function killGroup(pid: number, sig: NodeJS.Signals): void {
  243. if (pid <= 0) return
  244. try {
  245. process.kill(-pid, sig)
  246. } catch {
  247. // Swallow: see contract above.
  248. }
  249. }
  250. /**
  251. * Terminate one Windows process tree with `taskkill /T /F`. Contained like
  252. * POSIX group signalling — delivery races tree exit, so an absent tree, a
  253. * nonzero status, or a missing taskkill binary must not break idempotent
  254. * teardown.
  255. * @param pid - root process id; non-positive is a no-op.
  256. */
  257. export function taskkillProcessTree(pid: number): void {
  258. if (pid <= 0) return
  259. // Outcome deliberately unchecked: an already-absent tree (status 128), exit
  260. // races, and a missing taskkill binary (spawnSync reports, never throws) are
  261. // as tolerable here as ESRCH is for a POSIX group signal.
  262. spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' })
  263. }
  264. /**
  265. * Signal a detached process tree with platform-correct semantics: POSIX
  266. * signals the negative process-group id and falls back to the direct child
  267. * when the group is gone; Windows terminates the tree via taskkill (any
  268. * signal value force-terminates — Node maps signals to TerminateProcess).
  269. */
  270. function signalTree(
  271. platform: NodeJS.Platform,
  272. pid: number,
  273. sig: NodeJS.Signals,
  274. child: ChildProcess,
  275. taskkill: (pid: number) => void,
  276. ): void {
  277. if (platform === 'win32') {
  278. taskkill(pid)
  279. return
  280. }
  281. /* v8 ignore next -- kill/terminate gate on treeAlive(), which is false for pid -1; this guard protects direct callers only. */
  282. if (pid <= 0) return
  283. try {
  284. process.kill(-pid, sig)
  285. } catch {
  286. /* v8 ignore start -- the fallback needs a live child whose group signal fails
  287. (EPERM-style), which POSIX CI cannot stage; the swallow keeps teardown idempotent. */
  288. try {
  289. child.kill(sig)
  290. } catch {
  291. // The direct child already exited; teardown remains idempotent.
  292. }
  293. /* v8 ignore stop */
  294. }
  295. }
  296. /**
  297. * Spawn one isolated detached process tree with the spec's per-stream stdio
  298. * dispositions. Runtime exits resolve `done` as {@link SubprocessOutcome};
  299. * only spawn failures reject.
  300. * @param spec - fully resolved argv, cwd, stdio, grace, cancellation, environment.
  301. * @param internals - test-only spill-directory, platform, and taskkill overrides.
  302. * @returns live subprocess handle.
  303. */
  304. export function spawnSubprocess(spec: SubprocessSpawnSpec, internals: SpawnInternals = {}): SubprocessHandle {
  305. const spillDir = internals.spillDir ?? privateSpillDir()
  306. const platform = internals.platform ?? process.platform
  307. const taskkill = internals.taskkill ?? taskkillProcessTree
  308. if (spec.signal?.aborted) {
  309. throw new Error(`aborted before spawn: ${String(spec.signal.reason ?? 'aborted')}`)
  310. }
  311. const [program, ...args] = spec.argv
  312. if (program === undefined || program.length === 0) {
  313. throw new Error('invalid argv: expected a non-empty program name at argv[0]')
  314. }
  315. const isCollect = (mode: SubprocessOutputMode): mode is SubprocessCollect =>
  316. mode !== 'pipe' && mode !== 'inherit'
  317. const outMode = spec.stdio.stdout
  318. const errMode = spec.stdio.stderr
  319. const stdinMode = spec.stdio.stdin
  320. const env = childEnv(spec.env, spec.dshEnv)
  321. const child = spawn(program, args, {
  322. cwd: spec.cwd,
  323. env,
  324. stdio: [
  325. stdinMode === 'ignore' ? 'ignore' : 'pipe',
  326. outMode === 'inherit' ? 'inherit' : 'pipe',
  327. errMode === 'inherit' ? 'inherit' : 'pipe',
  328. ],
  329. // `detached` gives teardown a tree root on POSIX (its own process group);
  330. // Windows terminates by root pid through taskkill /T instead.
  331. detached: platform !== 'win32',
  332. })
  333. const collectStream = (mode: SubprocessOutputMode, stream: Readable | null, label: string): OutputCollector | undefined => {
  334. if (!isCollect(mode) || stream === null) return undefined
  335. const collector = new OutputCollector(mode.maxBytes, mode.spill?.maxBytes, label, spillDir)
  336. stream.on('data', (chunk: Buffer) => { collector.push(chunk) })
  337. return collector
  338. }
  339. const stdoutCollector = collectStream(outMode, child.stdout, 'stdout')
  340. const stderrCollector = collectStream(errMode, child.stderr, 'stderr')
  341. let graceTimer: NodeJS.Timeout | undefined
  342. let settled = false
  343. // Failed spawns use pid -1 so signalling remains a no-op.
  344. const pid = child.pid ?? -1
  345. /** Whether the detached tree's root (or POSIX group) is still alive. */
  346. const treeAlive = (): boolean => {
  347. if (pid <= 0) return false
  348. if (platform === 'win32') {
  349. // Windows has no group-liveness probe; the direct child's exit is the
  350. // observable boundary (taskkill /T already took the tree with it).
  351. return child.exitCode === null && child.signalCode === null
  352. }
  353. try {
  354. process.kill(-pid, 0)
  355. return true
  356. } catch (error) {
  357. const code = (error as NodeJS.ErrnoException).code
  358. /* v8 ignore next 2 -- POSIX reports an absent group as ESRCH; child-reaping timing
  359. makes observing the other arm platform-dependent. */
  360. if (code === 'ESRCH') return false
  361. /* v8 ignore start -- EPERM and non-POSIX negative-pid failures are platform defenses; CI runs
  362. tree-lifecycle tests on POSIX hosts where absence reports ESRCH. */
  363. if (code === 'EPERM') return true
  364. return child.exitCode === null && child.signalCode === null
  365. /* v8 ignore stop */
  366. }
  367. }
  368. const kill = (sig: NodeJS.Signals = 'SIGTERM'): void => {
  369. // Guard on TREE liveness, not outcome settlement: a TERM-trapping helper
  370. // can outlive the settled direct child and must stay signalable, while a
  371. // fully-dead tree (possible pid reuse) must not be re-signalled from a
  372. // caller's finally block.
  373. if (!treeAlive()) return
  374. signalTree(platform, pid, sig, child, taskkill)
  375. }
  376. const terminate = (): void => {
  377. if (graceTimer !== undefined) return // escalation already in flight
  378. if (!treeAlive()) return
  379. signalTree(platform, pid, 'SIGTERM', child, taskkill)
  380. // The escalation must survive direct-child settlement — the leader dying
  381. // does not mean the tree died — so settle does not clear this timer, and
  382. // it re-probes tree liveness before force-killing. It stays ref'd: the
  383. // pending SIGKILL is a commitment, and a parent exiting before it fires
  384. // would orphan a trapped survivor. Self-bounds at graceMs.
  385. graceTimer = setTimeout(() => {
  386. if (treeAlive()) signalTree(platform, pid, 'SIGKILL', child, taskkill)
  387. }, spec.graceMs)
  388. }
  389. // The caller owns timeout classification; this layer only reacts to abort.
  390. const onAbort = (): void => { terminate() }
  391. spec.signal?.addEventListener('abort', onAbort, { once: true })
  392. // Batch stdin is written and closed up front; process exit and captured
  393. // output remain authoritative, so write errors (EPIPE) are best-effort.
  394. if (typeof stdinMode === 'object' && child.stdin !== null) {
  395. child.stdin.on('error', () => { /* stdin write is best-effort; outcome rides on exit/output. */ })
  396. child.stdin.end(stdinMode.data)
  397. }
  398. const done = new Promise<SubprocessOutcome>((resolve, reject) => {
  399. let pipeDrainTimer: NodeJS.Timeout | undefined
  400. const settle = (exitCode: number | null, signal: NodeJS.Signals | null): void => {
  401. if (settled) return
  402. settled = true
  403. // Only harness-collected pipes are force-closed at the drain boundary;
  404. // a 'pipe'-mode stream belongs to the caller and closes with the child.
  405. if (stdoutCollector !== undefined) child.stdout?.destroy()
  406. if (stderrCollector !== undefined) child.stderr?.destroy()
  407. stdoutCollector?.seal()
  408. stderrCollector?.seal()
  409. cleanup()
  410. resolve({ exitCode, signal })
  411. }
  412. child.on('error', (error) => {
  413. // No meaningful close outcome follows a spawn failure.
  414. settled = true
  415. cleanup()
  416. reject(error)
  417. })
  418. child.on('exit', (exitCode, signal) => {
  419. // A surviving descendant that inherited a pipe must not hold the
  420. // outcome open indefinitely: after exit, the same bounded grace that
  421. // governs kills also bounds the close wait.
  422. pipeDrainTimer = setTimeout(() => { settle(exitCode, signal) }, spec.graceMs)
  423. })
  424. child.on('close', settle)
  425. function cleanup(): void {
  426. // graceTimer deliberately NOT cleared: the SIGKILL escalation must be
  427. // able to reach tree survivors after the direct child settles.
  428. if (pipeDrainTimer !== undefined) clearTimeout(pipeDrainTimer)
  429. spec.signal?.removeEventListener('abort', onAbort)
  430. }
  431. })
  432. const waitForExit = async (signal?: AbortSignal): Promise<boolean> => {
  433. while (treeAlive()) {
  434. if (signal?.aborted) return false
  435. await sleepTick()
  436. }
  437. return true
  438. }
  439. /**
  440. * Wait, bounded, for whole-tree exit — the dispose ladder's quiescence test.
  441. * Tree liveness, not direct-child settlement: a TERM-trapping helper that
  442. * outlives the leader must hold the ladder on its tier until it exits.
  443. */
  444. const treeExitsWithin = async (ms: number): Promise<boolean> => {
  445. using bound = deadline(undefined, ms, DISPOSE_TIER_TIMEOUT)
  446. return await waitForExit(bound.signal)
  447. }
  448. let disposal: Promise<void> | undefined
  449. const dispose = (graces: SubprocessDisposeGraces): Promise<void> => (disposal ??= (async () => {
  450. // A spawn failure has no process to tear down; observe the rejection so
  451. // disposal in a finally block cannot surface it as unhandled.
  452. if (pid <= 0) {
  453. await done.catch(() => {})
  454. return
  455. }
  456. // 1. Close a piped stdin and allow cooperative teardown and flush.
  457. if (stdinMode === 'pipe') child.stdin?.end()
  458. if (await treeExitsWithin(graces.eofGraceMs)) return
  459. // 2. POSIX gets a catchable graceful signal; Windows taskkill force-terminates.
  460. if (platform !== 'win32') {
  461. kill('SIGTERM')
  462. if (await treeExitsWithin(graces.graceMs)) return
  463. }
  464. // 3. Force-kill the tree and await a bounded exit edge.
  465. kill('SIGKILL')
  466. if (!(await treeExitsWithin(graces.graceMs))) {
  467. throw new Error(`child process tree did not exit within ${graces.graceMs}ms after forced termination`)
  468. }
  469. })())
  470. return {
  471. pid,
  472. /* v8 ignore start -- pipe-mode fds exist on every spawn Node returns; the null-coalesces guard a nonconforming ChildProcess only. */
  473. stdin: stdinMode === 'pipe' ? child.stdin ?? undefined : undefined,
  474. stdout: outMode === 'pipe' ? child.stdout ?? undefined : undefined,
  475. stderr: errMode === 'pipe' ? child.stderr ?? undefined : undefined,
  476. /* v8 ignore stop */
  477. collected: {
  478. ...stdoutCollector !== undefined ? { stdout: stdoutCollector } : {},
  479. ...stderrCollector !== undefined ? { stderr: stderrCollector } : {},
  480. },
  481. done,
  482. kill,
  483. terminate,
  484. waitForExit,
  485. dispose,
  486. }
  487. }