Skip to content

fix: recover proxy completions sessions when output budget is exhausted - #157673

Merged
obviyus merged 7 commits into
mainfrom
fix/completions-max-tokens-clamp-157307
Sep 25, 2026
Merged

obviyus merged 7 commits into
mainfrom
fix/completions-max-tokens-clamp-157307

Conversation

@obviyus

@obviyus obviyus commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #157307

What Problem This Solves

Fixes sessions getting stuck without a useful reply when an OpenAI-compatible proxy prompt consumes its configured context budget.

User Impact

Exhausted thinking-enabled requests enter existing bounded compaction recovery instead of repeatedly sending a one-token output limit. Normal budgets and deliberately short completions that fit remain unchanged. No configuration or migration is required.

Why This Change Was Made

Replace the insufficient-budget warning with a context-overflow error before provider I/O, using the existing 16-token useful-output floor for reasoning-capable models with thinking not disabled, only when context pressure reduces the requested budget. Non-reasoning and thinking-off requests retain the existing clamping and one-token fallback exactly, including when the estimate leaves zero or negative space. This preserves useful short replies while recovering reasoning-only stalls, using existing model.reasoning metadata and the already-resolved request thinking mode rather than a new heuristic. Any broader estimated-budget policy is outside this fix and remains a separate follow-up. Keep the context cap and the payload-aware clamping introduced by #85889; reuse the diagnostic floor from #140902. Recovery remains owned by the existing runtime, with its existing attempt limits.

Maintainer decision: thinking-enabled requests reduced below the existing 16-token floor enter bounded overflow recovery. The conservative estimate can compact a request the provider tokenizer might have fit; if the prompt cannot be compacted, the turn fails visibly rather than silently looping on one-token reasoning-only replies. Non-reasoning and thinking-off behavior, including the ordinary insufficient-budget warning and one-token fallback, is unchanged.

Evidence

  • Real isolated Gateway against a scripted loopback OpenAI-compatible reasoning provider, configured with contextTokens=16384 and maxTokens=2048, with thinking explicitly enabled for the final red/green. Synthetic history filled the session through normal agent turns.
  • Before: normal requests used max_tokens=2048; the next two turns sent six requests with max_tokens=1, received reasoning-only output, and failed without compaction.
  • After: the same stored session invoked compaction (summary budgets 1638 and 1024), retried with max_tokens=2048, and returned NORMAL_REPLY. The following turn also returned NORMAL_REPLY at 2048. No one-token request was sent after the fix.
  • The fixture initially emitted an invalid compaction summary, correctly rejected by the existing quality guard; after matching its required headings and pending ask, recovery completed without editing session state or changing configuration.
  • Regression cases for exhausted and sub-floor thinking-enabled budgets fail against the original producer (3 failures) and pass with the fix. The useful-floor boundary and an intentional one-token request are preserved.
  • After merging repaired main, repeated the real Gateway red/green with the narrowed guard: the baseline again sent six one-token requests across two failed turns; the candidate compacted and returned normal 2048-budget replies on recovery and the following turn.
  • Non-reasoning Gateway control: the same near-cap prompt returned OK with max_tokens=15 on both baseline and candidate, with no compaction. Focused tests also preserve the 1-token boundary.
  • Thinking-disabled Gateway control: a reasoning-capable Qwen-compatible model with --thinking off sent enable_thinking=false, retained max_tokens=15, and returned OK. The existing Qwen reasoning test now exercises a fixed near-cap system prompt with thinking off versus on.
  • Focused tests after the final refinement: 20 parameter tests, 20 reasoning-policy tests, and 44 overflow-recovery tests passed (40.57s wall combined after merging repaired main). Full suites were not run locally.

@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@obviyus
obviyus marked this pull request as ready for review September 24, 2026 23:07
@obviyus

obviyus commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator Author

The isolated Gateway before/after proof and focused tests pass. Landing is paused because required CI run https://github.com/openclaw/openclaw/actions/runs/36071138464 fails in unchanged src/infra/package-update-npm-pack.ts:7: TS2459, UpdateStepResult is declared locally in update-runner-types.js but not exported. The build-artifacts and check-test-types-core-5 jobs both report this error. No merge will be attempted while required CI is red.

