spawn.spec.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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('lets an explicit tombstone remove an ordinary ambient env entry', async () => {
  290. process.env.SUBPROCESS_TOMBSTONE_PROBE = 'ambient-value'
  291. try {
  292. const result = await finish(spawnSubprocess(spec(
  293. 'echo "${SUBPROCESS_TOMBSTONE_PROBE:-absent}"',
  294. { env: { SUBPROCESS_TOMBSTONE_PROBE: undefined } },
  295. )))
  296. expect(result.stdout.text).toBe('absent\n')
  297. } finally {
  298. delete process.env.SUBPROCESS_TOMBSTONE_PROBE
  299. }
  300. })
  301. it('an explicit extra env entry overrides the credential scrub', async () => {
  302. // EXPLICIT_OVERRIDE_PASSWORD matches the credential scrub pattern, yet an explicit
  303. // entry is still honored — the scrub only drops AMBIENT process.env creds.
  304. const result = await finish(spawnSubprocess(spec('echo "$EXPLICIT_OVERRIDE_PASSWORD"', {
  305. env: { EXPLICIT_OVERRIDE_PASSWORD: 'explicit-wins' },
  306. })))
  307. expect(result.stdout.text).toBe('explicit-wins\n')
  308. })
  309. it('does not crash or reject when the child ignores a large stdin (EPIPE)', async () => {
  310. // The child exits without reading, so closing a stdin pipe holding ~1 MiB triggers EPIPE.
  311. // The handler swallows that write error and `done` reports the child's real exit.
  312. const big = 'x'.repeat(1024 * 1024)
  313. const result = await finish(spawnSubprocess(spec('exit 7', { stdin: big })))
  314. expect(result.exitCode).toBe(7)
  315. })
  316. })
  317. describe('output truncation and spill', () => {
  318. it('applies stdout and stderr caps independently', async () => {
  319. const result = await finish(spawnSubprocess(
  320. spec('printf "%.0sx" $(seq 1 500); printf "%.0se" $(seq 1 500) >&2', {
  321. stdoutMaxBytes: 500,
  322. stderrMaxBytes: 100,
  323. }),
  324. { spillDir },
  325. ))
  326. expect(result.stdout.truncated).toBe(false)
  327. expect(result.stdout.text).toBe('x'.repeat(500))
  328. expect(result.stderr.truncated).toBe(true)
  329. expect(result.stderr.text.length).toBeLessThanOrEqual(100)
  330. })
  331. it('keeps the tail and spills the full stream to disk', async () => {
  332. // 200 numbered lines of ~10 bytes; cap at 500 bytes keeps a late tail.
  333. const result = await finish(spawnSubprocess(
  334. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  335. { spillDir },
  336. ))
  337. expect(result.stdout.truncated).toBe(true)
  338. expect(result.stdout.text.length).toBeLessThanOrEqual(500)
  339. expect(result.stdout.text).toContain('line-0200')
  340. expect(result.stdout.text).not.toContain('line-0001')
  341. expect(result.stdout.spillPath).toBeDefined()
  342. const full = readFileSync(result.stdout.spillPath!, 'utf8')
  343. expect(full).toContain('line-0001')
  344. expect(full).toContain('line-0200')
  345. })
  346. it('does not truncate output exactly at the cap', async () => {
  347. const result = await finish(spawnSubprocess(
  348. spec('printf "%.0sx" $(seq 1 500)', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  349. { spillDir },
  350. ))
  351. expect(result.stdout.truncated).toBe(false)
  352. expect(result.stdout.text.length).toBe(500)
  353. expect(result.stdout.spillPath).toBeUndefined()
  354. })
  355. it('settles with the tail and no spill path when final spill close fails', async () => {
  356. failNextClose.value = true
  357. const result = await finish(spawnSubprocess(
  358. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  359. { spillDir },
  360. ))
  361. expect(failNextClose.value).toBe(false)
  362. expect(result.exitCode).toBe(0)
  363. expect(result.stdout.truncated).toBe(true)
  364. expect(result.stdout.text).toContain('line-0200')
  365. expect(result.stdout.spillPath).toBeUndefined()
  366. })
  367. })
  368. describe('OutputCollector', () => {
  369. it('keeps the tail of a single oversized chunk', () => {
  370. const collector = new OutputCollector(10, 100, 'test', spillDir)
  371. collector.push(Buffer.from('0123456789abcdef'))
  372. const out = collector.finalize()
  373. expect(out.text).toBe('6789abcdef')
  374. expect(out.truncated).toBe(true)
  375. expect(readFileSync(out.spillPath!, 'utf8')).toBe('0123456789abcdef')
  376. })
  377. it('retains a byte-exact tail across uneven chunk boundaries', () => {
  378. // A diagnostic tail must be exactly the LAST maxBytes regardless of
  379. // chunking; dropping only whole chunks would under-retain.
  380. const collector = new OutputCollector(10, undefined, 'exact-tail', spillDir)
  381. collector.push(Buffer.from('aaaa'))
  382. collector.push(Buffer.from('bbbbbb'))
  383. collector.push(Buffer.from('cc'))
  384. const out = collector.finalize()
  385. expect(out.text).toBe('aabbbbbbcc')
  386. expect(Buffer.byteLength(out.text)).toBe(10)
  387. expect(out.truncated).toBe(true)
  388. })
  389. it('readFrom returns increments and flags lossy reads', () => {
  390. const collector = new OutputCollector(10, 100, 'test', spillDir)
  391. collector.push(Buffer.from('aaaaa'))
  392. const first = collector.readFrom(0)
  393. expect(first.text).toBe('aaaaa')
  394. expect(first.lossy).toBe(false)
  395. expect(first.nextOffset).toBe(5)
  396. collector.push(Buffer.from('bbbbb'))
  397. const second = collector.readFrom(first.nextOffset)
  398. expect(second.text).toBe('bbbbb')
  399. expect(second.lossy).toBe(false)
  400. // Push enough to slide the window past the last offset.
  401. collector.push(Buffer.from('c'.repeat(20)))
  402. const third = collector.readFrom(second.nextOffset)
  403. expect(third.lossy).toBe(true)
  404. expect(third.text).toBe('c'.repeat(10))
  405. expect(third.spillPath).toBeDefined()
  406. })
  407. it('contains close failures and drops the spill path', () => {
  408. const collector = new OutputCollector(4, 100, 'closefail', spillDir)
  409. collector.push(Buffer.from('aaaa'))
  410. collector.push(Buffer.from('bbbb'))
  411. expect(collector.readFrom(0).spillPath).toBeDefined()
  412. failNextClose.value = true
  413. let out: ReturnType<typeof collector.finalize>
  414. expect(() => { out = collector.finalize() }).not.toThrow()
  415. expect(failNextClose.value).toBe(false)
  416. expect(out!.text).toBe('bbbb')
  417. expect(out!.truncated).toBe(true)
  418. expect(out!.spillPath).toBeUndefined()
  419. })
  420. it('discards a spill that exceeds its configured cap', () => {
  421. const collector = new OutputCollector(4, 8, 'bounded', spillDir)
  422. collector.push(Buffer.from('aaaa'))
  423. collector.push(Buffer.from('bbbb'))
  424. const spillPath = collector.readFrom(0).spillPath!
  425. expect(readFileSync(spillPath, 'utf8')).toBe('aaaabbbb')
  426. collector.push(Buffer.from('c'))
  427. collector.push(Buffer.from('dddd'))
  428. const out = collector.finalize()
  429. expect(out.text).toBe('dddd')
  430. expect(out.truncated).toBe(true)
  431. expect(out.spillPath).toBeUndefined()
  432. expect(() => readFileSync(spillPath)).toThrow()
  433. })
  434. it('does not create a spill when the first overflowing chunk exceeds the cap', () => {
  435. const collector = new OutputCollector(4, 4, 'no-spill', spillDir)
  436. collector.push(Buffer.from('abcdefgh'))
  437. const out = collector.finalize()
  438. expect(out.text).toBe('efgh')
  439. expect(out.truncated).toBe(true)
  440. expect(out.spillPath).toBeUndefined()
  441. })
  442. it('contains cleanup failures while disabling an oversize spill', () => {
  443. const collector = new OutputCollector(4, 8, 'cleanup-fail', spillDir)
  444. collector.push(Buffer.from('aaaa'))
  445. collector.push(Buffer.from('bbbb'))
  446. const spillPath = collector.readFrom(0).spillPath!
  447. failNextClose.value = true
  448. failNextUnlink.value = true
  449. expect(() => { collector.push(Buffer.from('c')) }).not.toThrow()
  450. expect(failNextClose.value).toBe(false)
  451. expect(failNextUnlink.value).toBe(false)
  452. expect(collector.finalize().spillPath).toBeUndefined()
  453. unlinkSync(spillPath)
  454. })
  455. })
  456. describe('killGroup', () => {
  457. it('ignores non-positive pids', () => {
  458. expect(() => { killGroup(-1, 'SIGTERM') }).not.toThrow()
  459. expect(() => { killGroup(0, 'SIGTERM') }).not.toThrow()
  460. })
  461. it('swallows ESRCH for vanished groups', async () => {
  462. const running = spawnSubprocess(spec('true'))
  463. await running.done
  464. expect(() => { killGroup(running.pid, 'SIGTERM') }).not.toThrow()
  465. })
  466. })
  467. describe('stdio dispositions', () => {
  468. it("'pipe' exposes raw streams for caller-owned protocol decoding", async () => {
  469. const running = spawnSubprocess({
  470. ...spec('cat'),
  471. stdio: { stdin: 'pipe', stdout: 'pipe', stderr: { maxBytes: 1000 } },
  472. })
  473. expect(running.stdin).toBeDefined()
  474. expect(running.stdout).toBeDefined()
  475. expect(running.stderr).toBeUndefined()
  476. expect(running.collected.stdout).toBeUndefined()
  477. expect(running.collected.stderr).toBeDefined()
  478. const echoed = new Promise<string>((resolve) => {
  479. let text = ''
  480. running.stdout!.on('data', (chunk: Buffer) => { text += chunk.toString('utf8') })
  481. running.stdout!.on('end', () => { resolve(text) })
  482. })
  483. running.stdin!.end('through the pipe\n')
  484. const outcome = await running.done
  485. expect(outcome.exitCode).toBe(0)
  486. expect(await echoed).toBe('through the pipe\n')
  487. })
  488. it('a collect mode without spill keeps only the in-memory tail (no file)', async () => {
  489. const running = spawnSubprocess({
  490. ...spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done'),
  491. stdio: { stdin: 'ignore', stdout: { maxBytes: 100 }, stderr: { maxBytes: 100 } },
  492. }, { spillDir })
  493. await running.done
  494. const read = running.collected.stdout!.readFrom(0)
  495. expect(read.lossy).toBe(true)
  496. expect(read.text).toContain('line-0200')
  497. expect(read.spillPath).toBeUndefined()
  498. })
  499. })
  500. describe('windows tree semantics (injected platform)', () => {
  501. it('terminate routes through taskkill by root pid', async () => {
  502. const killed: number[] = []
  503. const running = spawnSubprocess(spec('sleep 60', { graceMs: 100 }), {
  504. spillDir,
  505. platform: 'win32',
  506. taskkill: (pid) => {
  507. killed.push(pid)
  508. // Simulate the forced tree termination taskkill performs.
  509. try {
  510. process.kill(pid, 'SIGKILL')
  511. } catch {
  512. // Already gone — matches taskkill's tolerated not-found status.
  513. }
  514. },
  515. })
  516. running.terminate()
  517. const outcome = await running.done
  518. expect(killed).toContain(running.pid)
  519. expect(outcome.signal).toBe('SIGKILL')
  520. })
  521. it('waitForExit falls back to direct-child liveness where groups do not exist', async () => {
  522. const running = spawnSubprocess(spec('true'), { spillDir, platform: 'win32', taskkill: () => {} })
  523. await running.done
  524. await expect(running.waitForExit()).resolves.toBe(true)
  525. })
  526. })
  527. describe('waitForExit', () => {
  528. it('waits for the whole detached tree, not just the shell', async () => {
  529. const pidFile = join(spillDir, `tree-wait-${Date.now()}.pid`)
  530. const running = spawnSubprocess(spec(`sleep 60 & echo $! > ${pidFile}; wait`))
  531. const grandchild = await waitForPidFile(pidFile)
  532. running.terminate()
  533. await running.done
  534. await expect(running.waitForExit()).resolves.toBe(true)
  535. await expect(waitGone(grandchild, 100)).resolves.toBeUndefined()
  536. })
  537. it('an aborted wait reports false while the tree lives', async () => {
  538. const running = spawnSubprocess(spec('sleep 60'))
  539. const controller = new AbortController()
  540. controller.abort()
  541. await expect(running.waitForExit(controller.signal)).resolves.toBe(false)
  542. running.terminate()
  543. await running.done
  544. })
  545. })
  546. describe('tree-survivor escalation (terminate and bounded waits reach helpers the leader left behind)', () => {
  547. it('terminate() SIGKILLs a TERM-trapping descendant after the direct child settles', async () => {
  548. // The leader spawns a TERM-trapping helper with all stdio detached from
  549. // the collected pipes, then exits: the helper holds the GROUP alive while
  550. // the direct child settles. The escalation must still reach it.
  551. const pidFile = join(spillDir, `survivor-${Date.now()}.pid`)
  552. const running = spawnSubprocess(spec(
  553. `bash -c 'trap "" TERM; echo $$ > ${pidFile}; sleep 60' >/dev/null 2>&1 & disown; wait_placeholder=; exit 0`,
  554. { graceMs: 300 },
  555. ))
  556. const helper = await waitForPidFile(pidFile)
  557. await running.done // direct child settled; helper survives in the group
  558. expect(() => process.kill(helper, 0)).not.toThrow()
  559. running.terminate() // SIGTERM (trapped) → grace → SIGKILL the group
  560. await expect(running.waitForExit()).resolves.toBe(true)
  561. await waitGone(helper)
  562. })
  563. it('a bounded waitForExit reports false while a survivor lives, true after escalation', async () => {
  564. const pidFile = join(spillDir, `survivor-wait-${Date.now()}.pid`)
  565. const running = spawnSubprocess(spec(
  566. `bash -c 'trap "" TERM; echo $$ > ${pidFile}; sleep 60' >/dev/null 2>&1 & disown; exit 0`,
  567. { graceMs: 200 },
  568. ))
  569. const helper = await waitForPidFile(pidFile)
  570. await running.done
  571. // A consumer-owned teardown tier bounds its wait and reads the verdict.
  572. const bound = new AbortController()
  573. const timer = setTimeout(() => { bound.abort() }, 100)
  574. await expect(running.waitForExit(bound.signal)).resolves.toBe(false)
  575. clearTimeout(timer)
  576. running.terminate()
  577. await expect(running.waitForExit()).resolves.toBe(true)
  578. expect(() => process.kill(helper, 0)).toThrow()
  579. })
  580. it('service teardown awaits tree survivors, not just handle settlement', async () => {
  581. const { Context } = await import('cordis')
  582. const { default: LocalSubprocessService } = await import('@deepseek-ai/dsh-subprocess-local')
  583. const ctx = new Context()
  584. const fiber = await ctx.plugin(LocalSubprocessService)
  585. ;(ctx.subprocess as InstanceType<typeof LocalSubprocessService>).internals = { spillDir }
  586. const pidFile = join(spillDir, `survivor-svc-${Date.now()}.pid`)
  587. const running = ctx.subprocess.spawn(spec(
  588. `bash -c 'trap "" TERM; echo $$ > ${pidFile}; sleep 60' >/dev/null 2>&1 & disown; exit 0`,
  589. { graceMs: 200 },
  590. ))
  591. const helper = await waitForPidFile(pidFile)
  592. await running.done
  593. await fiber.dispose()
  594. // Teardown itself waited for the survivor to die.
  595. expect(() => process.kill(helper, 0)).toThrow()
  596. })
  597. })
  598. describe('coverage seams', () => {
  599. it('taskkillProcessTree ignores non-positive pids and contains a missing binary', () => {
  600. expect(() => { taskkillProcessTree(-1) }).not.toThrow()
  601. expect(() => { taskkillProcessTree(0) }).not.toThrow()
  602. // On POSIX there is no taskkill; spawnSync reports the failure in its
  603. // result and the function stays silent — the same containment Windows
  604. // relies on for an already-absent tree.
  605. expect(() => { taskkillProcessTree(2 ** 30) }).not.toThrow()
  606. })
  607. it('a spawn-failed handle rejects done while waitForExit reports gone', async () => {
  608. const running = spawnSubprocess(spec('true', { cwd: '/nonexistent-dir-dsh-dispose-test' }))
  609. await expect(running.done).rejects.toThrow()
  610. await expect(running.waitForExit()).resolves.toBe(true)
  611. })
  612. it("an 'inherit' stdout with collected stderr wires only the requested collector", async () => {
  613. const running = spawnSubprocess({
  614. ...spec('echo to-parent; echo err >&2'),
  615. stdio: { stdin: 'ignore', stdout: 'inherit', stderr: { maxBytes: 1000 } },
  616. })
  617. const outcome = await running.done
  618. expect(outcome.exitCode).toBe(0)
  619. expect(running.stdout).toBeUndefined()
  620. expect(running.collected.stdout).toBeUndefined()
  621. expect(running.collected.stderr!.readFrom(0).text).toBe('err\n')
  622. })
  623. it("an 'inherit' stderr with collected stdout wires only the requested collector", async () => {
  624. const running = spawnSubprocess({
  625. ...spec('echo out; echo to-parent >&2'),
  626. stdio: { stdin: 'ignore', stdout: { maxBytes: 1000 }, stderr: 'inherit' },
  627. })
  628. const outcome = await running.done
  629. expect(outcome.exitCode).toBe(0)
  630. expect(running.stderr).toBeUndefined()
  631. expect(running.collected.stderr).toBeUndefined()
  632. expect(running.collected.stdout!.readFrom(0).text).toBe('out\n')
  633. })
  634. it('terminate() after the tree died delivers no termination signal', async () => {
  635. const running = spawnSubprocess(spec('true'))
  636. await running.done
  637. const spy = vi.spyOn(process, 'kill')
  638. try {
  639. running.terminate()
  640. const delivered = spy.mock.calls.filter(([, sig]) => sig !== 0)
  641. expect(delivered).toEqual([])
  642. } finally {
  643. spy.mockRestore()
  644. }
  645. await running.waitForExit()
  646. })
  647. it('repeated terminate after exit never probes or signals a reused process group', async () => {
  648. const running = spawnSubprocess(spec('sleep 60'))
  649. running.terminate()
  650. await running.done
  651. await running.waitForExit()
  652. const spy = vi.spyOn(process, 'kill').mockImplementation(() => true)
  653. try {
  654. running.terminate()
  655. expect(spy).not.toHaveBeenCalled()
  656. } finally {
  657. spy.mockRestore()
  658. }
  659. })
  660. it('waitForExit on a failed spawn reports exited immediately', async () => {
  661. const running = spawnSubprocess(spec('true', { cwd: '/nonexistent-dir-dsh-spawn-test' }))
  662. await expect(running.done).rejects.toThrow()
  663. await expect(running.waitForExit()).resolves.toBe(true)
  664. })
  665. it('a batch-stdin handle exposes no stdin surface', async () => {
  666. const running = spawnSubprocess(spec('cat', { stdin: 'batch\n' }))
  667. expect(running.stdin).toBeUndefined()
  668. await running.done
  669. expect(running.collected.stdout!.readFrom(0).text).toBe('batch\n')
  670. })
  671. })
  672. describe('coverage seams 2', () => {
  673. it('win32 treeAlive reports alive for a live child and gone after taskkill', async () => {
  674. let killedPid = 0
  675. const running = spawnSubprocess(spec('sleep 60'), {
  676. spillDir,
  677. platform: 'win32',
  678. taskkill: (pid) => {
  679. killedPid = pid
  680. try {
  681. process.kill(pid, 'SIGKILL')
  682. } catch {
  683. // Already gone.
  684. }
  685. },
  686. })
  687. const aborted = new AbortController()
  688. aborted.abort()
  689. await expect(running.waitForExit(aborted.signal)).resolves.toBe(false) // alive branch
  690. running.terminate()
  691. await running.done
  692. expect(killedPid).toBe(running.pid)
  693. await expect(running.waitForExit()).resolves.toBe(true)
  694. })
  695. it('an inert win32 taskkill leaves the tree alive for a bounded wait to report', async () => {
  696. // An inert taskkill simulates a tree that never reports exit: terminate()
  697. // delivers nothing, so a bounded consumer wait must come back false.
  698. const running = spawnSubprocess(spec('sleep 60'), { spillDir, platform: 'win32', taskkill: () => {} })
  699. running.terminate()
  700. const bound = new AbortController()
  701. const timer = setTimeout(() => { bound.abort() }, 60)
  702. await expect(running.waitForExit(bound.signal)).resolves.toBe(false)
  703. clearTimeout(timer)
  704. // Real cleanup: the injected platform spawned without detachment, so the
  705. // child is a plain (group-less) POSIX process — kill it directly.
  706. process.kill(running.pid, 'SIGKILL')
  707. await running.done
  708. })
  709. it("stderr: 'pipe' exposes the raw stream", async () => {
  710. const running = spawnSubprocess({
  711. ...spec('echo err >&2'),
  712. stdio: { stdin: 'ignore', stdout: { maxBytes: 1000 }, stderr: 'pipe' },
  713. })
  714. expect(running.stderr).toBeDefined()
  715. const text = new Promise<string>((resolve) => {
  716. let out = ''
  717. running.stderr!.on('data', (chunk: Buffer) => { out += chunk.toString('utf8') })
  718. running.stderr!.on('end', () => { resolve(out) })
  719. })
  720. await running.done
  721. expect(await text).toBe('err\n')
  722. })
  723. })
  724. describe('argv validation', () => {
  725. it('rejects an empty argv before spawning', () => {
  726. expect(() => spawnSubprocess({ ...spec('true'), argv: [] })).toThrow(/non-empty program name/)
  727. })
  728. it('rejects an empty program name before spawning', () => {
  729. expect(() => spawnSubprocess({ ...spec('true'), argv: [''] })).toThrow(/non-empty program name/)
  730. })
  731. it('spawns argv verbatim without shell interpretation', async () => {
  732. const result = await finish(spawnSubprocess({ ...spec('unused'), argv: ['printf', '%s', '$HOME'] }))
  733. expect(result.stdout.text).toBe('$HOME')
  734. })
  735. })
  736. describe('abort edge cases', () => {
  737. it('reports a fallback reason for reason-less pre-aborted signals', () => {
  738. // Real AbortControllers always set a DOMException reason; signal-like
  739. // objects from other libraries may not — the fallback covers them.
  740. const bare = {
  741. aborted: true,
  742. reason: undefined,
  743. addEventListener() {},
  744. removeEventListener() {},
  745. } as unknown as AbortSignal
  746. expect(() => spawnSubprocess(spec('echo hi', { signal: bare })))
  747. .toThrow(/aborted before spawn: aborted/)
  748. })
  749. it('reports the terminating signal of an externally self-killed command', async () => {
  750. // spawnSubprocess reports the raw signal; whether it counts as timeout/cancel is the
  751. // executor's classification (a self-kill is neither) — see executor.spec.ts.
  752. const result = await finish(spawnSubprocess(spec('kill -TERM $$')))
  753. expect(result.signal).toBe('SIGTERM')
  754. })
  755. })
  756. describe('environment and spill-file hardening', () => {
  757. it('scrubs credential-shaped and ambient DSH env vars from child processes', async () => {
  758. process.env.DSH_TEST_API_KEY = 'super-secret'
  759. process.env.DSH_TEST_TOKEN = 'also-secret'
  760. process.env.SUBPROCESS_TEST_PASSWORD = 'password-secret'
  761. process.env.DSH_TEST_PLAIN = 'visible'
  762. try {
  763. const result = await finish(spawnSubprocess(spec(
  764. 'echo "[${DSH_TEST_API_KEY:-absent}|${DSH_TEST_TOKEN:-absent}|${SUBPROCESS_TEST_PASSWORD:-absent}|${DSH_TEST_PLAIN:-absent}]"',
  765. )))
  766. expect(result.stdout.text.trim()).toBe('[absent|absent|absent|absent]')
  767. } finally {
  768. delete process.env.DSH_TEST_API_KEY
  769. delete process.env.DSH_TEST_TOKEN
  770. delete process.env.SUBPROCESS_TEST_PASSWORD
  771. delete process.env.DSH_TEST_PLAIN
  772. }
  773. })
  774. it('forwards explicit DSH_* env entries while scrubbing ambient ones', async () => {
  775. // Both facts through one explicit map: the ambient DSH_STALE is dropped by
  776. // the scrub, and the deliberately supplied current values merge after it.
  777. process.env.DSH_STALE = 'old-value'
  778. try {
  779. const result = await finish(spawnSubprocess(spec('echo "[${DSH_STALE:-absent}|$DSH_SHELL|$DSH_SESSION_ID]"', {
  780. env: { DSH_SHELL: '1', DSH_SESSION_ID: 'current-session' },
  781. })))
  782. expect(result.stdout.text.trim()).toBe('[absent|1|current-session]')
  783. } finally {
  784. delete process.env.DSH_STALE
  785. }
  786. })
  787. it('creates spill files with owner-only permissions and random names', async () => {
  788. const result = await finish(spawnSubprocess(
  789. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  790. { spillDir },
  791. ))
  792. const path = result.stdout.spillPath!
  793. expect(path).toMatch(/dsh-subprocess-\d+-\d+-[0-9a-f]{12}-stdout\.log$/)
  794. const mode = statSync(path).mode & 0o777
  795. expect(mode).toBe(0o600)
  796. })
  797. it('defaults spills into a private per-process directory', async () => {
  798. const result = await finish(spawnSubprocess(
  799. spec('for i in $(seq 1 200); do printf "line-%04d\\n" $i; done', { stdoutMaxBytes: 500, stderrMaxBytes: 500 }),
  800. ))
  801. const dir = dirname(result.stdout.spillPath!)
  802. expect(dir).toMatch(/dsh-subprocess-/)
  803. const mode = statSync(dir).mode & 0o777
  804. expect(mode).toBe(0o700)
  805. })
  806. it('killGroup never throws, even for EPERM-style failures', () => {
  807. const spy = vi.spyOn(process, 'kill').mockImplementation(() => {
  808. throw Object.assign(new Error('EPERM'), { code: 'EPERM' })
  809. })
  810. try {
  811. expect(() => { killGroup(12345, 'SIGTERM') }).not.toThrow()
  812. } finally {
  813. spy.mockRestore()
  814. }
  815. })
  816. it('honors AbortSignal on background-style runs (no timeout)', async () => {
  817. const controller = new AbortController()
  818. const running = spawnSubprocess(spec('sleep 60', { signal: controller.signal }))
  819. setTimeout(() => { controller.abort() }, 50)
  820. const result = await running.done
  821. expect(result.signal).toBe('SIGTERM')
  822. })
  823. })