spawn.spec.ts 36 KB

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