Skip to content

fix(auth-profiles): keep per-model quota buckets usable under an account block - #125573

Closed
jesse-merhi wants to merge 1 commit into
mainfrom
jesse/auth-profile-model-scoped-quota
Closed

jesse-merhi wants to merge 1 commit into
mainfrom
jesse/auth-profile-model-scoped-quota

Conversation

@jesse-merhi

Copy link
Copy Markdown
Member

What Problem This Solves

An OpenAI account can exhaust its account-wide window while individual models keep their own separate, unexhausted allowance. The usage probe already receives those per-model buckets in additional_rate_limits, but nothing parsed the field, so a quota block covered every model on the profile.

The result is that the model fallback chain goes dark exactly when it is supposed to take over. Observed on a live gateway: all four OpenAI profiles reported primary_window.used_percent: 100, while every one of them also reported

{"limit_name": "GPT-5.3-Codex-Spark", "metered_feature": "codex_bengalfox",
 "rate_limit": {"allowed": true, "limit_reached": false,
                "primary_window": {"used_percent": 0}}}

The configured chain was openai/gpt-5.6-sol -> openai/gpt-5.3-codex-spark. Sol hit the account limit, spark was correctly selected next, and then skipped:

[model-fallback/decision] decision=skip_candidate requested=openai/gpt-5.6-sol
candidate=openai/gpt-5.6-sol reason=rate_limit next=openai/gpt-5.3-codex-spark
detail=Provider openai is in cooldown

Every agent run on that gateway failed for ~13 hours with capacity sitting unused.

A second, smaller fault sat next to it. A usage probe rejected with HTTP 401 produced a flat 12h profile-wide cooldown that inherited the caller's rate_limit reason. That left cooldownReason: "rate_limit" with no cooldownModel — a reason that claims model scope on a record that blocks everything. isProfileUnusable can only narrow a model-scoped cooldown when a model is named, so it widened, and no consumer could tell a quota block from a dead token.

Why This Change Was Made

A block should describe exactly what the provider limited. Anything broader discards capacity the provider still grants, and a fallback chain whose whole purpose is surviving a quota limit must not be disabled by that limit.

The state model already supported narrowing (blockedModel, blockedScope, cooldownModel, isModelScopedCooldownReason); it had no way to express "the account window is spent, but these models are still served". blockExemptModels records exactly what the probe observed, and only that probe's observation may grant it — a stale list can never unblock a model the provider did not clear.

Model ids come from the reported bucket names by lowercasing, so there is no per-model table to maintain. An unrecognized name simply matches no model and changes nothing.

User Impact

When an account-wide quota is exhausted, models with their own unexhausted bucket stay usable and the fallback chain keeps working. Behavior is unchanged for providers that report no per-model buckets: absent additional_rate_limits means no exemptions and the block stays profile-wide, exactly as before.

A 401 from the probe is now recorded as auth. The 12h hold is unchanged and still profile-wide, which is correct for a credential the provider rejects — it is only labelled honestly now, so openclaw doctor, logs, and the cooldown predicates agree on what happened.

Persisted state gains one optional field. Older rows lack it and normalize to undefined, which is today's behavior; no migration is needed.

Evidence

Three regression tests, each failing on pre-fix code for its intended reason:

FAIL isProfileInCooldown > keeps a model with its own unexhausted bucket usable under an account-wide block
  AssertionError: gpt-5.6-luna: expected true to be false
FAIL WHAM-aware Codex cooldowns > keeps per-model buckets usable when the account-wide window is exhausted
  AssertionError: expected undefined to deeply equal [ 'gpt-5.6-luna' ]
FAIL WHAM-aware Codex cooldowns > records a probe auth rejection as an auth cooldown, not the request's rate limit
  AssertionError: expected 'rate_limit' to be 'auth'

Local validation, all green after the fix:

  • node scripts/run-vitest.mjs src/agents/auth-profiles — 27 files, 381 tests
  • node scripts/run-vitest.mjs src/agents/auth-profiles.getsoonestcooldownexpiry.test.ts src/agents/model-fallback.test.ts src/agents/model-fallback.probe.test.ts src/commands/models/list.status.test.ts src/commands/models/list.auth-overview.test.ts src/commands/doctor-auth.profile-health.test.ts src/commands/doctor/repair-sequencing.test.ts src/commands/doctor/shared/codex-route-warnings.test.ts — every suite consuming these predicates
  • pnpm tsgo:core, scripts/run-oxlint.mjs on changed files, oxfmt --check

Dependency contract proof: the additional_rate_limits shape above was read live from chatgpt.com/backend-api/codex/usage across four accounts, each returning an allowed spark bucket beside a 100%-used primary window.

