Skip to content

fix(agents): include tool schema tokens in context-overflow precheck - #140902

Merged
Patrick-Erichsen merged 3 commits into
openclaw:mainfrom
SunnyShu0925:fix/context-precheck-tool-schemas-140770
Sep 11, 2026
Merged

Patrick-Erichsen merged 3 commits into
openclaw:mainfrom
SunnyShu0925:fix/context-precheck-tool-schemas-140770

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #140770

What Problem This Solves

When an agent has a large MCP tool catalog, the context-overflow precheck reports route=fits while the transport silently clamps max_tokens to 1, producing single-token replies. The precheck only estimated transcript messages and system prompt — not the serialized tool definitions — so it could not see that tools consumed most of the context window. This fix includes tool schema token estimates in the precheck so it reflects the real input size the transport will send, and exposes a visible warning when the output budget is unusably small.

Why This Change Was Made

The precheck and transport layers use two different token estimates that disagree on whether tools count. The fix bridges them at the precheck layer so compaction routing sees the full input.

  • Solution: Pass toolSchemaTokens (estimated from the installed model-facing tool surface) through shouldPreemptivelyCompactBeforePrompt so the precheck's estimatedPromptTokens includes tool definitions. When a provider usage boundary is available, its totalTokens already includes the tool schemas from that request, so toolSchemaTokens is not added again to avoid double-counting.
  • Tool surface: The estimate projects name, description, and parameters from activeSession.agent.state.tools using the existing shared estimator. Client tools appended by attempt-client-tools.ts are counted. Runtime-only fields such as outputSchema, labels, and execution metadata are excluded, preventing false overflow.
  • Warning visibility: When the remaining output budget falls below MIN_USEFUL_OUTPUT_TOKENS (16), log.warn emits insufficient_output_budget at a normally visible level, not hidden behind model-debug environment settings.
  • What did NOT change: Compaction logic, transport clamp behavior (Math.max(1, ...) retained as safety floor), other callers of shouldPreemptivelyCompactBeforePrompt (param is optional, no behavior change). The precheck remains diagnostic-only outside provider-checkpoint recovery.

User Impact

Agents with large MCP tool catalogs will no longer have their context-overflow precheck silently miss tool-definition pressure. The precheck correctly identifies overflow from tool definitions, and operators see a visible insufficient_output_budget warning when the output budget is too small for a useful response.

Evidence

The runtime captures and test counts below were submitted for the original contributor head. Maintainer repair f2a0b9ade8aa adds regression cases for metadata-invariant estimates and a fitting checkpoint prompt with a large output schema; final-head hosted CI tracks those cases.

Real agent session via openclaw agent --local with a mock vLLM provider (mock-vllm/test-model, contextWindow=8192). The agent's installed tool catalog (20 plugins with coding tools) exceeds the small context window, triggering both the precheck overflow detection and the transport warning in the same session:

$ OPENCLAW_DEBUG_MODEL_TRANSPORT=1 OPENCLAW_LOG_LEVEL=debug openclaw agent --local -m "Say hello" --json

[agent/embedded] [context-overflow-precheck] pre-prompt check sessionKey=agent:main:main provider=mock-vllm/test-model route=compact_only estimatedPromptTokens=49801 pressureSource=transcript_estimate promptBudgetBeforeReserve=6144 overflowTokens=43657 toolResultReducibleChars=0 reserveTokens=2048 effectiveReserveTokens=2048 contextTokenBudget=8192 messages=3 unwindowedMessages=3 sessionFile=agent:main:main
[agent/embedded] [context-pressure-diagnostic] admitted provider attempt for mock-vllm/test-model route=compact_only estimatedPromptTokens=49801 promptBudgetBeforeReserve=6144
[openai-transport] [completions] clamp_max_tokens provider=mock-vllm api=openai-completions model=test-model requested=4096 output=1 effectiveContext=8192 estimatedInput=41612
[openai-transport] [completions] insufficient_output_budget provider=mock-vllm api=openai-completions model=test-model output=1 effectiveContext=8192 estimatedInput=41612

