Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 74 additions & 4 deletions src/math/mathProcess.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<ChildProcess, number>();
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/<pid>/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<MathProcessStopReceipt> {
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';
Expand All @@ -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<void> {
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();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/claudeCodeSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string>(resolve => {
let settled = false, started = false, terminal: Json | undefined, usageReported = false;
let apiFailure: MathAgentFailureDiagnostic | undefined;
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/cliSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -107,7 +107,7 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
let owned: ChildProcess;
try { owned = child = spawn(invocation.command, invocation.args, { cwd: workspace, env: invocation.env,
detached: process.platform !== 'win32',
stdio: ['pipe', 'pipe', 'pipe', ...('inheritedFds' in invocation ? invocation.inheritedFds ?? [] : [])] }); }
stdio: ['pipe', 'pipe', 'pipe', ...('inheritedFds' in invocation ? invocation.inheritedFds ?? [] : [])] }); trackMathProcessSession(owned); }
catch {
lastError = 'math_cli_process_start_failed'; diagnostic = { code: 'other' };
observe(() => options.onUsageIncomplete?.()); return 'failed';
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/codexSession.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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;
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/openCodeSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<void> | undefined, running = false, settled = true, threadId = '';
let lastError: string | undefined, lastInputTokens: number | undefined;
Expand Down
41 changes: 40 additions & 1 deletion tests/mathProcess.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }); });
Expand Down Expand Up @@ -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<number>(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 });
Expand Down
Loading