Skip to content

fix(tool-result-truncation): skip historical tool results in aggregate reduction to preserve prompt cache stability - #95264

Closed
mmyzwl wants to merge 5 commits into
openclaw:mainfrom
mmyzwl:fix/issue-95219-historical-tool-results-re-truncated-between-turns-cache-stability
Closed

mmyzwl wants to merge 5 commits into
openclaw:mainfrom
mmyzwl:fix/issue-95219-historical-tool-results-re-truncated-between-turns-cache-stability

Conversation

@mmyzwl

@mmyzwl mmyzwl commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Summary

When the same tool result message is processed across multiple turns, the aggregate reduction logic in buildAggregateToolResultReplacements() can progressively re-truncate older entries to make room for new tool output. This changes the byte representation of historical tool results between adjacent model requests, breaking prompt cache prefix stability.

Fixes #95219

Real behavior proof (required for external PRs)

Behavior addressed: Historical tool results are re-truncated between turns, causing the same message to appear differently across model requests (e.g., head-preserving → head+tail → pure placeholder).

Real setup tested:

  • Runtime: Node v24.13.1, Linux 4.19.112

Exact steps or command run after fix:

pnpm vitest run src/agents/embedded-agent-runner/tool-result-truncation.test.ts

After-fix evidence:

 ✓ Tests  35 passed (35)

 Test Files  1 passed (1)

Observed result after the fix: All 35 tests pass, including 2 new cross-turn stability tests that verify already-truncated messages are not re-truncated.

What was not tested: Full integration test with live LLM session (requires model access). The fix is verified at the unit-test level with realistic truncation marker patterns.

Tests and validation

Test Type Result Details
Unit Tests ✅ 35/35 passed

New tests

  1. does not re-truncate tool results that already contain a truncation marker — verifies messages with [... N more characters truncated; ...] suffix are skipped by aggregate reduction
  2. handles middle-omission markers in already-truncated tool results — verifies messages with ⚠️ [... middle content omitted …] pattern are also skipped

Risk checklist

Did user-visible behavior change? (No)

Did config, environment, or migration behavior change? (No)

Did security, auth, secrets, network, or tool execution behavior change? (No)

What is the highest-risk area?

  • Aggregate tool-result truncation — the fix skips already-truncated messages from the aggregate budget, which means the total prompt size may be marginally larger if many historical messages have been truncated in prior turns.

How is that risk mitigated?

  • The filter only applies to messages whose original text (before the current oversized truncation step) already had a truncation marker. Messages truncated fresh in the current turn are still eligible for aggregate reduction.
  • Unit tests verify both the stability guarantee and the within-turn budget compliance.

Current review state

What is the next action?

  • Maintainer review

…e reduction to preserve prompt cache stability

When the same tool result message is processed across multiple turns,
the aggregate reduction logic in buildAggregateToolResultReplacements()
can progressively re-truncate older entries to make room for new tool
output. This changes the byte representation of historical tool results
between adjacent model requests, breaking prompt cache prefix stability.

The fix adds a truncation-marker detection for text content blocks and
skips messages that already had a truncation marker before the oversized
truncation step. This ensures that once a historical tool result has been
projected into model-facing form, it stays stable across turns.

