1
0

executor.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import { mkdtempSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { describe, expect, it, vi } from 'vitest'
  5. import { Context } from '@deepseek-ai/cordis'
  6. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  7. import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  8. import type { SubprocessHandle, SubprocessOutputReader } from '@deepseek-ai/dsh-subprocess'
  9. import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
  10. import type { ShellProcess } from '@deepseek-ai/dsh-shell'
  11. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-bash-exec-spec-'))
  12. async function setup(config: ConstructorParameters<typeof LocalBashExecutor>[1] = {}) {
  13. const ctx = new Context()
  14. await ctx.plugin(LocalSubprocessRuntime)
  15. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  16. // A short kill grace via the REAL config path, so escalation tests stay fast.
  17. await ctx.plugin(LocalBashExecutor, { graceMs: 200, ...config })
  18. const bash = ctx.shell as LocalBashExecutor
  19. return { ctx, bash }
  20. }
  21. /**
  22. * Poll a handle's consuming readOutput until the ACCUMULATED delta contains
  23. * `expected`; returns the accumulation (reads never re-deliver, so the caller
  24. * gets everything produced up to the match).
  25. */
  26. async function readUntil(proc: ShellProcess, expected: string, timeoutMs = 5_000): Promise<string> {
  27. const deadline = Date.now() + timeoutMs
  28. let all = ''
  29. while (Date.now() < deadline) {
  30. all += proc.readOutput().delta
  31. if (all.includes(expected)) return all
  32. await new Promise(resolve => setTimeout(resolve, 20))
  33. }
  34. throw new Error(`process output did not include ${JSON.stringify(expected)}; accumulated ${JSON.stringify(all)}`)
  35. }
  36. describe('LocalBashExecutor.run', () => {
  37. it('resolves with output and the effective timeout', async () => {
  38. const { bash } = await setup({ timeoutMs: 5_000 })
  39. const result = await bash.run(bash.resolve({ command: 'echo hi' }))
  40. expect(result.exitCode).toBe(0)
  41. expect(result.stdout.text).toBe('hi\n')
  42. expect(result.timeoutMs).toBe(5_000)
  43. })
  44. it('uses config cwd, overridable per call', async () => {
  45. const { bash } = await setup({ cwd: '/tmp' })
  46. const fromConfig = await bash.run(bash.resolve({ command: 'pwd' }))
  47. expect(fromConfig.stdout.text.trim()).toMatch(/\/tmp$/)
  48. const fromCall = await bash.run(bash.resolve({ command: 'pwd', workdir: '/' }))
  49. expect(fromCall.stdout.text.trim()).toBe('/')
  50. })
  51. it('defaults cwd to process.cwd()', async () => {
  52. const { bash } = await setup()
  53. const result = await bash.run(bash.resolve({ command: 'pwd' }))
  54. expect(result.stdout.text.trim()).toBe(process.cwd())
  55. })
  56. it('caps per-call timeouts at maxTimeoutMs', async () => {
  57. const { bash } = await setup({ timeoutMs: 1_000, maxTimeoutMs: 2_000 })
  58. const result = await bash.run(bash.resolve({ command: 'true', timeoutMs: 99_999 }))
  59. expect(result.timeoutMs).toBe(2_000)
  60. })
  61. it('rejects invalid numeric config and timeout overrides', async () => {
  62. await expect(setup({ timeoutMs: Number.NaN })).rejects.toThrow(/timeoutMs/)
  63. await expect(setup({ maxTimeoutMs: 0 })).rejects.toThrow(/maxTimeoutMs/)
  64. await expect(setup({ maxOutputBytes: -1 })).rejects.toThrow(/maxOutputBytes/)
  65. await expect(setup({ maxSpillBytes: 0 })).rejects.toThrow(/maxSpillBytes/)
  66. await expect(setup({ graceMs: 0 })).rejects.toThrow(/graceMs/)
  67. await expect(setup({ graceMs: MAX_TIMER_DELAY_MS + 1 }))
  68. .rejects.toThrow(`graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`)
  69. const { bash } = await setup()
  70. expect(() => bash.resolve({ command: 'true', timeoutMs: Number.NaN })).toThrow(/request\.timeoutMs/)
  71. expect(() => bash.resolve({ command: 'true', timeoutMs: -1 })).toThrow(/request\.timeoutMs/)
  72. expect(() => bash.resolve({ command: 'true', stdoutMaxBytes: Number.NaN })).toThrow(/request\.stdoutMaxBytes/)
  73. expect(() => bash.resolve({ command: 'true', stdoutMaxBytes: -1 })).toThrow(/request\.stdoutMaxBytes/)
  74. })
  75. it('defaults stdoutMaxBytes to maxOutputBytes and lets foreground callers raise stdout only', async () => {
  76. const { bash } = await setup({ maxOutputBytes: 100 })
  77. expect(bash.resolve({ command: 'true' }).stdoutMaxBytes).toBe(100)
  78. const result = await bash.run(bash.resolve({
  79. command: 'printf "%.0sx" $(seq 1 500); printf "%.0se" $(seq 1 500) >&2',
  80. stdoutMaxBytes: 500,
  81. }))
  82. expect(result.stdout.truncated).toBe(false)
  83. expect(result.stdout.text).toBe('x'.repeat(500))
  84. expect(result.stderr.truncated).toBe(true)
  85. expect(result.stderr.text.length).toBeLessThanOrEqual(100)
  86. })
  87. it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
  88. const { bash } = await setup({ timeoutMs: 60_000 })
  89. const result = await bash.run(bash.resolve({ command: 'sleep 60', timeoutMs: 100 }))
  90. expect(result.timedOut).toBe(true)
  91. // Mutually exclusive: a timeout classifies as timedOut, never also aborted.
  92. expect(result.aborted).toBe(false)
  93. expect(result.timeoutMs).toBe(100)
  94. })
  95. it('propagates abort signals', async () => {
  96. const { bash } = await setup()
  97. const controller = new AbortController()
  98. const pending = bash.run(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  99. setTimeout(() => { controller.abort() }, 50)
  100. const result = await pending
  101. expect(result.aborted).toBe(true)
  102. // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut.
  103. expect(result.timedOut).toBe(false)
  104. })
  105. it('classifies a self-killed command as neither timed out nor aborted', async () => {
  106. // The command kills itself (SIGTERM) with no timeout and no upstream abort:
  107. // the deadline signal never fires, so both classifications are false — the
  108. // fused-signal classification reports the cause that cut the command short,
  109. // and here nothing the executor owns did.
  110. const { bash } = await setup({ timeoutMs: 60_000 })
  111. const result = await bash.run(bash.resolve({ command: 'kill -TERM $$' }))
  112. expect(result.signal).toBe('SIGTERM')
  113. expect(result.timedOut).toBe(false)
  114. expect(result.aborted).toBe(false)
  115. })
  116. it('rejects on spawn failure (bad workdir)', async () => {
  117. const { bash } = await setup()
  118. await expect(bash.run(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/)
  119. })
  120. it('resolve() carries stdin/env/dshEnv onto the spec, and run() threads them to the command', async () => {
  121. const { bash } = await setup()
  122. const spec = bash.resolve({
  123. command: 'cat; echo "[$SEAM_VAR][$DSH_SEAM_VAR]"',
  124. stdin: 'piped\n',
  125. env: { SEAM_VAR: 'env-ok' },
  126. dshEnv: { DSH_SEAM_VAR: 'dsh-ok' },
  127. })
  128. // resolve() keeps the optional input/environment fields verbatim.
  129. expect(spec.stdin).toBe('piped\n')
  130. expect(spec.env).toEqual({ SEAM_VAR: 'env-ok' })
  131. expect(spec.dshEnv).toEqual({ DSH_SEAM_VAR: 'dsh-ok' })
  132. const result = await bash.run(spec)
  133. expect(result.stdout.text).toBe('piped\n[env-ok][dsh-ok]\n')
  134. })
  135. it('resolve() omits stdin/env/dshEnv when the request supplies none', async () => {
  136. const { bash } = await setup()
  137. const spec = bash.resolve({ command: 'true' })
  138. expect('stdin' in spec).toBe(false)
  139. expect('env' in spec).toBe(false)
  140. expect('dshEnv' in spec).toBe(false)
  141. })
  142. })
  143. describe('LocalBashExecutor.start (background process handles)', () => {
  144. it('start returns immediately with a running handle that settles as completed', async () => {
  145. const { bash } = await setup()
  146. const before = Date.now()
  147. const proc = bash.start(bash.resolve({ command: 'sleep 0.2; echo done' }))
  148. expect(Date.now() - before).toBeLessThan(150)
  149. expect(proc.status).toBe('running')
  150. await proc.done
  151. expect(proc.status).toBe('completed')
  152. expect(proc.exitCode).toBe(0)
  153. })
  154. it('threads stdin and extra env into a background process', async () => {
  155. const { bash } = await setup()
  156. const proc = bash.start(bash.resolve({
  157. command: 'cat; echo "[$BG_VAR][$DSH_BG_VAR]"',
  158. stdin: 'bg-stdin\n',
  159. env: { BG_VAR: 'bg-env' },
  160. dshEnv: { DSH_BG_VAR: 'bg-dsh-env' },
  161. }))
  162. const output = await readUntil(proc, '[bg-env][bg-dsh-env]')
  163. expect(output).toContain('bg-stdin')
  164. await proc.done
  165. expect(proc.exitCode).toBe(0)
  166. })
  167. it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async () => {
  168. const { bash } = await setup()
  169. const proc = bash.start(bash.resolve({ command: 'echo first; sleep 1; echo second' }))
  170. const first = await readUntil(proc, 'first\n')
  171. expect(first).toBe('first\n')
  172. await proc.done
  173. // Read-after-exit returns the remaining buffered output — once.
  174. const second = proc.readOutput()
  175. expect(second.delta).toBe('second\n')
  176. expect(second.lossy).toBe(false)
  177. expect(proc.readOutput().delta).toBe('')
  178. })
  179. it('readOutput marks stderr sections', async () => {
  180. const { bash } = await setup()
  181. const proc = bash.start(bash.resolve({ command: 'echo out; echo err >&2' }))
  182. await proc.done
  183. expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
  184. })
  185. it('readOutput reports stderr-only deltas without a leading newline', async () => {
  186. const { bash } = await setup()
  187. const proc = bash.start(bash.resolve({ command: 'echo err >&2' }))
  188. await proc.done
  189. expect(proc.readOutput().delta).toBe('[stderr]\nerr\n')
  190. })
  191. it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
  192. const { bash } = await setup()
  193. const proc = bash.start(bash.resolve({ command: 'printf out; echo err >&2' }))
  194. await proc.done
  195. expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
  196. })
  197. it('readOutput flags lossy reads and reports stdout spill paths', async () => {
  198. const { bash } = await setup({ maxOutputBytes: 100 })
  199. const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done' }))
  200. await proc.done
  201. const read = proc.readOutput()
  202. // Window slid past offset 0 → lossy, spill path points at the full stream.
  203. expect(read.lossy).toBe(true)
  204. expect(read.stdoutSpillPath).toBeDefined()
  205. })
  206. it('readOutput reports stderr spill paths', async () => {
  207. const { bash } = await setup({ maxOutputBytes: 100 })
  208. const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i >&2; done' }))
  209. await proc.done
  210. const read = proc.readOutput()
  211. expect(read.lossy).toBe(true)
  212. expect(read.stderrSpillPath).toBeDefined()
  213. expect(read.delta).toContain('[stderr]')
  214. })
  215. it('kill() terminates the process group: true once, false after settlement', async () => {
  216. const { bash } = await setup()
  217. const proc = bash.start(bash.resolve({ command: 'sleep 60' }))
  218. expect(proc.kill()).toBe(true)
  219. await proc.done
  220. expect(proc.status).toBe('killed')
  221. expect(proc.signal).toBe('SIGTERM')
  222. expect(proc.kill()).toBe(false)
  223. })
  224. it('kill() returns false for a naturally completed process', async () => {
  225. const { bash } = await setup()
  226. const proc = bash.start(bash.resolve({ command: 'true' }))
  227. await proc.done
  228. expect(proc.status).toBe('completed')
  229. expect(proc.kill()).toBe(false)
  230. })
  231. it('kill escalation uses the configured graceMs (a TERM-trapping process dies by SIGKILL)', async () => {
  232. const { bash } = await setup() // setup pins graceMs: 200 via config
  233. // The child echoes AFTER arming the trap, so waiting for the marker
  234. // guarantees SIGTERM is already ignored when the kill lands (a fixed sleep
  235. // is load-flaky: a slow spawn would take the SIGTERM before the trap).
  236. const proc = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo armed; sleep 60' }))
  237. await readUntil(proc, 'armed')
  238. proc.kill()
  239. await proc.done
  240. expect(proc.status).toBe('killed')
  241. expect(proc.signal).toBe('SIGKILL')
  242. })
  243. it('a spec.signal abort settles the handle as killed, not completed', async () => {
  244. const { bash } = await setup()
  245. const controller = new AbortController()
  246. const proc = bash.start(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  247. controller.abort()
  248. await proc.done
  249. expect(proc.status).toBe('killed')
  250. expect(proc.signal).toBe('SIGTERM')
  251. })
  252. it('a self-signal exit settles the handle as killed, not completed', async () => {
  253. const { bash } = await setup()
  254. const proc = bash.start(bash.resolve({ command: 'kill -TERM $$' }))
  255. await proc.done
  256. expect(proc.status).toBe('killed')
  257. expect(proc.exitCode).toBeNull()
  258. expect(proc.signal).toBe('SIGTERM')
  259. })
  260. it('an asynchronous provider rejection does not claim that the command never started', async () => {
  261. const { ctx, bash } = await setup()
  262. const emptyReader: SubprocessOutputReader = {
  263. readFrom: () => ({ text: '', nextOffset: 0, lossy: false }),
  264. }
  265. vi.spyOn(ctx.subprocess, 'spawn').mockReturnValue({
  266. stdin: undefined,
  267. stdout: undefined,
  268. stderr: undefined,
  269. collected: { stdout: emptyReader, stderr: emptyReader },
  270. done: Promise.reject(new Error('provider lost the direct outcome')),
  271. terminate: vi.fn(),
  272. waitForExit: async () => true,
  273. } satisfies SubprocessHandle)
  274. const proc = bash.start(bash.resolve({ command: 'true' }))
  275. await expect(proc.done).resolves.toBeUndefined()
  276. expect(proc.status).toBe('killed')
  277. const output = proc.readOutput().delta
  278. expect(output).toContain('subprocess failed before reporting an outcome:')
  279. expect(output).not.toContain('spawn failed:')
  280. })
  281. it('an asynchronous creation failure settles as killed with a stage-neutral note', async () => {
  282. const { bash } = await setup()
  283. const proc = bash.start(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))
  284. // done resolves (never rejects) even though the process never ran.
  285. await expect(proc.done).resolves.toBeUndefined()
  286. expect(proc.status).toBe('killed')
  287. expect(proc.readOutput().delta).toContain('subprocess failed before reporting an outcome:')
  288. })
  289. })
  290. describe('process lifecycle ownership (the subprocess service, not the executor)', () => {
  291. it('a background process survives executor-fiber disposal and dies with the subprocess service', async () => {
  292. const ctx = new Context()
  293. const managerFiber = await ctx.plugin(LocalSubprocessRuntime)
  294. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  295. const executorFiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  296. const bash = ctx.shell as LocalBashExecutor
  297. // The child prints its own pid ($$ = the detached bash group leader) so
  298. // the test can probe liveness through the public read API alone.
  299. const proc = bash.start(bash.resolve({ command: 'echo $$; sleep 60' }))
  300. const pid = Number((await readUntil(proc, '\n')).trim())
  301. expect(Number.isInteger(pid) && pid > 0).toBe(true)
  302. // Executor reload/disposal leaves background work running — the
  303. // handle stays live and readable, mirroring the job runtime's
  304. // registrations-outlive-producer-fibers contract.
  305. await executorFiber.dispose()
  306. expect(proc.status).toBe('running')
  307. expect(() => process.kill(pid, 0)).not.toThrow()
  308. // Service disposal kills the group and AWAITS its exit (no orphans).
  309. await managerFiber.dispose()
  310. expect(() => process.kill(pid, 0)).toThrow()
  311. await proc.done
  312. expect(proc.status).toBe('killed')
  313. })
  314. it('service disposal escalates to SIGKILL for TERM-trapping children and settles handles', async () => {
  315. const ctx = new Context()
  316. const managerFiber = await ctx.plugin(LocalSubprocessRuntime)
  317. ;(ctx.subprocess as LocalSubprocessRuntime).internals = { spillDir }
  318. await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  319. const bash = ctx.shell as LocalBashExecutor
  320. const finished = bash.start(bash.resolve({ command: 'echo done' }))
  321. await finished.done
  322. expect(finished.status).toBe('completed')
  323. const trapping = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo armed; sleep 60' }))
  324. await readUntil(trapping, 'armed')
  325. await managerFiber.dispose()
  326. // A settled process was untouched; the live one died by escalation.
  327. expect(finished.status).toBe('completed')
  328. await trapping.done
  329. expect(trapping.status).toBe('killed')
  330. expect(trapping.signal).toBe('SIGKILL')
  331. })
  332. })