executor.spec.ts 15 KB

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