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
123 changes: 102 additions & 21 deletions bin/antigravity-ls-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,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;
Expand Down Expand Up @@ -370,25 +414,45 @@ 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 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}`);
// 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';
const timeoutError = () => new Error(`RPC ${method} timed out after ${timeoutMs}ms`);

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() {
Expand Down Expand Up @@ -824,13 +888,30 @@ 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;

for (let attempt = 0; attempt < 120; attempt++) {
await new Promise(r => setTimeout(r, 250));
const trajectory = await lsManager.callRpc('GetCascadeTrajectorySteps', { cascadeId });
const cascadeDeadline = Date.now() + CASCADE_DEADLINE_MS;

while (completedResponse === null && Date.now() < cascadeDeadline) {
// 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];

Expand All @@ -846,7 +927,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);
Expand Down
177 changes: 177 additions & 0 deletions bin/antigravity-ls-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,183 @@ test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async ()
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 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: [{
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(); }
});
test('preserves UTF-8 split across HTTP request-body chunks (#3186)', async () => {
const content = 'before-😀-after';
const body = Buffer.from(JSON.stringify({
Expand Down