From 8c602eb7a152ec953bb019b8119a289290db579a Mon Sep 17 00:00:00 2001 From: Ananovo Date: Mon, 2 Nov 2026 18:03:26 +0800 Subject: [PATCH] fix(cli,hub): prevent premature archive failures on Windows (#2126) * fix(cli,hub): prevent premature archive failures on Windows * fix(cli): preserve tree-wide forced shutdown escalation * fix(cli): stop disconnected survivor subtrees completely * test(hub): assert structured archive cleanup uncertainty * fix(cli): use invariant Windows process markers * fix(cli): attempt Windows termination when CIM fails --- cli/src/codex/shared/registry.test.ts | 10 + cli/src/codex/shared/registry.ts | 11 +- cli/src/runner/orphanReap.ts | 31 +- cli/src/runner/run.ts | 59 +- cli/src/runner/stopSessionRequests.test.ts | 27 + cli/src/runner/stopSessionRequests.ts | 15 + cli/src/utils/process.test.ts | 507 ------------------ cli/src/utils/process.ts | 134 +---- .../utils/windowsProcessStop.native.test.ts | 42 ++ cli/src/utils/windowsProcessStop.test.ts | 213 ++++++++ cli/src/utils/windowsProcessStop.ts | 238 ++++++++ hub/README.md | 6 + hub/src/sync/archiveCleanupError.ts | 16 + hub/src/sync/archivedFork.test.ts | 5 +- hub/src/sync/rpcGateway.test.ts | 14 + hub/src/sync/rpcGateway.ts | 27 +- hub/src/sync/syncEngine.ts | 61 ++- hub/src/sync/syncEngineArchiveSession.test.ts | 63 ++- hub/src/web/routes/sessions.test.ts | 22 + hub/src/web/routes/sessions.ts | 17 +- 20 files changed, 805 insertions(+), 713 deletions(-) create mode 100644 cli/src/runner/stopSessionRequests.test.ts create mode 100644 cli/src/runner/stopSessionRequests.ts create mode 100644 cli/src/utils/windowsProcessStop.native.test.ts create mode 100644 cli/src/utils/windowsProcessStop.test.ts create mode 100644 cli/src/utils/windowsProcessStop.ts create mode 100644 hub/src/sync/archiveCleanupError.ts diff --git a/cli/src/codex/shared/registry.test.ts b/cli/src/codex/shared/registry.test.ts index 6fe2b84c..d702cfa8 100644 --- a/cli/src/codex/shared/registry.test.ts +++ b/cli/src/codex/shared/registry.test.ts @@ -42,6 +42,16 @@ describe('shared runtime ownership', () => { expect(runtimeMayBeAlive(owner, new Map())).toBe(false); expect(runtimeMayBeAlive(owner, new Map([[1111, owner.marker]]))).toBe(true); }); + it('uses one supplied snapshot without weakening orphan-engine and unknown-marker protection', async () => { + const owner = await fixture(); + const table: import('@/utils/windowsProcessStop').WindowsProcessTable = new Map([[1111, { parentPid: 1, marker: 'reused', name: '', commandLine: '' }], + [2222, { parentPid: 1, marker: 'server-start', name: '', commandLine: '' }]]); + expect(runtimeMayBeAlive(owner, table)).toBe(true); + table.delete(2222); expect(runtimeMayBeAlive(owner, table)).toBe(false); + table.set(1111, { parentPid: 1, marker: null, name: '', commandLine: '' }); + expect(runtimeMayBeAlive(owner, table)).toBe(true); + expect(runtimeMayBeAlive(owner, null)).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 3ad2b3ad..190593e5 100644 --- a/cli/src/codex/shared/registry.ts +++ b/cli/src/codex/shared/registry.ts @@ -6,6 +6,7 @@ import { realpathSync } from 'node:fs'; import { z } from 'zod'; import { configuration } from '@/configuration'; import { getProcessStartMarker, isProcessAlive } from '@/utils/process'; +import { windowsGenerationMayBeAlive, type WindowsProcessTable } from '@/utils/windowsProcessStop'; import { withSettingsFileLock } from '@hapi/protocol/settingsFileLock'; const RuntimeSchema = z.object({ @@ -32,10 +33,12 @@ export function runtimeAlive(record: CodexRuntimeRecord): boolean { return isProcessAlive(record.pid) && getProcessStartMarker(record.pid) === record.marker; } -function generationMayBeAlive(pid: number, marker?: string, snapshot?: ReadonlyMap): boolean { - if (snapshot) { +function generationMayBeAlive(pid: number, marker?: string, snapshot?: ReadonlyMap | WindowsProcessTable | null): boolean { + if (snapshot !== undefined) { + if (snapshot === null) return true; if (!snapshot.has(pid)) return false; - const actual = snapshot.get(pid); + const entry = snapshot.get(pid); + const actual = typeof entry === 'object' && entry !== null ? entry.marker : entry; return !actual || !marker || actual === marker; } if (!isProcessAlive(pid)) return false; @@ -43,7 +46,7 @@ function generationMayBeAlive(pid: number, marker?: string, snapshot?: ReadonlyM // A failed OS probe is not evidence that the engine exited. return !actual || !marker || actual === marker; } -export function runtimeMayBeAlive(owner: CodexRuntimeRecord, snapshot?: ReadonlyMap): boolean { +export function runtimeMayBeAlive(owner: CodexRuntimeRecord, snapshot?: ReadonlyMap | WindowsProcessTable | null): boolean { return generationMayBeAlive(owner.pid, owner.marker, snapshot) || Boolean(owner.serverPid && generationMayBeAlive(owner.serverPid, owner.serverMarker, snapshot)); } diff --git a/cli/src/runner/orphanReap.ts b/cli/src/runner/orphanReap.ts index 6d3831b0..58d7d26b 100644 --- a/cli/src/runner/orphanReap.ts +++ b/cli/src/runner/orphanReap.ts @@ -16,6 +16,7 @@ import spawn from 'cross-spawn' import { getProcessStartMarker, isProcessAlive, windowsProcessListCimCommand } from '@/utils/process' +import { readWindowsProcessTable } from '@/utils/windowsProcessStop' export type ProcessSnapshot = { pid: number @@ -227,7 +228,11 @@ export function parseWindowsProcessSnapshot(stdout: string): ProcessSnapshot[] { export async function listProcessesForOrphanScan(): Promise { if (process.platform === 'win32') { - return listWindowsProcessesWithCommandLine() + const table = await readWindowsProcessTable(15_000, undefined, true) + if (!table) throw new Error('Cannot verify Windows orphan process snapshot') + return [...table].map(([pid, entry]) => ({ + pid, name: entry.name, cmd: entry.commandLine, startMarker: entry.marker, + })) } return listPosixProcessesWithStartMarker() } @@ -288,16 +293,20 @@ export async function reapRunnerSpawnedOrphans( /** @deprecated Prefer findTargets (includes same-snapshot markers). */ findOrphans?: (sessionId: string) => Promise killTree?: (pid: number) => Promise - getStartMarker?: (pid: number) => string | null - isAlive?: (pid: number) => boolean + getStartMarker?: (pid: number) => string | null | Promise + isAlive?: (pid: number) => boolean | Promise } = {} ): Promise<'stopped' | 'still_alive' | null> { const killTree = deps.killTree ?? (async (pid: number) => { const { killProcessTreeByPid } = await import('@/utils/process') return killProcessTreeByPid(pid) }) - const getStartMarker = deps.getStartMarker ?? getProcessStartMarker - const isAlive = deps.isAlive ?? isProcessAlive + const getStartMarker = deps.getStartMarker ?? (process.platform === 'win32' + ? async (pid: number) => (await readWindowsProcessTable(10_000, [pid]))?.get(pid)?.marker ?? null + : getProcessStartMarker) + const isAlive = deps.isAlive ?? (process.platform === 'win32' + ? async (pid: number) => { const table = await readWindowsProcessTable(10_000, [pid]); return table === null || table.has(pid) } + : isProcessAlive) let targets: OrphanTarget[] if (deps.findTargets) { @@ -308,10 +317,10 @@ export async function reapRunnerSpawnedOrphans( // Legacy: pids only — capture markers in a separate probe (tests / older callers). const orphanPids = await deps.findOrphans(sessionId) if (orphanPids === 'scan_failed') return 'still_alive' - targets = orphanPids.map((pid) => ({ + targets = await Promise.all(orphanPids.map(async (pid) => ({ pid, - startMarker: getStartMarker(pid), - })) + startMarker: await getStartMarker(pid), + }))) } else { const found = await findRunnerSpawnedOrphanTargets(sessionId) if (found === 'scan_failed') return 'still_alive' @@ -330,7 +339,7 @@ export async function reapRunnerSpawnedOrphans( // No generation identity from the match snapshot. If the PID is // already dead the orphan is gone; if still alive, skip kill and // continue other targets (do not abort the whole sweep). - if (!isAlive(orphanPid)) { + if (!await isAlive(orphanPid)) { resolved++ continue } @@ -338,12 +347,12 @@ export async function reapRunnerSpawnedOrphans( continue } - const currentMarker = getStartMarker(orphanPid) + const currentMarker = await getStartMarker(orphanPid) if (currentMarker === null) { // Probe failed mid-flight. Null is not proof of PID reuse (psutil // lesson: unknown create_time ≠ recycled). Skip kill; if still // alive, mark unconfirmed and continue. - if (!isAlive(orphanPid)) { + if (!await isAlive(orphanPid)) { resolved++ continue } diff --git a/cli/src/runner/run.ts b/cli/src/runner/run.ts index fc912d50..386c0799 100644 --- a/cli/src/runner/run.ts +++ b/cli/src/runner/run.ts @@ -43,6 +43,8 @@ import { buildMachineMetadata } from '@/agent/sessionFactory'; import { resolveWorkspaceRoots } from '@/utils/workspaceRoot'; import { hashRunnerCliApiToken, hashRunnerExtraHeaders } from './runnerIdentity'; import { readRuntimes, runtimeMayBeAlive, runtimeAuthHash } from '@/codex/shared/registry'; +import { readWindowsProcessTable } from '@/utils/windowsProcessStop'; +import { coalesceStopRequests } from './stopSessionRequests'; import { scheduleCursorModelsPrewarm } from '@/modules/common/cursorModelsPrewarm'; import { isLinkedGitWorktree } from '@/utils/isLinkedGitWorktree'; import { agentUnavailableMessage, getAgentAvailability } from '@/agent/agentAvailability'; @@ -128,7 +130,8 @@ export function classifyRecoveredProcessGeneration( export function probeRecoveredProcessGeneration( pid: number, - record: { processStartMarker: string; bootId?: string } + record: { processStartMarker: string; bootId?: string }, + currentMarker?: string | null ): 'verified' | 'quarantined' | 'exited' { if (!isProcessAlive(pid)) return 'exited'; const evidence = { @@ -138,7 +141,7 @@ export function probeRecoveredProcessGeneration( persistedBootId: record.bootId, }; if (classifyRecoveredProcessGeneration(true, null, record.processStartMarker, evidence) === 'exited') return 'exited'; - return classifyRecoveredProcessGeneration(true, getProcessStartMarker(pid), record.processStartMarker, evidence); + return classifyRecoveredProcessGeneration(true, currentMarker !== undefined ? currentMarker : getProcessStartMarker(pid), record.processStartMarker, evidence); } export function releaseRecoveredSpawnDedupe( @@ -1160,7 +1163,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): } // Stop a session by sessionId or PID fallback - const stopSession = async ( + const stopSession = coalesceStopRequests(async ( sessionId: string, opts?: { processStartMarker?: string } ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> => { @@ -1193,6 +1196,12 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): return false } + // Cache only positive liveness evidence for this stop. Retaining a dead + // owner is conservative; caching a negative result could hide a new live + // owner after PID reuse. Binding files are reread on EVERY decision. + const possiblyLiveGenerations = new Set(); + const runtimeGenerationKey = (record: Awaited>[number]) => + JSON.stringify([record.pid, record.marker, record.serverPid, record.serverMarker]); const readLiveRuntimesForStop = async () => { try { const scanStarted = Date.now(); @@ -1200,22 +1209,18 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): runtime.hub === configuration.apiUrl && runtime.authHash === runtimeAuthHash() ); - // 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)); + if (!records.length) return records; + const unchecked = records.filter(record => !possiblyLiveGenerations.has(runtimeGenerationKey(record))); + const table = isWindows() && unchecked.length ? await readWindowsProcessTable(10_000, + [...new Set(unchecked.flatMap(record => [record.pid, ...(record.serverPid ? [record.serverPid] : [])]))]) : undefined; + const live = records.filter(runtime => { + const key = runtimeGenerationKey(runtime); + if (possiblyLiveGenerations.has(key)) return true; + const alive = runtimeMayBeAlive(runtime, table); + // An unknown snapshot is safe to retain but not cache as evidence. + if (alive && table !== null) possiblyLiveGenerations.add(key); + return alive; + }); logger.debug('[RUNNER RUN] Runtime stop scan', { sessionId, records: records.length, live: live.length, elapsedMs: Date.now() - scanStarted }); return live; } catch (error) { @@ -1438,7 +1443,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): } try { const reportStop: Parameters[2] = report => { - logger.debug('[RUNNER RUN] Session process tree stop proof', { sessionId, ...report }); + logger.debug('[RUNNER RUN] Windows tree stop confirmation', { sessionId, pid, ...report }); }; const treeStopped = session.childProcess ? await killProcessByChildProcess(session.childProcess, false, reportStop) @@ -1447,8 +1452,8 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): 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; + logger.debug(`[RUNNER RUN] Requested termination for runner-spawned session ${sessionId}`); } catch (error) { logger.debug(`[RUNNER RUN] Failed to kill session ${sessionId}:`, error); return 'still_alive'; @@ -1605,7 +1610,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // while callers that just spawned this id can treat unknown defensively. logger.debug(`[RUNNER RUN] Session ${sessionId} not found without verified exit`); return 'unknown'; - }; + }); // A reused PID invalidates a binding, not every runtime for that session. const discardStaleProcess = (pid: number) => { @@ -1840,15 +1845,21 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): ...pidToTrackedSession.keys(), ...existingSessionIdByChildPid.keys() ]); + // The heartbeat runs during stop RPCs. Synchronous per-PID WMI probes + // can block their acknowledgements even after tree shutdown is async. + const heartbeatTable = isWindows() && pidsToCheck.size + ? await readWindowsProcessTable(10_000, [...pidsToCheck]) : undefined; for (const pid of pidsToCheck) { - if (!isProcessAlive(pid)) { + if (heartbeatTable === null) continue; // Failed query is not exit proof. + if (heartbeatTable ? !heartbeatTable.has(pid) : !isProcessAlive(pid)) { logger.debug(`[RUNNER RUN] Removing stale session with PID ${pid} (process no longer exists)`); onChildExited(pid); continue; } const persisted = persistedResumeProcesses.get(pid); if (persisted) { - const generation = probeRecoveredProcessGeneration(pid, persisted); + const currentMarker = heartbeatTable ? heartbeatTable.get(pid)?.marker ?? null : undefined; + const generation = probeRecoveredProcessGeneration(pid, persisted, currentMarker); if (generation === 'exited') { logger.debug(`[RUNNER RUN] Removing stale session with reused PID ${pid}`); discardStaleProcess(pid); diff --git a/cli/src/runner/stopSessionRequests.test.ts b/cli/src/runner/stopSessionRequests.test.ts new file mode 100644 index 00000000..07cb00f3 --- /dev/null +++ b/cli/src/runner/stopSessionRequests.test.ts @@ -0,0 +1,27 @@ +import { expect, it, vi } from 'vitest' +import { coalesceStopRequests } from './stopSessionRequests' + +it('joins in-flight cleanup after a lost acknowledgement, then permits re-verification', async () => { + let release!: () => void + const gate = new Promise(resolve => { release = resolve }) + const stop = vi.fn(async () => { await gate; return 'stopped' }) + const request = coalesceStopRequests(stop) + const first = request('session-a') + const retry = request('session-a') + expect(stop).toHaveBeenCalledTimes(1) + release() + expect(await Promise.all([first, retry])).toEqual(['stopped', 'stopped']) + await request('session-a') + expect(stop).toHaveBeenCalledTimes(2) +}) + +it('does not share stop evidence across PID generations and releases failed operations', async () => { + const stop = vi.fn(async () => { throw new Error('unconfirmed') }) + const request = coalesceStopRequests(stop) + const first = request('PID-100', { processStartMarker: 'old' }).catch(String) + const second = request('PID-100', { processStartMarker: 'new' }).catch(String) + await Promise.all([first, second]) + expect(stop).toHaveBeenCalledTimes(2) + await request('PID-100', { processStartMarker: 'old' }).catch(String) + expect(stop).toHaveBeenCalledTimes(3) +}) diff --git a/cli/src/runner/stopSessionRequests.ts b/cli/src/runner/stopSessionRequests.ts new file mode 100644 index 00000000..497685d1 --- /dev/null +++ b/cli/src/runner/stopSessionRequests.ts @@ -0,0 +1,15 @@ +/** A late RPC retry joins the original stop instead of racing its tree signals. */ +export function coalesceStopRequests(stop: (id: string, opts?: { processStartMarker?: string }) => Promise) { + const pending = new Map>() + return async (id: string, opts?: { processStartMarker?: string }): Promise => { + // Raw PID calls from different generations must never share evidence. + const key = JSON.stringify([id, opts?.processStartMarker ?? null]) + const existing = pending.get(key) + if (existing) return existing + const operation = stop(id, opts) + pending.set(key, operation) + try { return await operation } finally { + if (pending.get(key) === operation) pending.delete(key) + } + } +} diff --git a/cli/src/utils/process.test.ts b/cli/src/utils/process.test.ts index bbbcbdec..036d2802 100644 --- a/cli/src/utils/process.test.ts +++ b/cli/src/utils/process.test.ts @@ -426,408 +426,6 @@ 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), - // individually signal survivors from the pre-kill snapshot — but only when - // the process-generation marker still matches (PID reuse guard). - const { killProcessTreeByPid } = await import('./process') - const alive = new Set([100, 200]) // 100=root, 200=descendant - const markers = new Map([[100, 'gen-100'], [200, 'gen-200']]) - const taskkillPids: number[] = [] - vi.spyOn(process, 'kill').mockImplementation((pid: number, signal?: string | number) => { - if (signal === 0 || signal === undefined) { - if (!alive.has(pid)) { - const err = new Error('ESRCH') as NodeJS.ErrnoException - err.code = 'ESRCH' - throw err - } - return true - } - return true - }) - spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { - if (cmd === 'powershell') { - const script = String(args[args.length - 1] ?? '') - if (script.includes('ParentProcessId')) { - return completed('OK:200,100') - } - // getProcessStartMarker CIM probe - const filterMatch = /ProcessId = (\d+)/.exec(script) - if (filterMatch) { - const pid = Number(filterMatch[1]) - if (!alive.has(pid)) return completed('') - return completed(markers.get(pid) ?? '') - } - return completed('') - } - if (cmd === 'tasklist') { - const filter = args.find((a) => a.startsWith('PID eq ')) - const pid = filter ? Number(filter.replace('PID eq ', '')) : NaN - if (!alive.has(pid)) { - return completed('INFO: No tasks are running which match the specified criteria.') - } - return completed(`proc.exe ${pid} Console 1 1,000 K`) - } - if (cmd === 'taskkill') { - const idx = args.indexOf('/PID') - const pid = Number(args[idx + 1]) - taskkillPids.push(pid) - alive.delete(pid) - return completed('', 0) - } - return completed('') - }) - - const done = killProcessTreeByPid(100, true) - await vi.advanceTimersByTimeAsync(500) - await expect(done).resolves.toBe(true) - expect(taskkillPids).toContain(100) - expect(taskkillPids).toContain(200) - 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 - const taskkillPids: number[] = [] - vi.spyOn(process, 'kill').mockImplementation((pid: number, signal?: string | number) => { - if (signal === 0 || signal === undefined) { - if (!alive.has(pid)) { - const err = new Error('ESRCH') as NodeJS.ErrnoException - err.code = 'ESRCH' - throw err - } - return true - } - return true - }) - spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { - if (cmd === 'powershell') { - const script = String(args[args.length - 1] ?? '') - if (script.includes('ParentProcessId')) { - return completed('OK:200,100') - } - const filterMatch = /ProcessId = (\d+)/.exec(script) - if (filterMatch) { - const pid = Number(filterMatch[1]) - if (!alive.has(pid)) return completed('') - if (pid === 200 && rootGone) return completed('gen-200-reused') - return completed(pid === 100 ? 'gen-100' : 'gen-200') - } - return completed('') - } - if (cmd === 'tasklist') { - const filter = args.find((a) => a.startsWith('PID eq ')) - const pid = filter ? Number(filter.replace('PID eq ', '')) : NaN - if (!alive.has(pid)) { - return completed('INFO: No tasks are running which match the specified criteria.') - } - return completed(`proc.exe ${pid} Console 1 1,000 K`) - } - if (cmd === 'taskkill') { - const idx = args.indexOf('/PID') - const pid = Number(args[idx + 1]) - taskkillPids.push(pid) - if (pid === 100) { - alive.delete(100) - rootGone = true - } else { - alive.delete(pid) - } - return completed('', 0) - } - return completed('') - }) - - 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 () => { // #1911 bot Major: `.join(' ')` yields `$seen=@{} $bfs=@()` — parse error. // Assert generated command text, not mocked stdout (mocks never parse PS). @@ -868,111 +466,6 @@ describe('killProcess on Windows (orphanReap / stopSession)', () => { expect(parseWindowsProcessTreeStdout('OK:200,100', 999)).toBe('scan_failed') }) - it('killProcessTreeByPid treats bare root stdout (B1 fail-open shape) as scan_failed', async () => { - const { killProcessTreeByPid } = await import('./process') - let alive = true - vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { - if (signal === 0 || signal === undefined) { - if (!alive) { - const err = new Error('ESRCH') as NodeJS.ErrnoException - err.code = 'ESRCH' - throw err - } - return true - } - return true - }) - spawnSyncMock.mockImplementation((cmd: string) => { - // Status 0 + root-only — the measured CIM-failure shape under SilentlyContinue. - if (cmd === 'powershell') return completed('1234') - if (cmd === 'tasklist') { - if (!alive) { - return completed('INFO: No tasks are running which match the specified criteria.') - } - return completed(`proc.exe 1234 Console 1 1,000 K`) - } - if (cmd === 'taskkill') { - alive = false - return completed('', 0) - } - return completed('') - }) - const done = killProcessTreeByPid(1234, true) - await vi.advanceTimersByTimeAsync(500) - await expect(done).resolves.toBe(false) - expect(spawnSyncMock.mock.calls.some((c) => c[0] === 'taskkill')).toBe(true) - }) - - it('killProcessTreeByPid signals root but returns false when Windows tree scan fails', async () => { - const { killProcessTreeByPid } = await import('./process') - let alive = true - vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { - if (signal === 0 || signal === undefined) { - if (!alive) { - const err = new Error('ESRCH') as NodeJS.ErrnoException - err.code = 'ESRCH' - throw err - } - return true - } - return true - }) - spawnSyncMock.mockImplementation((cmd: string) => { - if (cmd === 'powershell') { - return { status: 1, stdout: Buffer.from(''), stderr: Buffer.from('parse error') } - } - if (cmd === 'tasklist') { - if (!alive) { - return completed('INFO: No tasks are running which match the specified criteria.') - } - return completed(`proc.exe 100 Console 1 1,000 K`) - } - if (cmd === 'taskkill') { - alive = false - return completed('', 0) - } - return completed('') - }) - const done = killProcessTreeByPid(100, true) - await vi.advanceTimersByTimeAsync(500) - await expect(done).resolves.toBe(false) - // Partial kill: root signalled, but never claim stopped without tree verify. - expect(spawnSyncMock.mock.calls.some((c) => c[0] === 'taskkill')).toBe(true) - }) - - it('killProcessTreeByPid signals root but returns false when Windows tree scan returns empty stdout', async () => { - const { killProcessTreeByPid } = await import('./process') - let alive = true - vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { - if (signal === 0 || signal === undefined) { - if (!alive) { - const err = new Error('ESRCH') as NodeJS.ErrnoException - err.code = 'ESRCH' - throw err - } - return true - } - return true - }) - spawnSyncMock.mockImplementation((cmd: string) => { - if (cmd === 'powershell') return completed('') // status 0, empty — scan_failed - if (cmd === 'tasklist') { - if (!alive) { - return completed('INFO: No tasks are running which match the specified criteria.') - } - return completed(`proc.exe 100 Console 1 1,000 K`) - } - if (cmd === 'taskkill') { - alive = false - return completed('', 0) - } - return completed('') - }) - const done = killProcessTreeByPid(100, true) - await vi.advanceTimersByTimeAsync(500) - await expect(done).resolves.toBe(false) - expect(spawnSyncMock.mock.calls.some((c) => c[0] === 'taskkill')).toBe(true) - }) }) describe('killProcessTreeByPid on POSIX (pgrep tree scan)', () => { diff --git a/cli/src/utils/process.ts b/cli/src/utils/process.ts index 2c5f67b9..cc4cb045 100644 --- a/cli/src/utils/process.ts +++ b/cli/src/utils/process.ts @@ -1,6 +1,7 @@ import type { ChildProcess } from 'node:child_process'; import spawn from 'cross-spawn'; import { readFileSync } from 'node:fs'; +import { stopWindowsProcessTree, type WindowsStopReport } from './windowsProcessStop'; export const isWindows = (): boolean => process.platform === 'win32'; @@ -458,137 +459,12 @@ 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, - onReport?: (report: ProcessTreeStopReport) => void -): Promise { +export async function killProcessTreeByPid(pid: number, force: boolean = false, report?: (result: WindowsStopReport) => 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); - 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) { - // 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() }); - } - } - 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; - 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); - 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); - } - 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 stopWindowsProcessTree(n, force, report); } return killProcessTree(n, force); } @@ -636,7 +512,7 @@ async function waitForProcessToDie(pid: number, force: boolean): Promise { export async function killProcessByChildProcess( child: ChildProcess, force: boolean = false, - onReport?: (report: ProcessTreeStopReport) => void + report?: (result: WindowsStopReport) => void ): Promise { const pid = child.pid; if (!pid) { @@ -644,5 +520,5 @@ export async function killProcessByChildProcess( } // Both platforms: tree-kill + full-tree verify (win32 must not trust root-only). - return killProcessTreeByPid(pid, force, onReport); + return killProcessTreeByPid(pid, force, report); } diff --git a/cli/src/utils/windowsProcessStop.native.test.ts b/cli/src/utils/windowsProcessStop.native.test.ts new file mode 100644 index 00000000..c8c4d991 --- /dev/null +++ b/cli/src/utils/windowsProcessStop.native.test.ts @@ -0,0 +1,42 @@ +import { execFileSync } from 'node:child_process' +import { describe, expect, it } from 'vitest' +import { readWindowsProcessTable, WINDOWS_PROCESS_TABLE_COMMAND, windowsProcessTableCommand } from './windowsProcessStop' + +describe.skipIf(process.platform !== 'win32')('Windows native process snapshot', () => { + it('runs the generated command under Windows PowerShell with matching generation markers', async () => { + const table = await readWindowsProcessTable(15_000, [process.pid], true) + expect(table).not.toBeNull() + expect(table!.get(process.pid)?.marker).toMatch(/^\d{4}-\d\d-\d\dT/) + expect(table!.get(process.pid)?.parentPid).toBeGreaterThanOrEqual(0) + expect(table!.get(process.pid)?.name).toBeTruthy() + const direct = await readWindowsProcessTable(15_000, [process.pid]) + expect(direct?.get(process.pid)?.marker).toBe(table!.get(process.pid)?.marker) + }, 40_000) + + it('uses invariant generation markers under a non-Gregorian current culture', () => { + const culture = "[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::GetCultureInfo('th-TH')\n" + const marker = (command: string): string => { + const output = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', culture + command], { + windowsHide: true, timeout: 15_000, stdio: 'pipe', encoding: 'utf8', + }) + return JSON.parse(output).processes[0].CreationDate + } + + const direct = marker(windowsProcessTableCommand([process.pid])) + const cim = marker(windowsProcessTableCommand([process.pid], true)) + expect(direct).toBe(cim) + }, 40_000) + + it('represents a missing process as a complete empty filtered snapshot', async () => { + const table = await readWindowsProcessTable(15_000, [2147483647]) + expect(table).not.toBeNull() + expect(table!.size).toBe(0) + }, 20_000) + + it('exits unsuccessfully when CIM fails instead of emitting a partial success table', () => { + const script = "function Get-CimInstance { throw 'simulated CIM failure' }\n" + WINDOWS_PROCESS_TABLE_COMMAND + expect(() => execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { + windowsHide: true, timeout: 15_000, stdio: 'pipe', + })).toThrow() + }, 20_000) +}) diff --git a/cli/src/utils/windowsProcessStop.test.ts b/cli/src/utils/windowsProcessStop.test.ts new file mode 100644 index 00000000..48fb1b2e --- /dev/null +++ b/cli/src/utils/windowsProcessStop.test.ts @@ -0,0 +1,213 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { execFileMock, syncMock } = vi.hoisted(() => ({ execFileMock: vi.fn(), syncMock: vi.fn() })) +vi.mock('node:child_process', () => ({ execFile: execFileMock })) +vi.mock('cross-spawn', () => ({ default: { sync: syncMock } })) +import { killProcessTreeByPid } from './process' +import { readWindowsProcessTable, windowsGenerationMayBeAlive } from './windowsProcessStop' + +const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')! +type Row = { ProcessId: number; ParentProcessId: number; CreationDate: string | null } +const row = (pid: number, parent = 0, marker: string | null = `gen-${pid}`): Row => ({ + ProcessId: pid, ParentProcessId: parent, CreationDate: marker +}) + +describe('Windows asynchronous tree stop', () => { + let rows: Row[] + let kills: Array<{ pid: number; force: boolean; tree: boolean }> + let onKill: (pid: number, force: boolean) => void + let rejectSoft: boolean + beforeEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + rows = [row(0, 0, null), row(100), row(200, 100)] + kills = [] + rejectSoft = false + onKill = pid => { rows = rows.filter(p => p.ProcessId !== pid) } + syncMock.mockReset().mockReturnValue({ status: 1, error: new Error('No synchronous probes permitted') }) + execFileMock.mockReset().mockImplementation((file, args, _options, callback) => { + queueMicrotask(() => { + if (file === 'powershell') { + callback(null, JSON.stringify({ complete: true, processes: rows }), '') + } else { + const pid = Number(args[args.indexOf('/PID') + 1]) + kills.push({ pid, force: args.includes('/F'), tree: args.includes('/T') }) + onKill(pid, args.includes('/F')) + callback(rejectSoft && !args.includes('/F') ? new Error('Soft termination refused') : null, '', '') + } + }) + return { kill: vi.fn() } + }) + }) + afterEach(() => { + Object.defineProperty(process, 'platform', originalPlatform) + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('confirms all descendants without blocking the runner with per-PID shell probes', async () => { + await expect(killProcessTreeByPid(100, true)).resolves.toBe(true) + expect(kills.map(k => k.pid)).toEqual([100, 200]) + expect(syncMock).not.toHaveBeenCalled() + }) + + it('does not terminate a PID reused after the original descendant exits', async () => { + onKill = pid => { + rows = rows.filter(p => p.ProcessId !== pid) + if (pid === 100) rows = [row(0, 0, null), row(200, 0, 'new-generation')] + } + await expect(killProcessTreeByPid(100, true)).resolves.toBe(true) + expect(kills.map(k => k.pid)).toEqual([100]) + }) + + it.each(['refused', 'grace-expired'])('force-stops new descendants tree-wide when soft termination is %s', async reason => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }) + rejectSoft = reason === 'refused' + onKill = (pid, force) => { + if (!force) { rows.push(row(300, 100)); return } + if (pid === 100 && kills.at(-1)?.tree) rows = [row(0, 0, null)] + else rows = rows.filter(p => p.ProcessId !== pid) + } + const operation = killProcessTreeByPid(100, false) + await vi.advanceTimersByTimeAsync(3_000) + await expect(operation).resolves.toBe(true) + expect(kills).toContainEqual({ pid: 100, force: true, tree: true }) + expect(rows.some(p => p.ProcessId === 300)).toBe(false) + }) + + it('does not confirm cleanup if a newly discovered descendant survives forced tree termination', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }) + rejectSoft = true + onKill = (pid, force) => { + if (!force) { rows.push(row(300, 100)); return } + if (pid !== 300) rows = rows.filter(p => p.ProcessId !== pid) + } + const operation = killProcessTreeByPid(100, false) + await vi.advanceTimersByTimeAsync(46_000) + await expect(operation).resolves.toBe(false) + expect(rows.some(p => p.ProcessId === 300)).toBe(true) + }) + + it('does not force a replacement root or its new children after soft termination', async () => { + rejectSoft = true + onKill = (pid, force) => { + if (!force) { + rows = [row(0, 0, null), row(100, 0, 'replacement-root'), row(200, 100), row(300, 100)] + return + } + rows = rows.filter(p => p.ProcessId !== pid) + } + await expect(killProcessTreeByPid(100, false)).resolves.toBe(true) + expect(kills.filter(k => k.force).map(k => k.pid)).toEqual([200]) + expect(rows.map(p => p.ProcessId)).toContain(300) + }) + + it.each([false, true])('terminates late descendants behind an exited intermediate process (force=%s)', async force => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }) + rows = [row(0, 0, null), row(100), row(200, 100), row(300, 200)] + onKill = (pid) => { + if (pid === 100) { rows = [row(0, 0, null), row(300, 200), row(400, 300)]; return } + if (pid === 300 && kills.at(-1)?.tree) rows = [row(0, 0, null)] + else rows = rows.filter(p => p.ProcessId !== pid) + } + const operation = killProcessTreeByPid(100, force) + await vi.advanceTimersByTimeAsync(3_000) + await expect(operation).resolves.toBe(true) + expect(kills).toContainEqual({ pid: 300, force: true, tree: true }) + expect(rows.some(p => p.ProcessId === 400)).toBe(false) + }) + + it('does not confirm a disconnected survivor subtree while its new child remains alive', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }) + rows = [row(0, 0, null), row(100), row(200, 100), row(300, 200)] + onKill = pid => { + if (pid === 100) { rows = [row(0, 0, null), row(300, 200), row(400, 300)]; return } + if (pid !== 400) rows = rows.filter(p => p.ProcessId !== pid) + } + const operation = killProcessTreeByPid(100, true) + await vi.advanceTimersByTimeAsync(46_000) + await expect(operation).resolves.toBe(false) + expect(rows.some(p => p.ProcessId === 400)).toBe(true) + }) + + it('attempts root tree termination through a direct probe when CIM is unavailable', async () => { + execFileMock.mockImplementation((file, args, _options, callback) => { + queueMicrotask(() => { + if (file === 'powershell') { + const script = String(args.at(-1)) + if (script.includes('Get-CimInstance')) callback(new Error('CIM failed'), '', '') + else callback(null, JSON.stringify({ complete: true, processes: [row(100)] }), '') + } else { + const pid = Number(args[args.indexOf('/PID') + 1]) + kills.push({ pid, force: args.includes('/F'), tree: args.includes('/T') }) + callback(null, '', '') + } + }) + return { kill: vi.fn() } + }) + await expect(killProcessTreeByPid(100, true)).resolves.toBe(false) + expect(kills).toContainEqual({ pid: 100, force: true, tree: true }) + }) + + it('never treats a failed snapshot as proof of exit', async () => { + execFileMock.mockImplementation((_file, _args, _options, callback) => { + queueMicrotask(() => callback(new Error('CIM failed'), '', '')) + return { kill: vi.fn() } + }) + await expect(killProcessTreeByPid(100, true)).resolves.toBe(false) + expect(kills).toEqual([]) + }) + + it.each(['', '[]', '{"complete":true,"processes":[]}', '{"complete":false,"processes":[]}', + '{"complete":true,"processes":[{"ProcessId":100}]}'])('rejects incomplete or malformed snapshot %s', async output => { + execFileMock.mockImplementation((_file, _args, _options, callback) => { + queueMicrotask(() => callback(null, output, '')) + return { kill: vi.fn() } + }) + expect(await readWindowsProcessTable()).toBeNull() + }) + + it('keeps ownership on failed or missing markers and recognizes only positive exit evidence', async () => { + const table = await readWindowsProcessTable() + expect(windowsGenerationMayBeAlive(null, 100, 'gen-100')).toBe(true) + expect(windowsGenerationMayBeAlive(table, 100, 'gen-100')).toBe(true) + expect(windowsGenerationMayBeAlive(table, 100, 'old-generation')).toBe(false) + expect(windowsGenerationMayBeAlive(table, 999, 'gen-999')).toBe(false) + }) + + it('does not signal a root whose PID was reused between snapshots', async () => { + let scans = 0 + const implementation = execFileMock.getMockImplementation()! + execFileMock.mockImplementation((file, ...args) => { + if (file === 'powershell' && ++scans === 2) rows = [row(0, 0, null), row(100, 0, 'new-root')] + return implementation(file, ...args) + }) + await expect(killProcessTreeByPid(100, true)).resolves.toBe(true) + expect(kills).toEqual([]) + }) + + it('keeps the Runner event loop responsive while OS probes are pending', async () => { + const callbacks: Array<() => void> = [] + execFileMock.mockImplementation((_file, _args, _options, callback) => { + callbacks.push(() => callback(new Error('probe unavailable'), '', '')) + return { kill: vi.fn() } + }) + const operation = killProcessTreeByPid(100, true) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(callbacks).toHaveLength(1) + callbacks[0]() + await new Promise(resolve => setTimeout(resolve, 0)) + expect(callbacks).toHaveLength(2) + callbacks[1]() + await expect(operation).resolves.toBe(false) + }) + + it('bounds an unkillable tree by elapsed time including OS queries', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }) + onKill = () => {} + const operation = killProcessTreeByPid(100, true) + await vi.advanceTimersByTimeAsync(46_000) + await expect(operation).resolves.toBe(false) + expect(kills.every(k => k.force)).toBe(true) + expect(syncMock).not.toHaveBeenCalled() + }) +}) diff --git a/cli/src/utils/windowsProcessStop.ts b/cli/src/utils/windowsProcessStop.ts new file mode 100644 index 00000000..b084007a --- /dev/null +++ b/cli/src/utils/windowsProcessStop.ts @@ -0,0 +1,238 @@ +import { execFile } from 'node:child_process' + +export type WindowsProcessEntry = { parentPid: number; marker: string | null; name: string; commandLine: string } +export type WindowsProcessTable = Map + +// One complete CIM snapshot supplies ancestry AND generation markers. Launching +// PowerShell/tasklist for each member made a small tree take over a minute. +export function windowsProcessTableCommand(pids?: number[], includeCommandLine = false): string { + if (pids?.length && !includeCommandLine) { + // Verification needs only PID + generation, not another WMI table. + // CIM truncates Windows FILETIME to microseconds; keep its existing + // marker format so both sources identify the same process generation. + return [ + "$ErrorActionPreference='Stop'", 'trap { exit 1 }', '$rows=@(', + `foreach($processId in @(${pids.join(',')})){`, + ' $p=$null', + ' try { $p=[System.Diagnostics.Process]::GetProcessById($processId) }', + ' catch [System.ArgumentException] { continue }', + ' try {', + ' try { $marker=$p.StartTime.ToUniversalTime().ToString("yyyy-MM-dd\'T\'HH:mm:ss.ffffff\'0Z\'", [System.Globalization.CultureInfo]::InvariantCulture) }', + ' catch { if($p.HasExited){continue}; throw }', + ' [pscustomobject]@{ProcessId=$processId;ParentProcessId=0;CreationDate=$marker}', + ' } finally { if($p){$p.Dispose()} }', + '}', ')', '@{complete=$true;processes=$rows} | ConvertTo-Json -Depth 4 -Compress', + ].join('\n') + } + const properties = `ProcessId,ParentProcessId,CreationDate${includeCommandLine ? ',Name,CommandLine' : ''}` + const filter = pids?.length ? ` -Filter "${pids.map(pid => `ProcessId = ${pid}`).join(' OR ')}"` : '' + return [ + "$ErrorActionPreference='Stop'", + 'trap { exit 1 }', + `$rows=@(Get-CimInstance Win32_Process -Property ${properties}${filter} | Select-Object ProcessId,ParentProcessId,Name,CommandLine,`, + " @{N='CreationDate';E={if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null }}})", + '@{complete=$true;processes=$rows} | ConvertTo-Json -Depth 4 -Compress', + ].join('\n') +} +export const WINDOWS_PROCESS_TABLE_COMMAND = windowsProcessTableCommand() + +function execute(file: string, args: string[], timeout: number): Promise { + if (timeout <= 0) return Promise.resolve(null) + return new Promise(resolve => { + execFile(file, args, { + encoding: 'utf8', windowsHide: true, timeout: Math.ceil(timeout), + killSignal: 'SIGKILL', maxBuffer: 16 * 1024 * 1024, + }, (error, stdout) => resolve(error ? null : stdout)) + }) +} + +export async function readWindowsProcessTable(timeout = 15_000, pids?: number[], includeCommandLine = false): Promise { + if (pids?.some(pid => !Number.isInteger(pid) || pid < 0)) return null + const output = await execute('powershell', ['-NoProfile', '-NonInteractive', '-Command', windowsProcessTableCommand(pids, includeCommandLine)], timeout) + if (output === null) return null + try { + const parsed = JSON.parse(output) + if (parsed?.complete !== true || !Array.isArray(parsed.processes) || (!pids?.length && !parsed.processes.length)) return null + const table: WindowsProcessTable = new Map() + for (const entry of parsed.processes) { + if (!entry || !Number.isInteger(entry.ProcessId) || entry.ProcessId < 0 + || !Number.isInteger(entry.ParentProcessId) || entry.ParentProcessId < 0 + || (entry.CreationDate !== null && typeof entry.CreationDate !== 'string') + || table.has(entry.ProcessId)) return null + table.set(entry.ProcessId, { parentPid: entry.ParentProcessId, marker: entry.CreationDate || null, + name: typeof entry.Name === 'string' ? entry.Name : '', + commandLine: typeof entry.CommandLine === 'string' ? entry.CommandLine : '', + }) + } + return table + } catch { return null } +} + +/** A failed probe conservatively keeps ownership; it must never authorize a kill. */ +export function windowsGenerationMayBeAlive(table: WindowsProcessTable | null, pid: number, marker?: string): boolean { + if (table === null) return true + const entry = table.get(pid) + return Boolean(entry && (!entry.marker || !marker || entry.marker === marker)) +} + +export type WindowsStopReport = { confirmed: boolean; phase: string; elapsedMs: number; snapshots: number } +export async function stopWindowsProcessTree(rootPid: number, force: boolean, report?: (result: WindowsStopReport) => void): Promise { + // Includes command startup, queries, signalling and verification, independent + // of tree size. Each async child is killed when its remaining budget expires. + const started = performance.now() + const deadline = started + 45_000 + let phase = 'initial-snapshot', snapshots = 1 + const finish = (confirmed: boolean) => { + report?.({ confirmed, phase, elapsedMs: Math.round(performance.now() - started), snapshots }) + return confirmed + } + const remaining = () => Math.max(0, deadline - performance.now()) + const signal = async (pid: number, hard: boolean, tree: boolean) => { + phase = 'signal' + return execute('taskkill', [ + ...(hard ? ['/F'] : []), ...(tree ? ['/T'] : []), '/PID', String(pid), + ], Math.min(5_000, remaining())) + } + const initial = await readWindowsProcessTable(Math.min(15_000, remaining())) + if (!initial) { + // A transient CIM failure must not leave the cancellation path with no + // termination attempt. A direct process probe still supplies a + // generation-safe witness for the known root; descendants remain + // unverified, so the result stays unconfirmed. + phase = 'root-fallback-probe'; snapshots++ + const rootProbe = await readWindowsProcessTable(Math.min(5_000, remaining()), [rootPid]) + if (rootProbe?.get(rootPid)) await signal(rootPid, force, true) + return finish(false) + } + const members = new Map() + const queue = [rootPid] + while (queue.length) { + const pid = queue.shift()! + if (members.has(pid)) continue + members.set(pid, initial.get(pid)?.marker ?? null) + for (const [child, entry] of initial) if (child !== pid && entry.parentPid === pid) queue.push(child) + } + + const unresolved = new Map(members) + const snapshot = () => { + phase = 'verification-snapshot'; snapshots++ + return readWindowsProcessTable(Math.min(10_000, remaining()), [...unresolved.keys()]) + } + const refresh = (table: WindowsProcessTable) => { + for (const [pid, marker] of unresolved) { + const current = table.get(pid) + // A different known generation proves the ORIGINAL process exited. + // Once resolved, PID reuse cannot reintroduce it into this tree. + if (!current || (marker && current.marker && marker !== current.marker)) unresolved.delete(pid) + } + } + refresh(initial) + if (!unresolved.size) return finish(true) + + // Recheck the root's generation immediately before tree-wide signalling. + let current = await snapshot() + if (!current) return finish(false) + refresh(current) + const rootMarker = members.get(rootPid) + if (unresolved.has(rootPid) && rootMarker && current.get(rootPid)?.marker === rootMarker) { + const softAccepted = await signal(rootPid, force, true) + if (!force && softAccepted !== null) { + const graceDeadline = Math.min(deadline, performance.now() + 2_000) + while (unresolved.size && performance.now() < graceDeadline) { + current = await snapshot() + if (!current) return finish(false) + refresh(current) + if (unresolved.size && performance.now() < graceDeadline) { + await new Promise(resolve => setTimeout(resolve, Math.min(100, graceDeadline - performance.now()))) + } + } + } + } + + if (!force && remaining()) { + // A console tree can grow while soft termination is refused or drains. + // Capture those descendants before escalation, rather than killing only + // the original PIDs and mistaking their exit for complete cleanup. + phase = 'escalation-snapshot'; snapshots++ + const expanded = await readWindowsProcessTable(Math.min(15_000, remaining())) + if (!expanded) return finish(false) + refresh(expanded) + const root = expanded.get(rootPid) + if (!root || (rootMarker && root.marker === rootMarker)) { + const pending = [rootPid], seen = new Set() + while (pending.length) { + const pid = pending.shift()! + if (seen.has(pid)) continue + seen.add(pid) + const entry = expanded.get(pid) + if (entry && !members.has(pid)) { + members.set(pid, entry.marker) + unresolved.set(pid, entry.marker) + } + for (const [child, candidate] of expanded) if (child !== pid && candidate.parentPid === pid) pending.push(child) + } + } + // Never tree-kill a replacement root. Recheck once more after the full + // snapshot so a slow CIM scan cannot authorize signalling a reused PID. + if (unresolved.has(rootPid) && rootMarker && root?.marker === rootMarker) { + current = await snapshot() + if (!current) return finish(false) + refresh(current) + if (unresolved.has(rootPid) && current.get(rootPid)?.marker === rootMarker) { + await signal(rootPid, true, true) + } + } + } + + // A missing intermediate process disconnects a survivor from the root's + // taskkill /T traversal. Expand each surviving generation's OWN subtree, + // including new children, before forcing that subtree and verifying it. + const pendingSignals = [...unresolved.keys()].reverse() + const scheduled = new Set(pendingSignals) + for (let index = 0; index < pendingSignals.length; index++) { + const pid = pendingSignals[index] + if (!unresolved.size) return finish(true) + if (!remaining()) return finish(false) + current = await snapshot() + if (!current) return finish(false) + refresh(current) + if (!unresolved.size) return finish(true) + const expected = unresolved.get(pid) + if (!expected || current.get(pid)?.marker !== expected) continue + phase = 'survivor-subtree-snapshot'; snapshots++ + const subtree = await readWindowsProcessTable(Math.min(15_000, remaining())) + if (!subtree) return finish(false) + refresh(subtree) + if (!unresolved.has(pid) || subtree.get(pid)?.marker !== expected) continue + const descendants = [pid], seen = new Set() + while (descendants.length) { + const child = descendants.shift()! + if (seen.has(child)) continue + seen.add(child) + const entry = subtree.get(child) + if (!entry) continue + const captured = members.get(child) + if (captured && entry.marker && captured !== entry.marker) continue + if (!members.has(child)) { + members.set(child, entry.marker) + unresolved.set(child, entry.marker) + } + for (const [next, candidate] of subtree) if (next !== child && candidate.parentPid === child) descendants.push(next) + } + current = await snapshot() + if (!current) return finish(false) + refresh(current) + if (unresolved.has(pid) && current.get(pid)?.marker === expected) await signal(pid, true, true) + for (const child of unresolved.keys()) { + if (!scheduled.has(child)) { scheduled.add(child); pendingSignals.push(child) } + } + } + while (remaining()) { + current = await snapshot() + if (!current) return finish(false) + refresh(current) + if (!unresolved.size) return finish(true) + await new Promise(resolve => setTimeout(resolve, Math.min(100, remaining()))) + } + return finish(false) +} diff --git a/hub/README.md b/hub/README.md index a3b148ec..aa0db7fa 100644 --- a/hub/README.md +++ b/hub/README.md @@ -121,6 +121,12 @@ for request/response shapes and error semantics, and `src/web/routes/` for all e - `POST /api/sessions/:id/upload` - Upload file (base64, max 50MB). - `POST /api/sessions/:id/upload/delete` - Delete uploaded file. - `POST /api/sessions/:id/archive` - Archive active session. + Runner-owned sessions wait for verified cleanup, including retries after an + early inactive/archived update. Concurrent requests join the same operation. + Cleanup confirmation has a 90-second budget; failure returns a structured + `archive-cleanup-unconfirmed` (409), `archive-cleanup-unavailable` (503), or + `archive-cleanup-timeout` (504) error. A timeout does not cancel Runner cleanup + or prove the process is still alive; retry to verify the final result. - `PATCH /api/sessions/:id` - Rename session. - `DELETE /api/sessions/:id` - Delete inactive session. - `GET /api/sessions/:id/slash-commands` - List slash commands. diff --git a/hub/src/sync/archiveCleanupError.ts b/hub/src/sync/archiveCleanupError.ts new file mode 100644 index 00000000..4f9ac2d1 --- /dev/null +++ b/hub/src/sync/archiveCleanupError.ts @@ -0,0 +1,16 @@ +/** Cleanup is unconfirmed; an inactive realtime update does not prove success. */ +export class ArchiveCleanupError extends Error { + readonly status: 409 | 503 | 504 + readonly code: 'archive-cleanup-unconfirmed' | 'archive-cleanup-unavailable' | 'archive-cleanup-timeout' + + constructor(reason: 'unconfirmed' | 'unavailable' | 'timeout', cause?: unknown) { + super(reason === 'timeout' + ? 'Timed out waiting for Runner to confirm session cleanup. Cleanup may still be running; retry to verify its result.' + : reason === 'unavailable' + ? 'Runner did not confirm session cleanup. Reconnect the Runner and retry to verify its result.' + : 'Session cleanup is not yet confirmed. Retry after the remaining processes have stopped.', { cause }) + this.name = 'ArchiveCleanupError' + this.status = reason === 'timeout' ? 504 : reason === 'unavailable' ? 503 : 409 + this.code = `archive-cleanup-${reason}` + } +} diff --git a/hub/src/sync/archivedFork.test.ts b/hub/src/sync/archivedFork.test.ts index 0a540764..3ceb2a30 100644 --- a/hub/src/sync/archivedFork.test.ts +++ b/hub/src/sync/archivedFork.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'bun:test' import { randomUUID } from 'node:crypto' import { Store } from '../store' import { SyncEngine } from './syncEngine' +import { ArchiveCleanupError } from './archiveCleanupError' import { RpcRegistry } from '../socket/rpcRegistry' import { MACHINE_CAPABILITIES } from '@hapi/protocol' import type { RpcGateway } from './rpcGateway' @@ -124,7 +125,9 @@ describe('archived Codex fork coordination', () => { await f.engine.resumeSession(f.source.id, 'ns') f.rpc.killSession = async () => ({}) f.rpc.stopRunnerSession = async () => 'unknown' - await expect(f.engine.archiveSession(f.source.id)).rejects.toThrow('still running') + const archiveFailure = await f.engine.archiveSession(f.source.id).catch(error => error) + expect(archiveFailure).toBeInstanceOf(ArchiveCleanupError) + expect(archiveFailure).toMatchObject({ code: 'archive-cleanup-unconfirmed', status: 409 }) expect(f.engine.getSession(f.source.id)?.metadata?.codexResumePending).toBeDefined() f.rpc.stopRunnerSession = async () => 'already_gone' await f.engine.archiveSession(f.source.id) diff --git a/hub/src/sync/rpcGateway.test.ts b/hub/src/sync/rpcGateway.test.ts index 028cda38..4ebc8915 100644 --- a/hub/src/sync/rpcGateway.test.ts +++ b/hub/src/sync/rpcGateway.test.ts @@ -13,6 +13,7 @@ function createGateway() { return { async emitWithAck(_event: string, payload: { method: string; params: string }) { calls.push(payload) + if (payload.method.endsWith(':stop-session')) return JSON.stringify({ status: 'already_gone' }) if (payload.method.endsWith(':cursor-chat-store-status')) { return JSON.stringify({ onDisk: false, store: null }) } @@ -58,6 +59,19 @@ describe('RpcGateway RPC timeouts', () => { await gateway.spawnSession('machine-1', 'C:\\workspace', 'claude') expect(timeouts).toEqual([60_000, 30_000]) }) + + it('uses the archive stop budget without putting timeout options on the wire', async () => { + const { gateway, timeouts, calls } = createGateway() + expect(await gateway.stopRunnerSession('machine-1', 'session-1', { timeoutMs: 75_000 })).toBe('already_gone') + expect(timeouts).toEqual([75_000]) + expect(JSON.parse(calls[0].params)).toEqual({ sessionId: 'session-1' }) + }) + + it('retains the normal stop timeout for unrelated callers', async () => { + const { gateway, timeouts } = createGateway() + await gateway.stopRunnerSession('machine-1', 'session-1') + expect(timeouts).toEqual([30_000]) + }) it('uses the default RPC timeout for regular machine RPCs', async () => { const { gateway, timeouts } = createGateway() diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index 39076d7b..98af727c 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -58,6 +58,13 @@ const MODEL_LIST_RPC_TIMEOUT_MS = 120_000 // Codex can spend 30s awaiting startup after preflight and process creation. const CODEX_SPAWN_RPC_TIMEOUT_MS = 60_000 +export class RunnerStopRpcError extends Error { + constructor(readonly timedOut: boolean, cause: unknown) { + super('Runner stop acknowledgement was not received', { cause }) + this.name = 'RunnerStopRpcError' + } +} + /** * tiann/hapi#916: thrown by {@link RpcGateway.rpcCall} when the target CLI is * unreachable (handler not registered or socket disconnected). Callers can @@ -215,12 +222,22 @@ export class RpcGateway { async stopRunnerSession( machineId: string, sessionId: string, - opts?: { processStartMarker?: string } + opts?: { processStartMarker?: string; timeoutMs?: number } ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> { - const result = await this.machineRpc(machineId, RPC_METHODS.StopSession, { - sessionId, - ...(opts?.processStartMarker ? { processStartMarker: opts.processStartMarker } : {}), - }) + const timeoutMs = opts?.timeoutMs ?? DEFAULT_RPC_TIMEOUT_MS + const started = performance.now() + let result: unknown + try { + result = await this.machineRpc(machineId, RPC_METHODS.StopSession, { + sessionId, + ...(opts?.processStartMarker ? { processStartMarker: opts.processStartMarker } : {}), + }, timeoutMs) + } catch (error) { + if (error instanceof RpcTargetMissingError) throw error + // Ack timeout does not cancel the remote stop. Preserve uncertainty + // instead of claiming that the process is definitely still alive. + throw new RunnerStopRpcError(performance.now() - started >= timeoutMs, error) + } const status = result && typeof result === 'object' ? (result as { status?: unknown }).status : undefined if (status === 'stopped' || status === 'already_gone' || status === 'still_alive' || status === 'unknown') return status throw new Error('Unexpected stop-session response') diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index ba869a04..8d561d04 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -38,6 +38,7 @@ import { isMachineSpawnPreallocatedStub } from '../store/sessions' import { RpcGateway, RpcTargetMissingError, + RunnerStopRpcError, type FileSearchOptions, type RpcCodexModel, type RpcCommandResponse, @@ -69,6 +70,7 @@ import { type RpcUploadFileResponse } from './rpcGateway' import { SessionCache } from './sessionCache' +import { ArchiveCleanupError } from './archiveCleanupError' import { AutomaticTitleSuggestionService } from './automaticTitleSuggestion' import { extractMessageEventType } from '../notifications/eventParsing' import { SessionEnumerationCache } from './sessionEnumerationCache' @@ -188,6 +190,7 @@ function extractClaudeUserMessageTextFromAgentOutput(content: unknown): string | } export class SyncEngine { + private readonly archiveRequests = new Map>() private readonly eventPublisher: EventPublisher private readonly sessionCache: SessionCache private readonly machineCache: MachineCache @@ -2070,6 +2073,16 @@ export class SyncEngine { } async archiveSession(sessionId: string): Promise { + const existing = this.archiveRequests.get(sessionId) + if (existing) return existing + const operation = this.archiveSessionOnce(sessionId) + this.archiveRequests.set(sessionId, operation) + try { await operation } finally { + if (this.archiveRequests.get(sessionId) === operation) this.archiveRequests.delete(sessionId) + } + } + + private async archiveSessionOnce(sessionId: string): Promise { if (this.historyActionsInFlight.has(sessionId) || this.archivedForkPending(sessionId)) { throw new Error('Archived fork is in progress; retry the fork to reconcile it before archiving') } @@ -2080,6 +2093,21 @@ export class SyncEngine { } private async archiveSessionUnlocked(sessionId: string): Promise { + // Windows may need longer than the ordinary 30s RPC timeout to prove a + // complete tree exited. All PID fallbacks share this bounded operation + // budget; an acknowledgement timeout must never become archive success. + const deadline = performance.now() + 90_000 + const stopRunner = async (machineId: string, id: string, processStartMarker?: string) => { + const timeoutMs = Math.ceil(deadline - performance.now()) + if (timeoutMs <= 0) throw new ArchiveCleanupError('timeout') + try { + return await this.rpcGateway.stopRunnerSession(machineId, id, { + timeoutMs, ...(processStartMarker ? { processStartMarker } : {}), + }) + } catch (error) { + throw new ArchiveCleanupError(error instanceof RunnerStopRpcError && error.timedOut ? 'timeout' : 'unavailable', error) + } + } // tiann/hapi#916 / #1910: KillSession is a session-socket RPC. A missing // target does not prove the runner child is dead (stale registration, // mid-reconnect, id rotation on resume). Always fall through to the @@ -2105,19 +2133,8 @@ export class SyncEngine { const runnerSpawned = Boolean(sessionMeta?.codexResumePending) || sessionMeta?.startedBy === 'runner' || sessionMeta?.startedFromRunner === true if (machineId && runnerSpawned) { - let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' - try { - status = await this.rpcGateway.stopRunnerSession(machineId, sessionId) - } catch (stopError) { - // Machine RPC missing is NOT proof the detached CLI is gone - // (KillMode=process children survive runner death). Refuse to - // archive on any StopSession failure — including when KillSession - // was also unreachable. Both targets missing still leaves a - // possible live orphan; retry StopSession when the runner - // reconnects (#1911 bot Major). - void stopError - status = 'still_alive' - } + // Missing Runner acknowledgement leaves cleanup unconfirmed. + let status = await stopRunner(machineId, sessionId) // KillSession acknowledges before cleanupAndExit finishes, and socket // loss is not exit proof. When the runner cannot find the HAPI id, // confirm the KillSession-reported OS pid + start marker. @@ -2128,14 +2145,7 @@ export class SyncEngine { && killProcessStartMarker.length > 0 ) if (status === 'unknown' && killPidConfirmable) { - try { - status = await this.rpcGateway.stopRunnerSession(machineId, `PID-${killPid}`, { - processStartMarker: killProcessStartMarker, - }) - } catch (pidStopError) { - void pidStopError - status = 'still_alive' - } + status = await stopRunner(machineId, `PID-${killPid}`, killProcessStartMarker) } // Estate dogfood (#1911 / Peer #1820): KillSession often supplies no // pid+marker when the CLI socket is already gone. If session-id stop @@ -2146,12 +2156,7 @@ export class SyncEngine { if (status === 'unknown' && !killPidConfirmable) { const hostPid = sessionMeta?.hostPid if (typeof hostPid === 'number' && hostPid > 0) { - try { - status = await this.rpcGateway.stopRunnerSession(machineId, `PID-${hostPid}`) - } catch (hostPidStopError) { - void hostPidStopError - status = 'still_alive' - } + status = await stopRunner(machineId, `PID-${hostPid}`) } } // Ambiguous machine-spawn keep-stub: startedBy=runner, no hostPid, still @@ -2172,7 +2177,7 @@ export class SyncEngine { } } if (status === 'still_alive' || status === 'unknown') { - throw new Error('Session process is still running and could not be stopped') + throw new ArchiveCleanupError('unconfirmed') } } else if (machineId && !runnerSpawned) { // Terminal / non-runner sessions: KillSession is the primary stop. diff --git a/hub/src/sync/syncEngineArchiveSession.test.ts b/hub/src/sync/syncEngineArchiveSession.test.ts index 268c9af2..db70db69 100644 --- a/hub/src/sync/syncEngineArchiveSession.test.ts +++ b/hub/src/sync/syncEngineArchiveSession.test.ts @@ -2,7 +2,8 @@ import { describe, expect, it, beforeEach } from 'bun:test' import { Store } from '../store' import { RpcRegistry } from '../socket/rpcRegistry' import { SyncEngine } from './syncEngine' -import { RpcTargetMissingError } from './rpcGateway' +import { RpcTargetMissingError, RunnerStopRpcError } from './rpcGateway' +import { ArchiveCleanupError } from './archiveCleanupError' import type { SessionCache } from './sessionCache' /** @@ -65,6 +66,66 @@ describe('SyncEngine.archiveSession runner reaping (#1910)', () => { engine = new SyncEngine(store, {} as never, new RpcRegistry(), { broadcast() {} } as never) }) + it('coalesces concurrent archive requests and releases the operation after completion', async () => { + const sessionId = insertActiveSession('concurrent-archive', 'machine-x') + setKillSessionOk() + let release!: () => void + const gate = new Promise(resolve => { release = resolve }) + let calls = 0 + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = async () => { + calls++ + await gate + return 'already_gone' + } + const first = engine.archiveSession(sessionId) + const second = engine.archiveSession(sessionId) + await new Promise(resolve => setTimeout(resolve, 0)) + const concurrentCalls = calls + release() + await Promise.all([first, second]) + expect(concurrentCalls).toBe(1) + await engine.archiveSession(sessionId) + expect(calls).toBe(2) + }) + + it('reports lost runner confirmation without asserting the process is still running', async () => { + const sessionId = insertActiveSession('runner-confirmation-lost', 'machine-x') + setKillSessionOk() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = async () => { + throw new Error('connection lost') + } + await expect(engine.archiveSession(sessionId)).rejects.toThrow('Runner did not confirm session cleanup') + expect(cache().getSession(sessionId)?.active).toBe(true) + }) + + it('preserves timeout uncertainty, then permits a real cleanup confirmation on retry', async () => { + const sessionId = insertActiveSession('runner-confirmation-timeout', 'machine-x') + setKillSessionOk() + const gateway = (engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway + gateway.stopRunnerSession = async () => { throw new RunnerStopRpcError(true, new Error('operation has timed out')) } + const error = await engine.archiveSession(sessionId).catch(error => error) + expect(error).toBeInstanceOf(ArchiveCleanupError) + expect(error.status).toBe(504) + expect(cache().getSession(sessionId)?.active).toBe(true) + gateway.stopRunnerSession = async () => 'already_gone' + await engine.archiveSession(sessionId) + expect(cache().getSession(sessionId)?.metadata?.lifecycleState).toBe('archived') + }) + + it('gives Runner cleanup an archive-specific budget exceeding the ordinary RPC timeout', async () => { + const sessionId = insertActiveSession('runner-archive-budget', 'machine-x') + setKillSessionOk() + let timeoutMs = 0 + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async (_machineId: string, _sid: string, opts: { timeoutMs: number }) => { + timeoutMs = opts.timeoutMs + return 'stopped' + } + await engine.archiveSession(sessionId) + expect(timeoutMs).toBeGreaterThan(30_000) + expect(timeoutMs).toBeLessThanOrEqual(90_000) + }) + it('does not archive when the runner confirms still_alive after KillSession miss', async () => { const sessionId = insertActiveSession('sess-still-alive', 'machine-x') setKillSessionMissingTarget() diff --git a/hub/src/web/routes/sessions.test.ts b/hub/src/web/routes/sessions.test.ts index bcc0adcd..78bc63cc 100644 --- a/hub/src/web/routes/sessions.test.ts +++ b/hub/src/web/routes/sessions.test.ts @@ -3,6 +3,7 @@ import { Hono } from 'hono' import type { Session, SyncEngine } from '../../sync/syncEngine' import type { WebAppEnv } from '../middleware/auth' import { createSessionsRoutes } from './sessions' +import { ArchiveCleanupError } from '../../sync/archiveCleanupError' import { RpcTargetMissingError } from '../../sync/rpcGateway' function createSession(overrides?: Partial): Session { @@ -1586,6 +1587,27 @@ describe('sessions routes', () => { // rows and for split-brain rows whose CLI is gone but the in-memory `active` // flag has not been reconciled to false yet. describe('POST /sessions/:id/archive (tiann/hapi#916)', () => { + it.each(['timeout', 'unavailable', 'unconfirmed'] as const)('returns a structured cleanup %s without claiming archive success', async (reason) => { + const error = new ArchiveCleanupError(reason) + const { app } = createApp(createSession({ active: true }), { + archiveSession: async () => { throw error }, + }) + const response = await app.request('/api/sessions/session-1/archive', { method: 'POST' }) + expect(response.status).toBe(error.status) + expect(await response.json()).toEqual({ error: error.message, code: error.code }) + }) + + it('rechecks Runner cleanup for an already inactive archived row on retry', async () => { + let calls = 0 + const session = createSession({ active: false, metadata: { + path: '/tmp/project', host: 'localhost', flavor: 'codex', machineId: 'machine-1', + lifecycleState: 'archived', startedBy: 'runner', + } }) + const { app } = createApp(session, { archiveSession: async () => { calls++ } }) + const response = await app.request('/api/sessions/session-1/archive', { method: 'POST' }) + expect(response.status).toBe(200) + expect(calls).toBe(1) + }) it('returns 2xx and calls archiveSession for an active session', async () => { const calls: string[] = [] const session = createSession({ active: true }) diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index 8a86e2ce..6883e67b 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -37,6 +37,7 @@ import type { WebAppEnv } from '../middleware/auth' import { loadScratchlistAttachmentLimitsFromEnv } from '../../config/scratchlistAttachmentLimits' import { validateScratchlistAttachmentsForWrite, scratchlistSessionBytesBeforeForPut } from '../../scratchlistAttachments/validate' import { TitleSuggestionError } from '../../sync/titleSuggestion' +import { ArchiveCleanupError } from '../../sync/archiveCleanupError' import { requireSessionFromParam, requireSyncEngine } from './guards' const MAX_UPLOAD_BYTES = 50 * 1024 * 1024 @@ -450,18 +451,28 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho } const lifecycleState = sessionResult.session.metadata?.lifecycleState - if (!sessionResult.session.active && lifecycleState === 'archived') { + const runnerOwned = sessionResult.session.metadata?.startedBy === 'runner' + || sessionResult.session.metadata?.startedFromRunner === true + if (!runnerOwned && !sessionResult.session.active && lifecycleState === 'archived') { return c.json({ ok: true, alreadyArchived: true }) } // tiann/hapi#1820: `idle` is a live lifecycle too — a session the hub // reconciled as keepalive-only must stay archivable once its socket // finally drops, exactly like a stale `running` row. - if (!sessionResult.session.active && !isLiveLifecycleState(lifecycleState)) { + if (!sessionResult.session.active && !isLiveLifecycleState(lifecycleState) + && !(runnerOwned && lifecycleState === 'archived')) { return c.json({ error: 'Session is inactive' }, 409) } - await engine.archiveSession(sessionResult.sessionId) + try { + await engine.archiveSession(sessionResult.sessionId) + } catch (error) { + if (error instanceof ArchiveCleanupError) { + return c.json({ error: error.message, code: error.code }, error.status) + } + throw error + } return c.json({ ok: true }) })