Repository navigation
fix(failover): oversized Groq requests stall the session with unusable rate-limit advice - #130275
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 28, 2026, 4:36 PM ET / 20:36 UTC. ClawSweeper reviewWhat this changesThe PR treats Groq TPM refusals whose stated requested token count exceeds the stated limit as unsatisfiable request-size failures, surfaces reset guidance, and permits configured model fallback. Regression provenancePossible regression — probable (reproduction; reviewed change). No predecessor PR is attributed. Merge readinessKeep open for normal maintainer landing: current main retains the reported TPM exclusion, while this branch adds a narrowly bounded request-size classification and recovery path with focused coverage. Priority: P1 Review scores
Verification
How this fits togetherProvider errors enter the agent failover layer, which classifies them and selects retry, fallback, or terminal recovery. The embedded-run recovery owner turns terminal classification into operator guidance. flowchart LR
A[Provider request] --> B[Provider refusal]
B --> C[Failover classification]
C --> D{Requested exceeds limit}
D -->|Yes| E[Reset or new-session guidance]
D -->|No| F[Rate-limit handling]
C --> G[Configured model fallback]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +95, Tests +285, Docs +5. Total +385 across 13 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Land the narrow requested-greater-than-limit classification after exact-head checks confirm the documented provider wording remains covered. Do we have a high-confidence way to reproduce the issue? Yes: the current source has the unconditional TPM exclusion and the branch’s tests and supplied built-CLI trace exercise the stated Limit/Requested failure; this read-only review did not rerun the provider scenario. Is this the best way to solve the issue? Yes: using the provider’s stated requested-versus-limit values distinguishes an impossible request from an ordinary bucket throttle while keeping existing fallback and compaction ownership boundaries intact. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 4c6ed51733d3. LabelsLabel justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (10 earlier review cycles; latest 8 shown)
|
5e8a03d to
5c8c7c0
Compare
5c8c7c0 to
983ae4a
Compare
c39b8de to
5edfdf4
Compare
|
Maintainer re-run requested for The job log shows the runner received a shutdown signal 90s into the Current state: 190 checks green, branch current with Fixes #130096 (Groq 413 request-size ceiling stalling sessions in retry loops). |
…e-limit advice Groq denominates a per-request size ceiling per minute, so a single request larger than the whole TPM limit is refused with an HTTP 413 whose body names TPM. The classifier's TPM guard read that wording as a rate limit, so the run took the backoff-and-retry path and surfaced "try again later" advice that can never work. Each retry carried the previous failure, so the payload grew and the session could not recover on its own. Groq states both numbers, and the two refusals are separable by wording: `Requested` above `Limit` cannot be admitted by an empty bucket, while ordinary throttling stays within the limit. Let the former through the TPM guard so the existing overflow tables classify it, and settle it ahead of the rate-limit exclusions in isLikelyContextOverflowError. Compaction and reset guidance then run, and the user sees advice that resolves the failure. Ordinary TPM throttling and refusals that state no sizes are unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
…ecovery The classifier change alone routed the Groq 413 into generic overflow recovery, which force-compacts, adopts a successor transcript, and retries. That recovery budgets against the model's context window (131,072 here) rather than the provider's per-request ceiling (8,000), so it cannot make the request fit: every round rewrote the session and re-sent a payload the provider had already refused. ClawSweeper flagged this as a P1 on openclaw#130275. Represent the ceiling separately from compaction-recoverable overflow. `isProviderRequestSizeCeilingError` names the case the classifier already detects -- a message stating `Requested` above `Limit` -- and the recovery owner branches on it to surface the reset guidance directly, without compacting, adopting, truncating, or retrying. The classification stays `context_overflow` so the user-facing guidance is unchanged, and ordinary TPM throttling still states a requested size within the limit and remains a rate limit. Covered at both recovery seams: the canonical owner suite asserts `compactEmbeddedRunForRecovery` is never invoked, and the colocated suite asserts the context engine is never asked to compact and no tool-result truncation runs. Both fail before this change with `{action: "retry"}`. Co-Authored-By: Claude Opus 5 <[email protected]>
Reading the two figures with separate patterns paired numbers that can describe different units: a message stating an RPM limit and, in a later sentence, a TPM request size resolved to `Limit 30, Requested 5000` and read as a request-size ceiling. That misclassifies a throttle waiting would clear, and now that the ceiling case is terminal the cost is an ended session rather than wrong copy. One pattern that spans both figures without crossing a sentence boundary, so the numbers are only paired when the provider stated them together. Co-Authored-By: Claude Opus 5 <[email protected]>
…eiling A transport-owning plugin harness disables generic compaction recovery, so the refusal leaves the embedded runner as a FailoverError whose message has already been replaced with context-overflow copy. The fallback boundary reads that message, so the new classification made it rethrow where it used to advance configured model and auth-profile candidates. ClawSweeper flagged the loss as a P1 on openclaw#130275. Record the fact on the FailoverError at construction, while the provider's own text is still intact, and branch on it at the boundary rather than re-deriving it from prose that no longer states the figures. A ceiling belongs to the refusing provider's quota rather than to any model's context window, which is the one case where a differently provisioned candidate may still admit the request -- so it is the exception to a rethrow that otherwise protects overflow from rotating onto a smaller window. Embedded recovery stays terminal. Handing the refusal back with `{ action: "none" }` instead returns it to the same-model rate-limit retry that reported it: measured against a local provider stand-in, that costs five provider requests and reaches auto-compaction anyway, against one for the terminal branch. Covered at the boundary: a normalized-copy FailoverError carrying the provider's text on `rawError` advances to the configured candidate, while an ordinary context overflow still rethrows. The first fails before this change. Co-Authored-By: Claude Opus 5 <[email protected]>
The pair was read from the first clause stating both figures, while the TPM hint was only required somewhere in the message. A refusal that states its figures in requests -- `on requests per minute (RPM): Limit 30, Requested 100` -- and names TPM in a later sentence therefore compared a request count against a token budget, and read as a ceiling. Since a ceiling is terminal, that ends a session which waiting would have cleared. ClawSweeper flagged it as a P1 on openclaw#130275. Require the unit to lead the clause, so the numbers are only paired when the provider stated them as tokens. A message stating both units keeps deciding on the token-denominated pair. Also pins the embedded terminal policy end to end: through the real runner a ceiling ends the turn with reset guidance and does not spend a configured fallback candidate, which is the counterpart to the boundary regression where a transport-owning harness does advance one. Co-Authored-By: Claude Opus 5 <[email protected]>
…suite The end-to-end case belongs with the other provider fault sequences, which already model a refusal as an injected status and assert the resulting blocked payload. Its first home was `model-fallback.run-embedded.e2e.test.ts`, which sits at its `max-lines` cap, so adding to it failed lint rather than saying anything about the fix. A 413 fault joins the existing union, carrying Groq's verbatim wording. The case asserts what an embedded run does with a ceiling: one attempt, a blocked `context_overflow` payload with the reset guidance, an eligible `groq/mock-2` candidate left unspent, and no rate-limit cooldown on the profile -- waiting cannot admit the request, so the profile has done nothing wrong. Co-Authored-By: Claude Opus 5 <[email protected]>
5edfdf4 to
f4680dd
Compare
|
Thanks @jerome-queck! Proof: A built OpenClaw CLI called a local responder that returned the captured Groq HTTP 413 with a full 8,000-token bucket and
Example
|
Groq can report a per-request size ceiling as a TPM rate-limit error. Record the token-denominated Requested > Limit fact at failover classification so embedded recovery stops compaction and retry with reset guidance, while transport-owning fallbacks can still advance and ordinary TPM throttling retains backoff. Co-authored-by: Jerome Queck <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
Closes #130096
🤖 AI-assisted (Claude Opus 5, via Claude Code). I wrote the issue, drove the investigation,
and read every path this touches.
What Problem This Solves
Fixes an issue where users on a Groq free/
on_demandtier would see a session stop responding —repeatedly failing with
⚠️ API rate limit reached. Please try again later.and never recovering —once a single turn grew past the model's tokens-per-minute limit.
Groq's TPM number is not only a rate, it is also a hard per-request size ceiling. A request larger
than the whole limit is refused against a completely full bucket, so waiting can never let it
through:
OpenClaw read that refusal as a waitable rate limit and retried it with backoff. Because each retry
carried the previous failure into the session, every attempt was larger than the one that just
failed, so the loop diverged rather than converged — +28 tokens per retry, 55 refusals over one
morning, a 3½-hour outage. The advice that actually ends it (
/resetor/new) was alreadyimplemented but sat behind the same predicate and was never shown.
Full measurements, headers, and the retry-growth table are in #130096.
Why This Change Was Made
Six commits. Four of them exist because of these reviews.
1. Classification (
d879eb8). The TPM guard inisContextOverflowErrorFromTablesexists for agood reason and is correct for every provider whose TPM number is only a rate. It is too coarse for
the one case where the same number is also a size ceiling. Groq states both numbers, which makes the
two refusals separable by wording alone:
Limit 8000, Used 7500, Requested 1000rate_limitLimit 8000, Requested 8098context_overflowNo new overflow pattern was added: the tables already carry
/413[\s\S]*too large/i, so the guardwas the only thing suppressing a match the classifier could already make.
2. Terminal recovery (
e9e7742) — the first P1. Classification alone routed the refusal intorecoverEmbeddedRunOverflow, which force-compacts, adopts a successor transcript, and retries. Thatrecovery budgets against the model's context window (131,072 here), not the provider's
per-request ceiling (8,000) — the live trace below shows it computing
compactionTokens=131073against an 8,000 ceiling. It cannot make the request fit, so each round rewrote the session and
re-sent a payload the provider had already refused.
So the ceiling is now represented separately from compaction-recoverable overflow, exactly as the
review asked.
isProviderRequestSizeCeilingErrornames the case the classifier already detects, andthe recovery owner branches on it to surface the reset guidance directly — no compaction, no
transcript adoption, no tool-result truncation, no retry. The classification stays
context_overflowso the user-facing guidance is unchanged, and ordinary TPM throttling still remains a rate limit.
3. Cross-unit false positive (
0c2b223). Reviewing the above surfaced a defect in my own firstcommit: the limit and the requested size were read with two independent patterns, so a message
stating an RPM limit in one sentence and a TPM request size in another resolved to
Limit 30, Requested 5000and read as a ceiling. That misclassifies a throttle waiting would clear,and making the ceiling case terminal raises the cost of it from wrong copy to an ended session. One
pattern now spans both figures without crossing a sentence boundary, so they are only paired when the
provider stated them together. It is net simpler than what it replaces.
4. Configured fallback at the boundary (
666bf47) — the second P1. The terminal branch sitsbelow the
genericCompactionRecoveryAllowedearly return, andgenericCompactionRecoveryAllowed = !pluginHarnessOwnsTransport(runtime-preparation.ts:211). Sofor a transport-owning plugin harness the refusal never reaches that branch: it leaves the embedded
runner as a
FailoverErrorand lands onmodel-fallback-runner.ts:628,which rethrows every context-overflow-shaped message rather than advancing candidates. Correct for
context overflow — another model may have a smaller window and fail worse — but wrong for a ceiling,
which belongs to the refusing provider's quota, not to any model's window. A differently
provisioned candidate is exactly what may still admit the request.
That guard reads
formatErrorMessage(err), and by thenerror-text.ts:161has replaced the providertext with
"Context overflow: prompt too large for the model…"— theLimitandRequestedfiguresthe predicate needs are gone, so re-deriving the fact there cannot work. It is therefore recorded
once, on the
FailoverError, at construction, while the provider's own text is still intact(
rawError), and the boundary reads the recorded fact. This is the review's recommended option 1,and it is also what its merge-risk note asked for: the fact is carried across the boundary rather
than inferred from user-facing copy.
5. Unit-bound parsing (
5738dec) — the third P1. ClawSweeper caught that the predicate requireda TPM hint anywhere in the message but then read the first clause stating both figures. A refusal
that states its numbers in requests and mentions TPM in a later sentence —
on requests per minute (RPM): Limit 30, Used 30, Requested 100 ... See the tokens per minute (TPM) guidance— compared a request count against a token budget and read as a ceiling. Because a ceilingis terminal, that ends a session waiting would have cleared, which is the failure this PR exists to
prevent, pointed the other way.
The unit now has to lead the clause, so the figures are only paired when the provider stated them as
tokens; a message stating both units still decides on the token-denominated pair. Two regressions
cover it and both fail against the previous pattern. This is the second defect the review has found
in my own parsing — worth saying plainly, because it is the part of this change with the least
margin for error and the most expensive failure mode.
Boundaries, stated plainly.
asymmetry is deliberate and measured — see Evidence §2.
Inside an embedded run the refusal is already in the hands of the same-model retry controller, so
returning it there is what produced the reported bug; at the boundary the run has ended and the
next thing is a different candidate, which is a genuinely different request.
agent-runner-fallback-settlement.ts:103logsAuto-compaction failed (…)on a branch that isnewly reachable for this error, where compaction never ran. Cosmetic and in a different owner, so
left out of this PR; happy to follow up.
reasoning, 30 the structural fact and its reader on
FailoverError, 15 the recovery branch, 6 theboundary exception; the rest is two re-export lines and hoisting the reset-guidance copy that the
ceiling branch and the exhausted branch now share instead of duplicating.
User Impact
A Groq session that crosses the per-request token ceiling now stops on the first refusal instead of
thrashing, and tells the user the thing that actually works:
Ordinary TPM throttling is untouched and still retries with backoff. Every tool-capable Groq model
carries the same 8,000 TPM, so this is not specific to
gpt-oss-120b.Evidence
1. Live provider-session trace (the review's main ask)
📎 Runnable artifact: all three measured runs, the mock provider, and the pinned config —
every log quoted below in full, plus the two rejected designs, reproducible with no API key.
No Groq key was available here, so the provider is stood in for locally: a ~60-line
node:httpresponder returning Groq's exact refusal — HTTP 413,
code: "rate_limit_exceeded",x-ratelimit-remaining-tokens: 8000(bucket full),retry-after: 1, body namingLimit 8000, Requested <n>. The classifier is message-based, not provider-based, so this exercisesthe real path. Org id is
org_REDACTEDand the key is a literal placeholder; nothing real isinvolved.
Driver:
openclaw agent exec "Say hello." --config <pinned> --state-dir <isolated> --model mock-groq/openai/gpt-oss-120b,against an isolated
OPENCLAW_STATE_DIR— never the operator's gateway.The provider contract this matches
The wording the predicate keys on is not inferred — it is a live Groq response captured against
api.groq.comand recorded in #130096, onopenai/gpt-oss-120b, freeon_demandtier:{"error":{"message":"Request too large for model `openai/gpt-oss-120b` in organization `org_REDACTED` service tier `on_demand` on tokens per minute (TPM): Limit 8000, Requested 8098, please reduce your message size and try again.","type":"tokens","code":"rate_limit_exceeded"}}Two things in that capture are load-bearing.
remaining-tokensequalslimit-tokens— the bucket isfull and the request is refused anyway, which is what makes
retry-after: 1unfollowable. Andthe provider states the unit in the same clause as the figures, which is exactly what
STATED_TOKEN_SIZES_RErequires after5738dec.The mock's body is that string, byte for byte:
Anyone with a Groq key can re-take the capture in one command (#130096):
Repeat it immediately and it fails identically, because the failure is about size, not bucket state.
(Groq sits behind Cloudflare, which answers
403 error code: 1010to a User-Agent naming an HTTPlibrary — set an ordinary one.)
After this PR — one request, terminal, correct guidance:
Note
compactionTokens=131073— the budget generic recovery would have compacted toward, againsta ceiling of 8,000. That single number is the P1 in one line.
Requests observed by the provider, and absent strings in the run:
With the terminal branch removed — the head of the first review (classifier fix present, terminal branch
removed, same mock, same command; full log).
This is the P1 reproduced end to end:
Four provider requests instead of one, and the reason is worse than "compaction was pointless":
compaction's own summarizer calls the same model, so it hits the same ceiling and fails three more
times before the safeguard cancels it to preserve history. Compaction cannot recover a per-request
ceiling — it can only spend more doomed calls against it.
Re-measured at the exact current head (
f4680dd, after the third rebase, freshly built): oneprovider request, refused
413 (Limit 8000, Requested 8098); the recovery owner logsprovider request-size ceiling ... compaction=skipped retry=skipped, the run surfaces the resetguidance, and
attempting auto-compaction/rate-limit same-model retry/Truncated ... tool resultappear 0 times each. The trace is1b-after-fix-exact-head.login the gist.2. Why embedded recovery stays terminal (measured)
Before settling on the review's split I built the alternative it implicitly rules out: recovery
returns
{action: "none"}for a ceiling and lets model failover own the whole thing. On paper it isstrictly tidier — one policy, no bespoke terminal branch, no asymmetry to explain. Same mock, same
command, only that branch changed (full log):
Five requests, and the reported bug restored. The provider answers a ceiling with
code: "rate_limit_exceeded", so the failover reason israte_limitregardless of how the messageclassifies — declining hands the refusal straight back to the same-model retry controller that
reported it, which re-sends the payload with backoff and, once the retries are spent, falls into
auto-compaction anyway.
So the asymmetry is not a wart: inside an embedded run the only thing downstream of "decline" is
the same request again, while at the fallback boundary the run has ended and the next thing is a
different candidate. Terminal in the first place, rotating in the second, is the split that leaves
both correct. That is exactly what ClawSweeper recommended, and I would not have believed it without
running it.
maintoday (classifiedrate_limit){action: "none"})3. Fallback-boundary regression (the second P1)
src/agents/model-fallback.test.tscovers the boundary in both directions, using the error shape thetransport-owned path actually produces — a
FailoverErrorwhose message is the normalizedcontext-overflow copy and whose
rawErrorcarries the provider's text:666bf47with theFailoverErrorrethrown instead,runcalled once rather than twice;runcalled once — this pins the existingcontract that the exception is carved out of, and passes before and after.
src/agents/failover-error.test.tscovers the structural fact directly: recorded fromrawErrorwhen the message no longer states the figures, read from a bare error's own message when it never
became a
FailoverError, found through a wrappingcause, and false for throttling, for ordinaryoverflow, and for
null/undefined.4. Owner-boundary regression, at both recovery seams
The first review asked to "cover that boundary". Both seams are covered, and both fail before the
fix with
{action: "retry"}— that P1 as an assertion:src/agents/embedded-agent-runner/run.overflow-context-recovery.test.ts— the canonical ownersuite, which mocks
./run/compaction-runtime.js, so it asserts the compaction entry pointcompactEmbeddedRunForRecoveryis never invoked, plus the new warn line. It deliberately setssessionLikelyHasOversizedToolResultsto true, so an implementation that only skippedcompaction would still fall into fallback truncation and return
retry— this pins realterminality, not just a compaction bypass.
src/agents/embedded-agent-runner/run/overflow-context-recovery.test.ts— the colocated suite,which runs the real compaction runtime, so it asserts the context engine is never asked to compact
and no tool-result truncation runs.
Both suites also pin the negative case — ordinary TPM throttling (
Used 7500, Requested 1000)returns
{action: "none"}and never reaches overflow recovery — and it passes before and after,so it holds the preserved behavior in place.
The canonical suite additionally pins that the terminal branch does not consume the run's recovery budget
(
overflowCompactionAttemptsstays 0,toolResultTruncationAttemptedstays false), so a genuineoverflow later in the same run still gets its full attempts.
5. Classifier regression
src/agents/failover/context-overflow.test.tscovers the oversized shape, the throttled shape, aTPM refusal stating neither size, and one stating a limit but no requested size (the last two
stay
rate_limit). Only the oversized assertion fails pre-fix.It also covers the newly exported predicate directly, including both cross-unit cases: an RPM limit
and a TPM request size in different sentences must not pair (
0c2b223), and an RPM clausestating both figures must not be read as a token ceiling merely because TPM is named elsewhere
(
5738dec). A message stating both units decides on the token-denominated pair. Each fails againstthe pattern it replaced.
src/agents/embedded-agent-runner.run-embedded-agent.fault-sequences.e2e.test.tspins the embeddedterminal policy through the real runner (
5edfdf4). A 413 fault carrying Groq's verbatim wordingjoins the existing fault union, and the case asserts one attempt, a
blockedcontext_overflowpayload with the reset guidance, an eligible
groq/mock-2candidate left unspent, and norate-limit cooldown on the profile — waiting cannot admit the request, so the profile has done
nothing wrong. It is the counterpart to the boundary regression above.
I first wrote that case in
model-fallback.run-embedded.e2e.test.ts, which sits at itsmax-linescap; CI caught it, and the fault-sequence suite is the better home anyway — it already models
refusals as injected statuses. That file is reverted to
mainbyte for byte.Blast radius. I swept every TPM-worded string literal under
src/agents,src/gateway,packages/ai/src/utils, andextensions/groqthrough the new predicate. Of 8 TPM-worded messages,exactly one flips — the new test's oversized case. No pre-existing fixture changes classification.
6. Acceptance criteria from the review
node scripts/run-vitest.mjs src/agents/failover/context-overflow.test.tsnode scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/overflow-context-recovery.test.tsFailoverError.requestSizeCeiling, recorded once at constructionmodel-fallback.test.ts, both directionsgit diff --check7. Full validation (Node 26.4.0, macOS)
Re-run in full after the third rebase, onto current
main(f30ed1b). Commit SHAs above move witheach rebase; the six subjects are stable.
pnpm buildpnpm tsgo:core,pnpm tsgo:test:srcvitest run src/agents/embedded-agent-runner/run src/agents/failover/ failover-error model-fallbackFailoverError(34 files)oxlint --deny-warningsover every changed source filepnpm lint(full)extensions/qa-lab,extensions/imap,extensions/daytona, none in this diffembedded-agent-runner.run-embedded-agent.fault-sequences.e2e.test.tsvitest.e2e.config.tsoxfmt --checkgit diff --checkpnpm checkOn the red CI rows. All infrastructure, zero findings — and
check-lint, the job that flaked onthe previous head, is now green. On this head's run, 199 checks pass; the red rows never reached
this diff: seven jobs failed in their
Checkout/ "Ensure secrets base commit (PR fast path)" setupsteps and two more were
cancelledby a runner shutdown mid-step (check-lint-core-2died inCheckout;check-test-types-core-1mid-stripe), withopenclaw/ci-gatemirroring them. Thewindow coincided with a maintainer-dispatched release-gate validation run, i.e. the capacity-stall
case
ci.yml's ownrelease_gateinput describes. Every one of those lanes passed on the previoushead and their surfaces are untouched by this diff; locally, the full battery on this exact head is
green (validation table above). A re-run of the failed jobs should clear the gate; I cannot trigger
one from a fork.
Proof gaps, stated plainly. I could not re-run the live Groq API from this machine (no key
here); the live measurements — status codes,
x-ratelimit-remaining-tokens: 8000on a refusedrequest, and the exact reservation arithmetic — are recorded in #130096 with a
curlrepro thatneeds only a key. Everything above is reproducible with no key at all. I also could not run the
autoreviewskill: this environment has nocodexbinary, and autoreview refuses to send withoutTruffleHog, which is not installed — I ran a structured self-review over the diff instead.
The transport-owned path is proved at its boundary rather than end to end: the mock stands in for a
provider, not for a transport-owning plugin harness, so the regression drives
runWithModelFallbackdirectly with the error shape that path produces. Building a harness pluginpurely to observe rotation would test the fixture more than the fix.
One note on the earlier ClawSweeper live check: its
expect_outputassertion looked for thedescribe-block name in Vitest's terminal output, but Vitest only prints file-level lines for passing
suites, so that assertion failed while the suite itself passed (
5 passed). Nothing was wrong withthe tests.
No changelog edit, per CONTRIBUTING.