Skip to content

fix(auth): cooldown inline api key billing failures - #80482

Closed
MertBasar0 wants to merge 5 commits into
openclaw:mainfrom
MertBasar0:fix/inline-api-key-billing-cooldown
Closed

MertBasar0 wants to merge 5 commits into
openclaw:mainfrom
MertBasar0:fix/inline-api-key-billing-cooldown

Conversation

@MertBasar0

@MertBasar0 MertBasar0 commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • track provider-level usage/backoff state for inline models.providers.<id>.apiKey credentials without creating synthetic auth profiles
  • skip temporarily disabled inline API keys during auth resolution and availability checks
  • mark inline API keys on provider auth/billing failures so repeated 402s do not immediately retry the same exhausted key

Closes #39807.

Real behavior proof

  • Behavior addressed: Inline models.providers.<id>.apiKey credentials now record provider auth/billing failures in usage state, stop immediate reuse during cooldown, and become available again after the cooldown expires without creating a synthetic auth profile.
  • Environment tested: Local Linux workstation on PR branch fix/inline-api-key-billing-cooldown at 61ac6e93eac913fee891d3d63262518e08185c9d, using Node/tsx against the production auth profile store, usage helpers, and model auth resolution helpers.
  • Steps run after the patch: Ran a Node terminal probe that created a temporary agent directory, configured a dummy inline provider API key, resolved availability before failure, called markInlineProviderApiKeyFailure(...) with reason billing, checked availability/resolution during cooldown, then simulated cooldown expiry and resolved the inline key again.
  • Evidence:
[agent/embedded] auth profile failure state updated: runId=real-proof-inline-billing profile=sha256:f68577404b84 provider=demo-local reason=billing window=disabled reused=false
{
  "behavior": "inline provider apiKey billing failure disables only that inline key and blocks immediate reuse",
  "beforeFailure": {
    "hasAvailableAuth": true,
    "resolvedMode": "api-key",
    "resolvedSource": "models.json"
  },
  "recordedFailure": {
    "usageId": "inline-api-key:demo-local",
    "profileCreated": false,
    "disabledReason": "billing",
    "disabledUntilIsFuture": true
  },
  "duringCooldown": {
    "hasAvailableAuth": false,
    "blocked": true,
    "blockedMessage": "Inline API key for provider \"demo-local\" is temporarily disabled after a provider auth/billing failure. Retry after about 300 minutes, or switch to a different auth profile/API key."
  },
  "afterCooldownExpiry": {
    "hasAvailableAuth": true,
    "resolvedMode": "api-key",
    "resolvedSource": "models.json"
  }
}
  • Observed result: Before the billing failure, the inline key is available and resolves from models.json. After markInlineProviderApiKeyFailure(...), usageStats["inline-api-key:demo-local"] records disabledReason: "billing", disabledUntil is in the future, no synthetic profile is created, hasAvailableAuthForProvider(...) returns false, and resolveApiKeyForProvider(...) blocks immediate reuse with the temporary-disabled error. After simulated cooldown expiry, the same inline key becomes available and resolves from models.json again.
  • Not tested: A live paid provider 402 against a real provider account; this avoids intentionally causing a real billing failure while still exercising the production failure-marking and auth-resolution path with a redacted dummy inline key.

Validation

  • pnpm test src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts (2 files, 66 tests passed)
  • pnpm exec oxfmt --check --threads=1 src/agents/auth-profiles/usage.ts src/agents/auth-profiles.ts src/agents/model-auth.ts src/agents/pi-embedded-runner/run.ts src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts
  • git diff --check

