@@ -34,6 +34,12 @@ import type { OcxAccountPoolQuotaWindow, OcxAccountPoolRotationStrategy, OcxConf |
34 | 34 | import { sweepExpiredOnWrite } from "../lib/state-store-sweeper"; |
35 | 35 | import { retainedUtf8Bytes } from "../lib/admission"; |
36 | 36 | import { routeCandidates, type AnthropicRouteDecision } from "./anthropic-model-routes"; |
| 37 | +import type { ProviderQuota } from "../providers/quota-types"; |
| 38 | +import { |
| 39 | + anthropicCooldownGeneration, |
| 40 | + clearAnthropicCooldownGenerations, |
| 41 | + noteAnthropicCooldownMutation, |
| 42 | +} from "../providers/quota/anthropic-cooldown-recovery"; |
37 | 43 |
|
38 | 44 | /** |
39 | 45 | * The read side of a `Headers` object, so a caller can pass the live upstream response's |
@@ -66,10 +72,15 @@ export type AnthropicAccountPoolConfig = NonNullable<OcxConfig["anthropicAccount |
66 | 72 | * `retry-after` would report a drained five-hour window as request-rate throttling. |
67 | 73 | */ |
68 | 74 | type AnthropicCooldownSource = "retry-after" | "reset-derived" | "default"; |
| 75 | +type AnthropicQuotaWindow = "five-hour" | "weekly"; |
69 | 76 |
|
70 | 77 | interface AccountHealth { |
71 | 78 | cooldownUntil: number; |
72 | 79 | cooldownSource: AnthropicCooldownSource; |
| 80 | + /** Windows whose rejected status established a reset-derived cooldown. */ |
| 81 | + rejectedQuotaWindows?: AnthropicQuotaWindow[]; |
| 82 | + /** Monotonic fence so an older quota probe cannot erase a newer refusal. */ |
| 83 | + cooldownGeneration: number; |
73 | 84 | } |
74 | 85 |
|
75 | 86 | interface AffinityEntry { |
@@ -140,19 +151,72 @@ function parseRetryAfterMs(value: string | null | undefined, now: number): numbe |
140 | 151 | } |
141 | 152 |
|
142 | 153 | /** Only rejected windows constrain recovery; all must reopen, so take the latest reset. */ |
143 | | -function parseRateLimitResetMs(headers: AnthropicRateLimitHeaders | null | undefined, now: number): number | undefined { |
| 154 | +function parseRateLimitReset( |
| 155 | + headers: AnthropicRateLimitHeaders | null | undefined, |
| 156 | + now: number, |
| 157 | +): { delayMs: number; rejectedQuotaWindows: AnthropicQuotaWindow[] } | undefined { |
144 | 158 | if (!headers) return undefined; |
145 | 159 | let latest: number | undefined; |
146 | | - for (const window of ["5h", "7d"] as const) { |
| 160 | + const rejectedQuotaWindows: AnthropicQuotaWindow[] = []; |
| 161 | + for (const [window, quotaWindow] of [["5h", "five-hour"], ["7d", "weekly"]] as const) { |
147 | 162 | if (headers.get(`anthropic-ratelimit-unified-${window}-status`)?.trim() !== "rejected") continue; |
| 163 | + rejectedQuotaWindows.push(quotaWindow); |
148 | 164 | const resetSeconds = Number(headers.get(`anthropic-ratelimit-unified-${window}-reset`)?.trim()); |
149 | 165 | if (!Number.isFinite(resetSeconds) || resetSeconds <= 0) continue; |
150 | 166 | const resetAt = resetSeconds * 1000; |
151 | 167 | if (delayUntil(resetAt, now) === undefined) continue; |
152 | 168 | if (latest === undefined || resetAt > latest) latest = resetAt; |
153 | 169 | } |
154 | 170 | if (latest === undefined) return undefined; |
155 | | - return latest - now; |
| 171 | + return { delayMs: latest - now, rejectedQuotaWindows }; |
| 172 | +} |
| 173 | + |
| 174 | +export type AnthropicCooldownRecoveryClaim = Readonly<{ |
| 175 | + accountId: string; |
| 176 | + cooldownGeneration: number; |
| 177 | + claimedAt: number; |
| 178 | +}>; |
| 179 | + |
| 180 | +export type AnthropicCooldownRecoverySettlement = "cleared" | "retained" | "superseded"; |
| 181 | + |
| 182 | +/** |
| 183 | + * Capture the exact reset-derived refusal a fresh usage probe is allowed to recover. |
| 184 | + * |
| 185 | + * The generation fence matters because the usage request is asynchronous: a newer 429 may |
| 186 | + * arrive while it is in flight, and an older answer must never erase that newer refusal. |
| 187 | + */ |
| 188 | +export function captureAnthropicCooldownRecovery( |
| 189 | + accountId: string, |
| 190 | + now = Date.now(), |
| 191 | +): AnthropicCooldownRecoveryClaim | null { |
| 192 | + const entry = upstreamHealth.get(accountId); |
| 193 | + if (!entry || entry.cooldownUntil <= now || entry.cooldownSource !== "reset-derived") return null; |
| 194 | + return { accountId, cooldownGeneration: entry.cooldownGeneration, claimedAt: now }; |
| 195 | +} |
| 196 | + |
| 197 | +/** |
| 198 | + * Clear only the claimed reset-derived cooldown when a fresh, complete usage result proves |
| 199 | + * headroom in every window that upstream previously reported as rejected. |
| 200 | + */ |
| 201 | +export function settleAnthropicCooldownRecovery( |
| 202 | + claim: AnthropicCooldownRecoveryClaim, |
| 203 | + quota: ProviderQuota, |
| 204 | +): AnthropicCooldownRecoverySettlement { |
| 205 | + const entry = upstreamHealth.get(claim.accountId); |
| 206 | + if (!entry || entry.cooldownSource !== "reset-derived" |
| 207 | + || entry.cooldownGeneration !== claim.cooldownGeneration |
| 208 | + || anthropicCooldownGeneration(claim.accountId) !== claim.cooldownGeneration |
| 209 | + || !Number.isFinite(quota.updatedAt) || quota.updatedAt < claim.claimedAt) return "superseded"; |
| 210 | + const windows = entry.rejectedQuotaWindows; |
| 211 | + if (!windows?.length) return "retained"; |
| 212 | + const recovered = windows.every(window => { |
| 213 | + const percent = window === "five-hour" ? quota.fiveHourPercent : quota.weeklyPercent; |
| 214 | + return typeof percent === "number" && Number.isFinite(percent) && percent >= 0 && percent < 100; |
| 215 | + }); |
| 216 | + if (!recovered) return "retained"; |
| 217 | + upstreamHealth.delete(claim.accountId); |
| 218 | + noteAnthropicCooldownMutation(claim.accountId); |
| 219 | + return "cleared"; |
156 | 220 | } |
157 | 221 |
|
158 | 222 | export function getAnthropicAccountHealthSnapshot( |
@@ -163,20 +227,24 @@ export function getAnthropicAccountHealthSnapshot( |
163 | 227 | if (!entry) return null; |
164 | 228 | if (entry.cooldownUntil <= now) { |
165 | 229 | upstreamHealth.delete(accountId); |
| 230 | + noteAnthropicCooldownMutation(accountId); |
166 | 231 | return null; |
167 | 232 | } |
168 | 233 | return { cooldownUntil: entry.cooldownUntil, cooldownSource: entry.cooldownSource }; |
169 | 234 | } |
170 | 235 |
|
171 | 236 | export function clearAnthropicAccountCooldown(accountId: string): boolean { |
172 | | - return upstreamHealth.delete(accountId); |
| 237 | + const cleared = upstreamHealth.delete(accountId); |
| 238 | + if (cleared) noteAnthropicCooldownMutation(accountId); |
| 239 | + return cleared; |
173 | 240 | } |
174 | 241 |
|
175 | 242 | export function sweepExpiredAnthropicRoutingHealth(now = Date.now()): number { |
176 | 243 | let removed = 0; |
177 | 244 | for (const [accountId, health] of upstreamHealth) { |
178 | 245 | if (health.cooldownUntil > now) continue; |
179 | 246 | upstreamHealth.delete(accountId); |
| 247 | + noteAnthropicCooldownMutation(accountId); |
180 | 248 | removed += 1; |
181 | 249 | } |
182 | 250 | return removed; |
@@ -185,6 +253,7 @@ export function sweepExpiredAnthropicRoutingHealth(now = Date.now()): number { |
185 | 253 | /** Test / logout helper. */ |
186 | 254 | export function clearAnthropicAccountPoolState(): void { |
187 | 255 | upstreamHealth.clear(); |
| 256 | + clearAnthropicCooldownGenerations(); |
188 | 257 | sessionAffinity.clear(); |
189 | 258 | manualPreference = undefined; |
190 | 259 | quorumCache = null; |
@@ -749,13 +818,16 @@ export function rotateAnthropicAccountOn429( |
749 | 818 | // without that fallback such a refusal cools for the 60s default and the exhausted |
750 | 819 | // account is back in the rotation a minute later. |
751 | 820 | const parsedRetry = parseRetryAfterMs(retryAfterHeader, now); |
752 | | - const resetDerived = parsedRetry === undefined ? parseRateLimitResetMs(rateLimitHeaders, now) : undefined; |
753 | | - const cooldownMs = parsedRetry ?? resetDerived ?? DEFAULT_COOLDOWN_MS; |
| 821 | + const resetDerived = parsedRetry === undefined ? parseRateLimitReset(rateLimitHeaders, now) : undefined; |
| 822 | + const cooldownMs = parsedRetry ?? resetDerived?.delayMs ?? DEFAULT_COOLDOWN_MS; |
| 823 | + const cooldownGeneration = noteAnthropicCooldownMutation(failedAccountId); |
754 | 824 | upstreamHealth.set(failedAccountId, { |
755 | 825 | cooldownUntil: now + cooldownMs, |
756 | 826 | cooldownSource: parsedRetry !== undefined |
757 | 827 | ? "retry-after" |
758 | 828 | : resetDerived !== undefined ? "reset-derived" : "default", |
| 829 | + ...(resetDerived ? { rejectedQuotaWindows: resetDerived.rejectedQuotaWindows } : {}), |
| 830 | + cooldownGeneration, |
759 | 831 | }); |
760 | 832 | sweepExpiredOnWrite(now); |
761 | 833 | clearAnthropicSessionAffinityForAccount(failedAccountId); |
|