diff --git a/src/oauth/generic-account-failover.ts b/src/oauth/generic-account-failover.ts index 49cca431de1..dd2c74d8634 100644 --- a/src/oauth/generic-account-failover.ts +++ b/src/oauth/generic-account-failover.ts @@ -274,8 +274,9 @@ export function preferKiroModelSupport( if (!model) return ids; if (providerName === "google-antigravity") { const positive = ids.filter(id => accountListsModel(providerName, id, model) === true); - if (positive.length) return positive; - return ids.filter(id => accountListsModel(providerName, id, model) !== false); + const modelMatched = positive.length ? positive : ids.filter(id => accountListsModel(providerName, id, model) !== false); + const nonExhausted = modelMatched.filter(id => !isAccountQuotaExhausted(providerName, id, model)); + return nonExhausted.length ? nonExhausted : modelMatched; } if (providerName !== "kiro") return ids; const cap = config?.providers?.kiro?.oauthAccountFailover?.maxConcurrentPerAccount; @@ -351,7 +352,8 @@ function rankAntigravityModelAccounts(config: OcxConfig, ids: string[], model: s const rows = new Map((getAccountSet(provider)?.accounts ?? []).map(row => [row.id, row])); const strategy = activeGenericStrategy(config, provider); if (strategy === "round-robin") { - const best = peekRoundRobinAccount(genericPoolKey(provider), ids, genericStickyLimit(config, provider)); + const poolKey = genericPoolKey(provider, classifyModelFamilyForQuota(provider, model)); + const best = peekRoundRobinAccount(poolKey, ids, genericStickyLimit(config, provider)); return best ? [best, ...ids.filter(id => id !== best)] : ids; } if (strategy === "fill-first") return stableGenericRoster(provider).filter(id => ids.includes(id)); @@ -580,10 +582,16 @@ export function noteGenericPoolSelection( requestedModelId?: string | null, ): void { if (activeGenericStrategy(config, providerName) !== "round-robin") return; - const poolKey = genericPoolKey(providerName); - const limit = genericStickyLimit(config, providerName); const family = classifyModelFamilyForQuota(providerName, requestedModelId); - const picked = pickRoundRobinAccount(poolKey, eligibleFailoverAccounts(providerName, Date.now(), family), limit); + const poolKey = genericPoolKey(providerName, family); + const limit = genericStickyLimit(config, providerName); + const eligible = preferKiroModelSupport( + providerName, + eligibleFailoverAccounts(providerName, Date.now(), family), + requestedModelId, + config, + ); + const picked = pickRoundRobinAccount(poolKey, eligible, limit); // The resolver may have admitted a different account than the ring proposed: a removal, a // reauth verdict or a manual selection can land during credential resolution. Realign the // cursor onto what actually served rather than leaving it on a road not taken. @@ -684,7 +692,7 @@ export function rotateGenericOAuthAccountOnRefusal( // PICK here, not peek: the failure already happened and this answer is the one being used, // so the ring genuinely advances. A caller that only asks whether a sibling exists peeks. return (commit ? pickRoundRobinAccount : peekRoundRobinAccount)( - genericPoolKey(providerName), + genericPoolKey(providerName, family), candidates, genericStickyLimit(config, providerName), ); @@ -822,7 +830,7 @@ export function preferredInitialAccount( // PEEK, not pick: this proposal is discardable, and advancing the ring for an account the // resolver then rejects would skip a turn for nothing. noteGenericPoolSelection commits. const picked = peekRoundRobinAccount( - genericPoolKey(providerName), + genericPoolKey(providerName, family), eligibleNow, genericStickyLimit(config, providerName), ); @@ -890,6 +898,13 @@ export function genericFailoverRetryAfterSeconds(providerName: string, now = Dat } /** Test seam and manual-recovery hook. */ +/** A manual selection must win in every ring a request can read, including the per-family ones. */ +export function seedGenericPoolSelection(providerName: string, accountId: string): void { + seedPoolRotationAccount(genericPoolKey(providerName), accountId); + if (providerName !== "google-antigravity") return; + for (const family of ["gem", "cla"] satisfies QuotaModelFamily[]) seedPoolRotationAccount(genericPoolKey(providerName, family), accountId); +} + export function forgetGenericFailoverRoster(providerName: string): void { presence.delete(providerName); } diff --git a/src/oauth/generic-session-affinity.ts b/src/oauth/generic-session-affinity.ts index 325d4cac71c..4291aa15c43 100644 --- a/src/oauth/generic-session-affinity.ts +++ b/src/oauth/generic-session-affinity.ts @@ -13,7 +13,8 @@ const IDLE_TTL_MS = 24 * 60 * 60_000; const MAX_ENTRIES = 2_000; const bindings = new Map(); const prefix = (provider: string) => `${JSON.stringify([getConfigDir(), provider])}\u0000`; -const key = (provider: string, session: string) => prefix(provider) + "session:" + createHash("sha256").update(session).digest("hex"); +const key = (provider: string, session: string, family?: string) => + prefix(provider) + (family ? `session:${family}:` : "session:") + createHash("sha256").update(session).digest("hex"); const cursorKey = (provider: string) => prefix(provider) + "fill-first"; /** A persisted operator/roster/policy change revokes old session choices before its writer returns. */ @@ -59,7 +60,9 @@ export function genericSessionAccount( config: OcxConfig, provider: string, session: string | null, model?: string | null, now = Date.now(), ): string | null { if (!genericSessionAffinityEnabled(config, provider) || !session) return null; - return readBinding(config, provider, key(provider, session), model, now); + const family = classifyModelFamilyForQuota(provider, model); + return readBinding(config, provider, key(provider, session, family), model, now) + ?? (family ? readBinding(config, provider, key(provider, session), model, now) : null); } function readBinding(config: OcxConfig, provider: string, id: string, model: string | null | undefined, now: number): string | null { @@ -127,6 +130,10 @@ export function bindGenericSessionAccount( const hit = session && genericSessionAccount(config, provider, session, model, now) === accountId; if (!hit && config.pool?.kernel === true && config.providers[provider]?.oauthAccountFailover?.strategy === "fill-first") keep(cursorKey(provider)); - if (session) keep(key(provider, session)); + const family = classifyModelFamilyForQuota(provider, model); + if (session) { + keep(key(provider, session, family)); + if (family) keep(key(provider, session)); + } while (bindings.size > MAX_ENTRIES) bindings.delete(bindings.keys().next().value!); } diff --git a/src/oauth/pool-kernel.ts b/src/oauth/pool-kernel.ts index ccded808398..c5c457f3cce 100644 --- a/src/oauth/pool-kernel.ts +++ b/src/oauth/pool-kernel.ts @@ -10,8 +10,8 @@ export const POOL_KEY_ANTHROPIC = "anthropic"; * with the two dedicated kinds, and so `reconcilePoolRotationState` can recognise * the entry as sweepable rather than skipping it as unknown. */ -export function genericPoolKey(providerName: string): string { - return `generic:${providerName}`; +export function genericPoolKey(providerName: string, family?: string): string { + return family ? `generic:${providerName}:${family}` : `generic:${providerName}`; } interface SelectionState { @@ -274,6 +274,10 @@ export function clearPoolRotationState(poolKey?: string): void { return; } selectionState.delete(poolKey); + const prefix = `${poolKey}:`; + for (const key of [...selectionState.keys()]) { + if (key.startsWith(prefix)) selectionState.delete(key); + } } export function reconcilePoolRotationState(context: GenerationContext): number { @@ -309,7 +313,7 @@ export function reconcilePoolRotationState(context: GenerationContext): number { : poolKey === POOL_KEY_CODEX || poolKey.startsWith(`${POOL_KEY_CODEX}:`) ? context.codexAccountIds : poolKey.startsWith("generic:") - ? genericIds.get(poolKey.slice("generic:".length)) ?? new Set() + ? genericIds.get(poolKey.slice("generic:".length).split(":")[0]!) ?? new Set() : null; if (!valid) continue; if (valid.size === 0) { diff --git a/src/server/management/oauth-account-routes.ts b/src/server/management/oauth-account-routes.ts index 8df040da50f..7536b333015 100644 --- a/src/server/management/oauth-account-routes.ts +++ b/src/server/management/oauth-account-routes.ts @@ -619,14 +619,13 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise< if (!latest) return jsonResponse({ error: "account not found" }, 404); return jsonResponse({ error: latest.paused ? "account is paused" : "account selection changed" }, 409); } - const { forgetGenericFailoverRoster } = await import("../../oauth/generic-account-failover"); + const { forgetGenericFailoverRoster, seedGenericPoolSelection } = await import("../../oauth/generic-account-failover"); forgetGenericFailoverRoster(provider); // Seed the rotation cursor on the operator's pick, or a sticky round-robin ring hands the // very next dispatch back to whatever the pool had chosen. forgetGenericFailoverRoster // only drops the presence count; it has never touched the cursor. Same defect the Codex // side carries resetCodexRoutingForManualSelection for. - const { genericPoolKey, seedPoolRotationAccount } = await import("../../oauth/pool-kernel"); - seedPoolRotationAccount(genericPoolKey(provider), body.accountId); + seedGenericPoolSelection(provider, body.accountId); const anthropicRouting = isAnthropicOAuthInstance(provider) ? (await import("../../oauth/anthropic-routing")).anthropicRoutingFor(provider) : undefined; anthropicRouting?.resetAnthropicRoutingForManualSelection(body.accountId); @@ -710,8 +709,8 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise< } if (result.activeAccountChanged) { if (!anthropicRouting) { - const { genericPoolKey, seedPoolRotationAccount } = await import("../../oauth/pool-kernel"); - seedPoolRotationAccount(genericPoolKey(provider), result.activeAccountId); + const { seedGenericPoolSelection } = await import("../../oauth/generic-account-failover"); + seedGenericPoolSelection(provider, result.activeAccountId); } const { clearModelCache } = await import("../../codex/model-cache"); const { clearGatherRoutedModelsInflight } = await import("../../codex/catalog"); diff --git a/tests/adapters/google/antigravity-account-roster.test.ts b/tests/adapters/google/antigravity-account-roster.test.ts index 4270dd1bab1..cdfeb55402d 100644 --- a/tests/adapters/google/antigravity-account-roster.test.ts +++ b/tests/adapters/google/antigravity-account-roster.test.ts @@ -11,12 +11,16 @@ import { antigravitySelectedAccountUnlistedMessage, clearGenericFailoverHealth, hasEligibleGenericOAuthFailoverTarget, + noteGenericPoolSelection, preferKiroModelSupport, preferredInitialAccount, rotateAntigravityAccountOnAuthRefusal, rotateGenericOAuthAccountOn429, routeAntigravityModel, + seedGenericPoolSelection, } from "../../../src/oauth/generic-account-failover"; +import { clearPoolRotationState } from "../../../src/oauth/pool-kernel"; +import { bindGenericSessionAccount, clearGenericSessionAffinity, genericSessionAccount } from "../../../src/oauth/generic-session-affinity"; import { ANTIGRAVITY_ACCOUNT_ROSTER_TTL_MS, antigravityAccountRosterModelIds, @@ -30,6 +34,7 @@ import { parseAntigravityAvailableModels, resolveAntigravityEffortWireModel, } from "../../../src/providers/antigravity-models"; +import { clearAccountQuotaCache, setCachedProviderAccountQuotaForTests } from "../../../src/providers/quota"; import type { OcxConfig, OcxProviderConfig } from "../../../src/types"; import { withStubbedProviderFetch } from "../../helpers/catalog-provider-fetch"; import { removeTreeWithRetry } from "../../helpers/remove-tree"; @@ -72,6 +77,8 @@ afterEach(() => { clearModelCache(); clearAntigravityAccountRosters(); clearGenericFailoverHealth(); + clearGenericSessionAffinity(); + clearAccountQuotaCache(PROVIDER); if (originalHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = originalHome; for (const home of homes.splice(0)) removeTreeWithRetry(home); @@ -271,4 +278,90 @@ describe("model routing fails closed on a proven roster omission (#7500)", () => record("acct-55", ROSTER_46); expect(rotateAntigravityAccountOnAuthRefusal(true, "acct-a", "stale-generation", "claude-opus-5-5")).toBeNull(); }); + + test("round-robin rotates across model-supporting accounts per family without resetting weights", () => { + clearPoolRotationState(); + homeWithAccounts(["acct-46a", "acct-55a", "acct-46b", "acct-55b"], "acct-55a"); + record("acct-46a", ROSTER_46); + record("acct-55a", ROSTER_55); + record("acct-46b", ROSTER_46); + record("acct-55b", ROSTER_55); + const rrConfig = { + pool: { kernel: true }, + providers: { + [PROVIDER]: provider({ oauthAccountFailover: { enabled: true, strategy: "round-robin", stickyLimit: 1 } }), + }, + } as unknown as OcxConfig; + const served: string[] = []; + for (let turn = 0; turn < 3; turn++) { + const picked = preferredInitialAccount(rrConfig, PROVIDER, Date.now(), "claude-opus-5-5") ?? "acct-55a"; + noteGenericPoolSelection(rrConfig, PROVIDER, picked, "claude-opus-5-5"); + served.push(picked); + } + expect(served).toEqual(["acct-55a", "acct-55b", "acct-55a"]); + }); + + test("conversation affinity keeps one account per quota family when a session alternates families", () => { + homeWithAccounts(["acct-55a", "acct-55b"], "acct-55a"); + record("acct-55a", ROSTER_55); + record("acct-55b", ROSTER_55); + const affinityConfig = { + providers: { + [PROVIDER]: provider({ oauthAccountFailover: { enabled: true, sessionAffinity: "conversation" } }), + }, + } as unknown as OcxConfig; + bindGenericSessionAccount(affinityConfig, PROVIDER, "session", "acct-55a", "claude-opus-5-5"); + bindGenericSessionAccount(affinityConfig, PROVIDER, "session", "acct-55b", "gemini-3.8-flash-high"); + expect(genericSessionAccount(affinityConfig, PROVIDER, "session", "claude-opus-5-5")).toBe("acct-55a"); + expect(genericSessionAccount(affinityConfig, PROVIDER, "session", "gemini-3.8-flash-high")).toBe("acct-55b"); + }); + test("model filtering drops an account whose quota family is exhausted unless every listing account is", () => { + homeWithAccounts(["acct-55a", "acct-55b"], "acct-55a"); + record("acct-55a", ROSTER_55); + record("acct-55b", ROSTER_55); + const spent = { updatedAt: Date.now(), customWindows: [{ label: "Cla", percent: 100 }, { label: "Gem", percent: 10 }] }; + setCachedProviderAccountQuotaForTests(PROVIDER, "acct-55a", spent); + expect(preferKiroModelSupport(PROVIDER, ["acct-55a", "acct-55b"], "claude-opus-5-5")).toEqual(["acct-55b"]); + expect(preferKiroModelSupport(PROVIDER, ["acct-55a", "acct-55b"], "gemini-3.8-flash-high")).toEqual(["acct-55a", "acct-55b"]); + setCachedProviderAccountQuotaForTests(PROVIDER, "acct-55b", spent); + expect(preferKiroModelSupport(PROVIDER, ["acct-55a", "acct-55b"], "claude-opus-5-5")).toEqual(["acct-55a", "acct-55b"]); + }); + test("model-listing reroutes follow the family round-robin ring", () => { + clearPoolRotationState(); + homeWithAccounts(["acct-46a", "acct-55a", "acct-55b"], "acct-46a"); + record("acct-46a", ROSTER_46); + record("acct-55a", ROSTER_55); + record("acct-55b", ROSTER_55); + const rrConfig = { + pool: { kernel: true }, + providers: { + [PROVIDER]: provider({ oauthAccountFailover: { enabled: true, strategy: "round-robin", stickyLimit: 1 } }), + }, + } as unknown as OcxConfig; + const served: (string | null)[] = []; + for (let turn = 0; turn < 3; turn++) { + const picked = preferredInitialAccount(rrConfig, PROVIDER, Date.now(), "claude-opus-5-5"); + served.push(picked); + if (picked) noteGenericPoolSelection(rrConfig, PROVIDER, picked, "claude-opus-5-5"); + } + expect(served).toEqual(["acct-55a", "acct-55b", "acct-55a"]); + }); + + test("a manual selection overrides a sticky family ring", () => { + clearPoolRotationState(); + homeWithAccounts(["acct-55a", "acct-55b"], "acct-55a"); + record("acct-55a", ROSTER_55); + record("acct-55b", ROSTER_55); + const rrConfig = { + pool: { kernel: true }, + providers: { + [PROVIDER]: provider({ oauthAccountFailover: { enabled: true, strategy: "round-robin", stickyLimit: 5 } }), + }, + } as unknown as OcxConfig; + noteGenericPoolSelection(rrConfig, PROVIDER, "acct-55a", "claude-opus-5-5"); + expect(preferredInitialAccount(rrConfig, PROVIDER, Date.now(), "claude-opus-5-5", "acct-46x")).toBe("acct-55a"); + seedGenericPoolSelection(PROVIDER, "acct-55b"); + expect(preferredInitialAccount(rrConfig, PROVIDER, Date.now(), "claude-opus-5-5", "acct-46x")).toBe("acct-55b"); + expect(preferredInitialAccount(rrConfig, PROVIDER, Date.now(), "gemini-3.8-flash-high", "acct-46x")).toBe("acct-55b"); + }); });