diff --git a/src/oauth/anthropic-routing.ts b/src/oauth/anthropic-routing.ts index 78f12cad9e6..8b63fb5adc0 100644 --- a/src/oauth/anthropic-routing.ts +++ b/src/oauth/anthropic-routing.ts @@ -20,7 +20,8 @@ import { createHash } from "node:crypto"; import { captureOAuthAccountSelection, commitOAuthAccountSelection, credentialGeneration, getAccountSet, getAccountCredential, getAccountCredentialWithStatus, markAccountNeedsReauthIfGeneration } from "./store"; import type { OAuthAccessSnapshot } from "./index"; -import { getCachedProviderAccountQuota } from "../providers/quota"; +import { fetchAccountQuota, getCachedProviderAccountQuota } from "../providers/quota"; +import { recordAnthropicWeeklyExhausted } from "../providers/quota/account-cache"; import { fallbackCodexAccountLogLabel } from "../codex/account-label"; import { normalizeAccountPoolStickyLimit, @@ -212,6 +213,7 @@ export function clearAnthropicAccountPoolState(): void { sessionAffinity.clear(); manualPreference = undefined; quorumCache = null; + weeklyReadingInflight.clear(); } export function anthropicSessionAffinitySizeForTests(): number { @@ -228,9 +230,27 @@ export function anthropicModelFamily(modelId: string | null | undefined): string const familyKey = (accountId: string, family: string) => `${accountId}\0${family}`; +/** + * The reset of an account's spent seven-day window, when the cached reading says it is at 100% and the reset + * is still ahead. A reading with no reset proves nothing about when the account serves again, so it does not + * count: unknown stays unknown and fails open. + * + * The cooldown map above is per process, and a short-lived instance starts empty, so it cannot know a window a + * previous instance already saw spent. The quota cache can (response headers, the usage probe, the disk + * snapshot), which is why this lives beside the cooldown instead of in it. + */ +function weeklyExhaustedUntil(accountId: string, now: number): number | undefined { + const quota = getCachedProviderAccountQuota(PROVIDER, accountId); + const resetAt = quota?.weeklyResetAt; + return typeof quota?.weeklyPercent === "number" && quota.weeklyPercent >= 100 + && typeof resetAt === "number" && resetAt > now ? resetAt : undefined; +} + +/** Single gate for every pick: cooled (account or family) or known to have spent its seven-day window. */ function isCooled(accountId: string, now: number, family?: string): boolean { return getAnthropicAccountHealthSnapshot(accountId, now) !== null - || (family !== undefined && getAnthropicAccountHealthSnapshot(familyKey(accountId, family), now) !== null); + || (family !== undefined && getAnthropicAccountHealthSnapshot(familyKey(accountId, family), now) !== null) + || weeklyExhaustedUntil(accountId, now) !== undefined; } function fiveHourKnown(accountId: string): boolean { @@ -299,6 +319,70 @@ function isPoolCredentialUsable(accountId: string, now: number): boolean { setComboPoolEligibilityProbe((provider, now) => provider === PROVIDER && getEligibleAnthropicAccounts(now).length > 0); +/** Longest a pick waits for a usage reading. A slow or failing probe must never hold a request. */ +const WEEKLY_READING_TIMEOUT_MS = 1_500; + +type WeeklyReadingProbe = (accountId: string) => Promise; +/** OCX_DISABLE_POOL_WEEKLY_PROBE=1 (the test preload sets it) turns the live read off; an injected probe still runs. */ +const defaultWeeklyReadingProbe: WeeklyReadingProbe = accountId => + process.env.OCX_DISABLE_POOL_WEEKLY_PROBE === "1" ? Promise.resolve(null) : fetchAccountQuota(PROVIDER, accountId, false); +let weeklyReadingProbe: WeeklyReadingProbe = defaultWeeklyReadingProbe; +const weeklyReadingInflight = new Map>(); + +/** Test seam: replace the per-account usage probe; call with no argument to restore it. */ +export function setAnthropicWeeklyReadingProbeForTests(probe?: WeeklyReadingProbe): void { + weeklyReadingProbe = probe ?? defaultWeeklyReadingProbe; + weeklyReadingInflight.clear(); +} + +/** + * Give an account with no cached weekly reading one chance to get one, so a fresh instance does not route onto + * an account whose seven-day window is already spent. Lazy by design: only the account about to be picked is + * read, never the roster, so a cold start costs at most one usage call per account per cache TTL (the probe's + * own 10-minute cache and in-flight de-duplication apply, and parallel callers share one promise here too). + * Waits at most WEEKLY_READING_TIMEOUT_MS and never throws: on timeout or error the reading stays unknown and + * the account stays pickable (a probe that outlives the wait still fills the cache for the next pick). + */ +export async function ensureAnthropicWeeklyReading(_config: OcxConfig, accountId: string): Promise { + if (weeklyKnown(accountId)) return; + let flight = weeklyReadingInflight.get(accountId); + if (!flight) { + flight = (async () => { + let timer: ReturnType | undefined; + try { + await Promise.race([ + Promise.resolve().then(() => weeklyReadingProbe(accountId)), + new Promise(resolve => { timer = setTimeout(resolve, WEEKLY_READING_TIMEOUT_MS); }), + ]); + } catch { /* fail open: unknown stays unknown */ } + finally { if (timer) clearTimeout(timer); } + })().finally(() => { if (weeklyReadingInflight.get(accountId) === flight) weeklyReadingInflight.delete(accountId); }); + weeklyReadingInflight.set(accountId, flight); + } + await flight; +} + +/** + * `resolveAnthropicAccountForSession` for async callers: if the picked account has no weekly reading, read it + * once, and if it turns out spent, resolve once more (the gate now excludes it). At most one extra probe per pick. + */ +export async function resolveAnthropicAccountForSessionWithReading( + sessionKey: string | null | undefined, + config: OcxConfig, + now = Date.now(), + modelId?: string | null, +): Promise { + let selection = resolveAnthropicAccountForSession(sessionKey, config, now, modelId); + if (!selection.accountId || !isAnthropicAccountPoolEnabled(config) || weeklyKnown(selection.accountId)) return selection; + // With fewer than two eligible accounts a re-pick has nowhere else to go, so the probe would be wasted. + if (getEligibleAnthropicAccounts(now, anthropicModelFamily(modelId)).length < 2) return selection; + await ensureAnthropicWeeklyReading(config, selection.accountId); + if (weeklyExhaustedUntil(selection.accountId, Date.now()) !== undefined) { + selection = resolveAnthropicAccountForSession(sessionKey, config, Date.now(), modelId); + } + return selection; +} + export function getEligibleAnthropicAccounts(now = Date.now(), family?: string): string[] { const set = getAccountSet(PROVIDER); if (!set) return []; @@ -383,15 +467,17 @@ export function forgetAnthropicFailoverQuorum(): void { quorumCache = null; } -/** Earliest remaining cooldown among cooled Anthropic accounts, for client Retry-After. */ +/** Earliest remaining cooldown or weekly reset among unavailable Anthropic accounts, for client Retry-After. */ 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) { // An account serves again only once both its own and its family's cooldown are over. + // A spent seven-day window counts the same way: the account serves again at its weekly reset. const until = Math.max(getAnthropicAccountHealthSnapshot(account.id, now)?.cooldownUntil ?? 0, - family ? getAnthropicAccountHealthSnapshot(familyKey(account.id, family), now)?.cooldownUntil ?? 0 : 0); + family ? getAnthropicAccountHealthSnapshot(familyKey(account.id, family), now)?.cooldownUntil ?? 0 : 0, + weeklyExhaustedUntil(account.id, now) ?? 0); if (!until) continue; if (earliest === null || until < earliest) earliest = until; } @@ -406,6 +492,8 @@ interface ScoredAccount { fiveHourTieBreak: number; /** True only under the opt-in weekly window; see compareScoredAccounts. */ knownFirst: boolean; + /** Weekly window only: a known 100% is a spent account and ranks behind an unknown reading. */ + spentLast: boolean; } function compareScoredAccounts(a: ScoredAccount, b: ScoredAccount): number { @@ -414,6 +502,12 @@ function compareScoredAccounts(a: ScoredAccount, b: ScoredAccount): number { // never opted in: an account measured at 100% would sort ahead of an unmeasured one purely // because it had a reading. The accepted scope preserves the five-hour default exactly. if (a.knownFirst && b.knownFirst && a.hasKnownUsage !== b.hasKnownUsage) { + // Under the weekly window a known 100% is a spent account, not a preferred one: an unknown reading + // (it may well have room) ranks before it. Every other known reading still outranks unknown. + if (a.spentLast && b.spentLast) { + const known = a.hasKnownUsage ? a : b; + if (known.score >= 100) return a.hasKnownUsage ? 1 : -1; + } return a.hasKnownUsage ? -1 : 1; } return a.score - b.score || a.fiveHourTieBreak - b.fiveHourTieBreak; @@ -433,6 +527,7 @@ function pickLowestUsage(config: OcxConfig, excludeId: string | undefined, now: // Every window EXCEPT the legacy five-hour default is an explicit opt-in, so // known-before-unknown applies to all of them and to none of the default path. knownFirst: window !== "five-hour", + spentLast: window === "weekly", })); let best = scored[0]!; for (let i = 1; i < scored.length; i++) { @@ -815,6 +910,12 @@ export function rotateAnthropicAccountOn429( if (limited) { upstreamHealth.set(family ? familyKey(failedAccountId, family) : failedAccountId, { cooldownUntil: now + cooldownMs, cooldownSource }); sweepExpiredOnWrite(now); + // A rejected seven-day window also goes into the quota cache as 100% until its reset: the cooldown above is + // per process, the cache is what every pick (and a restarted instance, via the disk snapshot) consults. + const weeklyReset = Number(header("7d-reset")); + if (!family && header("7d-status") === "rejected" && Number.isFinite(weeklyReset) && weeklyReset > 0) { + recordAnthropicWeeklyExhausted(failedAccountId, weeklyReset * 1000, now); + } } // Unbind only the session that hit the 429; others on the account move on their own next call. const key = normalizeAffinityComponent(sessionKey); diff --git a/src/providers/quota.ts b/src/providers/quota.ts index e02447ffb08..289fc465122 100644 --- a/src/providers/quota.ts +++ b/src/providers/quota.ts @@ -414,8 +414,8 @@ async function fetchExplicitCurrentQuota(provider: string, config: OcxProviderCo return read.result; } - -async function fetchAccountQuota( +/** One account's reading through the 10-minute cache and in-flight de-dup; routing reads a single account lazily. */ +export async function fetchAccountQuota( provider: string, accountId: string, forceRefresh: boolean, diff --git a/src/providers/quota/account-cache.ts b/src/providers/quota/account-cache.ts index 93c437a61df..2961b9b3f21 100644 --- a/src/providers/quota/account-cache.ts +++ b/src/providers/quota/account-cache.ts @@ -250,6 +250,27 @@ export function recordAnthropicAccountQuotaFromHeaders( persistAccountQuotaCache(); } +/** + * A seven-day 429 names the reset of the window it just spent. Record the account's weekly reading as 100% + * until that reset, so routing (which reads this cache) stops picking it, in this process and, through the + * disk snapshot, in a restarted one. The header recorder above does this too whenever upstream sends the + * utilization header; a rejected 429 may omit it, which is the case this covers. Keeps every other window. + */ +export function recordAnthropicWeeklyExhausted(accountId: string, weeklyResetAt: number, now = Date.now()): void { + if (!accountId || !Number.isFinite(weeklyResetAt) || weeklyResetAt <= now) return; + hydrateAccountQuotaCache(); + const key = accountCacheKey("anthropic", accountId); + const previous = accountQuotaCache.get(key); + accountQuotaCache.set(key, { + ...previous, + ts: previous?.ts ?? 0, + quota: normalizeAnthropicQuota({ + ...normalizeAnthropicQuota(previous?.quota, now), weeklyPercent: 100, weeklyResetAt, updatedAt: now, + }, now), + }); + persistAccountQuotaCache(); +} + /** * Providers whose per-account quota is OBSERVED in-band, never probed. * diff --git a/src/server/claude-messages.ts b/src/server/claude-messages.ts index 57322b37f46..7ce14108f19 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -90,7 +90,7 @@ import { getAnthropicPoolRetryAfterSeconds, isAnthropicAccountPoolEnabled, promoteAnthropicActiveAccount, - resolveAnthropicAccountForSession, + resolveAnthropicAccountForSessionWithReading, } from "../oauth/anthropic-routing"; import type { OcxConfig } from "../types"; import { readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress"; @@ -1774,7 +1774,7 @@ export async function handleClaudeCountTokens( : null, promptCacheKeyIsSharedCohort: translated.cacheKeySource === "system", }); - const selection = resolveAnthropicAccountForSession(sessionKey, config, Date.now(), route.modelId); + const selection = await resolveAnthropicAccountForSessionWithReading(sessionKey, config, Date.now(), route.modelId); if (!selection.accountId) { if (selection.reason === "all-cooled") { const retryAfter = getAnthropicPoolRetryAfterSeconds(Date.now(), anthropicModelFamily(route.modelId)); diff --git a/src/server/responses/request-transport.ts b/src/server/responses/request-transport.ts index 8aca8e7f8c6..5dae51a9bdb 100644 --- a/src/server/responses/request-transport.ts +++ b/src/server/responses/request-transport.ts @@ -16,7 +16,7 @@ import { commitAnthropicSelectionRouting, formatAnthropicProviderForLog, anthropicSessionKeyFromParts, - resolveAnthropicAccountForSession, + resolveAnthropicAccountForSessionWithReading, anthropicModelFamily, getAnthropicPoolRetryAfterSeconds, hasAnthropicFailoverQuorum, @@ -535,7 +535,7 @@ 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, Date.now(), route.modelId); + const selection = await resolveAnthropicAccountForSessionWithReading(anthropicSessionKey, config, Date.now(), route.modelId); if (!selection.accountId) { if (selection.reason === "all-cooled") { const retryAfterSec = getAnthropicPoolRetryAfterSeconds(Date.now(), anthropicModelFamily(route.modelId)); diff --git a/tests/adapters/anthropic/anthropic-account-pool.test.ts b/tests/adapters/anthropic/anthropic-account-pool.test.ts index dedf9297a81..27d419c5cef 100644 --- a/tests/adapters/anthropic/anthropic-account-pool.test.ts +++ b/tests/adapters/anthropic/anthropic-account-pool.test.ts @@ -15,6 +15,9 @@ import { normalizeAccountPoolQuotaWindow, parseAccountPoolQuotaWindow, resolveAnthropicAccountForSession, + resolveAnthropicAccountForSessionWithReading, + setAnthropicWeeklyReadingProbeForTests, + getAnthropicPoolRetryAfterSeconds, resetAnthropicRoutingForManualSelection, rotateAnthropicAccountOn429, getAnthropicPoolAccessSnapshot, @@ -61,6 +64,7 @@ beforeEach(() => { }); afterEach(() => { + setAnthropicWeeklyReadingProbeForTests(); clearAnthropicAccountPoolState(); clearPoolRotationState(); clearAccountQuotaCache("anthropic"); @@ -660,13 +664,14 @@ describe("anthropic account pool quota window scoring", () => { expect(resolveAnthropicAccountForSession("weekly-unknown-last", cfg(true, 80, { quotaWindow: "weekly" })).accountId).toBe(aId); }); - test("weekly mode ranks known 100% before unknown weekly usage", async () => { + test("weekly mode ranks unknown weekly usage before a known 100%", async () => { + // Was "known 100% before unknown": a spent account outranking one that may have room is inverted. const { aId, bId } = await seedTwoAccounts(); const updatedAt = Date.now(); setCachedProviderAccountQuotaForTests("anthropic", aId, { fiveHourPercent: 90, weeklyPercent: 100, updatedAt }); setCachedProviderAccountQuotaForTests("anthropic", bId, { fiveHourPercent: 0, updatedAt }); - expect(resolveAnthropicAccountForSession("weekly-known-100-before-unknown", cfg(true, 80, { quotaWindow: "weekly" })).accountId).toBe(aId); + expect(resolveAnthropicAccountForSession("weekly-known-100-before-unknown", cfg(true, 80, { quotaWindow: "weekly" })).accountId).toBe(bId); }); test("weekly tie breaks by lower five-hour usage", async () => { @@ -779,13 +784,15 @@ describe("anthropic account pool quota window scoring", () => { test("429 failover never returns null while any eligible account remains", async () => { const { aId, bId } = await seedTwoAccounts(); + // B is known spent for the week with its reset still ahead, so it is not eligible (was: still returned). setCachedProviderAccountQuotaForTests("anthropic", bId, { fiveHourPercent: 100, weeklyPercent: 100, + weeklyResetAt: Date.now() + 2 * 86_400_000, updatedAt: Date.now(), }); - expect(rotateAnthropicAccountOn429(cfg(true, 80, { quotaWindow: "weekly" }), aId, "30", "weekly-never-null")).toBe(bId); + expect(rotateAnthropicAccountOn429(cfg(true, 80, { quotaWindow: "weekly" }), aId, "30", "weekly-never-null")).toBeNull(); }); test("fill-first threshold uses configured window", async () => { @@ -856,3 +863,107 @@ describe("anthropic account pool quota window scoring", () => { expect(rotateAnthropicAccountOn429(config, aId, "30", "weekly-empty-failover")).toBe(bId); }); }); + + +describe("weekly-spent accounts across fresh instances", () => { + const rrConfig = () => cfg(true, 80, { strategy: "round-robin" }); + const dayAhead = () => Date.now() + 86_400_000; + /** What a new instance looks like: no cooldowns, affinity or ring, the stored selection admitted first. */ + async function freshInstance() { + clearAnthropicAccountPoolState(); + clearPoolRotationState(); + await admitAnthropic("", cfg(false)); + } + + test("a fresh instance never picks an account whose weekly window is spent (hash, affinity, active)", async () => { + const { aId, bId } = await seedTwoAccounts(); + // Admit the stored selection first: the gate (rightly) refuses to promote an account already known spent. + await freshInstance(); + setCachedProviderAccountQuotaForTests("anthropic", aId, { weeklyPercent: 100, weeklyResetAt: dayAhead(), updatedAt: Date.now() }); + setCachedProviderAccountQuotaForTests("anthropic", bId, { weeklyPercent: 20, weeklyResetAt: dayAhead(), updatedAt: Date.now() }); + + // Hash seats: without the gate about half of these keys land on A. + for (let i = 0; i < 40; i++) expect(resolveAnthropicAccountForSession(`s${i}`, rrConfig()).accountId).toBe(bId); + // Affinity bound to A (as a previous request in this process could have) is dropped, not honoured. + bindAnthropicSessionAffinity("bound", aId); + expect(resolveAnthropicAccountForSession("bound", cfg(true, 80)).accountId).toBe(bId); + // The stored active account is A: an unkeyed request must not stay on it. + expect(getAccountSet("anthropic")!.activeAccountId).toBe(aId); + expect(resolveAnthropicAccountForSession(null, rrConfig()).accountId).toBe(bId); + }); + + test("an account with no reading is read once, and a spent one is replaced, even for parallel picks", async () => { + const { aId, bId } = await seedTwoAccounts(); + let key = ""; + for (let i = 0; !key && i < 200; i++) { + if (resolveAnthropicAccountForSession(`probe-${i}`, rrConfig()).accountId === aId) key = `probe-${i}`; + } + expect(key).not.toBe(""); + await freshInstance(); + const calls: string[] = []; + setAnthropicWeeklyReadingProbeForTests(async id => { + calls.push(id); + await Bun.sleep(5); + setCachedProviderAccountQuotaForTests("anthropic", id, { weeklyPercent: 100, weeklyResetAt: dayAhead(), updatedAt: Date.now() }); + }); + + const picks = await Promise.all([ + resolveAnthropicAccountForSessionWithReading(key, rrConfig()), + resolveAnthropicAccountForSessionWithReading(key, rrConfig()), + ]); + expect(picks.map(pick => pick.accountId)).toEqual([bId, bId]); + expect(calls).toEqual([aId]); + }); + + test("with a single eligible account the probe is never called", async () => { + const { aId, bId } = await seedTwoAccounts(); + expect(rotateAnthropicAccountOn429(cfg(true, 80), bId, "600", null)).toBe(aId); + let calls = 0; + setAnthropicWeeklyReadingProbeForTests(async () => { calls++; }); + expect(getEligibleAnthropicAccounts()).toEqual([aId]); + expect((await resolveAnthropicAccountForSessionWithReading("solo", cfg(true, 80))).accountId).toBe(aId); + expect(calls).toBe(0); + }); + + test("a probe that throws or never answers fails open and does not throw", async () => { + const { aId } = await seedTwoAccounts(); + let key = ""; + for (let i = 0; !key && i < 200; i++) { + if (resolveAnthropicAccountForSession(`open-${i}`, rrConfig()).accountId === aId) key = `open-${i}`; + } + await freshInstance(); + setAnthropicWeeklyReadingProbeForTests(async () => { throw new Error("usage endpoint down"); }); + expect((await resolveAnthropicAccountForSessionWithReading(key, rrConfig())).accountId).toBe(aId); + + setAnthropicWeeklyReadingProbeForTests(() => new Promise(() => {})); + const started = Date.now(); + expect((await resolveAnthropicAccountForSessionWithReading(key, rrConfig())).accountId).toBe(aId); + expect(Date.now() - started).toBeLessThan(4_000); + }, 10_000); + + test("a seven-day 429 with the only other account known spent surfaces the 429 with the earliest weekly reset", async () => { + const { aId, bId } = await seedTwoAccounts(); + const now = Date.now(); + const aReset = now + 2 * 86_400_000; + setCachedProviderAccountQuotaForTests("anthropic", aId, { weeklyPercent: 100, weeklyResetAt: aReset, updatedAt: now }); + const bResetSec = Math.ceil(now / 1000) + 3_600; + const rejected = new Headers({ + "anthropic-ratelimit-unified-status": "rejected", + "anthropic-ratelimit-unified-7d-status": "rejected", + "anthropic-ratelimit-unified-7d-reset": String(bResetSec), + }); + + expect(rotateAnthropicAccountOn429(rrConfig(), bId, null, "k", now, rejected)).toBeNull(); + expect(getEligibleAnthropicAccounts(now)).toEqual([]); + expect(getAnthropicPoolRetryAfterSeconds(now)).toBe(Math.ceil((bResetSec * 1000 - now) / 1000)); + }); + + test("Retry-After follows the earliest weekly reset when no cooldown is recorded", async () => { + const { aId, bId } = await seedTwoAccounts(); + const now = Date.now(); + setCachedProviderAccountQuotaForTests("anthropic", aId, { weeklyPercent: 100, weeklyResetAt: now + 5_000_000, updatedAt: now }); + setCachedProviderAccountQuotaForTests("anthropic", bId, { weeklyPercent: 100, weeklyResetAt: now + 9_000_000, updatedAt: now }); + expect(getAnthropicPoolRetryAfterSeconds(now)).toBe(5_000); + expect(resolveAnthropicAccountForSession("k", rrConfig(), now)).toEqual({ accountId: null, reason: "all-cooled" }); + }); +}); diff --git a/tests/preload.ts b/tests/preload.ts index cb753e45346..8c04d19982d 100644 --- a/tests/preload.ts +++ b/tests/preload.ts @@ -73,6 +73,8 @@ process.env.OCX_TEST_HOME_GUARD = "1"; // Lets a test assert one preload per process rather than assuming Bun's scheduling. process.env.OCX_TEST_PRELOAD_PID = String(process.pid); process.env.OCX_DISABLE_UPDATE_CHECK = "1"; +// The pool's live weekly-usage read would otherwise spend a test's mocked fetch responses. +process.env.OCX_DISABLE_POOL_WEEKLY_PROBE = "1"; if (!isTestHomeGuardArmed() || !protectedHomeForTests()) { throw new Error("test home guard failed to arm; refusing to run tests unprotected");