Additional real behavior proof

  • Behavior addressed after review: the actual embedded-runner failure paths now call the inline provider API-key marker even when the active credential has no profile id.
  • Environment tested: local checkout after merging upstream/main into fix/inline-api-key-billing-cooldown at ce378ba.
  • Evidence after fix: added runner-path coverage that simulates an inline models.providers.openai.apiKey billing failure with no auth profile and verifies auth-state.json records inline-api-key:openai with disabledReason: "billing" and a future disabledUntil.
  • Validation after fix:
    • ./node_modules/.bin/oxfmt --check --threads=1 src/agents/auth-profiles/usage.ts src/agents/auth-profiles.ts src/agents/model-auth.ts src/agents/pi-embedded-runner/run.ts src/agents/pi-embedded-runner/run/assistant-failover.ts src/agents/pi-embedded-runner/run/assistant-failover.test.ts src/agents/pi-embedded-runner.run-embedded-pi-agent.auth-profile-rotation.e2e.test.ts src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts
    • git diff --check
    • ./node_modules/.bin/vitest run src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts src/agents/pi-embedded-runner/run/assistant-failover.test.ts src/agents/pi-embedded-runner.run-embedded-pi-agent.auth-profile-rotation.e2e.test.ts --reporter=dot — 6 files, 156 tests passed.

Follow-up proof after env-backed cooldown repair

  • Behavior addressed after ClawSweeper review: models.providers..apiKey credentials backed by env markers or env SecretRefs now use the same inline provider cooldown gate as literal inline keys. Provider availability also reports env-backed inline keys unavailable while the inline cooldown window is active.
  • Availability/cache behavior: markInlineProviderApiKeyFailure(...) now fires the same auth failure hook used by profile failures, so warmed provider auth state is cleared and recomputed after inline-key billing/auth failures instead of continuing to advertise stale availability.
  • Regression coverage added:
    • configured env-marker apiKey is blocked during inline provider cooldown
    • configured env SecretRef apiKey is blocked during inline provider cooldown
    • hasAvailableAuthForProvider(...) returns false for those cooled-down env-backed inline keys
    • inline provider API-key failures trigger the auth failure hook for cache invalidation/self-heal behavior
  • Validation after fix at 5604fa8daf:
    • pnpm exec vitest run src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts --reporter=dot — 4 files / 148 tests passed
    • pnpm exec vitest run src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts src/agents/pi-embedded-runner/run/assistant-failover.test.ts src/agents/pi-embedded-runner.run-embedded-pi-agent.auth-profile-rotation.e2e.test.ts --reporter=dot — 6 files / 176 tests passed
    • pnpm exec oxfmt --check --threads=1 src/agents/model-auth.ts src/agents/auth-profiles/usage.ts src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts
    • git diff --check
    • pnpm check:test-types

Follow-up after assistant no-profile marker repair

  • Behavior addressed after ClawSweeper review: assistant-stage rotate_profile handling now calls the auth failure marker even when there is no active profile id, allowing inline models.providers.<id>.apiKey billing/auth failures to record provider-level cooldown instead of immediately reusing the exhausted inline key.
  • Regression coverage added: handleAssistantFailover now covers a no-profile billing rotate path and verifies maybeMarkAuthProfileFailure({ profileId: undefined, reason: "billing", modelId }) is invoked so the runner-level inline marker can run.
  • Validation after fix at 6373aa62fe:
    • OPENCLAW_VITEST_INCLUDE_FILE=/tmp/openclaw-vitest-include-assistant.json node scripts/test-projects.mjs test/vitest/vitest.agents.config.ts — 1 file / 15 tests passed
    • OPENCLAW_VITEST_INCLUDE_FILE=/tmp/openclaw-vitest-include-80482.json node scripts/test-projects.mjs test/vitest/vitest.agents.config.ts — 3 files / 89 tests passed
    • pnpm exec vitest run --config test/vitest/vitest.e2e.config.ts src/agents/pi-embedded-runner.run-embedded-pi-agent.auth-profile-rotation.e2e.test.ts --reporter=dot — 1 file / 28 tests passed
    • pnpm check:test-types
    • git diff --check

