Skip to content

fix(auth): retry preferred profile after cooldown - #136784

Merged
Patrick-Erichsen merged 11 commits into
mainfrom
fix/recover-auto-auth-profile-order
Sep 3, 2026
Merged

Patrick-Erichsen merged 11 commits into
mainfrom
fix/recover-auto-auth-profile-order

Conversation

@Patrick-Erichsen

@Patrick-Erichsen Patrick-Erichsen commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Related: #25510
Related: #38335
Related: #117006

What Problem This Solves

When an operator explicitly orders OAuth before a metered API key, a session can correctly fail over to the API key while OAuth is unavailable and then remain on that paid fallback after OAuth becomes eligible to retry.

The recovery policy in this PR is:

  1. Honor an exact reset/cooldown timestamp when the provider supplies one.
  2. Otherwise retry rate-limit failures with exponential backoff starting at 30 seconds and capped at 24 hours.
  3. Reset the accumulated backoff after a successful request.
  4. On the next real auth selection after the retry deadline, let an automatically selected fallback yield to an earlier eligible profile in explicit auth.order.

No background provider traffic or scheduler is added. The next real request is the half-open probe.

Scenario That Led To This Work

This investigation started from a personal gateway running OpenClaw 2026.7.1-2:

  1. OpenAI OAuth was first in explicit auth.order; an API key was the emergency fallback.
  2. OAuth returned 429 usage_limit_reached, so the session correctly failed over and persisted the API-key profile as an automatic override.
  3. Server-side compaction did occur, but that release placed compactionCount under the wrong result metadata subtree. Session accounting therefore did not observe the compaction and could not use it as a rotation signal. fix(codex): persist automatic compaction history #110587 later fixed that historical counter defect.
  4. The API-key fallback consequently remained active and incurred metered API charges.

Current main has a related but distinct gap. #123894 deliberately keeps ordinary compaction/cooldown rotation on the current physical auth route, so a correctly counted compaction still does not promote a session from an API-key route back to an earlier OAuth route. This PR adds a narrow, directional recovery rule for that case without undoing general route stickiness.

Identifying account, organization, payment, profile, and credential details are intentionally omitted.

Why This Approach

The auth-profile subsystem already owns profile health, provider reset timestamps, persisted failure counters, and cooldown expiry. Session selection is therefore the right place to ask whether an automatically selected fallback should yield; the usage-state owner remains responsible for deciding when the preferred profile is eligible to probe.

Boundaries preserved:

  • explicit user pins remain strict;
  • implicit profile ordering remains stable;
  • only a profile earlier in an explicit order can displace the current automatic fallback;
  • model-scoped cooldowns are evaluated for the session model;
  • ordinary current-profile failures and compactions retain fix: API-key sessions switch to OAuth after compaction #123894's same-route rotation;
  • provider-reported reset timestamps override local exponential estimates;
  • incomplete or failed OpenAI quota probes retain the persisted local estimate rather than replacing it with a fixed delay;
  • there is no background request loop, config option, or persistence/schema change.

Production LOC and ownership

Against origin/main, production code is +94/-32 (net +62) and tests are +239/-47 (net +192). The production growth implements two missing state transitions in their existing owners: explicit-order session recovery (session-override.ts) and persisted half-open rate-limit retry (usage.ts / usage-state.ts).

An absorbing refactor was attempted by reusing the existing auth-order resolver, usage-state fields, provider-reset path, and capped exponential helper. Removing same-route rotation or replacing the existing health owner would be shorter only by discarding #123894's billing-safety invariant or creating a parallel state machine. The change adds no scheduler, schema, config, or duplicate retry owner.

User Impact

Operators can keep OAuth first and a metered API key second without making the paid fallback the de facto session default. Recovery occurs on the first real request after the preferred profile's provider deadline or local backoff deadline. If that probe fails again without a provider deadline, retries back off 30s -> 1m -> 2m -> ... -> 24h; successful use resets the sequence.

Evidence

Both regressions were written red before implementation:

  • after the OAuth deadline elapsed, the same session still selected the API-key profile;
  • after the second OpenAI OAuth failure without a reset timestamp, WHAM replaced the computed 60-second retry with a fixed 30-second delay.

Both now pass on the production selection and usage-state seams.

Focused auth-profile validation:

