From 8f0bef24e62fda268dba9a5a1d18c337d53faf62 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:39:09 -0600 Subject: [PATCH 1/3] =?UTF-8?q?fix(route-proxy):=20known-100%=20seating=20?= =?UTF-8?q?gate=20=E2=80=94=20exclude=20pairs=20with=20a=20future=20quota?= =?UTF-8?q?=20reset=20(#5295)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements #4370 acceptance (c) from triage task 8950. Demotion only reorders a pair after >=3 quota failures in 4h, so a leg whose binding window was ALREADY known exhausted (e.g. a monthly-walled leg) stayed a first-choice candidate until it killed three more sessions. - knownExhaustedPairs(now): the latest quota-bearing ledger failure for a pair whose detail carries a future reset (Retry-After-derived retryAfterMs from classifyHttp, or an absolute resetsAt/resetAt/retryAt field), not cleared by a later success. 40-day lookback covers monthly resets; the ledger is the only source — no new network dependency. - applyKnownExhaustedGate runs right after applyDemotion, following the #3228 credential-less exclusion pattern. Fail-safe: if the gate would empty the candidate list, the demoted order is kept (an exhausted leg as last resort beats no route). Decisions are logged to stderr, the proxy diagnostics stream. - The gate clock is nowMs(), so OPENCODE_ROUTE_PROXY_NOW_MS pins it for tests and incident replay. - Tests (node --test, 31/31 pass): exclusion while a live pair exists (ledger extract asserted: the t-ordered walk records exactly one attempt, leafB, beside the seeded leafA quota row), return after reset, all-exhausted bypass, and success-clears-gate. --- bin/opencode-route-proxy.mjs | 115 +++++++++++++++++++- bin/opencode-route-proxy.test.mjs | 170 +++++++++++++++++++++++++++++- 2 files changed, 283 insertions(+), 2 deletions(-) diff --git a/bin/opencode-route-proxy.mjs b/bin/opencode-route-proxy.mjs index 70f01618d0..4da6952c1d 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,118 @@ 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 = (timeStarted, quotaText) => { + let q; + try { + q = JSON.parse(quotaText); + } catch { + return null; + } + if (!q || typeof q !== "object") return null; + if (Number.isFinite(q.retryAfterMs) && q.retryAfterMs > 0) + return timeStarted + 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; + const quotaRows = db + .prepare( + `SELECT provider_id, model_id, time_started, quota FROM route_attempt + WHERE quota IS NOT NULL AND outcome != 'success' AND time_started > ? + AND time_started = ( + SELECT MAX(time_started) 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_started > ? + )`, + ) + .all(since, since); + const successRows = db + .prepare( + `SELECT provider_id, model_id, MAX(time_started) AS latest + FROM route_attempt + WHERE outcome = 'success' AND time_started > ? + 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_started, 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_started) 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 = (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))); + if (!kept.length) { + console.error( + "opencode-route-proxy: known-exhausted gate bypassed — every candidate is " + + "known-exhausted; 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 +914,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(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..993fc2c7d1 100644 --- a/bin/opencode-route-proxy.test.mjs +++ b/bin/opencode-route-proxy.test.mjs @@ -275,7 +275,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 +770,171 @@ 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 }) => { + 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, + 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(); + } +}); From e1a95041269bf34cc216db458a8c20d7eaad6656 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:46:49 -0600 Subject: [PATCH 2/3] =?UTF-8?q?fix(route-proxy):=20Codex=20round=20on=20#5?= =?UTF-8?q?295=20=E2=80=94=20credential-aware=20gate=20fallback,=20receipt?= =?UTF-8?q?-anchored=20retry=20delay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The gate fail-safe is now evaluated against credentialed survivors: the #3228 credential-less filter runs after the gate, so a kept list whose only members lack credentials would still have emptied the route and failed the request instead of retaining the exhausted leaf as last resort. New test: gate bypassed when the only survivor has no credential. - Relative quota resets are anchored to the attempt's time_ended (when the 429 was received), not time_started, so a slow quota response no longer consumes its own Retry-After backoff. New pinned-clock test with a 90s response time. --- bin/opencode-route-proxy.mjs | 27 ++++++++++----- bin/opencode-route-proxy.test.mjs | 56 +++++++++++++++++++++++++++++-- 2 files changed, 72 insertions(+), 11 deletions(-) diff --git a/bin/opencode-route-proxy.mjs b/bin/opencode-route-proxy.mjs index 4da6952c1d..b54c34e8ae 100755 --- a/bin/opencode-route-proxy.mjs +++ b/bin/opencode-route-proxy.mjs @@ -357,7 +357,7 @@ const demotedPairs = () => { // 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 = (timeStarted, quotaText) => { +const quotaResetMs = (timeEnded, quotaText) => { let q; try { q = JSON.parse(quotaText); @@ -365,8 +365,12 @@ const quotaResetMs = (timeStarted, quotaText) => { 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 timeStarted + q.retryAfterMs; + 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"]) { @@ -394,7 +398,7 @@ const knownExhaustedPairs = (now) => { const since = now - EXHAUSTED_LOOKBACK_MS; const quotaRows = db .prepare( - `SELECT provider_id, model_id, time_started, quota FROM route_attempt + `SELECT provider_id, model_id, time_started, time_ended, quota FROM route_attempt WHERE quota IS NOT NULL AND outcome != 'success' AND time_started > ? AND time_started = ( SELECT MAX(time_started) FROM route_attempt r2 @@ -418,7 +422,7 @@ const knownExhaustedPairs = (now) => { ); const out = new Map(); for (const r of quotaRows) { - const reset = quotaResetMs(r.time_started, r.quota); + 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); @@ -441,16 +445,21 @@ const knownExhaustedPairs = (now) => { // 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 = (candidates) => { +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))); - if (!kept.length) { + // 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 — every candidate is " + - "known-exhausted; keeping the demoted order (#5295)", + "opencode-route-proxy: known-exhausted gate bypassed — no credentialed " + + "candidate survives it; keeping the demoted order (#5295)", ); return candidates; } @@ -914,7 +923,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(candidates); + 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 993fc2c7d1..6bf2a441bb 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" ] }, @@ -776,7 +777,7 @@ test("config load names invalid windows instead of silently evaluating them", as // 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 }) => { +const seedQuotaFailure = (dbPath, { provider, model, atMs, retryAfterMs, endedMs }) => { const db = new DatabaseSync(dbPath); db.prepare( `INSERT INTO route_attempt ( @@ -787,7 +788,7 @@ const seedQuotaFailure = (dbPath, { provider, model, atMs, retryAfterMs }) => { ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, ).run( atMs, - atMs + 50, + endedMs ?? atMs + 50, null, null, "seed", @@ -938,3 +939,54 @@ test("a success after the quota failure clears the gate (#5295)", async () => { 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(); + } +}); From f749cd1026a24824533ba15bf6e4ee26d3ab764f Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:54:27 -0600 Subject: [PATCH 3/3] =?UTF-8?q?fix(route-proxy):=20Codex=20round=202=20on?= =?UTF-8?q?=20#5295=20=E2=80=94=20order=20gate=20observations=20by=20compl?= =?UTF-8?q?etion=20time?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Overlapping requests made start-time ordering unsound: a success that started after a failing request but completed before its 429 arrived would clear the gate. knownExhaustedPairs now selects the latest quota failure by time_ended, aggregates successes by MAX(time_ended), and clears only when a success completed after the quota response was received. New pinned-clock regression test for the overlap case. Suite 34/34. --- bin/opencode-route-proxy.mjs | 18 +++++++---- bin/opencode-route-proxy.test.mjs | 53 +++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/bin/opencode-route-proxy.mjs b/bin/opencode-route-proxy.mjs index b54c34e8ae..6379fbc8fb 100755 --- a/bin/opencode-route-proxy.mjs +++ b/bin/opencode-route-proxy.mjs @@ -396,24 +396,28 @@ const knownExhaustedPairs = (now) => { 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_started > ? - AND time_started = ( - SELECT MAX(time_started) FROM route_attempt r2 + 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_started > ? + AND r2.time_ended > ? )`, ) .all(since, since); const successRows = db .prepare( - `SELECT provider_id, model_id, MAX(time_started) AS latest + `SELECT provider_id, model_id, MAX(time_ended) AS latest FROM route_attempt - WHERE outcome = 'success' AND time_started > ? + WHERE outcome = 'success' AND time_ended > ? GROUP BY provider_id, model_id`, ) .all(since); @@ -426,7 +430,7 @@ const knownExhaustedPairs = (now) => { 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_started) continue; + if (successAt !== undefined && successAt > r.time_ended) continue; out.set(key, reset); } return out; diff --git a/bin/opencode-route-proxy.test.mjs b/bin/opencode-route-proxy.test.mjs index 6bf2a441bb..1435db7ba5 100644 --- a/bin/opencode-route-proxy.test.mjs +++ b/bin/opencode-route-proxy.test.mjs @@ -990,3 +990,56 @@ test("retry delay is anchored to the quota response receipt (#5295)", async () = 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(); + } +});