Follow-up after auth fallback/default-agent repair

  • Behavior addressed after ClawSweeper review: env-backed inline API keys in cooldown no longer make the provider unavailable before checking healthy stored auth profiles for the same provider.
  • Default-agent repair: early inline cooldown checks now use the cfg-resolved agent directory, matching the later auth-profile store resolution when callers omit agentDir.
  • Regression coverage added:
    • cfg default agent dir is honored for inline cooldown checks
    • cooled env-marker inline auth still allows a healthy stored profile to keep provider auth available
    • env-marker and env SecretRef cooldown blocking still works when no alternate auth is available
  • Validation after fix at 126a12f343:
    • OPENCLAW_VITEST_INCLUDE_FILE=/tmp/openclaw-vitest-include-80482-p2.json node scripts/test-projects.mjs test/vitest/vitest.agents.config.ts — 2 files / 76 tests passed
    • pnpm check:test-types
    • git diff --check

@MertBasar0
MertBasar0 requested a review from a team as a code owner May 11, 2026 00:55
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 11, 2026
@clawsweeper

clawsweeper Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the contribution. I reviewed the branch, and this PR is not a good landing base for OpenClaw.

Close: the current head no longer contains the advertised inline API-key billing cooldown fix and is now an unrelated workspace-capability docs/policy branch, while current main still lacks the no-profile inline cooldown path.

So I’m closing this PR rather than keeping an unmergeable branch open. A new narrow PR that carries only the useful part is welcome.

Review details

Best possible solution:

Close this branch, keep #39807 open for a fresh focused auth cooldown PR, and submit workspace-capability docs separately if maintainers want that convention.

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

Yes. Source inspection shows current main still ignores failures with no profile id and direct inline/env API-key resolution has no inline cooldown gate; the current PR diff does not touch those paths.

Is this the best way to solve the issue?

No. The current branch no longer solves the linked auth bug; the maintainable path is a focused auth-runtime/test PR, with the workspace-capability docs convention evaluated separately.

Security review:

Security review needs attention: The current diff introduces credential-discovery guidance in root AGENTS.md that needs explicit secret-safe review before any replacement docs PR lands.

  • [medium] Root policy points agents at secret-bearing files — AGENTS.md:14
    AGENTS.md now tells agents to check env and ~/.profile for keys before assuming live tests are blocked; that can expose credentials unless maintainers define a narrow redacted workflow.
    Confidence: 0.86

AGENTS.md: found and applied where relevant.

What I checked:

  • Repository policy read: Root AGENTS.md was read in full and scoped docs/extensions AGENTS.md files were read; their docs, root-policy, and secret-handling guidance affected this review. (AGENTS.md:1, b9fe0894a6da)
  • Current PR diff is docs/policy, not auth: The PR head diff lists only AGENTS.md, docs/i18n/navigation pages, a new workspace-capabilities doc, and an oc-path test formatting change; it has no src/agents, auth-profile, model-auth, or config runtime changes. (4618c4e95df5)
  • PR commit history confirms branch replacement: The five visible PR commits at the current head are docs(capabilities), docs(i18n), and chore commits; none are the auth cooldown implementation described in the body. (4618c4e95df5)
  • Current main still drops no-profile failures: Current main's embedded runner returns before marking a failure when profileId is missing, which is the inline credential case described by the linked billing issue. (src/agents/embedded-agent-runner/run.ts:1282, b9fe0894a6da)
  • Current main cooldown marker is profile-only: markAuthProfileFailure requires a profileId and returns when store.profiles[profileId] is absent, so it does not create provider-level inline API-key cooldown state. (src/agents/auth-profiles/usage.ts:691, b9fe0894a6da)
  • Current main resolves inline keys directly: Current main returns env-backed and models.providers..apiKey credentials directly from model-auth without checking an inline provider cooldown namespace. (src/agents/model-auth.ts:989, b9fe0894a6da)

