diff --git a/bin/design-code-proxy.mjs b/bin/design-code-proxy.mjs index 6f06c1b4f1..08005365b0 100755 --- a/bin/design-code-proxy.mjs +++ b/bin/design-code-proxy.mjs @@ -16,6 +16,19 @@ const AMR_UPSTREAM_URL = process.env.AMR_UPSTREAM_URL || 'https://amr-link.open- const httpAgent = new http.Agent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 32 }); const httpsAgent = new https.Agent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 32 }); +// Backend inactivity timeout (#2097): a backend (or the AMR upstream) that +// accepts the request and then goes silent must fail like any other backend +// error so the fallback fires, instead of hanging the client request and +// holding a pooled socket forever. The timeout is socket inactivity, not a +// total deadline: an actively streaming response keeps resetting it, so +// slow-but-alive streams are never killed. Pinned at 60s — generous for a +// slow first byte from a local language-server backend — and overridable +// via DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS (tests pin it short). +const BACKEND_TIMEOUT_MS = (() => { + const raw = Number(process.env.DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS); + return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 60_000; +})(); + const DESIGN_SYSTEM_PROMPT = `You are an elite Code & Systems Design Architect. Your core expertise is in software architecture, clean code design, UI/UX design engineering, design tokens, component abstractions, domain-driven design, and maintainable systems patterns. Provide elegant, production-grade architectures and idiomatic design implementations.`; @@ -230,7 +243,22 @@ const server = http.createServer((req, res) => { upstreamRes.pipe(res); }); + // Socket inactivity bound (#2097): a silent upstream times out into + // the same error path as a refused connection, so the local + // fallback fires instead of the request hanging forever. + clientReq.setTimeout(BACKEND_TIMEOUT_MS, () => { + clientReq.destroy(new Error(`AMR upstream silent for ${BACKEND_TIMEOUT_MS}ms (backend timeout)`)); + }); + + let upstreamSettled = false; clientReq.on('error', err => { + if (upstreamSettled) return; + upstreamSettled = true; + if (res.headersSent) { + console.error(`[design-code-proxy] Upstream error after response started: ${err.message}`); + res.destroy(); + return; + } console.error(`[design-code-proxy] Upstream error: ${err.message}. Falling back to local dispatch.`); dispatchWithFallback(body, res); }); @@ -279,7 +307,28 @@ const dispatchWithFallback = (body, clientRes) => { }); } - const tryTarget = (target, onFail) => { + const tryTarget = (target, onFailRaw) => { + // onFail must fire at most once per target: a timeout destroy surfaces + // as both a request error and (sometimes) a response error, and a + // second onFail would re-enter the fallback chain (#2097). + let failSettled = false; + const onFail = (err) => { + if (failSettled) return; + failSettled = true; + onFailRaw(err); + }; + // A target that has failed is retired: the fallback (or the final 502) + // owns the client response from that moment, and nothing the retired + // target does afterwards — a late response error, a timeout firing on + // a body still being drained — may touch the client response (Codex + // P2 on PR #4204). + const targetRetired = () => failSettled; + // Set when THIS target writes the client head (streaming path). A + // retired target whose head the client is carrying is still the owner + // of that stream: its late errors must tear the stream down, not be + // ignored (PR #4204 Codex P2, second round). Only a retired target + // that never wrote the head has handed the client to the fallback. + let headWrittenByMe = false; const stream = Boolean(body.stream); const payload = JSON.stringify({ ...body, @@ -305,6 +354,7 @@ const dispatchWithFallback = (body, clientRes) => { // pooled socket is released instead of stalling half-open. localRes.on('error', err => { console.warn(`[design-code-proxy] Error reading response from 127.0.0.1:${target.port}: ${err.message}`); + if (targetRetired() && !headWrittenByMe) return; // fallback owns the client response now if (!clientRes.headersSent) onFail(err); else clientRes.destroy(); }); @@ -313,7 +363,13 @@ const dispatchWithFallback = (body, clientRes) => { if (localRes.statusCode === 429 || localRes.statusCode >= 500) { console.warn(`[design-code-proxy] Target 127.0.0.1:${target.port} returned ${localRes.statusCode}`); localRes.resume(); // discard response - return onFail(new Error(`HTTP ${localRes.statusCode}`)); + onFail(new Error(`HTTP ${localRes.statusCode}`)); + // Retire the failed target immediately instead of draining a body + // that may never end: its socket is freed now, and the retired + // guard above keeps any resulting error away from the fallback's + // client response. + localReq.destroy(); + return; } // The head is written up front only for streaming. For a buffered @@ -342,6 +398,7 @@ const dispatchWithFallback = (body, clientRes) => { delete headers['content-length']; } clientRes.writeHead(localRes.statusCode || 200, headers); + headWrittenByMe = true; } }; @@ -399,6 +456,14 @@ const dispatchWithFallback = (body, clientRes) => { onFail(err); }); + // Socket inactivity bound (#2097): a backend that accepts and never + // answers (or stalls mid-response with no bytes flowing) is destroyed + // into the error path above, so onFail fires and the fallback runs. + // Actively streaming responses keep the socket busy and are untouched. + localReq.setTimeout(BACKEND_TIMEOUT_MS, () => { + localReq.destroy(new Error(`backend 127.0.0.1:${target.port} silent for ${BACKEND_TIMEOUT_MS}ms (backend timeout)`)); + }); + localReq.write(payload); localReq.end(); }; diff --git a/bin/design-code-proxy.test.mjs b/bin/design-code-proxy.test.mjs index 02dce6d99a..3e79f7f176 100644 --- a/bin/design-code-proxy.test.mjs +++ b/bin/design-code-proxy.test.mjs @@ -47,6 +47,52 @@ const startStub = (name) => new Promise((resolve) => { req.on('end', () => { stub.calls += 1; stub.remotePorts.push(req.socket.remotePort); + if (stub.mode === 'stall-mid-stream') { + // Send one SSE chunk, then go silent forever (PR #4204 Codex P2, + // second round): the backend timeout must tear the client stream + // down, not leave it open. + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + const chunk = { + id: 'chatcmpl-stub', object: 'chat.completion.chunk', created: 0, model: 'stub-model', + choices: [{ index: 0, delta: { content: `partial from ${name}` }, finish_reason: null }] + }; + res.write(`data: ${JSON.stringify(chunk)}\n\n`); + return; + } + if (stub.mode === 'stall-status') { + // Flush a 429 head and then leave the body open forever (#2097 / + // PR #4204 Codex P2): the proxy falls back at the head, and the + // stalled body must not be able to hurt the fallback afterwards. + res.writeHead(429, { 'Content-Type': 'application/json' }); + res.flushHeaders(); + return; + } + if (stub.mode === 'hang') { + // Accept the request and never respond (#2097): the wedged-backend + // case. The socket is left open; the proxy's backend timeout is + // the only thing that can unstick the client request. + return; + } + if (stub.mode === 'slow-stream') { + // Actively streaming with gaps well under any sane inactivity + // timeout: must NOT be killed by the backend timeout (#2097). + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + const chunk = { + id: 'chatcmpl-stub', object: 'chat.completion.chunk', created: 0, model: 'stub-model', + choices: [{ index: 0, delta: { content: `hello from ${name}` }, finish_reason: null }] + }; + let sent = 0; + const timer = setInterval(() => { + sent += 1; + if (sent <= 3) { + res.write(`data: ${JSON.stringify(chunk)}\n\n`); + } else { + clearInterval(timer); + res.end('data: [DONE]\n\n'); + } + }, 150); + return; + } if (stub.mode === 'error-mid-stream') { // Send a head and a partial body, then destroy the socket: // the proxy's backend response errors mid-stream (#782). @@ -108,7 +154,7 @@ const startStub = (name) => new Promise((resolve) => { }); }); -const startProxy = async () => { +const startProxy = async ({ backendTimeoutMs } = {}) => { const primary = await startStub('primary'); const fallback = await startStub('fallback'); const port = await freePort(); @@ -120,7 +166,8 @@ const startProxy = async () => { ...env, DESIGN_CODE_PROXY_PORT: String(port), ANTIGRAVITY_LS_PROXY_PORT: String(primary.port), - CODEX_PROXY_PORT: String(fallback.port) + CODEX_PROXY_PORT: String(fallback.port), + ...(backendTimeoutMs ? { DESIGN_CODE_PROXY_BACKEND_TIMEOUT_MS: String(backendTimeoutMs) } : {}) }, stdio: ['ignore', 'pipe', 'pipe'] }); @@ -326,3 +373,74 @@ test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies'); await alive.text(); }); + +test('silent primary times out and falls back instead of hanging forever (#2097)', async (t) => { + const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 800 }); + t.after(stop); + primary.mode = 'hang'; + const started = Date.now(); + const res = await post(port); + assert.ok(Date.now() - started < 5000, 'fallback must answer within the client abort window'); + assert.equal(res.status, 200); + const body = JSON.parse(await res.text()); + assert.equal(body.choices[0].message.content, 'hello from fallback'); + assert.equal(primary.calls, 1); + assert.equal(fallback.calls, 1); +}); + +test('both backends silent answer a bounded 502, never an indefinite hang (#2097)', async (t) => { + const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 800 }); + t.after(stop); + primary.mode = 'hang'; + fallback.mode = 'hang'; + const started = Date.now(); + const res = await post(port); + const elapsed = Date.now() - started; + assert.ok(elapsed < 5000, `both-hang must 502 within the client abort window, took ${elapsed}ms`); + assert.equal(res.status, 502); + const body = JSON.parse(await res.text()); + assert.match(body.error.message, /All design code backends failed/); + assert.match(body.error.message, /backend timeout/); +}); + +test('slow but actively streaming primary is not killed by the backend timeout (#2097)', async (t) => { + const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 800 }); + t.after(stop); + primary.mode = 'slow-stream'; + const res = await post(port, { stream: true }); + assert.equal(res.status, 200); + const text = await res.text(); + assert.match(text, /hello from primary/); + assert.match(text, /\[DONE\]/); + assert.equal(primary.calls, 1); + assert.equal(fallback.calls, 0); +}); + +test('a retired primary with a stalled 429 body cannot truncate the fallback stream (#2097, PR #4204 Codex P2)', async (t) => { + const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 400 }); + t.after(stop); + primary.mode = 'stall-status'; + fallback.mode = 'slow-stream'; + const res = await post(port, { stream: true }); + assert.equal(res.status, 200); + const text = await res.text(); + assert.match(text, /hello from fallback/); + assert.match(text, /\[DONE\]/); + assert.equal(primary.calls, 1); + assert.equal(fallback.calls, 1); +}); + +test('a primary that stalls mid-stream has its client stream torn down by the timeout (#2097, PR #4204 Codex P2 round 2)', async (t) => { + const { port, primary, fallback, stop } = await startProxy({ backendTimeoutMs: 400 }); + t.after(stop); + primary.mode = 'stall-mid-stream'; + const res = await post(port, { stream: true }); + assert.equal(res.status, 200); + // The body read must fail (stream torn down) rather than hang: the 5s + // client abort in post() only covers the fetch head, so race the read + // against a 3s bound explicitly. + const read = res.text().then(() => 'completed', () => 'torn-down'); + const bounded = new Promise(r => setTimeout(() => r('hung'), 3000)); + assert.equal(await Promise.race([read, bounded]), 'torn-down'); + assert.equal(fallback.calls, 0); +});