Skip to content

fix(agents): align TOOL_RESULT_CHARS_PER_TOKEN with ESTIMATED_CHARS_PER_TOKEN - #101997

Closed
SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/midturn-toolresult-ratio-101929
Closed

SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/midturn-toolresult-ratio-101929

Conversation

@SunnyShu0925

Copy link
Copy Markdown
Contributor

What Problem This Solves

context-overflow-midturn-precheck over-estimates tool-result token pressure by ~2x on Latin/ASCII-heavy tool outputs, triggering destructive truncate_tool_results_only recovery on turns well within the real context window.

  • Problem: TOOL_RESULT_CHARS_PER_TOKEN = 2 treats tool-result text as twice as token-dense as ordinary text, causing the estimator to fire at ~2.3-2.6x above provider-billed usage
  • Solution: Change TOOL_RESULT_CHARS_PER_TOKEN from 2 to 4, matching ESTIMATED_CHARS_PER_TOKEN used everywhere else in the estimator
  • What changed: src/agents/embedded-agent-runner/run/preemptive-compaction.ts (one constant), src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts (updated thresholds + regression test)
  • What did NOT change: 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 changes

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Motivation

Users with midTurnPrecheck.enabled: true on tool-result-heavy agent turns experience false-positive overflow detection. The precheck fires truncate_tool_results_only recovery 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 (estimateStringTokenPressure via estimateStringChars) is unaffected because CJK chars are already weighted at 4 chars/code-point, and the Math.max(conservativeToolResultEstimate, cjkAwareEstimate) structure ensures the CJK-aware estimate dominates when CJK content is present.

Evidence

  • Behavior addressed: context-overflow-midturn-precheck false-positive on tool-result-heavy turns
  • Real environment tested: Ubuntu Linux, Node 22.19, branch fix/midturn-toolresult-ratio-101929
  • Exact steps or command run after this patch:
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts --run
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/tool-result-context-guard.test.ts --run
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/tool-result-truncation.test.ts --run
npx oxfmt --check src/agents/embedded-agent-runner/run/preemptive-compaction.ts src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts
  • Evidence after fix:
$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts --run
 Test Files  1 passed (1)
      Tests  23 passed (23)

$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/tool-result-context-guard.test.ts --run
 Test Files  1 passed (1)
      Tests  45 passed (45)

$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/tool-result-truncation.test.ts --run
 Test Files  1 passed (1)
      Tests  57 passed (57)

$ npx oxfmt --check src/agents/embedded-agent-runner/run/preemptive-compaction.ts src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts
All matched files use the correct format.
  • Matrix of estimator behavior change:
Input Old TOOL_RESULT_CHARS_PER_TOKEN=2 New TOOL_RESULT_CHARS_PER_TOKEN=4
Latin text tool result (1000 chars) ~500 tokens ~250 tokens
CJK text tool result ~500 tokens per 1000 CJK chars ~500 tokens per 1000 CJK chars (unchanged)
JSON tool result payload ~93k tokens for 120-row payload ~46.5k tokens (correct density)
Reporter scenario (~250k chars, 200k ctx, 50k reserve) ~162k tokens → false overflow <150k tokens → fits
  • Observed result after fix:
    1. The new regression test (exact reporter scenario) passes: route=fits, overflowTokens=0
    2. The "regression-sized" synthetic test now correctly routes as "fits" instead of false overflow
    3. The "counts array/object tool-result payloads" test still verifies overflow is detected with a tight budget
    4. Non-CJK tool result text now uses the same density as normal text (= 4 chars/token)
    5. CJK tool result estimation is completely unchanged
    6. All 125 related tests pass with no regressions
  • What was not tested: Live end-to-end agent run with a real provider (GPT-5.5 / Claude) to confirm billed usage matches the new estimate — would require a running OpenClaw instance with valid credentials

Root Cause (if applicable)

TOOL_RESULT_CHARS_PER_TOKEN = 2 in estimateToolResultStringTokenPressure() at preemptive-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: true should 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)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Human Verification (required)

  • Verified scenarios: Token estimator unit tests (23/23), related agent runner suites (125/125), no regression in tool-result truncation or context guard paths
  • Edge cases checked: JSON tool-result payloads, CJK tool result content (unchanged), assistant tool-call arguments, circular reference handling, reserve token capping, message boundary overhead
  • What you did NOT verify: Live provider run with real token billing comparison; non-ASCII-encoded tool result edge cases

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Best-fix Verdict

  • Best fix: Yes — changing the constant from 2 to 4 is the minimal, correct fix. The value 4 matches ESTIMATED_CHARS_PER_TOKEN used everywhere else in the estimator. The SAFETY_MARGIN = 1.2 already 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.
  • Refactor needed: No — the char-based estimator in tool-result-char-estimator.ts is a separate code path (context guard, not the token estimator) and not part of the reported over-count.
  • Alternative considered: Raising to 3 (half-measure, no principled basis). Removing the conservative branch entirely (broader than needed — would change global compaction safety policy). Adding aggregate projection (only helps for >400k chars, not the reporter's scenario, and mixing concerns would repeat the maintainer feedback on fix(agents): align mid-turn tool-result projection precheck #101952).

AI Assistance

Risks and Mitigations

  • Highest risk area: The new 4 chars/token ratio could under-estimate for tool results with very efficient tokenization (e.g. purely numeric content or scripts with high token-compression ratios).
  • Mitigations: The SAFETY_MARGIN = 1.2 provides 20% buffer. The Math.max(conservativeToolResultEstimate, cjkAwareEstimate) structure preserves the CJK-aware path as a safety net. The ESTIMATED_CHARS_PER_TOKEN = 4 has been the system-wide default for all non-tool-result text without issues.
  • Compatibility impact: None — purely internal estimator constant change. No config keys, no API surface, no stored state format change.

…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
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jul 8, 2026
@clawsweeper

clawsweeper Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 7, 2026, 11:50 PM ET / 03:50 UTC.

Summary
The branch changes the embedded agent runner's tool-result token-density constant from 2 to 4 and updates focused preemptive-compaction tests for the new thresholds and reporter-shaped regression.

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.

  • Estimator density changed: 1 constant changed from 2 to 4 chars/token. This single value halves tool-result token pressure in a shared compaction estimator, so it matters beyond the added regression test.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #101929
Summary: This PR is a candidate fix for the canonical mid-turn precheck estimator overcount report, but it overlaps with other open fix attempts and leaves the estimator-policy decision unresolved.

Members:

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

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🧂 unranked krab
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Add redacted live agent/provider proof or tokenizer-backed evidence for the new 4 chars/token tool-result policy.
  • [P1] Add token-dense plain-text and JSON negative controls showing genuinely over-budget prompts still route to recovery.
  • [P1] Resolve the overlap with fix(agents): align mid-turn tool-result projection precheck #101952 and the linked bug before merge.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body reports unit, related-suite, and formatter output, but no after-fix live OpenClaw/provider run or redacted runtime logs showing the changed behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] Changing the constant to 4 halves tool-result pressure in the shared estimator, so genuinely token-dense tool-heavy prompts may skip precheck compaction and fail later at provider submission.
  • [P1] The PR body provides unit and format output only; it does not show an after-fix OpenClaw/provider run, tokenizer comparison, or redacted live logs for the changed behavior.
  • [P1] There are overlapping open PRs for the same linked bug, and the strongest overlapping PR has maintainer feedback requiring the estimator-policy choice to be split or proven before merge.

Maintainer options:

  1. Prove or preserve estimator safety (recommended)
    Keep the conservative ratio unless the PR adds provider/tokenizer evidence, token-dense negative controls, and an accepted maintainer rationale for relaxing the shared estimator.
  2. Accept lower precheck pressure
    Maintainers may deliberately accept the risk that some tool-heavy sessions reach provider overflow later instead of precheck recovery.
  3. Pause for canonical fix selection
    If the projection-layer approach is preferred, pause or close this constant-only branch and resolve the linked issue through the canonical PR.

Next step before merge

  • [P1] The remaining blocker is a maintainer safety-policy decision plus contributor real behavior proof, not a narrow repair that ClawSweeper should apply automatically.

Maintainer decision needed

  • Question: Should OpenClaw relax the shared tool-result token estimator from 2 to 4 chars/token, or should this bug be fixed by aligning the mid-turn precheck with the provider-boundary projection while preserving the conservative estimator?
  • Rationale: The diff is small, but it changes a shared compaction safety policy used outside the reported mid-turn path, and maintainer feedback on the overlapping PR explicitly asks for proof before accepting that relaxation.
  • Likely owner: vincentkoc — This account already left the item-specific maintainer review comment identifying the estimator-policy choice and required proof.
  • Options:
    • Preserve safety until proven (recommended): Keep the 2 chars/token estimator for now and land a projection-aligned fix, or require provider/tokenizer evidence and token-dense negative controls before changing the global ratio.
    • Accept the ratio relaxation: Maintainers can intentionally accept the lower estimator pressure if they are satisfied the live/provider evidence covers token-dense tool-result cases.
    • Choose a canonical PR first: Pause or close the overlapping constant-only branches once a maintainer selects the projection PR or a narrower replacement as the canonical landing path.

Security
Cleared: The diff only changes internal TypeScript estimator logic and tests; it does not touch secrets, dependencies, workflows, package metadata, downloads, or other supply-chain surfaces.

Review findings

  • [P1] Keep the estimator conservative until proven safe — src/agents/embedded-agent-runner/run/preemptive-compaction.ts:27
Review details

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

  • [P1] Keep the estimator conservative until proven safe — src/agents/embedded-agent-runner/run/preemptive-compaction.ts:27
    Changing TOOL_RESULT_CHARS_PER_TOKEN here halves tool-result pressure in the shared estimateLlmBoundaryTokenPressure path, which is used by the normal pre-prompt precheck as well as the mid-turn guard. The linked failure is real, but the added regression stays below the current aggregate cap and does not prove token-dense tool/JSON cases, so genuinely over-budget tool-heavy prompts can now skip precheck recovery and fail later at provider submission. Please either preserve the conservative ratio and fix the projection mismatch, or add provider/tokenizer evidence plus negative controls before relaxing this global safety policy.
    Confidence: 0.87

Overall correctness: patch is incorrect
Overall confidence: 0.87

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add P1: The PR targets a P1 agent runtime bug where false mid-turn recovery can rewrite useful transcript state and waste long-running tool-heavy turns.
  • add merge-risk: 🚨 session-state: The diff changes compaction routing pressure for tool-result-heavy transcripts and can alter when session context is compacted, truncated, or preserved.
  • add merge-risk: 🚨 availability: If the relaxed estimator undercounts token-dense tool output, over-budget prompts may bypass precheck recovery and fail at provider submission.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body reports unit, related-suite, and formatter output, but no after-fix live OpenClaw/provider run or redacted runtime logs showing the changed behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Label justifications:

  • P1: The PR targets a P1 agent runtime bug where false mid-turn recovery can rewrite useful transcript state and waste long-running tool-heavy turns.
  • merge-risk: 🚨 session-state: The diff changes compaction routing pressure for tool-result-heavy transcripts and can alter when session context is compacted, truncated, or preserved.
  • merge-risk: 🚨 availability: If the relaxed estimator undercounts token-dense tool output, over-budget prompts may bypass precheck recovery and fail at provider submission.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body reports unit, related-suite, and formatter output, but no after-fix live OpenClaw/provider run or redacted runtime logs showing the changed behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source 0, Tests +29. Total +29 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 1 1 0
Tests 1 39 10 +29
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 40 11 +29

What I checked:

Likely related people:

  • fuller-stack-dev: Git history and PR 85541 tie this account to the tool-heavy preflight estimator that introduced TOOL_RESULT_CHARS_PER_TOKEN = 2. (role: introduced estimator behavior; confidence: high; commits: c08400ea7d5d; files: src/agents/embedded-agent-runner/run/preemptive-compaction.ts, src/agents/pi-embedded-runner/run/preemptive-compaction.ts)
  • joshavant: PR 85541 was merged by this account and the commit message credits related co-authorship for the estimator path. (role: merger and co-author of estimator work; confidence: medium; commits: c08400ea7d5d; files: src/agents/embedded-agent-runner/run/preemptive-compaction.ts)
  • marchpure: PR 73499 added the opt-in mid-turn compaction precheck path that now surfaces this estimator during tool loops. (role: introduced mid-turn guard path; confidence: high; commits: b85147ff7615; files: src/agents/embedded-agent-runner/tool-result-context-guard.ts, src/agents/embedded-agent-runner/run/attempt.ts)
  • Takhoffman: History shows adjacent work refining cause-aware precheck overflow routing in the same agent compaction surface. (role: adjacent overflow-routing contributor; confidence: medium; commits: 66daafccae09; files: src/agents/embedded-agent-runner/run/preemptive-compaction.ts)
  • steipete: History traces the sibling tool-result character estimator split and conservative ratio to this account, making the estimator policy relevant to the same behavior family. (role: adjacent estimator contributor; confidence: medium; commits: 2d033d2aa842; files: src/agents/embedded-agent-runner/tool-result-char-estimator.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 8, 2026
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

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 proof: sufficient + ready for maintainer look rating. Contributors should track #101952 for the merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant