spawn.spec.ts 35 KB

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