The precheck ([context-overflow-precheck]) reports route=compact_only with estimatedPromptTokens=49801 — tool schema pressure from the installed tool surface flows through attempt-prompt-phase.ts → prepareEmbeddedAttemptPromptPreflight → shouldPreemptivelyCompactBeforePrompt. The transport ([completions] insufficient_output_budget) emits at log.warn level — visible under normal logging — showing output=1 (clamped) and estimatedInput=41612.

Provider boundary double-count prevention (production shouldPreemptivelyCompactBeforePrompt with simulated 79-tool catalog):

Provider boundary (totalTokens=100000) + toolSchemaTokens=136604:
  without tools: estimatedPromptTokens=100051
  with tools:    estimatedPromptTokens=100051
  double-count prevented: true

Vitest regression tests (33 passed, including 3 tool-schema tests):

$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts --run
 ✓ includes tool schema tokens in the precheck estimate so large catalogs trigger overflow
 ✓ does not alter the estimate when toolSchemaTokens is zero or undefined
 ✓ does not double-count tool schema tokens when a provider boundary is available
 Tests  33 passed (33)

Transport layer tests (47 passed, no regressions):

$ node scripts/run-vitest.mjs packages/ai/src/transports/openai-completions-params.tools.test.ts packages/ai/src/transports/openai-completions-params.shaping.test.ts packages/ai/src/transports/openai-completions-params.compat-and-tool-choice.test.ts packages/ai/src/transports/openai-completions-params.cache-and-compat.test.ts --run
 Test Files  4 passed (4)
 Tests  47 passed (47)

AI Assistance

This PR is AI-assisted. Used Codex CLI to analyze issue #140770, trace the root cause through preemptive-compaction.ts and openai-completions-params.ts, and implement the fix. Revised after ClawSweeper review to: (1) avoid double-counting tool schemas when a provider usage boundary already includes them, (2) estimate from the complete installed tool surface (activeSession.agent.state.tools) rather than effectiveTools, and (3) emit the insufficient-output-budget warning at log.warn level for normal visibility. Evidence includes a real openclaw agent --local session showing tool-pressure diagnostics through the full prompt-phase-to-preflight-to-transport path. All evidence above is from real local runtime execution.

@clawsweeper

clawsweeper Bot commented Sep 7, 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.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 7, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 7, 2026
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 10, 2026, 8:32 PM ET / September 11, 2026, 00:32 UTC (Revision 11).

ClawSweeper review

What this changes

Count installed model-facing tool definitions in context-pressure estimates and warn when compatible-provider output budgeting falls below 16 tokens.

Merge readiness

✅ Ready for maintainer review

This remains a useful, focused repair: current main still omits tool definitions from the precheck. The metadata repair resolves the false-overflow concern, the supplied runtime evidence supports the diagnostic changes, and no blocking introduced defect was found.

Priority: P2
Reviewed head: 12280f2fea43dcefd8841bbb818e339faa5a63a5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with relevant production-path diagnostic evidence and meaningful regression coverage, with no blocking finding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): The supplied original-head agent run exercises the production prompt-phase, preflight, and completions transport against a mock vLLM endpoint, showing schema-driven overflow diagnostics and the low-output warning. The later metadata projection repair has focused regression coverage; no final-head runtime rerun is claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The supplied original-head agent run exercises the production prompt-phase, preflight, and completions transport against a mock vLLM endpoint, showing schema-driven overflow diagnostics and the low-output warning. The later metadata projection repair has focused regression coverage; no final-head runtime rerun is claimed.
Evidence reviewed 8 items Current main still lacks the accounting term: The current-main transcript estimator sums messages and rendered prompt pressure without a tool-schema term. The latest release's precheck has the same omission, so this repair is neither implemented on main nor established as shipped.
Latest-release precheck: Inspection of v2026.9.3 confirms its local pressure calculation contains no tool-schema input. The separate release transport blob was unavailable; no release transport verification is claimed.
Installed tool surface and shared projection: The prompt phase supplies activeSession.agent.state.tools, matching the existing compaction request budget. The shared estimator projects only name, description, and parameters, excluding runtime output schemas and execution metadata.
Findings None None.
Security None None.

How this fits together

The embedded agent runner estimates context pressure from conversation history, the current prompt, and installed tools before submitting a provider request. The completions transport independently shapes that request and limits its output allowance.

