Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions src/oauth/generic-account-failover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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),
);
Expand Down Expand Up @@ -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),
);
Expand Down Expand Up @@ -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);
}
Expand Down
13 changes: 10 additions & 3 deletions src/oauth/generic-session-affinity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ const IDLE_TTL_MS = 24 * 60 * 60_000;
const MAX_ENTRIES = 2_000;
const bindings = new Map<string, { accountId: string; lastUsedAt: number; selection: OAuthAccountSelection }>();
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. */
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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!);
}
10 changes: 7 additions & 3 deletions src/oauth/pool-kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

interface SelectionState {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<string>()
? genericIds.get(poolKey.slice("generic:".length).split(":")[0]!) ?? new Set<string>()
: null;
if (!valid) continue;
if (valid.size === 0) {
Expand Down
9 changes: 4 additions & 5 deletions src/server/management/oauth-account-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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");
Expand Down
93 changes: 93 additions & 0 deletions tests/adapters/google/antigravity-account-roster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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";
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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");
});
});
Loading