Skip to content

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

Closed
mikasa0818 wants to merge 5 commits into
openclaw:mainfrom
mikasa0818:feat/issue-95219
Closed

mikasa0818 wants to merge 5 commits into
openclaw:mainfrom
mikasa0818:feat/issue-95219

Conversation

@mikasa0818

@mikasa0818 mikasa0818 commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #95219.

This stabilizes live prompt-history tool-result projection by rounding aggregate live truncation overflow up to a coarse quantum and taking selected older entries to a stable floor instead of progressively shaving the same old result on every prompt build. Persisted session/transcript recovery and its estimator keep exact aggregate shaving.

What Problem This Solves

Long channel sessions can accumulate large historical tool outputs. The live prompt aggregate truncation pass previously rebuilt model-facing content from the current message set and spent the exact aggregate overflow on older tool results first. When a later turn appended more tail tool output, the same historical tool result could be truncated to a different target and appear with different bytes in adjacent model requests, cutting the prompt-cache prefix at that old message.

Real behavior proof

  • Behavior or issue addressed: Historical tool-result projections should stay byte-stable across adjacent prompt builds when only newer tail tool output is appended.
  • Real environment tested: Local OpenClaw source checkout on Windows Git Bash with Node available; focused function-level prompt projection boundary exercised through the repo Vitest wrapper.
  • Exact steps or command run after this patch: node scripts/run-vitest.mjs src/agents/embedded-agent-runner/tool-result-truncation.test.ts
  • Evidence after fix: Focused Vitest completed with exit status 0. A direct production-function proof using node --import tsx also completed with exit status 0 and invoked truncateOversizedToolResultsInMessages() plus estimateToolResultReductionPotential() from the built source tree.
  • Observed result after fix: The direct proof reported oldestProjectionStable: true, first/second oldest projection lengths both 69, and exact persisted recovery estimate aggregateReducibleChars: 3000. The focused tests also confirm durable recovery still honors the exact aggregate cap.
  • What was not tested: I did not capture live provider prompt-cache metrics. SonarLint/Sonar scanner was not run because sonarlint, sonar-scanner, and sonarjs were not available in this environment.
  • Fix classification: Root cause fix
  • Why it matters / User impact: Stable old prompt bytes preserve more prompt-cache prefix reuse in long sessions with large tool histories, without changing stored transcripts or provider APIs.

Evidence

  • node scripts/run-vitest.mjs src/agents/embedded-agent-runner/tool-result-truncation.test.ts — exit status 0.
  • node --import tsx <inline production prompt-projection proof> — exit status 0; observed oldestProjectionStable: true, firstOldestLength: 69, secondOldestLength: 69, and recoveryEstimateAggregateReducibleChars: 3000.
  • Commit formatting hook completed on the two touched files.
  • SonarLint/Sonar scanner availability check found no sonarlint, sonar-scanner, or sonarjs executable in this environment.

Review findings addressed

  • RF-001 / RF-004 / RF-008: fixed by removing live quantum rounding from estimateToolResultReductionPotential(), keeping persisted recovery estimates exact, and adding a regression that reports aggregateReducibleChars: 3000 for a 15k -> 12k exact recovery case.
  • RF-002 / RF-003 / RF-005 / RF-007: added a direct production-function proof using node --import tsx that invokes the prompt projection owner and records the stable-prefix result. A live provider prompt-cache trace remains unavailable in this Windows environment and is disclosed under What was not tested.
  • RF-006: disclosed the retained-context tradeoff under Merge risk; selected older live prompt entries can go to the stable truncation floor to protect prompt-cache prefix stability.

Regression Test Plan

  • Target test file: src/agents/embedded-agent-runner/tool-result-truncation.test.ts
  • Scenario locked in: Regression test constructs one prompt history with three medium tool results, then constructs the adjacent prompt history with the same prefix plus one new tail tool result. The oldest historical tool-result projection must remain byte-identical across both prompt builds.
  • Why this is the smallest reliable guardrail: The colocated Vitest targets the owner function that builds model-facing prompt messages, avoiding a slow full embedded-runner test while still proving the prompt projection invariant. A second persisted-session test guards against accidentally applying the live quantum to durable transcript recovery.

Root Cause

  • Root cause: Root source invariant failure: buildAggregateToolResultReplacements used exact aggregate overflow (totalChars - aggregateBudgetChars) for live prompt projection and spent that exact amount on older tool results first. Because the newer tail grew between turns, the same old result received a different exact target and could be re-projected into different model-facing bytes.
  • Why this is root-cause fix: The source-of-truth boundary for this issue is the live prompt projection plan in tool-result-truncation.ts. Rounding live aggregate overflow up to a 20% aggregate-budget quantum and taking each selected old result to the stable floor creates deterministic headroom on the first aggregate rewrite, so adjacent turns with newer tail output do not shave the same oldest result again. The persisted recovery estimate deliberately stays exact, matching persisted session/transcript recovery.

