Skip to content

fix(clawrouter): fall back immediately on exhausted upstream credit - #193250

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-clawrouter-credit-immediate-fallback-20260919
Nov 5, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-clawrouter-credit-immediate-fallback-20260919

Conversation

@steipete

@steipete steipete commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

ClawRouter's upstream 400 reporting credit balance is too low spends the in-run retry budget before reaching a configured fallback. The upstream grant is sticky within the router session, so those requests cannot recover. Follow-up to #192575.

User Impact

OpenClaw now sends one request to the depleted route, then immediately tries the configured fallback model. The shared router key remains available to other sessions. Strict model selections still surface an actionable error without silently switching models; genuine router authentication and budget failures still cool down the credential.

Why This Change Was Made

The provider hook returns the new generic route_unavailable reason. Core policy skips same-model retries and credential rotation, preserves credential health, and carries the reason through error payloads, protocol validation, and cron notifications. Existing reasons either retry, disable credentials, or imply an invalid/retired model. No new configuration, cache, or storage is introduced.

Release-note context: ClawRouter upstream credit exhaustion now immediately advances configured model fallbacks without disabling the shared router key or overriding strict model selection.

Evidence

The real HTTP integration fixture now keeps the upstream rejection sticky, exercises Anthropic → OpenAI transports through the actual runner and fallback owner, and asserts request order, key availability, peer success, and strict-selection error behavior. It fails on parent 04dbffb6936a with four requests instead of two; the fix produces one primary request followed by one fallback request.

333 focused failover/cron tests passed, plus the affected cron browser test and 16 cron/run-inspector browser E2E tests. The earlier focused invocation took 93.10 seconds including compilation and four test shards. After the two test-lint corrections, the final three-scenario integration rerun passed in 69.59 seconds wrapper wall and 32.98 seconds file duration.

Three paired A/A and B/B owner microbenchmarks, each with 2,000 synthetic session contexts, reduced primary attempts from 16,000 to 2,000 with zero credential-cooldown decisions in both arms. Median owner wall time was 84.595 → 11.451 ms/cohort, CPU 105.231 → 14.874 ms/cohort, and V8 sampled allocations 43,651 → 7,498 bytes/session. Clock/sleep and request cost are synthetic; this is not a live-provider or whole-Gateway performance claim. This path does not scan the session database or workspace inventory.

Authored production growth is 23 lines, plus two generated validator lines, to extend the existing closed reason contract and its owners. The dedicated 75-line test allocation covers the sticky wire regression and distinct retry, credential-health, strict-selection, and cron contracts.

Validation note: pnpm check:changed --staged completed all stages; its only errors were a shadowed variable and redundant spread in the expanded test. Both are fixed, scoped lint/format and the wire regression pass, and the complete core-lint stage passes with the same changed-file context used by check:changed. All other check:changed stages passed unchanged. Final Codex autoreview is scoped-clean through P2.

Exact-head CI run 41981673466 passed on attempt 2. Attempt 1 timed out downloading the Android emulator image before product tests started; a single job-specific infrastructure retry passed on the unchanged reviewed head.

Use the provider-owned route_unavailable reason to skip same-model retries and auth-profile rotation without cooling the shared key. Preserve strict model selection errors and actionable cron guidance. Extend the sticky HTTP regression to prove one primary request then fallback and retain auth/budget cooldown coverage. Follow-up to #192575.
@clawsweeper

clawsweeper Bot commented Nov 5, 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 docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling extensions: clawrouter Extension: clawrouter size: XL labels Nov 5, 2026
@steipete
steipete marked this pull request as ready for review November 5, 2026 06:37
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-05T06:40:23.869769Z f250321 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: f250321e84ef967b11304e648cf95e5874d11146
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/embedded-agent-runner/run/auth-profile-failure-policy.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@steipete
steipete enabled auto-merge (squash) November 5, 2026 06:47
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 5, 2026
@clawsweeper

clawsweeper Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

ClawRouter upstream credit exhaustion immediately advances configured model fallbacks while preserving shared credential health and strict model selection.

Example: ClawRouter returns HTTP 400 with “Your credit balance is too low to access the Anthropic API.”

  • Before: The depleted primary route consumes retries before the configured fallback runs.
  • After: One primary request is followed by the configured fallback; a strict selection instead receives guidance to choose another model.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A coherent, source-supported repair with meaningful real-transport integration coverage; evidence remains in-process and broad CI is pending.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; supplied evidence exercises the real embedded runner and HTTP clients against a sticky synthetic rejection, but includes no shipped CLI or Gateway capture.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A request waits through retries against a depleted ClawRouter route before its configured fallback can answer.
Reason: The maintainer-authored direction resolves a concrete recovery failure with a narrow generic reason while preserving strict selections and genuine credential cooldown.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a remaining failover defect on main, and review found no actionable introduced bug; CI is still pending.

