Skip to content

[AI] fix(agents): align TOOL_RESULT_CHARS_PER_TOKEN with ESTIMATED_CH… - #101951

Closed
ghost wants to merge 1 commit into
mainfrom
unknown repository
Closed

ghost wants to merge 1 commit into
mainfrom
unknown repository

Conversation

@ghost

@ghost ghost commented Jul 8, 2026

Copy link
Copy Markdown

Summary

The mid-turn precheck token estimator over-counted tool-result text by ~2× because TOOL_RESULT_CHARS_PER_TOKEN=2 treated tool results as twice as token-dense as ordinary text. Aligning it with ESTIMATED_CHARS_PER_TOKEN=4 eliminates the systematic over-estimate while retaining the 1.2× safety margin.

  • Problem: TOOL_RESULT_CHARS_PER_TOKEN=2 in estimateToolResultContentTokenPressure() causes context-overflow-midturn-precheck to fire at ~2.3-2.6× above real provider-billed usage, triggering destructive truncate_tool_results_only recovery on turns well within the context window
  • Solution: Change TOOL_RESULT_CHARS_PER_TOKEN from 2 to 4, matching ESTIMATED_CHARS_PER_TOKEN used everywhere else
  • 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.2×), ESTIMATED_CHARS_PER_TOKEN (unchanged at 4), TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE in tool-result-char-estimator.ts (separate char-estimation path, not the token estimator), aggregate truncation projection in the estimator (kept scope minimal)

Change Type & Scope

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope

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

Linked Issue

Motivation

