spawn.ts 19 KB

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