Skip to content

fix: rate-limit Retry-After past maxRetryDelayMs sleeps the turn instead of failing over - #148580

Merged
altaywtf merged 7 commits into
openclaw:mainfrom
azuretek:fix/rate-limit-retry-after-fallback
Sep 20, 2026
Merged

altaywtf merged 7 commits into
openclaw:mainfrom
azuretek:fix/rate-limit-retry-after-fallback

Conversation

@azuretek

@azuretek azuretek commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Related: #143274 (canonical), #145719. Filed from #148558, which ClawSweeper closed into #143274 as a duplicate; this PR is the implementation of that report's proposal.

What Problem This Solves

Fixes: an agent run sleeps a 429 Retry-After of hours inside the turn instead of failing over, when the provider's message matches no usage-window keyword. Anthropic session-window exhaustion is this shape ("Please try again later." with a Retry-After equal to the window reset), so every scheduled job that hits it dies at its own timeout with cron: job execution timed out (last phase: model-call-started) while the configured fallback chain is never tried.

User Impact

User impact: with a fallback configured, a rate-limit floor longer than the saved retry.provider.maxRetryDelayMs (default 60 s) now fails over to the next auth profile or model immediately, so scheduled jobs complete on the fallback instead of timing out and interactive turns do not hang for hours. Short throttles inside the cap keep retrying on the same model. Nothing changes when no fallback is configured (the floor is honoured in full), when maxRetryDelayMs: 0 (cap disabled), or after a replay-unsafe tool action (the attempt keeps waiting and continuing the transcript, since neither rotation nor fallback can run there).

Why This Change Was Made

retry.provider.maxRetryDelayMs is documented as the longest server-requested wait before "the request fails immediately ... allowing higher-level retry logic to handle it". The SDK honours that and returns control, but only maxRetries was wired into the embedded run's failover controller, so maybeRetryTransient then slept the same delay the setting had just refused. This carries maxRetryDelayMs from the prepared session settings onto the attempt and into maybeRetryTransient next to the floor it caps, and treats a rate-limit floor above the cap as long-window evidence when a fallback exists and the attempt can still fail over. No new constant and no new setting; the threshold is the one the operator already configured.

How this relates to the two open PRs on the same lines:

The docs sentence in docs/concepts/retry.md that described the old behaviour as intended is updated to describe the cap.

Evidence

The prepared head 1207422ed4a is a patch-identical rebase onto repaired main at 2ba076dc630; the stable patch ID and touched-file set are unchanged, so the prior exact-patch proof remains applicable. Cloudflare Crabbox passed git diff --check, changed-scope guards through core production typecheck, the root/shard contract (24 tests), the focused controller and recovery suites (124 tests), and the embedded fault-sequence e2e (10 tests). Full core-test typechecking was not completed on the 12 GiB runner after 31 minutes without diagnostics; hosted CI remains required.

Regression tests fail on main at the branch's previous base (3d21b1dce) and pass with the change, with the source patch stashed and the tests kept:

src/agents/embedded-agent-runner/run/failover-retry-controller.test.ts
 × rate-limit floor past retry.provider.maxRetryDelayMs > fails over instead of sleeping when a fallback is configured
   → expected true to be false
      Tests  1 failed | 33 passed (34)

src/agents/embedded-agent-runner/run/attempt-recovery.test.ts
 × recoverEmbeddedRunAttempt > fails over past the saved maxRetryDelayMs when a fallback exists
   → expected 'retry' to be 'proceed'
      Tests  1 failed | 64 passed (65)

The replay-safety gate has its own failing-then-passing pair. With the failoverEligible check removed from the shortcut and everything else in place:

 × recoverEmbeddedRunAttempt > keeps waiting past the cap when tool activity made the attempt replay-unsafe
   → expected 'proceed' to be 'retry'
 × createEmbeddedRunFailoverRetryController > ... > still sleeps the floor when the attempt cannot fail over
   → expected false to be true

'proceed' there is the terminated turn ClawSweeper described on #145720; with the gate the attempt returns 'retry' and sleeps the floor as before.

The controller test uses the measured Anthropic body and a retry-after: 9897 header (resolveRetryAfterMs gives 9,897,000 ms) with maxRetryDelayMs: 30000. Control cases that must keep their current behaviour pass in both states: the same floor with no fallback still sleeps 9,897,000 ms; cap 0 and cap undefined still sleep; a 20 s floor inside the cap still retries on the same model; a server_error floor is still governed by the transient time window rather than this cap. The existing 120 s and 30-day floor tests are unchanged (they run without a fallback).

After-fix real behavior through the embedded runner (injected transport fault)

The fault-sequences e2e drives the real runEmbeddedAgent and injects a 429 whose assistant error text matches no usage-window keyword and carries the reset only in errorBody.headers["retry-after"] (9897 s), with the operator's retry.provider.maxRetryDelayMs: 30000 on the attempt. This is the real path buildAssistantFailoverSignal -> resolveRetryAfterMs -> maybeRetryTransient, not a controller mock; a single openai profile and a groq/mock-2 fallback are configured.

The test asserts the observed provider attempts. Reverting the four source files to upstream/main and keeping the test, the second attempt is the same model, proving the runner slept the floor and retried instead of failing over:

 × fails over a header-only multi-hour 429 past retry.provider.maxRetryDelayMs instead of sleeping it
   → expected [ [ 'openai', 'mock-1' ], [ 'groq', 'mock-2' ] ]
              to deeply equal [ [ 'openai', 'mock-1' ], [ 'openai', 'mock-1' ] ]

With the fix the second attempt is the groq fallback, the run completes on it, and sleepWithAbort is never called with the 9,897,000 ms floor. This is the after-fix runtime evidence the review asked for: an injected transport fault standing in for an on-demand session-window 429, exercised end to end through the production runner.

With the change: src/agents/embedded-agent-runner/run/ 54 files, 599 tests pass; the retry-related e2e files (model-fallback.run-embedded, run-embedded-agent.auth-profile-rotation, run-embedded-agent.fault-sequences) 3 files, 63 tests pass under test/vitest/vitest.e2e.config.ts. oxlint and oxfmt --check clean on the changed files.

run-loop.ts is deliberately untouched: it sits exactly at the 700-line max-lines ceiling on main, which is why the cap rides the existing maybeRetryTransient call in attempt-recovery.ts rather than a second setTransientRetryBudget argument.

Live shape this fixes, from the gateway log on 2026.9.4 (host clock Pacific):

12:00:01.196 [agent/embedded] transient same-model retry 1/3 for anthropic/claude-fable-5-1 reason=rate_limit: delayMs=7198000
12:40:00.292 [diagnostic] message processed: channel=cron ... outcome=error duration=2400016ms error="cron: job execution timed out (last phase: model-call-started)"

This is a library-level fix with no container to A/B; the failing-then-passing tests, including the embedded-runner e2e above, are the validation, and the deploy is the next release. An organic session-window 429 cannot be provoked on demand, which is why the e2e injects the exact transport shape rather than waiting for one; if the account's window closes again while this is open, the patched gateway log will be added here.

Contract decision

Adopted: retry.provider.maxRetryDelayMs also bounds fallback timing for an existing replay-safe run, so an install with a positive or default cap and a configured fallback switches account or model sooner rather than sleeping a multi-hour floor. Unchanged elsewhere: with no fallback configured the floor is honoured in full, maxRetryDelayMs: 0 leaves the cap disabled, and a replay-unsafe attempt still waits and continues the transcript, since neither rotation nor fallback can run there. The docs/concepts/retry.md sentence that described the previous behaviour as intended is updated to describe the cap.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: S labels Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 20, 2026, 8:11 AM ET / 12:11 UTC (Revision 20).

ClawSweeper review

What this changes

The embedded agent runner uses the existing retry-delay cap to reach configured fallbacks sooner after long rate limits, while preserving waits when replay is unsafe or no fallback is configured.

Merge readiness

⛔ Blocked before merge - 3 items remain

This remains useful work: current main and the latest release still accept the long wait. No blocking code defect was found, and the recorded transport proof remains relevant; approval of the changed retry contract is still unresolved.

Priority: P1
Reviewed head: b8f4b38a0184189faef703cc30510d18272d81ba
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, supported implementation with meaningful regression coverage and no blocking correctness finding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): Recorded real-HTTP harness runs exercised the production settings, embedded recovery, and fallback chain for saved and default caps, requiring one primary 429 request and a completed fallback reply. Historical source confirms that coverage; removing the slow harness does not invalidate those observations. Current mocked fault-sequence tests are supplemental.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Recorded real-HTTP harness runs exercised the production settings, embedded recovery, and fallback chain for saved and default caps, requiring one primary 429 request and a completed fallback reply. Historical source confirms that coverage; removing the slow harness does not invalidate those observations. Current mocked fault-sequence tests are supplemental.
Evidence reviewed 9 items Introduced behavior: The shortcut requires a rate limit, configured fallback, replay eligibility, and a finite positive cap exceeded by the provider floor. It leaves ordinary waits and existing fallback ownership intact.
Settings and replay-safety wiring: attempt.ts reads the cap from the prepared session settings; recovery forwards it with current-attempt replay safety. The settings owner supplies 60000 when absent. The changed transient path excludes Codex app-server failures; no Codex dependency contract is needed for this verdict.
Still absent from current main: The fetched main controller still uses wording-based usage-window detection and passes rate-limit floors into an unlimited time window without the proposed saved-cap check.
Findings None None.
Security None None.

How this fits together

The embedded agent runner receives provider failures and decides whether to continue the current conversation or invoke existing account and model fallback handling. This change connects saved retry settings to that decision.

flowchart TD
  A[Provider rate-limit response] --> C[Embedded recovery controller]
  B[Saved retry-delay cap] --> C
  C --> D{Over cap with fallback and safe replay?}
  D -->|Yes| E[Existing account and model fallback]
  D -->|No| F[Wait and continue transcript]
  E --> G[Reply or final failure]
  F --> G
Loading

Decision needed

Question Recommendation
Should the existing provider retry-delay cap also trigger earlier fallback for existing replay-safe runs? Accept the expanded cap contract: Adopt the documented earlier fallback behavior while retaining the existing no-fallback, disabled-cap, and replay-unsafe exceptions.

Why: Current documentation deliberately preserves long provider waits; the proposed contract changes that shipped behavior, and the inspected discussion does not establish maintainer acceptance.

Before merge

  • Resolve merge risk (P1) - Existing installations with a positive or default cap and configured fallbacks will switch accounts or models sooner, potentially changing cost and answers; unavailable alternatives can end the run instead of waiting for the primary.
  • Complete next step (P2) - Obtain explicit maintainer acceptance that positive or default retry-delay caps trigger earlier fallback for existing installations.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +42, Tests +263, Docs 0. Total +305 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 4 42 0 +42
Tests 4 264 1 +263
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 307 2 +305

Review metrics

Metric Value Why it matters
Production versus regression coverage production +42; tests and test support +263 net Production growth is justified by carrying one existing setting into the existing recovery decision.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #143274
Summary: This is a candidate for the canonical long-rate-limit problem, with a saved-cap policy and a narrower scope than profile-only rotation.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Approve earlier fallback timing (recommended)
    Accept that existing positive or default caps now advance configured alternatives instead of preserving long primary-provider waits.
  2. Pause for a compatibility-preserving policy
    Retain current timing until maintainers choose an explicit opt-in contract.

Technical review

Best possible solution:

Use the existing recovery owner and saved cap, with explicit acceptance of its expanded fallback-timing contract and preserved replay-unsafe continuation.

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

Yes: a replay-safe attempt with a header-only 9,897-second rate limit and configured fallback reaches an uncapped wait on current main. This was established from source and contributor evidence, not executed locally.

Is this the best way to solve the issue?

Yes, technically: carrying the existing setting into the existing controller avoids a competing threshold and preserves replay safety. Expanding its shipped meaning remains a product-policy choice.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: Reported multi-hour waits prevent configured fallback and cause scheduled jobs and interactive turns to fail.
  • merge-risk: 🚨 compatibility: The existing setting gains a broader effect on account and model selection timing for upgraded installations.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Recorded real-HTTP harness runs exercised the production settings, embedded recovery, and fallback chain for saved and default caps, requiring one primary 429 request and a completed fallback reply. Historical source confirms that coverage; removing the slow harness does not invalidate those observations. Current mocked fault-sequence tests are supplemental.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded real-HTTP harness runs exercised the production settings, embedded recovery, and fallback chain for saved and default caps, requiring one primary 429 request and a completed fallback reply. Historical source confirms that coverage; removing the slow harness does not invalidate those observations. Current mocked fault-sequence tests are supplemental.

Evidence

What I checked:

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

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 (19 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-18T17:12:30.650Z sha 6e762487140e1aa724d8ce7290c825dd929ec0aa :: blocked before merge. :: none
  • reviewed 2026-09-19T15:56:14.981Z sha 14b1a9ad3768a6c106d1b7f1e61eb7e0ba0ce784 :: blocked before merge. :: none
  • reviewed 2026-09-19T16:09:11.067Z sha 14b1a9ad3768a6c106d1b7f1e61eb7e0ba0ce784 :: blocked before merge. :: none
  • reviewed 2026-09-19T16:56:44.689Z sha 1207422ed4ae901e5ec341f6bbed0d55fc95e6a3 :: blocked before merge. :: none
  • reviewed 2026-09-19T18:37:46.237Z sha 1207422ed4ae901e5ec341f6bbed0d55fc95e6a3 :: blocked before merge. :: none
  • reviewed 2026-09-20T07:13:52.579Z sha 33b85d43f5c683ac6d37ef8ca68c2c3741cbf749 :: blocked before merge. :: none
  • reviewed 2026-09-20T09:39:33.204Z sha 5b3777efd99138bd5614fc495bd4c72130c2836e :: blocked before merge. :: none
  • reviewed 2026-09-20T11:40:19.036Z sha fb6830645288f8246d2e28e1fa5b82d2915ec1ec :: blocked before merge. :: none

@azuretek
azuretek force-pushed the fix/rate-limit-retry-after-fallback branch from c147f81 to 953ed5e Compare September 14, 2026 22:57
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 14, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 16, 2026
@azuretek
azuretek force-pushed the fix/rate-limit-retry-after-fallback branch from 7ba3793 to ea7c01c Compare September 16, 2026 02:01
@azuretek

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and force-pushed. The branch had fallen 592 commits behind (3d21b1dce -> c536d371d), which is also the likely cause of several failing check shards on the old base: main has since rewritten test/scripts/pr-wrappers.test.ts and touched sessions.send-yield-resume.test.ts.

SHA mapping, since a rebase replays every commit under a new SHA:

before after commit
953ed5ec6 e9e87a5d0 fix: fail over a rate-limit floor past retry.provider.maxRetryDelayMs
a3c1274b6 0f44598f3 test: header-only 429 failover through the embedded runner
628dc522b e5d3689f1 test: real-transport failover proof
7ba37933a ea7c01cd4 test: fresh default cap alongside a saved one

The previous head is preserved at backup/rate-limit-retry-after-fallback-2026-09-15 on the fork.

The rebase applied with no conflicts, but main also changed attempt.ts in the meantime: it makes the catch abort-aware and drops a runTrace argument, while this branch adds providerRetryMaxDelayMs about a hundred lines away. There is no textual overlap, so the interaction was settled by running it rather than by reading the merge:

  • pnpm run lint: exit 0
  • failover-retry-controller.test.ts and attempt-recovery.test.ts: 2 files, 101 tests passed
  • retry-after-failover.e2e.test.ts: 2 tests passed, saved cap 381532ms and fresh default 57107ms

That is a re-run of the real-transport harness on the rebased head, so the numbers differ from the ones in the body while the substance is the same. The runs were launched at low CPU and I/O priority so that the other services on the shared machine kept their share.

@azuretek

Copy link
Copy Markdown
Contributor Author

Rebased onto main at c536d371d and force-pushed. The branch was 592 commits behind. Backup of the previous head: backup/rate-limit-retry-after-fallback-2026-09-15 on the fork.

SHA mapping, since the rebase replays every commit under a new SHA:

  • 953ed5ec6 (the fix) is now e9e87a5d0, content unchanged.
  • a3c1274b6 is now 0f44598f3.
  • 628dc522b is now e5d3689f1.
  • 7ba37933a is now ea7c01cd4.

main also changed attempt.ts, in the catch block (abort-aware handling) and by removing a runTrace argument, while this branch adds providerRetryMaxDelayMs in that same file. The rebase was text-clean, and a clean rebase is not a correct one, so it was re-verified on the rebased head rather than assumed:

  • pnpm run lint: exit 0.
  • failover-retry-controller.test.ts and attempt-recovery.test.ts: pass.
  • retry-after-failover.e2e.test.ts, the real-transport harness covering both cap sources: 2 passed, 381532ms and 57107ms.

The recorded run in the PR body predates this rebase and was taken on the previous base. The behaviour under test is unchanged, and the run above is the rebased head.

@azuretek

Copy link
Copy Markdown
Contributor Author

Rebased onto main at ee36fb4bdf4 and force-pushed. The branch had drifted since the last rebase and conflicted in two files.

SHA mapping, since the rebase replays every commit under a new SHA:

  • e9e87a5d03a is now 5a423340e15 (fix: fail over a rate-limit floor past retry.provider.maxRetryDelayMs instead of sleeping it)
  • 0f44598f311 is now cd3457639b7 (test(agents): prove header-only 429 failover through the embedded runner e2e)
  • e5d3689f125 is now cef0d5e0ee1 (test(agents): prove 429 retry-after failover with the real transport)
  • ea7c01cd460 is now dff7e2d417d (test(agents): cover the fresh default cap alongside a saved one)
  • 74f114450a9 is now efc81f11c15 (fix(test): pass the injected error body as the body string the type expects)

The previous head stays reachable at backup/rate-limit-retry-after-fallback-2026-09-17 on my fork.

The conflict came from main moving the TransportDropScenario fixture into attempt-recovery.test-support.ts while this branch adds fallbackConfigured and providerRetryMaxDelayMs to it. Those two fields now sit on the moved fixture, and the docs/concepts/retry.md sentence is kept alongside main's newer paragraph.

Verification on the rebased head, Node 24.20.0 on a 4-core Linux box:

  • pnpm install --frozen-lockfile, pnpm tsgo:core:test and pnpm lint pass (lint reports 0 errors, 3 pre-existing warnings).
  • The unit files pass: 120 tests across attempt-recovery and failover-retry-controller.
  • embedded-agent-runner.run-embedded-agent.fault-sequences.e2e.test.ts passes 10/10, including fails over a header-only multi-hour 429 past retry.provider.maxRetryDelayMs instead of sleeping it.
  • embedded-agent-runner.retry-after-failover.e2e.test.ts is the one caveat, and it is a host-speed one rather than a retry one: on that 4-core box the first attempt exceeds the default prepared model runtime publication (workspace plugins; agent main) timeout, so the primary request is never issued and the scenario falls through to the fallback. Preparation times out, not the retry decision. CI runs this lane on faster hardware with a 660s no-output allowance, and the built-runtime work in test(agents): run the retry-after e2e against the built runtime #150246 removes the preparation cost this hits, measured there at 341s down to 4.6s.

@azuretek
azuretek force-pushed the fix/rate-limit-retry-after-fallback branch 2 times, most recently from fc191cc to 437d1ed Compare September 18, 2026 16:28
@clawsweeper clawsweeper Bot added the rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. label Sep 18, 2026
@openclaw-barnacle openclaw-barnacle Bot added size: M triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed size: L triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Sep 19, 2026
@altaywtf
altaywtf force-pushed the fix/rate-limit-retry-after-fallback branch from 14b1a9a to 1207422 Compare September 19, 2026 16:48
@altaywtf

Copy link
Copy Markdown
Member

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Sep 19, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@altaywtf
altaywtf force-pushed the fix/rate-limit-retry-after-fallback branch 3 times, most recently from 5b3777e to fb68306 Compare September 20, 2026 11:32
azuretek and others added 7 commits September 20, 2026 15:03
… instead of sleeping it

Anthropic's session-window exhaustion answers 429 with "This request would
exceed your account's rate limit. Please try again later." and a Retry-After
equal to the window reset, measured at 3598 s to 11143 s on 2026-09-14. That
text matches none of the usage-window keyword patterns, so maybeRetryTransient
treats it as a temporary throttle and sleeps the whole floor inside the turn.
Every scheduled job that hit it died at its own timeout with
"cron: job execution timed out (last phase: model-call-started)" while
agents.defaults.model.fallbacks was never tried.

retry.provider.maxRetryDelayMs already means "the longest server-requested
wait before the request should fail so higher-level retry logic can handle
it", and the SDK honours it; the controller then slept the same delay the
setting had just refused, because only maxRetries was wired through.

Carry maxRetryDelayMs from the prepared session settings onto the attempt and
into maybeRetryTransient next to the floor it caps. A rate-limit floor above
the cap with a fallback configured now fails over immediately; with no
fallback there is nothing to do but wait, so the floor is still honoured, and
maxRetryDelayMs: 0 keeps its documented meaning of no cap. Floors inside the
cap keep retrying on the same model.

The shortcut is also gated on the attempt being replay-safe. After an exec or
write, neither profile rotation nor model fallback runs downstream, so
declining the wait there would end the turn instead of continuing it; that
attempt keeps waiting and continuing the transcript exactly as before.

Related: openclaw#143274, openclaw#145719
…ner e2e

Adds an injected transport fault to the run-embedded fault-sequences e2e: a
429 whose assistant error text matches no usage-window keyword and carries the
reset only in errorBody.headers["retry-after"] (~2.75h), with the operator's
retry.provider.maxRetryDelayMs on the attempt. This is the real path
buildAssistantFailoverSignal -> resolveRetryAfterMs -> maybeRetryTransient,
not a controller mock.

Without the source fix the second observed attempt is openai/mock-1 again:
the runner slept the floor and retried the same model. With it the second
attempt is the groq fallback, and the 9,897,000ms floor never reaches
sleepWithAbort. This is the after-fix real-behavior evidence the review asked
for; an injected fault stands in for an on-demand session-window 429.

Related: openclaw#143274, openclaw#145719
Drive runWithModelFallback, the layer that owns the candidate chain, with two
loopback HTTP servers: the primary answers 429 with the reset only in
Retry-After, far above retry.provider.maxRetryDelayMs, and the fallback answers
a normal completion. With the cap applied the attempt declines the multi-hour
floor and the turn completes on the fallback instead of sleeping it.
The saved-cap and fresh-default paths reach the attempt differently, and a new
install has no settings.json at all, so both need to show the same failover.
…xpects

The fault-sequences harness handed errorBody an object where the runtime type
is the provider response body string, so test-types rejected it. resolveRetryAfterMs
parses a string body back to the same record, so the injected retry-after header
and the assertion it drives are unchanged.
@altaywtf
altaywtf force-pushed the fix/rate-limit-retry-after-fallback branch from fb68306 to b8f4b38 Compare September 20, 2026 12:03
@altaywtf
altaywtf merged commit fcc927f into openclaw:main Sep 20, 2026
226 checks passed
@altaywtf

Copy link
Copy Markdown
Member

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 21, 2026
…ead of failing over (openclaw#148580)

* fix: fail over a rate-limit floor past retry.provider.maxRetryDelayMs instead of sleeping it

Anthropic's session-window exhaustion answers 429 with "This request would
exceed your account's rate limit. Please try again later." and a Retry-After
equal to the window reset, measured at 3598 s to 11143 s on 2026-09-14. That
text matches none of the usage-window keyword patterns, so maybeRetryTransient
treats it as a temporary throttle and sleeps the whole floor inside the turn.
Every scheduled job that hit it died at its own timeout with
"cron: job execution timed out (last phase: model-call-started)" while
agents.defaults.model.fallbacks was never tried.

retry.provider.maxRetryDelayMs already means "the longest server-requested
wait before the request should fail so higher-level retry logic can handle
it", and the SDK honours it; the controller then slept the same delay the
setting had just refused, because only maxRetries was wired through.

Carry maxRetryDelayMs from the prepared session settings onto the attempt and
into maybeRetryTransient next to the floor it caps. A rate-limit floor above
the cap with a fallback configured now fails over immediately; with no
fallback there is nothing to do but wait, so the floor is still honoured, and
maxRetryDelayMs: 0 keeps its documented meaning of no cap. Floors inside the
cap keep retrying on the same model.

The shortcut is also gated on the attempt being replay-safe. After an exec or
write, neither profile rotation nor model fallback runs downstream, so
declining the wait there would end the turn instead of continuing it; that
attempt keeps waiting and continuing the transcript exactly as before.

Related: openclaw#143274, openclaw#145719

* test(agents): prove header-only 429 failover through the embedded runner e2e

Adds an injected transport fault to the run-embedded fault-sequences e2e: a
429 whose assistant error text matches no usage-window keyword and carries the
reset only in errorBody.headers["retry-after"] (~2.75h), with the operator's
retry.provider.maxRetryDelayMs on the attempt. This is the real path
buildAssistantFailoverSignal -> resolveRetryAfterMs -> maybeRetryTransient,
not a controller mock.

Without the source fix the second observed attempt is openai/mock-1 again:
the runner slept the floor and retried the same model. With it the second
attempt is the groq fallback, and the 9,897,000ms floor never reaches
sleepWithAbort. This is the after-fix real-behavior evidence the review asked
for; an injected fault stands in for an on-demand session-window 429.

Related: openclaw#143274, openclaw#145719

* test(agents): prove 429 retry-after failover with the real transport

Drive runWithModelFallback, the layer that owns the candidate chain, with two
loopback HTTP servers: the primary answers 429 with the reset only in
Retry-After, far above retry.provider.maxRetryDelayMs, and the fallback answers
a normal completion. With the cap applied the attempt declines the multi-hour
floor and the turn completes on the fallback instead of sleeping it.

* test(agents): cover the fresh default cap alongside a saved one

The saved-cap and fresh-default paths reach the attempt differently, and a new
install has no settings.json at all, so both need to show the same failover.

* fix(test): pass the injected error body as the body string the type expects

The fault-sequences harness handed errorBody an object where the runtime type
is the provider response body string, so test-types rejected it. resolveRetryAfterMs
parses a string body back to the same record, so the injected retry-after header
and the assertion it drives are unchanged.

* test(agents): set the transient retry budget through observeAttempt after the setter was removed upstream

* test(agents): drop slow retry-after transport harness

---------

Co-authored-by: Altay <[email protected]>
@azuretek
azuretek deleted the fix/rate-limit-retry-after-fallback branch October 18, 2026 01:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

2 participants