Repository navigation
fix(agents): include tool schema tokens in context-overflow precheck - #140902
Patrick-Erichsen merged 3 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 10, 2026, 8:32 PM ET / September 11, 2026, 00:32 UTC (Revision 11). ClawSweeper reviewWhat this changesCount 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 Review scores
Verification
How this fits togetherThe 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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +41, Tests +133. Total +174 across 7 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest 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. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (10 earlier review cycles; latest 8 shown)
|
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
fdb74ae to
8cfca31
Compare
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Reviewed the context-budget change and repaired one false-overflow case: runtime 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 |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
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 @clawsweeper re-review |
|
🦞👀 |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Merged via squash.
|
…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]>
…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]>
…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]>
Fixes #140770
What Problem This Solves
When an agent has a large MCP tool catalog, the context-overflow precheck reports
route=fitswhile the transport silently clampsmax_tokensto 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.
toolSchemaTokens(estimated from the installed model-facing tool surface) throughshouldPreemptivelyCompactBeforePromptso the precheck'sestimatedPromptTokensincludes tool definitions. When a provider usage boundary is available, itstotalTokensalready includes the tool schemas from that request, sotoolSchemaTokensis not added again to avoid double-counting.name,description, andparametersfromactiveSession.agent.state.toolsusing the existing shared estimator. Client tools appended byattempt-client-tools.tsare counted. Runtime-only fields such asoutputSchema, labels, and execution metadata are excluded, preventing false overflow.MIN_USEFUL_OUTPUT_TOKENS(16),log.warnemitsinsufficient_output_budgetat a normally visible level, not hidden behind model-debug environment settings.Math.max(1, ...)retained as safety floor), other callers ofshouldPreemptivelyCompactBeforePrompt(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_budgetwarning 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
f2a0b9ade8aaadds 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 --localwith 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:The precheck (
[context-overflow-precheck]) reportsroute=compact_onlywithestimatedPromptTokens=49801— tool schema pressure from the installed tool surface flows throughattempt-prompt-phase.ts→prepareEmbeddedAttemptPromptPreflight→shouldPreemptivelyCompactBeforePrompt. The transport ([completions] insufficient_output_budget) emits atlog.warnlevel — visible under normal logging — showingoutput=1(clamped) andestimatedInput=41612.Provider boundary double-count prevention (production
shouldPreemptivelyCompactBeforePromptwith simulated 79-tool catalog):Vitest regression tests (33 passed, including 3 tool-schema tests):
Transport layer tests (47 passed, no regressions):
AI Assistance
This PR is AI-assisted. Used Codex CLI to analyze issue #140770, trace the root cause through
preemptive-compaction.tsandopenai-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 thaneffectiveTools, and (3) emit the insufficient-output-budget warning atlog.warnlevel for normal visibility. Evidence includes a realopenclaw agent --localsession showing tool-pressure diagnostics through the full prompt-phase-to-preflight-to-transport path. All evidence above is from real local runtime execution.