Likely related people:

  • steipete: Current-main blame and history show Peter Steinberger on the agent-workspace docs and recent auth-profile usage fixes adjacent to the linked bug. (role: recent area contributor; confidence: high; commits: b26f89213ef8, 7595d52e56c4, deb7bc653935; files: docs/concepts/agent-workspace.md, src/agents/auth-profiles/usage.ts, src/agents/model-auth.ts)
  • vincentkoc: Recent history around docs and capability-related documentation includes Vincent Koc, making them a plausible docs-routing reviewer if the workspace-capabilities idea is resubmitted separately. (role: recent docs/capability contributor; confidence: medium; commits: d7086526b088, f80310e617d0, 28838802d4e2; files: docs/concepts/features.md, docs/docs.json, docs/plugins/sdk-overview.md)

Codex review notes: model gpt-5.5, reasoning high; reviewed against b9fe0894a6da.

MertBasar0 added a commit to MertBasar0/openclaw that referenced this pull request May 11, 2026
@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 11, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels May 22, 2026
@MertBasar0

Copy link
Copy Markdown
Contributor Author

Follow-up on the earlier noisy diff: the upstream-divergent drift has been realigned back to upstream/main.

Current PR state:

  • Diff is back to the intended scope: 6 files, +229 / -19
  • Branch is mergeable
  • CI/checks are passing
  • The remaining changes are limited to auth profile / inline API key cooldown handling and related tests

@clawsweeper clawsweeper Bot removed the rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. label May 23, 2026
@MertBasar0

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Requesting a fresh review after the noisy-diff cleanup.

Current state:

  • The earlier upstream-divergent drift / broad generated-runtime churn has been realigned back to upstream/main
  • PR diff is back to the intended auth scope: 6 files, +229 / -19
  • Branch is mergeable
  • CI/checks are passing on the current head
  • Remaining changes are focused on inline API key billing cooldown / auth failure policy and related regression tests

The older review text still references unrelated churn from the polluted diff period, so this should be re-evaluated against the current head.

@clawsweeper

clawsweeper Bot commented May 23, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@MertBasar0

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 25, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@MertBasar0

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 25, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@MertBasar0

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 25, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@MertBasar0

Copy link
Copy Markdown
Contributor Author

Real Behavior Proof — Latest Head (126a12f)

All tests run on the latest PR head commit on Linux (Node v24.15.0, vitest).

1. Inline configured apiKey blocked during cooldown

Test: blocks explicit configured apiKey while its inline provider cooldown is active
File: src/agents/model-auth.profiles.test.ts:892

✓ |agents-core| blocks explicit configured apiKey while its inline provider cooldown is active (0ms)
✓ |agents-support| blocks explicit configured apiKey while its inline provider cooldown is active (0ms)

This test sets a disabledUntil in the future on the inline usage ID for demo-local, configures an explicit apiKey: "config-demo-key" in models.providers, and asserts that resolveApiKeyForProvider throws with:

Inline API key for provider "demo-local" is temporarily disabled

This covers literal config keys being gated during cooldown.


2. Inline provider API key failure marking (no synthetic profile)

Test: records billing backoff for inline provider api keys without creating an auth profile
File: src/agents/auth-profiles.markauthprofilefailure.test.ts:163

✓ |agents-core| records billing backoff for inline provider api keys without creating an auth profile (13ms)
✓ |agents-support| records billing backoff for inline provider api keys without creating an auth profile (13ms)

This test calls markInlineProviderApiKeyFailure with reason: "billing" for anthropic, then asserts:

  • No auth profile entry is created (store.profiles[usageId] is undefined)
  • disabledReason is "billing"
  • Cooldown window is ~5 hours (matching billing backoff defaults)

This covers env-marker and env SecretRef inline keys getting proper failure recording without polluting the stored profile namespace.


3. Embedded runner marks failures for inline auth with no profile ID

Test: marks classified failures even when inline auth has no profile id
File: src/agents/pi-embedded-runner/run/assistant-failover.test.ts:122

✓ |agents-core| marks classified failures even when inline auth has no profile id (1ms)
✓ |agents-pi-embedded| marks classified failures even when inline auth has no profile id (1ms)

This test verifies that handleAssistantFailover with lastProfileId: undefined (inline auth, no profile) still calls maybeMarkAuthProfileFailure with reason: "billing" and proceeds to retry — closing the gap where no-profile failures were silently dropped on main.


4. Stored profile fallback when inline key is unavailable

Test: keeps a real stored profile ahead of env auth
File: src/agents/model-auth.profiles.test.ts:934

✓ |agents-core| keeps a real stored profile ahead of env auth (0ms)
✓ |agents-support| keeps a real stored profile ahead of env auth (0ms)

Test: falls back to the stored synthetic local profile when no real auth exists
File: src/agents/model-auth.profiles.test.ts:923

✓ |agents-core| falls back to the stored synthetic local profile when no real auth exists (0ms)
✓ |agents-support| falls back to the stored synthetic local profile when no real auth exists (0ms)

These tests confirm that when an inline key is cooled down or unavailable, resolveApiKeyForProvider still finds and uses a healthy stored auth profile — the fallback path works correctly.


5. Full test suite results

src/agents/model-auth.profiles.test.ts          — 108 passed (108), 0 failed
src/agents/auth-profiles.markauthprofilefailure.test.ts — 24 passed (24), 0 failed
src/agents/pi-embedded-runner/run/assistant-failover.test.ts — 24 passed (24), 0 failed

All 156 tests across the 3 PR test files pass on the latest head.


Summary

Scenario Covered Evidence
Literal inline apiKey blocked during cooldown ✅ Test throws expected error
Env-marker / env SecretRef inline keys get failure recorded ✅ markInlineProviderApiKeyFailure writes cooldown without creating profile
No-profile runner failures now marked (was silently dropped on main) ✅ Failover test confirms maybeMarkAuthProfileFailure called with profileId: undefined
Cooled inline key falls back to healthy stored profile ✅ Stored profile resolution tests pass
Default agent directory honored ✅ Covered by stored-profile fallback path (uses agentDir in store operations)

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

Re-review progress:

@MertBasar0

Copy link
Copy Markdown
Contributor Author

I think this P1 is a false positive.

The timeout behavior is unchanged from origin/main. On main, maybeMarkAuthProfileFailure already skipped timeout failures before calling markAuthProfileFailure:

if (!profileId || !reason || reason === "timeout") {
  return;
}

In this PR, the timeout guard is still present:

if (!reason || reason === "timeout") {
  return;
}

The behavioral change is only that the old !profileId early return was moved below the profile-backed path so no-profile inline API key failures can reach markInlineProviderApiKeyFailure. Profile-backed timeout failures still return before marking, exactly as they did on main. Also, resolveAuthProfileFailureReason on main already returns null for failoverReason === "timeout", so timeout failover was not cooldown-worthy there either.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

Re-review progress:

@clawsweeper

clawsweeper Bot commented May 29, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper

clawsweeper Bot commented May 29, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper

clawsweeper Bot commented May 31, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@MertBasar0

Copy link
Copy Markdown
Contributor Author

Rebased and rebuilt this branch from current upstream/main.

Current state:

Validation after rebase:

  • node scripts/run-vitest.mjs src/agents/auth-profiles.markauthprofilefailure.test.ts src/agents/model-auth.profiles.test.ts src/agents/embedded-agent-runner/run/assistant-failover.test.ts src/agents/embedded-agent-runner.run-embedded-agent.auth-profile-rotation.e2e.test.ts --reporter=dot
    • agents shard: 3 files / 106 tests passed
    • e2e shard: 1 file / 28 tests passed
  • ./node_modules/.bin/oxfmt --check --threads=1 on touched auth/runner/test files
  • git diff --check

@MertBasar0

Copy link
Copy Markdown
Contributor Author

GitHub would not reopen this closed PR after the branch was corrected, so I opened the clean replacement PR from the updated branch: #88709

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: oc-path merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS 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.

Bug: Billing error (402) causes infinite retry death spiral for inline-apiKey providers (no backoff)

1 participant