Production delta is +75 lines against +59 test lines. The growth is the capability itself — a provider contract field that was not read, plus the state to carry the observation to the consumer that needs it. No behavior was duplicated and no path was left behind.

Proof gap: this fixes the block that made spark unreachable, but the account this was diagnosed on has no OpenAI capacity left in any window until 20 Aug, so a live end-to-end run of the fallback actually landing on spark is not possible right now. The probe parse is proven against the real payload, and the predicate change is proven by unit tests.

…unt block

An OpenAI account can exhaust its account-wide window while individual
models keep their own unexhausted allowance; the usage probe reports those
in `additional_rate_limits`. That field was never parsed, so a quota block
covered every model on the profile and the fallback chain skipped the one
model that still had capacity — the chain went dark exactly when it was
supposed to take over.

Record the models the probe observed as still allowed and let a
profile-wide block exclude them. Model ids come from the reported bucket
names by lowercasing, so no per-model table is needed and an unrecognized
name simply never matches (it cannot unblock anything by accident).

A probe rejected with 401 also stopped claiming the caller's `rate_limit`:
the probe, not the model request, is what failed there, and labelling a 12h
profile-wide hold as a model-scopable quota block left state that no
consumer could read correctly.
@clawsweeper

clawsweeper Bot commented Aug 18, 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.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Aug 18, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 18, 2026
@clawsweeper

clawsweeper Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 5, 2026, 4:10 AM ET / 08:10 UTC (Revision 8).

ClawSweeper review

What this changes

The branch preserves access to OpenAI models with separate available quota buckets during an account-wide block and labels usage-probe authentication failures correctly.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 8 items remain

The quota-exemption behavior remains missing on current main, so this maintainer-owned PR still has value. All three prior blockers remain, and successful exempt-model runs expose another lifecycle defect.

Priority: P1
Reviewed head: 5fe0eb140a7e63d8c9abe4cd4760dc13ea8433d5

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful owner-local work remains incomplete across quota refresh, success settlement, and authentication reporting.
Proof confidence 🌊 off-meta tidepool Not applicable: The ordinary external-contributor proof gate does not apply to this MEMBER-authored PR. Its captured live payload is before-fix evidence, not observed fallback recovery; the new serialized exemption field independently lacks SQLite upgrade/reopen proof.
Patch quality 🦐 gold shrimp (3/6) 4 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary external-contributor proof gate does not apply to this MEMBER-authored PR. Its captured live payload is before-fix evidence, not observed fallback recovery; the new serialized exemption field independently lacks SQLite upgrade/reopen proof.
Evidence reviewed 13 items Verified introduced change: Reviewed the pinned parent-to-head patch and original owner code. The introduced delta adds exemption parsing, persistence, eligibility handling, and a probe-auth override.
Exemption lifecycle and tests: Initial failure recording writes the exemptions, but half-open re-arming spreads existing state without replacing them. Existing half-open tests cover block deadlines and generation checks; the added exemption test covers only initial failure recording.
Auth override does not reach reporting: The probe override changes cooldownReason to auth, while failureCounts retains the request reason. Unavailable reporting reads those counts, and model-fallback-cooldown.ts uses its result to distinguish persistent authentication failures from transient quota failures.
Findings 4 actionable findings [P1] Refresh exemptions when a half-open probe re-arms a block
[P1] Use the probe's auth reason in unavailable reporting
[P2] Require affirmative bucket availability before exempting a model
Security None None.

How this fits together

Auth-profile health state determines which saved provider credentials and models OpenClaw may try. Provider usage probes update that state, which then feeds credential rotation, model fallback, and unavailable-provider diagnostics.

flowchart TD
  A[Model request failure] --> B[Provider usage probe]
  B --> C[Quota and credential classification]
  C --> D[Persisted profile health]
  D --> E[Model eligibility]
  E --> F[Credential rotation and fallback]
  D --> G[Operator diagnostics]
Loading

Before merge

  • Refresh exemptions when a half-open probe re-arms a block (P1) - The newly parsed result.exemptModels never reaches this re-arm path. After an initial exemption for model A, a later probe allowing only model B retains A and keeps B blocked. Replace the list from each authoritative probe, including clearing it when no exemptions remain.
  • Use the probe's auth reason in unavailable reporting (P1) - A request recorded as rate_limit followed by a probe 401 now has cooldownReason: auth, but its failure counts still contain rate_limit. resolveProfilesUnavailableReason ignores the new reason and reports a transient quota failure, so fallback recovery can probe a credential this patch classified as rejected. Carry the canonical reason through reporting, as current main already does.
  • Require affirmative bucket availability before exempting a model (P2) - An additional bucket with an absent or null rate_limit passes both negative checks and becomes exempt solely from its name. Upstream explicitly supports this shape. It conveys no available-capacity observation, so it must not bypass an active account block; require affirmative availability.
  • Preserve the account block after exempt-model success (P2) - Late discovery on the unchanged reviewed head: this bypass permits an exempt model to succeed while the account window is still exhausted. The production success hook then calls markAuthProfileSuccess, whose reset clears blockedUntil for the entire profile without knowing the successful model. Subsequent turns therefore retry exhausted models. Make successful-use settlement preserve quota restrictions that the exempt-model success does not disprove.
  • Resolve merge risk (P1) - The new persisted exemption field lacks actual old-state, older-reader, and candidate-reopen compatibility proof through the SQLite owner.
  • Resolve merge risk (P1) - The branch conflicts with main's extracted usage reducers and worker flows; integration must preserve those owners and canonical probe-auth classification.
  • Resolve merge risk (P2) - The live payload establishes one bucket-name example, but does not verify the changed fallback path or the general display-name-to-model mapping after the fix.
  • Complete next step (P2) - Repair the four lifecycle/reporting findings, integrate with current main's usage owners, and establish provider and persisted-state compatibility evidence before merge.

Findings

  • [P1] Refresh exemptions when a half-open probe re-arms a block — src/agents/auth-profiles/usage.ts:561-568
  • [P1] Use the probe's auth reason in unavailable reporting — src/agents/auth-profiles/usage.ts:286-288
  • [P2] Require affirmative bucket availability before exempting a model — src/agents/auth-profiles/usage.ts:224-227
Agent review details

Security

None.

PR surface

Source +75, Tests +59. Total +134 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 4 90 15 +75
Tests 1 59 0 +59
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 149 15 +134

Review metrics

Metric Value Why it matters
Production versus regression coverage production net +75 LOC; tests net +59 LOC; no pure moves Growth carries a previously unread provider observation, but coverage currently stops before reprobe, successful-run settlement, and persistence.
Stored health contract 1 optional persisted field added; 0 config options added The exemption list changes upgrade-sensitive health-state serialization without expanding operator configuration.

Merge-risk options

Maintainer options:

  1. Complete the quota lifecycle on current owners (recommended)
    Integrate with main's shared reducers, repair all four findings, and verify persisted upgrade behavior plus the actual quota fallback.
  2. Keep the draft paused
    Retain the useful proposal until the lifecycle repairs and provider/state evidence can be completed.

Technical review

Best possible solution:

Carry verified quota observations through main's shared reducers and persisted normalization, replacing exemptions on every probe while preserving unrelated active blocks after exempt-model success; the new per-model state justifies bounded growth.

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

Yes, source inspection establishes deterministic reprobe, missing-bucket, auth-reporting, and successful-run failure paths. They were not executed during this read-only review.

Is this the best way to solve the issue?

No, the initial exemption path is incomplete across refresh and successful-run settlement; main's canonical reducers and auth classification provide the maintainable integration boundary.

Full review comments:

  • [P1] Refresh exemptions when a half-open probe re-arms a block — src/agents/auth-profiles/usage.ts:561-568
    The newly parsed result.exemptModels never reaches this re-arm path. After an initial exemption for model A, a later probe allowing only model B retains A and keeps B blocked. Replace the list from each authoritative probe, including clearing it when no exemptions remain.
    Confidence: 0.99
  • [P1] Use the probe's auth reason in unavailable reporting — src/agents/auth-profiles/usage.ts:286-288
    A request recorded as rate_limit followed by a probe 401 now has cooldownReason: auth, but its failure counts still contain rate_limit. resolveProfilesUnavailableReason ignores the new reason and reports a transient quota failure, so fallback recovery can probe a credential this patch classified as rejected. Carry the canonical reason through reporting, as current main already does.
    Confidence: 0.99
  • [P2] Require affirmative bucket availability before exempting a model — src/agents/auth-profiles/usage.ts:224-227
    An additional bucket with an absent or null rate_limit passes both negative checks and becomes exempt solely from its name. Upstream explicitly supports this shape. It conveys no available-capacity observation, so it must not bypass an active account block; require affirmative availability.
    Confidence: 0.99
  • [P2] Preserve the account block after exempt-model success — src/agents/auth-profiles/usage-state.ts:81-84
    Late discovery on the unchanged reviewed head: this bypass permits an exempt model to succeed while the account window is still exhausted. The production success hook then calls markAuthProfileSuccess, whose reset clears blockedUntil for the entire profile without knowing the successful model. Subsequent turns therefore retry exhausted models. Make successful-use settlement preserve quota restrictions that the exempt-model success does not disprove.
    Confidence: 0.98
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P1: The reported quota condition disables a real model-fallback workflow despite available provider capacity.
  • merge-risk: 🚨 auth-provider: Stale or unverified exemptions and inconsistent authentication reporting can select unavailable models or apply the wrong recovery policy.
  • merge-risk: 🚨 compatibility: The added serialized health field needs verified upgrade and reopen behavior through the current persistence owners.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The ordinary external-contributor proof gate does not apply to this MEMBER-authored PR. Its captured live payload is before-fix evidence, not observed fallback recovery; the new serialized exemption field independently lacks SQLite upgrade/reopen proof.

