executor.spec.ts 18 KB

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