Skip to content

fix(failover): oversized Groq requests stall the session with unusable rate-limit advice - #130275

Merged
obviyus merged 7 commits into
openclaw:mainfrom
jerome-queck:fix/tpm-request-size-ceiling-overflow
Aug 28, 2026
Merged

obviyus merged 7 commits into
openclaw:mainfrom
jerome-queck:fix/tpm-request-size-ceiling-overflow

Conversation

@jerome-queck

@jerome-queck jerome-queck commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Closes #130096

Maintainer verification at 8e115ac5. A built CLI against a local responder returning the
captured Groq 413 made four requests on current-main behavior, spent all three same-model retries,
and gave no reset guidance. The repaired head made one request, skipped retry, compaction, and
tool-result truncation, then returned /reset or /new guidance. All 287 focused tests passed,
including the provider fault-sequence E2E suite. Review also removed a duplicated 132-line unit
setup; the final diff is production +112/-17, tests +291/-6, and docs +5/-0.

Direct Codex contract check: openai/codex@3ae4225 maps streamed rate_limit_exceeded errors to
retryable rate-limit failures in codex-rs/codex-api/src/sse/responses.rs:413 and
codex-rs/protocol/src/error.rs:371, while ContextWindowExceeded is terminal in
codex-rs/core/src/session/turn.rs:1426.

🤖 AI-assisted (Claude Opus 5, via Claude Code). I wrote the issue, drove the investigation,
and read every path this touches.

Update for ClawSweeper's third review. The remaining P1 — preserve configured fallback for
transport-owning harnesses — is implemented
in 666bf47, as the review's recommended option 1:
the ceiling is now carried structurally on FailoverError and decided at the fallback boundary,
embedded recovery stays terminal, and there is a boundary regression that fails without it.
Nothing is left for a maintainer to decide.

Implementing it also settled a question I had raised in the other direction. I first tried the
tidier-looking design — recovery declines with {action: "none"} and lets failover own the whole
thing — and measured it against the provider stand-in: it costs five provider requests and
reaches auto-compaction anyway
, because declining returns the refusal to the same-model
rate-limit retry that reported it. That is the reported bug, restored. The measurement is in
Evidence §2. ClawSweeper's split — terminal
inside the embedded run, rotation preserved at the boundary — is the one that holds.

The follow-up review then found a third P1 in my own parsing — an RPM clause could be read as
a token ceiling when TPM appeared elsewhere in the message. Fixed in 5738dec with two
regressions; details in Why this change was made §5.

With this, the PR changes no fallback outcome relative to main. The three runs behind that
claim are published as a runnable artifact, linked in Evidence §1.