Evidence

What I checked:

  • Verified introduced change: Reviewed the pinned parent-to-head patch and original owner code. The introduced delta adds exemption parsing, persistence, eligibility handling, and a probe-auth override. (src/agents/auth-profiles/usage.ts:223, 5fe0eb140a7e)
  • Exemption lifecycle and tests: Initial failure recording writes the exemptions, but half-open re-arming spreads existing state without replacing them. Existing half-open tests cover block deadlines and generation checks; the added exemption test covers only initial failure recording. (src/agents/auth-profiles/usage.ts:561, 5fe0eb140a7e)
  • Auth override does not reach reporting: The probe override changes cooldownReason to auth, while failureCounts retains the request reason. Unavailable reporting reads those counts, and model-fallback-cooldown.ts uses its result to distinguish persistent authentication failures from transient quota failures. (src/agents/auth-profiles/usage.ts:286, 5fe0eb140a7e)
  • Successful fallback clears unrelated quota: The new eligibility bypass permits a successful exempt-model run while the account block remains active. The production success hook invokes markAuthProfileSuccess, whose reset clears blockedUntil and related block metadata without receiving the successful model. (src/agents/auth-profiles/profiles.ts:75, 5fe0eb140a7e)
  • Dependency-contract signal: resolveWhamExemptModels interprets additional_rate_limits from the OpenAI usage response, and the PR explicitly claims compatibility with a live Codex usage payload. This makes the upstream usage-response contract relevant; it is not inferred merely from the Codex name. (src/agents/auth-profiles/usage.ts:223, 5fe0eb140a7e)
  • Direct upstream contract inspection: Verified repository ownership through the sibling cache's GitHub origin. AdditionalRateLimitDetails allows rate_limit to be absent or null; the backend-client test explicitly exercises an additional bucket without rate-limit details. Personally inspected the runtime mapper at backend-client/src/client.rs:522-588 as well. (codex-rs/codex-backend-openapi-models/src/models/additional_rate_limit_details.rs:27, be6e8eac029b)

Likely related people:

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

  • Repair exemption refresh, affirmative availability, and successful-run settlement with boundary regressions.
  • Integrate with main's shared reducers and canonical probe-auth reporting.
  • Verify actual quota fallback and old-state/older-reader/candidate-reopen persistence behavior.

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 (7 earlier review cycles)
  • reviewed 2026-08-18T04:09:40.447Z sha 5fe0eb1 :: found issues before merge. :: [P1] Refresh exemptions when a half-open probe re-arms a block | [P1] Carry a probe 401's auth reason into reason aggregation
  • reviewed 2026-08-22T14:04:34.587Z sha 5fe0eb1 :: found issues before merge. :: [P1] Refresh exemptions when re-arming a WHAM block | [P1] Use the probe auth reason in unavailable-reason aggregation
  • reviewed 2026-08-25T14:37:13.678Z sha 5fe0eb1 :: needs changes before merge. :: [P1] Refresh exemptions when a half-open probe re-arms a block | [P1] Propagate probe auth into unavailable-reason aggregation
  • reviewed 2026-09-02T07:25:41.400Z sha 5fe0eb1 :: found issues before merge. :: [P1] Refresh exemptions on every half-open re-probe | [P1] Aggregate the probe's canonical auth reason
  • reviewed 2026-09-03T10:12:31.004Z sha 5fe0eb1 :: blocked before merge. :: [P1] Refresh exemptions on every half-open re-probe | [P1] Honor the probe's authoritative cooldown reason
  • reviewed 2026-09-27T11:03:07.182Z sha 5fe0eb1 :: blocked before merge. :: [P1] Refresh exemptions when a half-open probe re-arms a block | [P1] Use the probe's auth reason in unavailable reporting | [P2] Require affirmative bucket availability before exempting a model
  • reviewed 2026-09-27T12:44:30.402Z sha 5fe0eb1 :: blocked before merge. :: [P1] Refresh exemptions when a half-open probe re-arms a block | [P1] Use the probe's auth reason in unavailable reporting | [P2] Require affirmative bucket availability before exempting a model

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 22, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 3, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Oct 5, 2026
@steipete

Copy link
Copy Markdown
Contributor

Thanks for the PR. We're closing older pull requests that have gone stale against current main.

This draft has had no commits since August 18 and review left 8 blocking items; closing as stale. Please reopen or open a fresh PR if per-model quota buckets are still needed.

@steipete steipete closed this Oct 24, 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 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. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants