From afcca4ea1e06a2ac463adff26cea120e44932437 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:45:16 +0800 Subject: [PATCH] Reap sandbox processes left in an exited harness session Codex starts its filesystem-helper sandbox in a separate process group inside the app-server session. bwrap 0.9.0 arms PR_SET_PDEATHSIG only after the child reads its start eventfd, so a launcher killed between clone and that write strands the child forever. The stop check only probed the process group and reported such runs as stopped. Closing and stop confirmation now also find live members of the exited leader's session and SIGKILL them. A member that started no later than the recorded leader exit proves the session id was not reused, and each pid is re-read before the signal. Confirmation returns process-session-active while members remain. Co-Authored-By: Claude Opus 5.5 --- src/math/mathProcess.ts | 78 ++++++++++++++++++++++++++++++-- src/runtime/claudeCodeSession.ts | 3 +- src/runtime/cliSession.ts | 4 +- src/runtime/codexSession.ts | 3 +- src/runtime/openCodeSession.ts | 3 +- tests/mathProcess.test.ts | 41 ++++++++++++++++- 6 files changed, 122 insertions(+), 10 deletions(-) diff --git a/src/math/mathProcess.ts b/src/math/mathProcess.ts index 0c85a5ad..8b9702d7 100644 --- a/src/math/mathProcess.ts +++ b/src/math/mathProcess.ts @@ -1,5 +1,6 @@ import crypto from 'node:crypto'; import { spawn, type ChildProcess } from 'node:child_process'; +import fs from 'node:fs'; import path from 'node:path'; import { StringDecoder } from 'node:string_decoder'; import type { Readable } from 'node:stream'; @@ -70,13 +71,77 @@ export const stopMathProcess = (child: ChildProcess, signal: NodeJS.Signals): vo export type MathProcessStopReceipt = Readonly<{ status: 'stopped' } | { status: 'unconfirmed'; reason: 'process-exit-unconfirmed' | 'process-identity-unavailable' | 'unsupported-platform' | - 'process-group-active' | 'process-group-unavailable' }>; + 'process-group-active' | 'process-group-unavailable' | 'process-session-active' }>; + +const sessionExitTicks = new WeakMap(); +const childExited = (child: ChildProcess) => typeof child.exitCode === 'number' || typeof child.signalCode === 'string'; +const noteSessionExit = (child: ChildProcess): void => { + if (sessionExitTicks.has(child)) return; + // /proc/uptime and /proc//stat starttime share the boot clock; Linux USER_HZ is 100. + // Parse centiseconds as digits: 329484.29 * 100 is 32948428.99... in floating point. + let uptime: RegExpExecArray | null = null; + try { uptime = /^(\d+)\.(\d\d)\s/u.exec(fs.readFileSync('/proc/uptime', 'utf8')); } + catch { /* Without a clock reading no member can prove session continuity. */ } + if (uptime) sessionExitTicks.set(child, Number(uptime[1]) * 100 + Number(uptime[2])); +}; + +/** Record when an owned detached child exits so a later session sweep can prove its session id was not reused. */ +export function trackMathProcessSession(child: ChildProcess): void { + if (process.platform !== 'linux' || sessionExitTicks.has(child)) return; + if (childExited(child)) noteSessionExit(child); + else if (typeof child.once === 'function') child.once('exit', () => noteSessionExit(child)); +} + +type SessionMember = { pid: number; start: string }; +const readSessionMember = (pid: string, sid: number) => { + let stat: string; + try { stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8'); } catch { return undefined; } + const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' '); + return Number(fields[3]) === sid ? { state: fields[0], ppid: Number(fields[1]), start: fields[19] } : undefined; +}; + +/** Live members of a detached child's session that outlived it. + * Codex starts sandbox helpers in their own process groups, so a group signal + * misses them; a bwrap child stranded before PR_SET_PDEATHSIG then waits forever. + * Linux keeps a session id reserved while any member lives, so a member started + * no later than the observed leader exit proves the session was never reused. */ +function leakedSessionMembers(child: ChildProcess): SessionMember[] { + const sid = child.pid; + if (process.platform !== 'linux' || !sid || !childExited(child)) return []; + // A live /proc entry is a recycled pid, except our own leader before the runtime reaps it. + const leader = readSessionMember(String(sid), sid); + if (leader ? leader.state !== 'Z' || leader.ppid !== process.pid : fs.existsSync(`/proc/${sid}`)) return []; + noteSessionExit(child); + const exitTicks = sessionExitTicks.get(child); + if (exitTicks === undefined) return []; + let entries: string[]; + try { entries = fs.readdirSync('/proc'); } catch { return []; } + const members: SessionMember[] = []; + let continuous = false; + for (const entry of entries) { + if (!/^\d+$/.test(entry)) continue; + const member = readSessionMember(entry, sid); + if (!member) continue; + if (Number(member.start) <= exitTicks) continuous = true; + if (member.state !== 'Z' && member.state !== 'X') members.push({ pid: Number(entry), start: member.start }); + } + return continuous ? members : []; +} + +const killSessionMembers = (child: ChildProcess, members: readonly SessionMember[]): void => { + for (const member of members) { + // Re-read identity right before the signal so a recycled pid is never hit. + if (readSessionMember(String(member.pid), child.pid!)?.start !== member.start) continue; + try { process.kill(member.pid, 'SIGKILL'); } catch { /* Already exited. */ } + } +}; /** A bounded close is cleanup, not proof that the owned writer process group has exited. */ export async function confirmMathProcessStopped(child: ChildProcess, timeoutMs = 1000): Promise { if (process.platform === 'win32') return { status: 'unconfirmed', reason: 'unsupported-platform' }; if (!Number.isSafeInteger(child.pid) || child.pid! <= 0) return { status: 'unconfirmed', reason: 'process-identity-unavailable' }; + trackMathProcessSession(child); const deadline = Date.now() + Math.max(0, timeoutMs); for (;;) { const exited = typeof child.exitCode === 'number' || typeof child.signalCode === 'string'; @@ -87,22 +152,26 @@ export async function confirmMathProcessStopped(child: ChildProcess, timeoutMs = return { status: 'unconfirmed', reason: 'process-group-unavailable' }; group = 'absent'; } - if (exited && group === 'absent') return { status: 'stopped' }; + const members = exited && group === 'absent' ? leakedSessionMembers(child) : []; + if (exited && group === 'absent' && !members.length) return { status: 'stopped' }; + killSessionMembers(child, members); const remaining = deadline - Date.now(); if (remaining <= 0) return { status: 'unconfirmed', - reason: !exited ? 'process-exit-unconfirmed' : 'process-group-active' }; + reason: !exited ? 'process-exit-unconfirmed' : group === 'active' ? 'process-group-active' : 'process-session-active' }; await delay(Math.min(25, remaining)); } } /** Cleanup has a finite deadline even when solving has none. Launch owned children detached on POSIX. */ export function closeMathProcess(child: ChildProcess, gracefulInput = false, graceMs = 3_000): Promise { + trackMathProcessSession(child); return new Promise(resolve => { let force: NodeJS.Timeout | undefined, fallback: NodeJS.Timeout | undefined; const finish = () => { clearTimeout(force); clearTimeout(fallback); child.off('close', finish); stopMathProcess(child, 'SIGKILL'); + killSessionMembers(child, leakedSessionMembers(child)); resolve(); }; if ((child.exitCode !== null || child.signalCode !== null) && child.stdout?.closed && child.stderr?.closed) return finish(); @@ -170,7 +239,7 @@ export const runMathProcess = ( const finish = (exitCode: number | null, signal: NodeJS.Signals | null): void => { if (settled) return; settled = true; - if (stopping) stopMathProcess(child, 'SIGKILL'); + if (stopping) { stopMathProcess(child, 'SIGKILL'); killSessionMembers(child, leakedSessionMembers(child)); } if (timeout) clearTimeout(timeout); if (forceStopTimeout) clearTimeout(forceStopTimeout); if (fallbackTimeout) clearTimeout(fallbackTimeout); @@ -241,6 +310,7 @@ export const runMathProcess = ( options.onOutput?.('stderr', chunk); stderr = capture(stderr, chunk); }); + trackMathProcessSession(child); child.once('spawn', () => { started = true; }); child.once('error', (error: NodeJS.ErrnoException) => { processError = error; diff --git a/src/runtime/claudeCodeSession.ts b/src/runtime/claudeCodeSession.ts index 98ec171c..8584ece8 100644 --- a/src/runtime/claudeCodeSession.ts +++ b/src/runtime/claudeCodeSession.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { spawn, type ChildProcess } from 'node:child_process'; import { StringDecoder } from 'node:string_decoder'; -import { closeMathProcess, confirmMathProcessStopped } from '../math/mathProcess'; +import { closeMathProcess, confirmMathProcessStopped, trackMathProcessSession } from '../math/mathProcess'; import { readMathText } from '../math/mathRuntimeIo'; import { scheduleMathTimeout } from '../math/mathTimers'; import { assertMathAgentSkillsCurrent } from './agentSkills'; @@ -148,6 +148,7 @@ export async function createClaudeCodeMathSession(options: MathAgentOptions): Pr cwd: options.workspace, env: invocation.env, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe', ...('inheritedFds' in invocation ? invocation.inheritedFds ?? [] : [])], }); + trackMathProcessSession(owned); return await new Promise(resolve => { let settled = false, started = false, terminal: Json | undefined, usageReported = false; let apiFailure: MathAgentFailureDiagnostic | undefined; diff --git a/src/runtime/cliSession.ts b/src/runtime/cliSession.ts index 097c5a1e..db6ec69e 100644 --- a/src/runtime/cliSession.ts +++ b/src/runtime/cliSession.ts @@ -2,7 +2,7 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { spawn, type ChildProcess } from 'node:child_process'; -import { closeMathProcess, confirmMathProcessStopped } from '../math/mathProcess'; +import { closeMathProcess, confirmMathProcessStopped, trackMathProcessSession } from '../math/mathProcess'; import { readMathText, writeMathFrozen } from '../math/mathRuntimeIo'; import { scheduleMathTimeout } from '../math/mathTimers'; import { assertMathCanonicalPath } from '../math/paths'; @@ -107,7 +107,7 @@ export async function createCliMathSession(options: MathAgentOptions): Promise options.onUsageIncomplete?.()); return 'failed'; diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index 6344ca7d..4b84bdfc 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -1,5 +1,5 @@ import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'; -import { closeMathProcess, confirmMathProcessStopped, type MathProcessStopReceipt } from '../math/mathProcess'; +import { closeMathProcess, confirmMathProcessStopped, trackMathProcessSession, type MathProcessStopReceipt } from '../math/mathProcess'; import fs from 'node:fs'; import path from 'node:path'; import { randomUUID } from 'node:crypto'; @@ -158,6 +158,7 @@ class CodexRpc { stdio: extras.length ? ['pipe', 'pipe', 'pipe', ...extras] : 'pipe', detached: process.platform !== 'win32', }) as ChildProcessWithoutNullStreams; // All three protocol streams are pipes, including launches with extra inherited FDs. + trackMathProcessSession(this.child); const infoDescriptor = launch?.infoDescriptor; this.processIdentity = infoDescriptor === undefined ? Promise.resolve(undefined) : new Promise((resolve, reject) => { const pipe = this.child.stdio[infoDescriptor] as NodeJS.ReadableStream; diff --git a/src/runtime/openCodeSession.ts b/src/runtime/openCodeSession.ts index b9c040a7..5cb552ff 100644 --- a/src/runtime/openCodeSession.ts +++ b/src/runtime/openCodeSession.ts @@ -4,7 +4,7 @@ import net from 'node:net'; import { spawn } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { createParser } from 'eventsource-parser'; -import { closeMathProcess, confirmMathProcessStopped } from '../math/mathProcess'; +import { closeMathProcess, confirmMathProcessStopped, trackMathProcessSession } from '../math/mathProcess'; import { scheduleMathTimeout } from '../math/mathTimers'; import { assertMathAgentSkillsCurrent } from './agentSkills'; import type { MathAgentOptions, MathAgentSession } from './agentSession'; @@ -77,6 +77,7 @@ export async function createOpenCodeMathSession(options: MathAgentOptions): Prom environment: { ...options.environment, ...nativeEnvironment } }, options.executable, arguments_); const child = spawn(launch.command, launch.args, { cwd: workspace, env: launch.env, detached: true, stdio: ['ignore', 'pipe', 'pipe', ...('inheritedFds' in launch ? launch.inheritedFds ?? [] : [])] }); + trackMathProcessSession(child); const lifetime = new AbortController(); let closing: Promise | undefined, running = false, settled = true, threadId = ''; let lastError: string | undefined, lastInputTokens: number | undefined; diff --git a/tests/mathProcess.test.ts b/tests/mathProcess.test.ts index 99702f57..6d5f4dc7 100644 --- a/tests/mathProcess.test.ts +++ b/tests/mathProcess.test.ts @@ -5,7 +5,8 @@ import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { spawn, type ChildProcess } from 'node:child_process'; import { EventEmitter } from 'node:events'; -import { closeMathProcess, confirmMathProcessStopped, limitMathOutput, MATH_PROCESS_OUTPUT_LIMIT, runMathProcess, runLeanProcess } from '../src/math/mathProcess'; +import { closeMathProcess, confirmMathProcessStopped, limitMathOutput, MATH_PROCESS_OUTPUT_LIMIT, runMathProcess, runLeanProcess, + trackMathProcessSession } from '../src/math/mathProcess'; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); @@ -83,6 +84,44 @@ describe('process lifecycle and bounded output', () => { expect(await confirmMathProcessStopped(child, 0)).toEqual({ status: 'stopped' }); } finally { kill.mockRestore(); } }); + // Codex starts sandbox helpers in their own process groups inside its session. + // `set -m` gives the background sleep its own group, so a group signal misses it. + const spawnSessionWithStrayGroup = (keepLeader: boolean) => { + const child = spawn('/bin/bash', ['-c', `set -m; sleep 30 >/dev/null 2>&1 & echo $!; ${keepLeader ? 'sleep 30' : 'exit 0'}`], + { detached: true, stdio: ['ignore', 'pipe', 'ignore'] }); + trackMathProcessSession(child); + const stray = new Promise(resolve => child.stdout!.once('data', chunk => resolve(Number(String(chunk).trim())))); + return { child, stray }; + }; + const alive = (pid: number) => { + try { return !['Z', 'X'].includes(fs.readFileSync(`/proc/${pid}/stat`, 'utf8').split(') ')[1][0]); } catch { return false; } + }; + const pgid = (pid: number) => Number(fs.readFileSync(`/proc/${pid}/stat`, 'utf8').split(') ')[1].split(' ')[2]); + + it.skipIf(process.platform !== 'linux')('reaps session members in other process groups before confirming stop', async () => { + const { child, stray } = spawnSessionWithStrayGroup(false); + const pid = await stray; + try { + await new Promise(resolve => child.once('close', resolve)); + expect(alive(pid)).toBe(true); + expect(pgid(pid)).not.toBe(child.pid); + expect(() => process.kill(-child.pid!, 0)).toThrow(); + expect(await confirmMathProcessStopped(child)).toEqual({ status: 'stopped' }); + expect(alive(pid)).toBe(false); + } finally { try { process.kill(pid, 'SIGKILL'); } catch { /* reaped */ } } + }); + + it.skipIf(process.platform !== 'linux')('kills session members left behind when closing a live writer', async () => { + const { child, stray } = spawnSessionWithStrayGroup(true); + const pid = await stray; + try { + await closeMathProcess(child, false, 100); + for (let i = 0; i < 40 && alive(pid); i++) await new Promise(resolve => setTimeout(resolve, 25)); + expect(alive(pid)).toBe(false); + expect(await confirmMathProcessStopped(child, 0)).toEqual({ status: 'stopped' }); + } finally { try { process.kill(pid, 'SIGKILL'); } catch { /* reaped */ } } + }); + it('does not report a missing executable as started', async () => { const result = await runMathProcess('/nonexistent/math-command', [], { cwd: os.tmpdir(), timeoutMs: 1000 }); expect(result).toMatchObject({ started: false, errorCode: 'ENOENT', timedOut: false });