spawn.spec.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. import { mkdtempSync, readFileSync, statSync, unlinkSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { dirname, join } from 'node:path'
  4. import { describe, expect, it, vi } from 'vitest'
  5. import type { DshEnvironment } from '@deepseek-ai/dsh-subprocess'
  6. import { killGroup, OutputCollector, spawnSubprocess, taskkillProcessTree } from '../src/spawn.ts'
  7. import type { SubprocessHandle, SubprocessOutputReader } from '@deepseek-ai/dsh-subprocess'
  8. const { failNextClose, failNextUnlink } = vi.hoisted(() => ({
  9. failNextClose: { value: false },
  10. failNextUnlink: { value: false },
  11. }))
  12. vi.mock('node:fs', async (importOriginal) => {
  13. const actual = await importOriginal<typeof import('node:fs')>()
  14. return {
  15. ...actual,
  16. closeSync(fd: number): void {
  17. if (failNextClose.value) {
  18. failNextClose.value = false
  19. throw Object.assign(new Error('simulated EIO on close'), { code: 'EIO' })
  20. }
  21. actual.closeSync(fd)
  22. },
  23. unlinkSync(path: Parameters<typeof actual.unlinkSync>[0]): void {
  24. if (failNextUnlink.value) {
  25. failNextUnlink.value = false
  26. throw Object.assign(new Error('simulated EIO on unlink'), { code: 'EIO' })
  27. }
  28. actual.unlinkSync(path)
  29. },
  30. }
  31. })
  32. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-subprocess-spec-'))
  33. type SpecOverrides = Partial<Parameters<typeof spawnSubprocess>[0]> & {
  34. stdoutMaxBytes?: number
  35. stderrMaxBytes?: number
  36. maxSpillBytes?: number
  37. stdin?: string
  38. }
  39. function spec(command: string, overrides: SpecOverrides = {}) {
  40. const { stdoutMaxBytes = 64_000, stderrMaxBytes = 64_000, maxSpillBytes = 64 * 1024 * 1024, stdin, ...rest } = overrides
  41. return {
  42. argv: ['bash', '-c', command],
  43. cwd: process.cwd(),
  44. stdio: {
  45. stdin: stdin !== undefined ? { data: stdin } : 'ignore' as const,
  46. stdout: { maxBytes: stdoutMaxBytes, spill: { maxBytes: maxSpillBytes } },
  47. stderr: { maxBytes: stderrMaxBytes, spill: { maxBytes: maxSpillBytes } },
  48. },
  49. graceMs: 3_000,
  50. ...rest,
  51. }
  52. }
  53. /** Poll until a pid no longer exists (kill(pid, 0) throws ESRCH). */
  54. async function waitGone(pid: number, timeoutMs = 5_000): Promise<void> {
  55. const deadline = Date.now() + timeoutMs
  56. while (Date.now() < deadline) {
  57. try {
  58. process.kill(pid, 0)
  59. } catch {
  60. return
  61. }
  62. await new Promise(resolve => setTimeout(resolve, 20))
  63. }
  64. throw new Error(`pid ${pid} still alive after ${timeoutMs}ms`)
  65. }
  66. async function waitForStdout(running: SubprocessHandle, expected: string, timeoutMs = 5_000): Promise<void> {
  67. const deadline = Date.now() + timeoutMs
  68. while (Date.now() < deadline) {
  69. if (running.collected.stdout!.readFrom(0).text.includes(expected)) return
  70. await new Promise(resolve => setTimeout(resolve, 20))
  71. }
  72. throw new Error(`stdout did not include ${JSON.stringify(expected)} after ${timeoutMs}ms`)
  73. }
  74. /** Await settlement and project both collected streams like a batch outcome. */
  75. async function finish(running: SubprocessHandle) {
  76. const outcome = await running.done
  77. const final = (reader: SubprocessOutputReader | undefined) => {
  78. const read = reader!.readFrom(0)
  79. return { text: read.text, truncated: read.lossy, ...read.spillPath !== undefined ? { spillPath: read.spillPath } : {} }
  80. }
  81. return { ...outcome, stdout: final(running.collected.stdout), stderr: final(running.collected.stderr) }
  82. }
  83. async function waitForPidFile(path: string, timeoutMs = 5_000): Promise<number> {
  84. const deadline = Date.now() + timeoutMs
  85. while (Date.now() < deadline) {
  86. try {
  87. const pid = Number(readFileSync(path, 'utf8').trim())
  88. if (Number.isSafeInteger(pid) && pid > 0) return pid
  89. } catch {
  90. // The child shell has not written the pid file yet.
  91. }
  92. await new Promise(resolve => setTimeout(resolve, 20))
  93. }
  94. throw new Error(`pid file ${path} was not written after ${timeoutMs}ms`)
  95. }
  96. describe('spawnSubprocess', () => {
  97. it('captures stdout on success', async () => {
  98. const result = await finish(spawnSubprocess(spec('echo hello')))
  99. expect(result.exitCode).toBe(0)
  100. expect(result.signal).toBeNull()
  101. expect(result.stdout.text).toBe('hello\n')
  102. expect(result.stdout.truncated).toBe(false)
  103. expect(result.stderr.text).toBe('')
  104. })
  105. it('captures stderr separately', async () => {
  106. const result = await finish(spawnSubprocess(spec('echo oops >&2')))
  107. expect(result.exitCode).toBe(0)
  108. expect(result.stdout.text).toBe('')
  109. expect(result.stderr.text).toBe('oops\n')
  110. })
  111. it('captures both streams', async () => {
  112. const result = await finish(spawnSubprocess(spec('echo out; echo err >&2')))
  113. expect(result.stdout.text).toBe('out\n')
  114. expect(result.stderr.text).toBe('err\n')
  115. })
  116. it('reports non-zero exit codes', async () => {
  117. const result = await finish(spawnSubprocess(spec('exit 42')))
  118. expect(result.exitCode).toBe(42)
  119. expect(result.signal).toBeNull()
  120. })
  121. it('passes the ambient TERM through untouched (terminal policy is the caller\'s)', async () => {
  122. const result = await finish(spawnSubprocess(spec('echo "${TERM:-unset}"', {
  123. env: { TERM: 'callers-choice' },
  124. })))
  125. expect(result.stdout.text).toBe('callers-choice\n')
  126. })
  127. it('runs in the requested cwd', async () => {
  128. const result = await finish(spawnSubprocess(spec('pwd', { cwd: '/tmp' })))
  129. expect(result.stdout.text.trim()).toMatch(/\/tmp$/)
  130. })
  131. it('kills the process group with SIGTERM when the signal fires', async () => {
  132. // spawnSubprocess owns no timer: it kills on abort. The bash executor drives the timeout
  133. // by firing this signal via a deadline (see executor.spec.ts); here we
  134. // assert the kill itself lands as SIGTERM.
  135. const controller = new AbortController()
  136. const start = Date.now()
  137. const running = spawnSubprocess(spec('sleep 60', { signal: controller.signal }))
  138. setTimeout(() => { controller.abort('deadline') }, 100)
  139. const result = await running.done
  140. expect(Date.now() - start).toBeLessThan(5_000)
  141. expect(result.signal).toBe('SIGTERM')
  142. expect(result.exitCode).toBeNull()
  143. })
  144. it('terminate() escalates to SIGKILL when SIGTERM is trapped', async () => {
  145. const running = spawnSubprocess(spec('trap \'\' TERM; echo ready; while :; do sleep 60 & wait $!; done', { graceMs: 200 }))
  146. await waitForStdout(running, 'ready\n')
  147. running.terminate()
  148. const result = await running.done
  149. expect(result.signal).toBe('SIGKILL')
  150. })
  151. it('terminates the whole process group (grandchildren die too)', async () => {
  152. // The subshell writes the sleep's pid then waits on it; terminating the
  153. // group must take the sleep down with bash.
  154. const pidFile = join(spillDir, `grandchild-${Date.now()}.pid`)
  155. const running = spawnSubprocess(spec(`sleep 60 & echo $! > ${pidFile}; wait`))
  156. const grandchild = await waitForPidFile(pidFile)
  157. expect(grandchild).toBeGreaterThan(0)
  158. running.terminate()
  159. const result = await running.done
  160. expect(result.signal).toBe('SIGTERM')
  161. await waitGone(grandchild)
  162. })
  163. it('aborts via AbortSignal mid-run', async () => {
  164. const controller = new AbortController()
  165. const running = spawnSubprocess(spec('sleep 60', { signal: controller.signal }))
  166. setTimeout(() => { controller.abort('user cancelled') }, 50)
  167. const result = await running.done
  168. expect(result.signal).toBe('SIGTERM')
  169. })
  170. it('throws when the signal is already aborted before spawn', () => {
  171. const controller = new AbortController()
  172. controller.abort('too late')
  173. expect(() => spawnSubprocess(spec('echo hi', { signal: controller.signal })))
  174. .toThrow(/aborted before spawn: too late/)
  175. })
  176. it('rejects with a spawn error for a nonexistent cwd', async () => {
  177. await expect(spawnSubprocess(spec('echo hi', { cwd: '/nonexistent-dir-dsh-test' })).done)
  178. .rejects.toThrow(/ENOENT/)
  179. })
  180. it('terminate() is idempotent (second call does not restart escalation)', async () => {
  181. const running = spawnSubprocess(spec('sleep 60'))
  182. running.terminate()
  183. running.terminate()
  184. const result = await running.done
  185. expect(result.signal).toBe('SIGTERM')
  186. })
  187. it('bounds inherited-pipe draining after the shell exits', async () => {
  188. const pidFile = join(spillDir, `pipe-holder-${Date.now()}.pid`)
  189. const started = Date.now()
  190. const running = spawnSubprocess(spec(`sleep 60 & echo $! > ${pidFile}; echo shell-done`, { graceMs: 100 }))
  191. const descendant = await waitForPidFile(pidFile)
  192. try {
  193. const result = await finish(running)
  194. expect(Date.now() - started).toBeLessThan(1_000)
  195. expect(result.exitCode).toBe(0)
  196. expect(result.stdout.text).toBe('shell-done\n')
  197. } finally {
  198. process.kill(descendant, 'SIGKILL')
  199. await waitGone(descendant)
  200. }
  201. })
  202. })
  203. describe('stdin and extra env (set by in-process plugins)', () => {
  204. it('writes stdin to the command and closes it', async () => {
  205. const result = await finish(spawnSubprocess(spec('cat', { stdin: 'hello from stdin\n' })))
  206. expect(result.exitCode).toBe(0)
  207. expect(result.stdout.text).toBe('hello from stdin\n')
  208. })
  209. it('a command that reads stdin sees EOF when none is supplied', async () => {
  210. // No stdin → fd 0 is /dev/null, so `cat` reads EOF and exits 0 with no
  211. // output (it does NOT block).
  212. const result = await finish(spawnSubprocess(spec('cat')))
  213. expect(result.exitCode).toBe(0)
  214. expect(result.stdout.text).toBe('')
  215. })
  216. it('gives fd 0 the exact pre-seam type: /dev/null when no stdin, a pipe when supplied', async () => {
  217. // With no bytes, fd 0 remains the pre-seam `ignore` default (/dev/null, a character device).
  218. // Supplied bytes use Node's spawn pipe, which is an AF_UNIX socket rather than a FIFO.
  219. const none = await finish(spawnSubprocess(spec('test -c /dev/stdin && echo char || echo other')))
  220. expect(none.stdout.text).toBe('char\n')
  221. const piped = await finish(spawnSubprocess(spec('test -S /dev/stdin && echo socket || echo other', { stdin: 'x' })))
  222. expect(piped.stdout.text).toBe('socket\n')
  223. })
  224. it('merges ordinary extra env entries onto the scrubbed environment', async () => {
  225. const result = await finish(spawnSubprocess(spec('echo "$EXTRA_ONE/$EXTRA_TWO"', {
  226. env: { EXTRA_ONE: 'alpha', EXTRA_TWO: 'beta' },
  227. })))
  228. expect(result.stdout.text).toBe('alpha/beta\n')
  229. })
  230. it('an explicit extra env entry overrides the credential scrub', async () => {
  231. // EXPLICIT_OVERRIDE_KEY matches the credential scrub pattern, yet an explicit
  232. // entry is still honored — the scrub only drops AMBIENT process.env creds.
  233. const result = await finish(spawnSubprocess(spec('echo "$EXPLICIT_OVERRIDE_KEY"', {
  234. env: { EXPLICIT_OVERRIDE_KEY: 'explicit-wins' },
  235. })))
  236. expect(result.stdout.text).toBe('explicit-wins\n')
  237. })
  238. it('does not crash or reject when the child ignores a large stdin (EPIPE)', async () => {
  239. // The child exits without reading, so closing a stdin pipe holding ~1 MiB triggers EPIPE.
  240. // The handler swallows that write error and `done` reports the child's real exit.
  241. const big = 'x'.repeat(1024 * 1024)
  242. const result = await finish(spawnSubprocess(spec('exit 7', { stdin: big })))
  243. expect(result.exitCode).toBe(7)
  244. })
  245. })
  246. describe('output truncation and spill', () => {
  247. it('applies stdout and stderr caps independently', async () => {
  248. const result = await finish(spawnSubprocess(
  249. spec('printf "%.0sx" $(seq 1 500); printf "%.0se" $(seq 1 500) >&2', {
  250. stdoutMaxBytes: 500,
  251. stderrMaxBytes: 100,
  252. }),
  253. { spillDir },
  254. ))
  255. expect(result.stdout.truncated).toBe(false)
  256. expect(result.stdout.text).toBe('x'.repeat(500))
  257. expect(result.stderr.truncated).toBe(true)
  258. expect(result.stderr.text.length).toBeLessThanOrEqual(100)
  259. })
  260. it('keeps the tail and spills the full stream to disk', async () => {
  261. // 200 numbered lines of ~10 bytes; cap at 500 bytes keeps a late tail.
  262. const result = await finish(spawnSubprocess(
  263. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  264. { spillDir },
  265. ))
  266. expect(result.stdout.truncated).toBe(true)
  267. expect(result.stdout.text.length).toBeLessThanOrEqual(500)
  268. expect(result.stdout.text).toContain('line-0200')
  269. expect(result.stdout.text).not.toContain('line-0001')
  270. expect(result.stdout.spillPath).toBeDefined()
  271. const full = readFileSync(result.stdout.spillPath!, 'utf8')
  272. expect(full).toContain('line-0001')
  273. expect(full).toContain('line-0200')
  274. })
  275. it('does not truncate output exactly at the cap', async () => {
  276. const result = await finish(spawnSubprocess(
  277. spec('printf "%.0sx" $(seq 1 500)', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  278. { spillDir },
  279. ))
  280. expect(result.stdout.truncated).toBe(false)
  281. expect(result.stdout.text.length).toBe(500)
  282. expect(result.stdout.spillPath).toBeUndefined()
  283. })
  284. it('settles with the tail and no spill path when final spill close fails', async () => {
  285. failNextClose.value = true
  286. const result = await finish(spawnSubprocess(
  287. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  288. { spillDir },
  289. ))
  290. expect(failNextClose.value).toBe(false)
  291. expect(result.exitCode).toBe(0)
  292. expect(result.stdout.truncated).toBe(true)
  293. expect(result.stdout.text).toContain('line-0200')
  294. expect(result.stdout.spillPath).toBeUndefined()
  295. })
  296. })
  297. describe('OutputCollector', () => {
  298. it('keeps the tail of a single oversized chunk', () => {
  299. const collector = new OutputCollector(10, 100, 'test', spillDir)
  300. collector.push(Buffer.from('0123456789abcdef'))
  301. const out = collector.finalize()
  302. expect(out.text).toBe('6789abcdef')
  303. expect(out.truncated).toBe(true)
  304. expect(readFileSync(out.spillPath!, 'utf8')).toBe('0123456789abcdef')
  305. })
  306. it('retains a byte-exact tail across uneven chunk boundaries', () => {
  307. // A diagnostic tail must be exactly the LAST maxBytes regardless of
  308. // chunking; dropping only whole chunks would under-retain.
  309. const collector = new OutputCollector(10, undefined, 'exact-tail', spillDir)
  310. collector.push(Buffer.from('aaaa'))
  311. collector.push(Buffer.from('bbbbbb'))
  312. collector.push(Buffer.from('cc'))
  313. const out = collector.finalize()
  314. expect(out.text).toBe('aabbbbbbcc')
  315. expect(Buffer.byteLength(out.text)).toBe(10)
  316. expect(out.truncated).toBe(true)
  317. })
  318. it('readFrom returns increments and flags lossy reads', () => {
  319. const collector = new OutputCollector(10, 100, 'test', spillDir)
  320. collector.push(Buffer.from('aaaaa'))
  321. const first = collector.readFrom(0)
  322. expect(first.text).toBe('aaaaa')
  323. expect(first.lossy).toBe(false)
  324. expect(first.nextOffset).toBe(5)
  325. collector.push(Buffer.from('bbbbb'))
  326. const second = collector.readFrom(first.nextOffset)
  327. expect(second.text).toBe('bbbbb')
  328. expect(second.lossy).toBe(false)
  329. // Push enough to slide the window past the last offset.
  330. collector.push(Buffer.from('c'.repeat(20)))
  331. const third = collector.readFrom(second.nextOffset)
  332. expect(third.lossy).toBe(true)
  333. expect(third.text).toBe('c'.repeat(10))
  334. expect(third.spillPath).toBeDefined()
  335. })
  336. it('contains close failures and drops the spill path', () => {
  337. const collector = new OutputCollector(4, 100, 'closefail', spillDir)
  338. collector.push(Buffer.from('aaaa'))
  339. collector.push(Buffer.from('bbbb'))
  340. expect(collector.readFrom(0).spillPath).toBeDefined()
  341. failNextClose.value = true
  342. let out: ReturnType<typeof collector.finalize>
  343. expect(() => { out = collector.finalize() }).not.toThrow()
  344. expect(failNextClose.value).toBe(false)
  345. expect(out!.text).toBe('bbbb')
  346. expect(out!.truncated).toBe(true)
  347. expect(out!.spillPath).toBeUndefined()
  348. })
  349. it('discards a spill that exceeds its configured cap', () => {
  350. const collector = new OutputCollector(4, 8, 'bounded', spillDir)
  351. collector.push(Buffer.from('aaaa'))
  352. collector.push(Buffer.from('bbbb'))
  353. const spillPath = collector.readFrom(0).spillPath!
  354. expect(readFileSync(spillPath, 'utf8')).toBe('aaaabbbb')
  355. collector.push(Buffer.from('c'))
  356. collector.push(Buffer.from('dddd'))
  357. const out = collector.finalize()
  358. expect(out.text).toBe('dddd')
  359. expect(out.truncated).toBe(true)
  360. expect(out.spillPath).toBeUndefined()
  361. expect(() => readFileSync(spillPath)).toThrow()
  362. })
  363. it('does not create a spill when the first overflowing chunk exceeds the cap', () => {
  364. const collector = new OutputCollector(4, 4, 'no-spill', spillDir)
  365. collector.push(Buffer.from('abcdefgh'))
  366. const out = collector.finalize()
  367. expect(out.text).toBe('efgh')
  368. expect(out.truncated).toBe(true)
  369. expect(out.spillPath).toBeUndefined()
  370. })
  371. it('contains cleanup failures while disabling an oversize spill', () => {
  372. const collector = new OutputCollector(4, 8, 'cleanup-fail', spillDir)
  373. collector.push(Buffer.from('aaaa'))
  374. collector.push(Buffer.from('bbbb'))
  375. const spillPath = collector.readFrom(0).spillPath!
  376. failNextClose.value = true
  377. failNextUnlink.value = true
  378. expect(() => { collector.push(Buffer.from('c')) }).not.toThrow()
  379. expect(failNextClose.value).toBe(false)
  380. expect(failNextUnlink.value).toBe(false)
  381. expect(collector.finalize().spillPath).toBeUndefined()
  382. unlinkSync(spillPath)
  383. })
  384. })
  385. describe('killGroup', () => {
  386. it('ignores non-positive pids', () => {
  387. expect(() => { killGroup(-1, 'SIGTERM') }).not.toThrow()
  388. expect(() => { killGroup(0, 'SIGTERM') }).not.toThrow()
  389. })
  390. it('swallows ESRCH for vanished groups', async () => {
  391. const running = spawnSubprocess(spec('true'))
  392. await running.done
  393. expect(() => { killGroup(running.pid, 'SIGTERM') }).not.toThrow()
  394. })
  395. })
  396. describe('stdio dispositions', () => {
  397. it("'pipe' exposes raw streams for caller-owned protocol decoding", async () => {
  398. const running = spawnSubprocess({
  399. ...spec('cat'),
  400. stdio: { stdin: 'pipe', stdout: 'pipe', stderr: { maxBytes: 1000 } },
  401. })
  402. expect(running.stdin).toBeDefined()
  403. expect(running.stdout).toBeDefined()
  404. expect(running.stderr).toBeUndefined()
  405. expect(running.collected.stdout).toBeUndefined()
  406. expect(running.collected.stderr).toBeDefined()
  407. const echoed = new Promise<string>((resolve) => {
  408. let text = ''
  409. running.stdout!.on('data', (chunk: Buffer) => { text += chunk.toString('utf8') })
  410. running.stdout!.on('end', () => { resolve(text) })
  411. })
  412. running.stdin!.end('through the pipe\n')
  413. const outcome = await running.done
  414. expect(outcome.exitCode).toBe(0)
  415. expect(await echoed).toBe('through the pipe\n')
  416. })
  417. it('a collect mode without spill keeps only the in-memory tail (no file)', async () => {
  418. const running = spawnSubprocess({
  419. ...spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done'),
  420. stdio: { stdin: 'ignore', stdout: { maxBytes: 100 }, stderr: { maxBytes: 100 } },
  421. }, { spillDir })
  422. await running.done
  423. const read = running.collected.stdout!.readFrom(0)
  424. expect(read.lossy).toBe(true)
  425. expect(read.text).toContain('line-0200')
  426. expect(read.spillPath).toBeUndefined()
  427. })
  428. })
  429. describe('dispose ladder', () => {
  430. it('tier 1: a cooperative child exits on stdin EOF without any signal', async () => {
  431. const running = spawnSubprocess({
  432. ...spec('read -r line; exit 0'),
  433. stdio: { stdin: 'pipe', stdout: { maxBytes: 1000 }, stderr: { maxBytes: 1000 } },
  434. })
  435. await running.dispose({ eofGraceMs: 5_000, graceMs: 200 })
  436. const outcome = await running.done
  437. expect(outcome.exitCode).toBe(0)
  438. expect(outcome.signal).toBeNull()
  439. })
  440. it('tier 2: an EOF-deaf child dies by SIGTERM', async () => {
  441. const running = spawnSubprocess({
  442. ...spec('sleep 60'),
  443. stdio: { stdin: 'pipe', stdout: { maxBytes: 1000 }, stderr: { maxBytes: 1000 } },
  444. })
  445. await running.dispose({ eofGraceMs: 100, graceMs: 5_000 })
  446. const outcome = await running.done
  447. expect(outcome.signal).toBe('SIGTERM')
  448. })
  449. it('tier 3: a TERM-trapping child dies by SIGKILL, and dispose() is idempotent', async () => {
  450. const running = spawnSubprocess(spec('trap \'\' TERM; echo armed; sleep 60'))
  451. await waitForStdout(running, 'armed\n')
  452. const first = running.dispose({ eofGraceMs: 50, graceMs: 200 })
  453. const second = running.dispose({ eofGraceMs: 50, graceMs: 200 })
  454. expect(second).toBe(first)
  455. await first
  456. const outcome = await running.done
  457. expect(outcome.signal).toBe('SIGKILL')
  458. })
  459. })
  460. describe('windows tree semantics (injected platform)', () => {
  461. it('terminate routes through taskkill by root pid', async () => {
  462. const killed: number[] = []
  463. const running = spawnSubprocess(spec('sleep 60', { graceMs: 100 }), {
  464. spillDir,
  465. platform: 'win32',
  466. taskkill: (pid) => {
  467. killed.push(pid)
  468. // Simulate the forced tree termination taskkill performs.
  469. try {
  470. process.kill(pid, 'SIGKILL')
  471. } catch {
  472. // Already gone — matches taskkill's tolerated not-found status.
  473. }
  474. },
  475. })
  476. running.terminate()
  477. const outcome = await running.done
  478. expect(killed).toContain(running.pid)
  479. expect(outcome.signal).toBe('SIGKILL')
  480. })
  481. it('waitForExit falls back to direct-child liveness where groups do not exist', async () => {
  482. const running = spawnSubprocess(spec('true'), { spillDir, platform: 'win32', taskkill: () => {} })
  483. await running.done
  484. await expect(running.waitForExit()).resolves.toBe(true)
  485. })
  486. })
  487. describe('waitForExit', () => {
  488. it('waits for the whole detached tree, not just the shell', async () => {
  489. const pidFile = join(spillDir, `tree-wait-${Date.now()}.pid`)
  490. const running = spawnSubprocess(spec(`sleep 60 & echo $! > ${pidFile}; wait`))
  491. const grandchild = await waitForPidFile(pidFile)
  492. running.terminate()
  493. await running.done
  494. await expect(running.waitForExit()).resolves.toBe(true)
  495. await expect(waitGone(grandchild, 100)).resolves.toBeUndefined()
  496. })
  497. it('an aborted wait reports false while the tree lives', async () => {
  498. const running = spawnSubprocess(spec('sleep 60'))
  499. const controller = new AbortController()
  500. controller.abort()
  501. await expect(running.waitForExit(controller.signal)).resolves.toBe(false)
  502. running.terminate()
  503. await running.done
  504. })
  505. })
  506. describe('tree-survivor escalation (terminate/dispose reach helpers the leader left behind)', () => {
  507. it('terminate() SIGKILLs a TERM-trapping descendant after the direct child settles', async () => {
  508. // The leader spawns a TERM-trapping helper with all stdio detached from
  509. // the collected pipes, then exits: the helper holds the GROUP alive while
  510. // the direct child settles. The escalation must still reach it.
  511. const pidFile = join(spillDir, `survivor-${Date.now()}.pid`)
  512. const running = spawnSubprocess(spec(
  513. `bash -c 'trap "" TERM; echo $$ > ${pidFile}; sleep 60' >/dev/null 2>&1 & disown; wait_placeholder=; exit 0`,
  514. { graceMs: 300 },
  515. ))
  516. const helper = await waitForPidFile(pidFile)
  517. await running.done // direct child settled; helper survives in the group
  518. expect(() => process.kill(helper, 0)).not.toThrow()
  519. running.terminate() // SIGTERM (trapped) → grace → SIGKILL the group
  520. await expect(running.waitForExit()).resolves.toBe(true)
  521. await waitGone(helper)
  522. })
  523. it('dispose() holds each tier on whole-tree exit, not direct-child settlement', async () => {
  524. const pidFile = join(spillDir, `survivor-dispose-${Date.now()}.pid`)
  525. const running = spawnSubprocess(spec(
  526. `bash -c 'trap "" TERM; echo $$ > ${pidFile}; sleep 60' >/dev/null 2>&1 & disown; exit 0`,
  527. { graceMs: 200 },
  528. ))
  529. const helper = await waitForPidFile(pidFile)
  530. await running.done
  531. expect(() => process.kill(helper, 0)).not.toThrow()
  532. await running.dispose({ eofGraceMs: 100, graceMs: 300 })
  533. // The ladder only returns once the WHOLE tree is gone.
  534. expect(() => process.kill(helper, 0)).toThrow()
  535. })
  536. it('service teardown awaits tree survivors, not just handle settlement', async () => {
  537. const { Context } = await import('cordis')
  538. const { default: LocalSubprocessService } = await import('@deepseek-ai/dsh-subprocess-local')
  539. const ctx = new Context()
  540. const fiber = await ctx.plugin(LocalSubprocessService)
  541. ;(ctx.subprocess as InstanceType<typeof LocalSubprocessService>).internals = { spillDir }
  542. const pidFile = join(spillDir, `survivor-svc-${Date.now()}.pid`)
  543. const running = ctx.subprocess.spawn(spec(
  544. `bash -c 'trap "" TERM; echo $$ > ${pidFile}; sleep 60' >/dev/null 2>&1 & disown; exit 0`,
  545. { graceMs: 200 },
  546. ))
  547. const helper = await waitForPidFile(pidFile)
  548. await running.done
  549. await fiber.dispose()
  550. // Teardown itself waited for the survivor to die.
  551. expect(() => process.kill(helper, 0)).toThrow()
  552. })
  553. })
  554. describe('coverage seams', () => {
  555. it('taskkillProcessTree ignores non-positive pids and contains a missing binary', () => {
  556. expect(() => { taskkillProcessTree(-1) }).not.toThrow()
  557. expect(() => { taskkillProcessTree(0) }).not.toThrow()
  558. // On POSIX there is no taskkill; spawnSync reports the failure in its
  559. // result and the function stays silent — the same containment Windows
  560. // relies on for an already-absent tree.
  561. expect(() => { taskkillProcessTree(2 ** 30) }).not.toThrow()
  562. })
  563. it('dispose on a spawn-failed handle observes the rejection and returns', async () => {
  564. const running = spawnSubprocess(spec('true', { cwd: '/nonexistent-dir-dsh-dispose-test' }))
  565. const disposal = running.dispose({ eofGraceMs: 1_000, graceMs: 1_000 })
  566. await expect(running.done).rejects.toThrow()
  567. await expect(disposal).resolves.toBeUndefined()
  568. })
  569. it("an 'inherit' stdout with collected stderr wires only the requested collector", async () => {
  570. const running = spawnSubprocess({
  571. ...spec('echo to-parent; echo err >&2'),
  572. stdio: { stdin: 'ignore', stdout: 'inherit', stderr: { maxBytes: 1000 } },
  573. })
  574. const outcome = await running.done
  575. expect(outcome.exitCode).toBe(0)
  576. expect(running.stdout).toBeUndefined()
  577. expect(running.collected.stdout).toBeUndefined()
  578. expect(running.collected.stderr!.readFrom(0).text).toBe('err\n')
  579. })
  580. it("an 'inherit' stderr with collected stdout wires only the requested collector", async () => {
  581. const running = spawnSubprocess({
  582. ...spec('echo out; echo to-parent >&2'),
  583. stdio: { stdin: 'ignore', stdout: { maxBytes: 1000 }, stderr: 'inherit' },
  584. })
  585. const outcome = await running.done
  586. expect(outcome.exitCode).toBe(0)
  587. expect(running.stderr).toBeUndefined()
  588. expect(running.collected.stderr).toBeUndefined()
  589. expect(running.collected.stdout!.readFrom(0).text).toBe('out\n')
  590. })
  591. it('terminate() after the tree died delivers no termination signal', async () => {
  592. const running = spawnSubprocess(spec('true'))
  593. await running.done
  594. await running.waitForExit()
  595. const spy = vi.spyOn(process, 'kill')
  596. try {
  597. running.terminate()
  598. const delivered = spy.mock.calls.filter(([, sig]) => sig !== 0)
  599. expect(delivered).toEqual([])
  600. } finally {
  601. spy.mockRestore()
  602. }
  603. })
  604. it('waitForExit on a failed spawn reports exited immediately', async () => {
  605. const running = spawnSubprocess(spec('true', { cwd: '/nonexistent-dir-dsh-spawn-test' }))
  606. await expect(running.done).rejects.toThrow()
  607. await expect(running.waitForExit()).resolves.toBe(true)
  608. })
  609. it('dispose() on an already-exited tree returns without delivering a signal', async () => {
  610. const running = spawnSubprocess(spec('true'))
  611. await running.done
  612. await running.waitForExit()
  613. const spy = vi.spyOn(process, 'kill')
  614. try {
  615. await running.dispose({ eofGraceMs: 50, graceMs: 50 })
  616. const delivered = spy.mock.calls.filter(([, sig]) => sig !== 0)
  617. expect(delivered).toEqual([])
  618. } finally {
  619. spy.mockRestore()
  620. }
  621. })
  622. it('a batch-stdin handle exposes no stdin and dispose skips the EOF tier', async () => {
  623. const running = spawnSubprocess(spec('cat', { stdin: 'batch\n' }))
  624. expect(running.stdin).toBeUndefined()
  625. await running.done
  626. await running.dispose({ eofGraceMs: 50, graceMs: 50 })
  627. expect(running.collected.stdout!.readFrom(0).text).toBe('batch\n')
  628. })
  629. })
  630. describe('coverage seams 2', () => {
  631. it('win32 treeAlive reports alive for a live child and gone after taskkill', async () => {
  632. let killedPid = 0
  633. const running = spawnSubprocess(spec('sleep 60'), {
  634. spillDir,
  635. platform: 'win32',
  636. taskkill: (pid) => {
  637. killedPid = pid
  638. try {
  639. process.kill(pid, 'SIGKILL')
  640. } catch {
  641. // Already gone.
  642. }
  643. },
  644. })
  645. const aborted = new AbortController()
  646. aborted.abort()
  647. await expect(running.waitForExit(aborted.signal)).resolves.toBe(false) // alive branch
  648. running.terminate()
  649. await running.done
  650. expect(killedPid).toBe(running.pid)
  651. await expect(running.waitForExit()).resolves.toBe(true)
  652. })
  653. it('the win32 dispose ladder skips the POSIX SIGTERM tier and force-terminates', async () => {
  654. const kills: number[] = []
  655. const running = spawnSubprocess({
  656. ...spec('sleep 60'),
  657. stdio: { stdin: 'pipe', stdout: { maxBytes: 1000 }, stderr: { maxBytes: 1000 } },
  658. }, {
  659. spillDir,
  660. platform: 'win32',
  661. taskkill: (pid) => {
  662. kills.push(pid)
  663. try {
  664. process.kill(pid, 'SIGKILL')
  665. } catch {
  666. // Already gone.
  667. }
  668. },
  669. })
  670. await running.dispose({ eofGraceMs: 50, graceMs: 5_000 })
  671. // Exactly one forced tree termination: no POSIX SIGTERM tier ran.
  672. expect(kills).toEqual([running.pid])
  673. })
  674. it('dispose throws when even SIGKILL produces no exit within the grace', async () => {
  675. // An inert taskkill simulates a tree that never reports exit.
  676. const running = spawnSubprocess(spec('sleep 60'), { spillDir, platform: 'win32', taskkill: () => {} })
  677. await expect(running.dispose({ eofGraceMs: 20, graceMs: 40 }))
  678. .rejects.toThrow(/did not exit within 40ms after forced termination/)
  679. // Real cleanup: the injected platform spawned without detachment, so the
  680. // child is a plain (group-less) POSIX process — kill it directly.
  681. process.kill(running.pid, 'SIGKILL')
  682. await running.done
  683. })
  684. it("stderr: 'pipe' exposes the raw stream", async () => {
  685. const running = spawnSubprocess({
  686. ...spec('echo err >&2'),
  687. stdio: { stdin: 'ignore', stdout: { maxBytes: 1000 }, stderr: 'pipe' },
  688. })
  689. expect(running.stderr).toBeDefined()
  690. const text = new Promise<string>((resolve) => {
  691. let out = ''
  692. running.stderr!.on('data', (chunk: Buffer) => { out += chunk.toString('utf8') })
  693. running.stderr!.on('end', () => { resolve(out) })
  694. })
  695. await running.done
  696. expect(await text).toBe('err\n')
  697. })
  698. })
  699. describe('argv validation', () => {
  700. it('rejects an empty argv before spawning', () => {
  701. expect(() => spawnSubprocess({ ...spec('true'), argv: [] })).toThrow(/non-empty program name/)
  702. })
  703. it('rejects an empty program name before spawning', () => {
  704. expect(() => spawnSubprocess({ ...spec('true'), argv: [''] })).toThrow(/non-empty program name/)
  705. })
  706. it('spawns argv verbatim without shell interpretation', async () => {
  707. const result = await finish(spawnSubprocess({ ...spec('unused'), argv: ['printf', '%s', '$HOME'] }))
  708. expect(result.stdout.text).toBe('$HOME')
  709. })
  710. })
  711. describe('abort edge cases', () => {
  712. it('reports a fallback reason for reason-less pre-aborted signals', () => {
  713. // Real AbortControllers always set a DOMException reason; signal-like
  714. // objects from other libraries may not — the fallback covers them.
  715. const bare = {
  716. aborted: true,
  717. reason: undefined,
  718. addEventListener() {},
  719. removeEventListener() {},
  720. } as unknown as AbortSignal
  721. expect(() => spawnSubprocess(spec('echo hi', { signal: bare })))
  722. .toThrow(/aborted before spawn: aborted/)
  723. })
  724. it('reports the terminating signal of an externally self-killed command', async () => {
  725. // spawnSubprocess reports the raw signal; whether it counts as timeout/cancel is the
  726. // executor's classification (a self-kill is neither) — see executor.spec.ts.
  727. const result = await finish(spawnSubprocess(spec('kill -TERM $$')))
  728. expect(result.signal).toBe('SIGTERM')
  729. })
  730. })
  731. describe('environment and spill-file hardening', () => {
  732. it('scrubs credential-shaped and ambient DSH env vars from child processes', async () => {
  733. process.env.DSH_TEST_API_KEY = 'super-secret'
  734. process.env.DSH_TEST_TOKEN = 'also-secret'
  735. process.env.DSH_TEST_PLAIN = 'visible'
  736. try {
  737. const result = await finish(spawnSubprocess(spec('echo "[${DSH_TEST_API_KEY:-absent}|${DSH_TEST_TOKEN:-absent}|${DSH_TEST_PLAIN:-absent}]"')))
  738. expect(result.stdout.text.trim()).toBe('[absent|absent|absent]')
  739. } finally {
  740. delete process.env.DSH_TEST_API_KEY
  741. delete process.env.DSH_TEST_TOKEN
  742. delete process.env.DSH_TEST_PLAIN
  743. }
  744. })
  745. it('injects only the current trusted DSH environment after scrubbing ambient values', async () => {
  746. process.env.DSH_STALE = 'old-value'
  747. try {
  748. const result = await finish(spawnSubprocess(spec('echo "[${DSH_STALE:-absent}|$DSH_SHELL|$DSH_SESSION_ID]"', {
  749. dshEnv: { DSH_SHELL: '1', DSH_SESSION_ID: 'current-session' },
  750. })))
  751. expect(result.stdout.text.trim()).toBe('[absent|1|current-session]')
  752. } finally {
  753. delete process.env.DSH_STALE
  754. }
  755. })
  756. it('rejects DSH variables on the ordinary env channel', () => {
  757. expect(() => spawnSubprocess(spec('true', { env: { DSH_WRONG_CHANNEL: 'bad' } })))
  758. .toThrow(/DSH_WRONG_CHANNEL.*dshEnv/)
  759. })
  760. it('rejects ordinary variables on the managed env channel', () => {
  761. const invalid = { PATH: '/wrong-channel' } as unknown as DshEnvironment
  762. expect(() => spawnSubprocess(spec('true', { dshEnv: invalid })))
  763. .toThrow(/managed child env.*PATH.*use env/)
  764. })
  765. it('creates spill files with owner-only permissions and random names', async () => {
  766. const result = await finish(spawnSubprocess(
  767. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  768. { spillDir },
  769. ))
  770. const path = result.stdout.spillPath!
  771. expect(path).toMatch(/dsh-subprocess-\d+-\d+-[0-9a-f]{12}-stdout\.log$/)
  772. const mode = statSync(path).mode & 0o777
  773. expect(mode).toBe(0o600)
  774. })
  775. it('defaults spills into a private per-process directory', async () => {
  776. const result = await finish(spawnSubprocess(
  777. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  778. ))
  779. const dir = dirname(result.stdout.spillPath!)
  780. expect(dir).toMatch(/dsh-subprocess-/)
  781. const mode = statSync(dir).mode & 0o777
  782. expect(mode).toBe(0o700)
  783. })
  784. it('killGroup never throws, even for EPERM-style failures', () => {
  785. const spy = vi.spyOn(process, 'kill').mockImplementation(() => {
  786. throw Object.assign(new Error('EPERM'), { code: 'EPERM' })
  787. })
  788. try {
  789. expect(() => { killGroup(12345, 'SIGTERM') }).not.toThrow()
  790. } finally {
  791. spy.mockRestore()
  792. }
  793. })
  794. it('honors AbortSignal on background-style runs (no timeout)', async () => {
  795. const controller = new AbortController()
  796. const running = spawnSubprocess(spec('sleep 60', { signal: controller.signal }))
  797. setTimeout(() => { controller.abort() }, 50)
  798. const result = await running.done
  799. expect(result.signal).toBe('SIGTERM')
  800. })
  801. })