pnpm test src/agents/auth-profiles/usage.test.ts \
  src/agents/auth-profiles.markauthprofilefailure.test.ts \
  src/agents/auth-profiles/profiles.test.ts \
  src/agents/auth-profiles/session-override.rotation.test.ts \
  src/agents/auth-profiles/session-override.test.ts \
  src/agents/auth-profiles/session-override.user-pin.test.ts \
  src/agents/auth-profiles.cooldown-auto-expiry.test.ts
# 209 passed

The focused cases prove:

  • OAuth cooldown -> automatic API-key fallback -> OAuth retry in the same session;
  • exact provider reset timestamps win over the local estimate;
  • missing reset timestamps, including incomplete OpenAI quota probes, use exponential backoff through the 24-hour cap;
  • successful use clears the accumulated retry backoff;
  • persisted expired cooldown state retains the consecutive rate-limit count for the next half-open failure;
  • implicit order, user pins, model-scoped cooldowns, and same-route rotation remain stable.

Repository changed-file validation:

pnpm check:changed
# passed: formatting, core and test types, lint, dead exports, import cycles,
# architecture boundaries, schema guards, and changed-file policy checks

Dependency Contract Checked

OpenAI Codex's current account/rateLimits/read implementation reads authenticated backend quota snapshots and exposes backend-owned ordinaryUsageAllowed: request processor, protocol response, and rate-limit snapshot. The protocol explicitly distinguishes a reset estimate from proof of recovery, which is why this change treats the next real request as the probe.

Research Trail

Exact auth-fallback reports:

Prior implementations and constraints:

Related but separate boundaries considered:

Direct Codex Verification

The acting agent directly verified pinned Codex commit 0588fc941c3bd5abd0cb8cd38c51cd6e72e9eb16 in the local sibling checkout with git cat-file and git show. The cited response type contains backend-owned ordinary_usage_allowed and explicitly says clients must not infer recovery from percentages or reset times; the request processor exposes it only after matching the active account. This supports using a real provider request as the recovery proof rather than treating expiry alone as success.

@clawsweeper

clawsweeper Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Sep 3, 2026
@Patrick-Erichsen
Patrick-Erichsen marked this pull request as ready for review September 3, 2026 01:04
@Patrick-Erichsen
Patrick-Erichsen requested a review from a team as a code owner September 3, 2026 01:04
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 3, 2026, 2:54 AM ET / 06:54 UTC.

ClawSweeper review

What this changes

The PR lets an automatically selected fallback auth profile yield to a recovered higher-priority explicitly ordered profile and retains rate-limit failure history until a successful request.

Merge readiness

⛔ Blocked before merge - 5 items remain

Keep open for maintainer review: current main still lacks the recovery behavior, but the PR also adopts a 24-hour rate-limit backoff policy that changes fallback spending and retry behavior.

Priority: P2
Reviewed head: 9cff4ad9020a24bf0e72594b3bbcb741bfcfec68
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The targeted repair and focused coverage are solid, with the remaining issue being an explicit default-policy decision rather than a discrete source defect.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: Focused source-level regression coverage exists; no live proof was evaluated in this read-only review, and the member-authored PR does not require contributor proof action.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Focused source-level regression coverage exists; no live proof was evaluated in this read-only review, and the member-authored PR does not require contributor proof action.
Evidence reviewed 7 items Changed owner boundary: The PR's session resolver preserves user pins, limits recovery promotion to automatic selections under an explicit profile order, and requires an earlier profile with prior rate-limit history that is no longer unavailable.
Focused regression coverage: The introduced test models a cooldown-driven OAuth-to-API fallback, then expects the recovered OAuth profile to be selected on the same session.
Shared callers: Normal replies resolve the session auth selection before loading the agent runner; cron and gateway worker paths use the same resolver.
Findings None None.
Security None None.

How this fits together

Auth-profile selection chooses credentials for agent, cron, and gateway inference runs from configured order and persisted health state. Its result constrains the provider route used for the next model request.

flowchart LR
  A[Configured auth profile order] --> C[Session auth selection]
  B[Persisted profile health] --> C
  C --> D[Provider route selection]
  D --> E[Agent or gateway model request]
  E --> F[Success or failure health update]
Loading

Decision needed

Question Recommendation
Should unknown rate-limit failures retain retry history through expired cooldowns and back off for up to 24 hours before another primary-profile probe? Confirm bounded backoff: Accept the 24-hour capped half-open policy after exact-head validation of reply, cron, and gateway callers.

