Skip to content

fix(auth): auto-expire stale auth profile cooldowns and reset error count - #17853

Merged
thewilloftheshadow merged 3 commits into
openclaw:mainfrom
nabbilkhan:fix/auth-profile-cooldown-auto-expiry
Feb 16, 2026
Merged

thewilloftheshadow merged 3 commits into
openclaw:mainfrom
nabbilkhan:fix/auth-profile-cooldown-auto-expiry

Conversation

@nabbilkhan

@nabbilkhan nabbilkhan commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor

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 cooldownUntil timestamp expires, but the next transient failure immediately escalates to a 25-minute or 1-hour cooldown because errorCount was never reset.

The cascade looks like this:

  1. Rate limit → errorCount=1, cooldown=60s ✓
  2. Cooldown expires. Profile retried.
  3. Another transient 429 → errorCount=2, cooldown=5 minutes
  4. Expires. Another blip → errorCount=3, cooldown=25 minutes
  5. Expires. One more → errorCount=4, cooldown=1 hour
  6. Profile is now functionally dead — any future transient error immediately triggers a 1-hour lockout

This has been reported across multiple issues, all sharing the same root cause:

Root Cause

isProfileInCooldown() correctly checks Date.now() < cooldownUntil — so expired cooldowns do return false. But errorCount persists in usageStats indefinitely. The backoff formula 60s × 5^(errorCount-1) uses this stale count, so the next failure immediately produces a disproportionately long cooldown. The only way to reset errorCount today is via markAuthProfileUsed() 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 from resolveAuthProfileOrder() (the gate before every model selection attempt) that:

  1. Iterates all profiles in usageStats
  2. For each profile where cooldownUntil has passed: clears cooldownUntil
  3. For each profile where disabledUntil has passed: clears disabledUntil and disabledReason
  4. When all unusable windows for a profile have expired: resets errorCount and failureCounts to zero

This 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

  • Independent expiry — cooldownUntil and disabledUntil are cleared independently. A profile can have both (e.g., rate limit + billing); only the expired one is removed. errorCount is 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.
  • lastFailureAt preserved — The existing failureWindowMs decay logic in computeNextProfileUsageStats uses lastFailureAt to reset counters after 24 hours of inactivity. We preserve this field so the two mechanisms compose correctly.
  • Lazy disk persistence — The function mutates the in-memory store only. The stale values get persisted (or not) on the next markAuthProfileUsed / markAuthProfileFailure call, matching the existing save pattern throughout the module. No new file I/O on the hot path.
  • Defensive value checks — Handles NaN, Infinity, zero, and negative timestamps safely (ignores them).

Changes

File Change
src/agents/auth-profiles/usage.ts ADD clearExpiredCooldowns() — sweep + reset logic (~50 LOC)
src/agents/auth-profiles/usage.test.ts NEW — 17 unit tests for isProfileInCooldown and clearExpiredCooldowns
src/agents/auth-profiles/order.ts MODIFY — Call clearExpiredCooldowns(store, now) at the top of resolveAuthProfileOrder (~3 LOC)
src/agents/auth-profiles.cooldown-auto-expiry.test.ts NEW — 6 integration tests verifying expiry through resolveAuthProfileOrder
src/agents/auth-profiles.ts MODIFY — Re-export clearExpiredCooldowns from barrel (~1 LOC)
CHANGELOG.md MODIFY — Add entry

Addressed 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 — cooldownUntil means the profile becomes available at that instant.

Test plan

Unit tests (usage.test.ts — 17 tests)

  • isProfileInCooldown returns false for missing stats
  • isProfileInCooldown returns true for active cooldown
  • isProfileInCooldown returns false for expired cooldown
  • isProfileInCooldown returns true when disabledUntil still active (cooldownUntil expired)
  • clearExpiredCooldowns returns false on empty usageStats
  • clearExpiredCooldowns returns false when no profiles have cooldowns
  • clearExpiredCooldowns returns false when cooldown still active
  • Expired cooldownUntil cleared + errorCount reset to 0
  • Expired disabledUntil cleared + disabledReason cleared
  • Independent expiry: cooldown expired, disabled still active → errorCount NOT reset
  • Independent expiry: disabled expired, cooldown still active → errorCount NOT reset
  • Both expired → errorCount reset
  • Multiple profiles processed independently
  • Explicit now parameter for deterministic tests
  • Boundary: cooldownUntil exactly equals now → cleared
  • NaN and Infinity values ignored
  • Zero and negative values ignored

Integration tests (cooldown-auto-expiry.test.ts — 6 tests)

  • Expired cooldown profile placed in available list (round-robin path)
  • Expired cooldown profile placed in available list (explicit-order path)
  • Active cooldown profile stays in cooldown list
  • Expired cooldown resets errorCount (prevents escalation)
  • Mixed active/expired cooldowns across profiles
  • Cross-provider profiles all swept

Regression

  • All 4,870 existing tests pass (pnpm test)
  • pnpm build clean (0 type errors)
  • pnpm check clean (0 lint/format errors)

Note on PR #3607

PR #3607 addresses the same issue but has three gaps this PR resolves:

  1. It clears cooldownUntil and disabledUntil together — if they expire at different times, this can prematurely clear the one that's still active, or leave errorCount elevated when both are expired
  2. It does not reset errorCount, which is the actual driver of the escalation loop
  3. It has no automated tests

This PR can supersede #3607 if the maintainers prefer this approach.

Fixes #3604
Related: #13623, #15851, #11972, #8434

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

6 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment thread src/agents/auth-profiles/usage.test.ts Outdated
expect(store.usageStats?.["anthropic:default"]?.errorCount).toBe(0);
});

it("does not clear cooldownUntil that equals exactly `now`", () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 mudrii left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() + > 0 checks throughout
  • Independent expiry logic — cooldownUntil and disabledUntil cleared separately; errorCount reset 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. 🚀

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: L labels Feb 16, 2026
…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.
@nabbilkhan
nabbilkhan force-pushed the fix/auth-profile-cooldown-auto-expiry branch from cca607a to d8034d1 Compare February 16, 2026 17:45
@nabbilkhan

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main — merge conflicts resolved

Rebased the branch onto the current main to resolve the two merge conflicts:

src/agents/auth-profiles.ts (barrel re-export)

  • Upstream added getSoonestCooldownExpiry to the same export block where this PR adds clearExpiredCooldowns. Resolution: kept both exports in alphabetical order.

src/agents/auth-profiles/usage.ts (implementation)

  • Upstream added the getSoonestCooldownExpiry() function immediately after isProfileInCooldown() — the exact same insertion point where this PR adds clearExpiredCooldowns(). The two functions are completely independent (one queries soonest expiry, the other sweeps expired state). Resolution: kept both functions, getSoonestCooldownExpiry first (matching upstream order), followed by clearExpiredCooldowns.

No functional changes to the PR — the diff is identical to the original aside from accommodating the new upstream code. All CI checks pass cleanly on the rebased commits.

@thewilloftheshadow thewilloftheshadow self-assigned this Feb 16, 2026
@thewilloftheshadow
thewilloftheshadow merged commit 250896c into openclaw:main Feb 16, 2026
23 checks passed
@thewilloftheshadow

Copy link
Copy Markdown
Member

Landed via temp rebase onto main.

  • Gate: skipped (per request; CI already ran)
  • Land commit: 250896c
  • Merge commit: 250896c

Thanks @nabbilkhan!

@asfura

asfura commented Feb 16, 2026

Copy link
Copy Markdown

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

john-ver pushed a commit to apmcoin/apmclaw that referenced this pull request Mar 9, 2026
dustin-olenslager pushed a commit to dustin-olenslager/ironclaw-supreme that referenced this pull request Mar 24, 2026
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Auth profile cooldown doesn't auto-expire

4 participants