From 7b372509a4dd74bf61e04efdd8381486cbbcff84 Mon Sep 17 00:00:00 2001 From: opensource-elearning <159253500+opensource-elearning@users.noreply.github.com> Date: Fri, 28 Aug 2026 16:08:46 +0000 Subject: [PATCH 1/2] fix(combo): clear stale LKGP pin when provider/connection is exhausted When a combo target is marked exhausted via applyComboTargetExhaustion (providerExhausted, or the connection added to exhaustedConnections), the Last Known Good Provider (LKGP) pin was never cleared. On the next request, LKGP re-selected the same dead provider/connection first every time, so a failed free-tier connection (e.g. opencode noauth) kept being retried instead of falling through to healthy targets. Clear the pin for both the target executionKey and the combo, matching the existing clearLKGP pattern already used on the per-model done-retrying path. Applies to both handleComboChat and handleRoundRobinCombo. Closes #11911 --- open-sse/services/combo.ts | 88 ++++++++++++++++++++++++++++++-------- 1 file changed, 70 insertions(+), 18 deletions(-) diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.ts index 38c210ee5b4b..b92c1be3e053 100644 --- a/open-sse/services/combo.ts +++ b/open-sse/services/combo.ts @@ -2182,6 +2182,32 @@ async function handleComboChatInner({ // rather than waiting for the next turn's lazy headroom/status recheck. releaseStickyPinOnFailure(_sticky.messageHash, targetWithConnection.connectionId); + // #11911: when the provider/connection is marked exhausted (providerExhausted + // or the connection added to exhaustedConnections), clear the LKGP pin so + // the next request doesn't re-select the same dead provider first. + const exhaustedProvider = targetWithConnection.provider; + const exhaustedConnId = targetWithConnection.connectionId; + if ( + exhaustedProvider && + exhaustedProvider !== "unknown" && + (providerExhausted || + exhaustedConnections.has(`${exhaustedProvider}:${exhaustedConnId}`)) + ) { + void (async () => { + try { + const { clearLKGP } = await import("../../src/lib/localDb"); + await Promise.all([ + clearLKGP(combo.name, targetWithConnection.executionKey), + clearLKGP(combo.name, combo.id || combo.name), + ]); + } catch (err) { + log.warn("COMBO", "Failed to clear Last Known Good Provider. This is non-fatal.", { + err, + }); + } + })(); + } + // #2101: Prevent infinite fallback loops with 400 Bad Request errors that are genuinely // body-specific (malformed JSON, bad format, missing required fields). // These should NOT stop the combo: @@ -3302,24 +3328,20 @@ async function handleRoundRobinCombo({ "COMBO-RR", `Maximum combo attempts (${maxGlobalAttempts}) exceeded. Terminating loop to prevent runaway requests.` ); - return errorResponseWithComboDiagnostics( - 503, - "Maximum combo retry limit reached", - { - poolSize: modelCount, - attempted: globalAttempts, - excluded: [ - ...[...exhaustedProviders].map((p) => ({ provider: p, reason: "exhausted" })), - ...[...exhaustedConnections].map((c) => formatExhaustedConnectionKey(String(c))), - ], - attemptOrder: rrOutcomes.map((o) => ({ - provider: o.model.split("/")[0] || "unknown", - model: o.model, - })), - terminalReason: "max_attempts_exceeded", - recovery: buildRecoveryHint("max_attempts_exceeded"), - } - ); + return errorResponseWithComboDiagnostics(503, "Maximum combo retry limit reached", { + poolSize: modelCount, + attempted: globalAttempts, + excluded: [ + ...[...exhaustedProviders].map((p) => ({ provider: p, reason: "exhausted" })), + ...[...exhaustedConnections].map((c) => formatExhaustedConnectionKey(String(c))), + ], + attemptOrder: rrOutcomes.map((o) => ({ + provider: o.model.split("/")[0] || "unknown", + model: o.model, + })), + terminalReason: "max_attempts_exceeded", + recovery: buildRecoveryHint("max_attempts_exceeded"), + }); } if (retry > 0) { log.info( @@ -3695,6 +3717,36 @@ async function handleRoundRobinCombo({ targetWithConnection.connectionId ); + // #11911: when the provider/connection is marked exhausted (providerExhausted + // or the connection added to exhaustedConnections), clear the LKGP pin so + // the next request doesn't re-select the same dead provider first. + const exhaustedProvider = targetWithConnection.provider; + const exhaustedConnId = targetWithConnection.connectionId; + if ( + exhaustedProvider && + exhaustedProvider !== "unknown" && + (providerExhausted || + exhaustedConnections.has(`${exhaustedProvider}:${exhaustedConnId}`)) + ) { + void (async () => { + try { + const { clearLKGP } = await import("../../src/lib/localDb"); + await Promise.all([ + clearLKGP(combo.name, targetWithConnection.executionKey), + clearLKGP(combo.name, combo.id || combo.name), + ]); + } catch (err) { + log.warn( + "COMBO-RR", + "Failed to clear Last Known Good Provider. This is non-fatal.", + { + err, + } + ); + } + })(); + } + // Transient errors → mark in semaphore so round-robin stops stampeding this target. if ( !isStreamReadinessFailure && From 42964d4332ee64843c81afcd881c88a180de0c50 Mon Sep 17 00:00:00 2001 From: opensource-elearning <159253500+opensource-elearning@users.noreply.github.com> Date: Sat, 29 Aug 2026 10:30:31 +0530 Subject: [PATCH 2/2] fix(combo): gate combo-level LKGP clear on the exhausted provider/connection (#11914) Review feedback (#11914): the original #11911 clear dropped the whole combo-level LKGP pin unconditionally whenever any target was marked exhausted, even when that pin named a different, healthy target. Only the combo-level pin is read on the next request (applyStrategyOrdering / resolveAutoStrategy), so clearing it wholesale could throw away a good preference after a single unrelated failure. Extract the two identical inline blocks (handleComboChat + handleRoundRobinCombo) into clearLKGPOnExhaustion and gate the clear: - the executionKey pin always names the target that just failed - clear it; - the combo-level pin is cleared only when it names the exhausted provider and, when both carry a connectionId, the exhausted connection. The guard also drops the previous `exhaustedConnections.has("provider:" + connId)` interpolation when connId is null ("provider:null"), gating on providerExhausted instead when no connectionId is available. Adds 9 unit tests (tests/unit/combo/combo-lkgp-clear.test.ts) locking the clearing rules, incl. the healthy-sibling and healthy-provider survived cases the reviewer asked to preserve. --- open-sse/services/combo.ts | 67 ++---- open-sse/services/combo/lkgpClearing.ts | 85 ++++++++ tests/unit/combo/combo-lkgp-clear.test.ts | 238 ++++++++++++++++++++++ 3 files changed, 342 insertions(+), 48 deletions(-) create mode 100644 open-sse/services/combo/lkgpClearing.ts create mode 100644 tests/unit/combo/combo-lkgp-clear.test.ts diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.ts index b92c1be3e053..141bd3b36c18 100644 --- a/open-sse/services/combo.ts +++ b/open-sse/services/combo.ts @@ -228,6 +228,7 @@ export { isModelScoped400, }; import { applyComboTargetExhaustion } from "./combo/targetExhaustion.ts"; +import { clearLKGPOnExhaustion } from "./combo/lkgpClearing.ts"; import { applyNativeCodexTurnPin, getNativeCodexTurnPin, @@ -2185,28 +2186,15 @@ async function handleComboChatInner({ // #11911: when the provider/connection is marked exhausted (providerExhausted // or the connection added to exhaustedConnections), clear the LKGP pin so // the next request doesn't re-select the same dead provider first. - const exhaustedProvider = targetWithConnection.provider; - const exhaustedConnId = targetWithConnection.connectionId; - if ( - exhaustedProvider && - exhaustedProvider !== "unknown" && - (providerExhausted || - exhaustedConnections.has(`${exhaustedProvider}:${exhaustedConnId}`)) - ) { - void (async () => { - try { - const { clearLKGP } = await import("../../src/lib/localDb"); - await Promise.all([ - clearLKGP(combo.name, targetWithConnection.executionKey), - clearLKGP(combo.name, combo.id || combo.name), - ]); - } catch (err) { - log.warn("COMBO", "Failed to clear Last Known Good Provider. This is non-fatal.", { - err, - }); - } - })(); - } + void clearLKGPOnExhaustion({ + comboName: combo.name, + comboKey: combo.id || combo.name, + target: targetWithConnection, + providerExhausted, + exhaustedConnections, + log, + tag: "COMBO", + }); // #2101: Prevent infinite fallback loops with 400 Bad Request errors that are genuinely // body-specific (malformed JSON, bad format, missing required fields). @@ -3720,32 +3708,15 @@ async function handleRoundRobinCombo({ // #11911: when the provider/connection is marked exhausted (providerExhausted // or the connection added to exhaustedConnections), clear the LKGP pin so // the next request doesn't re-select the same dead provider first. - const exhaustedProvider = targetWithConnection.provider; - const exhaustedConnId = targetWithConnection.connectionId; - if ( - exhaustedProvider && - exhaustedProvider !== "unknown" && - (providerExhausted || - exhaustedConnections.has(`${exhaustedProvider}:${exhaustedConnId}`)) - ) { - void (async () => { - try { - const { clearLKGP } = await import("../../src/lib/localDb"); - await Promise.all([ - clearLKGP(combo.name, targetWithConnection.executionKey), - clearLKGP(combo.name, combo.id || combo.name), - ]); - } catch (err) { - log.warn( - "COMBO-RR", - "Failed to clear Last Known Good Provider. This is non-fatal.", - { - err, - } - ); - } - })(); - } + void clearLKGPOnExhaustion({ + comboName: combo.name, + comboKey: combo.id || combo.name, + target: targetWithConnection, + providerExhausted, + exhaustedConnections, + log, + tag: "COMBO-RR", + }); // Transient errors → mark in semaphore so round-robin stops stampeding this target. if ( diff --git a/open-sse/services/combo/lkgpClearing.ts b/open-sse/services/combo/lkgpClearing.ts new file mode 100644 index 000000000000..3dd2ea862925 --- /dev/null +++ b/open-sse/services/combo/lkgpClearing.ts @@ -0,0 +1,85 @@ +/** + * lkgpClearing.ts — clearing the Last Known Good Provider (LKGP) pin when a + * combo target is marked exhausted (#11911). + * + * Shared by both combo dispatchers (handleComboChat + handleRoundRobinCombo). + * `setLKGP` is only ever called on success, so a pin never got invalidated once + * its target started failing; the exhaustion-classification sites were the hole. + * + * Two pins are written on success (`setLKGP(combo.name, , provider, connId)`): + * - `:` — names exactly that one target, + * - `:` — the combo-level pin read by + * applyStrategyOrdering / resolveAutoStrategy on the next request. + * + * Clearing safety differs per pin: + * - The `executionKey` pin always names the target that just failed — clear it. + * - The combo-level pin records whichever target last succeeded, which needn't + * be the one that just failed (a target can be skipped and a *different*, + * healthy one tried and exhausted). Keep a preference that points at a + * healthy target; clear it only when it names the exhausted provider and, + * when both carry a connectionId, the exhausted connection. + */ +import type { ComboLogger } from "./types.ts"; + +export type LKGPExhaustionTarget = { + executionKey: string; + provider?: string | null; + connectionId?: string | null; +}; + +export type ClearLKGPOnExhaustionOptions = { + comboName: string; + /** `combo.id || combo.name` — the combo-level pin key (must match the read sites). */ + comboKey: string; + target: LKGPExhaustionTarget; + providerExhausted: boolean; + exhaustedConnections: Set; + log: ComboLogger; + tag: string; +}; + +/** + * Clear the LKGP pin when a combo target was just marked exhausted. No-op when + * nothing was actually marked (mirrors the #1731/#1731v2 classification guard: + * with a connectionId the exhaustion is connection-scoped, otherwise the + * provider itself is dead). Fire-and-forget at the call sites; failures are + * logged, never thrown. + */ +export async function clearLKGPOnExhaustion(opts: ClearLKGPOnExhaustionOptions): Promise { + const { comboName, comboKey, target, providerExhausted, exhaustedConnections, log, tag } = opts; + const provider = target.provider; + const connId = target.connectionId ?? undefined; + + // #11911: exhaustion is either provider-level (`providerExhausted`) or + // connection-level (the `${provider}:${connId}` key in exhaustedConnections). + // `providerExhausted` also returns true for a connection-scoped 401/403 (see + // markAuthLevelExhaustion) and agentrouter quota exhaustion, but in every such + // case the connId key lands in exhaustedConnections too — so with a connId the + // set membership is the load-bearing check, and the `"undefined"` interpolation + // the inline code had is avoided by gating on connId's presence. + if ( + !provider || + provider === "unknown" || + !(connId ? exhaustedConnections.has(`${provider}:${connId}`) : providerExhausted) + ) { + return; + } + + try { + const { clearLKGP, getLKGP } = await import("../../../src/lib/localDb"); + // The executionKey pin always names the target that just failed. + await clearLKGP(comboName, target.executionKey); + // The combo-level pin records whichever target last succeeded, which needn't + // be the one that just failed — keep a preference pointing at a healthy + // target, clear it only when it names the exhausted provider/connection. + const pinned = await getLKGP(comboName, comboKey); + if ( + pinned?.provider === provider && + (connId == null || pinned.connectionId == null || pinned.connectionId === connId) + ) { + await clearLKGP(comboName, comboKey); + } + } catch (err) { + log.warn(tag, "Failed to clear Last Known Good Provider. This is non-fatal.", { err }); + } +} diff --git a/tests/unit/combo/combo-lkgp-clear.test.ts b/tests/unit/combo/combo-lkgp-clear.test.ts new file mode 100644 index 000000000000..cd4ecbbe93c0 --- /dev/null +++ b/tests/unit/combo/combo-lkgp-clear.test.ts @@ -0,0 +1,238 @@ +// tests/unit/combo/combo-lkgp-clear.test.ts +// #11911 regression: when a combo target is marked exhausted (providerExhausted or the +// connection added to exhaustedConnections), the Last Known Good Provider (LKGP) pin must +// be cleared so the next request doesn't re-pin the same dead provider/connection. +// +// Locks the exact clearing rules of clearLKGPOnExhaustion (shared by handleComboChat + +// handleRoundRobinCombo): +// - the `executionKey` pin always names the target that just failed → always cleared on +// exhaustion of that target; +// - the combo-level pin (the only one read by applyStrategyOrdering / resolveAutoStrategy) +// records whichever target last succeeded, which needn't be the one that just failed → +// cleared only when it names the exhausted provider and, when both carry a connectionId, +// the exhausted connection. A preference pointing at a healthy target survives. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-lkgp-clear-")); +process.env.DATA_DIR = TEST_DATA_DIR; + +const { getDbInstance, resetDbInstance } = await import("../../../src/lib/db/core.ts"); +const { getLKGP, setLKGP } = await import("../../../src/lib/db/settings/lkgp.ts"); +const { clearLKGPOnExhaustion } = await import("../../../open-sse/services/combo/lkgpClearing.ts"); + +const log = { info() {}, warn() {}, error() {}, debug() {} }; + +function resetStorage() { + try { + if (globalThis.__omnirouteDb?.open) { + globalThis.__omnirouteDb.close(); + } + } catch {} + delete globalThis.__omnirouteDb; + resetDbInstance(); + if (fs.existsSync(TEST_DATA_DIR)) { + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true }); + } + fs.mkdirSync(TEST_DATA_DIR, { recursive: true }); + getDbInstance(); +} + +// Seeds the same two pins handleComboChat writes on success: the per-target +// executionKey pin and the combo-level pin. +function seedPins(comboName: string, comboKey: string, provider: string, connId?: string) { + setLKGP(comboName, comboKey, provider, connId ?? undefined); + setLKGP(comboName, "openai/gpt-4o", provider, connId ?? undefined); +} + +const comboName = "test-combo"; +const comboKey = "test-combo"; // combo.id || combo.name + +test("provider-level exhaustion clears both the executionKey and the combo-level pin", async () => { + resetStorage(); + seedPins(comboName, comboKey, "openai"); + + await clearLKGPOnExhaustion({ + comboName, + comboKey, + target: { executionKey: "openai/gpt-4o", provider: "openai", connectionId: null }, + providerExhausted: true, + exhaustedConnections: new Set(), + log, + tag: "COMBO", + }); + + assert.equal(await getLKGP(comboName, comboKey), null, "combo-level pin must be cleared"); + assert.equal(await getLKGP(comboName, "openai/gpt-4o"), null, "executionKey pin must be cleared"); +}); + +test("connection-level exhaustion clears both pins when they name the exact connection", async () => { + resetStorage(); + seedPins(comboName, comboKey, "openai", "conn-1"); + + await clearLKGPOnExhaustion({ + comboName, + comboKey, + target: { executionKey: "openai/gpt-4o", provider: "openai", connectionId: "conn-1" }, + providerExhausted: false, + exhaustedConnections: new Set(["openai:conn-1"]), + log, + tag: "COMBO", + }); + + assert.equal(await getLKGP(comboName, comboKey), null, "combo-level pin must be cleared"); + assert.equal(await getLKGP(comboName, "openai/gpt-4o"), null, "executionKey pin must be cleared"); +}); + +test("combo-level pin for a different, healthy provider is kept", async () => { + resetStorage(); + // Pin names provider B (the last successful target). A DIFFERENT target (A:conn-1) + // exhausts this request — B was never unhealthy, so its preference must survive. + seedPins(comboName, comboKey, "provider-b"); + + await clearLKGPOnExhaustion({ + comboName, + comboKey, + target: { executionKey: "a-model", provider: "provider-a", connectionId: "conn-1" }, + providerExhausted: true, + exhaustedConnections: new Set(["provider-a:conn-1"]), + log, + tag: "COMBO", + }); + + assert.deepEqual( + await getLKGP(comboName, comboKey), + { provider: "provider-b" }, + "combo-level pin naming a healthy provider must survive" + ); +}); + +test("combo-level pin naming a different connection of the same provider is kept", async () => { + resetStorage(); + // Pin names provider-a:conn-2 — a healthy SIBLING connection. Exhausting conn-1 must + // not drop the sibling's preference. + seedPins(comboName, comboKey, "provider-a", "conn-2"); + + await clearLKGPOnExhaustion({ + comboName, + comboKey, + target: { executionKey: "provider-a/gpt-4o", provider: "provider-a", connectionId: "conn-1" }, + providerExhausted: true, + exhaustedConnections: new Set(["provider-a:conn-1"]), + log, + tag: "COMBO", + }); + + assert.deepEqual( + await getLKGP(comboName, comboKey), + { provider: "provider-a", connectionId: "conn-2" }, + "combo-level pin naming a healthy sibling connection must survive" + ); + assert.equal( + await getLKGP(comboName, "provider-a/gpt-4o"), + null, + "the exhausted target's own executionKey pin must still be cleared" + ); +}); + +test("provider-level exhaustion clears a connection-scoped combo pin for that provider", async () => { + resetStorage(); + // Whole provider is dead; even a connection-scoped pin for that provider should go. + seedPins(comboName, comboKey, "openai", "conn-7"); + + await clearLKGPOnExhaustion({ + comboName, + comboKey, + target: { executionKey: "openai/gpt-4o", provider: "openai", connectionId: null }, + providerExhausted: true, + exhaustedConnections: new Set(), + log, + tag: "COMBO", + }); + + assert.equal(await getLKGP(comboName, comboKey), null); +}); + +test("no exhaustion marks nothing and both pins survive", async () => { + resetStorage(); + seedPins(comboName, comboKey, "openai", "conn-1"); + + await clearLKGPOnExhaustion({ + comboName, + comboKey, + target: { executionKey: "openai/gpt-4o", provider: "openai", connectionId: "conn-1" }, + providerExhausted: false, + exhaustedConnections: new Set(), + log, + tag: "COMBO", + }); + + assert.deepEqual(await getLKGP(comboName, comboKey), { + provider: "openai", + connectionId: "conn-1", + }); + assert.ok(await getLKGP(comboName, "openai/gpt-4o"), "executionKey pin must survive"); +}); + +test("unknown provider is never cleared (guard)", async () => { + resetStorage(); + seedPins(comboName, comboKey, "openai"); + + await clearLKGPOnExhaustion({ + comboName, + comboKey, + target: { executionKey: "unknown/gpt-4o", provider: "unknown", connectionId: null }, + providerExhausted: true, + exhaustedConnections: new Set(), + log, + tag: "COMBO", + }); + + assert.deepEqual(await getLKGP(comboName, comboKey), { provider: "openai" }); +}); + +test("a connection-scoped 401 (providerExhausted true + conn in exhaustion set) clears only when the pin names that exact provider:connection", async () => { + resetStorage(); + // Mirrors the #8137 auth case: providerExhausted returns true BUT the exhaustion is + // connection-scoped (a 401 on conn-1). A pin on the SAME provider's different + // connection is a healthy sibling — it must survive. + seedPins(comboName, comboKey, "provider-a", "conn-2"); + + await clearLKGPOnExhaustion({ + comboName, + comboKey, + target: { executionKey: "provider-a/gpt-4o", provider: "provider-a", connectionId: "conn-1" }, + providerExhausted: true, + exhaustedConnections: new Set(["provider-a:conn-1"]), + log, + tag: "COMBO", + }); + + assert.deepEqual( + await getLKGP(comboName, comboKey), + { provider: "provider-a", connectionId: "conn-2" }, + "a connection-scoped auth failure must not clear a sibling connection's pin" + ); +}); + +test("legacy provider-only combo pin is cleared when that provider exhausts without a connectionId", async () => { + resetStorage(); + // setLKGP stores `{provider}` when no connectionId is available — the legacy shape. + setLKGP(comboName, comboKey, "openai"); + setLKGP(comboName, "openai/gpt-4o", "openai"); + + await clearLKGPOnExhaustion({ + comboName, + comboKey, + target: { executionKey: "openai/gpt-4o", provider: "openai", connectionId: null }, + providerExhausted: true, + exhaustedConnections: new Set(), + log, + tag: "COMBO", + }); + + assert.equal(await getLKGP(comboName, comboKey), null); +});