executor.spec.ts 15 KB

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