Open History to see the last commit
1/**
2 * Regression coverage for the `killTree` orphan leak.
3 *
4 * THE DEFECT. On Windows with a git-bash `sh`, a multi-statement command — e.g.
5 * `journalFollowCommand`'s `mkdir -p …; : >> …; tail -c +1 -f …` — has its final
6 * `tail` spawned by an intermediate `sh.exe` that MSYS's fork emulation then
7 * exits. Windows never reparents, so `tail.exe`'s `ParentProcessId` keeps
8 * pointing at that dead pid, and `taskkill /PID <sh> /T /F` — which walks only
9 * LIVE parent links — never reaches it while still exiting `0`. Every follow read
10 * leaked a `tail.exe` for the life of the machine (measured: 2 per run of the
11 * journal conformance suite, 4 per run of the takeover suite).
12 *
13 * WHAT IS PORTABLE AND WHAT IS NOT. The attribution logic
14 * (`parseMsysProcessTable` + `msysDescendantWinPids`) is pure text→pids and is
15 * tested everywhere. The end-to-end proof is NOT portable and is Windows-gated:
16 * it needs the MSYS process table, which exists only under git-bash, and the leak
17 * itself is a Windows-only consequence of MSYS fork emulation. It is also
18 * meaningless under Docker (that provider's `tail` dies with its container) and
19 * on POSIX (`sh` really is `tail`'s parent, so signalling the wrapper suffices).
20 * A host process census cannot be written once and trusted everywhere — so
21 * rather than a test that passes everywhere for the wrong reason, the real
22 * assertion self-skips off Windows and says why.
23 */
24import { afterAll, describe, expect, it } from 'vitest'
25import * as fsp from 'node:fs/promises'
26import * as os from 'node:os'
27import * as path from 'node:path'
28import {
29 classifyTaskkillResult,
30 localProcessSandbox,
31 msysDescendantWinPids,
32 parseMsysProcessTable,
33 taskkillPid,
34} from '../src/index'
35
36/** Real `ps` output captured from git-bash on Windows 11, trimmed to the shape that matters. */
37const PS_FIXTURE = [
38 ' PID PPID PGID WINPID TTY UID STIME COMMAND',
39 ' 37196 1 37196 106236 ? 197609 20:17:41 /usr/bin/sh',
40 ' 37198 37196 37196 95720 ? 197609 20:17:41 /usr/bin/tail',
41 ' 37217 1 37217 87848 ? 197609 20:17:42 /usr/bin/ps',
42 ' 2236 1 2236 53084 ? 197609 18:39:41 /c/Program Files/nodejs/node',
43 '',
44].join('\n')
45
46describe('parseMsysProcessTable', () => {
47 it('reads pid/ppid/winpid and skips the header and blank lines', () => {
48 expect(parseMsysProcessTable(PS_FIXTURE)).toEqual([
49 { pid: 37196, ppid: 1, winpid: 106236 },
50 { pid: 37198, ppid: 37196, winpid: 95720 },
51 { pid: 37217, ppid: 1, winpid: 87848 },
52 { pid: 2236, ppid: 1, winpid: 53084 },
53 ])
54 })
55
56 it('drops `ps -W` native rows, whose ppid column is 0', () => {
57 // `-W` appends every native Windows process with a PPID/PGID of 0. They are
58 // in no MSYS tree, so they must never widen the sweep.
59 const withNative = `${PS_FIXTURE}\n 118284 0 0 52748 ? 0 18:39:42 C:\\Program Files\\Git\\bin\\sh.exe`
60 expect(parseMsysProcessTable(withNative)).toHaveLength(4)
61 })
62})
63
64describe('msysDescendantWinPids', () => {
65 it('finds the grandchild whose Windows parent link is broken', () => {
66 // 95720's Windows ParentProcessId points at an exited intermediate, so
67 // `taskkill /T` cannot reach it — MSYS's table is the only place the link
68 // back to our `sh` (winpid 106236) survives.
69 expect(
70 msysDescendantWinPids(parseMsysProcessTable(PS_FIXTURE), 106236),
71 ).toEqual([95720])
72 })
73
74 it('excludes the root itself', () => {
75 const rows = parseMsysProcessTable(PS_FIXTURE)
76 expect(msysDescendantWinPids(rows, 106236)).not.toContain(106236)
77 })
78
79 it('returns nothing when the root is not an MSYS process', () => {
80 // Nothing to sweep beyond what `taskkill /T` already covered.
81 expect(
82 msysDescendantWinPids(parseMsysProcessTable(PS_FIXTURE), 999999),
83 ).toEqual([])
84 })
85
86 it('terminates on a ppid cycle instead of hanging', () => {
87 const rows = [
88 { pid: 10, ppid: 1, winpid: 100 },
89 { pid: 11, ppid: 10, winpid: 101 },
90 { pid: 12, ppid: 11, winpid: 102 },
91 { pid: 10, ppid: 12, winpid: 100 },
92 ]
93 expect(msysDescendantWinPids(rows, 100).sort()).toEqual([101, 102])
94 })
95})
96
97describe('classifyTaskkillResult', () => {
98 it('treats exit 0 as killed', () => {
99 expect(classifyTaskkillResult(0, '')).toBe('killed')
100 })
101
102 it('treats 128 / "not found" as already-exited, not a failure', () => {
103 // The single most common teardown case: the process finished on its own
104 // before we asked. Calling it a failure would make every clean teardown log
105 // an error and retry a kill that has nothing to kill.
106 expect(classifyTaskkillResult(128, '')).toBe('already-exited')
107 expect(
108 classifyTaskkillResult(1, 'ERROR: The process "1234" not found.\r\n'),
109 ).toBe('already-exited')
110 expect(
111 classifyTaskkillResult(1, 'ERROR: The process "1234" does not exist.'),
112 ).toBe('already-exited')
113 })
114
115 it('treats /T\'s "no running instance of the task" as already-exited', () => {
116 // The wording `/T` uses when a tree member exits between taskkill
117 // enumerating it and signalling it. It comes back with status 1 and matches
118 // NEITHER "not found" nor "does not exist", so it used to be classified
119 // `failed` — logging a warning on an ordinary teardown race. That is the
120 // known suspect for the intermittent single-warning failure of "a normal
121 // kill neither throws nor reports a failure" below.
122 expect(
123 classifyTaskkillResult(
124 1,
125 'ERROR: The process with PID 1234 (child process of PID 5678) could not be terminated.\r\nReason: There is no running instance of the task.\r\n',
126 ),
127 ).toBe('already-exited')
128 })
129
130 it('treats any other nonzero status as a real failure', () => {
131 // A launched taskkill is not a successful taskkill — `spawnSync` reporting
132 // no `error` says only that the binary ran.
133 expect(classifyTaskkillResult(1, 'ERROR: Access is denied.\r\n')).toBe(
134 'failed',
135 )
136 expect(classifyTaskkillResult(null, '')).toBe('failed')
137 })
138
139 it('keeps a genuine refusal a failure even though it shares /T\'s "could not be terminated" prefix', () => {
140 // The widening above must not swallow these: the process is still running
141 // and the caller has leaked it. Both are verbatim taskkill output (captured
142 // against pid 4 and pid 0 respectively on Windows 11).
143 expect(
144 classifyTaskkillResult(
145 1,
146 'ERROR: The process with PID 4 could not be terminated.\r\nReason: Access is denied.\r\r\n',
147 ),
148 ).toBe('failed')
149 expect(
150 classifyTaskkillResult(
151 1,
152 'ERROR: The process with PID 0 could not be terminated.\r\nReason: This is critical system process. Taskkill cannot end this process.\r\n',
153 ),
154 ).toBe('failed')
155 })
156})
157
158const baseDir = path.join(os.tmpdir(), `tanstack-ai-lp-kt-${Date.now()}`)
159const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
160
161afterAll(async () => {
162 await fsp.rm(baseDir, { recursive: true, force: true })
163})
164
165function isAlive(pid: number): boolean {
166 try {
167 process.kill(pid, 0)
168 return true
169 } catch {
170 return false
171 }
172}
173
174// See the module doc: a host process census is not portable, so the end-to-end
175// proof is Windows-only rather than a test that passes everywhere vacuously.
176const windowsOnly = process.platform === 'win32' ? it : it.skip
177
178describe('killTree leaves no orphaned descendants (Windows/MSYS)', () => {
179 windowsOnly(
180 'kills the `tail` that `taskkill /T` cannot reach',
181 async () => {
182 const sbx = await provider.create({})
183 // `finally`, not a trailing `destroy()`: a throw from
184 // `parseMsysProcessTable`, `kill()`, or either assertion would otherwise
185 // leak the sandbox AND the `tail.exe` this very test exists to prove is
186 // killable — the suite would poison the machine it is diagnosing.
187 try {
188 await sbx.fs.write('/workspace/j.ndjson', 'line1\n')
189 // The exact shape of `journalFollowCommand`: a statement list whose last
190 // command MSYS runs under an intermediate shell that then exits.
191 const proc = await sbx.process.spawn(
192 `mkdir -p '/tmp/tanstack-kt' 2>/dev/null; : >> 'j.ndjson' 2>/dev/null; tail -c +1 -f 'j.ndjson' 2>/dev/null`,
193 { cwd: '/workspace' },
194 )
195 // Wait for real output so `tail` is definitely up before we look for it.
196 for await (const chunk of proc.stdout) {
197 if (chunk.includes('line1')) break
198 }
199
200 const table = parseMsysProcessTable(
201 (await sbx.process.exec('ps', { cwd: '/workspace' })).stdout,
202 )
203 const descendants = msysDescendantWinPids(table, proc.pid)
204 // Guard the guard: if this is empty the assertion below is vacuous.
205 expect(descendants.length).toBeGreaterThan(0)
206
207 await proc.kill()
208 // Windows process teardown is not instantaneous — and a FIXED sleep is
209 // the same "assume, don't verify" mistake this suite exists to catch. 500ms
210 // was under the real cost: `taskkill /T` alone measures ~1.9-3.0s on a
211 // loaded machine, so this asserted before the kill had landed and failed
212 // ~1 run in 4 under full-suite load (leaving the very `tail.exe` it is
213 // meant to prove dead). Poll for the outcome instead, up to a bound.
214 const deadline = Date.now() + 15_000
215 let survivors = descendants.filter((pid) => isAlive(pid))
216 while (survivors.length > 0 && Date.now() < deadline) {
217 await new Promise((resolve) => setTimeout(resolve, 100))
218 survivors = survivors.filter((pid) => isAlive(pid))
219 }
220
221 expect(survivors).toEqual([])
222 } finally {
223 await sbx.destroy()
224 }
225 },
226 30_000,
227 )
228})
229
230/**
231 * A captured warning, kept WITH its `meta`.
232 *
233 * Capturing only `message` is what made this suite's one intermittent failure
234 * undiagnosable: it printed
235 * `expected [ "local-process: taskkill failed to kill a process" ] to deeply
236 * equal []` and threw away the `status`/`stderr` that says WHICH taskkill
237 * wording was misclassified. `taskkillPid` already logs the raw stderr in
238 * `meta`; asserting on the full record is what puts it in the failure output.
239 */
240interface CapturedWarning {
241 message: string
242 meta?: Record<string, unknown>
243}
244
245describe('killTree teardown is total by construction', () => {
246 it('a normal kill neither throws nor reports a failure', async () => {
247 // Teardown paths on this branch (`SpawnHandle.kill`, `signal` abort
248 // handlers, `pipeToRunLog`) are deliberately unable to fail: a throwing kill
249 // would wedge a run at 'running' with its tailers parked, and treating the
250 // ordinary "it already exited" case as an error would cry wolf on every
251 // clean teardown. Both are asserted here rather than left to review.
252 const warnings: Array<CapturedWarning> = []
253 const noisy = localProcessSandbox({
254 baseDir,
255 removeOnDestroy: true,
256 logger: { warn: (message, meta) => warnings.push({ message, meta }) },
257 })
258 const sbx = await noisy.create({})
259
260 // `finally`: the `sleep 30` below outlives a failed assertion otherwise.
261 try {
262 // Kill a live process...
263 const live = await sbx.process.spawn('sleep 30')
264 await expect(live.kill()).resolves.toBeUndefined()
265
266 // ...and one that has already exited on its own.
267 const done = await sbx.process.spawn('exit 0')
268 await done.wait()
269 await expect(done.kill()).resolves.toBeUndefined()
270
271 // Asserting the whole record (not just `message`) so a future intermittent
272 // failure prints the raw taskkill status + stderr and is diagnosable on the
273 // first occurrence. Do NOT relax this to "warnings are allowed" — the
274 // warning firing here IS the signal that a benign wording is misclassified.
275 expect(warnings).toEqual([])
276 } finally {
277 await sbx.destroy()
278 }
279 }, 30_000)
280
281 // Counterpart to the assertion above: it is only meaningful if a warning CAN
282 // fire. Windows-only because the warning is emitted by the `taskkill` branch,
283 // which `killTree` never reaches on POSIX.
284 windowsOnly(
285 'reports a genuine refusal as a failure, with the raw taskkill stderr attached',
286 () => {
287 const warnings: Array<CapturedWarning> = []
288 // pid 0 is the System Idle Process: taskkill always refuses it ("This is
289 // critical system process"), so this is a real, reproducible refusal that
290 // cannot harm the machine — nothing is signalled and no real process is
291 // targeted. `tree: false` so taskkill never walks a live tree.
292 const gone = taskkillPid(0, false, {
293 warn: (message, meta) => warnings.push({ message, meta }),
294 })
295
296 expect(gone).toBe(false)
297 expect(warnings).toHaveLength(1)
298 expect(warnings[0]?.message).toBe(
299 'local-process: taskkill failed to kill a process',
300 )
301 // The raw stderr must reach the log — that is what makes an intermittent
302 // misclassification diagnosable instead of a mystery.
303 expect(warnings[0]?.meta).toMatchObject({ pid: 0, status: 1 })
304 expect(String(warnings[0]?.meta?.stderr)).toContain(
305 'could not be terminated',
306 )
307 },
308 30_000,
309 )
310})