Also rebased onto current main three times as it kept moving — most recently onto f30ed1b (489
further commits), a clean apply. The only semantic overlap in that round is #131554's new
markOwnedTranscriptRetry() hook in the recovery owner: it marks the three retry paths, and the
terminal ceiling branch intentionally does not mark one because it does not retry — the same shape
as the existing exhausted-surface branch. (The earlier round's one conflict, in
session-management-compaction.md where #130863 rewrote the surrounding list, stays resolved in
upstream's favor.)

Since the last review, ClawSweeper's fresh triage of the canonical issue (#130096, 2026-08-28) now
names this PR as the owning fix — clawsweeper:linked-pr-open added, needs-product-decision
removed — and calls exact-head review of this PR the next step.

What Problem This Solves

Fixes an issue where users on a Groq free/on_demand tier 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:

prompt_tokens ≈ 3598, max_tokens = 4500  →  HTTP 413
x-ratelimit-remaining-tokens: 8000       ← the bucket is FULL
retry-after: 1

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 (/reset or /new) was already
implemented 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 in isContextOverflowErrorFromTables exists for a
good 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:

Provider says Meaning Waiting helps?
Limit 8000, Used 7500, Requested 1000 bucket is busy yes → stays rate_limit
Limit 8000, Requested 8098 request exceeds the whole limit never → context_overflow

No new overflow pattern was added: the tables already carry /413[\s\S]*too large/i, so the guard
was the only thing suppressing a match the classifier could already make.

2. Terminal recovery (e9e7742) — the first P1. Classification alone routed the refusal into
recoverEmbeddedRunOverflow, which force-compacts, adopts a successor transcript, and retries. That
recovery 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=131073
against 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. isProviderRequestSizeCeilingError names the case the classifier already detects, and
the 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_overflow
so 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 first
commit: 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 5000 and 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 sits
below the genericCompactionRecoveryAllowed early return, and
genericCompactionRecoveryAllowed = !pluginHarnessOwnsTransport (runtime-preparation.ts:211). So
for a transport-owning plugin harness the refusal never reaches that branch: it leaves the embedded
runner as a FailoverError and lands on
model-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 then error-text.ts:161 has replaced the provider
text with "Context overflow: prompt too large for the model…" — the Limit and Requested figures
the 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 required
a 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 ceiling
is 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.

  • Embedded runs are terminal for this error class; the transport-owned path keeps rotating. That
    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:103 logs Auto-compaction failed (…) on a branch that is
    newly reachable for this error, where compaction never ran. Cosmetic and in a different owner, so
    left out of this PR; happy to follow up.
  • On production size: source is +110/−17. Roughly 40 lines are the classifier predicate and its
    reasoning, 30 the structural fact and its reader on FailoverError, 15 the recovery branch, 6 the
    boundary 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:

Context overflow: prompt too large for the model. Try /reset (or /new) to start a fresh session, or use a larger-context model.

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:http
responder returning Groq's exact refusal — HTTP 413, code: "rate_limit_exceeded",
x-ratelimit-remaining-tokens: 8000 (bucket full), retry-after: 1, body naming
Limit 8000, Requested <n>. The classifier is message-based, not provider-based, so this exercises
the real path. Org id is org_REDACTED and the key is a literal placeholder; nothing real is
involved.

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.com and recorded in #130096, on
openai/gpt-oss-120b, free on_demand tier:

prompt_tokens ≈ 3598, max_tokens = 4500  →  HTTP 413
x-ratelimit-limit-tokens:     8000
x-ratelimit-remaining-tokens: 8000       ← the bucket is FULL, and it still refuses
x-ratelimit-reset-tokens:     1ms
retry-after:                  1
{"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-tokens equals limit-tokens — the bucket is
full and the request is refused anyway, which is what makes retry-after: 1 unfollowable. And
the provider states the unit in the same clause as the figures, which is exactly what
STATED_TOKEN_SIZES_RE requires after 5738dec.

The mock's body is that string, byte for byte:

real = <message field from the capture above>
mock = <message the mock emits on request #1>
real == mock   # True

Anyone with a Groq key can re-take the capture in one command (#130096):

curl -sS -o /dev/null -D- https://api.groq.com/openai/v1/chat/completions \
  -H "Authorization: Bearer $GROQ_API_KEY" \
  -H 'Content-Type: application/json' \
  -H 'User-Agent: repro/1.0' \
  -d '{"model":"openai/gpt-oss-120b",
       "max_tokens":4500,
       "messages":[{"role":"user","content":"'"$(python3 -c 'print("word "*3500, end="")')"'"}]}'

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: 1010 to a User-Agent naming an HTTP
library — set an ordinary one.)

After this PR — one request, terminal, correct guidance:

[model-fetch] start  provider=mock-groq method=POST url=http://127.0.0.1:8731/v1/chat/completions
[model-fetch] response provider=mock-groq api=openai-completions model=openai/gpt-oss-120b status=413
[context-overflow-diag] ... compactionAttempts=0 observedTokens=unknown preflightEstimatedTokens=unknown compactionTokens=131073
[context-overflow-recovery] provider request-size ceiling for mock-groq/openai/gpt-oss-120b;
    livenessState=blocked suggestedAction=reset_or_new kind=context_overflow compaction=skipped retry=skipped
embedded run agent end: isError=true
    error=Context overflow: prompt too large for the model. Try /reset (or /new) to start a fresh session, or use a larger-context model.

Note compactionTokens=131073 — the budget generic recovery would have compacted toward, against
a ceiling of 8,000. That single number is the P1 in one line.

Requests observed by the provider, and absent strings in the run:

[mock-groq] #1 POST /v1/chat/completions bytes=73101 -> 413 (Limit 8000, Requested 8098)
(no further requests)

'attempting auto-compaction'   : 0 occurrences
'auto-compaction succeeded'    : 0 occurrences
'rate-limit same-model retry'  : 0 occurrences
'Truncated .* tool result'     : 0 occurrences

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:

[context-overflow-diag] ... compactionTokens=131073
[compaction-diag] decision branch=compact attempt=1 maxAttempts=3
context overflow detected (attempt 1/3); attempting auto-compaction for mock-groq/openai/gpt-oss-120b
[compaction] Full summarization failed: Summarization failed: 413 Request too large ... Requested 8182
[compaction-safeguard] Compaction summarization failed; cancelling compaction to preserve history
auto-compaction failed for mock-groq/openai/gpt-oss-120b: ... summarization_failed
[context-overflow-recovery] exhausted provider overflow recovery ...
[mock-groq] #1 POST ... -> 413 (Limit 8000, Requested 8098)
[mock-groq] #2 POST ... -> 413 (Limit 8000, Requested 8126)
[mock-groq] #3 POST ... -> 413 (Limit 8000, Requested 8154)
[mock-groq] #4 POST ... -> 413 (Limit 8000, Requested 8182)

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): one
provider request, refused 413 (Limit 8000, Requested 8098); the recovery owner logs
provider request-size ceiling ... compaction=skipped retry=skipped, the run surfaces the reset
guidance, and attempting auto-compaction / rate-limit same-model retry / Truncated ... tool result appear 0 times each. The trace is 1b-after-fix-exact-head.log in 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 is
strictly tidier — one policy, no bespoke terminal branch, no asymmetry to explain. Same mock, same
command, only that branch changed (full log):

[context-overflow-recovery] provider request-size ceiling ... compaction=skipped retry=skipped owner=failover
rate-limit same-model retry 1/3 for mock-groq/openai/gpt-oss-120b: delayMs=10000
[context-overflow-recovery] provider request-size ceiling ... compaction=skipped retry=skipped owner=failover
rate-limit same-model retry 2/3 for mock-groq/openai/gpt-oss-120b: delayMs=20000
context overflow detected (attempt 1/3); attempting auto-compaction for mock-groq/openai/gpt-oss-120b
[compaction-safeguard] Compaction summarization failed; cancelling compaction to preserve history
[mock-groq] #1 POST ... bytes=73093 -> 413 (Limit 8000, Requested 8098)
[mock-groq] #2 POST ... bytes=73161 -> 413 (Limit 8000, Requested 8126)
[mock-groq] #3 POST ... bytes=2857  -> 413 (Limit 8000, Requested 8154)
[mock-groq] #4 POST ... bytes=2857  -> 413 (Limit 8000, Requested 8182)
[mock-groq] #5 POST ... bytes=2857  -> 413 (Limit 8000, Requested 8210)

Five requests, and the reported bug restored. The provider answers a ceiling with
code: "rate_limit_exceeded", so the failover reason is rate_limit regardless of how the message
classifies — 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.

design provider requests compaction outcome
main today (classified rate_limit) many — retries with backoff, never converges (#130096)
classifier fix alone (the head you first reviewed) 4 attempted → safeguard cancelled right guidance, 3 wasted calls
decline to failover ({action: "none"}) 5 reached anyway after 2 retries reported bug restored
this PR 1 skipped right guidance, immediately

3. Fallback-boundary regression (the second P1)

src/agents/model-fallback.test.ts covers the boundary in both directions, using the error shape the
transport-owned path actually produces — a FailoverError whose message is the normalized
context-overflow copy and whose rawError carries the provider's text:

  • a request-size ceiling advances to the configured candidate — fails before 666bf47 with the
    FailoverError rethrown instead, run called once rather than twice;
  • an ordinary context overflow still rethrows, run called once — this pins the existing
    contract that the exception is carved out of, and passes before and after.

src/agents/failover-error.test.ts covers the structural fact directly: recorded from rawError
when the message no longer states the figures, read from a bare error's own message when it never
became a FailoverError, found through a wrapping cause, and false for throttling, for ordinary
overflow, 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 owner
    suite, which mocks ./run/compaction-runtime.js, so it asserts the compaction entry point
    compactEmbeddedRunForRecovery is never invoked, plus the new warn line. It deliberately sets
    sessionLikelyHasOversizedToolResults to true, so an implementation that only skipped
    compaction would still fall into fallback truncation and return retry — this pins real
    terminality, 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.
FAIL  run.overflow-context-recovery.test.ts > stops the run on a provider request-size ceiling instead of compacting
AssertionError: expected { action: 'retry' } to match object { action: 'surface', …(1) }
      463|     expect(mocks.compact).not.toHaveBeenCalled();

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
(overflowCompactionAttempts stays 0, toolResultTruncationAttempted stays false), so a genuine
overflow later in the same run still gets its full attempts.

5. Classifier regression

src/agents/failover/context-overflow.test.ts covers the oversized shape, the throttled shape, a
TPM 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 clause
stating 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 against
the pattern it replaced.

src/agents/embedded-agent-runner.run-embedded-agent.fault-sequences.e2e.test.ts pins the embedded
terminal policy through the real runner (5edfdf4). A 413 fault carrying Groq's verbatim wording
joins the existing fault union, and the case asserts 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. 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 its max-lines
cap; 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 main byte for byte.

Blast radius. I swept every TPM-worded string literal under src/agents, src/gateway,
packages/ai/src/utils, and extensions/groq through 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

Criterion Result
node scripts/run-vitest.mjs src/agents/failover/context-overflow.test.ts ✅ 11 tests
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/overflow-context-recovery.test.ts ✅ 4 tests
Carry the ceiling fact structurally across the failover boundary ✅ FailoverError.requestSizeCeiling, recorded once at construction
Transport-owning-harness regression proving an eligible candidate still runs ✅ model-fallback.test.ts, both directions
git diff --check ✅ clean

7. Full validation (Node 26.4.0, macOS)

Re-run in full after the third rebase, onto current main (f30ed1b). Commit SHAs above move with
each rebase; the six subjects are stable.

Command Result
pnpm build ✅
pnpm tsgo:core, pnpm tsgo:test:src ✅
vitest run src/agents/embedded-agent-runner/run src/agents/failover/ failover-error model-fallback ✅ 5,199 tests / 365 files
every non-live, non-e2e suite in the repo that references FailoverError (34 files) ✅ 1,968 tests — the recorded field breaks no equality or serialization assertion
oxlint --deny-warnings over every changed source file ✅ exit 0
pnpm lint (full) ✅ no finding in any changed file — 28 pre-existing findings, all in extensions/qa-lab, extensions/imap, extensions/daytona, none in this diff
e2e: embedded-agent-runner.run-embedded-agent.fault-sequences.e2e.test.ts ✅ 8/8, via vitest.e2e.config.ts
oxfmt --check ✅ 30,972 files
git diff --check ✅ clean
pnpm check ✅ all lanes (before the rebase; individual lanes re-run above)

On the red CI rows. All infrastructure, zero findings — and check-lint, the job that flaked on
the 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)" setup
steps and two more were cancelled by a runner shutdown mid-step (check-lint-core-2 died in
Checkout; check-test-types-core-1 mid-stripe), with openclaw/ci-gate mirroring them. The
window coincided with a maintainer-dispatched release-gate validation run, i.e. the capacity-stall
case ci.yml's own release_gate input describes. Every one of those lanes passed on the previous
head 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: 8000 on a refused
request, and the exact reservation arithmetic — are recorded in #130096 with a curl repro that
needs only a key. Everything above is reproducible with no key at all. I also could not run the
autoreview skill: this environment has no codex binary, and autoreview refuses to send without
TruffleHog, 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
runWithModelFallback directly with the error shape that path produces. Building a harness plugin
purely to observe rotation would test the fixture more than the fix.

One note on the earlier ClawSweeper live check: its expect_output assertion looked for the
describe-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 with
the tests.

No changelog edit, per CONTRIBUTING.

@clawsweeper

clawsweeper Bot commented Aug 26, 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 agents Agent runtime and tooling size: S labels Aug 26, 2026
@jerome-queck
jerome-queck marked this pull request as ready for review August 26, 2026 18:22
@clawsweeper

clawsweeper Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 28, 2026, 4:36 PM ET / 20:36 UTC.

ClawSweeper review

What this changes

The 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 provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep 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
Reviewed head: 8e115ac5c00bc9c3618db1acf1e5826fc489619c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with layered source coverage and supplied production-path behavior evidence.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (linked_artifact): The PR supplies after-fix built-CLI evidence for the production provider-error path: the baseline repeatedly requested while the patched build stopped and displayed reset/new-session guidance.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): The PR supplies after-fix built-CLI evidence for the production provider-error path: the baseline repeatedly requested while the patched build stopped and displayed reset/new-session guidance.
Evidence reviewed 7 items Current-main behavior: Current main retains the TPM exclusion that classifies Groq TPM wording as rate limiting unless the branch’s new requested-versus-limit exception is present.
Introduced classifier: The branch accepts only a TPM/token-denominated clause with both Limit and Requested values and requires Requested to exceed Limit.
Recovery owner: The embedded recovery owner stops rather than compacts or retries an unsatisfiable provider request, and returns existing reset/new-session guidance.
Findings None None.
Security None None.

How this fits together

Provider 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]
Loading

Before merge

  • Resolve merge risk (P1) - The deliberately narrow matcher depends on Groq retaining a token-denominated Limit … Requested … refusal; unrecognized wording remains on the pre-existing rate-limit path.
  • Complete next step (P2) - The existing PR already owns the bounded repair; remaining work is normal exact-head maintainer validation and landing.
Agent review details

Security

None.

PR surface

Source +95, Tests +285, Docs +5. Total +385 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 6 112 17 +95
Tests 5 291 6 +285
Docs 2 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 408 23 +385

Review metrics

Metric Value Why it matters
Production vs test delta production +112/-17; tests +291/-6; docs +5/-0 The production routing change is accompanied by classifier, wrapper, fallback, and recovery coverage.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #130096
Summary: This PR is the candidate fix for the Groq request-size classification problem.

Members:

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

Merge-risk options

Maintainer options:

  1. Validate the intended routing change (recommended)
    Confirm exact-head checks preserve ordinary TPM throttling while routing only impossible single requests to terminal guidance or configured fallback.

Technical review

Best 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.

Labels

Label justifications:

  • P1: An affected active Groq session can repeatedly retry an impossible request instead of receiving a recoverable terminal outcome.
  • merge-risk: 🚨 compatibility: The PR intentionally changes handling of a narrow existing provider-error shape from rate-limit handling to reset guidance or configured fallback.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The PR supplies after-fix built-CLI evidence for the production provider-error path: the baseline repeatedly requested while the patched build stopped and displayed reset/new-session guidance.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR supplies after-fix built-CLI evidence for the production provider-error path: the baseline repeatedly requested while the patched build stopped and displayed reset/new-session guidance.

Evidence

Acceptance criteria:

  • [P1] Confirm exact-head CI.
  • [P2] Retain the classifier, fallback, and terminal-recovery coverage.

What I checked:

