From 6cd1bd72f7d4e86112dd58d58fabfe949514ec8a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 08:33:19 -0500 Subject: [PATCH] fix(muse-proxy): fail fast while the subscription quota is exhausted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a turn reported the subscription quota exhausted, every later request still paid a full CLI turn to hear the same 429 — and a warm failure fell back to exec, paying a second spawn for the same answer. The proxy now learns the reset from the provider's own error (from either path) and answers requests itself until it passes; a warm quota failure no longer falls back to exec. Tests: both paths pinned; the harness now also plants the stub at $HOME/.local/bin/muse, where the proxy resolves the CLI first, so the suite cannot silently run a real system muse on NixOS machines. --- bin/muse-proxy.mjs | 69 ++++++++++++++++++++++++++++++++++++++++- bin/muse-proxy.test.mjs | 58 ++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 1 deletion(-) diff --git a/bin/muse-proxy.mjs b/bin/muse-proxy.mjs index 0c911baa91..0d8bd6beab 100644 --- a/bin/muse-proxy.mjs +++ b/bin/muse-proxy.mjs @@ -652,6 +652,55 @@ const warmHost = { } }; +// Quota state learned from the provider's own errors. When a turn reports +// the subscription quota exhausted, the error names the reset; until then +// every further attempt — warm or exec — is guaranteed to fail the same +// way, and each costs a full CLI turn (seconds, plus a CLI spawn on the +// exec path). Requests in the window fail fast with the provider's own +// message instead, a quota failure on the warm path no longer falls back +// to exec, and the state clears on its own at the stated reset. +let quotaExhaustedUntil = 0; +let quotaExhaustedMessage = ''; +const QUOTA_FALLBACK_HOLD_MS = 60_000; +const QUOTA_MAX_HOLD_MS = 6 * 3_600_000; +const noteQuotaError = (message) => { + if (typeof message !== 'string' || !/quota exhausted/i.test(message)) return false; + const reset = /resets at ([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z)/.exec(message); + const parsed = reset ? Date.parse(reset[1]) : NaN; + const until = Number.isNaN(parsed) + ? Date.now() + QUOTA_FALLBACK_HOLD_MS + : Math.min(parsed, Date.now() + QUOTA_MAX_HOLD_MS); + if (until > quotaExhaustedUntil) { + quotaExhaustedUntil = until; + quotaExhaustedMessage = message; + } + return true; +}; +const quotaBlocked = () => Date.now() < quotaExhaustedUntil; +// The failure shape the exec path already produces (#670): a bare 500 for +// non-stream clients, an SSE error frame for stream clients. +const sendQuotaError = (res, stream) => { + const errorBody = { error: { message: `Muse execution failed: ${quotaExhaustedMessage || 'Subscription quota exhausted'}` } }; + if (stream) { + if (!res.headersSent) { + res.writeHead(200, { + 'Content-Type': 'text/event-stream; charset=utf-8', + 'Cache-Control': 'no-cache, no-transform', + 'Connection': 'keep-alive', + 'X-Accel-Buffering': 'no' + }); + } + 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)); +}; + // Per-conversation serialization: turns on one session must not interleave, // and the delta decision must be made against the latest committed state. const warmChains = new Map(); @@ -762,7 +811,16 @@ const tryWarmChat = async ({ messages, baseModel, effort, fullName, stream, res, try { result = await enqueueWarm(key, job); } catch (err) { - console.warn(`[muse-proxy warm] warm path failed (${err.message}); ${headed ? 'stream already committed, terminating in place' : 'falling back to exec'}`); + const quota = noteQuotaError(err.message); + console.warn(`[muse-proxy warm] warm path failed (${err.message}); ${headed ? 'stream already committed, terminating in place' : quota ? 'quota exhausted, not falling back to exec' : 'falling back to exec'}`); + if (!headed && quota) { + // A quota failure is one the exec path cannot fix — it would pay a + // full CLI spawn to be told the same thing. Answer with the + // provider's error now; quotaBlocked() fails later requests fast + // until the stated reset. + sendQuotaError(res, stream); + return true; + } if (!headed) return false; if (!res.writableEnded) { res.write(`data: ${JSON.stringify({ error: { message: `Muse execution failed: ${err.message}` } })}\n\n`); @@ -941,6 +999,14 @@ const server = http.createServer((req, res) => { return; } + // Fail fast while a learned quota exhaustion is in force (see + // noteQuotaError): no warm turn, no CLI spawn — the provider's own + // stated reset governs when normal service resumes. + if (quotaBlocked()) { + sendQuotaError(res, stream); + return; + } + const chatId = `chatcmpl-muse-${crypto.randomUUID()}`; const created = Math.floor(Date.now() / 1000); @@ -1133,6 +1199,7 @@ const server = http.createServer((req, res) => { ? `muse exec terminated by signal ${signal}` : `muse exec exited with code ${code}`; const detail = (stderrLine || fallback).trim(); + noteQuotaError(detail); const errorBody = { error: { message: `Muse execution failed: ${detail}` } }; if (stream) { // The 200 + text/event-stream headers are already on the wire, diff --git a/bin/muse-proxy.test.mjs b/bin/muse-proxy.test.mjs index ded50732ca..3332b9db58 100644 --- a/bin/muse-proxy.test.mjs +++ b/bin/muse-proxy.test.mjs @@ -80,6 +80,10 @@ if (args[0] === 'serve') { const sid = msg.params.sessionId; const turnId = msg.params.commandId; reply({ commandId: msg.params.commandId, turnId, disposition: 'started', startedNewTurn: true, status: 'accepted' }); + if (text.includes('QUOTAWARM')) { + notify('turn/completed', { sessionId: sid, turnId, terminal: 'failed', reason: 'API error 429 [request_id=stub]: Subscription quota exhausted. Your usage window resets at 2999-01-01T00:00:00Z. (rate_limit_error)' }); + return; + } notify('item/started', { sessionId: sid, item: { itemId: 'a1', kind: 'agentMessage' } }); notify('item/delta', { sessionId: sid, itemId: 'a1', delta: 'RE:' + text }); notify('item/completed', { sessionId: sid, item: { itemId: 'a1', kind: 'agentMessage', messagePhase: 'finalAnswer', text: 'RE:' + text } }); @@ -97,6 +101,7 @@ if (args[0] === 'serve') { try { prompt = fs.readFileSync(promptFile, 'utf-8'); } catch {} const line = (o) => console.log(JSON.stringify(o)); if (prompt.includes('FAILME')) { console.error('stub muse: auth expired'); process.exit(3); } + if (prompt.includes('QUOTAME')) { console.error('run ended with Failed: API error 429 [request_id=stub]: Subscription quota exhausted. Your usage window resets at 2999-01-01T00:00:00Z. (rate_limit_error)'); process.exit(3); } if (prompt.includes('FAILPARTIAL')) { line({ payload_type: 'run.output.delta', payload: { text: 'partial answer' } }); line({ payload_type: 'run.terminal.failed', payload: { terminal: 'failed', text: 'partial answer' } }); @@ -138,6 +143,12 @@ const startProxy = async (extraEnv = {}) => { fs.mkdirSync(stubDir); fs.mkdirSync(path.join(tmp, 'home')); fs.writeFileSync(path.join(stubDir, 'muse'), STUB, { mode: 0o755 }); + // The proxy resolves the CLI at $HOME/.local/bin/muse before PATH (and + // before the NixOS system path), so the stub must live there too — with + // only the PATH stub, a machine that has a real system muse (a NixOS + // laptop) runs the real CLI in these tests. + fs.mkdirSync(path.join(tmp, 'home', '.local', 'bin'), { recursive: true }); + fs.writeFileSync(path.join(tmp, 'home', '.local', 'bin', 'muse'), STUB, { mode: 0o755 }); const port = await freePort(); const logFile = path.join(tmp, 'stub.log'); const child = spawn(process.execPath, [path.join(binDir, 'muse-proxy.mjs')], { @@ -448,3 +459,50 @@ test('flag probe: 1.4.13-shaped help — warm serve spawn passes --disable-reque assert.equal(serveArgv.length, 1); assert.ok(serveArgv[0].includes('--disable-request-user-input'), 'advertised flag must be passed'); }); + + +// --- Quota exhaustion: fail fast until the provider's stated reset -------- +// A quota-exhausted window used to cost every request a full CLI turn — +// the warm path failed after seconds and then paid a CLI spawn for the +// exec path to be told the same 429. Once any path reports the quota +// exhausted, the proxy answers later requests itself until the reset. +const chatRaw = async (port, body) => { + const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }); + return { status: res.status, text: await res.text() }; +}; + +test('quota exhausted on the exec path: later requests fail fast without a spawn', async (t) => { + const { port, stop, logFile } = await startProxy(); + t.after(stop); + + const first = await chatRaw(port, { messages: [{ role: 'user', content: 'QUOTAME please' }] }); + assert.equal(first.status, 500); + assert.match(first.text, /Subscription quota exhausted/); + assert.equal(argvLines(logFile, 'exec').length, 1, 'the first request paid the real exec attempt'); + + const second = await chatRaw(port, { messages: [{ role: 'user', content: 'hello again' }] }); + assert.equal(second.status, 500); + assert.match(second.text, /Subscription quota exhausted/); + assert.equal(argvLines(logFile, 'exec').length, 1, 'the second request must not spawn the CLI again'); +}); + +test('quota exhausted on the warm path: no exec fallback, later requests fail fast', async (t) => { + const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' }); + t.after(stop); + + const first = await chatRaw(port, { messages: [{ role: 'user', content: 'QUOTAWARM please' }] }); + assert.equal(first.status, 500); + assert.match(first.text, /Subscription quota exhausted/); + assert.equal(argvLines(logFile, 'exec').length, 0, 'a warm quota failure must not fall back to exec'); + + const second = await chatRaw(port, { messages: [{ role: 'user', content: 'hello again' }] }); + assert.equal(second.status, 500); + assert.match(second.text, /Subscription quota exhausted/); + const turns = fs.readFileSync(logFile, 'utf-8').split('\n').filter(l => l.startsWith('TURN')); + assert.equal(turns.length, 1, 'the second request must not reach the serve host'); + assert.equal(argvLines(logFile, 'exec').length, 0); +});