executor.spec.ts 15 KB

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