spawn.ts 21 KB

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