@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 25, 2026, 1:12 AM ET / 05:12 UTC (Revision 5).

ClawSweeper review

What this changes

The branch makes exhausted thinking-enabled proxy completions enter context-overflow recovery and adds tests for short-budget behavior with thinking on and off.

Regression provenance

Possible regression — suspected (failure trace). No predecessor PR is attributed.

Merge readiness

✅ Ready for maintainer review

Current main still sends one-token requests in the reported reasoning-proxy case. The latest branch addresses the prior short-request warning finding, and the recorded Gateway runs support recovery. The maintainer with repository maintain permission accepted the conservative budget threshold.

Priority: P1
Reviewed head: 7f51b6d0abab0d23e59671dc87d251867b2c0ae5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused real Gateway before-and-after evidence and compatibility controls support a bounded transport fix with no remaining actionable finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The changed completions builder raises a recoverable overflow before proxy I/O. The PR records a real isolated Gateway session against a scripted loopback reasoning provider: baseline turns sent one-token requests and failed, while the candidate compacted and returned normal replies on the recovery and following turns; non-reasoning and thinking-off controls retained short replies. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The changed completions builder raises a recoverable overflow before proxy I/O. The PR records a real isolated Gateway session against a scripted loopback reasoning provider: baseline turns sent one-token requests and failed, while the candidate compacted and returned normal replies on the recovery and following turns; non-reasoning and thinking-off controls retained short replies. No stored-data contract changes.
Evidence reviewed 9 items Introduced transport guard: The pinned PR diff makes a reasoning-enabled proxy request with fewer than 16 estimated output tokens throw a context-length error before provider I/O; nonthrowing short requests retain the warning.
Current-main behavior: Fetched main still clamps exhausted proxy output to one token, warns, and proceeds without the proposed reasoning guard.
Recovery boundary: The transport builds the payload before the provider call, and the agent runtime recognizes context-overflow errors for bounded recovery.
Findings None None.
Security None None.

How this fits together

The OpenAI-compatible completions transport turns session history and model settings into a provider request. Its output-budget decision determines whether the agent sends that request or enters the runtime's compaction recovery.

flowchart LR
 A[Session history and model settings] --> B[Completion request builder]
 B --> C{Useful output budget?}
 C -- Too small with thinking --> D[Overflow recovery and compaction]
 D --> B
 C -- Otherwise --> E[Proxy provider]
 E --> F[Agent reply]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +9, Tests +98. Total +107 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 31 22 +9
Tests 2 99 1 +98
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 130 23 +107

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #157307
Summary: This PR is the candidate fix for the linked, still-open reasoning-proxy session-stall report.

Members:

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

Technical review

Best possible solution:

Keep budget sizing in the transport and bounded compaction in the agent runtime, with the existing short-reply and warning behavior protected for nonthinking requests.

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

Yes. The captured PR evidence describes repeated baseline Gateway failures on the current one-token path and recovery on the candidate with the same stored session.

Is this the best way to solve the issue?

Yes. The shared request builder detects the unusable budget before provider I/O, while the existing agent runtime owns compaction and retry.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8a62a6763531.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The changed completions builder raises a recoverable overflow before proxy I/O. The PR records a real isolated Gateway session against a scripted loopback reasoning provider: baseline turns sent one-token requests and failed, while the candidate compacted and returned normal replies on the recovery and following turns; non-reasoning and thinking-off controls retained short replies. No stored-data contract changes.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The reported reasoning-proxy failure can leave an active agent session unable to produce useful replies until recovery.
  • merge-risk: 🚨 compatibility: The accepted threshold changes a near-cap thinking-enabled proxy request from a one-token provider call to a pre-I/O overflow error, including through the exported request builder.
  • 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 (live_output): The changed completions builder raises a recoverable overflow before proxy I/O. The PR records a real isolated Gateway session against a scripted loopback reasoning provider: baseline turns sent one-token requests and failed, while the candidate compacted and returned normal replies on the recovery and following turns; non-reasoning and thinking-off controls retained short replies. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed completions builder raises a recoverable overflow before proxy I/O. The PR records a real isolated Gateway session against a scripted loopback reasoning provider: baseline turns sent one-token requests and failed, while the candidate compacted and returned normal replies on the recovery and following turns; non-reasoning and thinking-off controls retained short replies. No stored-data contract changes.

