Repository navigation
fix(agents): align TOOL_RESULT_CHARS_PER_TOKEN with ESTIMATED_CHARS_PER_TOKEN - #101997
SunnyShu0925 wants to merge 1 commit into
Conversation
…ARS_PER_TOKEN Change TOOL_RESULT_CHARS_PER_TOKEN from 2 to 4 so that tool-result text is estimated at the same chars-per-token ratio as ordinary text. The old value of 2 caused the mid-turn precheck to over-estimate tool-result token pressure by ~2x, triggering destructive truncate_tool_results_only recovery on turns well within the real context window. Updated affected test thresholds to match the corrected estimates and added a regression test for the reporter's scenario: ~250k chars of tool-result text across ~20 calls on a 200k context window with 50k reserve tokens should no longer false-positive overflow. Co-Authored-By: Claude <[email protected]> Related to openclaw#101929
|
Codex review: needs real behavior proof before merge. Reviewed July 7, 2026, 11:50 PM ET / 03:50 UTC. Summary PR surface: Source 0, Tests +29. Total +29 across 2 files. Reproducibility: yes. at source level: current main has the reported 2 chars/token tool-result estimator and the linked issue provides concrete logs and billed-usage deltas. I did not rerun the live provider cron scenario during this read-only review. Review metrics: 1 noteworthy metric.
Root-cause cluster Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Proof guidance:
Risk before merge
Maintainer options:
Next step before merge
Maintainer decision needed
Security Review findings
Review detailsBest possible solution: Keep the conservative global estimator unless maintainers accept a documented density policy change, and fix the linked bug through a prompt-projection-aligned path or with live provider/tokenizer proof plus token-dense negative controls. Do we have a high-confidence way to reproduce the issue? Yes at source level: current main has the reported 2 chars/token tool-result estimator and the linked issue provides concrete logs and billed-usage deltas. I did not rerun the live provider cron scenario during this read-only review. Is this the best way to solve the issue? No: this constant-only change is a plausible mitigation, but it relaxes a shared safety policy without the proof a maintainer requested on the overlapping PR. The safer path is projection alignment or explicit evidence-backed acceptance of the new density policy. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against bf310355387d. Label changesLabel changes:
Label justifications:
Evidence reviewedPR surface: Source 0, Tests +29. Total +29 across 2 files. View PR surface stats
What I checked:
Likely related people:
What the crustacean ranks mean
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. How this review workflow works
|
|
Closing this PR as #101952 is the canonical fix for the same root cause — it aligns the mid-turn precheck with the provider-boundary projection rather than relaxing the global tool-result density estimator, has real behavior proof, and carries a ClawSweeper |
What Problem This Solves
context-overflow-midturn-precheckover-estimates tool-result token pressure by ~2x on Latin/ASCII-heavy tool outputs, triggering destructivetruncate_tool_results_onlyrecovery on turns well within the real context window.TOOL_RESULT_CHARS_PER_TOKEN = 2treats tool-result text as twice as token-dense as ordinary text, causing the estimator to fire at ~2.3-2.6x above provider-billed usageTOOL_RESULT_CHARS_PER_TOKENfrom 2 to 4, matchingESTIMATED_CHARS_PER_TOKENused everywhere else in the estimatorsrc/agents/embedded-agent-runner/run/preemptive-compaction.ts(one constant),src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts(updated thresholds + regression test)SAFETY_MARGIN(still 1.2x),ESTIMATED_CHARS_PER_TOKEN(unchanged at 4),JSON_PAYLOAD_CHARS_PER_TOKEN(unchanged at 3), CJK estimation path (unchanged), tool-result-char-estimator.ts (separate code path, not part of the reported over-count), no import additions or structural changesChange Type (select all)
Scope (select all)
Linked Issue/PR
Motivation
Users with
midTurnPrecheck.enabled: trueon tool-result-heavy agent turns experience false-positive overflow detection. The precheck firestruncate_tool_results_onlyrecovery that rewrites all prior tool results into tiny stubs, causing the model to re-fetch data it already obtained. This wastes tokens (~3x in the reporter's case), increases latency, and exposes long-running turns to transient provider errors.The root cause is
TOOL_RESULT_CHARS_PER_TOKEN = 2, which was set conservatively when the mid-turn precheck was first introduced. Real tokenizers (GPT, Claude) encode English tool-result text at approximately the same 4 chars/token rate as ordinary text.The separate CJK estimation path (
estimateStringTokenPressureviaestimateStringChars) is unaffected because CJK chars are already weighted at 4 chars/code-point, and theMath.max(conservativeToolResultEstimate, cjkAwareEstimate)structure ensures the CJK-aware estimate dominates when CJK content is present.Evidence
Root Cause (if applicable)
TOOL_RESULT_CHARS_PER_TOKEN = 2inestimateToolResultStringTokenPressure()atpreemptive-compaction.ts:115-118. Introduced by commit c08400e (Jason, 2026-05-22) carrying forward the conservative ratio from the earlier char estimator. Made visible by the mid-turn precheck path (b85147f, marchpure) that surfaces the conservative ratio as a false-positive routing signal.The estimator also counts over the untruncated in-memory transcript, but for the reporter's 200k context window scenario the aggregate tool-result cap is 400k chars — well above the ~250k chars of tool results — so aggregate projection does not help here. The ratio is the sole fix for this bug.
User-visible / Behavior Changes
Users running tool-heavy agent sessions with
midTurnPrecheck.enabled: trueshould see fewer unnecessary mid-turn context-overflow aborts and compaction retries. Runs that are genuinely over the effective prompt budget still raise the mid-turn precheck signal.Security Impact (required)
Human Verification (required)
Review Conversations
Compatibility / Migration
Best-fix Verdict
ESTIMATED_CHARS_PER_TOKENused everywhere else in the estimator. TheSAFETY_MARGIN = 1.2already provides 20% headroom for tokenizer variance. The separate CJK path is unaffected. Aggregate projection alignment (for tool-result payloads >400k chars on a 200k context window) is a potential follow-up enhancement.tool-result-char-estimator.tsis a separate code path (context guard, not the token estimator) and not part of the reported over-count.AI Assistance
TOOL_RESULT_CHARS_PER_TOKEN = 2provenance, evaluated three competing PR approaches, designed focused one-constant fix with regression testRisks and Mitigations
SAFETY_MARGIN = 1.2provides 20% buffer. TheMath.max(conservativeToolResultEstimate, cjkAwareEstimate)structure preserves the CJK-aware path as a safety net. TheESTIMATED_CHARS_PER_TOKEN = 4has been the system-wide default for all non-tool-result text without issues.