Skip to content

fix: show provider reset times for long rate limits - #198324

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-rate-limit-message-ignores-retry-after-20260919
Nov 13, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-rate-limit-message-ignores-retry-after-20260919

Conversation

@steipete

@steipete steipete commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes misleading “try again in a few minutes” replies when an embedded provider's 429 response supplies a retry time hours or days away.

User Impact

Long rate limits now name the affected provider/model, give a relative wait and an absolute date in the configured locale/timezone, and point users to the model picker or Model Fallbacks setting. Later turns on the same route/account reuse the existing shared limiter and avoid another provider request until reset; configured fallbacks still recover normally. Short or unknown waits keep the current brief advice.

The shared limiter remains process-local and does not survive a Gateway restart. This does not change native harness transport ownership. No new configuration, database schema, or cache.

Why This Change Was Made

The retry controller already knew the provider's retry floor, but formatting and failover records discarded it. Generic quota copy could then overwrite the useful explanation. Carry one absolute reset through the existing error/fallback records and consume it at the shared copy owner, including saved-login cooldown refusals. Recognize finite long 429s in the existing model/account gate, which previously required organization-TPM wording.

Related: #195422 (complementary native-harness reset propagation), #179967 (retry-controller long-window policy).

Evidence

Both regressions fail on parent 632f7ffaf51409229e6ebcabad07d9d7615bf70e: long replies use “a few minutes,” and the next admission on a generic timed 429 resolves instead of refusing. The candidate exercises real embedded-agent execution with a synthetic provider, fallback success, repeated strict sessions making zero additional provider calls, and successful admission after reset. Existing post-tool coverage preserves the no-replay behavior.

Exact rendered copy with a frozen clock at 2026-11-13T14:00:00Z, en-US, America/Los_Angeles:

Retry-After No fallback Successful fallback
Absent ⚠️ The AI service needs a short break. Please try again in a few minutes. Fallback answered.
30 seconds ⚠️ The AI service needs a short break. Please try again in a few minutes. Fallback answered.
3 days ⚠️ anthropic/test-model is rate-limited. The provider says to retry in 3 days (Nov 16, 2026 at 6:00 AM PST). Choose another model in the model picker, or configure Model fallbacks in Settings (agents.defaults.model.fallbacks). Fallback answered.

Node renders the same absolute deadline as Nov 16, 2026, 6:00 AM PST; Bun renders it as Nov 16, 2026 at 6:00 AM PST. The exact-text assertion allows only these observed ICU separator variants. The underlying primary failure retains the same exact copy with or without a fallback. Header/body timing and the queued retry-budget refusal are covered too.

Real Gateway and HTTP transport proof

On final head d4aad91db52a5b781ff8aebde348e03b6dc91410, an isolated Gateway received three real chat.send requests over its WebSocket RPC transport. Its real embedded agent called a loopback synthetic Responses HTTP provider; no agent/attempt/transport mock was installed. The provider returned HTTP 429 with Retry-After: 259200 for openai/wire-limited and a successful SSE reply for openai/wire-backup.

  1. First session: one HTTP request; agent.wait.error and the live chat error event both rendered:

    ⚠️ openai/wire-limited is rate-limited. The provider says to retry in 3 days (Nov 16, 2026, 7:33 AM PST). Choose another model in the model picker, or configure Model fallbacks in Settings (agents.defaults.model.fallbacks).

  2. A second session on the same route/account: zero HTTP requests, identical terminal and live-event notice.
  3. A session with a configured fallback: one HTTP request to the backup only, terminal status ok, reply SYNTHETIC_FALLBACK_OK, effective model openai/wire-backup.

Total wire requests: exactly wire-limited, then wire-backup. The earlier fault-injection suite and scripted-stream integration tests are separate evidence; they do not establish HTTP coverage. The isolated Gateway and provider were shut down after verification.

Owner measurement

Acceptance: after the first known long 429, subsequent same-route/account turns start zero provider requests; owner CPU, allocation, and latency must improve. Extend the existing committed workload:

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/provider-rate-limit-stream-measure.ts --scenario long-reset --mode timing --turns 2000
# Repeat with --mode allocation in separate passes.

2,000 distinct synthetic sessions share a route/account with a roughly 10k-token prepared prompt and a three-day retry floor. Six interleaved AB/BA samples per arm/mode, preceded by two A/A controls; Node 26.12.1. This measures provider admission/serialization, not whole-Gateway throughput. The owner performs no database or workspace scan, so a large database or file tree is not materialized. No production data was used.

Metric Parent median / p95 Candidate median / p95
Provider starts 2,000 / 2,000 1 / 1
Local refusals 0 / 0 1,999 / 1,999
Owner wall time, 2,000 turns 23.68 / 23.84 ms 11.02 / 11.30 ms
Main-thread CPU per turn 11.98 / 12.16 µs 5.51 / 5.64 µs
Sampled allocated bytes per turn 70,569 / 70,690 B 5,790 / 5,854 B
Process RSS, timing median 88.2 MB 82.1 MB

A/A controls: 24.33–24.56 ms, 12.3315–12.341 µs/turn, 70,479–70,535 allocated B/turn. Main AB wall ranges: 23.32–23.84 ms before, 10.86–11.30 ms after. CPU profile captured at the final owner path.

Production delta: +158 lines. Growth carries the missing reset across existing failure boundaries and adds one localized renderer; no competing parser/state owner was introduced. The simplification pass removed repeated reply-fact work and unnecessary timer rescheduling on immediate refusal.

Validation: 298 focused tests passed across nine files, including the embedded-agent fault-injection suite. Formatter, terminal-resolution, and prompt-prefix consumer tests also passed in the preceding focused run. Codex autoreview is scoped-clean through P2. The initial CI run found two test-only ICU punctuation mismatches; both were reproduced locally under Node and corrected without changing production formatting. All 26 tests in the affected file pass under both Node and Bun after the correction, with targeted lint/type/format checks passing. Every other substantive job in the first CI run passed. pnpm check:changed passed all type, lint, format, schema, and structural checks; its only failures are the two independently reproduced parent unused exports below.

The unchanged parent reproduces two unused-export failures: resolveAuthoritativeSharedOAuthCredentialUnderLock (last external caller removed by 3577724c7276d11a89f5ece2714406b37341c2a9, #198214) and RELEASE_VALIDATION_WAIVERS (introduced unused by 2a1285197991490df98f847f425f2c7fdb41d433, #173437). These are main regressions, not waived product findings; the OAuth regression needs follow-up by its owner. All source files were restored to the exact parent for the reproduction, with a clean diff.

Final-head CI: run 43452117425 passed on d4aad91db52a5b781ff8aebde348e03b6dc91410; no inherited-CI exception was needed.

Carry the known reset through embedded failover records and reply copy so
long 429s name the limited route, localized deadline, and model-picker or
fallback action. Reuse the existing route/account limiter for long timed
429s to avoid repeated provider calls before reset.

Keep short/unknown retry guidance and existing fallback recovery. No new
configuration or state owner. Include regression and synthetic owner proof.
@clawsweeper

clawsweeper Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 13, 2026
@steipete
steipete marked this pull request as ready for review November 13, 2026 15:04
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T15:07:07.807754Z 9603fd3 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 13, 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: d4aad91db52a5b781ff8aebde348e03b6dc91410
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/runtime-plan/prepare-auth.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

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review head 9603fd38dbf3867a37b6e40711666f21a0d731ca. The branch, exact rendered copy, local proof, and owner measurements are current. Focus on preserving long provider reset deadlines through fallback/reply formatting and reusing the existing route/account gate without replaying completed tool work.

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Preserve long provider reset deadlines in failure replies and reuse the existing account/model limiter to avoid premature requests.

Example: At 2026-11-13 14:00 UTC, anthropic/test-model returns a three-day Retry-After.

  • Before: The reply advises trying again in a few minutes, and another session can contact the limited route.
  • After: The reply gives the November 16 reset date and model-switch guidance, while subsequent sessions avoid that route until recovery.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused repair with shipped-entry-point proof, distinct regression coverage, and the earlier finding resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Final-head Gateway RPC and live error output exercise the actual embedded agent and HTTP transport against a synthetic 429 provider, demonstrating deadline copy, cross-session request suppression, and successful backup routing.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Users receive advice to retry within minutes even when the provider reported a reset hours or days away.
Reason: The maintainer-authored direction corrects actionable recovery information and avoids repeated requests using established owners.

Merge readiness

✅ Ready for maintainer review

This PR addresses a current embedded-provider failure with no actionable findings remaining; the earlier ICU assertion defect is fixed.

Priority: P2
Reviewed head: d4aad91db52a5b781ff8aebde348e03b6dc91410

Before merge

None.

Findings

None.

Agent review details

How this fits together

Embedded provider failures pass through retry, fallback, and reply preparation; the shared limiter controls subsequent requests, and the copy owner renders safe recovery guidance.

flowchart TD
  A[Chat request] --> B[Embedded agent]
  B --> C[Account and model limiter]
  C --> D[Provider HTTP transport]
  D --> E[Failure and fallback records]
  E --> C
  E --> F[Shared failure copy]
  F --> G[Terminal and chat reply]
Loading

Technical review

Best possible solution:

Carry the deadline through existing failure records and render it at the shared copy owner while preserving fallback and no-replay policy.

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

Current-main source exposes both failures, and the supplied regression evidence records failures on the parent; this read-only review ran no target code.

Is this the best way to solve the issue?

The change repairs the existing metadata and admission owners without introducing competing state, parsers, configuration, or transport ownership.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared provider admission changes intended behavior with a stated reason (68a7e7b: Coordinate shared organization-TPM exhaustion while retaining caller-owned retries and account isolation.)
  • Central failure-copy ownership keeps the original intent (6dc77a3: Consolidate divergent failure wording in one reason-keyed rendering module.)
  • Saved-login diagnostic suppression keeps the original intent (c0effea: Keep operator-local saved-login labels out of public cooldown replies while retaining useful recovery guidance.)
  • Provider failures alongside tool warnings keeps the original intent (4d6205c: Prepare classified provider-failure payloads at the shared terminal owner so earlier tool warnings cannot hide them.)
  • Retry-exhaustion copy precedence changes intended behavior with a stated reason (f0bc1de: Explain controller-recorded retry exhaustion instead of displaying a misleading short provider hint; this PR explicitly prioritizes a known long reset deadline.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main still has the reported gap: Fetched main limits shared observation to organization-TPM errors and lacks the new deadline renderer; generic timed 429s therefore remain outside this gate. (src/llm/provider-rate-limit.ts:289, af10e5594d38)
  • Existing owners carry the fix: The existing limiter now recognizes finite generic rate-limit waits longer than one minute, retaining its account/model identity, expiry, and admission mechanics. (src/llm/provider-rate-limit.ts:303, d4aad91db52a)
  • Localized safe copy: The shared renderer uses structured route and deadline facts, configured locale/timezone, and model-picker recovery guidance without publishing raw diagnostics or saved-login labels. (src/agents/failover/user-copy.ts:168, d4aad91db52a)
  • Earlier finding resolved: The only change since the earlier reviewed head permits the observed Node/Bun ICU separators while retaining full-string checking and equality between the failure and surfaced reply. (src/agents/embedded-agent-runner/run/assistant-failure.failover.test.ts:94, d4aad91db52a)
  • Final-head Gateway and HTTP proof: The body and fix: show provider reset times for long rate limits #198324 (comment) record real chat.send RPC turns, an actual embedded agent and loopback HTTP provider: one initial 429, zero requests for a second strict session, and one backup-only request returning SYNTHETIC_FALLBACK_OK. (d4aad91db52a)
  • Exact-head checks and authority: No substantive check remains failing or running; CodeQL is neutral and an earlier context job was cancelled. The aggregate CI gate remains pending, security-sensitive review reports maintainer authority, and GitHub reports mergeable=true. (d4aad91db52a)

Likely related people:

  • Peter Steinberger: Raw commit 68a7e7b adds src/llm/provider-rate-limit.ts:34 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 68a7e7b5b766; files: src/llm/provider-rate-limit.ts)
  • Ayaan Zaidi: Raw commit 4d6205c adds src/agents/embedded-agent-runner/run/terminal-preparation.ts:289 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 4d6205c9535d; files: src/agents/embedded-agent-runner/run/terminal-preparation.ts)

PR surface

Source +158, Tests +131, Docs +11, Other +43. Total +343 across 24 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 16 228 70 +158
Tests 6 140 9 +131
Docs 1 11 0 +11
Config 0 0 0 0
Generated 0 0 0 0
Other 1 45 2 +43
Total 24 424 81 +343

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 LOC Production +228/-70; tests +140/-9 Production growth carries reset metadata across existing boundaries and adds one localized renderer; regression coverage exercises copy, admission, fallback, and expiry.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit. Replaced prior rating: 🧂 unranked krab.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Long provider rate limits produce misleading recovery advice and unnecessary requests, with existing model-switch and fallback recovery available.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit. Replaced prior rating: 🧂 unranked krab.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-13T15:20:24.316Z sha 9603fd3 :: needs changes before merge. :: [P2] Make the localized deadline assertion portable across ICU versions

Reviewed November 13, 2026, 10:41 AM ET / 15:41 UTC (Revision 2).

@steipete

Copy link
Copy Markdown
Contributor Author

Addressed review item 1 (P2) on final head d4aad91db52a5b781ff8aebde348e03b6dc91410: lines 90–103 of the copy regression now accept exactly the two observed full ICU-rendered strings (Node comma versus Bun “at”), then require the surfaced reply to equal the failure message exactly. Both formerly failing cases were reproduced under Node before this correction. The affected file now passes 26/26 tests under both Node and Bun; targeted type/lint/format and a fresh Codex review are clean. Production code is unchanged by this correction.

The review also correctly identified that the earlier scripted StreamFn and mocked-attempt tests did not prove the HTTP boundary. The PR body now labels those accurately and records a separate completed real Gateway/HTTP proof on this final head. Three real chat.send RPC turns used the actual embedded agent and loopback Responses HTTP provider:

  1. First strict session: one HTTP 429 (Retry-After: 259200), with this exact terminal RPC and live chat error text:

    ⚠️ openai/wire-limited is rate-limited. The provider says to retry in 3 days (Nov 16, 2026, 7:33 AM PST). Choose another model in the model picker, or configure Model fallbacks in Settings (agents.defaults.model.fallbacks).

  2. Second strict session, same account/route: zero provider HTTP requests and the identical notice.
  3. Fallback-enabled session: one HTTP request, to wire-backup only; terminal status ok, reply SYNTHETIC_FALLBACK_OK, effective model openai/wire-backup.

Total actual wire requests were exactly wire-limited, then wire-backup; no agent, attempt, or transport mock. All data was synthetic and the isolated processes were shut down after verification. Final-head CI is running after the ICU assertion repair.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. labels Nov 13, 2026
@steipete
steipete merged commit 4527846 into main Nov 13, 2026
164 of 165 checks passed
@steipete
steipete deleted the steipete/perf-micro-rate-limit-message-ignores-retry-after-20260919 branch November 13, 2026 15:45
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 14, 2026
* fix: show provider reset times for long rate limits

Carry the known reset through embedded failover records and reply copy so
long 429s name the limited route, localized deadline, and model-picker or
fallback action. Reuse the existing route/account limiter for long timed
429s to avoid repeated provider calls before reset.

Keep short/unknown retry guidance and existing fallback recovery. No new
configuration or state owner. Include regression and synthetic owner proof.

* test: accept Node and Bun date separator variants
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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts security-sensitive-changed size: M 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.

1 participant