Evidence

What I checked:

  • Introduced transport guard: The pinned PR diff makes a reasoning-enabled proxy request with fewer than 16 estimated output tokens throw a context-length error before provider I/O; nonthrowing short requests retain the warning. (packages/ai/src/transports/openai-completions-params.ts:533, 7f51b6d0abab)
  • Current-main behavior: Fetched main still clamps exhausted proxy output to one token, warns, and proceeds without the proposed reasoning guard. (packages/ai/src/transports/openai-completions-params.ts:513, 8a62a6763531)
  • Recovery boundary: The transport builds the payload before the provider call, and the agent runtime recognizes context-overflow errors for bounded recovery. (src/agents/embedded-agent-runner/run/overflow-context-recovery.ts:86, 7f51b6d0abab)
  • Short-budget controls: Added tests cover the restored warning, non-reasoning fallback, thinking-off Qwen behavior, and the 16-token boundary, addressing the concrete prior review finding. (packages/ai/src/transports/openai-completions-params.test.ts:309, 7f51b6d0abab)
  • Real Gateway proof: The captured PR body at source revision 93beebfcccd86236a16ad434aa5fd22f4a0a25ac991a3e343283b366b908061a reports six one-token baseline requests across two failed turns; the candidate compacted the same session, returned NORMAL_REPLY at a 2048-token limit, and repeated that result on the next turn. It also reports non-reasoning and thinking-off controls. (7f51b6d0abab)
  • Accepted compatibility tradeoff: The re-review comment explicitly accepts visible failure or compaction when a thinking-enabled request falls below the estimated 16-token floor. Repository permission identifies its author as having maintain access; this acceptance covers the current narrowed change.

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • rendrag-git: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • SunnyShu: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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 (4 earlier review cycles)
  • reviewed 2026-09-24T23:16:40.118Z sha 2fdf371 :: blocked before merge. :: [P1] Preserve short replies for non-reasoning proxy models
  • reviewed 2026-09-25T02:03:01.607Z sha 71c2e7a :: blocked before merge. :: [P1] Respect disabled thinking before rejecting short proxy replies
  • reviewed 2026-09-25T02:17:09.501Z sha acd244c :: blocked before merge. :: none
  • reviewed 2026-09-25T02:32:36.221Z sha eb64068 :: blocked before merge. :: [P2] Preserve the warning when a short proxy request still proceeds

@obviyus

obviyus commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Narrowed the guard per the compatibility finding: model.reasoning uses the existing sub-16 floor; non-reasoning models preserve all positive short budgets; genuinely exhausted budgets reject for both. Repeated the isolated Gateway red/green after merging repaired main, and the non-reasoning near-cap control returned OK at max_tokens=15 before and after, without compaction. All 62 focused tests pass. Updated evidence is in the PR body.

@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. 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. labels Sep 25, 2026
@obviyus

obviyus commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the thinking-disabled finding in acd244c by reusing the existing resolved request thinkingEnabled value before budget clamping. A real Gateway turn with a reasoning-capable Qwen-compatible model and thinking off sent enable_thinking=false with max_tokens=15 and returned OK. The existing Qwen policy test now covers thinking-off short replies versus thinking-on overflow for a fixed near-cap system prompt. All 82 focused parameter, reasoning-policy, and recovery tests pass.

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 25, 2026
@obviyus

obviyus commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Narrowed to the reported thinking-enabled stall only. Non-reasoning and thinking-off requests now retain main’s existing positive short budgets AND one-token fallback for zero/negative estimates. The broader estimated-budget policy is not part of this fix. Added regression coverage for both fallback cases. Repeated the real Gateway red/green with thinking explicitly enabled: baseline six one-token requests across two failed turns; final candidate compacted the same session and returned NORMAL_REPLY at budget 2048 on recovery and the following turn. All 82 focused tests pass. Updated body documents the final scope.

@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Final reasoning-only fix and all 82 focused tests pass, including the repeated real Gateway recovery. Landing is paused on fresh CI run https://github.com/openclaw/openclaw/actions/runs/36086261461: check-additional-runtime-topology-architecture reports two Madge cycles outside this diff, one across state database/user-profile modules and one across gateway/server-startup-config-helpers.ts, server-startup-config.ts, and server-startup-secret-diagnostics.ts. No merge or deterministic-failure rerun was attempted.

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 25, 2026
@obviyus

obviyus commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Restored the ordinary insufficient_output_budget warning for nonthrowing short requests, with coverage for non-reasoning and thinking-off paths. All 84 focused tests pass after merging repaired main.

Maintainer decision (also in the PR body): thinking-enabled requests below the existing 16-token floor enter bounded overflow recovery. The conservative estimate can compact a request the provider tokenizer might have fit; if the prompt cannot be compacted, the turn fails visibly instead of silently looping on one-token reasoning-only replies. This tradeoff is accepted for the reported bug. Non-reasoning and thinking-off behavior, including warnings and one-token fallback, is unchanged.

@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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 Sep 25, 2026
@obviyus
obviyus merged commit 63944b8 into main Sep 25, 2026
341 of 346 checks passed
@obviyus
obviyus deleted the fix/completions-max-tokens-clamp-157307 branch September 25, 2026 05:33
@obviyus

obviyus commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Merged as 63944b8. Thinking-enabled proxy requests with an exhausted output budget now enter existing bounded compaction recovery instead of looping on one-token reasoning-only replies; non-thinking fallbacks and warnings are preserved. The isolated Gateway reproduced six one-token baseline requests across two failed turns, then recovered with normal 2048-token budgets on the repaired turn and the next turn. All 84 focused tests and required CI passed, with hosted review ready on the merged head. Thanks @name5566 for reporting this.

amittell added a commit to amittell/openclaw that referenced this pull request Sep 25, 2026
Ayaan Zaidi's upstream fix for openclaw#157307, merged to main 2026-09-25, after
the 9.6 tag. For an explicit proxy-like openai-completions endpoint, a
request whose estimated input left fewer than 16 output tokens was clamped
to max(1, ...) and sent anyway; a server with a larger real window
prefilled the whole prompt and returned a one-token reasoning-only reply
that overflow recovery could not see, so the session stalled at the cap.
For a reasoning-capable model with thinking not disabled, the builder now
throws a context_length_exceeded error before provider I/O, only when
context pressure lowered the requested budget, and the existing bounded
overflow recovery compacts and retries. Non-reasoning and thinking-off
requests keep the warning and the one-token fallback upstream; the next
commit changes that for the fork.

Applied with cherry-pick -x. The three files were at the same blobs on
this branch and at v2026.9.6 as at the commit's parent (params.ts
ff4d379), so it applied clean and each file now equals upstream's
blob.

Tests ALONE on the branch: openai-completions-params 20/20,
params.reasoning 20/20, transport.requests 4/4,
run.overflow-context-recovery 45/45.

(cherry picked from commit 63944b8)
amittell added a commit to amittell/openclaw that referenced this pull request Sep 25, 2026
Fork delta on upstream openclaw#157673 (the previous commit), re-expressed from the
fork's c1c8e83bbf4. Upstream refuses a proxy-like openai-completions request
whose output budget was clamped below 16 tokens only for a reasoning model
with thinking not disabled; non-reasoning and thinking-off requests are
still sent, down to max_completion_tokens=1. The bots run qwen3.8-27b with
thinking off often, and Alex chose all-models coverage: a sub-floor reply at
the cap is a stalled turn in every mode, and only compaction frees room for
the next one. The guard now throws upstream's context_length_exceeded error
in every mode; the insufficient_output_budget warning went with the only
path that reached it. A request that was not clamped (a requested budget
that fits) is unchanged.

Upstream tests pinned to the fork decision, each with a FORK DIVERGENCE
comment: "preserves non-reasoning short budgets..." and "warns when a short
non-thinking request proceeds" in openai-completions-params.test.ts, and the
thinking-off near-cap lines of the qwen enable_thinking test in
params.reasoning.test.ts.

From c1c8e83bbf4: its intentionally-short case (15 left, 8 requested, sent
as 8) is folded into the pinned non-reasoning test; its other two params
cases duplicate upstream's. Its transport and recovery tests are kept and
moved to thinking off, the mode upstream still sends. The transport test
asserts no request reaches the server and the terminal carries
context_length_exceeded. The recovery test builds the candidate with
projectProviderError, as the transport assigns it, and passes its text as
assistantErrorText, as attempt-recovery does.

Found on the way: upstream's refusal text ("Context window exceeded: ...")
is matched only by isLikelyContextOverflowError. isContextOverflow and
classifyFailoverSignal return false and null for it, and nothing reads the
context_length_exceeded code, so recovery depends on attempt-recovery
passing the candidate's errorMessage as assistantErrorText, which it does.
c1c8e83bbf4's "Context overflow: ..." wording matched all three; upstream's
wording is kept here so the delta stays minimal.

Tests ALONE: params 20/20, params.reasoning 20/20, transport.requests 5/5,
run.overflow-context-recovery 46/46. With the previous commit's params.ts
the six fork-behaviour tests fail (3, 1, 1, 1), and the transport test
records upstream sending max_completion_tokens=1.
amittell added a commit to amittell/openclaw that referenced this pull request Sep 25, 2026
…d the OTel carry

A new dated section for the three commits added on top of the deployed
16e061d: what each changes, how it was applied, which upstream tests
are pinned to the fork decision, the refusal-text finding (upstream's
wording is recognised only by the text heuristic), and the validation
run on this tree.
@amittell

Copy link
Copy Markdown
Contributor

Thanks for landing this - it covers every exhausted request our two gateways logged on 09-23 and 09-24 (37, all thinking-enabled skill-review runs).

Two follow-ups, filed as #158159 with a PR in #158161:

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 26, 2026
…ed (openclaw#157673)

Closes openclaw#157307

## What Problem This Solves

Fixes sessions getting stuck without a useful reply when an OpenAI-compatible proxy prompt consumes its configured context budget.

## User Impact

Exhausted thinking-enabled requests enter existing bounded compaction recovery instead of repeatedly sending a one-token output limit. Normal budgets and deliberately short completions that fit remain unchanged. No configuration or migration is required.

## Why This Change Was Made

Replace the insufficient-budget warning with a context-overflow error before provider I/O, using the existing 16-token useful-output floor for reasoning-capable models with thinking not disabled, only when context pressure reduces the requested budget. Non-reasoning and thinking-off requests retain the existing clamping and one-token fallback exactly, including when the estimate leaves zero or negative space. This preserves useful short replies while recovering reasoning-only stalls, using existing model.reasoning metadata and the already-resolved request thinking mode rather than a new heuristic. Any broader estimated-budget policy is outside this fix and remains a separate follow-up. Keep the context cap and the payload-aware clamping introduced by openclaw#85889; reuse the diagnostic floor from openclaw#140902. Recovery remains owned by the existing runtime, with its existing attempt limits.

Maintainer decision: thinking-enabled requests reduced below the existing 16-token floor enter bounded overflow recovery. The conservative estimate can compact a request the provider tokenizer might have fit; if the prompt cannot be compacted, the turn fails visibly rather than silently looping on one-token reasoning-only replies. Non-reasoning and thinking-off behavior, including the ordinary insufficient-budget warning and one-token fallback, is unchanged.

## Evidence

- Real isolated Gateway against a scripted loopback OpenAI-compatible reasoning provider, configured with contextTokens=16384 and maxTokens=2048, with thinking explicitly enabled for the final red/green. Synthetic history filled the session through normal agent turns.
- Before: normal requests used max_tokens=2048; the next two turns sent six requests with max_tokens=1, received reasoning-only output, and failed without compaction.
- After: the same stored session invoked compaction (summary budgets 1638 and 1024), retried with max_tokens=2048, and returned NORMAL_REPLY. The following turn also returned NORMAL_REPLY at 2048. No one-token request was sent after the fix.
- The fixture initially emitted an invalid compaction summary, correctly rejected by the existing quality guard; after matching its required headings and pending ask, recovery completed without editing session state or changing configuration.
- Regression cases for exhausted and sub-floor thinking-enabled budgets fail against the original producer (3 failures) and pass with the fix. The useful-floor boundary and an intentional one-token request are preserved.
- After merging repaired main, repeated the real Gateway red/green with the narrowed guard: the baseline again sent six one-token requests across two failed turns; the candidate compacted and returned normal 2048-budget replies on recovery and the following turn.
- Non-reasoning Gateway control: the same near-cap prompt returned OK with max_tokens=15 on both baseline and candidate, with no compaction. Focused tests also preserve the 1-token boundary.
- Thinking-disabled Gateway control: a reasoning-capable Qwen-compatible model with --thinking off sent enable_thinking=false, retained max_tokens=15, and returned OK. The existing Qwen reasoning test now exercises a fixed near-cap system prompt with thinking off versus on.
- Focused tests after the final refinement: 20 parameter tests, 20 reasoning-policy tests, and 44 overflow-recovery tests passed (40.57s wall combined after merging repaired main). Full suites were not run locally.

Co-authored-by: Ayaan Zaidi <[email protected]>
amittell added a commit to amittell/openclaw that referenced this pull request Sep 26, 2026
…imate margin

The openai-completions request builder estimates input as chars/4 with a
1.25 safety margin. Against a real tokenizer (Qwen3) that estimate is
1.4-1.6x the true count for prose, code, tool schemas and CJK text, so a
fixed prompt that really fills about 65-73% of the context was refused
before provider I/O, with nothing for compaction to recover.

When the margined estimate leaves no room and thinking is off (or the
model is non-reasoning), budget from the unmargined chars/4 estimate
instead and refuse only when that also leaves no room. If the unmargined
estimate undercounts, the provider's own context-length rejection enters
the same overflow recovery. Thinking-enabled requests keep the margined
estimate and the 16-token floor from openclaw#157673.

The runtime's required-maintenance test now passes unchanged: its
foreground requests go out with roughly 700 and 4,400 output tokens
instead of triggering an extra overflow compaction. The refusal fixtures move to estimates of at
least 1.25x the context, and an explicit one-token request at an
exhausted estimate is still sent.
amittell added a commit to amittell/openclaw that referenced this pull request Sep 26, 2026
…mates

The unmargined fallback only fired once the margined estimate left no room
at all, so a non-thinking request whose margined room was 1-15 tokens was
still sent with that cap (down to 1, the original one-token defect), and
the cap then jumped back up once the margin was fully exhausted.

For requests without thinking, budget from the unmargined estimate as soon
as the margined estimate leaves fewer than 16 output tokens, and refuse
with context_length_exceeded when the unmargined room is also under 16.
Every cap that context pressure reduces is now at least 16 tokens, caps
fall steadily within each estimate, and refusal is terminal as the prompt
grows. Thinking-enabled requests keep the margined estimate and the
16-token floor from openclaw#157673 unchanged. A caller's own maxTokens that fits
the room (1, 2, 16) is still sent as requested; only budgets that context
pressure cuts are held to the floor.

The refusal now says which estimate it used and how many of the 16
tokens remain, instead of "leaves only 1 output tokens" for an exhausted
prompt. The margin drop is logged as keep_max_tokens when a caller's cap
is honored without clamping, and the insufficient_output_budget warning
is removed because no reduced cap under the floor is sent any more.
steipete pushed a commit that referenced this pull request Oct 14, 2026
…an over-long prompt (#158161)

* fix(ai): reject exhausted proxy completions budgets in every thinking mode

When the estimated input leaves no room for output, the openai-completions
request builder falls back to max_completion_tokens=1 and still sends the
request. #157673 turned that into a context overflow for thinking-enabled
reasoning models; non-reasoning models and thinking-off requests still send
the one-token request, which cannot hold a useful reply and comes back cut
off by length.

Throw the same context_length_exceeded error for those requests when the
estimate leaves zero or negative output space, so the existing overflow
recovery compacts instead. Positive short budgets (1-15 tokens that fit the
estimate) and their insufficient_output_budget warning are unchanged for
non-reasoning and thinking-off requests, and deliberately short requested
budgets are untouched.

Refs #157307

* fix(ai): budget exhausted non-thinking proxy requests without the estimate margin

The openai-completions request builder estimates input as chars/4 with a
1.25 safety margin. Against a real tokenizer (Qwen3) that estimate is
1.4-1.6x the true count for prose, code, tool schemas and CJK text, so a
fixed prompt that really fills about 65-73% of the context was refused
before provider I/O, with nothing for compaction to recover.

When the margined estimate leaves no room and thinking is off (or the
model is non-reasoning), budget from the unmargined chars/4 estimate
instead and refuse only when that also leaves no room. If the unmargined
estimate undercounts, the provider's own context-length rejection enters
the same overflow recovery. Thinking-enabled requests keep the margined
estimate and the 16-token floor from #157673.

The runtime's required-maintenance test now passes unchanged: its
foreground requests go out with roughly 700 and 4,400 output tokens
instead of triggering an extra overflow compaction. The refusal fixtures move to estimates of at
least 1.25x the context, and an explicit one-token request at an
exhausted estimate is still sent.

* fix(ai): hold proxy completions caps to the useful floor on both estimates

The unmargined fallback only fired once the margined estimate left no room
at all, so a non-thinking request whose margined room was 1-15 tokens was
still sent with that cap (down to 1, the original one-token defect), and
the cap then jumped back up once the margin was fully exhausted.

For requests without thinking, budget from the unmargined estimate as soon
as the margined estimate leaves fewer than 16 output tokens, and refuse
with context_length_exceeded when the unmargined room is also under 16.
Every cap that context pressure reduces is now at least 16 tokens, caps
fall steadily within each estimate, and refusal is terminal as the prompt
grows. Thinking-enabled requests keep the margined estimate and the
16-token floor from #157673 unchanged. A caller's own maxTokens that fits
the room (1, 2, 16) is still sent as requested; only budgets that context
pressure cuts are held to the floor.

The refusal now says which estimate it used and how many of the 16
tokens remain, instead of "leaves only 1 output tokens" for an exhausted
prompt. The margin drop is logged as keep_max_tokens when a caller's cap
is honored without clamping, and the insufficient_output_budget warning
is removed because no reduced cap under the floor is sent any more.

* fix(ai): warn when proxy completions fall back to the unmargined estimate

Budgets taken from the unmargined estimate were logged only at debug
level, so the warn-level signal operators used to spot prompts at the
context cap (the insufficient_output_budget lines) disappeared by
default. Log those clamp_max_tokens and keep_max_tokens lines at warn
level, with the margined estimate alongside, since the provider may
still reject the request. Ordinary clamping stays at debug level.

Document the requested-cap rule exactly: the room never counts below one
token, so a requested cap of 1 is sent in every mode even when the
estimate already exceeds the context, and a prompt that really does is
rejected by the provider and enters overflow recovery. Any other
requested cap within the room is sent as is, and a cap that context
pressure cuts below 16 tokens is refused.

Pin the fallback threshold (3,145 characters -> 16 tokens, 3,146 -> 212
at a 1,000-token context), the refusal threshold (3,932 -> 16, 3,933
refused), the refusal wording for both estimates, and the one-token
request with thinking enabled.

* fix(ai): recover from TGI context rejections through compaction

Budgeting from the unmargined estimate lets an undercounted prompt reach
the provider, so recovery depends on its rejection reading as an
overflow. Hugging Face TGI rejects with HTTP 422 `Input validation error:`
and one of two wordings from router/src/validation.rs:
"`inputs` tokens + `max_new_tokens` must be <= N" and
"`inputs` must have less than N tokens". classifyFailoverSignal returned
`format` for both, which stops the runner's compaction, and
isContextOverflow matched neither.

Both wordings join the assistant and strict failover overflow tables.
classifyFailoverSignal, isContextOverflowError and isContextOverflow now
return overflow for both; a `max_new_tokens` limit on its own still does
not. The corpus rows, the assistant-message rows and the predicate test
fail without the table entries (2, 2 and 1 tests).
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…an over-long prompt (openclaw#158161)

* fix(ai): reject exhausted proxy completions budgets in every thinking mode

When the estimated input leaves no room for output, the openai-completions
request builder falls back to max_completion_tokens=1 and still sends the
request. openclaw#157673 turned that into a context overflow for thinking-enabled
reasoning models; non-reasoning models and thinking-off requests still send
the one-token request, which cannot hold a useful reply and comes back cut
off by length.

Throw the same context_length_exceeded error for those requests when the
estimate leaves zero or negative output space, so the existing overflow
recovery compacts instead. Positive short budgets (1-15 tokens that fit the
estimate) and their insufficient_output_budget warning are unchanged for
non-reasoning and thinking-off requests, and deliberately short requested
budgets are untouched.

Refs openclaw#157307

* fix(ai): budget exhausted non-thinking proxy requests without the estimate margin

The openai-completions request builder estimates input as chars/4 with a
1.25 safety margin. Against a real tokenizer (Qwen3) that estimate is
1.4-1.6x the true count for prose, code, tool schemas and CJK text, so a
fixed prompt that really fills about 65-73% of the context was refused
before provider I/O, with nothing for compaction to recover.

When the margined estimate leaves no room and thinking is off (or the
model is non-reasoning), budget from the unmargined chars/4 estimate
instead and refuse only when that also leaves no room. If the unmargined
estimate undercounts, the provider's own context-length rejection enters
the same overflow recovery. Thinking-enabled requests keep the margined
estimate and the 16-token floor from openclaw#157673.

The runtime's required-maintenance test now passes unchanged: its
foreground requests go out with roughly 700 and 4,400 output tokens
instead of triggering an extra overflow compaction. The refusal fixtures move to estimates of at
least 1.25x the context, and an explicit one-token request at an
exhausted estimate is still sent.

* fix(ai): hold proxy completions caps to the useful floor on both estimates

The unmargined fallback only fired once the margined estimate left no room
at all, so a non-thinking request whose margined room was 1-15 tokens was
still sent with that cap (down to 1, the original one-token defect), and
the cap then jumped back up once the margin was fully exhausted.

For requests without thinking, budget from the unmargined estimate as soon
as the margined estimate leaves fewer than 16 output tokens, and refuse
with context_length_exceeded when the unmargined room is also under 16.
Every cap that context pressure reduces is now at least 16 tokens, caps
fall steadily within each estimate, and refusal is terminal as the prompt
grows. Thinking-enabled requests keep the margined estimate and the
16-token floor from openclaw#157673 unchanged. A caller's own maxTokens that fits
the room (1, 2, 16) is still sent as requested; only budgets that context
pressure cuts are held to the floor.

The refusal now says which estimate it used and how many of the 16
tokens remain, instead of "leaves only 1 output tokens" for an exhausted
prompt. The margin drop is logged as keep_max_tokens when a caller's cap
is honored without clamping, and the insufficient_output_budget warning
is removed because no reduced cap under the floor is sent any more.

* fix(ai): warn when proxy completions fall back to the unmargined estimate

Budgets taken from the unmargined estimate were logged only at debug
level, so the warn-level signal operators used to spot prompts at the
context cap (the insufficient_output_budget lines) disappeared by
default. Log those clamp_max_tokens and keep_max_tokens lines at warn
level, with the margined estimate alongside, since the provider may
still reject the request. Ordinary clamping stays at debug level.

Document the requested-cap rule exactly: the room never counts below one
token, so a requested cap of 1 is sent in every mode even when the
estimate already exceeds the context, and a prompt that really does is
rejected by the provider and enters overflow recovery. Any other
requested cap within the room is sent as is, and a cap that context
pressure cuts below 16 tokens is refused.

Pin the fallback threshold (3,145 characters -> 16 tokens, 3,146 -> 212
at a 1,000-token context), the refusal threshold (3,932 -> 16, 3,933
refused), the refusal wording for both estimates, and the one-token
request with thinking enabled.

* fix(ai): recover from TGI context rejections through compaction

Budgeting from the unmargined estimate lets an undercounted prompt reach
the provider, so recovery depends on its rejection reading as an
overflow. Hugging Face TGI rejects with HTTP 422 `Input validation error:`
and one of two wordings from router/src/validation.rs:
"`inputs` tokens + `max_new_tokens` must be <= N" and
"`inputs` must have less than N tokens". classifyFailoverSignal returned
`format` for both, which stops the runner's compaction, and
isContextOverflow matched neither.

Both wordings join the assistant and strict failover overflow tables.
classifyFailoverSignal, isContextOverflowError and isContextOverflow now
return overflow for both; a `max_new_tokens` limit on its own still does
not. The corpus rows, the assistant-message rows and the predicate test
fail without the table entries (2, 2 and 1 tests).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants