diff --git a/bin/muse-proxy.mjs b/bin/muse-proxy.mjs index f87a796cf9..c987ef68c0 100644 --- a/bin/muse-proxy.mjs +++ b/bin/muse-proxy.mjs @@ -322,6 +322,42 @@ const WARM_TTL_MS = 2 * 60 * 60 * 1000; const WARM_MAX_SESSIONS = 64; const WARM_TURN_TIMEOUT_MS = 300 * 1000; +// Exec-fallback turn deadline (#2159): the exec path settles a request +// only when its child closes, so without a deadline a hung `muse exec` +// child wedges the request forever and leaks the process. The override +// is a strict positive integer of milliseconds within Node's timer +// range (<= 2^31 - 1; setTimeout clamps larger delays to ~1ms, which +// would time out every turn immediately); anything else warns once +// and falls back to the default — 0/disabled is not expressible. +const EXEC_TURN_TIMEOUT_MS = 300 * 1000; +const EXEC_KILL_GRACE_MS = 3000; +const parseExecTurnTimeoutMs = () => { + const raw = process.env.MUSE_PROXY_EXEC_TURN_TIMEOUT_MS; + if (raw === undefined) return EXEC_TURN_TIMEOUT_MS; + const n = Number(raw); + if (!Number.isInteger(n) || n <= 0 || n > 2147483647) { + console.warn(`[muse-proxy] ignoring invalid MUSE_PROXY_EXEC_TURN_TIMEOUT_MS=${JSON.stringify(raw)}; using ${EXEC_TURN_TIMEOUT_MS}ms`); + return EXEC_TURN_TIMEOUT_MS; + } + return n; +}; +const EXEC_TURN_TIMEOUT_MS_VALUE = parseExecTurnTimeoutMs(); + +// Shared kill escalation for the exec fallback (#2159): SIGTERM, then +// SIGKILL after a grace period. Used by both the turn deadline and the +// client-disconnect handler, and idempotent so the two can race safely. +const killChildWithEscalation = (child) => { + if (!child || child.__killEscalationStarted) return; + if (child.exitCode !== null || child.signalCode !== null) return; + child.__killEscalationStarted = true; + try { child.kill('SIGTERM'); } catch (_) {} + const grace = setTimeout(() => { + try { child.kill('SIGKILL'); } catch (_) {} + }, EXEC_KILL_GRACE_MS); + grace.unref?.(); + child.once('close', () => clearTimeout(grace)); +}; + // MSP command ids must be UUIDv7 (the host rejects v4: "expected UUIDv7"). let uuidV7LastMs = -1; let uuidV7Seq = 0; @@ -1691,9 +1727,35 @@ const server = http.createServer((req, res) => { return; } + // Turn deadline (#2159): from spawn, exec fallback only. The kill + // normally produces the child's close event, and the close handler + // below settles the request through the existing error shape. But + // 'close' waits for the child's stdio pipes to drain, and a + // descendant that inherited those pipes can hold them open + // indefinitely after the child itself is dead — so the deadline + // also arms an independent settle at deadline + kill grace that + // bounds settlement and prompt-file cleanup whether or not + // 'close' ever fires (Codex review on PR #4242). + let timedOut = false; + let settleTimer = null; + const deadlineTimer = setTimeout(() => { + timedOut = true; + killChildWithEscalation(child); + // The +1s past the grace lets the normal SIGKILL path settle + // through 'close' first; only a 'close' that never comes (the + // descendant-pipe case) actually reaches this timer. + settleTimer = setTimeout(() => { + try { child.stdout?.destroy(); } catch (_) {} + try { child.stderr?.destroy(); } catch (_) {} + settleRequest(null, null); + }, EXEC_KILL_GRACE_MS + 1000); + settleTimer.unref?.(); + }, EXEC_TURN_TIMEOUT_MS_VALUE); + deadlineTimer.unref?.(); + res.on('close', () => { if (!res.writableEnded) { - try { child.kill('SIGTERM'); } catch (_) {} + killChildWithEscalation(child); } }); @@ -1782,13 +1844,50 @@ const server = http.createServer((req, res) => { } }); - child.on('close', (code, signal) => { + const emitFailure = (detail) => { + const errorBody = { error: { message: `Muse execution failed: ${detail}` } }; + if (stream) { + // The 200 + text/event-stream headers are already on the wire, + // so a bare JSON body would be invisible to an SSE client + // parsing `data:` lines — it would see an empty, successful + // stream (#670). Frame the error as an SSE event and close + // the stream with [DONE] instead. + if (!res.writableEnded) { + res.write(`data: ${JSON.stringify(errorBody)}\n\n`); + res.write('data: [DONE]\n\n'); + } + res.end(); + return; + } + if (!res.headersSent) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + } + res.end(JSON.stringify(errorBody)); + }; + + let settled = false; + const settleRequest = (code, signal) => { + if (settled) return; + settled = true; + clearTimeout(deadlineTimer); + if (settleTimer) clearTimeout(settleTimer); if (lineBuffer.trim().length > 0) { processJsonLine(lineBuffer); lineBuffer = ''; } try { fs.unlinkSync(promptFile); } catch (_) {} + // Deadline check FIRST (#2159): a turn killed for exceeding the + // deadline is a timeout failure even if the child had already + // emitted a completed terminal event — never a silent + // successful stop — and the #484 reconciliation is skipped. + if (timedOut) { + if (!res.writableEnded) { + emitFailure(`muse exec turn timed out after ${EXEC_TURN_TIMEOUT_MS_VALUE}ms`); + } + return; + } + if (res.writableEnded) return; // Reconcile the streamed deltas with the terminal event's @@ -1828,24 +1927,7 @@ const server = http.createServer((req, res) => { ? `muse exec terminated by signal ${signal}` : `muse exec exited with code ${code}`; const detail = (stderrLine || fallback).trim(); - const errorBody = { error: { message: `Muse execution failed: ${detail}` } }; - if (stream) { - // The 200 + text/event-stream headers are already on the wire, - // so a bare JSON body would be invisible to an SSE client - // parsing `data:` lines — it would see an empty, successful - // stream (#670). Frame the error as an SSE event and close - // the stream with [DONE] instead. - if (!res.writableEnded) { - res.write(`data: ${JSON.stringify(errorBody)}\n\n`); - res.write('data: [DONE]\n\n'); - } - res.end(); - return; - } - if (!res.headersSent) { - res.writeHead(500, { 'Content-Type': 'application/json' }); - } - res.end(JSON.stringify(errorBody)); + emitFailure(detail); return; } @@ -1909,9 +1991,15 @@ const server = http.createServer((req, res) => { } }, null, 2)); } - }); + }; + + child.on('close', settleRequest); child.on('error', err => { + if (settled) return; + settled = true; + clearTimeout(deadlineTimer); + if (settleTimer) clearTimeout(settleTimer); console.error(`[muse-proxy child error] ${err.message}`); try { fs.unlinkSync(promptFile); } catch (_) {} if (!res.headersSent) { diff --git a/bin/muse-proxy.test.mjs b/bin/muse-proxy.test.mjs index 56c818a30f..2ee3fd88d8 100644 --- a/bin/muse-proxy.test.mjs +++ b/bin/muse-proxy.test.mjs @@ -99,6 +99,24 @@ if (args[0] === 'serve') { let prompt = ''; try { prompt = fs.readFileSync(promptFile, 'utf-8'); } catch {} const line = (o) => console.log(JSON.stringify(o)); + if (process.env.STUB_LOG) fs.appendFileSync(process.env.STUB_LOG, 'EXECPID ' + process.pid + String.fromCharCode(10)); + if (prompt.includes('HANGAFTERDONE')) { + line({ payload_type: 'run.output.delta', payload: { text: 'Hel' } }); + line({ payload_type: 'run.terminal.completed', payload: { terminal: 'completed', text: 'Hello world' } }); + setInterval(() => {}, 1000); + return; + } + if (prompt.includes('HANGTERMI')) { process.on('SIGTERM', () => {}); setInterval(() => {}, 1000); return; } + if (prompt.includes('HANGME')) { setInterval(() => {}, 1000); return; } + if (prompt.includes('HANGDESCENDANT')) { + // A descendant that inherits our stdout/stderr and outlives us: the + // proxy's child 'close' event waits on those pipes, so killing this + // process alone never settles the request (Codex P2 on PR #4242). + const descendant = require('child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'inherit' }); + if (process.env.STUB_LOG) fs.appendFileSync(process.env.STUB_LOG, 'DESCPID ' + descendant.pid + String.fromCharCode(10)); + setInterval(() => {}, 1000); + return; + } if (prompt.includes('FAILME')) { console.error('stub muse: auth expired'); process.exit(3); } if (prompt.includes('FAILPARTIAL')) { line({ payload_type: 'run.output.delta', payload: { text: 'partial answer' } }); @@ -1000,3 +1018,139 @@ test('warm chain map self-deletes settled entries; same-key turns stay ordered ( assert.deepEqual(turns.slice(-2), ['order one', 'order two'], 'same-key turns must run in enqueue order'); await waitChainsEmpty(); }); + +// --------------------------------------------------------------------------- +// Exec-fallback turn deadline (#2159): a hung muse exec child must be +// killed (SIGTERM, then SIGKILL after the grace), the request must +// settle with the existing error shape, and the timeout must never be +// reported as a silent successful stop. +// --------------------------------------------------------------------------- + +const postChat = (port, body, signal) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + signal +}); + +const waitForCondition = async (fn, timeoutMs = 10000) => { + const deadline = Date.now() + timeoutMs; + for (;;) { + const v = fn(); + if (v) return v; + if (Date.now() > deadline) throw new Error('waitForCondition timed out'); + await new Promise(r => setTimeout(r, 50)); + } +}; + +const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } }; + +const stubExecPid = (logFile) => { + try { + const m = fs.readFileSync(logFile, 'utf-8').match(/EXECPID (\d+)/); + return m ? Number(m[1]) : null; + } catch { return null; } +}; + +const stubPromptFile = (logFile) => { + const m = fs.readFileSync(logFile, 'utf-8').match(/--prompt-file (\S+)/); + return m ? m[1] : null; +}; + +test('exec deadline: never-exiting child is killed, request 500s with the timeout, prompt file removed (#2159)', async (t) => { + const { port, stop, logFile } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); + t.after(stop); + const res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGME now' }] }); + assert.equal(res.status, 500); + const body = JSON.parse(await res.text()); + assert.match(body.error.message, /muse exec turn timed out after 300ms/); + const pid = stubExecPid(logFile); + assert.ok(pid, 'stub exec pid recorded'); + await waitForCondition(() => !pidAlive(pid)); + const promptFile = stubPromptFile(logFile); + assert.ok(promptFile, 'prompt file path recorded in stub argv log'); + assert.equal(fs.existsSync(promptFile), false, 'prompt file must be unlinked on the deadline path'); +}); + +test('exec deadline: request settles at deadline+grace even when a descendant holds the stdio pipes (#2159)', async (t) => { + const { port, stop, logFile } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); + t.after(stop); + const started = Date.now(); + let res = null; + try { + res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGDESCENDANT now' }] }, AbortSignal.timeout(20000)); + } catch { /* aborted: settlement was not bounded */ } + assert.ok(res, 'request must settle at deadline + kill grace, not when the descendant exits'); + assert.equal(res.status, 500); + const body = JSON.parse(await res.text()); + assert.match(body.error.message, /muse exec turn timed out after 300ms/); + assert.ok(Date.now() - started < 15000, 'settlement must be bounded independently of the descendant lifetime'); + const pid = stubExecPid(logFile); + assert.ok(pid, 'stub exec pid recorded'); + await waitForCondition(() => !pidAlive(pid)); + const promptFile = stubPromptFile(logFile); + assert.ok(promptFile, 'prompt file path recorded in stub argv log'); + assert.equal(fs.existsSync(promptFile), false, 'prompt file must be unlinked on the independent settle path'); + const dm = fs.readFileSync(logFile, 'utf-8').match(/DESCPID (\d+)/); + assert.ok(dm, 'descendant pid recorded'); + try { process.kill(Number(dm[1]), 'SIGKILL'); } catch { /* already gone */ } +}); + +test('exec deadline: streaming request gets an SSE-framed timeout error + [DONE] (#2159)', async (t) => { + const { port, stop } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); + t.after(stop); + const res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGME now' }], stream: true }); + assert.equal(res.status, 200); + const sse = await res.text(); + assert.match(sse, /muse exec turn timed out after 300ms/); + assert.ok(sse.trimEnd().endsWith('data: [DONE]'), `stream must end with [DONE], got: ${JSON.stringify(sse)}`); +}); + +test('exec deadline: SIGTERM-ignoring child is SIGKILLed after the grace (#2159)', async (t) => { + const { port, stop, logFile } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); + t.after(stop); + const started = Date.now(); + const res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGTERMI now' }] }); + assert.equal(res.status, 500); + const body = JSON.parse(await res.text()); + assert.match(body.error.message, /muse exec turn timed out after 300ms/); + assert.ok(Date.now() - started >= 3000, 'SIGKILL escalation must wait the 3000ms grace'); + const pid = stubExecPid(logFile); + assert.ok(pid && !pidAlive(pid), 'SIGTERM-ignoring child must be dead after the grace'); +}); + +test('exec deadline: completed-then-hangs child is a timeout failure, not a stop (#2159)', async (t) => { + const { port, stop } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '300' }); + t.after(stop); + const res = await postChat(port, { messages: [{ role: 'user', content: 'please HANGAFTERDONE now' }] }); + assert.equal(res.status, 500, 'a completed terminal event must not mask the deadline'); + const body = JSON.parse(await res.text()); + assert.match(body.error.message, /muse exec turn timed out after 300ms/); +}); + +test('exec deadline: a normal child inside the deadline is unaffected (#2159)', async (t) => { + const { port, stop } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '5000' }); + t.after(stop); + const plain = JSON.parse(await chat(port, { messages: [{ role: 'user', content: 'hi' }] })); + assert.equal(plain.choices[0].message.content, 'Hello world'); +}); + +test('exec deadline: an override above Node timer limit falls back to the default, not a ~1ms timeout (#2159)', async (t) => { + const { port, stop } = await startProxy({ MUSE_PROXY_EXEC_TURN_TIMEOUT_MS: '2147483648' }); + t.after(stop); + const plain = JSON.parse(await chat(port, { messages: [{ role: 'user', content: 'hi' }] })); + assert.equal(plain.choices[0].message.content, 'Hello world'); +}); + +test('exec disconnect: client disconnect kills the child via the shared helper (#2159)', async (t) => { + const { port, stop, logFile } = await startProxy(); + t.after(stop); + const ac = new AbortController(); + const pending = postChat(port, { messages: [{ role: 'user', content: 'please HANGME now' }] }, ac.signal) + .catch(() => null); + const pid = await waitForCondition(() => stubExecPid(logFile)); + assert.ok(pidAlive(pid), 'child runs while the request is open'); + ac.abort(); + await pending; + await waitForCondition(() => !pidAlive(pid)); +});