diff --git a/cli/src/codex/shared/registry.test.ts b/cli/src/codex/shared/registry.test.ts index 10a98592..6fe2b84c 100644 --- a/cli/src/codex/shared/registry.test.ts +++ b/cli/src/codex/shared/registry.test.ts @@ -17,6 +17,31 @@ async function fixture(): Promise { sessions: { sid: { threadId: 'thread', namespace: 'ns', active: true } } }; } describe('shared runtime ownership', () => { + it('uses one complete process snapshot without per-record OS probes', async () => { + const owner = await fixture(); + const probe = vi.spyOn(state.processes, 'has'); + try { + for (let scan = 0; scan < 3; scan++) { + for (let index = 0; index < 50; index++) { + expect(runtimeMayBeAlive({ ...owner, pid: 3000 + index, serverPid: 4000 + index }, new Map())).toBe(false); + } + } + expect(probe).not.toHaveBeenCalled(); + } finally { probe.mockRestore(); } + }); + it('retains live wrappers, orphan engines and unknown generations in a fresh snapshot', async () => { + const owner = await fixture(); + expect(runtimeMayBeAlive(owner, new Map([[1111, owner.marker]]))).toBe(true); + expect(runtimeMayBeAlive(owner, new Map([[2222, owner.serverMarker!]]))).toBe(true); + expect(runtimeMayBeAlive(owner, new Map([[1111, null]]))).toBe(true); + expect(runtimeMayBeAlive({ ...owner, serverMarker: undefined }, new Map([[2222, 'unverified-start']]))).toBe(true); + }); + it('does not confuse old runtime generations with reused PIDs or retain a stale live snapshot', async () => { + const owner = await fixture(); state.processes.set(1111, owner.marker); + expect(runtimeMayBeAlive(owner, new Map([[1111, 'new-wrapper'], [2222, 'new-engine']]))).toBe(false); + expect(runtimeMayBeAlive(owner, new Map())).toBe(false); + expect(runtimeMayBeAlive(owner, new Map([[1111, owner.marker]]))).toBe(true); + }); it('distinguishes PID reuse from an unknown generation and a live orphan engine', async () => { const owner = await fixture(); state.processes.set(1111, 'different-start'); expect(runtimeAlive(owner)).toBe(false); expect(runtimeMayBeAlive(owner)).toBe(false); diff --git a/cli/src/codex/shared/registry.ts b/cli/src/codex/shared/registry.ts index e8ec3461..0d4409e2 100644 --- a/cli/src/codex/shared/registry.ts +++ b/cli/src/codex/shared/registry.ts @@ -32,15 +32,20 @@ export function runtimeAlive(record: CodexRuntimeRecord): boolean { return isProcessAlive(record.pid) && getProcessStartMarker(record.pid) === record.marker; } -function generationMayBeAlive(pid: number, marker?: string): boolean { +function generationMayBeAlive(pid: number, marker?: string, snapshot?: ReadonlyMap): boolean { + if (snapshot) { + if (!snapshot.has(pid)) return false; + const actual = snapshot.get(pid); + return !actual || !marker || actual === marker; + } if (!isProcessAlive(pid)) return false; const actual = getProcessStartMarker(pid); // A failed OS probe is not evidence that the engine exited. return !actual || !marker || actual === marker; } -export function runtimeMayBeAlive(owner: CodexRuntimeRecord): boolean { - return generationMayBeAlive(owner.pid, owner.marker) - || Boolean(owner.serverPid && generationMayBeAlive(owner.serverPid, owner.serverMarker)); +export function runtimeMayBeAlive(owner: CodexRuntimeRecord, snapshot?: ReadonlyMap): boolean { + return generationMayBeAlive(owner.pid, owner.marker, snapshot) + || Boolean(owner.serverPid && generationMayBeAlive(owner.serverPid, owner.serverMarker, snapshot)); } export async function readRuntimes(options?: { strict?: boolean }): Promise { diff --git a/cli/src/runner/orphanReap.test.ts b/cli/src/runner/orphanReap.test.ts index 11d6a6b3..5414bf5d 100644 --- a/cli/src/runner/orphanReap.test.ts +++ b/cli/src/runner/orphanReap.test.ts @@ -7,6 +7,7 @@ import { commandMatchesRunnerSpawnedSession, findRunnerSpawnedOrphanTargets, findStopSessionOrphanTargets, + parseWindowsProcessSnapshot, reapRunnerSpawnedOrphans, selectOrphanPidsForSession, selectOrphanTargetsForSession, @@ -17,6 +18,17 @@ import { windowsProcessMarkerCimCommand, } from '@/utils/process' +describe('complete Windows process snapshots', () => { + it.each(['', '[]', '{}', 'null', '[{"ProcessId":1},{}]', '[{"ProcessId":0}]'])('rejects unverifiable listing %s', raw => { + expect(() => parseWindowsProcessSnapshot(raw)).toThrow(); + }); + it('retains missing creation times as unknown rather than treating the PID as absent', () => { + expect(parseWindowsProcessSnapshot('[{"ProcessId":0},{"ProcessId":42,"CreationDate":null}]')).toEqual([ + { pid: 42, name: '', cmd: '', startMarker: null } + ]); + }); +}); + describe('orphanReap argv matching', () => { const sessionId = 'sess-abc-123' diff --git a/cli/src/runner/orphanReap.ts b/cli/src/runner/orphanReap.ts index d4d5d690..6d3831b0 100644 --- a/cli/src/runner/orphanReap.ts +++ b/cli/src/runner/orphanReap.ts @@ -191,7 +191,12 @@ export function listWindowsProcessesWithCommandLine(): ProcessSnapshot[] { if (result.error || result.status !== 0) { throw result.error ?? new Error(`powershell Win32_Process exit ${result.status}`) } - const raw = (result.stdout ?? '').trim() + return parseWindowsProcessSnapshot((result.stdout ?? '').toString()) +} + +/** Reject incomplete/invalid listings before absence can prove a PID exited. */ +export function parseWindowsProcessSnapshot(stdout: string): ProcessSnapshot[] { + const raw = stdout.trim() // Empty stdout is a failed scan, not "no processes" — a live Windows host // always has System/Idle. Match process.ts collectWindowsProcessTree // fail-closed semantics so orphan reap does not claim archive-ok (#1911). @@ -202,7 +207,11 @@ export function listWindowsProcessesWithCommandLine(): ProcessSnapshot[] { | Array<{ ProcessId?: number; Name?: string; CommandLine?: string; CreationDate?: string }> | { ProcessId?: number; Name?: string; CommandLine?: string; CreationDate?: string } const rows = Array.isArray(parsed) ? parsed : [parsed] - return rows + if (!rows.length || rows.some(row => !row || typeof row.ProcessId !== 'number' + || !Number.isInteger(row.ProcessId) || row.ProcessId < 0)) { + throw new Error('powershell Win32_Process returned an invalid process snapshot') + } + const processes = rows .map((row) => ({ pid: Number(row.ProcessId), name: row.Name ?? '', @@ -212,6 +221,8 @@ export function listWindowsProcessesWithCommandLine(): ProcessSnapshot[] { : null, })) .filter((proc) => Number.isFinite(proc.pid) && proc.pid > 0) + if (!processes.length) throw new Error('powershell Win32_Process returned no verifiable processes') + return processes } export async function listProcessesForOrphanScan(): Promise { diff --git a/cli/src/runner/run.ts b/cli/src/runner/run.ts index 53053db8..12439871 100644 --- a/cli/src/runner/run.ts +++ b/cli/src/runner/run.ts @@ -15,7 +15,7 @@ import { spawnHappyCLI } from '@/utils/spawnHappyCLI'; import { writeRunnerState, RunnerLocallyPersistedState, readRunnerState, acquireRunnerLock, releaseRunnerLock } from '@/persistence'; import { getCliArgs } from '@/utils/cliArgs'; import { getProcessStartMarker, isProcessAlive, isWindows, killProcess, killProcessByChildProcess, killProcessTreeByPid } from '@/utils/process'; -import { findStopSessionOrphanTargets, reapRunnerSpawnedOrphans } from '@/runner/orphanReap'; +import { findStopSessionOrphanTargets, listWindowsProcessesWithCommandLine, reapRunnerSpawnedOrphans } from '@/runner/orphanReap'; import { decideUntrackedRunnerWebhook } from '@/runner/lateRunnerWebhook'; import { cleanupFailedStartupAfterExit, sessionStartupTimeout, waitForRecoverableStartup } from './sessionStartup'; import { @@ -1163,11 +1163,29 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): const readLiveRuntimesForStop = async () => { try { - return (await readRuntimes({ strict: true })).filter(runtime => + const scanStarted = Date.now(); + const records = (await readRuntimes({ strict: true })).filter(runtime => runtime.hub === configuration.apiUrl && runtime.authHash === runtimeAuthHash() - && runtimeMayBeAlive(runtime) ); + // A fresh, complete process snapshot keeps archive cost independent + // of old registry entries. Per-record tasklist/CIM calls made three + // reads of nine retired runtimes exceed the 30s StopSession RPC. + // Read the registry first, then snapshot; never reuse it across scans. + let markers: ReadonlyMap | undefined; + if (isWindows() && records.length > 0) { + try { + const processes = listWindowsProcessesWithCommandLine(); + if (!processes.length) throw new Error('Empty Windows process snapshot'); + markers = new Map(processes.map(proc => [proc.pid, proc.startMarker ?? null])); + } catch (error) { + logger.warn(`[RUNNER RUN] Cannot verify Windows runtimes during stop of ${sessionId}: ${String(error)}`); + return null; + } + } + const live = records.filter(runtime => runtimeMayBeAlive(runtime, markers)); + logger.debug('[RUNNER RUN] Runtime stop scan', { sessionId, records: records.length, live: live.length, elapsedMs: Date.now() - scanStarted }); + return live; } catch (error) { logger.warn( `[RUNNER RUN] Codex runtime registry unreadable during stop of ${sessionId}: ${ @@ -1359,6 +1377,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): return await finishKeepWrapperDetach(pid); } + let treeTerminationVerified = false; if (session.startedBy === 'runner') { // Adopted post-restart sessions have no ChildProcess handle — still // tree-kill so agent grandchildren cannot outlive the wrapper. @@ -1389,14 +1408,18 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): } } try { + const reportStop: Parameters[2] = report => { + logger.debug('[RUNNER RUN] Session process tree stop proof', { sessionId, ...report }); + }; const treeStopped = session.childProcess - ? await killProcessByChildProcess(session.childProcess) - : await killProcessTreeByPid(pid); + ? await killProcessByChildProcess(session.childProcess, false, reportStop) + : await killProcessTreeByPid(pid, false, reportStop); if (!treeStopped) { logger.debug(`[RUNNER RUN] Process tree for session ${sessionId} is still alive after stop request`); return 'still_alive'; } logger.debug(`[RUNNER RUN] Requested termination for runner-spawned session ${sessionId}`); + treeTerminationVerified = true; } catch (error) { logger.debug(`[RUNNER RUN] Failed to kill session ${sessionId}:`, error); return 'still_alive'; @@ -1419,10 +1442,12 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): spawnSession.markChildStopping(existingSessionId); } const deadline = Date.now() + 5_000; - while (isProcessAlive(pid) && Date.now() < deadline) { + // Full-tree termination already proved this generation exited. A + // second raw-PID probe can observe an unrelated, newly reused PID. + while (!treeTerminationVerified && isProcessAlive(pid) && Date.now() < deadline) { await new Promise(resolve => setTimeout(resolve, 50)); } - if (isProcessAlive(pid)) { + if (!treeTerminationVerified && isProcessAlive(pid)) { logger.debug(`[RUNNER RUN] Session ${sessionId} process ${pid} is still alive after stop request`); return 'still_alive'; } diff --git a/cli/src/utils/process.test.ts b/cli/src/utils/process.test.ts index 5e2f6f9a..7c2b1559 100644 --- a/cli/src/utils/process.test.ts +++ b/cli/src/utils/process.test.ts @@ -41,6 +41,53 @@ function unavailable(command: string) { } describe('getHapiRunnerProcessIdentity on Windows', () => { + it.each(['', '[]', '{}', '{broken', JSON.stringify([{ ProcessId: 100, CreationDate: 'generation' }]), + JSON.stringify([{ ProcessId: process.pid }, { ProcessId: process.pid }]), + JSON.stringify([{ ProcessId: process.pid }, { ProcessId: 1.5 }]), + JSON.stringify([{ ProcessId: process.pid }, { ProcessId: -1 }])])( + 'rejects an unverifiable complete process-generation snapshot: %s', async (stdout) => { + const { readWindowsProcessStartMarkers } = await import('./process') + spawnSyncMock.mockReturnValue(completed(stdout)) + expect(readWindowsProcessStartMarkers()).toBeNull() + } + ) + + it('keeps present processes with unknown creation times distinct from absent processes', async () => { + const { readWindowsProcessStartMarkers } = await import('./process') + spawnSyncMock.mockReturnValue(completed(JSON.stringify([ + { ProcessId: process.pid, CreationDate: 'scanner-generation' }, + { ProcessId: 100, CreationDate: null } + ]))) + const snapshot = readWindowsProcessStartMarkers()! + expect(snapshot.has(100)).toBe(true) + expect(snapshot.get(100)).toBeNull() + expect(snapshot.has(200)).toBe(false) + }) + + it('does not use stdout as a complete snapshot after a failed OS query', async () => { + const { readWindowsProcessStartMarkers } = await import('./process') + const stdout = JSON.stringify([{ ProcessId: process.pid, CreationDate: 'scanner-generation' }]) + spawnSyncMock.mockReturnValue(completed(stdout, 1)) + expect(readWindowsProcessStartMarkers()).toBeNull() + spawnSyncMock.mockReturnValue({ ...completed(stdout), error: new Error('query failed') }) + expect(readWindowsProcessStartMarkers()).toBeNull() + }) + it('reads the generation directly from CIM without a redundant tasklist probe', async () => { + const { getProcessStartMarker } = await import('./process') + spawnSyncMock.mockImplementation((command: string) => command === 'powershell' + ? completed('generation-100') : completed('hapi.exe 100 Console')) + expect(getProcessStartMarker(100)).toBe('generation-100') + expect(spawnSyncMock.mock.calls.filter(call => call[0] === 'tasklist')).toHaveLength(0) + }) + + it('keeps a missing CIM generation unknown and rejects invalid PIDs without probing', async () => { + const { getProcessStartMarker } = await import('./process') + spawnSyncMock.mockReturnValue(completed('')) + expect(getProcessStartMarker(100)).toBeNull() + spawnSyncMock.mockClear() + for (const pid of [0, -1, 1.5, NaN, Infinity]) expect(getProcessStartMarker(pid)).toBeNull() + expect(spawnSyncMock).not.toHaveBeenCalled() + }) beforeAll(() => { if (!originalPlatformDescriptor?.configurable) { throw new Error('process.platform is not configurable in this runtime') @@ -335,6 +382,186 @@ describe('killProcess on Windows (orphanReap / stopSession)', () => { expect(taskkills[0]![1]).toEqual(['/F', '/T', '/PID', '9901']) }) + it('services queued control work between Windows tree generation probes', async () => { + vi.useRealTimers() + const { killProcessTreeByPid } = await import('./process') + const alive = new Set([100, 200]) + let controlServiced = false + let controlServicedBeforeSignalling = false + setImmediate(() => { controlServiced = true }) + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'powershell') { + const script = args.at(-1) ?? '' + return completed(script.includes('ParentProcessId') ? 'OK:200,100' : 'generation') + } + if (cmd === 'tasklist') { + const pid = Number(args.find(a => a.startsWith('PID eq '))?.slice(7)) + return completed(alive.has(pid) ? `proc.exe ${pid} Console` : 'INFO: No tasks') + } + if (cmd === 'taskkill') { + if (alive.size === 2) controlServicedBeforeSignalling = controlServiced + alive.delete(Number(args[args.indexOf('/PID') + 1])) + } + return completed('') + }) + await expect(killProcessTreeByPid(100, true)).resolves.toBe(true) + expect(controlServicedBeforeSignalling).toBe(true) + expect(alive.size).toBe(0) + }) + + it('keeps a single-process tree on individual checks instead of adding bulk enumeration', async () => { + vi.useRealTimers() + const { killProcessTreeByPid } = await import('./process') + const root = 100_001_001;let alive = true, bulkQueries = 0, markerQueries = 0 + spawnSyncMock.mockImplementation((command: string, args: string[] = []) => { + if (command === 'powershell') { + const script = args.at(-1) ?? '' + if (script.includes('ParentProcessId')) return completed(`OK:${root}`) + if (script.includes('Select-Object ProcessId,')) { + bulkQueries++ + return completed(JSON.stringify([ + { ProcessId: process.pid, CreationDate: 'scanner' }, + ...(alive ? [{ ProcessId: root, CreationDate: 'original' }] : []) + ])) + } + markerQueries++;return completed(alive ? 'original' : '') + } + if (command === 'tasklist') return completed(alive ? `process.exe ${root} Console` : 'INFO: No tasks') + if (command === 'taskkill') alive = false + return completed('') + }) + await expect(killProcessTreeByPid(root, true)).resolves.toBe(true) + expect(bulkQueries).toBe(0) + expect(markerQueries).toBe(1) + }) + + it.each(['exited', 'reused', 'root-reused', 'initial-exited'] as const)('batches identity checks while preserving tree generations: %s', async (outcome) => { + vi.useRealTimers() + const { killProcessTreeByPid } = await import('./process') + const root = 100_001_001, child = 100_001_002 + const alive = new Set([root, child]) + const markers = new Map([[root, 'root-generation'], [child, 'child-generation']]) + const signalled: number[] = [] + let singleMarkerProbes = 0, snapshots = 0 + const childTasklistProbes: number[] = [] + spawnSyncMock.mockImplementation((command: string, args: string[] = []) => { + if (command === 'powershell') { + const script = args.at(-1) ?? '' + if (script.includes('ParentProcessId')) return completed(`OK:${child},${root}`) + if (script.includes('Select-Object ProcessId,')) { + snapshots++ + if (snapshots === 1 && outcome === 'initial-exited') alive.delete(child) + const result = completed(JSON.stringify([ + { ProcessId: process.pid, CreationDate: 'scanner-generation' }, + ...[...alive].map(pid => ({ ProcessId: pid, CreationDate: markers.get(pid) })) + ])) + if (snapshots === 1 && outcome === 'root-reused') markers.set(root, 'replacement-generation') + if (snapshots === 1 && outcome === 'initial-exited') { alive.add(child);markers.set(child, 'replacement-generation') } + return result + } + singleMarkerProbes++ + const pid = Number(/ProcessId = (\d+)/.exec(script)?.[1]) + return completed(alive.has(pid) ? markers.get(pid) ?? '' : '') + } + if (command === 'tasklist') { + const pid = Number(args.find(arg => arg.startsWith('PID eq '))?.slice(7)) + if (pid === child) childTasklistProbes.push(pid) + return completed(alive.has(pid) ? `process.exe ${pid} Console` : 'INFO: No tasks') + } + if (command === 'taskkill') { + const pid = Number(args[args.indexOf('/PID') + 1]);signalled.push(pid);alive.delete(pid) + if (outcome === 'exited') alive.delete(child) + else markers.set(child, 'replacement-generation') + } + return completed('') + }) + const report = vi.fn() + await expect(killProcessTreeByPid(root, true, report)).resolves.toBe(true) + expect(signalled).toEqual([outcome === 'root-reused' ? child : root]) + // The root still receives an immediate generation check before its signal. + expect(singleMarkerProbes).toBe(outcome === 'root-reused' ? 2 : 1) + if (outcome !== 'root-reused') expect(childTasklistProbes).toEqual([]) + expect(snapshots).toBe(3) + expect(report).toHaveBeenCalledWith(expect.objectContaining({ + outcome: 'verified', members: expect.arrayContaining([expect.objectContaining({ + pid: child, resolution: outcome === 'reused' ? 'generation_changed' : 'exited' + })]) + })) + if (outcome === 'root-reused') { + expect(alive.has(root)).toBe(true) + expect(report).toHaveBeenCalledWith(expect.objectContaining({ members: expect.arrayContaining([ + expect.objectContaining({ pid: root, resolution: 'generation_changed' }) + ]) })) + } + }) + + it('rechecks a survivor immediately before signalling when its batch observation is stale', async () => { + vi.useRealTimers() + const { killProcessTreeByPid } = await import('./process') + const root = 100_001_001, child = 100_001_002 + const alive = new Set([root, child]);let generation = 'original';let snapshots = 0 + const signalled: number[] = [] + spawnSyncMock.mockImplementation((command: string, args: string[] = []) => { + if (command === 'powershell') { + const script = args.at(-1) ?? '' + if (script.includes('ParentProcessId')) return completed(`OK:${child},${root}`) + if (script.includes('Select-Object ProcessId,')) { + snapshots++ + const result = completed(JSON.stringify([ + { ProcessId: process.pid, CreationDate: 'scanner' }, + ...[...alive].map(pid => ({ ProcessId: pid, CreationDate: generation })) + ])) + if (snapshots === 2) generation = 'replacement' + return result + } + return completed(generation) + } + if (command === 'tasklist') { + const pid = Number(args.find(arg => arg.startsWith('PID eq '))?.slice(7)) + return completed(alive.has(pid) ? `process.exe ${pid} Console` : 'INFO: No tasks') + } + if (command === 'taskkill') { + const pid = Number(args[args.indexOf('/PID') + 1]);signalled.push(pid);alive.delete(pid) + } + return completed('') + }) + await expect(killProcessTreeByPid(root, true)).resolves.toBe(true) + expect(signalled).toEqual([root]) + expect(alive.has(child)).toBe(true) + expect(snapshots).toBe(3) + }) + + it('cannot confirm a present survivor with unknown generation from an otherwise valid snapshot', async () => { + const { killProcessTreeByPid } = await import('./process') + const root = 100_001_001, child = 100_001_002 + const alive = new Set([root, child]);const signalled: number[] = [] + spawnSyncMock.mockImplementation((command: string, args: string[] = []) => { + if (command === 'powershell') { + const script = args.at(-1) ?? '' + if (script.includes('ParentProcessId')) return completed(`OK:${child},${root}`) + if (script.includes('Select-Object ProcessId,')) return completed(JSON.stringify([ + { ProcessId: process.pid, CreationDate: 'scanner' }, + ...[...alive].map(pid => ({ ProcessId: pid, CreationDate: pid === child ? null : 'original' })) + ])) + if (script.includes(`ProcessId = ${root}`)) return completed('original') + throw new Error('A verified batch must not downgrade unknown descendant identity to a per-PID guess') + } + if (command === 'tasklist') { + const pid = Number(args.find(arg => arg.startsWith('PID eq '))?.slice(7)) + return completed(alive.has(pid) ? `process.exe ${pid} Console` : 'INFO: No tasks') + } + if (command === 'taskkill') { + const pid = Number(args[args.indexOf('/PID') + 1]);signalled.push(pid);alive.delete(pid) + } + return completed('') + }) + const report = vi.fn();const done = killProcessTreeByPid(root, true, report) + await vi.advanceTimersByTimeAsync(3_000) + await expect(done).resolves.toBe(false) + expect(signalled).toEqual([root]) + expect(report).toHaveBeenCalledWith(expect.objectContaining({ outcome: 'unconfirmed' })) + }) + it('killProcessTreeByPid signals surviving descendants after taskkill /T misses them', async () => { // #1911 bot Major: taskkill /T exit 0 is "signalled", not "tree gone". // When the root dies but a grandchild survives (broken intermediate link), @@ -396,8 +623,98 @@ describe('killProcess on Windows (orphanReap / stopSession)', () => { expect(alive.size).toBe(0) }) + it('waits for an unverifiable descendant to finish exiting without signalling it', async () => { + const { killProcessTreeByPid } = await import('./process') + const alive = new Set([100, 200]) + const signalled: number[] = [] + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'powershell') { + const script = args.at(-1) ?? '' + if (script.includes('ParentProcessId')) return completed('OK:200,100') + return completed(script.includes('ProcessId = 100') ? 'generation-100' : '') + } + if (cmd === 'tasklist') { + const pid = Number(args.find(a => a.startsWith('PID eq '))?.slice(7)) + return completed(alive.has(pid) ? `proc.exe ${pid} Console` : 'INFO: No tasks') + } + if (cmd === 'taskkill') { + const pid = Number(args[args.indexOf('/PID') + 1]) + signalled.push(pid);alive.delete(pid) + setTimeout(() => alive.delete(200), 200) + } + return completed('') + }) + const done = killProcessTreeByPid(100, true) + await vi.advanceTimersByTimeAsync(3_000) + await expect(done).resolves.toBe(true) + expect(signalled).toEqual([100]) + }) + + it('does not reintroduce an exited tree member when its PID is reused during the grace wait', async () => { + const { killProcessTreeByPid } = await import('./process') + const alive = new Set([100, 200, 300]) + const signalled: number[] = [] + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'powershell') { + const script = args.at(-1) ?? '' + if (script.includes('ParentProcessId')) return completed('OK:300,200,100') + return completed(script.includes('ProcessId = 300') ? '' : 'generation') + } + if (cmd === 'tasklist') { + const pid = Number(args.find(a => a.startsWith('PID eq '))?.slice(7)) + return completed(alive.has(pid) ? `proc.exe ${pid} Console` : 'INFO: No tasks') + } + if (cmd === 'taskkill') { + const pid = Number(args[args.indexOf('/PID') + 1]) + signalled.push(pid); alive.delete(pid); alive.delete(200) + setTimeout(() => alive.add(200), 100) + setTimeout(() => alive.delete(300), 200) + } + return completed('') + }) + const done = killProcessTreeByPid(100, true) + await vi.advanceTimersByTimeAsync(3_000) + await expect(done).resolves.toBe(true) + expect(signalled).toEqual([100]) + expect(alive.has(200)).toBe(true) + }) + + it('fails closed without signalling a surviving descendant whose generation cannot be read', async () => { + const { killProcessTreeByPid } = await import('./process') + const report = vi.fn() + const alive = new Set([100, 200]) + const signalled: number[] = [] + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'powershell') { + const script = args.at(-1) ?? '' + if (script.includes('ParentProcessId')) return completed('OK:200,100') + return completed(script.includes('ProcessId = 100') ? 'generation-100' : '') + } + if (cmd === 'tasklist') { + const pid = Number(args.find(a => a.startsWith('PID eq '))?.slice(7)) + return completed(alive.has(pid) ? `proc.exe ${pid} Console` : 'INFO: No tasks') + } + if (cmd === 'taskkill') { + const pid = Number(args[args.indexOf('/PID') + 1]) + signalled.push(pid); alive.delete(pid) + } + return completed('') + }) + const done = killProcessTreeByPid(100, true, report) + await vi.advanceTimersByTimeAsync(3_000) + await expect(done).resolves.toBe(false) + expect(signalled).toEqual([100]) + expect(alive.has(200)).toBe(true) + expect(report).toHaveBeenCalledTimes(1) + expect(report.mock.calls[0]![0]).toMatchObject({ + rootPid: 100, outcome: 'unconfirmed', + members: expect.arrayContaining([expect.objectContaining({pid: 200, expectedMarker: null, alive: true})]) + }) + }) + it('killProcessTreeByPid does not kill a surviving PID that was reused', async () => { const { killProcessTreeByPid } = await import('./process') + const report = vi.fn((_report: import('./process').ProcessTreeStopReport) => { throw new Error('diagnostic sink unavailable') }) const alive = new Set([100, 200]) // After root kill, PID 200 is recycled with a new generation marker. let rootGone = false @@ -451,12 +768,20 @@ describe('killProcess on Windows (orphanReap / stopSession)', () => { return completed('') }) - const done = killProcessTreeByPid(100, true) - await vi.advanceTimersByTimeAsync(500) - // Root signalled; reused descendant left alone → tree verify fails closed. - await expect(done).resolves.toBe(false) + const done = killProcessTreeByPid(100, true, report) + await vi.advanceTimersByTimeAsync(3_000) + // A different creation marker proves the original descendant exited. + // The new process must remain alive and must not block archive. + await expect(done).resolves.toBe(true) expect(taskkillPids).toEqual([100]) expect(alive.has(200)).toBe(true) + expect(report).toHaveBeenCalledTimes(1) + expect(report.mock.calls[0]![0]).toMatchObject({ + rootPid: 100, outcome: 'verified', + members: expect.arrayContaining([expect.objectContaining({ + pid: 200, expectedMarker: 'gen-200', observedMarker: 'gen-200-reused', resolution: 'generation_changed' + })]) + }) }) it('windowsProcessTreeCimCommand is newline-separated (WinPS-parseable)', async () => { @@ -464,8 +789,8 @@ describe('killProcess on Windows (orphanReap / stopSession)', () => { // Assert generated command text, not mocked stdout (mocks never parse PS). const { windowsProcessTreeCimCommand } = await import('./process') const cmd = windowsProcessTreeCimCommand(4242) - expect(cmd).toContain('$root=4242') - expect(cmd).toContain('ParentProcessId=$p') + expect(cmd).toContain('$root=[long]4242') + expect(cmd).toContain('ParentProcessId') // Statements must be on separate lines — spaces between `$x=@{}` tokens fail. expect(cmd).toContain('\n$seen=@{}') expect(cmd).toContain('\n$bfs=@()') diff --git a/cli/src/utils/process.ts b/cli/src/utils/process.ts index 5acea9b8..3786e760 100644 --- a/cli/src/utils/process.ts +++ b/cli/src/utils/process.ts @@ -73,8 +73,10 @@ export function windowsProcessMarkerCimCommand(pid: number): string { /** Stable marker for one OS PID generation; null means the platform probe failed. */ export function getProcessStartMarker(pid: number): string | null { - if (!isProcessAlive(pid)) return null; + if (!Number.isInteger(pid) || pid <= 0) return null; if (isWindows()) { + // CIM already answers whether this PID has a readable generation. A + // preceding tasklist adds a process launch without strengthening identity. // Same UTC ISO 'o' string as orphanReap listWindowsProcessesWithCommandLine. // Do not print raw DateTime or use WMIC DMTF (format mismatch skips reap). const powershell = spawn.sync('powershell', [ @@ -87,6 +89,7 @@ export function getProcessStartMarker(pid: number): string | null { } return null; } + if (!isProcessAlive(pid)) return null; const result = spawn.sync('ps', ['-p', String(pid), '-o', 'lstart='], { stdio: 'pipe', env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' }, @@ -96,6 +99,38 @@ export function getProcessStartMarker(pid: number): string | null { return result.stdout?.toString().trim() || null; } +/** A fresh complete listing. Null means unavailable, never proof of absence. */ +export function readWindowsProcessStartMarkers(): ReadonlyMap | null { + if (!isWindows()) return null; + try { + const command = [ + "$ErrorActionPreference='Stop'", + 'trap { exit 1 }', + 'Get-CimInstance Win32_Process | Select-Object ProcessId,' + + `@{N='CreationDate';E={if ($_.CreationDate) { ${WINDOWS_CIM_CREATION_DATE_MARKER_EXPR} } else { $null }}}` + + ' | ConvertTo-Json -Compress', + ].join('\n'); + const result = spawn.sync('powershell', ['-NoProfile', '-NonInteractive', '-Command', command], { + encoding: 'utf8', windowsHide: true, timeout: SPAWN_SYNC_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 + }); + if (result.error || result.status !== 0) return null; + const parsed: unknown = JSON.parse(result.stdout?.toString() ?? ''); + const rows = Array.isArray(parsed) ? parsed : [parsed]; + const markers = new Map(); + for (const value of rows) { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const row = value as Record; + if (typeof row.ProcessId !== 'number' || !Number.isInteger(row.ProcessId) + || row.ProcessId < 0 || markers.has(row.ProcessId)) return null; + markers.set(row.ProcessId, typeof row.CreationDate === 'string' && row.CreationDate.length > 0 + ? row.CreationDate : null); + } + // This caller remains alive for the whole query. Missing it makes the + // listing unverifiable; do not infer that any other PID has exited. + return markers.has(process.pid) ? markers : null; + } catch { return null; } +} + // ponytail: ps -p is cheap and avoids PID-reuse false positives after OS upgrades/reboots function isRunnerCommand(commandLine: string): boolean { return /(?:^|\s)runner(?:\s|$)/.test(commandLine) && /(?:^|\s)start-sync(?:\s|$)/.test(commandLine); @@ -218,7 +253,17 @@ export function windowsProcessTreeCimCommand(pid: number): string { return [ "$ErrorActionPreference='Stop'", 'trap { exit 1 }', - `$root=${pid}`, + `$root=[long]${pid}`, + // One complete enumeration keeps cost independent of tree depth. Build + // parent links from the same observation, rather than querying each parent. + '$processes=@(Get-CimInstance Win32_Process)', + 'if($processes.Count -eq 0 -or -not ($processes | Where-Object ProcessId -eq $PID)){ throw "Incomplete process snapshot" }', + '$children=@{}', + 'foreach($process in $processes){', + ' $parent=[long]$process.ParentProcessId', + ' if(-not $children.ContainsKey($parent)){ $children[$parent]=[System.Collections.Generic.List[long]]::new() }', + ' $children[$parent].Add([long]$process.ProcessId)', + '}', '$seen=@{}', '$bfs=@()', '$queue=@($root)', @@ -227,8 +272,7 @@ export function windowsProcessTreeCimCommand(pid: number): string { ' if($seen.ContainsKey($p)){continue}', ' $seen[$p]=$true', ' $bfs+=$p', - ' Get-CimInstance Win32_Process -Filter "ParentProcessId=$p" |', - ' ForEach-Object { $queue+=,[int]$_.ProcessId }', + ' if($children.ContainsKey($p)){ foreach($child in $children[$p]){ $queue+=,$child } }', '}', // children-first: reverse BFS so root is last; OK: marks clean completion 'if($bfs.Count -gt 0){ [array]::Reverse($bfs); Write-Output ("OK:" + ($bfs -join ",")) }', @@ -385,37 +429,137 @@ async function killProcessTree(pid: number, force: boolean): Promise { return pids.every((candidate) => !isProcessAlive(candidate)); } +export type ProcessTreeStopReport = { + rootPid: number; + outcome: 'verified' | 'scan_failed' | 'unconfirmed'; + elapsedMs: number; + phaseMs: Record; + members: Array<{ + pid: number; + expectedMarker: string | null; + observedMarker?: string | null; + alive?: boolean; + observedAt?: number; + resolution?: 'exited' | 'generation_changed'; + }>; +}; + /** Kill a PID and all descendants, verifying the complete tree is gone. */ -export async function killProcessTreeByPid(pid: number, force: boolean = false): Promise { +export async function killProcessTreeByPid( + pid: number, + force: boolean = false, + onReport?: (report: ProcessTreeStopReport) => void +): Promise { const n = typeof pid === 'number' ? pid : Number(pid) if (!Number.isFinite(n) || n <= 0) return false; if (isWindows()) { + const started = Date.now(); + const phaseMs: Record = {}; + const members = new Map(); + const finish = (outcome: ProcessTreeStopReport['outcome']): boolean => { + // Report observations already made by the verifier. Re-probing here can + // both hide the failing instant and add seconds to an archive request. + try { onReport?.({ rootPid: n, outcome, elapsedMs: Date.now() - started, phaseMs, members: [...members.values()] }); } + catch { /* Diagnostics must not change the termination decision. */ } + return outcome === 'verified'; + }; // taskkill /T exit 0 means "signalled", not "every descendant is dead". // Collect the tree + generation markers first, signal the root with /T, // then individually signal any surviving pre-kill PIDs whose generation // still matches (PID reuse must not be killed) (#1911 bot Major). const treePids = collectWindowsProcessTree(n); + phaseMs.scan = Date.now() - started; if (treePids === 'scan_failed') { // Still signal the (known) root — scan failure must not mean zero kill — // but never claim stopped without a full-tree verify (#1911 Opus Major). await signalAndWaitWindowsRoot(n, force); - return false; + phaseMs.signal = Date.now() - started - phaseMs.scan; + return finish('scan_failed'); } + // A leaf needs only one identity probe. Do not add full enumerations to + // the common model-discovery cleanup path, which has no descendants. + const useSnapshot = treePids.length > 1; + const initialSnapshot = useSnapshot ? readWindowsProcessStartMarkers() : null; const markers = new Map(); for (const candidate of treePids) { - markers.set(candidate, getProcessStartMarker(candidate)); + // The bulk observation is fresh for this phase. If it was unavailable, + // retain individual identity checks and service control work between them. + await new Promise(resolve => setImmediate(resolve)); + markers.set(candidate, initialSnapshot ? initialSnapshot.get(candidate) ?? null : getProcessStartMarker(candidate)); + members.set(candidate, { pid: candidate, expectedMarker: markers.get(candidate) ?? null }); + if (initialSnapshot && !initialSnapshot.has(candidate)) { + Object.assign(members.get(candidate)!, { alive: false, resolution: 'exited', observedAt: Date.now() }); + } } - await signalAndWaitWindowsRoot(n, force); + phaseMs.markers = Date.now() - started - phaseMs.scan; + const signallingStarted = Date.now(); + let signalRoot = !initialSnapshot || initialSnapshot.has(n); + const rootMarker = markers.get(n); + if (initialSnapshot && rootMarker) { + const current = getProcessStartMarker(n); + Object.assign(members.get(n)!, { observedMarker: current, observedAt: Date.now() }); + signalRoot = current === rootMarker; + } + if (signalRoot) await signalAndWaitWindowsRoot(n, force); + const survivorSnapshot = useSnapshot ? readWindowsProcessStartMarkers() : null; for (const survivor of treePids) { + await new Promise(resolve => setImmediate(resolve)); if (survivor === n) continue; - if (!isProcessAlive(survivor)) continue; const expected = markers.get(survivor); + if (survivorSnapshot) { + if (!survivorSnapshot.has(survivor)) continue; + const observed = survivorSnapshot.get(survivor); + Object.assign(members.get(survivor)!, { observedMarker: observed, observedAt: Date.now() }); + if (!expected || !observed || observed !== expected) continue; + } else if (!isProcessAlive(survivor)) continue; + // A previous batch can become stale while another survivor is stopped. + // Recheck this exact generation immediately before signalling it. const current = getProcessStartMarker(survivor); - // Unverifiable or reused PID — leave alone; final every() fails closed. + Object.assign(members.get(survivor)!, { observedMarker: current, observedAt: Date.now() }); + // Unverifiable or reused PID — never signal the new/unknown process. if (!expected || !current || current !== expected) continue; await signalAndWaitWindowsRoot(survivor, true); } - return treePids.every((candidate) => !isProcessAlive(candidate)); + phaseMs.signal = Date.now() - signallingStarted; + // A wrapper can exit before its descendants finish draining. Keep the + // full-tree proof, allowing a bounded grace period without signalling an + // unverified or reused PID. + const deadline = Date.now() + 2_000; + const verificationStarted = Date.now(); + const remaining = new Set(treePids.filter(candidate => !members.get(candidate)?.resolution)); + for (;;) { + const verificationSnapshot = useSnapshot ? readWindowsProcessStartMarkers() : null; + for (const candidate of remaining) { + await new Promise(resolve => setImmediate(resolve)); + const member = members.get(candidate)!; + const alive = verificationSnapshot ? verificationSnapshot.has(candidate) : isProcessAlive(candidate); + Object.assign(member, { alive, observedAt: Date.now() }); + if (!alive) { + member.resolution = 'exited'; + remaining.delete(candidate); + continue; + } + const expected = markers.get(candidate); + const current = expected ? verificationSnapshot + ? verificationSnapshot.get(candidate) ?? null : getProcessStartMarker(candidate) : null; + member.observedMarker = current; + // A different known generation proves this tree member exited. Once + // proven gone, a PID must never re-enter the tree through later reuse. + // A missing marker alone is ambiguous and cannot prove termination. + if (expected && current && current !== expected) { + member.resolution = 'generation_changed'; + remaining.delete(candidate); + } else if (!verificationSnapshot && !isProcessAlive(candidate)) { + Object.assign(member, { alive: false, resolution: 'exited' }); + remaining.delete(candidate); + } + member.observedAt = Date.now(); + } + phaseMs.verify = Date.now() - verificationStarted; + if (remaining.size === 0) return finish('verified'); + if (Date.now() >= deadline) return finish('unconfirmed'); + await new Promise(resolve => setTimeout(resolve, 100)); + } } return killProcessTree(n, force); } @@ -457,7 +601,8 @@ async function waitForProcessToDie(pid: number, force: boolean): Promise { export async function killProcessByChildProcess( child: ChildProcess, - force: boolean = false + force: boolean = false, + onReport?: (report: ProcessTreeStopReport) => void ): Promise { const pid = child.pid; if (!pid) { @@ -465,5 +610,5 @@ export async function killProcessByChildProcess( } // Both platforms: tree-kill + full-tree verify (win32 must not trust root-only). - return killProcessTreeByPid(pid, force); + return killProcessTreeByPid(pid, force, onReport); } diff --git a/cli/src/utils/windowsProcessTree.pwsh.test.ts b/cli/src/utils/windowsProcessTree.pwsh.test.ts index 607bbf35..1295baab 100644 --- a/cli/src/utils/windowsProcessTree.pwsh.test.ts +++ b/cli/src/utils/windowsProcessTree.pwsh.test.ts @@ -67,13 +67,12 @@ describePwsh('windowsProcessTreeCimCommand under real pwsh (#1911 B1)', () => { const mock = ` function Get-CimInstance { param($ClassName, $Filter) - $ppid = [int](($Filter -split "=")[1]) - if ($ppid -eq 1234) { - [pscustomobject]@{ ProcessId = 2000 } - [pscustomobject]@{ ProcessId = 3000 } - } elseif ($ppid -eq 2000) { - [pscustomobject]@{ ProcessId = 4000 } - } + # A healthy full enumeration includes parent links and the scanner itself. + [pscustomobject]@{ ProcessId = 1234; ParentProcessId = 0 } + [pscustomobject]@{ ProcessId = 2000; ParentProcessId = 1234 } + [pscustomobject]@{ ProcessId = 3000; ParentProcessId = 1234 } + [pscustomobject]@{ ProcessId = 4000; ParentProcessId = 2000 } + [pscustomobject]@{ ProcessId = $PID; ParentProcessId = 0 } } ${windowsProcessTreeCimCommand(1234)} ` @@ -84,7 +83,11 @@ ${windowsProcessTreeCimCommand(1234)} it('emits OK:root alone when the mocked tree has no children', () => { const mock = ` -function Get-CimInstance { param($ClassName, $Filter) } +function Get-CimInstance { + param($ClassName, $Filter) + [pscustomobject]@{ ProcessId = 1234; ParentProcessId = 0 } + [pscustomobject]@{ ProcessId = $PID; ParentProcessId = 0 } +} ${windowsProcessTreeCimCommand(1234)} ` const result = runPwsh(mock) diff --git a/cli/src/utils/windowsProcessTreeQuery.test.ts b/cli/src/utils/windowsProcessTreeQuery.test.ts new file mode 100644 index 00000000..8a277407 --- /dev/null +++ b/cli/src/utils/windowsProcessTreeQuery.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { execFileSync } from 'node:child_process' +import { windowsProcessTreeCimCommand } from './process' + +// Execute the actual generated WinPS query against an in-memory CIM fixture. +// No process is signalled by this test. +describe.skipIf(process.platform !== 'win32')('Windows process-tree query', () => { + it('uses one CIM enumeration across the Windows PID range and terminates on parent cycles', () => { + const setup = ` +$script:calls=0 +$script:rows=@( + [pscustomobject]@{ProcessId=100;ParentProcessId=300}, + [pscustomobject]@{ProcessId=200;ParentProcessId=100}, + [pscustomobject]@{ProcessId=300;ParentProcessId=200}, + [pscustomobject]@{ProcessId=[uint32]3000000000;ParentProcessId=200}, + [pscustomobject]@{ProcessId=400;ParentProcessId=[uint32]4000000000}, + [pscustomobject]@{ProcessId=$PID;ParentProcessId=0} +) +function Get-CimInstance { + param([string]$ClassName,[string]$Filter) + $script:calls++ + if($Filter){ + $parent=[int]($Filter -replace 'ParentProcessId=','') + return $script:rows|Where-Object ParentProcessId -eq $parent + } + return $script:rows +} +` + const output = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', + setup + windowsProcessTreeCimCommand(100) + '\n"COUNT:$script:calls"'], + { encoding: 'utf8', windowsHide: true, timeout: 10_000 }) + expect(output).toContain('OK:3000000000,300,200,100') + expect(output).toContain('COUNT:1') + }) + + it('never emits a success sentinel when CIM enumeration fails', () => { + const script = "function Get-CimInstance { throw 'fixture CIM failure' }\n" + windowsProcessTreeCimCommand(100) + let failure: { status?: number; stdout?: string } | undefined + try { + execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], + { encoding: 'utf8', windowsHide: true, timeout: 10_000, stdio: 'pipe' }) + } catch (error) { failure = error as typeof failure } + expect(failure).toBeDefined() + expect(failure?.status).not.toBe(0) + expect(failure?.stdout ?? '').not.toContain('OK:') + }) + + it.each(['@()', '@([pscustomobject]@{ProcessId=100;ParentProcessId=0})'])( + 'rejects an empty or partial enumeration without success: %s', (rows) => { + const script = `function Get-CimInstance { ${rows} }\n` + windowsProcessTreeCimCommand(100) + let failure: { status?: number; stdout?: string } | undefined + try { + execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], + { encoding: 'utf8', windowsHide: true, timeout: 10_000, stdio: 'pipe' }) + } catch (error) { failure = error as typeof failure } + expect(failure).toBeDefined() + expect(failure?.status).not.toBe(0) + expect(failure?.stdout ?? '').not.toContain('OK:') + } + ) +})