Priority: P2
Reviewed head: f250321e84ef967b11304e648cf95e5874d11146

Before merge

None.

Findings

None.

Agent review details

How this fits together

The ClawRouter plugin classifies upstream failures; shared agent policies consume that classification to control retries, credential health, model fallback, and user-facing errors.

flowchart TD
  A[Upstream credit rejection] --> B[ClawRouter classifier]
  B --> C[Route unavailable reason]
  C --> D[Skip retries and credential rotation]
  D --> E[Configured model fallback]
  D --> F[Strict selection error]
  C --> G[Protocol and cron reporting]
Loading

Technical review

Best possible solution:

Use the provider-owned route classification and existing recovery policies to advance only authorized configured fallbacks without penalizing the shared key.

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

Current main retains server_error recovery for the reported HTTP 400 response, and the supplied sticky HTTP fixture exposes the extra attempts; this read-only review did not independently run it.

Is this the best way to solve the issue?

The change is a focused extension of existing owners: a depleted route must neither replay nor damage credential health, and no existing reason expresses both requirements without misleading model or billing semantics.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Current main retains retryable classification: Fetched main still maps the specific ClawRouter HTTP 400 credit-balance response to server_error; this PR changes it to route_unavailable. (extensions/clawrouter/index.ts:574, 15bec5ab81c2)
  • Existing owners implement the complete policy: The introduced hunks suppress same-model retry, bypass profile rotation, exclude the reason from shared credential failures, and extend existing error consumers without a parallel manager or state store. (src/agents/embedded-agent-runner/run/failover-policy.ts:176, f250321e84ef)
  • Sticky HTTP regression: The supplied fixture uses the admitted embedded runner, real HTTP transport clients, and model fallback owner; it asserts one primary request followed by fallback, strict-selection rejection, peer success, and unchanged 401/402 cooldown controls. The body reports failure on the parent and success on the reviewed head; this review executed no target code. (src/agents/clawrouter-failover.integration.test.ts:164, f250321e84ef)
  • Prior repair and accepted direction: fix(clawrouter): preserve shared key after upstream credit failures #192575 deliberately preserved the shared key while allowing bounded recovery; this maintainer-authored follow-up explains that a sticky depleted grant requires immediate fallback instead. (extensions/clawrouter/index.ts:578, 837402a456bb)
  • Additive reason compatibility: The canonical tuple retains every existing reason and adds one value; cron history readers derive their enum from that tuple and tolerate unknown optional reasons. No existing record, preference, credential, or configuration is rewritten. (src/cron/run-history-detail.ts:77, f250321e84ef)
  • Current head checks and security gate: The exact-head ci-gate remains pending. The security-sensitive review status succeeds, and the guard explicitly states that no SecOps approval is required for this author and change. (f250321e84ef)

Likely related people:

  • Peter Steinberger: Raw commit 837402a adds extensions/clawrouter/index.ts:574 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 837402a456bb; files: extensions/clawrouter/index.ts)
  • Vincent Koc: Raw commit a390d12 adds extensions/clawrouter/index.ts:186 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: a390d1248fbc; files: extensions/clawrouter/index.ts)

PR surface

Source +25, Tests +75, Docs 0, Other +1. Total +101 across 26 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 15 3213 3188 +25
Tests 9 111 36 +75
Docs 1 2 2 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 26 3327 3226 +101

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus test growth Authored production +26/-3; tests +111/-36 The net 23 production lines extend existing reason consumers; the net 75 test lines cover sticky transport recovery and distinct policy boundaries, with generated validator churn excluded.

Labels

Label changes:

  • add P2: Avoids futile recovery attempts for a specific ClawRouter upstream funding failure while retaining existing fallback and strict-selection contracts.
  • add merge-risk: 🚨 compatibility: Adds a plugin-returnable, persisted and wire-visible reason value; the maintainer-authored direction accepts this additive contract expansion, and existing values remain valid.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Avoids futile recovery attempts for a specific ClawRouter upstream funding failure while retaining existing fallback and strict-selection contracts.
  • merge-risk: 🚨 compatibility: Adds a plugin-returnable, persisted and wire-visible reason value; the maintainer-authored direction accepts this additive contract expansion, and existing values remain valid.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 5, 2026, 1:53 AM ET / 06:53 UTC.

@steipete
steipete merged commit 6f69195 into main Nov 5, 2026
333 of 340 checks passed
@steipete
steipete deleted the steipete/perf-micro-clawrouter-credit-immediate-fallback-20260919 branch November 5, 2026 07:24
@steipete

steipete commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 6, 2026
…penclaw#193250)

Use the provider-owned route_unavailable reason to skip same-model retries and auth-profile rotation without cooling the shared key. Preserve strict model selection errors and actionable cron guidance. Extend the sticky HTTP regression to prove one primary request then fallback and retain auth/budget cooldown coverage. Follow-up to openclaw#192575.
RomneyDa pushed a commit that referenced this pull request Nov 17, 2026
…ns start at once (#192534)

## What Problem This Solves

Fixes: a Gateway using the Claude CLI runtime can push its host into memory exhaustion when several conversations start new Claude processes close together.

On an 8 GB Linux VM without swap, several Slack/Teams turns arrived within about 3 minutes. The Gateway went from 3 to 7 warm Claude CLI processes, available memory fell from ~3.8 GB to ~250 MB and stayed there, and the VM thrashed (no OOM kill, CPU ~5%) until a reboot about 2 hours later. The only limit on warm processes was a fixed count of 16; idle warm processes were kept even while the host ran out of memory.

## User Impact

User impact: when host memory is low, a new Claude CLI conversation first closes idle warm processes (least recently used first). If memory is still low and every warm process is busy, that turn fails over instead of starting another process, and a channel reply says: "⚠️ This host is low on memory, so it could not start another session. Try again after active conversations finish." (Before, any such failure would have shown the generic "AI service needs a short break" rate-limit copy.) Hosts with enough free memory behave as before; turns that reuse their own warm process are unaffected; busy turns are never closed.

## Why This Change Was Made

Before a turn starts a new warm process, the live-session registry reads host free memory through the existing `readHostFreeMemoryBytes()` helper (`os.freemem()`, which is `MemAvailable` on Linux; `process.availableMemory()` on macOS). It walks the warm processes once in least-recently-used order: while memory is below 1 GiB, it closes each idle process and waits for it to exit before the next reading. If memory is still below the floor after that pass, the turn fails over with the `rate_limit` category the 16-session cap already uses, plus a distinct `cli_live_session_host_memory` code. The existing failover-code copy (`renderFailoverCodeUserCopy`) owns its user text, and the rate-limit reply renderer now returns a host-authored code's copy before generic rate-limit text (auth-profile cooldown keeps its expiry-aware copy). The registry map is now kept in least-recently-used order, so both the memory path and the existing count cap close the conversation that has waited longest.

The 1 GiB floor comes from measurements of one warm session:

| Measurement | RSS |
| --- | --- |
| Claude Code 2.1.314, Linux arm64 container, stream-json, idle after start | ~180 MiB |
| Same, after one Haiku turn / three concurrent Sonnet turns | ~195–198 MiB each |
| Full warm session under a Gateway (macOS): Claude Code + two Node supervisor helpers | ~490 MiB (264 + 138 + 87) |

1 GiB leaves room for about two more warm sessions before the kernel has to reclaim. The 16-session cap stays as the upper bound. No config key is added.

## Evidence

- Two `executePluginOwnedProcess` tests (an entry point on both `main` and this branch), with host memory simulated at `readHostFreeMemoryBytes`:
  - Low memory, new conversation: the least recently used idle process closes; the busy one and the recently used one stay. On `main` this fails on behavior (`recent.close` not called).
  - Low memory, only a busy process: the turn rejects with `rate_limit` / `cli_live_session_host_memory` before the plugin runs, the busy process stays, and `resolveReplyFailureSummary` returns the host-memory copy. On `main` this fails on behavior (the turn runs: `reason: "exit"`).
- `src/agents/cli-runner/`, `extensions/anthropic`, and the CLI attempt-execution tests: 1479 passed on the candidate; the registry and `execute-plugin` tests pass on the exact head (108). One failure, `extensions/anthropic/session-catalog.test.ts` ("reports the discovery frontier…"), also fails alone on this host and does not touch the changed files.
- Real path on the previous head `a646b6b8` (the repair batch after it adds the failover code and copy and makes eviction one bounded pass; the tests above cover both): isolated Gateway (own state, config and Claude config dir, test API key from env only), `anthropic/claude-haiku-4-5` with `agentRuntime.id: "claude-cli"`, turns sent with `openclaw agent`. Memory pressure was simulated at the same seam the code reads (`os.freemem` / `process.availableMemory`), with each live Claude process under the Gateway counted as 700 MiB, so closing a process really raises the reading.
  - Real memory: 4 concurrent sessions start (`activeSessions=1…4`), no closures.
  - Low memory, new 5th session: `free-memory read: live claude processes=4 reported=424MiB` → `memory pressure: closing idle session activeSessions=4` → `processes=3 reported=1124MiB` → `cli live session start … activeSessions=4`; the turn replied.
  - Low memory, existing session: reused its warm process, no memory read, no closure; replied.
  - Low memory, all four warm sessions busy with long turns, new session: failed over in 54 ms (`Host memory is too low for another CLI live session.`); all four busy turns completed.

## Limits

- Admission only. A warm process that grows during a long turn after it started is not limited here.
- `readHostFreeMemoryBytes()` reads host memory on Linux, not a container cgroup limit; that helper is shared and unchanged.
- Turns that start at the same instant can each read the same free-memory value before any process exists; the floor's headroom covers a small burst, and the 16-session cap still holds.
- The failover category stays `rate_limit`, as the existing count cap uses; the distinct code carries the cause.
- The live check ran on macOS with a simulated reading; the Linux numbers come from an isolated Claude Code container run.

## Merge danger

Two-way door: a revert restores the previous behavior. No config, schema, stored state or published contract changes.

Blast radius: Gateways using a CLI runtime with warm live sessions (today Claude CLI). If the floor is wrong for a host, the effect is more closed idle sessions (a cold start on the next turn) or a failover when memory is below 1 GiB and every warm session is busy. Other runtimes and channels are not affected.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit de07e00)

Release adaptation: revalidate the existing current-run authority between awaited idle-process cleanup and before capability creation; use the abort-race lazy factory so an already-aborted request starts no close. Preserve baseline cleanup-finally repair. Add one execution-boundary regression for revoked requester authority; no unrelated follow-ups.

# #192534 companion dispositions

Signed baseline e13cf15; audit bd692e9. Working base 8b3ca5d lacks the memory floor and activation LRU refresh; 16-count limit exists. Mechanical probe: clean, six touched files. Exact merged source de07e00.

Later same-path commits, each reviewed in saved relevant-followups.patch / other-followups.patch:
- 30e9d3e #200073: not-applicable, listed model chat rejection code/copy independent of host memory.
- 3a3eed8 #199591: not-applicable, tool loop policy refactor independent of memory admission.
- 8fc58f8 #199226: not-applicable, app naming copy independent of memory.
- 8ccba17 #198426: not-applicable to this admission change, warm callback async-context repair independent; do not silently absorb. Existing requestToolPermission is bound; no callback change required by memory.
- 2110db5 #198288: not-applicable, model chat eligibility and code/copy independent.
- 4527846 #198324: not-applicable, provider rate-limit reset deadlines; host-local memory refusal has no provider deadline.
- 4f8df80 #198224: present-equivalent, baseline registry remove already uses finally and releases retired map after failed cleanup.
- 8cd7d87 #197655: not-applicable, main test allocation pruning; retain this release allocation.
- 5dc6683 #197163: present-equivalent, buildHarnessHostRequester used in baseline; separate tool hook metadata.
- 7786960 #197051: not-applicable, managed WebSearch availability, independent tool policy.
- ac7e941 #196677: not-applicable, expired API-key copy independent of host admission.
- 4d6205c #194439: not-applicable, provider failure/tool warning handling independent of pre-execution host refusal.
- 4845a0f #193508: not-applicable, native credential removal propagation; no new credentials accessed by memory policy. Existing live assertion retained/rechecked.
- 6f69195 #193250: not-applicable, exhausted upstream credit failover category independent of local resource refusal.
No later #192534 mentions.

Prerequisites: readHostFreeMemoryBytes exists unchanged in baseline; @openclaw/retry abort race accepts lazy factory; createCliFailoverError preserves explicit code; FailoverError carries code; existing rate-limit reply renderer consumes it; registry closeRecord joins process exit and owned cleanup. These are present-equivalent.

Neighbor tests: cli-live-session-registry.test.ts, execute-plugin.test.ts, execute-plugin.policy.test.ts, execute-plugin.steering.test.ts, failover/user-copy.test.ts are existing consumers, not missing implementation companions. execute-plugin.warm-context.test.ts exists only after the independent #198426 change and is not applicable to this baseline or memory fix. Run focused registry/execution/copy siblings. Selected-file references: broad generic filename inventory is mostly incidental error/execute references; traced actual owners/imports above. Docs and allocation are non-runtime references; no generated exports or workflow changes needed.

Focused proof: baseline 2 failed/36 passed (LRU eviction missing; busy-only admission incorrectly exits successfully). Green 135 passed across five existing owner/consumer files, including host-memory failure copy and revoked-requester preservation. Format and diff checks clean. Type-aware lint blocked by the established shared TypeScript declaration-confinement boundary; no bypass/install. Parent owns integration and broad release qualification.

Co-authored-by: RomneyDa <[email protected]>

Parent qualification: corrected the authority regression's required braces and matching test allocation (102 lines); no production change from worker. Combined 145/145 tests across seven files passed; post-braces changed suite 39/39 passed. Supported parent type-aware lint and formatting passed six files, executable syntax and diff checks passed. Worker dependency-layout lint limitation resolved. Parent self-review and source/companion comparison recorded in cli-resources-parent-review.md. Full stable/FRV remains pending; publication held.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docs Improvements or additions to documentation extensions: clawrouter Extension: clawrouter gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: XL 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.

1 participant