Skip to content

fix(agents): reduce tool-result token over-count in mid-turn precheck - #101950

Closed
ZOOWH wants to merge 1 commit into
openclaw:mainfrom
ZOOWH:fix/101929-tool-result-token-estimate
Closed

ZOOWH wants to merge 1 commit into
openclaw:mainfrom
ZOOWH:fix/101929-tool-result-token-estimate

Conversation

@ZOOWH

@ZOOWH ZOOWH commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

context-overflow-midturn-precheck estimates prompt tokens ~2.3–2.6× above provider-billed usage on tool-result-heavy turns. This fires truncation recovery on turns nowhere near the context window.

Fixes #101929.

Root Cause / Fix

Root cause: TOOL_RESULT_CHARS_PER_TOKEN was 2 in both tool-result-char-estimator.ts and run/preemptive-compaction.ts. Tool results (JSON, code output) average ~4-5 chars/token in practice — not 2. The 2 chars/token estimate:

  • In the estimator: chars × 4/2 = 2× weighted chars, inflating context guard budget
  • In the precheck: chars / 2, doubling token pressure vs the actual chars / 4-5

Both paths contributed to the ~2.3-2.6× over-count.

Fix: Raise both constants from 2 to 3:

  • tool-result-char-estimator.ts:14: TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE = 3
  • run/preemptive-compaction.ts:27: TOOL_RESULT_CHARS_PER_TOKEN = 3

Evidence

Real behavior proof

$ node --import tsx -e '
import { estimateLlmBoundaryTokenPressure }
  from "./src/agents/embedded-agent-runner/run/preemptive-compaction.js";

// 30,000 chars of ASCII tool result
const text = "alpha beta gamma delta epsilon ".repeat(1000);
const tokens = estimateLlmBoundaryTokenPressure({
  messages: [{ role: "toolResult", content: text }],
  systemPrompt: "sys", prompt: "continue",
});
// Old: ~15,000 tokens (30,000/2). New: ~10,000 tokens (30,000/3).
console.log(JSON.stringify({ chars: text.length, estimatedTokens: tokens,
  oldEstimate: Math.ceil(text.length / 2),
  reduction: Math.round((1 - tokens / Math.ceil(text.length/2)) * 100) + "%" }));
'

{"chars":30000,"estimatedTokens":10000,"oldEstimate":15000,"reduction":"33%"}

Regression suite

$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/tool-result-char-estimator.test.ts \
    src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts \
    src/agents/embedded-agent-runner/tool-result-context-guard.test.ts

 Test Files  5 passed (5)
      Tests  143 passed (143)

Autoreview

autoreview --mode branch --engine claude --model claude-sonnet-5
overall: patch is correct (0.95)
autoreview clean: no accepted/actionable findings reported

oxfmt / oxlint

  • oxfmt --check — ✅
  • git diff --check — ✅

Change Type / Scope / Security Impact

  • Type: fix
  • Scope: src/agents/embedded-agent-runner/ — tool-result token estimator + preemptive compaction
  • Files: 2 source + 3 test (+6 source, +6 test)
  • Security: No security impact
  • Backward compatibility: Safe — reduces false truncation, does not increase it

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

This PR is superseded by the stronger open fix at #101952, which targets the same linked mid-turn precheck bug with the provider-boundary projection change and sufficient real behavior proof; this branch remains a narrower constant-only mitigation with insufficient proof for the reported route.

Root-cause cluster
Relationship: superseded
Canonical: #101952
Summary: This PR and two sibling PRs target the same canonical mid-turn precheck estimator issue; the proof-positive projection-layer PR is the viable canonical landing path, while this branch is a narrower constant-only overlap.

Members:

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

Canonical path: Use #101952, or an equivalent exact-head projection-layer fix, as the canonical landing path and then resolve the narrower alternatives against the landed behavior.

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

Review details

Best possible solution:

Use #101952, or an equivalent exact-head projection-layer fix, as the canonical landing path and then resolve the narrower alternatives against the landed behavior.

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

Yes, at source level: current main still runs mid-turn precheck on contextMessages while the provider submission path separately applies aggregate tool-result projection, and the linked issue includes concrete logs and billed-usage deltas. I did not rerun the live provider cron scenario.

Is this the best way to solve the issue?

No. This PR is a plausible mitigation for part of the over-count, but the best fix is the projection-layer approach in #101952 because it estimates the same prompt shape that the provider path sends.

Security review:

Security review cleared: The diff changes internal TypeScript estimator logic and focused tests only; it does not touch secrets, dependencies, workflows, package scripts, or supply-chain-sensitive surfaces.

AGENTS.md: found and applied where relevant.

What I checked:

  • Root policy read: Read the full root AGENTS.md and the scoped src/agents and embedded-runner run AGENTS.md files; the review applied the best-fix, session-state merge-risk, scoped-agent-test, and Codex dependency-inspection guidance. (AGENTS.md:1, fdc98242a1e5)
  • Current main still has the projection mismatch this branch does not fix: On origin/main, the mid-turn guard passes contextMessages directly into shouldPreemptivelyCompactBeforePrompt, while the provider prompt path later applies resolveLiveToolResultAggregateMaxChars and truncateOversizedToolResultsInMessages before model submission. (src/agents/embedded-agent-runner/tool-result-context-guard.ts:530, fdc98242a1e5)
  • This PR is still a constant-only mitigation: The current PR head changes TOOL_RESULT_CHARS_PER_TOKEN to 3 and TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE to 3, but it does not add the provider-boundary aggregate projection before the mid-turn precheck. (src/agents/embedded-agent-runner/run/preemptive-compaction.ts:30, 1a9eafe115fe)
  • Canonical replacement is open, proof-positive, and viable: Live GitHub data shows fix(agents): align mid-turn tool-result projection precheck #101952 is open, non-draft, mergeable, maintainer-modifiable, labeled proof: sufficient, and marked ready for maintainer look; its diff projects mid-turn messages through truncateOversizedToolResultsInMessages and uses the normal text ratio for tool-result strings. (src/agents/embedded-agent-runner/tool-result-context-guard.ts:326, 270c14865275)
  • Canonical issue describes both ratio and unprojected-transcript causes: The linked issue reports context-overflow-midturn-precheck estimates 2.29-2.56x above billed usage and explicitly calls out both the 2 chars/token ratio and estimating over the untruncated in-memory transcript while the outbound prompt is capped.
  • Codex dependency contract spot-check: The inspected Codex request builders serialize the supplied input/messages into Responses API and websocket payloads, supporting the review assumption that OpenClaw's provider-boundary prompt projection is the relevant input shape to estimate. (../codex/codex-rs/core/src/client.rs:829)

Likely related people:

  • steipete: Blame for the current preemptive-compaction constants, estimator branch, and mid-turn precheck call points to Peter Steinberger's recent agent runtime commit, and CONTRIBUTING.md maps Peter Steinberger to @steipete. (role: recent source contributor; confidence: high; commits: a6768d9de567, 8a43223014cb, 2d033d2aa842; 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/tool-result-char-estimator.ts)
  • jalehman: CONTRIBUTING.md lists Josh Lehman for Compaction and Context Engine, which are the owner surfaces for this mid-turn precheck/projection decision; related PR history also ties that area to recent context-boundary work. (role: adjacent context/compaction owner; confidence: medium; commits: a68caa185bf1; 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/tool-result-truncation.ts)
  • Tyler Yust: History for tool-result truncation includes an earlier context-overflow recovery commit by Tyler Yust, making him relevant to the broader recovery behavior even though the current estimator lines are newer. (role: earlier overflow-recovery contributor; confidence: medium; commits: 0deb8b0da187; files: src/agents/embedded-agent-runner/tool-result-truncation.ts, src/agents/embedded-agent-runner/tool-result-context-guard.ts)

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

@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
TOOL_RESULT_CHARS_PER_TOKEN was 2 in both tool-result-char-estimator.ts
and preemptive-compaction.ts. Tool results (JSON, code output) average
~4-5 chars/token in practice — not 2. The 2 chars/token estimate
produced a ~2-2.6× token over-count vs billed usage, triggering
mid-turn truncation on turns far below the real context window.

Change TOOL_RESULT_CHARS_PER_TOKEN(_ESTIMATE) from 2 to 3 in both
files. The estimator ratio drops from 4/2=2.0x to 4/3≈1.33x, and
the token pressure estimate changes from chars/2 to chars/3.

Fixes openclaw#101929
@ZOOWH
ZOOWH force-pushed the fix/101929-tool-result-token-estimate branch from ff333f4 to 1a9eafe Compare July 8, 2026 02:18
@ZOOWH

ZOOWH commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 8, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

1 participant