flowchart TD
  A[Conversation and prompt] --> C[Context pressure estimate]
  B[Installed tool definitions] --> C
  C --> D[Budget diagnostics and checkpoint recovery]
  D --> E[Provider request shaping]
  E --> F[Output budget clamp]
  F --> G[Low budget warning and provider request]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +41, Tests +133. Total +174 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 5 51 10 +41
Tests 2 133 0 +133
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 184 10 +174

Review metrics

Metric Value Why it matters
Production versus regression coverage Production net +41 lines; tests +133 lines Production growth supplies the missing accounting input and warning while reusing the existing schema projection.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #140770
Summary: This PR addresses the canonical issue's missing schema accounting and warning; the other open PR addresses complementary recovery.

Members:

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

Technical review

Best possible solution:

Keep model-facing schema accounting shared with compaction budgeting while preserving provider-authoritative usage and existing request-admission behavior.

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

Yes, from source: a small transcript and large direct-tool catalog can fit the main precheck while exhausting the transport's schema-inclusive budget. This review did not execute a current-main reproduction.

Is this the best way to solve the issue?

Yes, for the bounded diagnostic repair: the patch reuses model-facing schema accounting and preserves provider-usage semantics. It does not unify every estimator or solve all truncated-reply recovery.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This repairs misleading context diagnostics for large tool catalogs on compatible-provider routes, with a documented workaround.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The supplied original-head agent run exercises the production prompt-phase, preflight, and completions transport against a mock vLLM endpoint, showing schema-driven overflow diagnostics and the low-output warning. The later metadata projection repair has focused regression coverage; no final-head runtime rerun is claimed.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied original-head agent run exercises the production prompt-phase, preflight, and completions transport against a mock vLLM endpoint, showing schema-driven overflow diagnostics and the low-output warning. The later metadata projection repair has focused regression coverage; no final-head runtime rerun is claimed.

Evidence