Why: This is an intentional operator cost-versus-recovery tradeoff beyond the narrow session-promotion repair; source review cannot choose its default policy safely.

Before merge

  • Resolve merge risk (P2) - After repeated unknown rate limits, the new retained counter expands retry cooldowns from the prior five-minute maximum to as much as 24 hours, which can keep existing operators on a metered fallback longer.
  • Resolve merge risk (P1) - The bug-fix branch adds a net 62 production lines across the auth-selection and health owners; the added policy must justify that growth rather than remain an incidental side effect.
  • Complete next step (P2) - Confirm the 24-hour unknown-rate-limit backoff policy and validate the exact head across reply, cron, and gateway selection paths before merge.
  • Resolve review confidence - ClawSweeper must reach high confidence before merge readiness is known.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +62, Tests +192. Total +254 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 4 94 32 +62
Tests 6 239 47 +192
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 333 79 +254

Review metrics

Metric Value Why it matters
Production versus test delta production +94/-32 (net +62); tests +239/-47 (net +192) The branch expands persistent health-policy behavior alongside focused regression coverage, so the policy scope warrants owner review.

Merge-risk options

Maintainer options:

  1. Confirm and validate the backoff policy (recommended)
    Obtain auth-owner confirmation for the 24-hour capped retry policy, then validate the exact head through all shared selection callers before merge.
  2. Keep short retry windows
    Revise the branch to preserve the recovery promotion while resetting rate-limit history when its cooldown expires.

Technical review

Best possible solution:

Land only after the auth owners explicitly accept the bounded 24-hour half-open retry policy and validate the exact head across the shared reply, cron, and gateway selection paths.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: the focused test constructs the cooldown, automatic fallback, expiry, and same-session retry path, though this read-only review did not execute it.

Is this the best way to solve the issue?

Unclear: the automatic recovery is a targeted repair, but retaining rate-limit history into a 24-hour backoff is a separate default-policy choice requiring owner confirmation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 6d763ee148d4.

Labels

Label justifications:

  • P2: The change affects provider-auth recovery and fallback selection without evidence of a current outage or data-loss condition.
  • merge-risk: 🚨 compatibility: Persisted rate-limit history changes how existing installations retry profiles after cooldown expiry.
  • merge-risk: 🚨 auth-provider: The changed cooldown policy directly controls credential-profile selection and provider fallback duration.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Focused source-level regression coverage exists; no live proof was evaluated in this read-only review, and the member-authored PR does not require contributor proof action.

Evidence

Acceptance criteria:

  • [P1] Exercise a repeated unknown-rate-limit sequence through the reply, cron, and gateway selection callers and confirm recovery promotion, route affinity, and user pins.

What I checked:

Likely related people:

  • fuller-stack-dev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • nabbilkhan: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Confirm the 24-hour retained-rate-limit policy with the auth owners.
  • Validate the exact head through reply, cron, and gateway selection paths.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-09-03T01:15:06.460Z sha ec1cb0e :: blocked before merge. :: none
  • reviewed 2026-09-03T06:00:22.109Z sha d789a75 :: blocked before merge. :: none
  • reviewed 2026-09-03T06:22:06.616Z sha e2d13fa :: blocked before merge. :: none

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review — the latest head adds the agreed 24-hour capped exponential retry path for OpenAI OAuth when WHAM supplies no reset timestamp, plus the corresponding regressions and corrected PR evidence.

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Patrick-Erichsen
Patrick-Erichsen merged commit b55b725 into main Sep 3, 2026
218 checks passed
@Patrick-Erichsen
Patrick-Erichsen deleted the fix/recover-auto-auth-profile-order branch September 3, 2026 07:03
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 4, 2026
* fix(auth): retry preferred profile after cooldown

* fix(auth): cap unknown rate-limit backoff at 24 hours

* fix(auth): preserve backoff after incomplete quota probes

* test(auth): align cooldown expiry contract

* test(auth): deduplicate cooldown expiry coverage

* fix(auth): preserve user-selected session profiles

* fix(auth): scope recovery to explicit provider order

* fix(auth): isolate rate-limit retry history

* test(auth): assert isolated retry counters

* fix(auth): recover only cooldown fallbacks

* fix(auth): retain rate-limit history until success
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant