Skip to content

fix(auth): resume quota recovery after token expiry - #155665

Merged
steipete merged 2 commits into
mainfrom
codex/quota-expired-recovery
Sep 22, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/quota-expired-recovery

Conversation

@steipete

@steipete steipete commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes quota recovery getting stuck when an OpenAI subscription's access token expires while its usage limit is active.

User Impact

After capacity returns, the next turn can renew the credential and recheck usage. If renewal leaves no usable credential, normal auth selection can still choose an allowed configured API key or fallback. Account pins and hard storage failures retain their existing behavior.

Why This Change Was Made

The quota check previously required an already-fresh bearer, so it never reached the existing refresh owner for an expired one. It now composes that owner with the existing locked credential and quota-generation checks. Only a fresh usage observation clears the quota block.

The refresh owner records settled failures separately from provider-owned errors, preserving immutable errors, contention diagnostics and redaction. Quota reconciliation joins peer operations and reloads authoritative snapshots before returning control to normal auth selection. Tracked refresh settlement and catalog-worker retirement remain intact.

Error presentation and pure usage policy move to their existing owners. Pure tests no longer allocate mutation/bootstrap fixtures, and tests use real cooldown/unavailable-reason policy instead of copied approximations. Assertions, process isolation, deadlines and shard counts are preserved.

Evidence

After-change real behavior proof: an actual built OpenClaw Gateway, isolated SQLite state and WebSocket chat.send, with mocked OpenAI OAuth/WHAM/inference HTTP endpoints. This is a runtime integration harness, not a live OpenAI account test. The complete expired-bearer scenario passed on the exact source tree in the verdict below; the summary records assertions exercised by that passing native test.

CI=1 OPENCLAW_BUILD_PRIVATE_QA=1 OPENCLAW_E2E_WORKERS=1 \
node scripts/run-vitest.mjs run test/e2e/qa-lab/runtime/quota-reset.e2e.test.ts \
  --config test/vitest/vitest.e2e.config.ts --testNamePattern 'wham, expired=true'

Executed with verbose/JSON reporters on Linux Node 24.19 / pnpm 12.4, four CPUs and 15.4 GiB RAM. Native worker lease: GitHub Actions run 35718054596; the lease was stopped after collection, independently of the successful test command.

{
  "verification": "real ephemeral OpenClaw Gateway with mocked OpenAI HTTP provider",
  "sourceCommit": "9dfd6f45156b962e54dcb1df45d8d8133064458a",
  "sourceTree": "24d141fa131b005f700eabff28d1ecd1b899c750",
  "platform": "linux-x64",
  "node": "v24.19.0",
  "pnpm": "12.4.0",
  "scenario": "Gateway quota reset (wham, expired=true, scoped=false, available=false, stale-success=false) recovers the next chat after upstream capacity returns without admitting exhausted or revoked auth",
  "result": "PASS",
  "passed": 1,
  "failed": 0,
  "notSelected": 8,
  "commandSeconds": 47.456,
  "verifiedAssertions": {
    "exhaustedAndEarlyRetriesRejected": true,
    "refreshRequestCount": 1,
    "usageProbeAndInferenceObservedOnRecovery": true,
    "recoveredChatDeliveredMarker": true,
    "quotaBlockAbsentAfterRecovery": true,
    "revokedRetriesRejected": 2,
    "authorizationAndAccountBindingsChecked": true,
    "providerFixtureErrors": 0
  },
  "nativeReportSha256": "b2bde2707fdc9cad0e1d36ddb491b8cfb3493a676842e8c2d68739993efccdea"
}
  • 428 owner/sibling tests passed in 64.55 seconds, including every one of the 306 original owner cases, mutable/frozen contention errors, queue settlement, fences, usage writes, pins and normal credential selection. Typed lint passed in 30.01 seconds; the catalog-worker OAuth retirement case passed in 105.59 seconds. Independent final P2 review found no actionable issues.
  • Regression evidence is retained: the previous implementation selected a fallback reply instead of the usable primary credential and lost auth-preparation information after a null result. The frozen-error variant failed before the final provenance correction. The final combined run passes these cases without weakened assertions.
  • First PR CI exposed inconsistent returns/an untyped callback and a missed contention-diagnostic contract. These were repaired at the producer/error owner and verified with the expanded suite. Final formatting passes. The earlier changed-files gate passed production types/all 25 core-test graphs and static guards; its two obsolete-export findings were removed and all three dead-export scans passed. Fresh CI on the published head remains required before merge.
  • Broader diagnostic remains failing: the original 11-case Gateway quota run improved from 8/11 to 9/11 on the earlier candidate, but claim-write/result-write native SQLite I/O recovery still fails with state read-admission changes, also observed on the original baseline. Those failed results remain retained as a separate state admission/cache repair. The focused after-change verdict above does not claim that broader suite is green.

