From 3afde72a9b7c400d7ac83ca1c6c90285d6da0bee Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 17:56:02 -0600 Subject: [PATCH 1/2] fix(antigravity-ls-proxy): bound language-server RPCs with timeouts (#2102) --- bin/antigravity-ls-proxy.mjs | 94 +++++++++++++++---- bin/antigravity-ls-proxy.test.mjs | 148 ++++++++++++++++++++++++++++++ 2 files changed, 226 insertions(+), 16 deletions(-) diff --git a/bin/antigravity-ls-proxy.mjs b/bin/antigravity-ls-proxy.mjs index 76f5fed6b8..133e433b1a 100755 --- a/bin/antigravity-ls-proxy.mjs +++ b/bin/antigravity-ls-proxy.mjs @@ -204,6 +204,50 @@ const findLanguageServerBinary = () => { return candidates[0]; }; +// --- RPC timeout policy (#2102) ------------------------------------------- +// callRpc used to fetch the language server with no timeout, so a server +// that passes heartbeat but never answers an RPC hung /v1/models and every +// chat request forever. Every RPC is now bounded, including the +// response-body read (the AbortSignal stays attached until the body is +// consumed). Budgets are method-specific: the model catalog and trajectory +// polls are cheap, cascade start/send queue work server-side, and +// GetModelResponse carries long model generations, so it gets minutes. +// Tests inject short budgets via ANTIGRAVITY_LS_RPC_TIMEOUTS (a JSON object +// mapping method name -> milliseconds) and the cascade deadline via +// ANTIGRAVITY_LS_CASCADE_DEADLINE_MS. +const RPC_TIMEOUTS_MS = { + GetAvailableModels: 3_000, + StartCascade: 30_000, + SendUserCascadeMessage: 30_000, + GetCascadeTrajectorySteps: 5_000, + GetModelResponse: 300_000 +}; +const DEFAULT_RPC_TIMEOUT_MS = 30_000; + +const parseRpcTimeoutOverrides = () => { + try { + const parsed = JSON.parse(process.env.ANTIGRAVITY_LS_RPC_TIMEOUTS || '{}'); + const out = {}; + for (const [k, v] of Object.entries(parsed || {})) { + if (typeof v === 'number' && Number.isFinite(v) && v > 0) out[k] = v; + } + return out; + } catch { + return {}; + } +}; +const RPC_TIMEOUT_OVERRIDES = parseRpcTimeoutOverrides(); +const rpcTimeoutMs = (method) => + RPC_TIMEOUT_OVERRIDES[method] ?? RPC_TIMEOUTS_MS[method] ?? DEFAULT_RPC_TIMEOUT_MS; + +const parsePositiveMs = (raw, fallback) => { + const n = Number(raw); + return Number.isFinite(n) && n > 0 ? n : fallback; +}; +// Cascade polling obeys a strict elapsed-time deadline, not an iteration +// count: slow polls stretched the old 120-attempt loop far past 30s. +const CASCADE_DEADLINE_MS = parsePositiveMs(process.env.ANTIGRAVITY_LS_CASCADE_DEADLINE_MS, 30_000); + class LanguageServerManager { constructor() { this.managedChild = null; @@ -372,22 +416,38 @@ class LanguageServerManager { async callRpc(method, payload) { const { port, token } = await this.ensureActive(); const url = `http://127.0.0.1:${port}/exa.language_server_pb.LanguageServerService/${method}`; + const timeoutMs = rpcTimeoutMs(method); + // One signal for the whole RPC: it bounds the fetch AND the body read. + const signal = AbortSignal.timeout(timeoutMs); + const isTimeout = (err) => err?.name === 'TimeoutError' || err?.name === 'AbortError'; + const timeoutError = () => new Error(`RPC ${method} timed out after ${timeoutMs}ms`); - const res = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'x-codeium-csrf-token': token - }, - body: JSON.stringify(payload) - }); - - if (!res.ok) { - const errText = await res.text(); - throw new Error(`RPC ${method} returned HTTP ${res.status}: ${errText}`); + let res; + try { + res = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-codeium-csrf-token': token + }, + body: JSON.stringify(payload), + signal + }); + } catch (err) { + if (isTimeout(err)) throw timeoutError(); + throw err; } - return await res.json(); + try { + if (!res.ok) { + const errText = await res.text(); + throw new Error(`RPC ${method} returned HTTP ${res.status}: ${errText}`); + } + return await res.json(); + } catch (err) { + if (isTimeout(err)) throw timeoutError(); + throw err; + } } cleanup() { @@ -821,11 +881,13 @@ const server = http.createServer(async (req, res) => { } }); - // Poll for completion + // Poll for completion, bounded by a strict elapsed-time + // deadline (#2102) instead of an iteration count. let completedResponse = null; let usageInfo = null; + const cascadeDeadline = Date.now() + CASCADE_DEADLINE_MS; - for (let attempt = 0; attempt < 120; attempt++) { + while (completedResponse === null && Date.now() < cascadeDeadline) { await new Promise(r => setTimeout(r, 250)); const trajectory = await lsManager.callRpc('GetCascadeTrajectorySteps', { cascadeId }); const steps = trajectory?.steps || []; @@ -843,7 +905,7 @@ const server = http.createServer(async (req, res) => { } if (completedResponse === null) { - throw new Error('Cascade execution timed out after 30 seconds'); + throw new Error(`Cascade execution timed out after ${CASCADE_DEADLINE_MS}ms`); } const inputTokens = parseInt(usageInfo?.inputTokens || '0', 10); diff --git a/bin/antigravity-ls-proxy.test.mjs b/bin/antigravity-ls-proxy.test.mjs index 68d07a27c7..f94a9bfe50 100644 --- a/bin/antigravity-ls-proxy.test.mjs +++ b/bin/antigravity-ls-proxy.test.mjs @@ -251,3 +251,151 @@ test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async () assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies'); await alive.text(); }); + +// --- RPC timeouts (#2102) --------------------------------------------------- +// A language server that passes heartbeat but never answers an RPC used to +// hang /v1/models and every chat request forever: callRpc fetched with no +// timeout. These tests run their own stub + proxy pairs with short injected +// budgets (ANTIGRAVITY_LS_RPC_TIMEOUTS / ANTIGRAVITY_LS_CASCADE_DEADLINE_MS) +// so nothing waits for the production budgets. + +const startTimeoutRig = async ({ hang = [], delayMs = {}, cascadeSteps = [], timeouts = {}, cascadeDeadlineMs = 30_000 } = {}) => { + const hangSet = new Set(hang); + const stub = http.createServer((req, res) => { + let body = ''; + req.on('data', (c) => { body += c; }); + req.on('end', () => { + const method = req.url.split('/').pop(); + if (hangSet.has(method)) return; // heartbeat-ok, RPC never answers + const respond = () => { + if (res.destroyed) return; + res.writeHead(200, { 'Content-Type': 'application/json' }); + if (method === 'GetAvailableModels') res.end(JSON.stringify({ response: { models: {} } })); + else if (method === 'GetModelResponse') res.end(JSON.stringify({ response: 'slow but alive' })); + else if (method === 'StartCascade') res.end(JSON.stringify({ cascadeId: 'cascade-timeout-test' })); + else if (method === 'GetCascadeTrajectorySteps') res.end(JSON.stringify({ steps: cascadeSteps })); + else res.end('{}'); + }; + const d = delayMs[method] || 0; + if (d) setTimeout(respond, d); else respond(); + }); + }); + const lsPort = await freePort(); + await new Promise((resolve) => stub.listen(lsPort, '127.0.0.1', resolve)); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-proxy-timeout-test-')); + const port = await freePort(); + const child = spawn(process.execPath, [path.join(binDir, 'antigravity-ls-proxy.mjs')], { + env: { + ...process.env, + ANTIGRAVITY_LS_PROXY_PORT: String(port), + ANTIGRAVITY_LS_ADDRESS: `127.0.0.1:${stub.address().port}`, + ANTIGRAVITY_CSRF_TOKEN: 'test-token', + ANTIGRAVITY_LS_RPC_TIMEOUTS: JSON.stringify(timeouts), + ANTIGRAVITY_LS_CASCADE_DEADLINE_MS: String(cascadeDeadlineMs), + XDG_STATE_HOME: path.join(tmp, 'state') + }, + stdio: ['ignore', 'pipe', 'pipe'] + }); + let log = ''; + child.stdout.on('data', (d) => { log += d; }); + child.stderr.on('data', (d) => { log += d; }); + const deadline = Date.now() + 10000; + for (;;) { + try { + const res = await fetch(`http://127.0.0.1:${port}/health`); + if (res.ok) break; + } catch {} + if (Date.now() > deadline) throw new Error(`timeout-rig proxy did not start: ${log}`); + await new Promise((r) => setTimeout(r, 100)); + } + return { + port, + close: () => { child.kill('SIGKILL'); stub.close(); } + }; +}; + +test('a hung GetAvailableModels still serves the static catalog, bounded (#2102)', async () => { + const rig = await startTimeoutRig({ hang: ['GetAvailableModels'], timeouts: { GetAvailableModels: 200 } }); + try { + const t0 = Date.now(); + const res = await fetch(`http://127.0.0.1:${rig.port}/v1/models`); + const elapsed = Date.now() - t0; + assert.equal(res.status, 200); + const body = await res.json(); + assert.ok(body.data.some((m) => m.id === 'gemini-3.8-flash'), 'static MODEL_MAP catalog must be served'); + assert.ok(elapsed < 5000, `models took ${elapsed}ms; the catalog RPC must be bounded`); + } finally { rig.close(); } +}); + +test('a hung GetModelResponse returns a clean bounded API error (#2102)', async () => { + const rig = await startTimeoutRig({ hang: ['GetModelResponse'], timeouts: { GetModelResponse: 200 } }); + try { + const t0 = Date.now(); + const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ model: 'gemini-3.8-flash', messages: [{ role: 'user', content: 'hello' }] }) + }); + const elapsed = Date.now() - t0; + assert.notEqual(res.status, 200); + const body = await res.json(); + assert.match(JSON.stringify(body), /GetModelResponse timed out after 200ms/); + assert.ok(elapsed < 5000, `chat took ${elapsed}ms; the RPC must be bounded`); + } finally { rig.close(); } +}); + +test('a slow-but-alive RPC below its budget still succeeds (#2102)', async () => { + const rig = await startTimeoutRig({ delayMs: { GetModelResponse: 100 }, timeouts: { GetModelResponse: 2000 } }); + try { + const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ model: 'gemini-3.8-flash', messages: [{ role: 'user', content: 'hello' }] }) + }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.choices[0].message.content, 'slow but alive'); + } finally { rig.close(); } +}); + +test('cascade polling stops at the elapsed deadline, not an iteration count (#2102)', async () => { + const rig = await startTimeoutRig({ + timeouts: { GetCascadeTrajectorySteps: 1000 }, + cascadeDeadlineMs: 600, + cascadeSteps: [] + }); + try { + const t0 = Date.now(); + const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ model: 'gemini-3.8-flash', mode: 'cascade', messages: [{ role: 'user', content: 'hello' }] }) + }); + const elapsed = Date.now() - t0; + assert.notEqual(res.status, 200); + const body = await res.json(); + assert.match(JSON.stringify(body), /Cascade execution timed out after 600ms/); + assert.ok(elapsed < 5000, `cascade took ${elapsed}ms; the deadline must bound it`); + } finally { rig.close(); } +}); + +test('a healthy cascade still completes (#2102)', async () => { + const rig = await startTimeoutRig({ + cascadeSteps: [{ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { response: 'cascade answer' }, + metadata: {} + }] + }); + try { + const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ model: 'gemini-3.8-flash', mode: 'cascade', messages: [{ role: 'user', content: 'hello' }] }) + }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.choices[0].message.content, 'cascade answer'); + } finally { rig.close(); } +}); From c3adadb0ab988137c1b90eb99cbaaff76fcdf7b6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 3 Nov 2026 05:01:26 -0600 Subject: [PATCH 2/2] fix(antigravity-ls-proxy): bound each cascade poll by the remaining deadline (#2102) Codex P2 on PR #4080: a poll starting near the deadline could sleep a full 250ms, run a full 5s RPC, and have its late response accepted, overrunning the 30s cascade deadline. The sleep and the poll RPC are now capped at the remaining budget (callRpc gains an optional cap that can only shrink the per-method budget), a poll that hits the cap reads as the deadline expiring, and a response landing after the deadline is discarded. Regression test mirrors the Codex repro (100ms deadline, 1000ms trajectory delay): the request now ends at the deadline with the cascade timeout error instead of HTTP 200 after ~1.3s. node --test bin/antigravity-ls-proxy.test.mjs: 20/20 pass on laptop. --- bin/antigravity-ls-proxy.mjs | 27 +++++++++++++++++++++++---- bin/antigravity-ls-proxy.test.mjs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/bin/antigravity-ls-proxy.mjs b/bin/antigravity-ls-proxy.mjs index 69d2de1e31..79c41f7434 100755 --- a/bin/antigravity-ls-proxy.mjs +++ b/bin/antigravity-ls-proxy.mjs @@ -414,10 +414,14 @@ class LanguageServerManager { throw new Error('Timed out waiting for managed Antigravity Language Server to initialize'); } - async callRpc(method, payload) { + async callRpc(method, payload, timeoutCapMs) { const { port, token } = await this.ensureActive(); const url = `http://127.0.0.1:${port}/exa.language_server_pb.LanguageServerService/${method}`; - const timeoutMs = rpcTimeoutMs(method); + // A caller with its own deadline (the cascade poll loop) may cap the + // per-method budget at the time it has left; the cap can only shrink it. + const timeoutMs = timeoutCapMs === undefined + ? rpcTimeoutMs(method) + : Math.min(rpcTimeoutMs(method), Math.max(1, timeoutCapMs)); // One signal for the whole RPC: it bounds the fetch AND the body read. const signal = AbortSignal.timeout(timeoutMs); const isTimeout = (err) => err?.name === 'TimeoutError' || err?.name === 'AbortError'; @@ -891,8 +895,23 @@ const server = http.createServer(async (req, res) => { const cascadeDeadline = Date.now() + CASCADE_DEADLINE_MS; while (completedResponse === null && Date.now() < cascadeDeadline) { - await new Promise(r => setTimeout(r, 250)); - const trajectory = await lsManager.callRpc('GetCascadeTrajectorySteps', { cascadeId }); + // Every step of the poll is bounded by the time left to the + // deadline (Codex review on PR #4080): the sleep is capped, + // the poll RPC is capped, and a response that lands after + // the deadline is not accepted. + await new Promise(r => setTimeout(r, Math.min(250, cascadeDeadline - Date.now()))); + const pollBudgetMs = cascadeDeadline - Date.now(); + if (pollBudgetMs <= 0) break; + let trajectory; + try { + trajectory = await lsManager.callRpc('GetCascadeTrajectorySteps', { cascadeId }, pollBudgetMs); + } catch (err) { + // The poll hit the remaining-budget cap: that is the + // cascade deadline expiring, not an RPC failure. + if (Date.now() >= cascadeDeadline) break; + throw err; + } + if (Date.now() >= cascadeDeadline) break; const steps = trajectory?.steps || []; const lastStep = steps[steps.length - 1]; diff --git a/bin/antigravity-ls-proxy.test.mjs b/bin/antigravity-ls-proxy.test.mjs index 2a0dd0cf89..30e7bf2375 100644 --- a/bin/antigravity-ls-proxy.test.mjs +++ b/bin/antigravity-ls-proxy.test.mjs @@ -379,6 +379,36 @@ test('cascade polling stops at the elapsed deadline, not an iteration count (#21 } finally { rig.close(); } }); +test('a cascade poll that lands after the deadline is not accepted (#2102)', async () => { + // Codex repro on PR #4080: with a 100ms cascade deadline and a 1000ms + // trajectory delay, the old loop accepted the late completion and + // answered 200 after ~1.3s. The poll must be bounded by the remaining + // deadline budget and the late response discarded. + const rig = await startTimeoutRig({ + cascadeDeadlineMs: 100, + delayMs: { GetCascadeTrajectorySteps: 1000 }, + cascadeSteps: [{ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { response: 'late answer' }, + metadata: {} + }] + }); + try { + const t0 = Date.now(); + const res = await fetch(`http://127.0.0.1:${rig.port}/v1/chat/completions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ model: 'gemini-3.8-flash', mode: 'cascade', messages: [{ role: 'user', content: 'hello' }] }) + }); + const elapsed = Date.now() - t0; + assert.notEqual(res.status, 200); + const body = await res.json(); + assert.match(JSON.stringify(body), /Cascade execution timed out after 100ms/); + assert.ok(elapsed < 800, `cascade took ${elapsed}ms; a late poll must not stretch past the deadline`); + } finally { rig.close(); } +}); + test('a healthy cascade still completes (#2102)', async () => { const rig = await startTimeoutRig({ cascadeSteps: [{