GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(oauth): recover Anthropic reset cooldowns · lidge-jun/opencodex@b350d03

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • devlog/_fin/260928_anthropic_cooldown_recovery
    • 000_decision.md
  • src
    • cli
      • account-extended.ts
    • oauth
      • anthropic-routing.ts
    • providers
      • quota.ts
      • quota
        • anthropic-cooldown-recovery.ts
        • vendor-probes-oauth.ts
  • tests
    • cli
      • cli-account-pool-verbs.test.ts
    • providers
      • anthropic-cooldown-recovery.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎devlog/_fin/260928_anthropic_cooldown_recovery/000_decision.md‎

Copy file name to clipboard
+46Lines changed: 46 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Anthropic cooldown recovery ownership
2+
3+
## Decision log
4+
5+
- Purpose: let an authoritative Anthropic usage refresh release a stale reset-derived
6+
cooldown without weakening explicit upstream backoff or clearing another account's state.
7+
- Existing constraints: routing health is process-local, usage probes are asynchronous, and
8+
credentials or a newer 429 can replace the state observed when a probe starts.
9+
- Alternatives considered: clear every cooldown after any successful usage response; clear
10+
only through the operator endpoint; or bind recovery to the observed refusal and credential.
11+
- Decision: a probe captures the exact account credential generation and cooldown generation
12+
before dispatch. Settlement requires the same live credential, the same reset-derived
13+
cooldown, a fresh timestamp, and utilization below 100% for every window that the 429 marked
14+
rejected. Account-level single-flight keys also include an active recovery generation, so a
15+
forced post-429 refresh cannot join work dispatched before the refusal. Any later cooldown
16+
mutation revokes publication ownership as well as settlement ownership. Partial, failed,
17+
exhausted, stale, Retry-After, and default-backoff evidence does not recover anything.
18+
- Why this option: a successful quota HTTP response alone says neither which credential it
19+
measured nor whether a newer refusal arrived while it was in flight. Generation fences make
20+
those ownership claims explicit while preserving the existing manual escape hatch.
21+
- Impact and trade-off: recovered accounts re-enter routing immediately; uncertain evidence
22+
remains fail-closed until expiry or `clear-cooldown`. The extra bookkeeping is process-local
23+
and bounded to one generation plus one health record per account. Superseded probes return an
24+
unavailable result instead of publishing quota that no longer describes the routing state.
25+
26+
## Data flow
27+
28+
1. A 429 records its source, rejected quota windows, and a monotonic cooldown generation.
29+
2. A fresh usage probe captures that generation plus the stored credential generation.
30+
When recovery is pending, both the provider-usage flight and the outer account-quota flight
31+
are generation-scoped, so the probe dispatches after the claim instead of joining older work
32+
that might describe pre-refusal state.
33+
3. The usage response is parsed and checked for complete headroom evidence.
34+
4. Publication and settlement both require the observed cooldown generation to remain current.
35+
Settlement deletes only the still-matching reset-derived record.
36+
37+
The CLI dispatches `openai` to `/api/codex-auth/accounts/clear-cooldown` and `anthropic` to
38+
`/api/oauth/accounts/clear-cooldown`. Anthropic IDs and aliases are resolved through the OAuth
39+
account list before the write; other providers remain rejected because they do not expose this
40+
process-local cooldown owner.
41+
42+
## Focused verification
43+
44+
- `tests/providers/anthropic-cooldown-recovery.test.ts`
45+
- `tests/cli/cli-account-pool-verbs.test.ts`
46+
- `tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts`
Collapse file

‎src/cli/account-extended.ts‎

Copy file name to clipboardExpand all lines: src/cli/account-extended.ts
+28-19Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -627,33 +627,42 @@ export async function cmdImport(args: string[], deps: AccountDeps): Promise<numb
627627
return result.failedCount > 0 || result.unsupportedCount > 0 ? 1 : 0;
628628
}
629629

630-
/**
631-
* Lift a quota cooldown on a Codex account.
632-
*
633-
* This is the user-facing escape from the lockout described in
634-
* `devlog/_plan/260726_cooldown_lockout_hardening`: injected routing makes the proxy the
635-
* only model path for Codex Desktop, so a stuck cooldown reads as "the whole app is dead".
636-
*
637-
* Codex accounts only. API-key pools already reset their own 429 cooldowns through key
638-
* management (`clearKeyCooldowns`), and OAuth providers have no equivalent state here.
639-
*/
630+
/** Lift a process-local cooldown through the management route that owns that pool. */
640631
export async function cmdClearCooldown(args: string[], deps: AccountDeps): Promise<number> {
641632
const wantsJson = flag(args, "--json");
642633
const name = args.shift();
643634
const requestedId = args.shift();
644635
if (!name || !requestedId || args.length) return usage();
645636
const classified = configAndType(deps, name);
646637
if ("error" in classified) return usage(`Error: ${classified.error}`);
647-
if (classified.type !== "codex") {
648-
return usage(`Error: ${name} is not a Codex account pool; cooldown clearing applies to Codex accounts only`);
638+
if (classified.type !== "codex" && !(classified.type === "oauth" && name === "anthropic")) {
639+
return usage(`Error: ${name} has no operator-clearable account cooldown`);
649640
}
650641
const baseUrl = await resolveBaseUrl(deps);
651642
if (!baseUrl) return proxyUnreachable();
652-
const target = await resolveCodexAccountTarget(deps, baseUrl, requestedId);
653-
if ("networkDown" in target) return proxyUnreachable(target.transportError);
654-
if ("error" in target) return reportCodexAccountTargetError(target);
655-
const id = target.id;
656-
const response = await apiJson(deps, baseUrl, "POST", "/api/codex-auth/accounts/clear-cooldown", { id });
643+
let id: string;
644+
let response: Awaited<ReturnType<typeof apiJson>>;
645+
if (classified.type === "codex") {
646+
const target = await resolveCodexAccountTarget(deps, baseUrl, requestedId);
647+
if ("networkDown" in target) return proxyUnreachable(target.transportError);
648+
if ("error" in target) return reportCodexAccountTargetError(target);
649+
id = target.id;
650+
response = await apiJson(deps, baseUrl, "POST", "/api/codex-auth/accounts/clear-cooldown", { id });
651+
} else {
652+
const list = await apiJson(deps, baseUrl, "GET", `/api/oauth/accounts?provider=${encodeURIComponent(name)}`);
653+
if (list.status === 0) return proxyUnreachable(list.transportError);
654+
if (list.status !== 200) return apiError(list.json, `failed to list ${name} OAuth accounts`, list.status);
655+
const target = resolveGenericOAuthAccountTarget(
656+
Array.isArray(list.json.accounts) ? list.json.accounts : [],
657+
requestedId,
658+
);
659+
if ("error" in target) return usage(`Error: ${target.error}`);
660+
id = target.id;
661+
response = await apiJson(deps, baseUrl, "POST", "/api/oauth/accounts/clear-cooldown", {
662+
provider: name,
663+
accountId: id,
664+
});
665+
}
657666
if (response.status === 0) return proxyUnreachable(response.transportError);
658667
if (response.status !== 200) return apiError(response.json, `failed to clear cooldown for ${requestedId}`, response.status);
659668
const cleared = response.json?.cleared === true;
@@ -773,7 +782,7 @@ export async function cmdPriority(args: string[], deps: AccountDeps): Promise<nu
773782
return 0;
774783
}
775784

776-
function resolveGenericOAuthPauseTarget(accounts: unknown[], requested: string): { id: string } | { error: string } {
785+
function resolveGenericOAuthAccountTarget(accounts: unknown[], requested: string): { id: string } | { error: string } {
777786
const rows = accounts.filter((value): value is { id: string; alias?: unknown } =>
778787
typeof value === "object" && value !== null && typeof (value as { id?: unknown }).id === "string",
779788
);
@@ -804,7 +813,7 @@ export async function cmdPause(args: string[], deps: AccountDeps, paused: boolea
804813
const list = await apiJson(deps, baseUrl, "GET", `/api/oauth/accounts?provider=${encodeURIComponent(name)}`);
805814
if (list.status === 0) return proxyUnreachable(list.transportError);
806815
if (list.status !== 200) return apiError(list.json, `failed to list ${name} OAuth accounts`, list.status);
807-
const target = resolveGenericOAuthPauseTarget(Array.isArray(list.json.accounts) ? list.json.accounts : [], requestedId);
816+
const target = resolveGenericOAuthAccountTarget(Array.isArray(list.json.accounts) ? list.json.accounts : [], requestedId);
808817
if ("error" in target) return usage(`Error: ${target.error}`);
809818

810819
const response = await apiJson(deps, baseUrl, "PUT", "/api/oauth/accounts/pause", {
Collapse file

‎src/oauth/anthropic-routing.ts‎

Copy file name to clipboardExpand all lines: src/oauth/anthropic-routing.ts
+78-6Lines changed: 78 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ import type { OcxAccountPoolQuotaWindow, OcxAccountPoolRotationStrategy, OcxConf
3434
import { sweepExpiredOnWrite } from "../lib/state-store-sweeper";
3535
import { retainedUtf8Bytes } from "../lib/admission";
3636
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";
3743

3844
/**
3945
* 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
6672
* `retry-after` would report a drained five-hour window as request-rate throttling.
6773
*/
6874
type AnthropicCooldownSource = "retry-after" | "reset-derived" | "default";
75+
type AnthropicQuotaWindow = "five-hour" | "weekly";
6976

7077
interface AccountHealth {
7178
cooldownUntil: number;
7279
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;
7384
}
7485

7586
interface AffinityEntry {
@@ -140,19 +151,72 @@ function parseRetryAfterMs(value: string | null | undefined, now: number): numbe
140151
}
141152

142153
/** 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 {
144158
if (!headers) return undefined;
145159
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) {
147162
if (headers.get(`anthropic-ratelimit-unified-${window}-status`)?.trim() !== "rejected") continue;
163+
rejectedQuotaWindows.push(quotaWindow);
148164
const resetSeconds = Number(headers.get(`anthropic-ratelimit-unified-${window}-reset`)?.trim());
149165
if (!Number.isFinite(resetSeconds) || resetSeconds <= 0) continue;
150166
const resetAt = resetSeconds * 1000;
151167
if (delayUntil(resetAt, now) === undefined) continue;
152168
if (latest === undefined || resetAt > latest) latest = resetAt;
153169
}
154170
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";
156220
}
157221

158222
export function getAnthropicAccountHealthSnapshot(
@@ -163,20 +227,24 @@ export function getAnthropicAccountHealthSnapshot(
163227
if (!entry) return null;
164228
if (entry.cooldownUntil <= now) {
165229
upstreamHealth.delete(accountId);
230+
noteAnthropicCooldownMutation(accountId);
166231
return null;
167232
}
168233
return { cooldownUntil: entry.cooldownUntil, cooldownSource: entry.cooldownSource };
169234
}
170235

171236
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;
173240
}
174241

175242
export function sweepExpiredAnthropicRoutingHealth(now = Date.now()): number {
176243
let removed = 0;
177244
for (const [accountId, health] of upstreamHealth) {
178245
if (health.cooldownUntil > now) continue;
179246
upstreamHealth.delete(accountId);
247+
noteAnthropicCooldownMutation(accountId);
180248
removed += 1;
181249
}
182250
return removed;
@@ -185,6 +253,7 @@ export function sweepExpiredAnthropicRoutingHealth(now = Date.now()): number {
185253
/** Test / logout helper. */
186254
export function clearAnthropicAccountPoolState(): void {
187255
upstreamHealth.clear();
256+
clearAnthropicCooldownGenerations();
188257
sessionAffinity.clear();
189258
manualPreference = undefined;
190259
quorumCache = null;
@@ -749,13 +818,16 @@ export function rotateAnthropicAccountOn429(
749818
// without that fallback such a refusal cools for the 60s default and the exhausted
750819
// account is back in the rotation a minute later.
751820
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);
754824
upstreamHealth.set(failedAccountId, {
755825
cooldownUntil: now + cooldownMs,
756826
cooldownSource: parsedRetry !== undefined
757827
? "retry-after"
758828
: resetDerived !== undefined ? "reset-derived" : "default",
829+
...(resetDerived ? { rejectedQuotaWindows: resetDerived.rejectedQuotaWindows } : {}),
830+
cooldownGeneration,
759831
});
760832
sweepExpiredOnWrite(now);
761833
clearAnthropicSessionAffinityForAccount(failedAccountId);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.