From b4105c2b08aaa83fc1b4b0defd74595ae1cc2c23 Mon Sep 17 00:00:00 2001 From: Vadym O Date: Tue, 10 Nov 2026 22:23:13 +0800 Subject: [PATCH 1/4] fix(anthropic-pool): cool a model-scoped weekly 429 per model family, log limit headers on every 429 A 429 whose representative claim is seven_day_ (e.g. seven_day_opus) for a request of that family now cools only (account, family): the account keeps serving its other models, and an Opus request is refused only when every account is out of Opus. Every other 429 still cools the whole account. Each 429 logs model, representative-claim, unified/5h/7d status, retry-after, reset and the chosen cooldown, and the no-eligible-account line now counts cooled, re-auth and unusable accounts instead of claiming they are all in cooldown. Co-Authored-By: Claude Code --- src/oauth/anthropic-routing.ts | 108 ++++++++++++------ src/server/claude-messages.ts | 5 +- src/server/responses/adapter-continuation.ts | 1 + src/server/responses/adapter-dispatch.ts | 1 + src/server/responses/request-transport.ts | 5 +- src/server/responses/sidecar-execution.ts | 1 + .../anthropic-ratelimit-headers.test.ts | 47 ++++++++ 7 files changed, 126 insertions(+), 42 deletions(-) diff --git a/src/oauth/anthropic-routing.ts b/src/oauth/anthropic-routing.ts index b23c1bd78c1..ae94e3b289b 100644 --- a/src/oauth/anthropic-routing.ts +++ b/src/oauth/anthropic-routing.ts @@ -183,6 +183,7 @@ export function getAnthropicAccountHealthSnapshot( } export function clearAnthropicAccountCooldown(accountId: string): boolean { + for (const key of upstreamHealth.keys()) if (key.startsWith(`${accountId}\0`)) upstreamHealth.delete(key); return upstreamHealth.delete(accountId); } @@ -208,8 +209,19 @@ export function anthropicSessionAffinitySizeForTests(): number { return sessionAffinity.size; } -function isCooled(accountId: string, now: number): boolean { - return getAnthropicAccountHealthSnapshot(accountId, now) !== null; +/** + * The model family a model-scoped weekly limit names: a 429 whose representative claim is `seven_day_opus` spends + * only the account's Opus allowance, so it cools (account, "opus") and the account keeps serving its other models. + */ +export function anthropicModelFamily(modelId: string | null | undefined): string | undefined { + return /\b(opus|sonnet|haiku|fable)\b/i.exec(modelId ?? "")?.[1]?.toLowerCase(); +} + +const familyKey = (accountId: string, family: string) => `${accountId}\0${family}`; + +function isCooled(accountId: string, now: number, family?: string): boolean { + return getAnthropicAccountHealthSnapshot(accountId, now) !== null + || (family !== undefined && getAnthropicAccountHealthSnapshot(familyKey(accountId, family), now) !== null); } function fiveHourKnown(accountId: string): boolean { @@ -278,13 +290,13 @@ function isPoolCredentialUsable(accountId: string, now: number): boolean { setComboPoolEligibilityProbe((provider, now) => provider === PROVIDER && getEligibleAnthropicAccounts(now).length > 0); -export function getEligibleAnthropicAccounts(now = Date.now()): string[] { +export function getEligibleAnthropicAccounts(now = Date.now(), family?: string): string[] { const set = getAccountSet(PROVIDER); if (!set) return []; return set.accounts .filter(account => account.needsReauth !== true - && !isCooled(account.id, now) + && !isCooled(account.id, now, family) && isPoolCredentialUsable(account.id, now)) .map(account => account.id); } @@ -363,14 +375,16 @@ export function forgetAnthropicFailoverQuorum(): void { } /** Earliest remaining cooldown among cooled Anthropic accounts, for client Retry-After. */ -export function getAnthropicPoolRetryAfterSeconds(now = Date.now()): number | null { +export function getAnthropicPoolRetryAfterSeconds(now = Date.now(), family?: string): number | null { const set = getAccountSet(PROVIDER); if (!set) return null; let earliest: number | null = null; for (const account of set.accounts) { - const snap = getAnthropicAccountHealthSnapshot(account.id, now); - if (!snap?.cooldownUntil) continue; - if (earliest === null || snap.cooldownUntil < earliest) earliest = snap.cooldownUntil; + // An account serves again only once both its own and its family's cooldown are over. + const until = Math.max(getAnthropicAccountHealthSnapshot(account.id, now)?.cooldownUntil ?? 0, + family ? getAnthropicAccountHealthSnapshot(familyKey(account.id, family), now)?.cooldownUntil ?? 0 : 0); + if (!until) continue; + if (earliest === null || until < earliest) earliest = until; } if (earliest === null || earliest <= now) return null; return Math.max(1, Math.ceil((earliest - now) / 1000)); @@ -396,9 +410,9 @@ function compareScoredAccounts(a: ScoredAccount, b: ScoredAccount): number { return a.score - b.score || a.fiveHourTieBreak - b.fiveHourTieBreak; } -function pickLowestUsage(config: OcxConfig, excludeId: string | undefined, now: number): string | null { +function pickLowestUsage(config: OcxConfig, excludeId: string | undefined, now: number, family?: string): string | null { const window = anthropicQuotaWindow(anthropicAccountPoolConfig(config)); - const unfiltered = getEligibleAnthropicAccounts(now).filter(id => id !== excludeId); + const unfiltered = getEligibleAnthropicAccounts(now, family).filter(id => id !== excludeId); const available = window === "weekly" ? unfiltered.filter(id => !exhausted5h(id)) : unfiltered; const eligible = available.length > 0 ? available : unfiltered; if (eligible.length === 0) return null; @@ -467,16 +481,17 @@ function pickAlternateAnthropicAccount( config: OcxConfig, excludeId: string, now: number, + family?: string, ): string | null { const strategy = anthropicPoolStrategy(config); - const eligible = getEligibleAnthropicAccounts(now).filter(id => id !== excludeId); + const eligible = getEligibleAnthropicAccounts(now, family).filter(id => id !== excludeId); if (strategy === "round-robin") { return peekRoundRobinAccount(POOL_KEY_ANTHROPIC, eligible, stickyLimitForPool(config)); } if (strategy === "fill-first") { return pickNextFillFirstAnthropicAccount(config, excludeId, eligible); } - return pickLowestUsage(config, excludeId, now); + return pickLowestUsage(config, excludeId, now, family); } function pruneExpiredAffinity(now: number): void { @@ -529,8 +544,8 @@ function isActiveUnderFillFirstThreshold(config: OcxConfig, accountId: string): * Fill-first: keep eligible active under threshold; otherwise advance to the next * eligible id in stable sorted order after the current active (wrapping). */ -function pickFillFirstAnthropicAccount(config: OcxConfig, now: number): string | null { - const eligible = getEligibleAnthropicAccounts(now); +function pickFillFirstAnthropicAccount(config: OcxConfig, now: number, family?: string): string | null { + const eligible = getEligibleAnthropicAccounts(now, family); if (eligible.length === 0) return null; const set = getAccountSet(PROVIDER); @@ -557,12 +572,13 @@ function pickFillFirstAnthropicAccount(config: OcxConfig, now: number): string | function pickUnboundStrategyAccount( config: OcxConfig, now: number, + family?: string, ): { accountId: string; reason: "round-robin" | "fill-first" } | null { const strategy = anthropicPoolStrategy(config); if (strategy === "quota") return null; if (strategy === "round-robin") { - const eligible = getEligibleAnthropicAccounts(now); + const eligible = getEligibleAnthropicAccounts(now, family); const limit = stickyLimitForPool(config); const picked = peekRoundRobinAccount(POOL_KEY_ANTHROPIC, eligible, limit); if (!picked) return null; @@ -570,7 +586,7 @@ function pickUnboundStrategyAccount( } if (strategy === "fill-first") { - const picked = pickFillFirstAnthropicAccount(config, now); + const picked = pickFillFirstAnthropicAccount(config, now, family); if (!picked) return null; return { accountId: picked, reason: "fill-first" }; } @@ -586,7 +602,9 @@ export function resolveAnthropicAccountForSession( sessionKey: string | null | undefined, config: OcxConfig, now = Date.now(), + modelId?: string | null, ): AnthropicAccountSelection { + const family = anthropicModelFamily(modelId); pruneExpiredAffinity(now); const set = getAccountSet(PROVIDER); if (!set || set.accounts.length === 0) return { accountId: null, reason: "none" }; @@ -617,7 +635,7 @@ export function resolveAnthropicAccountForSession( const exhausted = [quota?.fiveHourPercent, quota?.weeklyPercent, quota?.monthlyPercent, ...(quota?.customWindows ?? []).map(window => window.percent)] .some(percent => typeof percent === "number" && percent >= 100); - if (!exhausted && getEligibleAnthropicAccounts(now).includes(chosen)) { + if (!exhausted && getEligibleAnthropicAccounts(now, family).includes(chosen)) { return { accountId: chosen, reason: "manual" }; } } @@ -626,13 +644,13 @@ export function resolveAnthropicAccountForSession( // Round-robin's pick is arbitrary, so a keyed session always takes its hash seat, ahead of the // in-process binding: warm and fresh processes agree, and a session moved off a spent seat // returns to it in every process once it recovers instead of alternating between processes. - const hashed = strategy === "round-robin" ? sessionHashAccount(key, getEligibleAnthropicAccounts(now)) : null; + const hashed = strategy === "round-robin" ? sessionHashAccount(key, getEligibleAnthropicAccounts(now, family)) : null; if (hashed) return { accountId: hashed, reason: sessionAffinity.get(key)?.accountId === hashed ? "affinity" : "hash" }; if (key) { const affined = sessionAffinity.get(key); if (affined && now - affined.lastUsedAt <= AFFINITY_IDLE_TTL_MS) { const stillThere = set.accounts.some(a => a.id === affined.accountId && a.needsReauth !== true); - if (stillThere && !isCooled(affined.accountId, now) && isPoolCredentialUsable(affined.accountId, now)) { + if (stillThere && !isCooled(affined.accountId, now, family) && isPoolCredentialUsable(affined.accountId, now)) { return { accountId: affined.accountId, reason: "affinity" }; } sessionAffinity.delete(key); @@ -644,21 +662,21 @@ export function resolveAnthropicAccountForSession( // Round-robin only when there is a real new-session key (or active is unusable). if (!key && (strategy === "round-robin" || strategy === "fill-first")) { const activeOk = set.accounts.some(a => a.id === set.activeAccountId && a.needsReauth !== true) - && !isCooled(set.activeAccountId, now) + && !isCooled(set.activeAccountId, now, family) && isPoolCredentialUsable(set.activeAccountId, now); if (activeOk) { return { accountId: set.activeAccountId, reason: "active" }; } } - const strategyPick = pickUnboundStrategyAccount(config, now); + const strategyPick = pickUnboundStrategyAccount(config, now, family); if (strategyPick) { return { accountId: strategyPick.accountId, reason: strategyPick.reason }; } const threshold = anthropicAutoSwitchThreshold(config); const activeOk = set.accounts.some(a => a.id === set.activeAccountId && a.needsReauth !== true) - && !isCooled(set.activeAccountId, now) + && !isCooled(set.activeAccountId, now, family) && isPoolCredentialUsable(set.activeAccountId, now); let accountId: string | null = null; @@ -673,7 +691,7 @@ export function resolveAnthropicAccountForSession( accountId = set.activeAccountId; reason = "active"; } else { - const picked = pickLowestUsage(config, undefined, now); + const picked = pickLowestUsage(config, undefined, now, family); if (picked) { accountId = picked; reason = activeOk && picked === set.activeAccountId ? "active" : "lowest-usage"; @@ -686,7 +704,7 @@ export function resolveAnthropicAccountForSession( accountId = set.activeAccountId; reason = "active"; } else { - const picked = pickLowestUsage(config, set.activeAccountId, now); + const picked = pickLowestUsage(config, set.activeAccountId, now, family); if (picked) { accountId = picked; reason = "only-eligible"; @@ -694,7 +712,7 @@ export function resolveAnthropicAccountForSession( } if (!accountId) { - const anyCooled = set.accounts.some(a => isCooled(a.id, now)); + const anyCooled = set.accounts.some(a => isCooled(a.id, now, family)); return { accountId: null, reason: anyCooled ? "all-cooled" : "none" }; } @@ -734,6 +752,7 @@ export function rotateAnthropicAccountOn429( sessionKey?: string | null, now = Date.now(), rateLimitHeaders?: AnthropicRateLimitHeaders | null, + modelId?: string | null, ): string | null { // Reactive 429 failover is NOT gated on the pool flag. That flag buys PROACTIVE routing -- // session affinity, quota-ranked new-session selection, autoSwitchThreshold, strategy -- all @@ -741,21 +760,29 @@ export function rotateAnthropicAccountOn429( // just rate-limited is a different thing: it only ever runs after a refusal, and stranding a // 429 while a second logged-in account sits idle is a defect, not a configuration choice. // Presence is the activation rule, the same one an apiKeyPool of two keys already uses. - if (!isAnthropicAccountPoolEnabled(config) && !hasAnthropicFailoverQuorum(now)) return null; - // Retry-After first: it is the header written FOR this decision. The rejected window's // reset is the fallback, because a 429 that omits Retry-After still carries it -- and // without that fallback such a refusal cools for the 60s default and the exhausted // account is back in the rotation a minute later. + // A model-scoped weekly limit (claim `seven_day_` matching the request's model) cools only that family on + // the account; every other 429 cools the whole account, as before. Its reset is the unified one. + const header = (name: string) => rateLimitHeaders?.get(`anthropic-ratelimit-unified-${name}`)?.trim() || undefined; + const claim = header("representative-claim"); + const requestFamily = anthropicModelFamily(modelId); + const family = requestFamily !== undefined && claim === `seven_day_${requestFamily}` ? requestFamily : undefined; const parsedRetry = parseRetryAfterMs(retryAfterHeader, now); - const resetDerived = parsedRetry === undefined ? parseRateLimitResetMs(rateLimitHeaders, now) : undefined; + const resetDerived = parsedRetry !== undefined ? undefined + : family ? delayUntil(Number(header("reset")) * 1000, now) : parseRateLimitResetMs(rateLimitHeaders, now); const cooldownMs = parsedRetry ?? resetDerived ?? DEFAULT_COOLDOWN_MS; - upstreamHealth.set(failedAccountId, { - cooldownUntil: now + cooldownMs, - cooldownSource: parsedRetry !== undefined - ? "retry-after" - : resetDerived !== undefined ? "reset-derived" : "default", - }); + const cooldownSource = parsedRetry !== undefined ? "retry-after" : resetDerived !== undefined ? "reset-derived" : "default"; + const failover = isAnthropicAccountPoolEnabled(config) || hasAnthropicFailoverQuorum(now); + // Which limit refused is only in these headers: log them on every 429 (no credential is among them). + console.warn(`[anthropic-pool] 429 on ${formatAnthropicAccountOrdinal(failedAccountId)} model=${modelId ?? "-"}` + + ` claim=${claim ?? "-"} status=${header("status") ?? "-"} 5h=${header("5h-status") ?? "-"} 7d=${header("7d-status") ?? "-"}` + + ` retry-after=${retryAfterHeader?.trim() || "-"} reset=${header("reset") ?? "-"}` + + (failover ? ` cooldown=${Math.ceil(cooldownMs / 1000)}s (${cooldownSource}) scope=${family ?? "account"}` : " cooldown=none (no failover pool)")); + if (!failover) return null; + upstreamHealth.set(family ? familyKey(failedAccountId, family) : failedAccountId, { cooldownUntil: now + cooldownMs, cooldownSource }); sweepExpiredOnWrite(now); // Unbind only the session that hit the 429; others on the account move on their own next call. const key = normalizeAffinityComponent(sessionKey); @@ -772,13 +799,18 @@ export function rotateAnthropicAccountOn429( // because those dormant values remain in config. The quota picker is the neutral // recovery policy already used by the default strategy. const hashRunnerUp = isAnthropicAccountPoolEnabled(config) && anthropicPoolStrategy(config) === "round-robin" - ? sessionHashAccount(key, getEligibleAnthropicAccounts(now).filter(id => id !== failedAccountId)) + ? sessionHashAccount(key, getEligibleAnthropicAccounts(now, requestFamily).filter(id => id !== failedAccountId)) : null; const next = isAnthropicAccountPoolEnabled(config) - ? hashRunnerUp ?? pickAlternateAnthropicAccount(config, failedAccountId, now) - : pickLowestUsage(config, failedAccountId, now); + ? hashRunnerUp ?? pickAlternateAnthropicAccount(config, failedAccountId, now, requestFamily) + : pickLowestUsage(config, failedAccountId, now, requestFamily); if (!next) { - console.warn("[anthropic-pool] all eligible Anthropic OAuth accounts are in cooldown; returning 429"); + // Not only cooldowns: an account that needs re-auth or holds no usable credential is not eligible either. + const others = getAccountSet(PROVIDER)?.accounts.filter(a => a.id !== failedAccountId) ?? []; + console.warn("[anthropic-pool] no other eligible Anthropic OAuth account; returning 429" + + ` (others=${others.length} cooled=${others.filter(a => isCooled(a.id, now, requestFamily)).length}` + + ` reauth=${others.filter(a => a.needsReauth === true).length}` + + ` unusable=${others.filter(a => !isPoolCredentialUsable(a.id, now)).length})`); return null; } diff --git a/src/server/claude-messages.ts b/src/server/claude-messages.ts index 9b5a5d9df06..d9ba0bdddc4 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -85,6 +85,7 @@ import { captureOAuthAccountSelection } from "../oauth/store"; import { anthropicSessionKeyFromParts, getAnthropicPoolAccessSnapshot, + anthropicModelFamily, getAnthropicPoolRetryAfterSeconds, isAnthropicAccountPoolEnabled, promoteAnthropicActiveAccount, @@ -1769,10 +1770,10 @@ export async function handleClaudeCountTokens( : null, promptCacheKeyIsSharedCohort: translated.cacheKeySource === "system", }); - const selection = resolveAnthropicAccountForSession(sessionKey, config); + const selection = resolveAnthropicAccountForSession(sessionKey, config, Date.now(), route.modelId); if (!selection.accountId) { if (selection.reason === "all-cooled") { - const retryAfter = getAnthropicPoolRetryAfterSeconds(); + const retryAfter = getAnthropicPoolRetryAfterSeconds(Date.now(), anthropicModelFamily(route.modelId)); const response = anthropicErrorResponse( 429, "All Anthropic OAuth accounts are temporarily rate-limited", diff --git a/src/server/responses/adapter-continuation.ts b/src/server/responses/adapter-continuation.ts index 37c0c868c28..19d56b6711a 100644 --- a/src/server/responses/adapter-continuation.ts +++ b/src/server/responses/adapter-continuation.ts @@ -397,6 +397,7 @@ export function createAdapterContinuations( anthropicSessionKey, Date.now(), response.headers, + route.modelId, ); if (nextAccountId) { try { void response.body?.cancel().catch(() => {}); } catch { /* already closed */ } diff --git a/src/server/responses/adapter-dispatch.ts b/src/server/responses/adapter-dispatch.ts index 3f098095fd4..1c4c0592aa6 100644 --- a/src/server/responses/adapter-dispatch.ts +++ b/src/server/responses/adapter-dispatch.ts @@ -876,6 +876,7 @@ export async function prepareAdapterExchange( anthropicSessionKey, Date.now(), upstreamResponse.headers, + route.modelId, ); if (!nextAccountId) break; try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ } diff --git a/src/server/responses/request-transport.ts b/src/server/responses/request-transport.ts index 853e1a61266..8aca8e7f8c6 100644 --- a/src/server/responses/request-transport.ts +++ b/src/server/responses/request-transport.ts @@ -17,6 +17,7 @@ import { formatAnthropicProviderForLog, anthropicSessionKeyFromParts, resolveAnthropicAccountForSession, + anthropicModelFamily, getAnthropicPoolRetryAfterSeconds, hasAnthropicFailoverQuorum, } from "../../oauth/anthropic-routing"; @@ -534,10 +535,10 @@ export async function prepareResponsesTransport( } else genericFailoverAccountId = admitted.accountId; if (hasPassiveAccountQuota(route.providerName)) passiveQuotaWriterGeneration = captureConfigGeneration(); } else if (route.providerName === "anthropic" && isAnthropicAccountPoolEnabled(config)) { - const selection = resolveAnthropicAccountForSession(anthropicSessionKey, config); + const selection = resolveAnthropicAccountForSession(anthropicSessionKey, config, Date.now(), route.modelId); if (!selection.accountId) { if (selection.reason === "all-cooled") { - const retryAfterSec = getAnthropicPoolRetryAfterSeconds(); + const retryAfterSec = getAnthropicPoolRetryAfterSeconds(Date.now(), anthropicModelFamily(route.modelId)); return formatErrorResponse( 429, "rate_limit_error", diff --git a/src/server/responses/sidecar-execution.ts b/src/server/responses/sidecar-execution.ts index dcfd225dd66..4cca928cf4b 100644 --- a/src/server/responses/sidecar-execution.ts +++ b/src/server/responses/sidecar-execution.ts @@ -243,6 +243,7 @@ export async function executeResponsesSidecars( anthropicSessionKey, Date.now(), responseHeaders, + route.modelId, ); if (!nextAccountId) { hop.permit?.release(); diff --git a/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts b/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts index f1ad70542ea..02168b9ac83 100644 --- a/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts +++ b/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts @@ -4,10 +4,13 @@ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { + anthropicModelFamily, clearAnthropicAccountCooldown, clearAnthropicAccountPoolState, forgetAnthropicFailoverQuorum, getAnthropicAccountHealthSnapshot, + getAnthropicPoolRetryAfterSeconds, + getEligibleAnthropicAccounts, rotateAnthropicAccountOn429, resetAnthropicRoutingForManualSelection, resolveAnthropicAccountForSession, @@ -103,6 +106,50 @@ function drainedFiveHour(resetEpochSeconds: number): Headers { }); } +describe("a model-scoped weekly 429 cools only that model family", () => { + /** A seven_day_opus refusal: the account's Opus allowance is spent, its other models are not. */ + const opusWeekly = (resetEpochSeconds: number) => new Headers({ + "anthropic-ratelimit-unified-status": "rejected", + "anthropic-ratelimit-unified-representative-claim": "seven_day_opus", + "anthropic-ratelimit-unified-reset": String(resetEpochSeconds), + "anthropic-ratelimit-unified-5h-status": "allowed", + "anthropic-ratelimit-unified-7d-status": "allowed", + }); + + test("Opus cools per account, Sonnet keeps the account, and every 429 logs its limit headers", async () => { + const start = Date.now(); + const ids = await seed(2); + const reset = Math.floor(start / 1000) + 3 * 86_400; + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, null, "s1", start, opusWeekly(reset), "claude-opus-5")).toBe(ids[1]!); + expect(warn.mock.calls.map(c => String(c[0])).find(l => l.startsWith("[anthropic-pool] 429 on "))).toEndWith( + " model=claude-opus-5 claim=seven_day_opus status=rejected 5h=allowed 7d=allowed" + + ` retry-after=- reset=${reset} cooldown=${3 * 86_400}s (reset-derived) scope=opus`); + } finally { warn.mockRestore(); } + expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)).toBeNull(); + expect(getEligibleAnthropicAccounts(start, "opus")).toEqual([ids[1]!]); + expect(getEligibleAnthropicAccounts(start, "sonnet")).toEqual(ids); + + // Both accounts out of Opus: an Opus request is refused with the family's reset, a Sonnet one still routes. + rotateAnthropicAccountOn429(poolEnabled(), ids[1]!, null, "s2", start, opusWeekly(reset), "claude-opus-5"); + expect(resolveAnthropicAccountForSession("s3", poolEnabled(), start, "claude-opus-5").reason).toBe("all-cooled"); + expect(getAnthropicPoolRetryAfterSeconds(start, anthropicModelFamily("claude-opus-5"))).toBe(3 * 86_400); + expect(resolveAnthropicAccountForSession("s4", poolEnabled(), start, "claude-sonnet-5-5").accountId).not.toBeNull(); + clearAnthropicAccountCooldown(ids[0]!); + expect(getEligibleAnthropicAccounts(start, "opus")).toEqual([ids[0]!]); + }); + + test("a five-hour claim on an Opus request still cools the whole account", async () => { + const start = Date.now(); + const ids = await seed(2); + rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, "120", null, start, + new Headers({ "anthropic-ratelimit-unified-representative-claim": "five_hour" }), "claude-opus-5"); + expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)?.cooldownUntil).toBe(start + 120_000); + expect(getEligibleAnthropicAccounts(start, "sonnet")).toEqual([ids[1]!]); + }); +}); + describe("Anthropic cooldown honours the stated window", () => { test("a multi-hour Retry-After is not truncated to the guessed-backoff ceiling", async () => { const start = Date.now(); From ab1707b1a35069b9c18186849c34610fc4c46d59 Mon Sep 17 00:00:00 2001 From: Vadym O Date: Tue, 10 Nov 2026 22:24:03 +0800 Subject: [PATCH 2/4] chore(release): 2.65.0-vadymhimself.18 Co-Authored-By: Claude Code --- desktop/src-tauri/Cargo.lock | 2 +- desktop/src-tauri/Cargo.toml | 2 +- desktop/src-tauri/tauri.conf.json | 2 +- package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 6e8ab282aa7..e7e7510e298 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -2541,7 +2541,7 @@ dependencies = [ [[package]] name = "opencodex-desktop" -version = "2.65.0-vadymhimself.17" +version = "2.65.0-vadymhimself.18" dependencies = [ "dbus", "reqwest 0.12.24", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index ada4bc86270..52c49a7e4fe 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodex-desktop" -version = "2.65.0-vadymhimself.17" +version = "2.65.0-vadymhimself.18" description = "OpenCodex desktop shell" authors = ["OpenCodex contributors"] license = "MIT" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 58e1a8da69c..f071b2f8bc2 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCodex", - "version": "2.65.0-vadymhimself.17", + "version": "2.65.0-vadymhimself.18", "identifier": "com.opencodex.desktop", "build": { "frontendDist": "../ui", diff --git a/package.json b/package.json index 6e6dfb67219..1a5577b2d5f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.65.0-vadymhimself.17", + "version": "2.65.0-vadymhimself.18", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", From a8344a0997b0e3011e5962a6ebd600c06e8bb490 Mon Sep 17 00:00:00 2001 From: Vadym O Date: Tue, 10 Nov 2026 22:25:07 +0800 Subject: [PATCH 3/4] fix(anthropic-pool): log every anthropic-ratelimit-unified-* header and the cooldown end on each 429 Co-Authored-By: Claude Code --- src/oauth/anthropic-routing.ts | 13 +++++++++---- .../anthropic/anthropic-ratelimit-headers.test.ts | 5 +++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/oauth/anthropic-routing.ts b/src/oauth/anthropic-routing.ts index ae94e3b289b..284ba7899b1 100644 --- a/src/oauth/anthropic-routing.ts +++ b/src/oauth/anthropic-routing.ts @@ -776,11 +776,16 @@ export function rotateAnthropicAccountOn429( const cooldownMs = parsedRetry ?? resetDerived ?? DEFAULT_COOLDOWN_MS; const cooldownSource = parsedRetry !== undefined ? "retry-after" : resetDerived !== undefined ? "reset-derived" : "default"; const failover = isAnthropicAccountPoolEnabled(config) || hasAnthropicFailoverQuorum(now); - // Which limit refused is only in these headers: log them on every 429 (no credential is among them). + // Which limit refused is only in these headers: log every unified one on every 429 (no credential is among them). + const unified: string[] = []; + (rateLimitHeaders as Headers | null | undefined)?.forEach?.((value, name) => { + if (name.startsWith("anthropic-ratelimit-unified-")) unified.push(`${name.slice(28)}=${value}`); + }); console.warn(`[anthropic-pool] 429 on ${formatAnthropicAccountOrdinal(failedAccountId)} model=${modelId ?? "-"}` - + ` claim=${claim ?? "-"} status=${header("status") ?? "-"} 5h=${header("5h-status") ?? "-"} 7d=${header("7d-status") ?? "-"}` - + ` retry-after=${retryAfterHeader?.trim() || "-"} reset=${header("reset") ?? "-"}` - + (failover ? ` cooldown=${Math.ceil(cooldownMs / 1000)}s (${cooldownSource}) scope=${family ?? "account"}` : " cooldown=none (no failover pool)")); + + ` retry-after=${retryAfterHeader?.trim() || "-"} ${unified.join(" ") || "unified=-"}` + + (failover + ? ` cooldown=${Math.ceil(cooldownMs / 1000)}s until ${new Date(now + cooldownMs).toISOString()} (${cooldownSource}) scope=${family ?? "account"}` + : " cooldown=none (no failover pool)")); if (!failover) return null; upstreamHealth.set(family ? familyKey(failedAccountId, family) : failedAccountId, { cooldownUntil: now + cooldownMs, cooldownSource }); sweepExpiredOnWrite(now); diff --git a/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts b/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts index 02168b9ac83..28b634cbd90 100644 --- a/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts +++ b/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts @@ -124,8 +124,9 @@ describe("a model-scoped weekly 429 cools only that model family", () => { try { expect(rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, null, "s1", start, opusWeekly(reset), "claude-opus-5")).toBe(ids[1]!); expect(warn.mock.calls.map(c => String(c[0])).find(l => l.startsWith("[anthropic-pool] 429 on "))).toEndWith( - " model=claude-opus-5 claim=seven_day_opus status=rejected 5h=allowed 7d=allowed" - + ` retry-after=- reset=${reset} cooldown=${3 * 86_400}s (reset-derived) scope=opus`); + " model=claude-opus-5 retry-after=- 5h-status=allowed 7d-status=allowed representative-claim=seven_day_opus" + + ` reset=${reset} status=rejected cooldown=${3 * 86_400}s until ${new Date(reset * 1000).toISOString()}` + + " (reset-derived) scope=opus"); } finally { warn.mockRestore(); } expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)).toBeNull(); expect(getEligibleAnthropicAccounts(start, "opus")).toEqual([ids[1]!]); From 6ce8af987c562f03fa2dfd55542ecef09f062ae2 Mon Sep 17 00:00:00 2001 From: Vadym O Date: Tue, 10 Nov 2026 22:33:04 +0800 Subject: [PATCH 4/4] test(pin): count only real 429 failovers, not the per-429 diagnostic line The 429 log line now prints on every 429 (pinned included), so the pin e2e counts the '; failing over to' line that only a real account switch prints. Co-Authored-By: Claude Code --- tests/server/agentradar-account-pin-e2e.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/server/agentradar-account-pin-e2e.test.ts b/tests/server/agentradar-account-pin-e2e.test.ts index 59198fd1774..04a7b96bdca 100644 --- a/tests/server/agentradar-account-pin-e2e.test.ts +++ b/tests/server/agentradar-account-pin-e2e.test.ts @@ -167,7 +167,7 @@ test("an AgentRadar account pin serves exactly its own stored account (pin.check codexAccounts: [1, 2].map(n => ({ id: `acct${n}`, email: `c${n}@example.invalid`, isMain: false, chatgptAccountId: `cga${n}` })), }); const rotations = () => ocx.log.split("[anthropic-pool] credential denial on").length - 1; - const failovers429 = () => ocx.log.split("[anthropic-pool] 429 on").length - 1; + const failovers429 = () => ocx.log.split("; failing over to").length - 1; try { // Claude: unpinned control serves the active account; a pin serves exactly its own, both ways, and names it. let r = await msg(ocx);