Repository navigation
fix(models): a new API key saved in Models stays blocked by the old key's rate-limit cooldown - #160452
fix(models): a new API key saved in Models stays blocked by the old key's rate-limit cooldown#160452masatohoshino wants to merge 2 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
|
Codex review: blocked before merge. Reviewed September 28, 2026, 10:14 AM ET / 14:14 UTC (Revision 2). ClawSweeper reviewWhat this changesSaving 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 Review scores
Verification
How this fits togetherThe 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]
Decision needed
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
Agent review detailsSecurityNone. PR surfaceSource +8, Tests +23. Total +31 across 4 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest 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. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
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. |
…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 | | --- | --- | |  |  | - 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]>
|
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. |
…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 | | --- | --- | |  |  | - 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]>
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 withAuth profile "<provider>:manual" is temporarily unavailableuntil 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 optionalresetFailureStateflag that the batch writer already has; only the manual API-key save sets it. Usage history such aslastUsedis 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 (baseupstream/main3a306a430ea).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_exceededforkey-A; other keys reach the fake model. Keys are saved withopenclaw gateway call models.authSetApiKey, the Gateway method the Models page calls; turns are sent withopenclaw agent.Before (base
3a306a430ea):After (this PR):
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=cooldownafter 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 activerate_limitcooldown, saves a replacement, and checks the persisted failure state is cleared andlastUsedis 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:
pnpm test <file> --maxWorkers=1wallsrc/commands/models/auth-api-key.test.tschecks-node-changed-compact-large-*(shardagentic-commands-models, run https://github.com/openclaw/openclaw/actions/runs/36423201618)src/commands/models/auth.test.tsresetFailureState: trueoxfmt --check,git diff --check,pnpm check:changed --base upstream/main: passed.The
autoreviewskill on this head: no findings.CI on the first head (
adba4f7648e, https://github.com/openclaw/openclaw/actions/runs/36423201618):checks-node-changed-compact-large-10failed insrc/commands/models/auth.test.ts: three mock assertions expected the exact upsert arguments and did not include the newresetFailureState: true. Fixed in the second commit; the file passes locally (62 tests).checks-node-changed-compact-large-35failed insrc/gateway/server.config-patch.test.ts(openclaw.changes.list preserves an approved include-only operation...) withConfigMutationConflictError: active config environment changed while preparing write(marked retryable). This change does not touch config writes; the file passes on this branch locally (81 tests).checks-ui-e2e (4/9)failed inui/src/e2e/session-progress-widget.e2e.test.ts(keeps target liveness when the selected agent scope changes). The same test fails in the same shard on many unrelated pull requests the same day, for example https://github.com/openclaw/openclaw/actions/runs/36425181979, https://github.com/openclaw/openclaw/actions/runs/36423815421 and https://github.com/openclaw/openclaw/actions/runs/36417805300. This change has no UI code.check-dependencieswas canceled at its time limit while the dead-code scan was still running; no check reported a finding.openclaw/ci-gatefollows from the failures above and the pending security-sensitive approval.