diff --git a/bin/opencode-route-proxy.mjs b/bin/opencode-route-proxy.mjs index 70f01618d0..6379fbc8fb 100755 --- a/bin/opencode-route-proxy.mjs +++ b/bin/opencode-route-proxy.mjs @@ -12,7 +12,7 @@ // OpenCode server uses (.opencode/opencode.jsonc: model_routes + // provider blocks), picks the actual pool member (ordered / round-robin // / weighted selection, variant remaps, disabled providers skipped, -// quota demotion from the route_attempt ledger), expands provider +// quota demotion from the route_attempt ledger, plus the known-exhausted seating gate #5295), expands provider // routes (experimental.provider_routes, #3256) into their member // providers, and makes ONE plain // chat-completions call to that member's endpoint with the member's @@ -351,6 +351,131 @@ const demotedPairs = () => { } }; +// The reset instant a quota detail promises, if it carries one +// (#5295): a Retry-After-derived relative wait (the shape +// classifyHttp records for 429s), or an absolute reset recorded under +// any of the equivalent field names. A quota record with no reset +// (e.g. a bare paymentRequired) cannot gate: how long it lasts is +// unknown, and demotion remains its only handling. +const quotaResetMs = (timeEnded, quotaText) => { + let q; + try { + q = JSON.parse(quotaText); + } catch { + return null; + } + if (!q || typeof q !== "object") return null; + // A relative retry delay runs from when the quota response was + // RECEIVED (the attempt's time_ended), not from when the request + // started: anchoring to the start would let a slow 429 response + // consume its own backoff. + if (Number.isFinite(q.retryAfterMs) && q.retryAfterMs > 0) + return timeEnded + q.retryAfterMs; + for (const k of ["resetsAtMs", "resetAtMs", "retryAtMs"]) + if (Number.isFinite(q[k]) && q[k] > 0) return q[k]; + for (const k of ["resetsAt", "resetAt", "retryAt"]) { + const ms = Date.parse(q[k]); + if (Number.isFinite(ms)) return ms; + } + return null; +}; + +// (provider,model) pairs whose binding quota window is KNOWN +// exhausted (#5295, #4370 acceptance (c)): the pair's latest +// quota-bearing failure in the ledger carries a reset still in the +// future, and no success has been recorded for the pair since that +// failure. Unlike demotion — reactive (>=3 failures in 4h) and +// reorder-only — this is a seating-time exclusion known BEFORE the +// next failure: a monthly-walled leg at a known 100% must not be a +// first-choice candidate while any live candidate exists. The ledger +// is the only source (no new network dependency in the hot path); +// the lookback bounds the scan while covering monthly resets. +const EXHAUSTED_LOOKBACK_MS = 40 * 24 * 60 * 60 * 1000; +const knownExhaustedPairs = (now) => { + let db = null; + try { + db = openDb(); + const since = now - EXHAUSTED_LOOKBACK_MS; + // All ordering is by COMPLETION time (time_ended): with + // overlapping requests, start-time ordering can mistake a + // success that finished before a quota response arrived for a + // recovery after it. + const quotaRows = db + .prepare( + `SELECT provider_id, model_id, time_started, time_ended, quota FROM route_attempt + WHERE quota IS NOT NULL AND outcome != 'success' AND time_ended > ? + AND time_ended = ( + SELECT MAX(time_ended) FROM route_attempt r2 + WHERE r2.provider_id = route_attempt.provider_id + AND r2.model_id = route_attempt.model_id + AND r2.quota IS NOT NULL AND r2.outcome != 'success' + AND r2.time_ended > ? + )`, + ) + .all(since, since); + const successRows = db + .prepare( + `SELECT provider_id, model_id, MAX(time_ended) AS latest + FROM route_attempt + WHERE outcome = 'success' AND time_ended > ? + GROUP BY provider_id, model_id`, + ) + .all(since); + const latestSuccess = new Map( + successRows.map((r) => [`${r.provider_id}/${r.model_id}`, r.latest]), + ); + const out = new Map(); + for (const r of quotaRows) { + const reset = quotaResetMs(r.time_ended, r.quota); + if (reset === null || reset <= now) continue; + const key = `${r.provider_id}/${r.model_id}`; + const successAt = latestSuccess.get(key); + if (successAt !== undefined && successAt > r.time_ended) continue; + out.set(key, reset); + } + return out; + } catch { + return new Map(); + } finally { + try { + db?.close(); + } catch {} + } +}; + +// Exclude known-exhausted candidates (#5295), following the +// credential-less exclusion pattern (#3228) — but fail-safe: if the +// gate would empty the candidate list, the demoted order is kept as +// it was, because a known-exhausted leg as last resort beats no +// route at all. Gate decisions are recorded on stderr, the proxy's +// diagnostics stream. +const applyKnownExhaustedGate = (cfg, candidates) => { + if (!candidates.length) return candidates; + const exhausted = knownExhaustedPairs(nowMs()); + if (!exhausted.size) return candidates; + const key = (c) => `${c.providerId}/${c.modelKey}`; + const kept = candidates.filter((c) => !exhausted.has(key(c))); + // The fail-safe is evaluated against CREDENTIALED survivors: the + // credential-less filter (#3228) runs after this gate, so a kept + // list whose only members have no credential would still empty the + // route — and the exhausted leaf must then stay as the last resort + // instead of the request failing with "no credentialed members". + if (!kept.some((c) => hasCredential(cfg, c.providerId))) { + console.error( + "opencode-route-proxy: known-exhausted gate bypassed — no credentialed " + + "candidate survives it; keeping the demoted order (#5295)", + ); + return candidates; + } + for (const c of candidates) + if (exhausted.has(key(c))) + console.error( + `opencode-route-proxy: known-exhausted gate excluded ${key(c)} ` + + `until ${new Date(exhausted.get(key(c))).toISOString()} (#5295)`, + ); + return kept; +}; + const recordAttempt = (a) => { let db = null; try { @@ -802,6 +927,7 @@ const runCompletion = async (routeId, body, clientSignal, hooks = {}) => { const wantStream = Boolean(body.stream); let candidates = resolveRoute(cfg, routeId, hooks.variantIn ?? null); candidates = applyDemotion(candidates, demotedPairs()); + candidates = applyKnownExhaustedGate(cfg, candidates); if (!candidates.length) throw new LeafError(`route ${routeId} has no available members`, { tag: "UnknownProvider", diff --git a/bin/opencode-route-proxy.test.mjs b/bin/opencode-route-proxy.test.mjs index e18ef2d7b7..1435db7ba5 100644 --- a/bin/opencode-route-proxy.test.mjs +++ b/bin/opencode-route-proxy.test.mjs @@ -204,6 +204,7 @@ const startProxy = async (arg = {}) => { "t-disabled": { "selection": "ordered", "targets": ["leafOff/m-b", "leafB/m-b"] }, "t-nocred-first": { "selection": "ordered", "targets": ["leafNoCred/m-nc", "leafB/m-b"] }, "t-nocred-only": { "selection": "ordered", "targets": ["leafNoCred/m-nc"] }, + "t-gate-nocred": { "selection": "ordered", "targets": ["leafA/m-a", "leafNoCred/m-b"] }, "t-window": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "window": "peak" }, "leafB/m-b" ] }, "t-window-inv": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "window": { "name": "peak", "invert": true } }, "leafB/m-b" ] }, "t-window-unknown": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "window": "no-such-window" }, "leafB/m-b" ] }, @@ -275,7 +276,7 @@ const startProxy = async (arg = {}) => { leafA.server.close(); leafB.server.close(); }; - return { base, post, attempts, leafA, leafB, cleanup, log: () => log }; + return { base, post, attempts, leafA, leafB, cleanup, dbPath, log: () => log }; }; const MSGS = [ @@ -770,3 +771,275 @@ test("config load names invalid windows instead of silently evaluating them", as await p.cleanup(); } }); + +// ------------------------------------------------------------ #5295 gate + +// Seed one quota-bearing failure for a (provider, model) pair, as if +// the leaf had answered 429 with a Retry-After `retryAfterMs` long at +// `atMs`. Written straight into the fixture ledger the proxy reads. +const seedQuotaFailure = (dbPath, { provider, model, atMs, retryAfterMs, endedMs }) => { + const db = new DatabaseSync(dbPath); + db.prepare( + `INSERT INTO route_attempt ( + time_started, time_ended, session_id, assistant_message_id, + route_id, provider_id, model_id, variant, outcome, + error_tag, error_code, error_status, error_message, retryable, + output_started, failed_over_to, quota + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + ).run( + atMs, + endedMs ?? atMs + 50, + null, + null, + "seed", + provider, + model, + null, + "failure", + "RateLimit", + null, + 429, + "leaf HTTP 429: quota", + 1, + 0, + null, + JSON.stringify({ retryAfterMs }), + ); + db.close(); +}; + +// A Monday noon UTC, pinned via OPENCODE_ROUTE_PROXY_NOW_MS so the +// gate's clock is deterministic. +const GATE_NOW = Date.UTC(2026, 0, 5, 12, 0, 0); + +test("known-exhausted pair is excluded while a live pair exists (#5295)", async () => { + const p = await startProxy({ nowMs: GATE_NOW }); + try { + // One minute ago the leaf said: retry after an hour. The pair is + // known exhausted for another ~59 minutes — one failure is + // enough; demotion's >=3 must not be required. + seedQuotaFailure(p.dbPath, { + provider: "leafA", + model: "m-a", + atMs: GATE_NOW - 60_000, + retryAfterMs: 3_600_000, + }); + const res = await p.post({ model: "opencode-route/t-ordered", messages: MSGS }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.choices[0].message.content, "LEAF-B"); + assert.equal(p.leafA.hits, 0, "the exhausted leaf must not be attempted"); + const rows = p.attempts().filter((r) => r.route_id === "t-ordered"); + assert.equal(rows.length, 1); + assert.equal(rows[0].provider_id, "leafB"); + assert.ok( + p.log().includes("known-exhausted gate excluded leafA/m-a"), + `gate decision should be in the proxy diagnostics: ${p.log()}`, + ); + } finally { + await p.cleanup(); + } +}); + +test("known-exhausted pair returns after its reset passes (#5295)", async () => { + const p = await startProxy({ nowMs: GATE_NOW }); + try { + // Two hours ago the leaf said retry after an hour: the reset is + // an hour in the past at the pinned now, so the gate has lifted. + seedQuotaFailure(p.dbPath, { + provider: "leafA", + model: "m-a", + atMs: GATE_NOW - 7_200_000, + retryAfterMs: 3_600_000, + }); + const res = await p.post({ model: "opencode-route/t-ordered", messages: MSGS }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.choices[0].message.content, "LEAF-A"); + assert.equal(p.leafB.hits, 0); + } finally { + await p.cleanup(); + } +}); + +test("all candidates known-exhausted: route still walks in order (#5295)", async () => { + const p = await startProxy({ nowMs: GATE_NOW }); + try { + seedQuotaFailure(p.dbPath, { + provider: "leafA", + model: "m-a", + atMs: GATE_NOW - 60_000, + retryAfterMs: 3_600_000, + }); + seedQuotaFailure(p.dbPath, { + provider: "leafB", + model: "m-b", + atMs: GATE_NOW - 60_000, + retryAfterMs: 3_600_000, + }); + // Fail-safe: a known-exhausted leg as last resort beats no route, + // so the walk keeps the (demoted) order and leaf A still serves. + const res = await p.post({ model: "opencode-route/t-ordered", messages: MSGS }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.choices[0].message.content, "LEAF-A"); + assert.ok( + p.log().includes("known-exhausted gate bypassed"), + `bypass should be in the proxy diagnostics: ${p.log()}`, + ); + } finally { + await p.cleanup(); + } +}); + +test("a success after the quota failure clears the gate (#5295)", async () => { + const p = await startProxy({ nowMs: GATE_NOW }); + try { + seedQuotaFailure(p.dbPath, { + provider: "leafA", + model: "m-a", + atMs: GATE_NOW - 120_000, + retryAfterMs: 3_600_000, + }); + // The pair served successfully a minute after that failure + // (another door sharing the ledger): the exhaustion is stale. + const db = new DatabaseSync(p.dbPath); + db.prepare( + `INSERT INTO route_attempt ( + time_started, time_ended, session_id, assistant_message_id, + route_id, provider_id, model_id, variant, outcome, + error_tag, error_code, error_status, error_message, retryable, + output_started, failed_over_to, quota + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + ).run( + GATE_NOW - 60_000, + GATE_NOW - 59_000, + null, + null, + "seed", + "leafA", + "m-a", + null, + "success", + null, + null, + null, + null, + 1, + 0, + null, + null, + ); + db.close(); + const res = await p.post({ model: "opencode-route/t-ordered", messages: MSGS }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.choices[0].message.content, "LEAF-A"); + } finally { + await p.cleanup(); + } +}); + +test("gate bypassed when the only survivor has no credential (#5295)", async () => { + const p = await startProxy({ nowMs: GATE_NOW }); + try { + seedQuotaFailure(p.dbPath, { + provider: "leafA", + model: "m-a", + atMs: GATE_NOW - 60_000, + retryAfterMs: 3_600_000, + }); + // leafA/m-a is known-exhausted and leafNoCred/m-b is not — but + // leafNoCred has no credential, so excluding leafA would still + // empty the route at the #3228 filter. The gate must bypass and + // keep leafA as the last resort instead of failing the request. + const res = await p.post({ model: "opencode-route/t-gate-nocred", messages: MSGS }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.choices[0].message.content, "LEAF-A"); + assert.ok( + p.log().includes("known-exhausted gate bypassed"), + `bypass should be in the proxy diagnostics: ${p.log()}`, + ); + } finally { + await p.cleanup(); + } +}); + +test("retry delay is anchored to the quota response receipt (#5295)", async () => { + const p = await startProxy({ nowMs: GATE_NOW }); + try { + // The 429 took 90s to arrive (started 2 minutes ago, received 30s + // ago) and asked for 60 more seconds of backoff. Anchored to the + // request start the pair would already be eligible again + // (start + 60s < now); anchored to the receipt it is exhausted + // for another ~30s. + seedQuotaFailure(p.dbPath, { + provider: "leafA", + model: "m-a", + atMs: GATE_NOW - 120_000, + endedMs: GATE_NOW - 30_000, + retryAfterMs: 60_000, + }); + const res = await p.post({ model: "opencode-route/t-ordered", messages: MSGS }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.choices[0].message.content, "LEAF-B"); + assert.equal(p.leafA.hits, 0); + } finally { + await p.cleanup(); + } +}); + +test("an overlapping success completed before the quota response does not clear the gate (#5295)", async () => { + const p = await startProxy({ nowMs: GATE_NOW }); + try { + // Quota failure: started 2 minutes ago, the 429 arrived 10s ago. + seedQuotaFailure(p.dbPath, { + provider: "leafA", + model: "m-a", + atMs: GATE_NOW - 120_000, + endedMs: GATE_NOW - 10_000, + retryAfterMs: 3_600_000, + }); + // Overlapping success: STARTED after the failing request (so + // start-time ordering would call it the latest word) but + // COMPLETED a minute ago — before the 429 was received. It is + // not a recovery; the gate must hold. + const db = new DatabaseSync(p.dbPath); + db.prepare( + `INSERT INTO route_attempt ( + time_started, time_ended, session_id, assistant_message_id, + route_id, provider_id, model_id, variant, outcome, + error_tag, error_code, error_status, error_message, retryable, + output_started, failed_over_to, quota + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + ).run( + GATE_NOW - 110_000, + GATE_NOW - 60_000, + null, + null, + "seed", + "leafA", + "m-a", + null, + "success", + null, + null, + null, + null, + 1, + 0, + null, + null, + ); + db.close(); + const res = await p.post({ model: "opencode-route/t-ordered", messages: MSGS }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.choices[0].message.content, "LEAF-B"); + assert.equal(p.leafA.hits, 0); + } finally { + await p.cleanup(); + } +});