diff --git a/cli/README.md b/cli/README.md index 6a2b4e7f897..76782703ab6 100644 --- a/cli/README.md +++ b/cli/README.md @@ -355,6 +355,15 @@ bun scripts/tooling/hapi-display-image.mjs /absolute/path/to/image.png "optional hook falls back to a plain exec or to continuing in-process, and is logged. Implementation: `src/runtime/disclaimExec.ts`, `src/runtime/responsibility.ts`. +- On Windows, Runner-spawned wrappers join a private Job Object before loading + the CLI or launching agents. The Runner and wrapper each hold a handle; a + normal Runner stop or crash does not kill the session. A new Runner reopens + the Job only when the original wrapper generation can still prove membership. + A missing handle or a root-only exit is not proof that descendants are gone. + Only an empty, verified Job authorizes generation-scoped Archive exit proof. + `StopSession` targets the Job, after shared-root protection, rather than a + list of PIDs. Legacy sessions do not gain Job ownership retroactively. + When changing agent bootstrap, handoff, or shared-session plumbing: - One conversation keeps one HAPI session id. `HAPI_SESSION_ID` is exported into the agent process at bootstrap and cannot change afterwards, so a resume must pick the HAPI session *before* the agent starts. Terminal `hapi claude --resume ` / `--continue` look up the owning session (`GET /cli/sessions/resume-target-by-agent`, which also matches rotated-away ids in `claudeSessionIdHistory`) and reopen it with `--existing-session-id`, handing an active remote session over first, asking the hub to clear a hub-authored archive on an inactive one (`POST /cli/sessions/:id/prepare-local-resume`; bootstrap still refuses hub-archived rows), and refusing one already controlled by another terminal; bare `--resume` uses the `hapi resume` picker filtered to Claude. `--fork-session` and conversations unknown to HAPI start a new session. Implementation: `src/claude/resumeIdentity.ts`, `src/commands/resume.ts` (`prepareLocalResume`). diff --git a/cli/src/agent/sessionFactory.ts b/cli/src/agent/sessionFactory.ts index 0d6834d1802..7c7690facbf 100644 --- a/cli/src/agent/sessionFactory.ts +++ b/cli/src/agent/sessionFactory.ts @@ -15,6 +15,7 @@ import { getInvokedCwd } from '@/utils/invokedCwd' import { getProcessStartMarker } from '@/utils/process' import { readWorktreeEnv } from '@/utils/worktreeEnv' import { CURRENT_MACHINE_CAPABILITIES } from '@hapi/protocol/runnerCapabilities' +import { windowsSessionWrapperMarker } from '@/runtime/windowsJobEntry' import { exportHapiSessionEnv } from '@/agent/hapiSessionEnv' import packageJson from '../../package.json' @@ -137,7 +138,7 @@ export function buildSessionMetadata(options: { // PID. It never reads the marker of a terminal session, so skip the // probe there (on Windows it is a synchronous PowerShell spawn). ...(options.startedBy === 'runner' - ? { hostStartMarker: getProcessStartMarker(process.pid) ?? undefined } + ? { hostStartMarker: windowsSessionWrapperMarker() ?? getProcessStartMarker(process.pid) ?? undefined } : {}), startedBy: options.startedBy, lifecycleState: 'running', diff --git a/cli/src/api/apiMachine.ts b/cli/src/api/apiMachine.ts index 38d2bf67754..19aaea310ab 100644 --- a/cli/src/api/apiMachine.ts +++ b/cli/src/api/apiMachine.ts @@ -109,8 +109,8 @@ type MachineRpcHandlers = { /** Read-only exit probe — never tree-kills (#2658). */ probeSessionExit: ( sessionId: string, - opts?: { processStartMarker?: string } - ) => Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> + opts?: { processStartMarker?: string; hubSessionId?: string; windowsJobOnly?: boolean } + ) => Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown' | 'not_contained'> requestShutdown: () => void } @@ -717,7 +717,7 @@ export class ApiMachineClient { }) this.rpcHandlerManager.registerHandler(RPC_METHODS.ProbeSessionExit, async (params: any) => { - const { sessionId, processStartMarker, hubSessionId } = params || {} + const { sessionId, processStartMarker, hubSessionId, windowsJobOnly } = params || {} if (!sessionId) { throw new Error('Session ID is required') } @@ -725,6 +725,7 @@ export class ApiMachineClient { sessionId, { ...(typeof processStartMarker === 'string' ? { processStartMarker } : {}), + ...(windowsJobOnly === true ? { windowsJobOnly } : {}), ...(typeof hubSessionId === 'string' && hubSessionId.length > 0 ? { hubSessionId } : {}), diff --git a/cli/src/index.ts b/cli/src/index.ts index 4b5762ff4da..5be124ab305 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -1,11 +1,13 @@ #!/usr/bin/env bun import { handleDisclaimExecEntry, takeDisclaimFallbackNote } from './runtime/disclaimExec' +import { joinWindowsSessionJobAtEntry } from './runtime/windowsJobEntry' async function main(): Promise { // Before the CLI module graph loads: the macOS responsibility re-exec must // happen before any module side effects. await handleDisclaimExecEntry() + await joinWindowsSessionJobAtEntry() const fallbackNote = takeDisclaimFallbackNote() // Dependency-free, so `--help` and `--version` work even when HAPI_HOME cannot be created. const { captureLauncherPid } = await import('./runtime/launcherPid') diff --git a/cli/src/runner/orphanReap.ts b/cli/src/runner/orphanReap.ts index d4a8091bf4e..211eb376725 100644 --- a/cli/src/runner/orphanReap.ts +++ b/cli/src/runner/orphanReap.ts @@ -341,15 +341,15 @@ export async function reapRunnerSpawnedOrphans( findTargets?: (sessionId: string) => Promise /** @deprecated Prefer findTargets (includes same-snapshot markers). */ findOrphans?: (sessionId: string) => Promise - killTree?: (pid: number) => Promise + killTree?: (pid: number, expectedMarker: string) => Promise prepare?: (target: OrphanTarget) => Promise getStartMarker?: (pid: number) => string | null | Promise isAlive?: (pid: number) => boolean | Promise } = {} ): Promise<'stopped' | 'still_alive' | null> { - const killTree = deps.killTree ?? (async (pid: number) => { + const killTree = deps.killTree ?? (async (pid: number, expectedMarker: string) => { const { killProcessTreeByPid } = await import('@/utils/process') - return killProcessTreeByPid(pid) + return killProcessTreeByPid(pid, false, undefined, undefined, undefined, expectedMarker) }) const getStartMarker = deps.getStartMarker ?? (process.platform === 'win32' ? async (pid: number) => (await readWindowsProcessTable(10_000, [pid]))?.get(pid)?.marker ?? null @@ -439,7 +439,7 @@ export async function reapRunnerSpawnedOrphans( const afterPrepare = normalizeStartMarker(await resolveStartMarker(getStartMarker, orphanPid)) if (afterPrepare !== expectedMarker) { anyUnconfirmed = true; continue } } - if (!(await killTree(orphanPid))) { + if (!(await killTree(orphanPid, expectedMarker))) { anyUnconfirmed = true continue } diff --git a/cli/src/runner/run.ts b/cli/src/runner/run.ts index f8ed9e817c5..a65fd5dc2e5 100644 --- a/cli/src/runner/run.ts +++ b/cli/src/runner/run.ts @@ -12,6 +12,8 @@ import { configuration } from '@/configuration'; import packageJson from '../../package.json'; import { getEnvironmentInfo } from '@/ui/doctor'; import { spawnHappyCLI } from '@/utils/spawnHappyCLI'; +import { WINDOWS_SESSION_JOB_ENV } from '@/runtime/windowsJobEntry'; +import { loadWindowsSessionJobs, type WindowsJobReservation } from './windowsSessionJobs'; import { isBunCompiled } from '@/projectPath'; import { describeChildFatalContext } from './childFatalDiagnostics'; import { writeRunnerState, RunnerLocallyPersistedState, readRunnerState, acquireRunnerLock, releaseRunnerLock } from '@/persistence'; @@ -314,6 +316,11 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): const { machineId } = await authAndSetupMachineIfNeeded(); logger.debug('[RUNNER RUN] Auth and machine setup complete'); + const windowsJobs = await loadWindowsSessionJobs(`${configuration.runnerStateFile}.windows-jobs.json`, error => { + logger.debug('[RUNNER RUN] Windows session Job state unavailable:', error); + }); + windowsJobs?.refresh(); + // Setup state - key by PID const pidToTrackedSession = new Map(); // Retained until actual child exit even if webhook timeout removes normal @@ -492,6 +499,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): logger.debug(`[RUNNER RUN] Current tracked sessions before webhook: ${Array.from(pidToTrackedSession.keys()).join(', ')}`); // Check if we already have this PID (runner-spawned) + windowsJobs?.refresh(pid); const existingSession = pidToTrackedSession.get(pid); if (existingSession && sessionMetadata.capabilities?.concurrentClients) { @@ -509,6 +517,9 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): } if (existingSession && existingSession.startedBy === 'runner') { + if (sessionMetadata.hostStartMarker) { + windowsJobs?.associate(pid, sessionMetadata.hostStartMarker, sessionId); + } // Update runner-spawned session with reported data invalidateVerifiedExit(sessionId); invalidateVerifiedExit(`PID-${pid}`); @@ -684,6 +695,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): let spawnDirectory = directory; let worktreeInfo: WorktreeInfo | null = null; let happyProcess: ReturnType | null = null; + let jobReservation: WindowsJobReservation | null = null; let copiedCodexConfigPath: string | null = null; const cleanupCopiedCodexConfig = async (reason: string): Promise => { @@ -871,6 +883,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): logger.debug('[RUNNER RUN] Child stderr tail', trimmed); }; + jobReservation = windowsJobs?.reserve() ?? null; happyProcess = spawnHappyCLI(args, { cwd: spawnDirectory, detached: true, // Sessions stay alive when runner stops @@ -880,7 +893,8 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // high-water mark. Placed before process.env so users can override it. BUN_JSC_forceRAMSize: String(256 * 1024 * 1024), ...process.env, - ...extraEnv + ...extraEnv, + [WINDOWS_SESSION_JOB_ENV]: jobReservation?.name, } }); happyProcess.once('exit', () => { @@ -898,6 +912,8 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): happyProcess.once('error', captureSpawnErrorBeforePidCheck); if (!happyProcess.pid) { + jobReservation?.job.close(); + jobReservation = null; // Allow the async 'error' event to fire before we read it await new Promise((resolve) => setImmediate(resolve)); const details = [`cwd=${spawnDirectory}`]; @@ -928,6 +944,9 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): } const pid = happyProcess.pid; + const jobMarker = jobReservation ? windowsJobs?.register(pid, jobReservation, + options.existingSessionId ?? options.reservedSessionId ?? options.sessionId) : undefined; + jobReservation = null; const trackHubId = options.existingSessionId ?? options.reservedSessionId; if (trackHubId) { existingSessionIdByChildPid.set(pid, trackHubId); @@ -997,7 +1016,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pidToTrackedSession.set(pid, trackedSession); if (trackedSession.requestedHappySessionId) { pidToRequestedSessionId.set(pid, trackedSession.requestedHappySessionId); - const processStartMarker = getProcessStartMarker(pid); + const processStartMarker = jobMarker ?? getProcessStartMarker(pid); if (processStartMarker) { persistedResumeProcesses.set(pid, { requestedSessionId: trackedSession.requestedHappySessionId, @@ -1093,9 +1112,12 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // and-forget: under load an unawaited kill can fail silently and // leave an immortal detached child. // Capture marker before cleanup deletes resume-process state. - const timeoutMarker = persistedResumeProcesses.get(pid)?.processStartMarker; - let treeDead = false; - if (happyProcess) { + const timeoutMarker = persistedResumeProcesses.get(pid)?.processStartMarker ?? jobMarker ?? undefined; + const canUseJob = !!timeoutMarker && !!windowsJobs?.tracks(pid, timeoutMarker); + let treeDead = canUseJob && await windowsJobs!.stop(pid, timeoutMarker!, () => + !pidToTrackedSession.has(pid) && pidToRequestedSessionId.get(pid) === trackedSession.requestedHappySessionId, + ) === 'exited'; + if (!canUseJob && (!isWindows() || timeoutMarker) && happyProcess) { try { treeDead = await killProcessByChildProcess( happyProcess, false, 'SIGTERM', undefined, undefined, timeoutMarker, @@ -1104,7 +1126,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): logger.debug(`[RUNNER RUN] Webhook-timeout tree-kill failed for PID ${pid}:`, error); } } - if (!treeDead && isProcessAlive(pid)) { + if (!canUseJob && (!isWindows() || timeoutMarker) && !treeDead && isProcessAlive(pid)) { try { treeDead = await killProcessTreeByPid( pid, false, 'SIGTERM', undefined, undefined, timeoutMarker, @@ -1186,6 +1208,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): } return spawnResult; } catch (error) { + jobReservation?.job.close(); const errorMessage = error instanceof Error ? error.message : String(error); logger.debug('[RUNNER RUN] Failed to spawn session:', error); await cleanupCopiedCodexConfig('exception'); @@ -1257,18 +1280,21 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> => { logger.debug(`[RUNNER RUN] Attempting to stop session ${sessionId}`); const signalDeadlines = new Map(); - const prepareSessionStop = async (id: string, pid: number, expectedMarker?: string): Promise => { - if (!isProcessAlive(pid)) return true; + const prepareSessionStop = async (id: string, pid: number, expectedMarker?: string, + ownsWrapper?: () => boolean): Promise => { const flavor = pidToTrackedSession.get(pid)?.happySessionMetadataFromLocalWebhook?.flavor ?? persistedResumeProcesses.get(pid)?.flavor; if (flavor && flavor !== 'opencode') return true; + if (!(ownsWrapper ? ownsWrapper() : isProcessAlive(pid))) return true; const marker = expectedMarker ?? getProcessStartMarker(pid); if (!marker) return false; try { const client = await ApiClient.create(); const expiresAt = await client.prepareOpenCodeSessionStop(id, machineId, pid, marker); if (expiresAt !== undefined) signalDeadlines.set(pid, expiresAt); - return (!isProcessAlive(pid) || getProcessStartMarker(pid) === marker) + // A Job owns the exact generation even if its wrapper disappears + // during drain. Legacy callers must still recheck the numeric PID. + return (ownsWrapper || !isProcessAlive(pid) || getProcessStartMarker(pid) === marker) && (expiresAt === undefined || monotonicTimeMs() < expiresAt); } catch (error) { logger.debug(`[RUNNER RUN] Session ${id} shutdown preparation unconfirmed: ${error instanceof Error ? error.message : 'Unknown error'}`); @@ -1309,7 +1335,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): const possiblyLiveGenerations = new Set(); const runtimeGenerationKey = (record: Awaited>[number]) => JSON.stringify([record.pid, record.marker, record.serverPid, record.serverMarker]); - const readLiveRuntimesForStop = async () => { + const readLiveRuntimesForStop = async (strict = false) => { try { const scanStarted = Date.now(); const records = (await readRuntimes({ strict: true })).filter(runtime => @@ -1339,7 +1365,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // KillSession PID-* fallback cannot prove the OS pid is not a shared // Codex wrapper when the registry is unreadable — soft [] would // tree-kill sibling roots (#1911 Overseer B2). - if (sessionId.startsWith('PID-')) return null; + if (strict || sessionId.startsWith('PID-')) return null; // findRuntime also soft-fails; if a shared Codex root may still exist, // refuse the orphan sweep. Non-Codex stops proceed with [] so archive // is not machine-wide blocked by schema drift. @@ -1363,7 +1389,13 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): sessionId ); const orphanStatus = await reapRunnerSpawnedOrphans(sessionId, { - killTree: (pid) => killProcessTreeByPid(pid, false, undefined, signalDeadlines.get(pid)), + killTree: async (pid, marker) => { + if (!windowsJobs?.tracks(pid, marker)) { + return killProcessTreeByPid(pid, false, undefined, signalDeadlines.get(pid), undefined, marker); + } + const result = await stopRegisteredJob(pid, marker); + return result === 'stopped' || result === 'already_gone'; + }, prepare: (target) => target.needsPublicationDrain === false ? Promise.resolve(true) : prepareSessionStop(sessionId, target.pid, target.startMarker ?? undefined), findTargets: (id) => findStopSessionOrphanTargets( @@ -1428,11 +1460,52 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): return wrapperHasActiveSiblingRoots(live, sessionId, pid); }; + async function stopRegisteredJob(pid: number, marker: string): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> { + const job = windowsJobs!; + const state = job.observe(pid, marker); + job.flush(); + if (state === 'exited') return 'already_gone'; + if (state === 'unknown') return 'unknown'; + const raw = sessionId.startsWith('PID-'); + const original = pidToTrackedSession.get(pid); + const memoryAllowsStop = () => { + const current = pidToTrackedSession.get(pid); + if (!current) return true; + if (current !== original) return false; + return raw ? !Object.keys(current.sharedSessions ?? {}).length : !keepWrapperForSharedSiblings(current, sessionId); + }; + const registryAllowsStop = async () => { + const live = await readLiveRuntimesForStop(true); + return live !== null && !(raw ? pidHasActiveSharedRoots(live, pid) : wrapperHasActiveSiblingRoots(live, sessionId, pid)); + }; + if (!memoryAllowsStop() || !await registryAllowsStop()) return 'unknown'; + const logicalId = raw ? original?.happySessionId ?? pidToConfirmedSessionId.get(pid) + ?? persistedResumeProcesses.get(pid)?.confirmedSessionId ?? pidToRequestedSessionId.get(pid) : sessionId; + // Publication drain is addressed to the wrapper, not its reused numeric PID. + if (logicalId && job.ownsWrapper(pid, marker)) { + if (!await prepareSessionStop(logicalId, pid, marker, () => job.ownsWrapper(pid, marker))) return 'still_alive'; + if (!await registryAllowsStop()) return 'unknown'; + } + const deadline = signalDeadlines.get(pid); + const result = await job.stop(pid, marker, () => memoryAllowsStop() + && (deadline === undefined || monotonicTimeMs() < deadline), + deadline === undefined ? undefined : Math.max(0, deadline - monotonicTimeMs())); + if (result === 'exited') { + terminated.add(pid); + return 'stopped'; + } + return result === 'alive' ? 'still_alive' : 'unknown'; + } + // KillSession pid fallback must verify the start marker BEFORE any tracked // PID match can tree-kill a reused OS pid. if (sessionId.startsWith('PID-')) { const pid = parseInt(sessionId.slice(4), 10); if (Number.isFinite(pid) && pid > 0) { + const marker = opts?.processStartMarker; + if (marker && windowsJobs?.tracks(pid, marker)) { + return stopRegisteredJob(pid, marker); + } const liveForPid = await liveRegistryRuntimes(); if (liveForPid === null) return 'still_alive'; const decision = decideRawPidStop({ @@ -1575,6 +1648,9 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // persistedResumeProcesses during tree wait (#2658). const stopGenerationMarker = persistedResumeProcesses.get(pid)?.processStartMarker ?? opts?.processStartMarker; + if (stopGenerationMarker && windowsJobs?.tracks(pid, stopGenerationMarker)) { + return stopRegisteredJob(pid, stopGenerationMarker); + } if (session.startedBy === 'runner') { // Adopted post-restart sessions have no ChildProcess handle — still // tree-kill so agent grandchildren cannot outlive the wrapper. @@ -1609,6 +1685,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): if (isWindows()) return await finishWithOrphanSweep('unknown') return await finishWithOrphanSweep('already_gone'); } + if (isWindows() && !stopGenerationMarker) return 'unknown'; if (stopGenerationMarker && getProcessStartMarker(pid) !== stopGenerationMarker) return 'unknown'; const reportStop: Parameters[2] = report => { logger.debug('[RUNNER RUN] Windows tree stop confirmation', { sessionId, pid, ...report }); @@ -1689,6 +1766,9 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): const requestedSessionId = pidToRequestedSessionId.get(pid) ?? persisted?.requestedSessionId; const confirmedSessionId = pidToConfirmedSessionId.get(pid) ?? persisted?.confirmedSessionId; if (requestedSessionId !== sessionId && confirmedSessionId !== sessionId) continue; + if (persisted && windowsJobs?.tracks(pid, persisted.processStartMarker)) { + return stopRegisteredJob(pid, persisted.processStartMarker); + } if (isProcessAlive(pid)) { if (!persisted) return 'still_alive'; const generation = probeRecoveredProcessGeneration(pid, persisted); @@ -1755,6 +1835,15 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): return await finishWithOrphanSweep('already_gone'); } + // A tracked Job can still own descendants even after wrapper bookkeeping + // was cleared. Never choose a Job by PID alone or guess among generations. + const knownJobs = windowsJobs?.generationsForSession(sessionId) ?? []; + if (knownJobs.length > 1) return 'unknown'; + if (knownJobs.length === 1) { + const { pid, marker } = knownJobs[0]; + return stopRegisteredJob(pid, marker); + } + // Maps missed (or marker-mismatch cleared a stale row). Scan live argv for // `--started-by runner` + this HAPI session id and tree-kill matches — // excluding PIDs that still host active shared sibling roots (registry @@ -1767,7 +1856,13 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): sessionId ); const orphanStatus = await reapRunnerSpawnedOrphans(sessionId, { - killTree: (pid) => killProcessTreeByPid(pid, false, undefined, signalDeadlines.get(pid)), + killTree: async (pid, marker) => { + if (!windowsJobs?.tracks(pid, marker)) { + return killProcessTreeByPid(pid, false, undefined, signalDeadlines.get(pid), undefined, marker); + } + const result = await stopRegisteredJob(pid, marker); + return result === 'stopped' || result === 'already_gone'; + }, prepare: (target) => target.needsPublicationDrain === false ? Promise.resolve(true) : prepareSessionStop(sessionId, target.pid, target.startMarker ?? undefined), findTargets: (id) => findStopSessionOrphanTargets( @@ -1844,12 +1939,14 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): const probeSessionExit = async ( sessionId: string, - opts?: { processStartMarker?: string; hubSessionId?: string }, - ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> => { + opts?: { processStartMarker?: string; hubSessionId?: string; windowsJobOnly?: boolean }, + ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown' | 'not_contained'> => { if (sessionId.startsWith('PID-')) { const pid = parseInt(sessionId.slice(4), 10); if (!Number.isFinite(pid) || pid <= 0) return 'unknown'; const expected = opts?.processStartMarker; + if (opts?.windowsJobOnly && !expected) return 'unknown'; + if (opts?.windowsJobOnly && !windowsJobs?.tracks(pid, expected)) return 'not_contained'; const witnessKey = `${pid}:${expected ?? ''}` const captureWindowsTreeWitness = async (): Promise => { @@ -1912,6 +2009,14 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): return null } + if (expected && windowsJobs?.tracks(pid, expected)) { + const result = windowsJobs.observe(pid, expected); + windowsJobs.flush(); + if (result === 'unknown') return 'unknown'; + if (result === 'alive') return 'still_alive'; + return await codexOwnedStillAlive() ?? 'already_gone'; + } + if (isProcessAlive(pid)) { if (expected) { const current = getProcessStartMarker(pid); @@ -2048,6 +2153,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // Do not tombstone PID-* here — wrapper exit alone is not full-tree // proof. ProbeSessionExit / StopSession record tombstones after // descendant checks (#2658). + windowsJobs?.refresh(pid); logger.debug(`[RUNNER RUN] Removing exited process PID ${pid} from tracking`); const existingSessionId = existingSessionIdByChildPid.get(pid); if (existingSessionId) { @@ -2271,6 +2377,8 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): logger.debug(`[RUNNER RUN] Health check started at ${new Date().toLocaleString()}`); } + // An orphaned Job can become empty after its wrapper exited. + windowsJobs?.refresh(); // Prune stale sessions const pidsToCheck = new Set([ ...pidToTrackedSession.keys(), @@ -2473,6 +2581,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): await new Promise(resolve => setTimeout(resolve, 100)); apiMachine.shutdown(); + windowsJobs?.close(); await stopControlServer(); await cleanupRunnerState(); await releaseRunnerLock(runnerLockHandle); diff --git a/cli/src/runner/windowsSessionJobs.test.ts b/cli/src/runner/windowsSessionJobs.test.ts new file mode 100644 index 00000000000..ad714c4b7ff --- /dev/null +++ b/cli/src/runner/windowsSessionJobs.test.ts @@ -0,0 +1,95 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { WindowsSessionJobs } from './windowsSessionJobs' + +const disk = vi.hoisted(() => new Map()) +vi.mock('node:fs', () => ({ + readFileSync: (key: string) => { + if (!disk.has(key)) throw Object.assign(new Error('missing'), { code: 'ENOENT' }) + return disk.get(key) + }, + writeFileSync: (key: string, value: string) => disk.set(key, value), + renameSync: (from: string, to: string) => disk.set(to, disk.get(from)!), +})) + +const PID = 123 +const MARKER = '2026-11-30T01:02:03.4567890Z' +const REUSED = '2026-11-30T01:02:03.4567900Z' + +function setup() { + let owner: string | null = null + let counters: { total: number; active: number } | null = { total: 0, active: 0 } + const job = { + counts: vi.fn(() => counters), + containsProcess: vi.fn((pid: number, marker?: string) => pid === PID && owner !== null && marker === owner), + joinCurrentProcess: vi.fn(() => false), + terminate: vi.fn(() => { counters = { total: 3, active: 0 }; return true }), + close: vi.fn(), + } + const win = { + createSessionJob: vi.fn(() => job), + openSessionJob: vi.fn((): typeof job | null => job), + readWindowsProcessIdentity: vi.fn(() => MARKER), + } + const reload = () => new WindowsSessionJobs(win, 'jobstate.json', vi.fn()) + const registry = reload() + expect(registry.register(PID, registry.reserve()!, 'session-a')).toBe(MARKER) + return { registry, reload, win, job, state(marker: string | null, counts: typeof counters) { owner = marker; counters = counts } } +} + +beforeEach(() => disk.clear()) + +describe('Runner Windows Job evidence', () => { + it('cannot use a pending empty or populated job without matching wrapper generation', () => { + const { registry, state, job } = setup() + expect(registry.observe(PID, MARKER)).toBe('unknown') + state(REUSED, { total: 3, active: 0 }) + expect(registry.observe(PID, MARKER)).toBe('unknown') + expect(registry.observe(PID, REUSED)).toBe('unknown') + expect(job.terminate).not.toHaveBeenCalled() + }) + + it('tracks late descendants after wrapper exit and persists only generation-scoped full-tree proof', () => { + const { registry, state, reload, win } = setup() + state(MARKER, { total: 1, active: 1 }) + registry.refresh(PID) + expect(registry.observe(PID, MARKER)).toBe('alive') + state(null, { total: 3, active: 1 }) + expect(registry.observe(PID, MARKER)).toBe('alive') + state(null, { total: 3, active: 0 }) + registry.refresh() + win.openSessionJob.mockReturnValue(null) + expect(reload().observe(PID, MARKER)).toBe('exited') + expect(reload().observe(PID, REUSED)).toBe('unknown') + }) + + it('reopens only while the original wrapper can prove membership', () => { + const { registry, state, reload, win } = setup() + state(MARKER, { total: 2, active: 2 }) + registry.close() + expect(reload().observe(PID, MARKER)).toBe('alive') + state(REUSED, { total: 2, active: 0 }) + expect(reload().observe(PID, MARKER)).toBe('unknown') + win.openSessionJob.mockReturnValue(null) + expect(reload().observe(PID, MARKER)).toBe('unknown') + }) + + it('signalls the verified Job, not a PID, and honours the last-moment veto', async () => { + const { registry, state, job } = setup() + state(MARKER, { total: 2, active: 2 }) + registry.refresh() + state(null, { total: 3, active: 1 }) + expect(await registry.stop(PID, MARKER, () => false)).toBe('unknown') + expect(await registry.stop(PID, REUSED, () => true)).toBe('unknown') + expect(job.terminate).not.toHaveBeenCalled() + expect(await registry.stop(PID, MARKER, () => true)).toBe('exited') + expect(job.terminate).toHaveBeenCalledTimes(1) + expect(registry.generationsForSession('session-a')).toEqual([]) + }) + + it('does not turn a failed accounting query into exit evidence or send a signal', async () => { + const { registry, state, job } = setup() + state(MARKER, null) + expect(await registry.stop(PID, MARKER, () => true)).toBe('unknown') + expect(job.terminate).not.toHaveBeenCalled() + }) +}) diff --git a/cli/src/runner/windowsSessionJobs.ts b/cli/src/runner/windowsSessionJobs.ts new file mode 100644 index 00000000000..70d0b6de972 --- /dev/null +++ b/cli/src/runner/windowsSessionJobs.ts @@ -0,0 +1,201 @@ +import { randomUUID } from 'node:crypto' +import { readFileSync, renameSync, writeFileSync } from 'node:fs' +import type { SessionJob } from '../runtime/windowsJobObject' + +export type WindowsJobState = 'alive' | 'exited' | 'unknown' +export type WindowsJobReservation = { name: string; job: SessionJob } + +type WindowsJobBinding = { + pid: number + marker: string + name: string + state: 'pending' | 'bound' | 'exited' + sessionIds?: string[] +} + +export interface WindowsJobAdapter { + createSessionJob(name: string): SessionJob | null + openSessionJob(name: string): SessionJob | null + readWindowsProcessIdentity(pid: number): string | null +} + +const generationKey = (pid: number, marker: string) => `${pid}:${marker}` +const validMarker = (marker: unknown): marker is string => typeof marker === 'string' + && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/.test(marker) + +function isBinding(value: unknown): value is WindowsJobBinding { + if (!value || typeof value !== 'object') return false + const row = value as Partial + return typeof row.pid === 'number' && Number.isInteger(row.pid) && row.pid > 0 && row.pid <= 0xffffffff + && validMarker(row.marker) && typeof row.name === 'string' + && /^Local\\hapi-session-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(row.name) + && (row.state === 'pending' || row.state === 'bound' || row.state === 'exited') + && (row.sessionIds === undefined || (Array.isArray(row.sessionIds) && row.sessionIds.length <= 2 + && row.sessionIds.every(id => typeof id === 'string' && id.length > 0 && id.length <= 512))) +} + +/** Windows-only ownership, independent of root-PID and ordinary session-id tombstones. */ +export class WindowsSessionJobs { + private readonly entries = new Map() + private dirty = false + + constructor(private readonly win: WindowsJobAdapter, private readonly path: string, private readonly log: (e: unknown) => void) { + try { + const rows: unknown = JSON.parse(readFileSync(path, 'utf8')) + if (Array.isArray(rows)) { + for (const binding of rows.filter(isBinding)) { + this.entries.set(generationKey(binding.pid, binding.marker), { binding }) + } + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') this.log(error) + } + } + + reserve(): WindowsJobReservation | null { + const name = `Local\\hapi-session-${randomUUID()}` + const job = this.win.createSessionJob(name) + return job ? { name, job } : null + } + + register(pid: number, reservation: WindowsJobReservation, requestedId?: string): string | null { + const marker = this.win.readWindowsProcessIdentity(pid) + if (!validMarker(marker)) { + reservation.job.close() + return null + } + const key = generationKey(pid, marker) + // Never replace a generation with a second Job (including its exit proof). + if (this.entries.has(key)) { + reservation.job.close() + return null + } + this.entries.set(key, { + binding: { pid, marker, name: reservation.name, state: 'pending', + ...(requestedId && requestedId.length <= 512 ? { sessionIds: [requestedId] } : {}), }, + handle: reservation.job, + }) + this.dirty = true + this.flush() + return marker + } + + tracks(pid: number, marker?: string): boolean { + return validMarker(marker) && this.entries.has(generationKey(pid, marker)) + } + + associate(pid: number, marker: string, sessionId: string): void { + const row = this.entries.get(generationKey(pid, marker)) + if (!row || row.binding.state !== 'bound' || !sessionId || sessionId.length > 512) return + const ids = row.binding.sessionIds ??= [] + if (ids.length >= 2 || ids.includes(sessionId)) return + ids.push(sessionId) + this.dirty = true + this.flush() + } + + generationsForSession(sessionId: string): Array<{ pid: number; marker: string }> { + const result: Array<{ pid: number; marker: string }> = [] + for (const { binding } of this.entries.values()) { + if (binding.state !== 'exited' && binding.sessionIds?.includes(sessionId)) { + result.push({ pid: binding.pid, marker: binding.marker }) + } + } + return result + } + + ownsWrapper(pid: number, marker: string): boolean { + return !!this.entries.get(generationKey(pid, marker))?.handle?.containsProcess(pid, marker) + } + + observe(pid: number, marker: string): WindowsJobState { + const row = this.entries.get(generationKey(pid, marker)) + if (!row) return 'unknown' + const binding = row.binding + if (binding.state === 'exited') return 'exited' + if (!row.handle) { + const reopened = this.win.openSessionJob(binding.name) + // A persisted name is not a handle. Rebind only if the same root + // generation still holds membership; a recreated name is unsafe. + if (!reopened?.containsProcess(pid, marker)) { + reopened?.close() + return 'unknown' + } + row.handle = reopened + } + const job = row.handle + if (!job) return 'unknown' // Lost name/ACL is not exit evidence. + if (binding.state === 'pending') { + // A newly created empty Job proves nothing. Check PID and FILETIME + // against the same OS process handle before trusting any Job state. + if (!job.containsProcess(pid, marker)) return 'unknown' + binding.state = 'bound' + this.dirty = true + } + const counts = job.counts() + if (!counts || counts.total === 0) return 'unknown' + if (counts.active > 0) return 'alive' + binding.state = 'exited' + job.close() + row.handle = undefined + this.dirty = true + return 'exited' + } + + async stop(pid: number, marker: string, canStop: () => boolean, timeoutMs = 5_000): Promise { + const state = this.observe(pid, marker) + this.flush() + if (state !== 'alive') return state + if (!canStop()) return 'unknown' + const row = this.entries.get(generationKey(pid, marker)) + if (!row?.handle?.terminate()) return 'unknown' + const deadline = performance.now() + Math.max(0, timeoutMs) + for (;;) { + const current = this.observe(pid, marker) + this.flush() + if (current !== 'alive' || performance.now() >= deadline) return current + await new Promise(resolve => setTimeout(resolve, Math.min(50, Math.max(0, deadline - performance.now())))) + } + } + + refresh(pid?: number): void { + for (const { binding } of this.entries.values()) { + if (pid === undefined || binding.pid === pid) this.observe(binding.pid, binding.marker) + } + this.flush() + } + + flush(): void { + if (!this.dirty) return + // Bound records may still own live processes, so never evict them just + // because the root exited. Bound the historical proof, not live state. + const exited = [...this.entries].filter(([, row]) => row.binding.state === 'exited') + for (const [key] of exited.slice(0, Math.max(0, exited.length - 512))) this.entries.delete(key) + const tmp = `${this.path}.${process.pid}.tmp` + try { + writeFileSync(tmp, JSON.stringify([...this.entries.values()].map(row => row.binding)), { mode: 0o600 }) + renameSync(tmp, this.path) + this.dirty = false + } catch (error) { + this.log(error) + } + } + + close(): void { + this.refresh() + for (const row of this.entries.values()) { + row.handle?.close() + row.handle = undefined + } + } +} + +export async function loadWindowsSessionJobs(path: string, log: (error: unknown) => void): Promise { + if (process.platform !== 'win32' || !process.versions.bun) return undefined + try { + return new WindowsSessionJobs(await import('../runtime/windowsJobObject'), path, log) + } catch (error) { + log(error) + return undefined + } +} diff --git a/cli/src/runtime/__fixtures__/windowsJobObject.ts b/cli/src/runtime/__fixtures__/windowsJobObject.ts new file mode 100644 index 00000000000..7f40cf719f5 --- /dev/null +++ b/cli/src/runtime/__fixtures__/windowsJobObject.ts @@ -0,0 +1,116 @@ +import { spawn, type ChildProcess } from 'node:child_process' +import { once } from 'node:events' +import { strict as assert } from 'node:assert' +import { randomUUID } from 'node:crypto' +import { createSessionJob, openSessionJob, readWindowsProcessIdentity } from '../windowsJobObject' +import { WINDOWS_SESSION_JOB_ENV, joinWindowsSessionJobAtEntry, windowsSessionWrapperMarker } from '../windowsJobEntry' + +const fixture = process.argv[1] +const [role, name, inheritedName] = process.argv.slice(2) + +function start(role: string, ...args: string[]): ChildProcess { + return spawn(process.execPath, [fixture, role, ...args], { detached: true, stdio: ['ignore', 'pipe', 'inherit'], windowsHide: true }) +} + +async function readPid(child: ChildProcess): Promise { + const signal = AbortSignal.timeout(8_000) + const chunks = await once(child.stdout!, 'data', { signal }) + const pid = Number(String(chunks[0]).trim()) + assert.ok(Number.isSafeInteger(pid) && pid > 0, `invalid fixture PID: ${chunks}`) + return pid +} + +if (role === 'grandchild') { + setTimeout(() => {}, 25_000) +} else if (role === 'member' || role === 'keeper') { + process.env[WINDOWS_SESSION_JOB_ENV] = name + process.argv.push('--started-by', 'runner') + await joinWindowsSessionJobAtEntry() + const marker = windowsSessionWrapperMarker() + assert.ok(marker) + assert.equal(marker, readWindowsProcessIdentity(process.pid)) + assert.equal(process.env[WINDOWS_SESSION_JOB_ENV], undefined) + const child = start('grandchild') + console.log(child.pid) + child.stdout?.destroy() + child.unref() + if (role === 'keeper') setTimeout(() => {}, 20_000) +} else if (role === 'runner-owner') { + const job = createSessionJob(name) + assert.ok(job) + const wrapper = start('keeper', name) + console.log(await readPid(wrapper)) + await Bun.sleep(20_000) + job.close() +} else if (role === 'nested') { + const parent = openSessionJob(inheritedName, true) + assert.ok(parent && parent.joinCurrentProcess()) + parent.close() + const child = start('member', name) + const exited = once(child, 'exit', { signal: AbortSignal.timeout(8_000) }) + console.log(await readPid(child)) + assert.deepEqual(await exited, [0, null]) +} else if (name === 'crash') { + const jobName = `Local\\hapi-session-${randomUUID()}` + const owner = start('runner-owner', jobName) + const exited = once(owner, 'exit', { signal: AbortSignal.timeout(8_000) }) + try { + const grandchildPid = await readPid(owner) + assert.ok(owner.kill(), 'only the fixture Runner owner is stopped') + await exited + const recovered = openSessionJob(jobName) + assert.ok(recovered?.containsProcess(grandchildPid), 'recover membership after an actual owner process exit') + recovered?.close() + } finally { + owner.kill() + const recovered = openSessionJob(jobName) + recovered?.terminate() + recovered?.close() + } +} else { + const scenario = name ?? 'ordinary' + const jobName = `Local\\hapi-session-${randomUUID()}` + const parentName = `Local\\hapi-session-${randomUUID()}` + const job = createSessionJob(jobName) + assert.ok(job) + const outer = scenario === 'nested' ? createSessionJob(parentName) : null + assert.ok(scenario !== 'nested' || outer) + const control = start('grandchild') + let root: ChildProcess | undefined + try { + assert.deepEqual(job.counts(), { total: 0, active: 0 }) + assert.equal(createSessionJob(jobName), null, 'an existing object must not be claimed by create') + const recovery = scenario === 'recovery' + root = scenario === 'nested' ? start('nested', jobName, parentName) : start(recovery ? 'keeper' : 'member', jobName) + const rootExit = recovery ? null : once(root, 'exit', { signal: AbortSignal.timeout(8_000) }) + const grandchildPid = await readPid(root) + if (rootExit) assert.deepEqual(await rootExit, [0, null]) + const counts = job.counts() + assert.equal(counts?.active, recovery ? 2 : 1, 'grandchild stays in the Job independently of wrapper exit') + assert.ok((counts?.total ?? 0) >= 2) + assert.ok(job.containsProcess(grandchildPid)) + assert.ok(!job.containsProcess(control.pid!)) + assert.match(readWindowsProcessIdentity(grandchildPid) ?? '', /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/) + if (recovery) job.close() + const reopened = openSessionJob(jobName) + assert.ok(reopened && reopened.containsProcess(grandchildPid), 'a live wrapper holding the Job handle allows Runner recovery') + try { + assert.ok(reopened.terminate()) + const deadline = performance.now() + 5000 + while (reopened.counts()?.active !== 0 && performance.now() < deadline) await Bun.sleep(25) + assert.equal(reopened.counts()?.active, 0) + assert.ok(readWindowsProcessIdentity(control.pid!), 'terminating a Job must not kill the unrelated fixture process') + } finally { + reopened.close() + } + } finally { + const pending = openSessionJob(jobName) + pending?.terminate() + pending?.close() + outer?.terminate() + outer?.close() + root?.kill() + control.kill() + job.close() + } +} diff --git a/cli/src/runtime/windowsJobEntry.ts b/cli/src/runtime/windowsJobEntry.ts new file mode 100644 index 00000000000..5f0476d35c7 --- /dev/null +++ b/cli/src/runtime/windowsJobEntry.ts @@ -0,0 +1,32 @@ +/** Internal runner-to-wrapper bootstrap. No agent or CLI side effects before joining. */ +export const WINDOWS_SESSION_JOB_ENV = 'HAPI_INTERNAL_WINDOWS_SESSION_JOB' +let ownGenerationMarker: string | null = null + +export function windowsSessionWrapperMarker(): string | null { + return ownGenerationMarker +} + +export async function joinWindowsSessionJobAtEntry(): Promise { + const name = process.env[WINDOWS_SESSION_JOB_ENV] + if (name === undefined) return + // Do not pass an assignment credential to tools, agents, or another Runner. + delete process.env[WINDOWS_SESSION_JOB_ENV] + if (process.platform !== 'win32') return + const role = process.argv.lastIndexOf('--started-by') + if (role < 0 || process.argv[role + 1] !== 'runner') return + try { + const { openSessionJob, readWindowsProcessIdentity } = await import('./windowsJobObject') + const job = openSessionJob(name, true) + if (job?.joinCurrentProcess()) { + // Intentionally hold this non-inheritable handle until wrapper exit + // so a new Runner can reopen its named Job after a Runner restart. + ownGenerationMarker = readWindowsProcessIdentity(process.pid) + return + } + job?.close() + } catch { + // Restricted host jobs / unsupported runtimes keep the session usable. + // Runner never treats a launch as contained without checking membership. + } + process.stderr.write('[HAPI] Windows session Job could not be established; tree exit cannot be verified by Job membership.\n') +} diff --git a/cli/src/runtime/windowsJobObject.native.test.ts b/cli/src/runtime/windowsJobObject.native.test.ts new file mode 100644 index 00000000000..301fcb5e0a9 --- /dev/null +++ b/cli/src/runtime/windowsJobObject.native.test.ts @@ -0,0 +1,15 @@ +import { execFile } from 'node:child_process' +import { promisify } from 'node:util' +import { fileURLToPath } from 'node:url' +import { describe, it } from 'vitest' + +const fixture = fileURLToPath(new URL('./__fixtures__/windowsJobObject.ts', import.meta.url)) +const exec = promisify(execFile) + +describe.skipIf(process.platform !== 'win32')('native Windows Job membership', () => { + it.each(['ordinary', 'nested', 'recovery', 'crash'])('contains a real descendant: %s', async (scenario) => { + await exec(process.env.HAPI_BUN_EXEC || 'bun', [fixture, 'run', scenario], { + windowsHide: true, timeout: 25_000, + }) + }, 30_000) +}) diff --git a/cli/src/runtime/windowsJobObject.ts b/cli/src/runtime/windowsJobObject.ts new file mode 100644 index 00000000000..85a9683a48e --- /dev/null +++ b/cli/src/runtime/windowsJobObject.ts @@ -0,0 +1,120 @@ +/** Win32 Job handles are loaded lazily by the Runner and its Windows child entry point. */ +import { dlopen, FFIType as T, ptr } from 'bun:ffi' + +const PROCESS_TERMINATE = 0x0001 +const PROCESS_SET_QUOTA = 0x0100 +const PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 +const JOB_OBJECT_ASSIGN_PROCESS = 0x0001 +const JOB_OBJECT_QUERY = 0x0004 +const JOB_OBJECT_TERMINATE = 0x0008 +const BASIC_ACCOUNTING_INFORMATION = 1 +const ERROR_ALREADY_EXISTS = 183 +const FILETIME_EPOCH = 116_444_736_000_000_000n + +const { symbols: win } = dlopen('kernel32.dll', { + CreateJobObjectW: { args: [T.ptr, T.ptr], returns: T.ptr }, + OpenJobObjectW: { args: [T.u32, T.i32, T.ptr], returns: T.ptr }, + CloseHandle: { args: [T.ptr], returns: T.i32 }, + GetLastError: { args: [], returns: T.u32 }, + AssignProcessToJobObject: { args: [T.ptr, T.ptr], returns: T.i32 }, + IsProcessInJob: { args: [T.ptr, T.ptr, T.ptr], returns: T.i32 }, + QueryInformationJobObject: { args: [T.ptr, T.i32, T.ptr, T.u32, T.ptr], returns: T.i32 }, + TerminateJobObject: { args: [T.ptr, T.u32], returns: T.i32 }, + OpenProcess: { args: [T.u32, T.i32, T.u32], returns: T.ptr }, + GetProcessTimes: { args: [T.ptr, T.ptr, T.ptr, T.ptr, T.ptr], returns: T.i32 }, +}) + +type NativeHandle = NonNullable> + +export type SessionJob = { + counts(): { total: number; active: number } | null + containsProcess(pid: number, expectedMarker?: string): boolean + joinCurrentProcess(): boolean + terminate(): boolean + close(): void +} + +function namedJob(name: string): Buffer | null { + // Internal names are random, session-local, and never constructed from a user PID. + if (!/^Local\\hapi-session-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(name)) return null + return Buffer.from(name + '\0', 'utf16le') +} + +function openProcess(pid: number, access: number): NativeHandle | null { + return Number.isInteger(pid) && pid > 0 && pid <= 0xffffffff ? win.OpenProcess(access, 0, pid) : null +} + +function readMarker(processHandle: NativeHandle): string | null { + const times = Buffer.alloc(32) + if (!win.GetProcessTimes(processHandle, ptr(times), ptr(times, 8), ptr(times, 16), ptr(times, 24))) return null + const ticks = times.readBigUInt64LE() - FILETIME_EPOCH + if (ticks < 0n) return null + // Match Win32_Process.CreationDate: CIM truncates FILETIME to microseconds. + const date = new Date(Number(ticks / 10_000n)).toISOString() + return date.slice(0, -1) + String((ticks % 10_000n) / 10n).padStart(3, '0') + '0Z' +} + +export function readWindowsProcessIdentity(pid: number): string | null { + const processHandle = openProcess(pid, PROCESS_QUERY_LIMITED_INFORMATION) + if (!processHandle) return null + try { return readMarker(processHandle) } finally { win.CloseHandle(processHandle) } +} + +function useHandle(initial: NativeHandle): SessionJob { + let handle: NativeHandle | null = initial + const counts = () => { + // JOBOBJECT_BASIC_ACCOUNTING_INFORMATION: 4x LARGE_INTEGER, then 4x DWORD. + const accounting = Buffer.alloc(48) + if (!handle || !win.QueryInformationJobObject(handle, BASIC_ACCOUNTING_INFORMATION, ptr(accounting), accounting.length, null)) return null + return { total: accounting.readUInt32LE(36), active: accounting.readUInt32LE(40) } + } + return { + counts, + containsProcess(pid, expectedMarker) { + if (!handle) return false + const proc = openProcess(pid, PROCESS_QUERY_LIMITED_INFORMATION) + if (!proc) return false + try { + const result = Buffer.alloc(4) + return !!win.IsProcessInJob(proc, handle, ptr(result)) && result.readInt32LE() !== 0 + && (expectedMarker === undefined || readMarker(proc) === expectedMarker) + } finally { win.CloseHandle(proc) } + }, + joinCurrentProcess() { + if (!handle) return false + const proc = openProcess(process.pid, PROCESS_TERMINATE | PROCESS_SET_QUOTA | PROCESS_QUERY_LIMITED_INFORMATION) + if (!proc) return false + try { + return !!win.AssignProcessToJobObject(handle, proc) + } finally { win.CloseHandle(proc) } + }, + terminate: () => !!handle && !!win.TerminateJobObject(handle, 1), + close() { + if (!handle) return + win.CloseHandle(handle) + handle = null + }, + } +} + +export function createSessionJob(name: string): SessionJob | null { + const encoded = namedJob(name) + if (!encoded) return null + const handle = win.CreateJobObjectW(null, ptr(encoded)) + if (!handle) return null + if (win.GetLastError() === ERROR_ALREADY_EXISTS) { + win.CloseHandle(handle) + return null + } + // Closed Runner handles must not terminate detached sessions. Do not set + // KILL_ON_JOB_CLOSE, BREAKAWAY_OK or SILENT_BREAKAWAY_OK on this job. + return useHandle(handle) +} + +export function openSessionJob(name: string, forChild = false): SessionJob | null { + const encoded = namedJob(name) + if (!encoded) return null + const access = forChild ? JOB_OBJECT_ASSIGN_PROCESS : JOB_OBJECT_QUERY | JOB_OBJECT_TERMINATE + const handle = win.OpenJobObjectW(access, 0, ptr(encoded)) + return handle ? useHandle(handle) : null +} diff --git a/cli/src/utils/windowsProcessStop.test.ts b/cli/src/utils/windowsProcessStop.test.ts index 5e84aabc21f..fec531d14be 100644 --- a/cli/src/utils/windowsProcessStop.test.ts +++ b/cli/src/utils/windowsProcessStop.test.ts @@ -285,7 +285,7 @@ describe('Windows asynchronous tree stop', () => { expect(kills).toEqual([]) }) - it('does not signal a reused root through the CIM-failure fallback', async () => { + it.each(['reused-root', 'gen-100'])('requires a full snapshot even if targeted probe reports %s', async (probeMarker) => { execFileMock.mockImplementation((file, args, _options, callback) => { queueMicrotask(() => { if (file === windowsSystemTool('powershell')) { @@ -293,7 +293,7 @@ describe('Windows asynchronous tree stop', () => { if (script.includes('Get-CimInstance')) callback(new Error('CIM failed'), '', '') else callback(null, JSON.stringify({ complete: true, - processes: [row(100, 0, 'reused-root')], + processes: [row(100, 0, probeMarker)], }), '') } else { const pid = Number(args[args.indexOf('/PID') + 1]) diff --git a/cli/src/utils/windowsProcessStop.ts b/cli/src/utils/windowsProcessStop.ts index 9275b1b0a67..cb1b79ef4c3 100644 --- a/cli/src/utils/windowsProcessStop.ts +++ b/cli/src/utils/windowsProcessStop.ts @@ -162,6 +162,9 @@ export async function stopWindowsProcessTree(rootPid: number, force: boolean, re if (!remaining()) return finish(false) const initial = await readWindowsProcessTable(Math.min(15_000, remaining())) if (!initial) { + // Generation-scoped callers require ancestry as well as root identity. + // A targeted PID probe cannot authorize signalling an unknown tree. + if (expectedMarker !== undefined) return finish(false) // 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 @@ -169,8 +172,7 @@ export async function stopWindowsProcessTree(rootPid: number, force: boolean, re phase = 'root-fallback-probe'; snapshots++ const rootProbe = await readWindowsProcessTable(Math.min(5_000, remaining()), [rootPid]) const rootEntry = rootProbe?.get(rootPid) - // Never signal a reused root when the expected marker is known (#2658). - if (rootEntry && (!expectedMarker || rootEntry.marker === expectedMarker)) { + if (rootEntry) { await signal(rootPid, force, true) } return finish(false) diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index e6a3bd031a0..236c9c9389d 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -312,8 +312,9 @@ export class RpcGateway { hubSessionId?: string processStartMarker?: string timeoutMs?: number + windowsJobOnly?: boolean }, - ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> { + ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown' | 'not_contained'> { if (typeof opts.namespace !== 'string' || opts.namespace.length === 0) { return 'unknown' } @@ -343,6 +344,7 @@ export class RpcGateway { method, params: JSON.stringify({ sessionId: probeTargetId, + ...(opts.windowsJobOnly === true ? { windowsJobOnly: true } : {}), ...(opts.hubSessionId ? { hubSessionId: opts.hubSessionId } : {}), ...(opts.processStartMarker ? { processStartMarker: opts.processStartMarker } : {}), }), @@ -355,6 +357,7 @@ export class RpcGateway { } 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 + if (opts.windowsJobOnly && status === 'not_contained') return status throw new Error('Unexpected probe-session-exit response') } diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 92f2a7296ee..ab1d16e7319 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -3965,7 +3965,7 @@ export class SyncEngine { // skip. Transport loss alone never clears (#2658). const probeSupported = Boolean(ownerMachine) && (!ownerCaps || ownerCaps.includes(MACHINE_CAPABILITIES.ProbeSessionExit)) - let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' = 'unknown' + let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' | 'not_contained' = 'unknown' const sessionSocketGone = !this.rpcGateway.hasSessionRpcTarget(sessionId) if (probeSupported) { const timeoutMs = Math.ceil(deadline - performance.now()) @@ -4088,18 +4088,21 @@ export class SyncEngine { } const verifiedExitedOwners = new Set() - // Windows durable refuse is deferred to #2660 — generation-bound - // tree-exit evidence is not obtainable from the normal child-exit - // path. These owners fall through to merge-base StopSession cleanup - // instead of permanently 409ing Archive. + // Legacy/uncontained Windows sessions keep merge-base cleanup. A + // capable Runner distinguishes those from contained generations + // with unknown exit evidence, which must keep their durable latches. const windowsScopedOwners = new Set() + const usesLegacyWindowsStop = (machine: { metadata?: { platform?: string; capabilities?: readonly string[] } | null } | undefined) => + machinePlatformIsWindows(machine?.metadata?.platform) + && !machine?.metadata?.capabilities?.includes(MACHINE_CAPABILITIES.WindowsSessionJobProbe) for (const [ownerKey, owner] of ownersToProbe) { const ownerMachine = this.getMachineByNamespace(owner.machineId, liveBeforeStop.namespace) ?? this.getMachine(owner.machineId) - if (machinePlatformIsWindows(ownerMachine?.metadata?.platform)) { + if (usesLegacyWindowsStop(ownerMachine)) { windowsScopedOwners.add(ownerKey) continue } + const windowsJobOnly = machinePlatformIsWindows(ownerMachine?.metadata?.platform) const ownerCaps = ownerMachine?.metadata?.capabilities // Legacy machines with no capability list still probe; an // explicit list without ProbeSessionExit skips (older Runner). @@ -4108,7 +4111,7 @@ export class SyncEngine { if (!probeSupported) continue const timeoutMs = Math.ceil(deadline - performance.now()) if (timeoutMs <= 0) throw new ArchiveCleanupError('timeout') - let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' = 'unknown' + let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' | 'not_contained' = 'unknown' try { status = await this.rpcGateway.probeRunnerSessionExit( owner.machineId, @@ -4118,6 +4121,7 @@ export class SyncEngine { hubSessionId: sessionId, timeoutMs, processStartMarker: owner.hostStartMarker, + ...(windowsJobOnly ? { windowsJobOnly: true } : {}), }, ) } catch (error) { @@ -4126,6 +4130,10 @@ export class SyncEngine { } status = 'unknown' } + if (windowsJobOnly && status === 'not_contained') { + windowsScopedOwners.add(ownerKey) + continue + } // Clear-only-where-provable (#2658): record verified exit, but // defer durable clear until Archive is unblocked — otherwise a // blocked attempt discards proof needed on retry. @@ -4216,7 +4224,7 @@ export class SyncEngine { if (verifiedExitedOwners.has(ownerKey) || windowsScopedOwners.has(ownerKey)) continue const machine = this.getMachineByNamespace(entry.machineId, afterProbe.namespace) ?? this.getMachine(entry.machineId) - if (machinePlatformIsWindows(machine?.metadata?.platform)) { + if (usesLegacyWindowsStop(machine)) { windowsScopedOwners.add(ownerKey) } } @@ -4240,7 +4248,7 @@ export class SyncEngine { if (windowsScopedOwners.has(ownerKey) || verifiedExitedOwners.has(ownerKey)) continue const machine = this.getMachineByNamespace(request.machineId, afterProbe.namespace) ?? this.getMachine(request.machineId) - if (machinePlatformIsWindows(machine?.metadata?.platform)) { + if (usesLegacyWindowsStop(machine)) { windowsScopedOwners.add(ownerKey) if (!ownersToProbe.has(ownerKey)) { ownersToProbe.set(ownerKey, { diff --git a/hub/src/sync/syncEngineArchiveSession.test.ts b/hub/src/sync/syncEngineArchiveSession.test.ts index 5afbd3f7117..86be87b9ba5 100644 --- a/hub/src/sync/syncEngineArchiveSession.test.ts +++ b/hub/src/sync/syncEngineArchiveSession.test.ts @@ -5,6 +5,7 @@ import { SyncEngine } from './syncEngine' import { RpcTargetMissingError, RunnerStopRpcError } from './rpcGateway' import { ArchiveCleanupError } from './archiveCleanupError' import type { SessionCache } from './sessionCache' +import { MACHINE_CAPABILITIES } from '@hapi/protocol' /** * #1910 / #1705: `killSession` is a session-socket RPC. A missing target does @@ -1132,16 +1133,16 @@ describe('SyncEngine.archiveSession runner reaping (#1910)', () => { expect(cache().getSession(sessionId)?.metadata?.lifecycleState).toBe('archived') }) - it('archives a Windows session with durable work after unplanned exit (#2660 scope)', async () => { - // Platform scope: durable Archive refuse requires generation-bound exit - // evidence. Windows lacks that without launch-time containment (#2660), - // so outstanding durable work must not permanently 409 — fall through - // to merge-base StopSession cleanup (exactly as good as today). - // Abandoned runner requests must neither block nor authorise either — - // same win32 scope as the durable map. + it.each(['legacy', 'not_contained', 'already_gone', 'unknown', 'still_alive'] as const)( + 'scopes Windows Archive to generation-bound proof: %s', async (probeResult) => { engine.getOrCreateMachine( 'machine-win', - { host: 'win-host', platform: 'win32', happyCliVersion: 'test' }, + { + host: 'win-host', platform: 'win32', happyCliVersion: 'test', + ...(probeResult !== 'legacy' ? { + capabilities: [MACHINE_CAPABILITIES.ProbeSessionExit, MACHINE_CAPABILITIES.WindowsSessionJobProbe], + } : {}), + }, null, NAMESPACE, ) @@ -1194,20 +1195,26 @@ describe('SyncEngine.archiveSession runner reaping (#1910)', () => { probeRunnerSessionExit: unknown } } - // Probe would return unknown (no generation tombstone after unplanned - // exit) — under the Windows scope we must not even require it. - gateway.rpcGateway.probeRunnerSessionExit = async () => { + gateway.rpcGateway.probeRunnerSessionExit = async (_machine: string, target: string, opts: Record) => { + expect(target).toBe('PID-9001') + expect(opts).toMatchObject({ windowsJobOnly: true, processStartMarker: 'worker-A', namespace: NAMESPACE }) probes++ - return 'unknown' + return probeResult === 'legacy' ? 'unknown' : probeResult } - gateway.rpcGateway.stopRunnerSession = async () => 'already_gone' - - await engine.archiveSession(sessionId) - expect(cache().getSession(sessionId)?.metadata?.lifecycleState).toBe('archived') - expect(cache().getSession(sessionId)?.metadata?.liveWorkByGeneration?.[keyA]).toBeUndefined() - expect(cache().getSession(sessionId)?.agentState?.requests?.['win-perm']).toBeUndefined() - // Durable Windows owners are skipped for ProbeSessionExit refuse. - expect(probes).toBe(0) + let stops = 0 + gateway.rpcGateway.stopRunnerSession = async () => { stops++; return 'already_gone' } + + if (probeResult === 'unknown' || probeResult === 'still_alive') { + await expect(engine.archiveSession(sessionId)).rejects.toMatchObject({ code: 'archive-session-working' }) + expect(cache().getSession(sessionId)?.metadata?.liveWorkByGeneration?.[keyA]).toBeDefined() + expect(stops).toBe(0) + } else { + await engine.archiveSession(sessionId) + expect(cache().getSession(sessionId)?.metadata?.lifecycleState).toBe('archived') + expect(cache().getSession(sessionId)?.metadata?.liveWorkByGeneration?.[keyA]).toBeUndefined() + expect(cache().getSession(sessionId)?.agentState?.requests?.['win-perm']).toBeUndefined() + } + expect(probes).toBe(probeResult === 'legacy' ? 0 : 1) }) it('still refuses POSIX Archive when durable work has no verified exit', async () => { diff --git a/shared/src/runnerCapabilities.ts b/shared/src/runnerCapabilities.ts index 1b23554a735..c584b59ab4e 100644 --- a/shared/src/runnerCapabilities.ts +++ b/shared/src/runnerCapabilities.ts @@ -41,6 +41,7 @@ export const MACHINE_CAPABILITIES = { LocalSessionImport: 'local-session-import', /** Non-signaling session/PID exit probe (generation-keyed live-work clear). */ ProbeSessionExit: RPC_METHODS.ProbeSessionExit, + WindowsSessionJobProbe: 'windows-session-job-probe', } as const export type MachineCapability = @@ -57,6 +58,7 @@ export const CURRENT_MACHINE_CAPABILITIES: readonly MachineCapability[] = [ MACHINE_CAPABILITIES.WorkspaceFileAccess, MACHINE_CAPABILITIES.LocalSessionImport, MACHINE_CAPABILITIES.ProbeSessionExit, + MACHINE_CAPABILITIES.WindowsSessionJobProbe, ] /**