Detection regex: /\[\.\.\. \d+ .*(chars|characters) truncated;/
This matches both the DEFAULT_SUFFIX and COMPACT_RECOVERY_SUFFIX patterns
as well as the MIDDLE_OMISSION_MARKER.

Fixes openclaw#95219

Co-Authored-By: Claude <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jun 20, 2026
@clawsweeper

clawsweeper Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I did a careful shell check against current main, and this is already implemented.

Current main already contains a broader maintainer implementation for the same prompt-cache stability problem, so this branch is obsolete even though the idea was pointed at a real bug.

Root-cause cluster
Relationship: superseded
Canonical: #95624
Summary: A merged maintainer PR is now the canonical implementation for the same historical tool-result prompt-cache stability problem, so this PR is superseded.

Members:

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

So I’m closing this as already implemented rather than keeping a duplicate issue open.

Review details

Best possible solution:

Keep the current main projection-state implementation from the merged maintainer PR and close overlapping contributor branches for this same fix path.

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

Yes, at source level: the linked issue's failing shape is the live prompt projection path, and current main now has regression coverage for byte-stable projections as history grows. I did not run tests because this was a read-only review.

Is this the best way to solve the issue?

Yes for current main, not this branch: the merged projection-state implementation is the better fix because it reuses per-attempt projected bytes by tool-result identity instead of relying on marker detection in message text.

Security review:

Security review cleared: No concrete security or supply-chain concern was found; the PR diff touches agent prompt truncation code and a colocated test only.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • vincentkoc: Current-main blame and the merged canonical PR tie Vincent Koc to the projection-state implementation that supersedes this branch. (role: recent area contributor; confidence: high; commits: 3288291a0869, 3053cbc8a5d7, 708c1b31e097; files: src/agents/embedded-agent-runner/tool-result-truncation.ts, src/agents/embedded-agent-runner/run/attempt.ts, src/agents/embedded-agent-runner/tool-result-truncation.test.ts)
  • ooiuuii: Merged PR metadata and commit history show this author on the earlier aggregate tool-result bounding work that the prompt-cache stability bug built on. (role: introduced adjacent behavior; confidence: high; commits: f49a3e4c266c, 4f54861333fb; files: src/agents/embedded-agent-runner/tool-result-truncation.ts, src/agents/embedded-agent-runner/run/attempt.ts)
  • steipete: Live PR metadata for Bound aggregate persisted tool results #87639 shows steipete merged the aggregate tool-result bounding change in this area. (role: merger of adjacent behavior; confidence: medium; commits: f49a3e4c266c, 4f54861333fb; files: src/agents/embedded-agent-runner/tool-result-truncation.ts, src/agents/embedded-agent-runner/run/attempt.ts)

Codex review notes: model internal, reasoning high; reviewed against de60f4276793; fix evidence: commit 3288291a0869, main fix timestamp 2026-06-22T21:03:58+08:00.

@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. P2 Normal backlog priority with limited blast radius. 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 Jun 20, 2026
mmyzwl and others added 2 commits June 23, 2026 00:04
…nst aggregate budget

Already-truncated tool results must remain byte-stable for prompt cache
prefix stability, but their text length must still count against the
aggregate reduction budget. Previously they were filtered from candidates
before totalChars was computed, causing the system to underestimate
prompt pressure when many historical truncated messages exist.

- Partition candidates into skippedTruncated (historical, not re-truncatable)
  and eligible (fresh, truncatable) instead of filtering out historical ones
- totalChars includes both partitions so the budget is correctly sized
- Reduction is only applied to eligible entries, preserving historical stability

Addresses review finding:
- P1: Count skipped history against the aggregate budget

Part of openclaw#95219
@mmyzwl
mmyzwl force-pushed the fix/issue-95219-historical-tool-results-re-truncated-between-turns-cache-stability branch from 00522ce to 20cb986 Compare June 22, 2026 16:09
@mmyzwl

mmyzwl commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated aggregate accounting: already-truncated historical tool results remain byte-stable but their text length still counts toward the aggregate budget via a partition (skippedTruncated vs eligible). totalChars now includes both partitions, while reduction is only applied to eligible entries.

@clawsweeper

clawsweeper Bot commented Jun 22, 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.

mmyzwl added 2 commits June 23, 2026 00:40
- Rename truncatedCount to _truncatedCount (unused variable lint)
- Replace !!originalEntry?.message with != null check (implicit coercion lint)

Part of openclaw#95219
When already-truncated messages count against the aggregate budget,
totalChars is at or near the budget cap rather than exceeding it by
~79 chars (the stable message text). Update test expectations.

Part of openclaw#95219
@clawsweeper clawsweeper Bot removed 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 Jun 22, 2026
@clawsweeper

clawsweeper Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

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

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. 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.

[Bug]: Historical tool results are re-truncated between turns, breaking prompt cache prefix stability

1 participant