diff --git a/src/config/loader.ts b/src/config/loader.ts index 0b5665b..3fa0a34 100644 --- a/src/config/loader.ts +++ b/src/config/loader.ts @@ -164,6 +164,93 @@ export function getCharacterLimit(): number { return override; } +/** + * Lifecycle / shutdown timeout knobs. + * + * These govern graceful self-shutdown and downstream child cleanup: + * - CHILD_SHUTDOWN: SIGTERM→SIGKILL grace per spawned child (default 30s). + * - PARENT_POLL: cadence of the parent-liveness poll (default 2s). + * - CLIENT_CLOSE: per-client close() timeout so a wedged child cannot stall + * shutdown before the kill sequence runs (default 2s). + */ +export const DEFAULT_CHILD_SHUTDOWN_TIMEOUT_MS = 30_000; +const MIN_CHILD_SHUTDOWN_TIMEOUT_MS = 1_000; +const MAX_CHILD_SHUTDOWN_TIMEOUT_MS = 300_000; // 5 min ceiling + +export const DEFAULT_PARENT_POLL_INTERVAL_MS = 2_000; +const MIN_PARENT_POLL_INTERVAL_MS = 500; +const MAX_PARENT_POLL_INTERVAL_MS = 60_000; + +export const DEFAULT_CLIENT_CLOSE_TIMEOUT_MS = 2_000; +const MIN_CLIENT_CLOSE_TIMEOUT_MS = 250; +const MAX_CLIENT_CLOSE_TIMEOUT_MS = 30_000; + +/** + * Read a bounded integer env var for the shutdown path. + * + * **WHY clamp instead of throw:** unlike {@link getCharacterLimit} (read on the + * execution/output path, where fail-fast is fine), these knobs are read while + * SHUTTING DOWN. A throw here would abort the very cleanup the value configures + * and re-create the orphan it is meant to prevent. So a non-numeric value falls + * back to the default and an out-of-range value is clamped — shutdown never + * throws on a misconfigured timeout. + */ +function getBoundedEnvMs( + value: string | undefined, + defaultMs: number, + minMs: number, + maxMs: number +): number { + if (!value) return defaultMs; + const parsed = parseInt(value, 10); + if (isNaN(parsed)) return defaultMs; + if (parsed < minMs) return minMs; + if (parsed > maxMs) return maxMs; + return parsed; +} + +/** + * Grace period (ms) a spawned child gets after SIGTERM before it is SIGKILLed. + * + * Exit is polled, so a child that honors SIGTERM exits well within this window + * and is not delayed; the timeout only bounds a misbehaving/wedged child. + * Overridable via CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS (1s..5min). + */ +export function getChildShutdownTimeoutMs(): number { + return getBoundedEnvMs( + process.env.CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS, + DEFAULT_CHILD_SHUTDOWN_TIMEOUT_MS, + MIN_CHILD_SHUTDOWN_TIMEOUT_MS, + MAX_CHILD_SHUTDOWN_TIMEOUT_MS + ); +} + +/** + * Cadence (ms) of the active parent-liveness poll. + * Overridable via CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS (0.5s..60s). + */ +export function getParentPollIntervalMs(): number { + return getBoundedEnvMs( + process.env.CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS, + DEFAULT_PARENT_POLL_INTERVAL_MS, + MIN_PARENT_POLL_INTERVAL_MS, + MAX_PARENT_POLL_INTERVAL_MS + ); +} + +/** + * Per-client close() timeout (ms) during shutdown. + * Overridable via CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS (0.25s..30s). + */ +export function getClientCloseTimeoutMs(): number { + return getBoundedEnvMs( + process.env.CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS, + DEFAULT_CLIENT_CLOSE_TIMEOUT_MS, + MIN_CLIENT_CLOSE_TIMEOUT_MS, + MAX_CLIENT_CLOSE_TIMEOUT_MS + ); +} + /** * Get allowed read paths */ diff --git a/src/index.ts b/src/index.ts index d23fd3c..592c215 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,10 +13,11 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { z } from 'zod'; -import { initConfig, isPythonEnabled, isRateLimitEnabled, getRateLimitConfig, shouldSkipDangerousPatternCheck } from './config/loader.js'; +import { initConfig, isPythonEnabled, isRateLimitEnabled, getRateLimitConfig, shouldSkipDangerousPatternCheck, getChildShutdownTimeoutMs, getParentPollIntervalMs } from './config/loader.js'; import { ExecuteTypescriptInputSchema, ExecutePythonInputSchema, ExecutionResultSchema } from './config/schemas.js'; import { MCPClientPool } from './mcp/client-pool.js'; import { watchClientDisconnect } from './mcp/stdin-watcher.js'; +import { watchParentExit } from './mcp/parent-watcher.js'; import { redirectConsoleLogToStderr } from './utils/stdio-guard.js'; import { SecurityValidator } from './validation/security-validator.js'; import { ConnectionPool } from './mcp/connection-pool.js'; @@ -67,6 +68,7 @@ class CodeExecutorServer { private denoAvailable: boolean = false; private healthCheckServer: HealthCheckServer | null = null; private shutdownInProgress = false; // P1: Prevent concurrent shutdown attempts + private stopParentWatch: (() => void) | null = null; // halts the parent-liveness poll // Resolves when the downstream MCP client pool has finished initializing. // The pool is initialized in the BACKGROUND (see start()) so the upstream MCP // handshake is never blocked by slow/unreachable downstream servers. Tool @@ -733,6 +735,25 @@ Returns: }); }); + // Belt-and-suspenders to the stdin watcher above: actively poll parent + // liveness. stdin EOF can fail to arrive (host SIGKILLed, or a wrapper/an + // inherited fd holds our stdin pipe's write end open), in which case this + // poll is the only signal that the host is gone. On POSIX, parent death + // reparents us to PID 1; that is what we watch for. See parent-watcher.ts. + this.stopParentWatch = watchParentExit({ + getPpid: () => process.ppid, + initialPpid: process.ppid, + intervalMs: getParentPollIntervalMs(), + isPosix: process.platform !== 'win32', + onParentExit: (reason) => { + console.error(`Parent process gone (${reason}) — initiating shutdown...`); + void this.shutdown().catch((error) => { + console.error('Error during parent-exit-triggered shutdown:', error); + process.exit(1); + }); + }, + }); + console.error('Code Executor MCP Server started successfully (downstream MCP pool initializing in background)'); // Initialize MCP client pool in the background. Tool handlers await @@ -795,9 +816,12 @@ Returns: * 3. Clean up rate limiter * 4. Disconnect MCP clients (with 2s SIGTERM grace period) * - * @param timeoutMs - Maximum time for entire shutdown (default: 35s = 30s drain + 5s cleanup) + * @param timeoutMs - Maximum time for the entire shutdown. When omitted it is + * derived from config as drain + per-child grace + buffer, so the graceful + * child-kill window (CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS) is never + * pre-empted by this overall cap. */ - async shutdown(timeoutMs: number = 35000): Promise { + async shutdown(timeoutMs?: number): Promise { // P1: Prevent concurrent shutdown attempts (manual + signal handler races) if (this.shutdownInProgress) { console.error('Shutdown already in progress - ignoring duplicate call'); @@ -805,6 +829,20 @@ Returns: } this.shutdownInProgress = true; + // Stop the parent-liveness poll — shutdown is underway (hygiene; the guard + // above already makes a second trigger a no-op). + if (this.stopParentWatch) { + this.stopParentWatch(); + this.stopParentWatch = null; + } + + // Overall cap must outlast Phase-1 drain plus the Phase-4 per-child graceful + // kill window, otherwise the timeout race below would force process.exit(0) + // (and a synchronous SIGKILL via the 'exit' handler) before a legitimately + // graceful child shutdown could complete. +5s cleanup buffer. + const drainTimeoutMs = 30_000; + const effectiveTimeoutMs = timeoutMs ?? drainTimeoutMs + getChildShutdownTimeoutMs() + 5_000; + const shutdownStart = Date.now(); // Wrap entire shutdown in timeout protection @@ -812,7 +850,7 @@ Returns: // Phase 1: Drain connection pool (wait for active executions) console.error('Phase 1: Draining connection pool...'); try { - await this.connectionPool.drain(30000); // 30s timeout for executions + await this.connectionPool.drain(drainTimeoutMs); // wait for active executions } catch (error) { console.error('Error draining connection pool:', error); } @@ -846,10 +884,10 @@ Returns: setTimeout(() => { const elapsed = Date.now() - shutdownStart; console.error( - `⚠️ Shutdown timeout after ${timeoutMs}ms (elapsed: ${elapsed}ms) - forcing exit` + `⚠️ Shutdown timeout after ${effectiveTimeoutMs}ms (elapsed: ${elapsed}ms) - forcing exit` ); resolve(); - }, timeoutMs); + }, effectiveTimeoutMs); }); await Promise.race([shutdownPromise, timeoutPromise]); @@ -881,6 +919,9 @@ const handleShutdownSignal = async (signal: string) => { process.on('SIGINT', () => void handleShutdownSignal('SIGINT')); process.on('SIGTERM', () => void handleShutdownSignal('SIGTERM')); +// SIGHUP: controlling terminal / session leader went away (a common parent-death +// signal). Treat it as a graceful shutdown rather than the default (terminate). +process.on('SIGHUP', () => void handleShutdownSignal('SIGHUP')); // Synchronous last-resort cleanup. If the process exits without the async // graceful path completing (e.g. host sends SIGKILL after a timeout, or an diff --git a/src/mcp/client-pool.ts b/src/mcp/client-pool.ts index caba777..207d57a 100644 --- a/src/mcp/client-pool.ts +++ b/src/mcp/client-pool.ts @@ -12,8 +12,9 @@ import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'; import { EventEmitter } from 'events'; import { execFileSync } from 'child_process'; import * as fs from 'fs/promises'; -import { getPoolConfig } from '../config/loader.js'; -import { isValidMCPToolName, normalizeError, isErrnoException } from '../utils/utils.js'; +import { getPoolConfig, getChildShutdownTimeoutMs, getClientCloseTimeoutMs } from '../config/loader.js'; +import { isValidMCPToolName, normalizeError } from '../utils/utils.js'; +import { killProcessGracefully } from './process-killer.js'; import type { MCPConfig, MCPServerConfig, ToolInfo, ProcessInfo, StdioServerConfig, HttpServerConfig } from '../types.js'; import { isStdioConfig, isHttpConfig } from '../types.js'; import type { IToolSchemaProvider, CachedToolSchema } from '../types.js'; @@ -922,82 +923,80 @@ export class MCPClientPool implements IToolSchemaProvider { } /** - * Disconnect all clients and kill child processes + * Await `close()` but never let it hang shutdown. * - * Graceful shutdown: SIGTERM → wait 2s → SIGKILL + * WHY: a wedged downstream child (e.g. basic-memory stuck on a lock) can make + * the SDK's `client.close()` / `transport.close()` block indefinitely. Before + * this bound, that hung the whole disconnect() BEFORE the SIGTERM→SIGKILL step + * ran, so the child orphaned anyway. We cap the close and then proceed to kill + * the underlying PID regardless. */ - async disconnect(): Promise { - // Close MCP clients - const disconnections = Array.from(this.clients.values()).map( - async (client) => { - try { - await client.close(); - } catch (error) { - console.error('Error disconnecting client:', error); - } + private async closeWithTimeout( + close: () => Promise, + timeoutMs: number, + label: string + ): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((resolve) => { + timer = setTimeout(() => { + console.error(`⚠️ ${label} did not close within ${timeoutMs}ms — proceeding to terminate`); + resolve(); + }, timeoutMs); + }); + try { + await Promise.race([ + close().catch((error) => console.error(`Error closing ${label}:`, error)), + timeout, + ]); + } finally { + if (timer) { + clearTimeout(timer); } - ); - - await Promise.all(disconnections); + } + } - // Kill child processes (STDIO servers only) - const processCleanup = Array.from(this.processes.values()).map( - async (processInfo) => { - try { - const { pid, serverName } = processInfo; + /** + * Disconnect all clients and kill child processes. + * + * Graceful shutdown per child: SIGTERM → poll for exit → SIGKILL once the + * configured grace window (CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS, default + * 30s) elapses. `client.close()` is bounded (CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS) + * so a wedged child cannot stall the kill sequence. + */ + async disconnect(): Promise { + const closeTimeoutMs = getClientCloseTimeoutMs(); + const childTimeoutMs = getChildShutdownTimeoutMs(); + const logToStderr = (message: string): void => console.error(message); - // Try graceful shutdown (SIGTERM) - try { - process.kill(pid, 'SIGTERM'); - console.error(`✓ Sent SIGTERM to ${serverName} (PID ${pid})`); - - // Wait 2 seconds for graceful shutdown - await new Promise((resolve) => setTimeout(resolve, 2000)); - - // Check if process still exists - try { - process.kill(pid, 0); // Signal 0 checks existence - // Process still alive, force kill - process.kill(pid, 'SIGKILL'); - console.error(`⚠️ Force killed ${serverName} (PID ${pid}) with SIGKILL`); - } catch { - // Process already exited - console.error(`✓ ${serverName} (PID ${pid}) exited gracefully`); - } - } catch (error) { - // Process might already be dead, safe to ignore ESRCH (No such process) - // TYPE-001 fix: Use isErrnoException type guard instead of unsafe cast - if (!isErrnoException(error) || error.code !== 'ESRCH') { - console.error(`Error killing ${serverName} (PID ${pid}):`, error); - } - } - } catch (error) { - console.error('Error during process cleanup:', error); - } - } + // Close MCP clients — bounded, so a wedged client cannot stall the kill step. + const disconnections = Array.from(this.clients.values()).map((client) => + this.closeWithTimeout(() => client.close(), closeTimeoutMs, 'MCP client') ); + await Promise.all(disconnections); + // Kill tracked STDIO child processes (graceful → force after grace window). + const processCleanup = Array.from(this.processes.values()).map(({ pid, serverName }) => + killProcessGracefully(pid, { + timeoutMs: childTimeoutMs, + logger: logToStderr, + serverName, + }) + ); await Promise.all(processCleanup); - // Close any transports whose connect() is still in flight (mid-init shutdown). + // Close transports whose connect() is still in flight (mid-init shutdown). // These are not yet in `processes`, so without this their children would leak. - const pendingCleanup = Array.from(this.pendingStdioTransports).map( - async (transport) => { - const pid = transport.pid; - try { - await transport.close(); - } catch { - // best effort - } - if (pid != null) { - try { - process.kill(pid, 'SIGKILL'); - } catch { - // already gone / not permitted - } - } + const pendingCleanup = Array.from(this.pendingStdioTransports).map(async (transport) => { + const pid = transport.pid; + await this.closeWithTimeout(() => transport.close(), closeTimeoutMs, 'pending transport'); + if (pid != null) { + await killProcessGracefully(pid, { + timeoutMs: childTimeoutMs, + logger: logToStderr, + serverName: 'pending-transport', + }); } - ); + }); await Promise.all(pendingCleanup); this.pendingStdioTransports.clear(); diff --git a/src/mcp/parent-watcher.ts b/src/mcp/parent-watcher.ts new file mode 100644 index 0000000..0715363 --- /dev/null +++ b/src/mcp/parent-watcher.ts @@ -0,0 +1,76 @@ +/** + * Active parent-liveness watcher for the stdio MCP transport. + * + * WHY: stdin EOF (see stdin-watcher.ts) is the primary signal that the MCP host + * (our parent) is gone, but it is not always delivered — the host can be + * SIGKILLed, or a launcher/wrapper (or a child that inherited fd 0) can hold the + * write end of our stdin pipe open, so the EOF never arrives. When that happens + * the server — and every downstream MCP child it spawned (e.g. basic-memory, + * which then keeps holding its SQLite lock) — orphans forever. + * + * On POSIX a process whose parent dies is reparented to init/launchd (PID 1), so + * `process.ppid` changing away from its startup value is a reliable, polling-based + * "parent is gone" signal that does not depend on the pipe. This complements the + * stdin watcher rather than replacing it. + * + * Kept as a standalone, side-effect-free module (mirrors stdin-watcher.ts) so it + * is unit-testable with an injected `getPpid` and fake timers — importing the + * main server module would run its startup side effects. + */ + +/** + * Options for {@link watchParentExit}. + */ +export interface WatchParentExitOptions { + /** Reads the current parent PID. Default: `() => process.ppid`. */ + getPpid: () => number; + /** Parent PID captured at startup, used as the reference for "reparented". */ + initialPpid: number; + /** Poll cadence in milliseconds. */ + intervalMs: number; + /** Whether the platform has POSIX reparent-to-PID-1 semantics. */ + isPosix: boolean; + /** Invoked exactly once when the parent is detected gone. */ + onParentExit: (reason: string) => void; +} + +/** + * Poll parent liveness and invoke `onParentExit` exactly once when the parent + * is gone (the process has been reparented away from its startup parent). + * + * No-op (returns a no-op stop) when: + * - `isPosix` is false (Windows reparent semantics differ — stdin EOF is relied + * on there), or + * - `initialPpid <= 1` (the process was launched directly by init/launchd, so + * "ppid === 1" is not a death signal — avoids a false positive). + * + * @returns A `stop()` function that halts polling. + */ +export function watchParentExit(opts: WatchParentExitOptions): () => void { + const { getPpid, initialPpid, intervalMs, isPosix, onParentExit } = opts; + + // Guard clauses: situations where the poll cannot give a reliable signal. + if (!isPosix || initialPpid <= 1) { + return () => {}; + } + + let fired = false; + const timer = setInterval(() => { + if (fired) { + return; + } + // Reparented away from the startup parent (→ PID 1 on POSIX) ⇒ parent gone. + if (getPpid() !== initialPpid) { + fired = true; + clearInterval(timer); + onParentExit('reparented'); + } + }, intervalMs); + + // Don't keep the event loop alive solely for this poll. + if (typeof timer.unref === 'function') { + timer.unref(); + } + + return () => clearInterval(timer); +} diff --git a/src/mcp/process-killer.ts b/src/mcp/process-killer.ts new file mode 100644 index 0000000..4e90d4e --- /dev/null +++ b/src/mcp/process-killer.ts @@ -0,0 +1,104 @@ +/** + * Graceful child-process termination. + * + * WHY: when the client pool shuts down it must stop the downstream MCP servers + * it spawned (e.g. basic-memory). A flat "sleep N then check once" wastes time + * for a child that exits immediately on SIGTERM and gives no headroom for one + * that needs a moment. This polls for exit instead: SIGTERM → check existence + * every `pollIntervalMs` → return as soon as the child is gone → SIGKILL only if + * it is still alive once the bounded grace window elapses. + * + * Pure and dependency-injected (`kill`, `sleep`, `logger`) so it is unit-testable + * with fake timers and a mock kill, without spawning real processes. + */ + +import { isErrnoException } from '../utils/utils.js'; + +/** + * Outcome of a graceful kill: + * - `'gone'` — the process was already dead when we tried to SIGTERM it. + * - `'exited'` — it exited on its own within the grace window after SIGTERM. + * - `'killed'` — it was still alive at the deadline and got SIGKILLed. + */ +export type KillResult = 'gone' | 'exited' | 'killed'; + +/** + * Options for {@link killProcessGracefully}. + */ +export interface KillProcessOptions { + /** Signal sender. Default: `process.kill` bound to `process`. */ + kill?: (pid: number, signal: NodeJS.Signals | number) => void; + /** Existence-probe cadence in milliseconds. Default: 250. */ + pollIntervalMs?: number; + /** Total grace window in milliseconds before SIGKILL. Default: 30_000. */ + timeoutMs?: number; + /** Sleep helper. Default: `setTimeout`-based. Injectable for tests. */ + sleep?: (ms: number) => Promise; + /** Optional diagnostic logger (goes to stderr in production). */ + logger?: (message: string) => void; + /** Human-readable server name for log lines. */ + serverName?: string; +} + +const DEFAULT_POLL_INTERVAL_MS = 250; +const DEFAULT_TIMEOUT_MS = 30_000; + +/** + * Probe whether `pid` is still alive using signal 0 (no signal is delivered). + */ +function isAlive(pid: number, kill: (pid: number, signal: NodeJS.Signals | number) => void): boolean { + try { + kill(pid, 0); + return true; + } catch { + return false; // ESRCH (gone) or EPERM — treat as "cannot confirm alive" + } +} + +/** + * SIGTERM a process, poll for its exit, and SIGKILL it if it outlives the grace + * window. Never throws — termination is best-effort by design. + */ +export async function killProcessGracefully( + pid: number, + opts: KillProcessOptions = {} +): Promise { + const kill = opts.kill ?? ((p: number, signal: NodeJS.Signals | number) => process.kill(p, signal)); + const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS; + const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const sleep = opts.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const log = opts.logger ?? (() => {}); + const label = opts.serverName ? `${opts.serverName} (PID ${pid})` : `PID ${pid}`; + + // Step 1: ask the child to exit. + try { + kill(pid, 'SIGTERM'); + log(`✓ Sent SIGTERM to ${label}`); + } catch (error) { + if (isErrnoException(error) && error.code === 'ESRCH') { + return 'gone'; // already dead — nothing to do + } + // e.g. EPERM: we cannot signal it and SIGKILL would fail too. Best effort. + log(`Error sending SIGTERM to ${label}: ${String(error)}`); + return 'gone'; + } + + // Step 2: poll for exit across the grace window. + const iterations = Math.max(1, Math.ceil(timeoutMs / pollIntervalMs)); + for (let i = 0; i < iterations; i++) { + await sleep(pollIntervalMs); + if (!isAlive(pid, kill)) { + log(`✓ ${label} exited gracefully`); + return 'exited'; + } + } + + // Step 3: still alive at the deadline — force kill. + try { + kill(pid, 'SIGKILL'); + log(`⚠️ Force killed ${label} with SIGKILL`); + } catch { + // Raced to exit between the last probe and now — fine. + } + return 'killed'; +} diff --git a/tests/integration/fixtures/fake-mcp-server.mjs b/tests/integration/fixtures/fake-mcp-server.mjs new file mode 100644 index 0000000..a18c5e9 --- /dev/null +++ b/tests/integration/fixtures/fake-mcp-server.mjs @@ -0,0 +1,35 @@ +/** + * Minimal downstream STDIO MCP server used by the orphan-cleanup integration + * test. It connects over stdio (so the code-executor binary tracks it as a real + * spawned child) and then stays alive, writing its PID to FAKE_MCP_PID_FILE once + * connected so the test can track and assert on it. + * + * Set FAKE_MCP_IGNORE_SIGTERM=1 to make it ignore SIGTERM, which forces the + * SIGKILL-escalation branch of killProcessGracefully(). + */ + +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { writeFileSync } from 'node:fs'; + +if (process.env.FAKE_MCP_IGNORE_SIGTERM === '1') { + // Swallow SIGTERM so the parent must escalate to SIGKILL to reap us. + process.on('SIGTERM', () => {}); +} + +const server = new McpServer({ name: 'fake-mcp', version: '1.0.0' }); +server.registerTool( + 'noop', + { description: 'No-op tool so tools/list is non-empty during the handshake.' }, + async () => ({ content: [{ type: 'text', text: 'ok' }] }) +); + +const transport = new StdioServerTransport(); +await server.connect(transport); + +// Announce readiness + PID only AFTER the handshake transport is connected, so +// the test proceeds once we are a tracked downstream child of the binary. +const pidFile = process.env.FAKE_MCP_PID_FILE; +if (pidFile) { + writeFileSync(pidFile, String(process.pid)); +} diff --git a/tests/integration/orphan-cleanup.test.ts b/tests/integration/orphan-cleanup.test.ts new file mode 100644 index 0000000..f3d4ff3 --- /dev/null +++ b/tests/integration/orphan-cleanup.test.ts @@ -0,0 +1,180 @@ +/** + * End-to-end orphan-cleanup test against the REAL compiled binary. + * + * The project ships a bun standalone binary (bin/code-executor-mcp); unit tests + * of the TS source do not prove its runtime behavior (see CLAUDE.md). This test + * spawns that binary, has it connect to a real downstream STDIO MCP child (the + * fake-mcp-server fixture), then makes the parent go away two ways: + * 1. stdin EOF (host disconnect) — exercises the stdin-watcher path + * 2. the binary's parent process is killed — exercises the parent-watcher poll + * and asserts the downstream child is reaped (no orphan) and the binary exits. + * + * SAFETY / isolation: the binary is run with HOME pointed at a throwaway temp + * dir and a config that registers ONLY the fake server, so it can never connect + * to the developer's real MCP servers (basic-memory etc.). Both bun and node + * honor $HOME for os.homedir(), which is what config discovery uses. + * + * Skips entirely when the binary has not been built (e.g. CI, fresh clone) — + * mirrors tests/integration/sampling-flow.test.ts. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = resolve(fileURLToPath(import.meta.url), '..'); +const BINARY = resolve(here, '../../bin/code-executor-mcp'); +const FIXTURE = resolve(here, 'fixtures/fake-mcp-server.mjs'); +const hasBinary = existsSync(BINARY); + +const CHILD_SHUTDOWN_MS = 2000; // short grace so the test is fast +const describeBinary = hasBinary ? describe : describe.skip; + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +function delay(ms: number): Promise { + return new Promise((r) => setTimeout(r, ms)); +} + +async function waitFor(predicate: () => boolean, timeoutMs: number, intervalMs = 100): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (predicate()) return true; + await delay(intervalMs); + } + return predicate(); +} + +async function readPidWhenReady(pidFile: string, timeoutMs: number): Promise { + await waitFor(() => existsSync(pidFile), timeoutMs); + const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10); + if (isNaN(pid)) throw new Error(`fake server PID file not written within ${timeoutMs}ms`); + return pid; +} + +interface Workspace { + home: string; + fakePidFile: string; + /** Env for the binary: isolated HOME + fast shutdown knobs. */ + env: NodeJS.ProcessEnv; +} + +function setupWorkspace(): Workspace { + const home = mkdtempSync(join(tmpdir(), 'ce-orphan-')); + const fakePidFile = join(home, 'fake.pid'); + // detectMCPConfigLocation() (startup gate) AND the pool both read + // $HOME/.claude.json; register only the fake downstream server there. + const config = { + mcpServers: { + fake: { + command: process.execPath, // node + args: [FIXTURE], + env: { FAKE_MCP_PID_FILE: fakePidFile }, + }, + }, + }; + writeFileSync(join(home, '.claude.json'), JSON.stringify(config)); + + const env: NodeJS.ProcessEnv = { + ...process.env, + HOME: home, + ENABLE_HEALTH_CHECK: 'false', + CODE_EXECUTOR_ALLOW_NESTED: '1', // never enter LEAF MODE — we need the child + CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS: String(CHILD_SHUTDOWN_MS), + CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS: '300', + CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS: '1000', + }; + return { home, fakePidFile, env }; +} + +const spawned: ChildProcess[] = []; +const homes: string[] = []; + +afterEach(() => { + // Best-effort sweep: kill any process we spawned (and their groups) and remove temp homes. + for (const p of spawned) { + if (p.pid) { + try { process.kill(-p.pid, 'SIGKILL'); } catch { /* not a leader / gone */ } + try { process.kill(p.pid, 'SIGKILL'); } catch { /* gone */ } + } + } + spawned.length = 0; + for (const h of homes) { + try { rmSync(h, { recursive: true, force: true }); } catch { /* best effort */ } + } + homes.length = 0; +}); + +describeBinary('orphan cleanup (real binary)', () => { + it('reaps its downstream child and exits cleanly when stdin closes (host disconnect)', async () => { + const ws = setupWorkspace(); + homes.push(ws.home); + + const proc = spawn(BINARY, [], { cwd: ws.home, env: ws.env, stdio: ['pipe', 'pipe', 'pipe'] }); + spawned.push(proc); + let stderr = ''; + proc.stderr?.on('data', (d) => (stderr += String(d))); + const exited = new Promise((res) => proc.on('exit', (code) => res(code))); + + const childPid = await readPidWhenReady(ws.fakePidFile, 25000); + expect(isAlive(childPid)).toBe(true); + await delay(500); // let the binary register the child in its `processes` map + + proc.stdin?.end(); // EOF → host-disconnect shutdown + + const code = await Promise.race([ + exited, + delay(15000).then(() => 'timeout' as const), + ]); + const reaped = await waitFor(() => !isAlive(childPid), CHILD_SHUTDOWN_MS + 4000); + + expect(reaped, `downstream child ${childPid} was not reaped.\nbinary stderr:\n${stderr}`).toBe(true); + expect(code).toBe(0); + }, 45000); + + it('detects parent death (ppid poll) and reaps its downstream child', async () => { + const ws = setupWorkspace(); + homes.push(ws.home); + const binPidFile = join(ws.home, 'binary.pid'); + + // Launch the binary under an intermediate `sh` whose stdin is fed by a + // long-lived `sleep`. When we kill ONLY the sh (not its group), the binary + // is reparented to PID 1 but its stdin stays OPEN (sleep holds the write + // end) — so the stdin-watcher cannot fire and the parent-watcher poll is the + // only thing that can trigger shutdown. + const script = `sleep 30 | "${BINARY}" & echo $! > "${binPidFile}"; wait`; + const launcher = spawn('sh', ['-c', script], { + cwd: ws.home, + env: ws.env, + stdio: ['ignore', 'ignore', 'ignore'], + detached: true, // own process group, so we can kill just `sh` and sweep the group later + }); + spawned.push(launcher); + + const childPid = await readPidWhenReady(ws.fakePidFile, 25000); + const binPid = await readPidWhenReady(binPidFile, 5000); + expect(isAlive(childPid)).toBe(true); + expect(isAlive(binPid)).toBe(true); + await delay(500); + + // Kill ONLY the launcher shell (positive PID). The binary + sleep reparent + // to init; the binary keeps running until its parent-watcher poll notices. + try { process.kill(launcher.pid as number, 'SIGKILL'); } catch { /* gone */ } + + const binGone = await waitFor(() => !isAlive(binPid), 12000); + const childGone = await waitFor(() => !isAlive(childPid), CHILD_SHUTDOWN_MS + 4000); + + expect(binGone, `binary ${binPid} did not shut down after its parent died`).toBe(true); + expect(childGone, `downstream child ${childPid} was not reaped`).toBe(true); + }, 45000); +}); diff --git a/tests/parent-watcher.test.ts b/tests/parent-watcher.test.ts new file mode 100644 index 0000000..b10f539 --- /dev/null +++ b/tests/parent-watcher.test.ts @@ -0,0 +1,141 @@ +/** + * Tests for the active parent-liveness watcher. + * + * stdin EOF (see stdin-watcher.ts) is the primary host-disconnect signal, but it + * can fail to fire — the host is SIGKILLed, or a wrapper / an inherited fd holds + * the write end of our stdin pipe open. Without a second signal the server (and + * the downstream MCP children it spawned, e.g. basic-memory) orphans forever. + * + * watchParentExit() polls process.ppid: on POSIX, when the parent dies the child + * is reparented to init/launchd (PID 1), so ppid changing away from its startup + * value is a reliable "parent is gone" signal. This converts that into a single + * shutdown trigger. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { watchParentExit } from '../src/mcp/parent-watcher.js'; + +describe('watchParentExit', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it('should_invokeOnParentExitOnce_when_reparentedToInit', () => { + let ppid = 4242; + const onParentExit = vi.fn(); + + watchParentExit({ + getPpid: () => ppid, + initialPpid: 4242, + intervalMs: 1000, + isPosix: true, + onParentExit, + }); + + vi.advanceTimersByTime(1000); + expect(onParentExit).not.toHaveBeenCalled(); + + // Parent dies → reparented to PID 1 + ppid = 1; + vi.advanceTimersByTime(1000); + + expect(onParentExit).toHaveBeenCalledTimes(1); + expect(onParentExit).toHaveBeenCalledWith('reparented'); + }); + + it('should_invokeOnParentExitAtMostOnce_when_polledRepeatedlyAfterReparent', () => { + let ppid = 5000; + const onParentExit = vi.fn(); + + watchParentExit({ + getPpid: () => ppid, + initialPpid: 5000, + intervalMs: 500, + isPosix: true, + onParentExit, + }); + + ppid = 1; + vi.advanceTimersByTime(500 * 5); // five more polls after reparent + + expect(onParentExit).toHaveBeenCalledTimes(1); + }); + + it('should_notInvokeOnParentExit_when_ppidStaysAtInitial', () => { + const onParentExit = vi.fn(); + + watchParentExit({ + getPpid: () => 7777, + initialPpid: 7777, + intervalMs: 1000, + isPosix: true, + onParentExit, + }); + + vi.advanceTimersByTime(1000 * 10); + + expect(onParentExit).not.toHaveBeenCalled(); + }); + + it('should_beNoOp_when_notPosix', () => { + let ppid = 1234; + const onParentExit = vi.fn(); + + watchParentExit({ + getPpid: () => ppid, + initialPpid: 1234, + intervalMs: 1000, + isPosix: false, // Windows: ppid reparent semantics differ — rely on stdin EOF + onParentExit, + }); + + ppid = 1; + vi.advanceTimersByTime(1000 * 10); + + expect(onParentExit).not.toHaveBeenCalled(); + }); + + it('should_beDisabled_when_initialPpidIsInitOrLess', () => { + // Launched directly by init/launchd: ppid is already 1, so "ppid === 1" + // is not a death signal. Avoid the false positive entirely. + let ppid = 1; + const onParentExit = vi.fn(); + + watchParentExit({ + getPpid: () => ppid, + initialPpid: 1, + intervalMs: 1000, + isPosix: true, + onParentExit, + }); + + ppid = 1; + vi.advanceTimersByTime(1000 * 10); + + expect(onParentExit).not.toHaveBeenCalled(); + }); + + it('should_stopPolling_when_stopCalled', () => { + let ppid = 9000; + const onParentExit = vi.fn(); + + const stop = watchParentExit({ + getPpid: () => ppid, + initialPpid: 9000, + intervalMs: 1000, + isPosix: true, + onParentExit, + }); + + stop(); + ppid = 1; + vi.advanceTimersByTime(1000 * 10); + + expect(onParentExit).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/process-killer.test.ts b/tests/process-killer.test.ts new file mode 100644 index 0000000..59f0a91 --- /dev/null +++ b/tests/process-killer.test.ts @@ -0,0 +1,84 @@ +/** + * Tests for graceful child-process termination. + * + * On shutdown the client pool must stop the downstream MCP servers it spawned + * (e.g. basic-memory). The current code does a flat 2s sleep then a single + * existence check; killProcessGracefully() replaces that with SIGTERM → + * poll-for-exit → SIGKILL-on-timeout, so a well-behaved child that exits quickly + * is not delayed, while a wedged child is force-killed once the bounded grace + * window elapses. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { killProcessGracefully } from '../src/mcp/process-killer.js'; + +function esrch(): NodeJS.ErrnoException { + const err = new Error('kill ESRCH') as NodeJS.ErrnoException; + err.code = 'ESRCH'; + return err; +} + +describe('killProcessGracefully', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it('should_sendSIGTERMFirst_when_invoked', async () => { + // Child never dies → we will eventually SIGKILL, but SIGTERM must come first. + const kill = vi.fn(); // all signals succeed (child stays alive) + + const p = killProcessGracefully(123, { kill, timeoutMs: 1000, pollIntervalMs: 250 }); + await vi.advanceTimersByTimeAsync(1000); + await p; + + expect(kill.mock.calls[0]).toEqual([123, 'SIGTERM']); + }); + + it('should_notSendSIGKILL_when_childExitsBeforeTimeout', async () => { + let aliveProbes = 0; + const kill = vi.fn((_pid: number, signal: NodeJS.Signals | number) => { + if (signal === 0) { + aliveProbes++; + if (aliveProbes >= 2) throw esrch(); // gone on the 2nd existence probe + return; // still alive on the 1st probe + } + // SIGTERM succeeds + }); + + const p = killProcessGracefully(123, { kill, timeoutMs: 30_000, pollIntervalMs: 250 }); + await vi.advanceTimersByTimeAsync(500); // two poll intervals + const result = await p; + + expect(result).toBe('exited'); + expect(kill).not.toHaveBeenCalledWith(123, 'SIGKILL'); + }); + + it('should_sendSIGKILL_when_childStillAlivePastTimeout', async () => { + const kill = vi.fn(); // existence probe never throws → child always "alive" + + const p = killProcessGracefully(123, { kill, timeoutMs: 1000, pollIntervalMs: 250 }); + await vi.advanceTimersByTimeAsync(1000); + const result = await p; + + expect(result).toBe('killed'); + expect(kill).toHaveBeenCalledWith(123, 'SIGKILL'); + }); + + it('should_returnGone_when_initialSIGTERMThrowsESRCH', async () => { + const kill = vi.fn((_pid: number, _signal: NodeJS.Signals | number) => { + throw esrch(); // process already dead + }); + + const p = killProcessGracefully(123, { kill, timeoutMs: 1000, pollIntervalMs: 250 }); + const result = await p; + + expect(result).toBe('gone'); + expect(kill).toHaveBeenCalledTimes(1); // only the SIGTERM attempt + expect(kill).not.toHaveBeenCalledWith(123, 'SIGKILL'); + }); +}); diff --git a/tests/shutdown-config.test.ts b/tests/shutdown-config.test.ts new file mode 100644 index 0000000..547cbe6 --- /dev/null +++ b/tests/shutdown-config.test.ts @@ -0,0 +1,124 @@ +/** + * Lifecycle / shutdown timeout configuration tests. + * + * Covers the three operational knobs that govern graceful self-shutdown and + * downstream child cleanup: + * - CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS (SIGTERM→SIGKILL grace per child) + * - CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS (parent-liveness poll cadence) + * - CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS (per-client close() timeout) + * + * Unlike getCharacterLimit()/getPoolConfig(), these getters are read on the + * SHUTDOWN path, where throwing would abort the very cleanup they configure. + * They therefore CLAMP out-of-range values and FALL BACK to the default on a + * non-numeric value rather than throwing. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { + getChildShutdownTimeoutMs, + getParentPollIntervalMs, + getClientCloseTimeoutMs, + DEFAULT_CHILD_SHUTDOWN_TIMEOUT_MS, + DEFAULT_PARENT_POLL_INTERVAL_MS, + DEFAULT_CLIENT_CLOSE_TIMEOUT_MS, +} from '../src/config/loader.js'; + +describe('Lifecycle shutdown configuration', () => { + const originalEnv = { ...process.env }; + + beforeEach(() => { + delete process.env.CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS; + delete process.env.CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS; + delete process.env.CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS; + }); + + afterEach(() => { + process.env = { ...originalEnv }; + }); + + describe('getChildShutdownTimeoutMs (default 30s, 1s..5min)', () => { + it('should_returnDefault_when_envUnset', () => { + expect(getChildShutdownTimeoutMs()).toBe(DEFAULT_CHILD_SHUTDOWN_TIMEOUT_MS); + expect(DEFAULT_CHILD_SHUTDOWN_TIMEOUT_MS).toBe(30_000); + }); + + it('should_useEnvValue_when_validAndInRange', () => { + process.env.CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS = '120000'; + expect(getChildShutdownTimeoutMs()).toBe(120_000); + }); + + it('should_acceptFiveMinuteCeiling_when_atUpperBound', () => { + process.env.CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS = '300000'; + expect(getChildShutdownTimeoutMs()).toBe(300_000); + }); + + it('should_clampToMin_when_belowLowerBound', () => { + process.env.CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS = '10'; + expect(getChildShutdownTimeoutMs()).toBe(1_000); + }); + + it('should_clampToMax_when_aboveUpperBound', () => { + process.env.CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS = '999999999'; + expect(getChildShutdownTimeoutMs()).toBe(300_000); + }); + + it('should_fallBackToDefault_when_nonNumeric', () => { + process.env.CODE_EXECUTOR_CHILD_SHUTDOWN_TIMEOUT_MS = 'not-a-number'; + expect(getChildShutdownTimeoutMs()).toBe(DEFAULT_CHILD_SHUTDOWN_TIMEOUT_MS); + }); + }); + + describe('getParentPollIntervalMs (default 2s, 0.5s..60s)', () => { + it('should_returnDefault_when_envUnset', () => { + expect(getParentPollIntervalMs()).toBe(DEFAULT_PARENT_POLL_INTERVAL_MS); + expect(DEFAULT_PARENT_POLL_INTERVAL_MS).toBe(2_000); + }); + + it('should_useEnvValue_when_validAndInRange', () => { + process.env.CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS = '5000'; + expect(getParentPollIntervalMs()).toBe(5_000); + }); + + it('should_clampToMin_when_belowLowerBound', () => { + process.env.CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS = '50'; + expect(getParentPollIntervalMs()).toBe(500); + }); + + it('should_clampToMax_when_aboveUpperBound', () => { + process.env.CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS = '120000'; + expect(getParentPollIntervalMs()).toBe(60_000); + }); + + it('should_fallBackToDefault_when_nonNumeric', () => { + process.env.CODE_EXECUTOR_PARENT_POLL_INTERVAL_MS = 'xyz'; + expect(getParentPollIntervalMs()).toBe(DEFAULT_PARENT_POLL_INTERVAL_MS); + }); + }); + + describe('getClientCloseTimeoutMs (default 2s, 0.25s..30s)', () => { + it('should_returnDefault_when_envUnset', () => { + expect(getClientCloseTimeoutMs()).toBe(DEFAULT_CLIENT_CLOSE_TIMEOUT_MS); + expect(DEFAULT_CLIENT_CLOSE_TIMEOUT_MS).toBe(2_000); + }); + + it('should_useEnvValue_when_validAndInRange', () => { + process.env.CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS = '5000'; + expect(getClientCloseTimeoutMs()).toBe(5_000); + }); + + it('should_clampToMin_when_belowLowerBound', () => { + process.env.CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS = '10'; + expect(getClientCloseTimeoutMs()).toBe(250); + }); + + it('should_clampToMax_when_aboveUpperBound', () => { + process.env.CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS = '99999'; + expect(getClientCloseTimeoutMs()).toBe(30_000); + }); + + it('should_fallBackToDefault_when_nonNumeric', () => { + process.env.CODE_EXECUTOR_CLIENT_CLOSE_TIMEOUT_MS = ''; + expect(getClientCloseTimeoutMs()).toBe(DEFAULT_CLIENT_CLOSE_TIMEOUT_MS); + }); + }); +});