Production delta: +123 lines; tests/test support: +685; assertion baseline shrinks by two grandfathered assertions (one net line). Counts include pure owner/test moves. Growth implements missing refresh composition, generation validation and owner-scoped failure provenance while reusing existing credential, quota and auth-selection owners; no new configuration, persistence schema or alternative auth-selection flow.

@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components. This comment is informational because the PR author has repository Maintain or Admin access.

  • Current SHA: 9dfd6f45156b962e54dcb1df45d8d8133064458a
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/oauth-manager.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth-refresh-failure.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/usage-state.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/usage.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 22, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 22, 2026
@clawsweeper

clawsweeper Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 22, 2026, 6:37 AM ET / 10:37 UTC.

ClawSweeper review

What this changes

Reconnects subscription quota recovery to OAuth token renewal, preserves normal credential fallback, and reorganizes supporting error handling and tests.

Merge readiness

⛔ Blocked before merge - 1 item remains

The fix remains necessary: current main excludes expired credentials from quota recovery. No blocking correctness or security defect was found in the introduced patch.

Priority: P2
Reviewed head: 352dc9451b002ca9a979e7d694f711ce198d15b1

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Recorded reviewer rating: A focused owner-level repair with preserved regression coverage and no blocking finding from source review. Real behavior proof remains required by host policy.
Proof confidence 🌊 off-meta tidepool Recorded reviewer rating; Required by policy: the recorded not-applicable assessment does not satisfy the current PR proof policy. Put relevant after-change evidence in the main PR body, then request a fresh review with @clawsweeper re-review. Recorded reviewer context: The ordinary contributor proof gate is exempt for this verified repository-admin PR. Its body reports real-Gateway expired-token recovery through the changed quota owner, with two baseline SQLite failures explicitly unresolved; those reports were not independently executed here. No stored-data contract changes were introduced.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Required by policy Required by policy: the recorded not-applicable assessment does not satisfy the current PR proof policy. Put relevant after-change evidence in the main PR body, then request a fresh review with @clawsweeper re-review. Recorded reviewer context: The ordinary contributor proof gate is exempt for this verified repository-admin PR. Its body reports real-Gateway expired-token recovery through the changed quota owner, with two baseline SQLite failures explicitly unresolved; those reports were not independently executed here. No stored-data contract changes were introduced.
Evidence reviewed 10 items Current-main defect remains: Current main requires a future token expiry in shouldProbeWhamForFailure, and shouldHalfOpenProbeWhamBlock uses that predicate before reaching recovery. An expired bearer therefore prevents the due quota check.
Recovery retains the existing owners: Expired credentials pass through resolveApiKeyForProfile with profile fallback disabled. The quota claim checks the refreshed credential and original quota generation; the result write checks both again. Only observed available capacity clears the block.
Failure settlement and authentication boundary: The refresh owner marks external failures settled only after cleanup succeeds. Cleanup aggregates do not retain that mark. Quota reconciliation joins peer operations and reloads stored state; its outcome bypasses only the outer cooldown precheck, leaving normal auth eligibility, pins, direct-credential authorization and fallback policy in place.
Findings None None.
Security None None.

How this fits together

OpenClaw checks stored account quota before attempting an agent turn. This change lets that check renew an expired credential, obtain fresh usage information, and return control to normal authentication selection.

flowchart TD
  A[Agent turn] --> B[Stored account quota]
  B --> C{Access token expired?}
  C -->|Yes| D[Existing OAuth refresh owner]
  C -->|No| E[Usage probe]
  D --> E
  E --> F[Locked credential and quota checks]
  F --> G[Normal auth selection]
  D -->|Settled credential failure| G
Loading

Before merge

  • Add real behavior proof - Required by policy: the recorded not-applicable assessment does not satisfy the current PR proof policy. Put relevant after-change evidence in the main PR body, then request a fresh review with @clawsweeper re-review. Recorded reviewer context: The ordinary contributor proof gate is exempt for this verified repository-admin PR. Its body reports real-Gateway expired-token recovery through the changed quota owner, with two baseline SQLite failures explicitly unresolved; those reports were not independently executed here. No stored-data contract changes were introduced.
Agent review details

Security

None.

PR surface

Source +116, Tests +680, Other -1. Total +795 across 15 files.

View PR surface stats
Area Files Added Removed Net
Source 6 379 263 +116
Tests 8 1749 1069 +680
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 2 -1
Total 15 2129 1334 +795

Review metrics

Metric Value Why it matters
Production versus test growth Production +116 net lines; tests and test support +680 Production growth supports refresh settlement and quota reconciliation; a 752-line pure-test block was independently verified as moved verbatim.

Technical review

Best possible solution:

Keep quota recovery composed with the existing refresh owner and normal auth selection, clearing blocks only from current usage observations.

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

Yes, from source: an active subscription block with a due probe and expired OAuth token is rejected by current main's freshness predicate before refresh can run. This read-only review did not execute the scenario.

Is this the best way to solve the issue?

Yes. Reusing the credential owner and returning settled outcomes to normal auth selection repairs the missing composition without duplicating refresh or fallback policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 80b9608a25e1.

Labels

Label changes:

  • add P2: Repairs a bounded subscription-recovery failure triggered by token expiry during an active quota block.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit. This is the recorded reviewer rating; real behavior proof remains required by host policy.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Required by policy: the recorded not-applicable assessment does not satisfy the current PR proof policy. Put relevant after-change evidence in the main PR body, then request a fresh review with @clawsweeper re-review. Recorded reviewer context: The ordinary contributor proof gate is exempt for this verified repository-admin PR. Its body reports real-Gateway expired-token recovery through the changed quota owner, with two baseline SQLite failures explicitly unresolved; those reports were not independently executed here. No stored-data contract changes were introduced.

Label justifications:

  • P2: Repairs a bounded subscription-recovery failure triggered by token expiry during an active quota block.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit. This is the recorded reviewer rating; real behavior proof remains required by host policy.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Required by policy: the recorded not-applicable assessment does not satisfy the current PR proof policy. Put relevant after-change evidence in the main PR body, then request a fresh review with @clawsweeper re-review. Recorded reviewer context: The ordinary contributor proof gate is exempt for this verified repository-admin PR. Its body reports real-Gateway expired-token recovery through the changed quota owner, with two baseline SQLite failures explicitly unresolved; those reports were not independently executed here. No stored-data contract changes were introduced.

Evidence

What I checked:

  • Current-main defect remains: Current main requires a future token expiry in shouldProbeWhamForFailure, and shouldHalfOpenProbeWhamBlock uses that predicate before reaching recovery. An expired bearer therefore prevents the due quota check. (src/agents/auth-profiles/usage.ts:190, 80b9608a25e1)
  • Recovery retains the existing owners: Expired credentials pass through resolveApiKeyForProfile with profile fallback disabled. The quota claim checks the refreshed credential and original quota generation; the result write checks both again. Only observed available capacity clears the block. (src/agents/auth-profiles/usage.ts:474, 352dc9451b00)
  • Failure settlement and authentication boundary: The refresh owner marks external failures settled only after cleanup succeeds. Cleanup aggregates do not retain that mark. Quota reconciliation joins peer operations and reloads stored state; its outcome bypasses only the outer cooldown precheck, leaving normal auth eligibility, pins, direct-credential authorization and fallback policy in place. (src/agents/auth-profiles/oauth-manager.ts:961, 352dc9451b00)
  • Existing credential-selection contract: The normal auth planner distinguishes declared direct credentials from ambient credentials, checks pinned-profile eligibility, and retains cooldown checks at prepared-attempt admission. The patch does not replace this policy or add a new stored-data format. (src/agents/runtime-plan/prepare-auth.ts:405, 352dc9451b00)
  • Earlier quota recovery is related but incomplete: GitHub confirms fix(auth): recover accounts after subscription quota resets #145853 merged as 2e4391a. Its on-demand quota recovery provides the existing owner, but current-main inspection shows the expired-token case remains excluded. (2e4391ac95ae)
  • Validation reported in the captured PR body: The supplied body reports 408 owner/sibling tests passing in 130.04 seconds, two checks failing against the prior implementation, and real-Gateway quota results improving from 8/11 to 9/11 including expired-token recovery. It explicitly retains claim-write and result-write SQLite I/O failures also observed on the baseline. These are contributor-reported results, not reviewer executions; no target code was executed. (352dc9451b00)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • 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)

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.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The main PR body now includes an after-change runtime verdict for 9dfd6f4, the exact source tree and native report digest, and the command that exercised a real built Gateway with isolated SQLite state, WebSocket chat.send and mocked OpenAI OAuth/WHAM/inference endpoints. The expired-bearer scenario passed, including one refresh, restored delivery, blocked early/exhausted retries and rejected revoked credentials. This is mock-provider runtime behavior proof, not a live OpenAI account test or a not-applicable exemption.

The CI contention-diagnostic and typed-lint failures were also repaired. Final focused validation passed 428 owner/sibling cases, catalog-worker retirement and typed lint; independent P2 review is clean. The two broader baseline SQLite I/O failures remain explicitly documented rather than counted as passing evidence.

@clawsweeper

clawsweeper Bot commented Sep 22, 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:

@steipete
steipete merged commit 27b99a4 into main Sep 22, 2026
208 checks passed
@steipete
steipete deleted the codex/quota-expired-recovery branch September 22, 2026 12:08
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 23, 2026
* fix(auth): resume quota recovery after token expiry

* fix(auth): preserve settled refresh diagnostics

Co-authored-by: Peter Steinberger <[email protected]>
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 P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant