Repository navigation
fix(auth): auto-expire stale auth profile cooldowns and reset error count - #17853
thewilloftheshadow merged 3 commits into
Conversation
| expect(store.usageStats?.["anthropic:default"]?.errorCount).toBe(0); | ||
| }); | ||
|
|
||
| it("does not clear cooldownUntil that equals exactly `now`", () => { |
There was a problem hiding this comment.
Test name contradicts test behavior
The test name says "does not clear cooldownUntil that equals exactly now" but the assertions verify the opposite — that it does clear (toBe(true), toBeUndefined(), toBe(0)). The inline comment on line 231 confirms the intended behavior is to clear. The test name should match what it's actually testing.
| it("does not clear cooldownUntil that equals exactly `now`", () => { | |
| it("clears cooldownUntil that equals exactly `now`", () => { |
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/usage.test.ts
Line: 222:222
Comment:
**Test name contradicts test behavior**
The test name says "does not clear cooldownUntil that equals exactly `now`" but the assertions verify the opposite — that it **does** clear (`toBe(true)`, `toBeUndefined()`, `toBe(0)`). The inline comment on line 231 confirms the intended behavior is to clear. The test name should match what it's actually testing.
```suggestion
it("clears cooldownUntil that equals exactly `now`", () => {
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Good catch — the test name was left over from an earlier draft where the boundary was exclusive (> instead of >=). The implementation uses >= (cooldown "until" means the profile becomes available at that instant), so the test correctly asserts it clears. Fixed in cca607a.
mudrii
left a comment
There was a problem hiding this comment.
Code Review
Verdict: APPROVE ✅
What it fixes
errorCount persists after cooldown expiry, causing disproportionate backoffs on the next transient failure. Adds clearExpiredCooldowns() called from resolveAuthProfileOrder().
Code Patterns ✅
- No hot-path IO — in-memory mutation only; lazy persistence on next store write
- NaN/Infinity guarded —
Number.isFinite()+> 0checks throughout - Independent expiry logic —
cooldownUntilanddisabledUntilcleared separately;errorCountreset only when ALL windows expired. Correct design.
Security 🔒
No bypass vectors — the function only clears cooldowns that have already expired (timestamp check). Does not shorten active cooldowns or bypass rate limits. The >= boundary is correct ("until" means available at that instant). Sweeping ALL providers in cleanup is the right call — stale state should be cleaned regardless.
Testing ✅
17 unit tests + 6 integration tests — comprehensive coverage including edge cases: NaN, Infinity, zero, negative, boundary equality, mixed active/expired, cross-provider, independent expiry scenarios.
PR Structure ✅
2 clean commits, 6 on-topic files, no scope creep. Excellent PR description with root cause analysis, design decisions, and comparison to competing PR #3607.
High-quality PR. Ship it. 🚀
…ount When an auth profile hits a rate limit, `errorCount` is incremented and `cooldownUntil` is set with exponential backoff. After the cooldown expires, the time-based check correctly returns false — but `errorCount` persists. The next transient failure immediately escalates to a much longer cooldown because the backoff formula uses the stale count: 60s × 5^(errorCount-1), max 1h This creates a positive feedback loop where profiles appear permanently stuck after rate limits, requiring manual JSON editing to recover. Add `clearExpiredCooldowns()` which sweeps all profiles on every call to `resolveAuthProfileOrder()` and clears expired `cooldownUntil` / `disabledUntil` values along with resetting `errorCount` and `failureCounts` — giving the profile a fair retry window (circuit-breaker half-open → closed transition). Key design decisions: - `cooldownUntil` and `disabledUntil` handled independently (a profile can have both; only the expired one is cleared) - `errorCount` reset only when ALL unusable windows have expired - `lastFailureAt` preserved for the existing failureWindowMs decay logic - In-memory mutation; disk persistence happens lazily on the next store write, matching the existing save pattern Fixes openclaw#3604 Related: openclaw#13623, openclaw#15851, openclaw#11972, openclaw#8434
The test verifies that cooldownUntil IS cleared when it equals exactly `now` (>= comparison), but the test name said "does not clear". Fixed the name to match the actual assertion behavior.
cca607a to
d8034d1
Compare
Rebased onto latest
|
|
Landed via temp rebase onto main. Thanks @nabbilkhan! |
|
Not sure if this fixes the issue where on multi-model auth (Gemini-cli), where each model has their own limits and cooldown, hitting the rate limit one one model kills all other models on the same auth |
Problem
I've been running a multi-agent OpenClaw setup (>20 agents across 4 industries). The single most disruptive issue I've hit is auth profiles getting "stuck" in cooldown — the
cooldownUntiltimestamp expires, but the next transient failure immediately escalates to a 25-minute or 1-hour cooldown becauseerrorCountwas never reset.The cascade looks like this:
errorCount=1, cooldown=60s ✓errorCount=2, cooldown=5 minuteserrorCount=3, cooldown=25 minuteserrorCount=4, cooldown=1 hourThis has been reported across multiple issues, all sharing the same root cause:
Root Cause
isProfileInCooldown()correctly checksDate.now() < cooldownUntil— so expired cooldowns do returnfalse. ButerrorCountpersists inusageStatsindefinitely. The backoff formula60s × 5^(errorCount-1)uses this stale count, so the next failure immediately produces a disproportionately long cooldown. The only way to reseterrorCounttoday is viamarkAuthProfileUsed()after a successful request — but if the first retry after cooldown fails, the count jumps again before any success can clear it.Solution
Add
clearExpiredCooldowns()— a sweep function called fromresolveAuthProfileOrder()(the gate before every model selection attempt) that:usageStatscooldownUntilhas passed: clearscooldownUntildisabledUntilhas passed: clearsdisabledUntilanddisabledReasonerrorCountandfailureCountsto zeroThis implements the circuit-breaker pattern: half-open → test → closed. Once a cooldown is served, the profile gets a clean slate. If it fails again, it starts from
errorCount=1(60s cooldown) instead of escalating from a stale count.Design decisions
cooldownUntilanddisabledUntilare cleared independently. A profile can have both (e.g., rate limit + billing); only the expired one is removed.errorCountis only reset when all unusable windows have expired. This addresses the review concern raised on PR fix: Auto-expire auth profile cooldowns when timestamp expires #3607 about clearing them together.lastFailureAtpreserved — The existingfailureWindowMsdecay logic incomputeNextProfileUsageStatsuseslastFailureAtto reset counters after 24 hours of inactivity. We preserve this field so the two mechanisms compose correctly.markAuthProfileUsed/markAuthProfileFailurecall, matching the existing save pattern throughout the module. No new file I/O on the hot path.NaN,Infinity, zero, and negative timestamps safely (ignores them).Changes
src/agents/auth-profiles/usage.tsclearExpiredCooldowns()— sweep + reset logic (~50 LOC)src/agents/auth-profiles/usage.test.tsisProfileInCooldownandclearExpiredCooldownssrc/agents/auth-profiles/order.tsclearExpiredCooldowns(store, now)at the top ofresolveAuthProfileOrder(~3 LOC)src/agents/auth-profiles.cooldown-auto-expiry.test.tsresolveAuthProfileOrdersrc/agents/auth-profiles.tsclearExpiredCooldownsfrom barrel (~1 LOC)CHANGELOG.mdAddressed review feedback
1. Misleading test name (Greptile-flagged, 4/5 → resolved)
Problem: The test
"does not clear cooldownUntil that equals exactly now"asserted the opposite — that it does clear. The test logic and assertions were correct; only the description was wrong (leftover from an earlier draft where the boundary was exclusive>instead of>=).Fix: Renamed to
"clears cooldownUntil that equals exactly now"in cca607a. The>=comparison is intentional —cooldownUntilmeans the profile becomes available at that instant.Test plan
Unit tests (
usage.test.ts— 17 tests)isProfileInCooldownreturns false for missing statsisProfileInCooldownreturns true for active cooldownisProfileInCooldownreturns false for expired cooldownisProfileInCooldownreturns true when disabledUntil still active (cooldownUntil expired)clearExpiredCooldownsreturns false on empty usageStatsclearExpiredCooldownsreturns false when no profiles have cooldownsclearExpiredCooldownsreturns false when cooldown still activecooldownUntilcleared +errorCountreset to 0disabledUntilcleared +disabledReasonclearednowparameter for deterministic testsnow→ clearedIntegration tests (
cooldown-auto-expiry.test.ts— 6 tests)Regression
pnpm test)pnpm buildclean (0 type errors)pnpm checkclean (0 lint/format errors)Note on PR #3607
PR #3607 addresses the same issue but has three gaps this PR resolves:
cooldownUntilanddisabledUntiltogether — if they expire at different times, this can prematurely clear the one that's still active, or leaveerrorCountelevated when both are expirederrorCount, which is the actual driver of the escalation loopThis PR can supersede #3607 if the maintainers prefer this approach.
Fixes #3604
Related: #13623, #15851, #11972, #8434