What I checked:

  • Current main still lacks the accounting term: The current-main transcript estimator sums messages and rendered prompt pressure without a tool-schema term. The latest release's precheck has the same omission, so this repair is neither implemented on main nor established as shipped. (src/agents/embedded-agent-runner/run/preemptive-compaction.ts:114, acbe754b9316)
  • Latest-release precheck: Inspection of v2026.9.3 confirms its local pressure calculation contains no tool-schema input. The separate release transport blob was unavailable; no release transport verification is claimed. (src/agents/embedded-agent-runner/run/preemptive-compaction.ts:114, 1391f7cd2d40)
  • Installed tool surface and shared projection: The prompt phase supplies activeSession.agent.state.tools, matching the existing compaction request budget. The shared estimator projects only name, description, and parameters, excluding runtime output schemas and execution metadata. (src/agents/embedded-agent-runner/run/attempt-prompt-phase.ts:402, 12280f2fea43)
  • Recovery and request-admission boundaries: Provider usage boundaries avoid adding tool pressure twice. Ordinary heuristic overflow remains diagnostic; only the existing selected-checkpoint recovery path can short-circuit submission. The transport change adds a warning without changing the clamp. (src/agents/embedded-agent-runner/run/attempt-prompt-preflight.ts:293, 12280f2fea43)
  • Runtime proof and review continuity: The supplied PR-body snapshot records an actual openclaw agent --local run against a mock vLLM endpoint: the production precheck reports 49,801 estimated tokens and compact_only, followed by the production transport's insufficient_output_budget warning at output=1. This demonstrates improved diagnostics, not prevention of every truncated reply. The capture belongs to contributor head 8cfca31; subsequent comments explain the metadata repair and fixture-only final commit. The prior completed review at the current head retained no findings or rank-up moves. (8cfca31320e0)
  • Regression coverage: The complete changed test files cover oversized catalogs, absent or zero tool pressure, provider-boundary double-count prevention, metadata-invariant estimates, and admission of a fitting checkpoint despite a large runtime output schema. The final fixture explicitly exceeds its 108,000-token prompt allowance. Tests were inspected, not executed in this read-only review. (src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts:752, 12280f2fea43)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • fuller-stack-dev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Patrick-Erichsen: 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 (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-07T06:56:09.949Z sha 8cfca31 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-07T07:04:56.104Z sha 8cfca31 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-07T07:11:35.814Z sha 8cfca31 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-07T08:48:35.096Z sha 8cfca31 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-08T01:51:57.420Z sha 8cfca31 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-11T00:12:42.037Z sha f2a0b9a :: needs maintainer review before merge. :: none
  • reviewed 2026-09-11T00:19:41.470Z sha f2a0b9a :: needs maintainer review before merge. :: none
  • reviewed 2026-09-11T00:26:05.920Z sha 12280f2 :: needs maintainer review before merge. :: none

The context-overflow precheck estimates prompt token pressure to decide
compaction routing, but it only counted transcript messages, system prompt,
and rendered prompt text — not the serialized tool definitions that the
transport layer sends alongside. On proxy-like OpenAI-compatible endpoints
with large MCP catalogs, this caused the precheck to report route=fits while
the transport silently clamped max_tokens to Math.max(1, ...), producing
single-token replies.

Add toolSchemaTokens as an optional parameter to
shouldPreemptivelyCompactBeforePrompt and estimateTranscriptBoundaryTokenPressure,
estimated from the effective tool definitions at the prompt phase call site.
Also emit a diagnostic warning when the transport's remaining output budget
drops below a useful floor.

Fixes openclaw#140770
@SunnyShu0925
SunnyShu0925 force-pushed the fix/context-precheck-tool-schemas-140770 branch from fdb74ae to 8cfca31 Compare September 7, 2026 06:26
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 7, 2026
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review.

@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 7, 2026
@roboclaw-bot roboclaw-bot added the clawtributor-review Clawtributor pull request awaiting prioritized maintainer review label Sep 8, 2026
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

Reviewed the context-budget change and repaired one false-overflow case: runtime AgentTool objects include output schemas and execution metadata that are not sent to the model. The estimator now shares the existing model-facing projection (name, description, parameters) and keeps provider-usage accounting unchanged.

Added regression coverage for metadata-invariant estimates and a fitting checkpoint prompt with a large output schema. Existing before/after provider proof remains relevant to including tool definitions; the new regression cases await hosted CI on f2a0b9a. Fresh P0–P2 autoreview and independent source review found no remaining blocker. No new local test execution is claimed.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Patrick-Erichsen

Patrick-Erichsen commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

CI on f2a0b9a ran the added metadata-exclusion and fitting-checkpoint regressions successfully. The embedded-run shard had 1,913 passing tests and one failing oversized-catalog fixture: excluding metadata made that catalog fit its old 130,000-token prompt allowance.

Commit 12280f2fea43 fixes only that fixture, using a 128,000-token context window and 20,000-token reserve, and explicitly requiring the tool estimate to exceed the resulting 108,000-token prompt budget. Production code is unchanged. Independent source review confirmed the fixture still catches missing tool accounting. Fresh final-head CI is required before landing.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Patrick-Erichsen
Patrick-Erichsen merged commit 02d4507 into openclaw:main Sep 11, 2026
210 checks passed
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 11, 2026
…penclaw#140902)

* fix(agents): include tool schema tokens in context-overflow precheck

The context-overflow precheck estimates prompt token pressure to decide
compaction routing, but it only counted transcript messages, system prompt,
and rendered prompt text — not the serialized tool definitions that the
transport layer sends alongside. On proxy-like OpenAI-compatible endpoints
with large MCP catalogs, this caused the precheck to report route=fits while
the transport silently clamped max_tokens to Math.max(1, ...), producing
single-token replies.

Add toolSchemaTokens as an optional parameter to
shouldPreemptivelyCompactBeforePrompt and estimateTranscriptBoundaryTokenPressure,
estimated from the effective tool definitions at the prompt phase call site.
Also emit a diagnostic warning when the transport's remaining output budget
drops below a useful floor.

Fixes openclaw#140770

* fix(agents): count only model-facing tool schema fields

* test(agents): keep tool catalog fixture above prompt budget

---------

Co-authored-by: Patrick Erichsen <[email protected]>
obviyus added a commit that referenced this pull request Sep 25, 2026
…ed (#157673)

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.

Co-authored-by: Ayaan Zaidi <[email protected]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawtributor-review Clawtributor pull request awaiting prioritized maintainer review P2 Normal backlog priority with limited blast radius. 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

Development

Successfully merging this pull request may close these issues.

[Bug]: context-overflow precheck ignores tool schemas, so max_tokens silently clamps to 1 and replies truncate

3 participants