Skip to content

fix(models): a new API key saved in Models stays blocked by the old key's rate-limit cooldown - #160452

Closed
masatohoshino wants to merge 2 commits into
openclaw:mainfrom
masatohoshino:fix/151354-key-save-clears-cooldown
Closed

masatohoshino wants to merge 2 commits into
openclaw:mainfrom
masatohoshino:fix/151354-key-save-clears-cooldown

Conversation

@masatohoshino

@masatohoshino masatohoshino commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #151354

What Problem This Solves

Fixes: after a provider key hits a 429, replacing it on the Control UI Models page (or with openclaw models auth paste-api-key) does not take effect. The next turns fail with Auth profile "<provider>:manual" is temporarily unavailable until the old key's cooldown expires or the Gateway restarts.

User Impact

User impact: an operator who rotates a rate-limited or out-of-quota key gets working requests on the very next turn, with no restart and no wait for the old cooldown.

Why This Change Was Made

Saving a key writes the new credential into the same saved profile (<provider>:manual), but the profile's failure state (cooldown, error counts) stayed, so profile selection kept skipping it. The old key is not sent again; the request is refused locally before any provider call.

Saving an API key now clears that one profile's failure state in the same locked write as the credential. This follows the ClawSweeper review on #151354 ("repair failure-state invalidation at the credential owners"), and the contract provider sign-in already has: it writes new credentials with resetFailureState: true. The upsert gains the same optional resetFailureState flag that the batch writer already has; only the manual API-key save sets it. Usage history such as lastUsed is kept, and other profiles are untouched. If the new key fails too, the next request records a fresh cooldown as usual.

Security-sensitive path: the change touches src/agents/auth-profiles/upsert-with-lock.ts, which the repository's security review policy classifies under credentials. It is narrow: it does not change how or where credentials are stored, who can write them, or what is logged or returned. It only adds an optional flag that clears the usage-health fields (cooldown, disabled window, error counters) of the one profile being written, inside the same lock and transaction, and only the manual API-key save passes it.

Scope is the saved-profile path the report's logs show (a hashed profile id with reason=rate_limit). Inline provider keys written directly in the config are unchanged: in the same setup a 429 on an inline key recorded no cooldown. The issue's other suggestions (a probe button, a rotation log line, a zero-failover warning, a run-failed hook) are separate features and not part of this fix.

Evidence

Behavior tested at adba4f7648e; the later commit changes tests only (base upstream/main 3a306a430ea).

A built Gateway on loopback with an isolated state directory and one OpenAI-compatible provider pointed at a local fake model server behind a small proxy. The proxy logs each request's bearer key and answers 429 rate_limit_exceeded for key-A; other keys reach the fake model. Keys are saved with openclaw gateway call models.authSetApiKey, the Gateway method the Models page calls; turns are sent with openclaw agent.

Before (base 3a306a430ea):

$ save key-A through models.authSetApiKey (the Models page call)
  "provider": "mock",
  "profileId": "mock:manual"
--- proxy requests so far: 0
$ turn 1 (key-A is out of quota: the fake answers 429)
⚠️ API rate limit reached. Please try again later.
--- keys seen by the provider during turn 1:      10 auth=key-A 
$ operator replaces the key with key-B through models.authSetApiKey
  "provider": "mock",
  "profileId": "mock:manual"
$ turn 2, immediately after the key change
Auth profile "mock:manual" is temporarily unavailable for mock/mock-1.
--- provider requests during turn 2: 0

After (this PR):

$ save key-A through models.authSetApiKey (the Models page call)
  "provider": "mock",
  "profileId": "mock:manual"
--- proxy requests so far: 0
$ turn 1 (key-A is out of quota: the fake answers 429)
⚠️ API rate limit reached. Please try again later.
--- keys seen by the provider during turn 1:      10 auth=key-A 
$ operator replaces the key with key-B through models.authSetApiKey
  "provider": "mock",
  "profileId": "mock:manual"
$ turn 2, immediately after the key change
This is a mock assistant reply with some selectable text for the repro.
--- provider requests during turn 2: 1
    POST /v1/chat/completions auth=key-B

Observed result: on the base, turn 2 fails locally with zero provider requests although key-B was saved; with this change it sends key-B and gets the reply. Both runs log auth profile failure state updated: profile=sha256:... provider=mock reason=rate_limit window=cooldown after turn 1, the same line the report shows.

Not covered: a real provider account and the Control UI screen itself (the proof calls the same Gateway method directly); the rate limit is simulated by the proxy.

Focused tests
  • New test in src/commands/models/auth-api-key.test.ts: seeds a saved key with an active rate_limit cooldown, saves a replacement, and checks the persisted failure state is cleared and lastUsed is kept. It fails on the base.

  • node scripts/run-vitest.mjs src/commands/models/auth-api-key.test.ts src/agents/auth-profiles/upsert-with-lock.sqlite.test.ts src/gateway/server-methods/models-auth-status.test.ts src/commands/models/auth.test.ts: 35, 103, 21 and 62 passed.

  • Test cost:

    File Change Local pnpm test <file> --maxWorkers=1 wall CI
    src/commands/models/auth-api-key.test.ts one new test 49 s (whole file, 35 tests) new test 1.2 s; whole file 56.0 s of test time in checks-node-changed-compact-large-* (shard agentic-commands-models, run https://github.com/openclaw/openclaw/actions/runs/36423201618)
    src/commands/models/auth.test.ts three existing assertions now expect resetFailureState: true 23 s (whole file, 62 tests) 6.8 s of test time for the whole file in the same run; no new tests
  • oxfmt --check, git diff --check, pnpm check:changed --base upstream/main: passed.

  • The autoreview skill on this head: no findings.

CI on the first head (adba4f7648e, https://github.com/openclaw/openclaw/actions/runs/36423201618):

@clawsweeper

clawsweeper Bot commented Sep 28, 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 28, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Maintainer security review required

This external contributor PR changes sensitive security components. A maintainer must review these changes before merging.

Current SHA: 5e4b95f203b5bbf941e4475ad9cf5782a999da07

These sensitive security changes were made:

  • src/agents/auth-profiles/upsert-with-lock.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

After reviewing the changes, post a new PR comment containing only approval commands, each on its own line:

/allow-security-sensitive-change

A later push requires a fresh approval comment.

@clawsweeper clawsweeper Bot added P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 28, 2026, 10:14 AM ET / 14:14 UTC (Revision 2).

ClawSweeper review

What this changes

Saving a manual provider API key now clears that saved profile’s cooldown and failure counters while preserving usage history.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open. Current main still retains a saved profile’s cooldown when its API key is replaced, and the PR provides convincing Gateway-path before/after evidence for the repair. The linked issue also discusses inline-key rotation, which this PR does not claim to fix.

Priority: P0
Reviewed head: 5e4b95f203b5bbf941e4475ad9cf5782a999da07
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-level repair, meaningful persisted-state regression coverage, and direct Gateway-path before/after proof support a strong review rating.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The changed locked credential owner is reached through the real Gateway models.authSetApiKey method followed by an agent turn against an isolated local provider proxy; after a simulated 429 and key replacement, the trace shows the new key reaching the provider and receiving a reply. A persisted preexisting cooldown regression covers the unchanged storage format and verifies existing-state compatibility.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The changed locked credential owner is reached through the real Gateway models.authSetApiKey method followed by an agent turn against an isolated local provider proxy; after a simulated 429 and key replacement, the trace shows the new key reaching the provider and receiving a reply. A persisted preexisting cooldown regression covers the unchanged storage format and verifies existing-state compatibility.
Evidence reviewed 8 items Introduced repair: The pinned PR adds a failure-state reset to the locked upsert and enables it for manual API-key saves.
Current-main gap: The fetched main revision saves the replacement key without requesting a failure-state reset; its upsert leaves existing usage statistics in place.
Product entry point: The Models page calls models.authSetApiKey, whose Gateway handler invokes the same manual-key writer used by the PR proof.
Findings None None.
Security None None.

How this fits together

The Models page and CLI send API-key changes to the Gateway’s model-auth writer. Agent requests then read saved credentials and their health state to decide whether to call the provider.

flowchart LR
  A[Models page or CLI] --> B[Gateway key save]
  B --> C[Locked profile write]
  C --> D[Credential and health state]
  D --> E[Agent profile selection]
  E --> F[Provider request]
Loading

Decision needed

Question Recommendation
Does the current PR head preserve credential scope and storage safety while clearing the replaced saved profile’s failure state? Approve the scoped reset: Approve this head after confirming the reset stays within the authorized profile write and does not expose or redirect credentials.

Why: The repository’s exact-head security-sensitive gate requires a maintainer’s credential-path review and approval; this read-only review cannot grant it.

Before merge

  • Complete next step (P2) - Obtain the repository’s exact-head security-sensitive maintainer review and approval before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +8, Tests +23. Total +31 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 8 0 +8
Tests 2 38 15 +23
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 46 15 +31

Review metrics

Metric Value Why it matters
Regression-test cost 1 added; 1.2 s reported CI test time The PR reports the new persisted-state regression’s execution cost as required by repository test policy.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #151354
Summary: This PR is a candidate repair for the linked issue’s saved-profile cooldown failure; its inline-key concern is outside this branch.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Land the saved-profile repair after the required credential-path approval, and assess inline-key rotation separately against the linked issue’s remaining behavior.

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

Yes. The contributor records a before/after Gateway call and agent turn with an injected 429; current-main source retains the same cooldown path, although this reviewer did not execute it.

Is this the best way to solve the issue?

Yes for saved profiles. Resetting only the written profile’s failure state at the credential owner is a narrow repair; inline-key rotation remains separate.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P0: A rotated saved key remains unusable for agent turns until cooldown expiry or a technical restart, blocking recovery.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The changed locked credential owner is reached through the real Gateway models.authSetApiKey method followed by an agent turn against an isolated local provider proxy; after a simulated 429 and key replacement, the trace shows the new key reaching the provider and receiving a reply. A persisted preexisting cooldown regression covers the unchanged storage format and verifies existing-state compatibility.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed locked credential owner is reached through the real Gateway models.authSetApiKey method followed by an agent turn against an isolated local provider proxy; after a simulated 429 and key replacement, the trace shows the new key reaching the provider and receiving a reply. A persisted preexisting cooldown regression covers the unchanged storage format and verifies existing-state compatibility.

Evidence

What I checked:

  • Introduced repair: The pinned PR adds a failure-state reset to the locked upsert and enables it for manual API-key saves. (src/agents/auth-profiles/upsert-with-lock.ts:421, 5e4b95f203b5)
  • Current-main gap: The fetched main revision saves the replacement key without requesting a failure-state reset; its upsert leaves existing usage statistics in place. (src/commands/models/auth-api-key.ts:144, eed9d9bf225e)
  • Product entry point: The Models page calls models.authSetApiKey, whose Gateway handler invokes the same manual-key writer used by the PR proof. (src/gateway/server-methods/models-auth-status.ts:348, 5e4b95f203b5)
  • Existing-state regression coverage: The new test seeds a persisted profile with an active rate-limit cooldown, replaces its key, and checks that failure state clears while lastUsed remains. (src/commands/models/auth-api-key.test.ts:199, 5e4b95f203b5)
  • Production-path proof: The PR body records an isolated built Gateway using models.authSetApiKey and an agent turn against a local provider proxy: before the change the replacement turn made zero provider requests; afterward it sent the new key and received a reply. This is contributor-supplied terminal evidence, not a run repeated by this reviewer. (5e4b95f203b5)
  • Linked issue scope: The linked issue and its prior Codex review identify saved-profile cooldown retention and a separate possible inline-key path; this PR explicitly limits itself to saved profiles.

Likely related people:

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

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-28T12:45:19.748Z sha adba4f7 :: blocked before merge. :: none

@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator

Thank you for tracing this to the saved profile’s retained failure state and providing the scoped fix. This branch now conflicts with main; I carried the repair forward in #169528 with Co-authored-by credit for Masato Hoshino. The current-main reproduction uses the real Models → Set API key flow and an isolated 429 stub: the replacement is saved but the next request makes zero provider calls; the port sends key B and succeeds. Leaving this PR open for Ayaan to close.

obviyus added a commit that referenced this pull request Oct 12, 2026
…9528)

Related: #151354. Carries forward the saved-profile repair from #160452, which conflicts with current main.

## What Problem This Solves

Fixes: after a provider key hits a rate limit, saving a replacement in Settings → Models reports success but the next request is still blocked by the old key's cooldown.

## User Impact

User impact: operators can use a replacement API key immediately without restarting the Gateway or waiting for the old key's cooldown. Other accounts, profile order, and usage history stay unchanged.

## Why This Change Was Made

Clear only the replaced profile's failure state in the same locked credential write. Models and `models auth paste-api-key` already share this writer; generic writes remain health-preserving unless explicitly asked to reset.

Why it was this way: #124014 deliberately restricted failure-state resets to successful credential replacement rather than clearing every account before login; #144420 later shared manual key editing through the generic writer without opting into that reset. This applies the existing scoped-reset contract to manual keys while keeping its sibling-account and usage-history protections.

No overlap with Pash/Sarah changes.

## Evidence

Built isolated Gateways with a loopback OpenAI-compatible stub and dummy keys. Both runs use the actual Models page's **Set API key** action, then the already-connected Gateway transport for the next agent request:

| Step | Current main (`cbba7e2e2ef4`) | This change (`6dfd10508f8a`) |
| --- | --- | --- |
| Save key A; request returns HTTP 429 | Rate-limit failure and persisted cooldown | Same |
| Save key B in Models | “Secret saved.” | “Secret saved.” |
| Immediately request again | `Auth profile "rotation:manual" is temporarily unavailable`; zero provider calls | Stub receives key B and replies “Key B works immediately after rotation.” |

The screenshots show the saved-key state. The request results above come from Gateway responses and the stub's recorded requests, not from an inferred screenshot result.

| Before | After |
| --- | --- |
| ![Before: replacement saved but model remains unavailable](https://github.com/user-attachments/assets/59947379-f7ee-497c-9d5f-8b7e11212895) | ![After: replacement saved and model is available](https://github.com/user-attachments/assets/e4ec28d3-222e-4881-8fe2-27e99ccf617e) |

- Extended the existing configured/explicit/ordered key-replacement regression: all three cases fail on main because the old cooldown and failure count survive; all pass with the fix. It also preserves a sibling's failure state and the replaced profile's `lastUsed`.
- Focused command, locked SQLite writer, and Gateway auth suites: **152 tests passed across four files**. Formatting and `git diff --check` passed.
- Final bounded Codex review found no actionable defects.

Scope: saved API-key replacement only. The second issue report about stale stored credentials taking precedence over a directly edited config key remains separate; this does not change credential precedence, doctor migration, or logging.

Merge danger: two-way door for future saves; reverting restores the old save behavior, but cannot reconstruct cooldown counters already cleared. Blast radius is the one saved API-key profile explicitly replaced through Models or the shared CLI writer. No schema, permission, storage-location, or credential-disclosure changes.

Co-authored-by: Masato Hoshino <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator

Thanks @masatohoshino. This fix landed in #169528 (2b9aa2e) with you credited as co-author, so I'm closing this one as replaced. Saving a new API key in Models now clears the old key's cooldown.

@obviyus obviyus closed this Oct 12, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…nclaw#169528)

Related: openclaw#151354. Carries forward the saved-profile repair from openclaw#160452, which conflicts with current main.

## What Problem This Solves

Fixes: after a provider key hits a rate limit, saving a replacement in Settings → Models reports success but the next request is still blocked by the old key's cooldown.

## User Impact

User impact: operators can use a replacement API key immediately without restarting the Gateway or waiting for the old key's cooldown. Other accounts, profile order, and usage history stay unchanged.

## Why This Change Was Made

Clear only the replaced profile's failure state in the same locked credential write. Models and `models auth paste-api-key` already share this writer; generic writes remain health-preserving unless explicitly asked to reset.

Why it was this way: openclaw#124014 deliberately restricted failure-state resets to successful credential replacement rather than clearing every account before login; openclaw#144420 later shared manual key editing through the generic writer without opting into that reset. This applies the existing scoped-reset contract to manual keys while keeping its sibling-account and usage-history protections.

No overlap with Pash/Sarah changes.

## Evidence

Built isolated Gateways with a loopback OpenAI-compatible stub and dummy keys. Both runs use the actual Models page's **Set API key** action, then the already-connected Gateway transport for the next agent request:

| Step | Current main (`b372edb6424e`) | This change (`6dfd10508f8a`) |
| --- | --- | --- |
| Save key A; request returns HTTP 429 | Rate-limit failure and persisted cooldown | Same |
| Save key B in Models | “Secret saved.” | “Secret saved.” |
| Immediately request again | `Auth profile "rotation:manual" is temporarily unavailable`; zero provider calls | Stub receives key B and replies “Key B works immediately after rotation.” |

The screenshots show the saved-key state. The request results above come from Gateway responses and the stub's recorded requests, not from an inferred screenshot result.

| Before | After |
| --- | --- |
| ![Before: replacement saved but model remains unavailable](https://github.com/user-attachments/assets/59947379-f7ee-497c-9d5f-8b7e11212895) | ![After: replacement saved and model is available](https://github.com/user-attachments/assets/e4ec28d3-222e-4881-8fe2-27e99ccf617e) |

- Extended the existing configured/explicit/ordered key-replacement regression: all three cases fail on main because the old cooldown and failure count survive; all pass with the fix. It also preserves a sibling's failure state and the replaced profile's `lastUsed`.
- Focused command, locked SQLite writer, and Gateway auth suites: **152 tests passed across four files**. Formatting and `git diff --check` passed.
- Final bounded Codex review found no actionable defects.

Scope: saved API-key replacement only. The second issue report about stale stored credentials taking precedence over a directly edited config key remains separate; this does not change credential precedence, doctor migration, or logging.

Merge danger: two-way door for future saves; reverting restores the old save behavior, but cannot reconstruct cooldown counters already cleared. Blast radius is the one saved API-key profile explicitly replaced through Models or the shared CLI writer. No schema, permission, storage-location, or credential-disclosure changes.

Co-authored-by: Masato Hoshino <[email protected]>
Co-authored-by: Ayaan Zaidi <[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 commands Command implementations P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. security-review-required security-sensitive-changed size: S 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.

Feature Request: Auto-refresh model auth profiles when API keys change in Control UI

2 participants