Likely related people:

  • steipete: Current-main history and blame for the failover classification surface identify sustained recent work in this owner boundary. (role: recent area contributor; confidence: medium; commits: 90ddeb4, 145ec377; files: src/agents/failover/context-overflow.ts, src/agents/model-fallback-runner.ts)

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 (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-26T23:38:26.961Z sha 5c8c7c056bd4f9f4c9b988157a1d3d966e0ff88b :: found issues before merge. :: [P1] Preserve configured fallback for transport-owned harnesses
  • reviewed 2026-08-27T00:11:36.229Z sha 5c8c7c056bd4f9f4c9b988157a1d3d966e0ff88b :: found issues before merge. :: [P1] Preserve configured fallback for transport-owning harnesses
  • reviewed 2026-08-27T14:12:18.137Z sha 983ae4ac025c97a2e61cc300172981bfd2cc15cd :: needs maintainer review before merge. :: none
  • reviewed 2026-08-27T14:24:15.648Z sha fbce71aea23ba3be0e0e93a8086882cddb972f7c :: needs changes before merge. :: [P1] Bind the parsed Limit/Requested pair to TPM
  • reviewed 2026-08-27T14:59:46.612Z sha 91a223bfcc4f5c26857c6cf775e23f3fca74b7af :: needs maintainer review before merge. :: none
  • reviewed 2026-08-27T16:18:48.018Z sha 5edfdf45f6ebd5a88c6025708cc6d3892c913873 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T17:23:07.762Z sha f4680dd :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T17:34:45.169Z sha f4680dd :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 26, 2026
@jerome-queck
jerome-queck force-pushed the fix/tpm-request-size-ceiling-overflow branch from 5e8a03d to 5c8c7c0 Compare August 26, 2026 23:30
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M and removed size: S labels Aug 26, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 26, 2026
@jerome-queck
jerome-queck force-pushed the fix/tpm-request-size-ceiling-overflow branch from 5c8c7c0 to 983ae4a Compare August 27, 2026 14:04
@clawsweeper clawsweeper Bot added 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 27, 2026
@clawsweeper clawsweeper Bot removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 27, 2026
@jerome-queck
jerome-queck force-pushed the fix/tpm-request-size-ceiling-overflow branch 2 times, most recently from c39b8de to 5edfdf4 Compare August 27, 2026 16:09
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Aug 27, 2026
@jerome-queck

Copy link
Copy Markdown
Contributor Author

Maintainer re-run requested for check-lint — the only red check is a runner flake, not a finding.

The job log shows the runner received a shutdown signal 90s into the oxlint:extensions shard (exit 143); no lint errors were printed before it died, and every completed run of that shard on this branch has been clean. openclaw/ci-gate is red only because it aggregates that canceled lane. Full log excerpt is in the PR body under Evidence → CI note.

Current state: 190 checks green, branch current with main (MERGEABLE), ClawSweeper 🦞 5/6 with findings none, status: 👀 ready for maintainer look. As a fork author I can't re-run the job myself, and pushing a no-op commit to re-trigger would reset the reviewed head — so a one-click re-run of the failed check-lint job is the last thing between this PR and a fully green gate.

Fixes #130096 (Groq 413 request-size ceiling stalling sessions in retry loops).

jerome-queck and others added 6 commits August 28, 2026 23:32
…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]>
@jerome-queck
jerome-queck force-pushed the fix/tpm-request-size-ceiling-overflow branch from 5edfdf4 to f4680dd Compare August 28, 2026 16:45
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Aug 28, 2026
@obviyus

obviyus commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

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 Requested 8098. Current-main behavior made four requests and spent all three same-model retries. Exact head 8e115ac5 made one request, skipped retry and compaction, and returned /reset or /new guidance. All 287 focused tests and exact-head openclaw/ci-gate passed.

  • Bug: OpenClaw treated an impossible single-request size ceiling as temporary TPM throttling, so it retried a request that could never fit.
  • Fix: OpenClaw now records Requested > Limit from the token-denominated provider clause, stops embedded recovery with useful guidance, and keeps ordinary TPM throttling on its normal backoff path.

Example

Before After
Four failed requests, three waits, raw provider error One failed request, no retry or compaction, reset/new-session guidance

@obviyus
obviyus merged commit 7e05bd4 into openclaw:main Aug 28, 2026
462 of 464 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 29, 2026
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]>
@jerome-queck
jerome-queck deleted the fix/tpm-request-size-ceiling-overflow branch August 29, 2026 14:13
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.

A provider whose TPM limit is also a per-request size ceiling can never reach compaction

2 participants