Merge risk

  • Risk labels considered: session-state / prompt-cache behavior.
  • Risk explanation: The live prompt view may reduce selected older aggregate results to the stable truncation floor rather than only shaving the exact current overflow. This affects only model-facing request-local projection; the original session messages are not rewritten by the live path, and persisted recovery estimates remain exact.
  • Why acceptable: The change is internal to prompt projection, keeps the existing older-first/fresh-output preference, adds no config/schema/protocol/migration surface, and includes regression tests for both adjacent-turn stability and persisted exact recovery.
  • Patch quality notes: Final diff is limited to tool-result-truncation.ts and its colocated test. No fallback path, no lint suppression, no .only, no @ts-ignore, no lockfile, and no unrelated file changes.
  • Maintainer-ready confidence: 86/100.

Scope boundary

  • What did NOT change: This PR does not change provider routing, prompt-cache API metadata, transcript storage format, migrations, public config, semantic compaction, persisted recovery estimates, or unrelated files; only live prompt-history aggregate truncation policy changed.
  • Architecture / source-of-truth check: The canonical source-of-truth owner is src/agents/embedded-agent-runner/tool-result-truncation.ts; callers continue invoking the same truncation APIs, and persisted session state recovery keeps exact aggregate shaving.
  • Related open PR scan: fix(cache): stable tool result aggregate truncation #93186 is an earlier open/conflicting candidate with the same narrow live-projection direction; fix(tool-result-truncation): skip historical tool results in aggregate reduction to preserve prompt cache stability #95264 is a parallel candidate that skips already-marked historical truncations. This PR applies the current-main-safe quantum fix only and does not depend on either branch.

@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 solves the PR's central bug with the merged per-attempt tool-result projection implementation from #95624, so this separate live-quantum branch is no longer needed as a merge candidate.

Root-cause cluster
Relationship: superseded
Canonical: #95624
Summary: The current PR and the merged maintainer PR target the same historical tool-result prompt-cache instability; the merged PR is now the canonical current-main implementation.

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 per-attempt projection-state implementation from #95624 and close this superseded branch; reopen only with evidence that current main still rewrites historical tool-result bytes.

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

No current-main failing reproduction remains from source inspection: current main keeps a request-local projection state and has a growing-history regression test that asserts the old projected prefix stays byte-stable. I did not run tests in this read-only review.

Is this the best way to solve the issue?

No, this PR is no longer the best landing path because current main already solved the bug through the merged per-attempt projection-state implementation. The safer path is to keep that implementation rather than add this alternate live-quantum policy.

Security review:

Security review cleared: No concrete security or supply-chain concern is visible; the PR touches agent prompt-projection logic and a colocated test only.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • vincentkoc: Authored the merged per-attempt prompt projection fix series in fix(agents): keep long-context tool-result prompts cache-stable #95624 and merged it into main. (role: current-main fix author and merger; confidence: high; commits: 30925601aef7, bda4404f695a, 708c1b31e097; files: src/agents/embedded-agent-runner/tool-result-truncation.ts, src/agents/embedded-agent-runner/tool-result-truncation.test.ts, src/agents/embedded-agent-runner/run/attempt.ts)
  • ooiuuii: Authored the merged aggregate prompt tool-result bounding work in Bound aggregate persisted tool results #87639, which introduced the adjacent aggregate truncation path refined by the current-main fix. (role: introduced adjacent behavior; confidence: high; commits: 4f54861333fb, f49a3e4c266c; 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)
  • steipete: Merged the adjacent aggregate prompt tool-result bounding PR that made this prompt-projection behavior visible for later refinement. (role: adjacent merger; confidence: medium; commits: f49a3e4c266c; files: src/agents/embedded-agent-runner/tool-result-truncation.ts, src/agents/embedded-agent-runner/run/attempt.ts)
  • Josh Lehman: Current local blame shows recent transcript-target refactors carrying the same tool-result truncation lines forward after the merged fix. (role: recent area carrier; confidence: medium; commits: 132d70bfb3c9, 475252453b4b; files: src/agents/embedded-agent-runner/tool-result-truncation.ts)

Codex review notes: model internal, reasoning high; reviewed against 89b2db77d4d5; fix evidence: commit 708c1b31e097, main fix timestamp 2026-06-22T01:17:50Z.

@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
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. labels Jun 20, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jun 21, 2026
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 24, 2026
@clawsweeper

clawsweeper Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this Jun 24, 2026
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. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

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