process-exit.spec.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { fileURLToPath } from 'node:url'
  5. import { execa } from 'execa'
  6. import { describe, expect, it, vi } from 'vitest'
  7. import { resolveExampleLaunch } from '@deepseek-ai/dsh-loader-smoke'
  8. import { createProcessInspector } from '../src/process-inspector.ts'
  9. import type { ProcessIdentity, ProcessInspector } from '../src/process-inspector.ts'
  10. import { taskkillProcessTree } from '../src/spawn.ts'
  11. type ExitTrigger = 'direct' | 'uncaught-exception' | 'unhandled-rejection' | 'dispose'
  12. type ManagedKind = 'ordinary' | 'terminal'
  13. interface TreeState { root: number; descendant: number }
  14. const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
  15. const hostScript = fileURLToPath(new URL('./fixtures/process-exit-host.ts', import.meta.url))
  16. const scenarioTimeoutMs = 30_000
  17. function processExists(pid: number): boolean {
  18. try {
  19. process.kill(pid, 0)
  20. return true
  21. } catch (error: unknown) {
  22. if ((error as NodeJS.ErrnoException).code === 'ESRCH') return false
  23. throw error
  24. }
  25. }
  26. async function readTree(path: string): Promise<TreeState> {
  27. return vi.waitFor(async () => {
  28. const text = await readFile(path, 'utf8')
  29. const state = JSON.parse(text) as Partial<TreeState>
  30. if (!Number.isSafeInteger(state.root) || !Number.isSafeInteger(state.descendant)
  31. || (state.root ?? 0) <= 0 || (state.descendant ?? 0) <= 0 || state.root === state.descendant) {
  32. throw new Error(`invalid managed-tree state: ${text}`)
  33. }
  34. return state as TreeState
  35. }, { interval: 10, timeout: scenarioTimeoutMs })
  36. }
  37. async function captureIdentities(inspector: ProcessInspector, state: TreeState): Promise<ProcessIdentity[]> {
  38. return vi.waitFor(() => {
  39. const expected = new Set([state.root, state.descendant])
  40. const identities = inspector.processTree(state.root).filter(identity => expected.has(identity.pid))
  41. if (identities.length !== expected.size) throw new Error('managed tree is not fully observable yet')
  42. return identities
  43. }, { interval: 10, timeout: scenarioTimeoutMs })
  44. }
  45. async function waitForGone(state: TreeState): Promise<void> {
  46. await Promise.all([state.root, state.descendant].map(pid => vi.waitFor(() => {
  47. if (processExists(pid)) throw new Error(`managed pid ${pid} is still alive`)
  48. }, { interval: 25, timeout: 10_000 })))
  49. }
  50. function cleanupTree(state: TreeState | undefined, identities: ProcessIdentity[]): void {
  51. if (state === undefined) return
  52. if (process.platform === 'win32') {
  53. taskkillProcessTree(state.root)
  54. for (const pid of [state.descendant, state.root]) {
  55. try {
  56. process.kill(pid, 'SIGKILL')
  57. } catch (_alreadyGone) {
  58. // The exact recorded process already exited.
  59. }
  60. }
  61. return
  62. }
  63. const inspector = createProcessInspector()
  64. for (const identity of identities) {
  65. try {
  66. inspector.signalProcess(identity, 'SIGKILL')
  67. } catch (_alreadyGone) {
  68. // Exact start identity prevents PID-reuse cleanup from reaching another process.
  69. }
  70. }
  71. if (identities.length === 0) {
  72. for (const pid of [state.descendant, state.root]) {
  73. try {
  74. process.kill(pid, 'SIGKILL')
  75. } catch (_alreadyGone) {
  76. // The scenario failed before process identities became observable.
  77. }
  78. }
  79. }
  80. }
  81. async function runScenario(kind: ManagedKind, trigger: ExitTrigger) {
  82. const root = await mkdtemp(join(tmpdir(), `dsh-subprocess-host-exit-${kind}-${trigger}-`))
  83. const launch = resolveExampleLaunch({
  84. srcBin: hostScript,
  85. mode: 'src',
  86. tsconfigPath: join(repoRoot, 'tsconfig.json'),
  87. configArgs: [kind, trigger, root],
  88. })
  89. const child = execa(launch.command, launch.args, {
  90. cwd: repoRoot,
  91. env: launch.env,
  92. stdin: 'ignore',
  93. reject: false,
  94. timeout: scenarioTimeoutMs,
  95. })
  96. let state: TreeState | undefined
  97. let identities: ProcessIdentity[] = []
  98. let settled = false
  99. let treeGone = false
  100. try {
  101. // The host validates tree.json before waiting for proceed, so observing it
  102. // is sufficient readiness; a second marker only adds a redundant Windows poll.
  103. state = await readTree(join(root, 'tree.json'))
  104. if (process.platform !== 'win32') identities = await captureIdentities(createProcessInspector(), state)
  105. await writeFile(join(root, 'proceed'), 'proceed')
  106. const outcome = await child
  107. settled = true
  108. await waitForGone(state)
  109. treeGone = true
  110. const disposeCounts = trigger === 'dispose'
  111. ? JSON.parse(await readFile(join(root, 'dispose.json'), 'utf8')) as {
  112. listenersBefore: number
  113. listenersAfterLoad: number
  114. listenersAfterDispose: number
  115. }
  116. : undefined
  117. return { outcome, disposeCounts }
  118. } finally {
  119. if (!settled) {
  120. child.kill('SIGKILL')
  121. await child.catch(() => {})
  122. }
  123. if (!treeGone) {
  124. cleanupTree(state, identities)
  125. if (state !== undefined) await waitForGone(state).catch(() => {})
  126. }
  127. await rm(root, { recursive: true, force: true })
  128. }
  129. }
  130. describe('synchronous cleanup on host exit', () => {
  131. it.each([
  132. { trigger: 'direct' as const, expectedCode: 23, diagnostic: undefined },
  133. { trigger: 'uncaught-exception' as const, expectedCode: 1, diagnostic: 'host-exit-uncaught-exception' },
  134. { trigger: 'unhandled-rejection' as const, expectedCode: 1, diagnostic: 'host-exit-unhandled-rejection' },
  135. ])('removes an ordinary managed tree after $trigger', { timeout: 45_000 }, async ({
  136. trigger,
  137. expectedCode,
  138. diagnostic,
  139. }) => {
  140. const { outcome } = await runScenario('ordinary', trigger)
  141. expect(outcome.exitCode).toBe(expectedCode)
  142. expect(outcome.signal).toBeUndefined()
  143. if (diagnostic !== undefined) expect(outcome.stderr).toContain(diagnostic)
  144. })
  145. it.skipIf(process.platform === 'win32')(
  146. 'removes a terminal root and descendant after direct exit',
  147. { timeout: 45_000 },
  148. async () => {
  149. const { outcome } = await runScenario('terminal', 'direct')
  150. expect(outcome.exitCode).toBe(23)
  151. expect(outcome.signal).toBeUndefined()
  152. },
  153. )
  154. it('preserves normal terminate-and-join disposal and removes the exit listener', { timeout: 45_000 }, async () => {
  155. const { outcome, disposeCounts } = await runScenario('ordinary', 'dispose')
  156. expect(outcome.exitCode).toBe(0)
  157. expect(disposeCounts?.listenersAfterLoad).toBe((disposeCounts?.listenersBefore ?? 0) + 1)
  158. expect(disposeCounts?.listenersAfterDispose).toBe(disposeCounts?.listenersBefore)
  159. })
  160. })