Users with midTurnPrecheck.enabled: true on tool-result-heavy agent turns (e.g. work-queue digest agents) 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 (~3× in the reporter's case), increases latency, and exposes long-running turns to transient provider errors — all while the turn is well within the real context window.

The root cause is the conservative TOOL_RESULT_CHARS_PER_TOKEN=2 which was set 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, making the 2 value a systematic 2× over-count.

Review Contract

Ref: #101929 / PR #TBD
Surface: agents / compaction / mid-turn precheck estimator

Bug: TOOL_RESULT_CHARS_PER_TOKEN=2 causes context-overflow-midturn-precheck to over-estimate tool-result token pressure by ~2× vs provider-billed usage
Cause: estimateToolResultContentTokenPressure() at preemptive-compaction.ts:108-122 divides tool-result chars by 2 instead of 4, and the mid-turn precheck at tool-result-context-guard.ts:530 calls shouldPreemptivelyCompactBeforePrompt over the untruncated in-memory transcript before the provider-boundary aggregate truncation
Provenance:
  introduced by: 2d033d2aa84 (Peter Steinberger, 2026-03-03) — TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE=2 in char estimator
  carried forward by: c08400ea7d5 (Jason, 2026-05-22) — TOOL_RESULT_CHARS_PER_TOKEN=2 in token estimator
  made visible by: b85147ff7615 (marchpure) — mid-turn precheck path that surfaces the conservative ratio
  Confidence: clear

Best fix: Yes — aligning TOOL_RESULT_CHARS_PER_TOKEN with ESTIMATED_CHARS_PER_TOKEN is the minimal, correct fix. The SAFETY_MARGIN=1.2 already provides headroom for tokenizer variance. A more comprehensive fix (applying provider-boundary aggregate truncation projection) would add import-cycle risk without proportional benefit for the common case.
Refactor: No — the char-based estimator in tool-result-char-estimator.ts is a separate code path (context guard, not token estimator) and not part of the reported over-count
Proof: 17 unit tests pass including new regression test; related suites pass (attempt.llm-boundary: 23, tool-result-truncation: 38, tool-result-context-guard: 45, overflow-compaction-loop: 26)
Risk: Changing the constant from 2→4 could theoretically under-estimate for highly tokenization-efficient tool results (e.g. pure numeric JSON or non-English scripts). The SAFETY_MARGIN=1.2 and the fact that normal text has always used 4 chars/token mitigate this. The separate char-estimator path (tool-result-char-estimator.ts) keeps its own TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE=2 for the context guard, which is unchanged.

Real Behavior Proof

Behavior addressed: On a tool-result-heavy turn with ~250k chars of tool result text across ~20 calls, a 200k context window, and 50k reserve tokens, the old estimator produced estimatedPromptTokens ≈ 162k (>150k prompt budget), triggering false overflow. The corrected estimator produces an estimate comfortably below 150k.

Real environment tested: Ubuntu Linux, Node 22.19, branch fix/midturn-precheck-estimator-101929, local checkout

Exact steps or command run after this patch:

# Run the preemptive-compaction unit tests (16 original + 1 new regression)
$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts --run

# Verify related suites are unaffected
$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts --run
$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/tool-result-truncation.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/run.overflow-compaction.loop.test.ts --run

Evidence after fix:

$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts --run
 RUN  v4.1.8 /home/0668000999/OpenClaw
 Test Files  1 passed (1)
      Tests  17 passed (17)

$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts --run
 Test Files  1 passed (1)
      Tests  23 passed (23)

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

$ 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/run.overflow-compaction.loop.test.ts --run
 Test Files  1 passed (1)
      Tests  26 passed (26)

Observed result after fix:

  • The new regression test passes: ~250k chars of tool results + 200k context + 50k reserve → route=fits, shouldCompact=false, overflowTokens=0, estimatedPromptTokens < 150_000
  • All 16 existing tests continue to pass with adjusted thresholds
  • No regressions across 149 related tests (attempt.llm-boundary, tool-result-truncation, tool-result-context-guard, overflow-compaction-loop)

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
  • CJK-heavy tool result text with the new ratio (the CJK-aware estimateStringChars handles encoding differences, but the chars-per-token ratio is encoding-agnostic)

Verification Environment

  • OS: Ubuntu Linux (server)
  • Runtime: Node 22.19
  • Model/provider: N/A (unit test only)
  • Integration/channel: N/A

Risks and Mitigations

  • highest risk area: The new 4 chars/token ratio could under-estimate for tool results with very efficient tokenization (e.g. repetitive JSON arrays, pure numeric content, or scripts with high token-compression ratios). The SAFETY_MARGIN=1.2 provides some headroom, and the fact that ESTIMATED_CHARS_PER_TOKEN=4 has been the system-wide default for all non-tool-result text without issues suggests this risk is low.
  • Relief methods: The SAFETY_MARGIN multiplier (1.2) is applied after estimation, providing a 20% buffer. The aggregate truncation projection at the provider boundary provides an additional implicit safety net — even if the estimate is slightly low, the real outbound prompt is smaller than the in-memory transcript.
  • Compatibility impact: None — this is a purely internal estimator constant change. No config keys, no API surface, no stored state format change.

Security Impact

  • 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

Compatibility / Migration

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

Human Verification

  • Verified scenarios: Token estimator unit tests (17/17), related agent runner tests (149/149), no regression in tool-result truncation, context guard, overflow compaction, or LLM boundary paths
  • Edge cases checked: Mixed oversized + aggregate tool tails, array/object tool-result payloads, JSON tool results, assistant tool-call argument counting, reserve token capping for small context models
  • What you did NOT verify: Live provider run with real token billing comparison; CJK-heavy tool result edge case with the new ratio

AI Assistance 🤖

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.

Related to #101929

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

clawsweeper Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close: this branch is a partial and currently dirty/conflicting landing candidate for the linked mid-turn precheck bug, and it is superseded by #101952, which changes the guard to estimate the provider-boundary projected tool-result view and includes live runtime proof.

Root-cause cluster
Relationship: superseded
Canonical: #101952
Summary: This PR and the sibling PRs target the same mid-turn precheck estimator bug, but the canonical landing path is the open replacement PR with projection-layer changes and live proof.

Members:

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

Canonical path: Close this branch and keep review focused on #101952; if maintainers want any narrow regression-test idea from this branch, fold it into that canonical PR.

So I’m closing this here and keeping the remaining discussion on #101952.

Review details

Best possible solution:

Close this branch and keep review focused on #101952; if maintainers want any narrow regression-test idea from this branch, fold it into that canonical PR.

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

Yes, at source level: current main still has the mid-turn guard estimating contextMessages before the provider-boundary aggregate tool-result projection, and the linked issue supplies concrete logs and billed-usage comparisons. I did not rerun the live provider cron scenario in this read-only review.

Is this the best way to solve the issue?

No. This branch is a plausible partial fix to one ratio, but #101952 is the better landing path because it estimates the same projected prompt view the provider path sends and includes live runtime proof.

Security review:

Security review cleared: Security review cleared: the diff changes only TypeScript estimator/test code and does not touch dependencies, secrets, workflows, package metadata, downloads, or other supply-chain surfaces.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • Takhoffman: History shows repeated work on precheck routing, aggregate tool-result fallback, and context limits in the same feature family. (role: adjacent overflow-routing contributor; confidence: high; commits: 66daafccae09, a8fb094c5b76, 4f00b769251d; files: src/agents/pi-embedded-runner/run/preemptive-compaction.ts, src/agents/pi-embedded-runner/tool-result-truncation.ts)
  • steipete: History ties this account to the tool-result char estimator split and later tool-result overflow recovery hardening. (role: adjacent estimator and recovery contributor; confidence: medium; commits: 2d033d2aa842, a42ee69ad4a7; files: src/agents/pi-embedded-runner/tool-result-char-estimator.ts, src/agents/pi-embedded-runner/tool-result-context-guard.ts, src/agents/pi-embedded-runner/tool-result-truncation.ts)
  • keshav55: The early preemptive context overflow detection during tool loops appears in the feature-family history for this guard path. (role: early mid-turn guard contributor; confidence: medium; commits: 3aa4199ef098; files: src/agents/pi-embedded-runner/tool-result-context-guard.ts)
  • jalehman: History shows context-engine prompt cache stabilization and reviewed/co-authored early guard work adjacent to this runtime path. (role: context-engine adjacent contributor; confidence: medium; commits: a327b6750dbe, 3aa4199ef098; files: src/agents/pi-embedded-runner/tool-result-context-guard.ts, src/agents/embedded-agent-runner/tool-result-context-guard.ts)
  • zw-xysk: Current-file blame for the visible estimator and guard lines points to a broad current-main carrier commit, but the commit title is unrelated to the original behavior. (role: recent area carrier; confidence: low; commits: e5c224754c18; files: src/agents/embedded-agent-runner/run/preemptive-compaction.ts, src/agents/embedded-agent-runner/tool-result-context-guard.ts, src/agents/embedded-agent-runner/run/attempt.ts)

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

@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. labels Jul 8, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 8, 2026
@ghost ghost closed this Jul 8, 2026
@ghost
ghost deleted the fix/midturn-precheck-estimator-101929 branch July 8, 2026 05:36
This pull request was closed.
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: 🚨 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XS 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.

0 participants