Skip to content

fix(cache): stable tool result aggregate truncation - #93186

Closed
L-Trump wants to merge 2 commits into
openclaw:mainfrom
L-Trump:fix/stable-tool-result-aggregate-truncation
Closed

L-Trump wants to merge 2 commits into
openclaw:mainfrom
L-Trump:fix/stable-tool-result-aggregate-truncation

Conversation

@L-Trump

@L-Trump L-Trump commented Jun 15, 2026 •

Copy link
Copy Markdown

Summary

  • Reduces prompt-cache churn during long tool-heavy agent runs by making live tool-result prompt projection less eager to rewrite old prefix content.
  • Changes live aggregate tool-result reduction from exact byte shaving to coarse 20% budget quanta, creating a stateless hysteresis band while preserving the existing oldest-first truncation strategy.
  • Keeps persisted/session recovery paths on exact shaving so durable transcript rewrites still minimize data loss and on-disk diffs.
  • Replaces non-deterministic Date.now() timestamps on synthetic missing tool-result placeholders with deterministic numeric timestamps derived from the source assistant/tool-use message, with 0 as the fallback when no source timestamp exists.
  • Preserves the ToolResultMessage.timestamp: number contract for runtime and persisted synthetic repair messages.
  • Intended outcome: repeated tool-loop requests should preserve provider prompt-cache prefixes more often, especially when total tool-result text hovers near the aggregate cap.
  • Out of scope: redesigning transcript repair ordering, changing provider payload schemas, disabling synthetic missing tool results, or adding persistent per-message projection caches.
  • Reviewers should focus on whether the 20% live-projection quantum is the right minimal cache-stability tradeoff, and whether deriving synthetic repair timestamps from source turns is the right contract-preserving stabilization layer.

Linked context

Which issue does this close?

Closes #

Which issues, PRs, or discussions are related?

Related #15409
Related #58036

Was this requested by a maintainer or owner?

No maintainer request. This was prompted by live OpenClaw cache-trace investigation showing repeated prefix-cache invalidation during tool-heavy sessions.

Real behavior proof

Behavior or issue addressed:

  • During long active tool loops, live prompt assembly could repeatedly rewrite older tool-result projections as new tool results were appended near the aggregate cap.
  • That changed serialized prompt prefixes between adjacent model calls and reduced provider prompt-cache reuse.
  • Synthetic missing tool-result repair also used timestamp: Date.now(), creating non-deterministic transcript bytes when placeholders were regenerated.
  • Current PR head verified: b2278f63ee87805e60b188e8407a3bcb23c05017.

Real environment tested:

  • Local OpenClaw gateway on NixOS, OpenClaw 2026.6.5, after rebuild/switch and gateway restart.

  • Running process inspected from /proc:

    /nix/store/jb0rvygwwcvhc98v637rlfj17bnch7ln-openclaw-gateway-2026.6.5/lib/openclaw/dist/index.js gateway --port 18789
    
  • Cache tracing source: /home/ltrump/.openclaw/logs/cache-trace.jsonl.

  • Controlled proof session: agent:main:tui-fa8b100b-b024-40d1-a589-6fd489022a47.

  • Main controlled proof run: 17d7842f-dbd7-4a20-86bc-24454f17485b.

  • The local Nix-packaged gateway dist was inspected and matched the current PR head behavior before collecting traces.

Exact steps or command run after this patch:

  1. Rebuilt/switched the local OpenClaw gateway and restarted it.

  2. Verified the running process path with ps and /proc/<pid>/exe.

  3. Inspected the running dist chunks with rg:

    rg -n "AGGREGATE_REDUCTION_QUANTUM_RATIO|aggregateReductionQuantumRatio|aggregateReductionQuantumChars" \
      /nix/store/jb0rvygwwcvhc98v637rlfj17bnch7ln-openclaw-gateway-2026.6.5/lib/openclaw/dist/tool-result-truncation-*.js
    
    rg -n "readFiniteTimestamp|timestamp: readFiniteTimestamp|sourceTimestamp" \
      /nix/store/jb0rvygwwcvhc98v637rlfj17bnch7ln-openclaw-gateway-2026.6.5/lib/openclaw/dist/session-transcript-repair-*.js \
      /nix/store/jb0rvygwwcvhc98v637rlfj17bnch7ln-openclaw-gateway-2026.6.5/lib/openclaw/dist/compaction-successor-transcript-*.js
  4. Ran a controlled cache-trace workload in a fresh TUI session:

    • generated /home/ltrump/.openclaw/workspace/tmp/cache-proof-large.txt, about 4.74 MB;
    • performed 14 sequential read tool calls on different offsets, each limit=2000;
    • forced one LLM turn between tool calls so each appended result created a new prompt assembly;
    • then performed 6 sequential small exec tool calls.
  5. Parsed /home/ltrump/.openclaw/logs/cache-trace.jsonl for stream:context transitions, aggregate tool-result size, common-prefix preservation, synthetic missing tool-result timestamps, and provider cacheRead values.

Evidence after fix:

  • Running dist verification showed live/estimate quantum opt-in and deterministic synthetic timestamps:

    tool-result-truncation-CSLN3t54.js:
      const AGGREGATE_REDUCTION_QUANTUM_RATIO = 0.2;
      aggregateReductionQuantumRatio: AGGREGATE_REDUCTION_QUANTUM_RATIO   # 2 occurrences
      aggregateReductionQuantumRatio: params.aggregateReductionQuantumRatio # 1 occurrence
      const aggregateReductionQuantumChars = params.aggregateReductionQuantumRatio !== void 0 ? ... : 1;
    
    session-transcript-repair-B17NYGhL.js:
      function readFiniteTimestamp(value)
      timestamp: readFiniteTimestamp(params.sourceTimestamp) ?? 0
      sourceTimestamp: readFiniteTimestamp(msg.timestamp)
      no timestamp: Date.now() hit in this chunk
    
    compaction-successor-transcript-DOYIvTa2.js:
      const parentEntryTimestamp = typeof params.parent.timestamp === "string" ? Date.parse(params.parent.timestamp) : void 0;
      const parentMessageTimestamp = readFiniteTimestamp(params.parent.message?.timestamp) ?? readFiniteTimestamp(parentEntryTimestamp);
      sourceTimestamp: parentMessageTimestamp
      sourceTimestamp: entry.timestamp
      const assistantTimestamp = readFiniteTimestamp(finalMessage.timestamp);
    
  • Which paths use the 20% aggregate quantum:

    • truncateOversizedToolResultsInMessages() uses aggregateReductionQuantumRatio: AGGREGATE_REDUCTION_QUANTUM_RATIO because it is the live prompt-projection path. It does not rewrite the session file, and it is the path that directly affects provider prompt-cache prefix stability during tool loops.
    • estimateToolResultReductionPotential() also uses the same ratio so pressure/possible-reduction estimates match the live projection behavior that will actually run.
  • Which paths intentionally do not use the quantum:

    • truncateOversizedToolResultsInExistingSessionManager() / session-manager recovery paths leave aggregateReductionQuantumRatio undefined.
    • truncateOversizedToolResultsInSession() persisted session-file recovery paths leave aggregateReductionQuantumRatio undefined.
    • With the ratio undefined, buildAggregateToolResultReplacements() uses a 1-char quantum, i.e. exact shaving.
    • Reason: persisted recovery mutates durable session/transcript state, so it should make the minimum necessary reduction to recover from pressure/overflow. The cache-stability hysteresis band is only needed for transient live prompt projections and their matching estimates.
  • Redacted runtime log excerpt from cache-trace.jsonl, controlled aggregate trace from run 17d7842f-dbd7-4a20-86bc-24454f17485b:

    seq 13  toolTotal 258,954
    seq 14  toolTotal 310,700
    seq 15  toolTotal 362,446
    seq 16  toolTotal 414,192
    seq 17  toolTotal 465,938
    seq 18  toolTotal 414,634  <-- aggregate quantum reduction after appending another ~51.7k read result
    seq 19  toolTotal 466,380
    seq 20  toolTotal 415,076  <-- aggregate quantum reduction again
    seq 21  toolTotal 466,822
    seq 22  toolTotal 415,518  <-- aggregate quantum reduction again
    

    With toolResultMaxChars = 128000, the aggregate budget is approximately 128000 * 4 = 512000 chars. At seq 17 -> seq 18, exact overflow would have been only a few thousand chars:

    465,938 + ~51,746 ~= 517,684
    517,684 - 512,000 ~= 5,684
    

    Instead, aggregate tool-result text dropped to 414,634, implying a reduction of about 103k chars:

    517,684 - 414,634 ~= 103,050
    

    That matches the configured 20% live projection quantum:

    512,000 * 0.2 = 102,400
    

    This confirms the running gateway used chunked aggregate reduction rather than exact byte shaving for live prompt projection.

  • Prefix stability after the read-heavy phase:

    seq 23 -> seq 24: common prefix 31/31, lost 0
    seq 24 -> seq 25: common prefix 33/33, lost 0
    seq 25 -> seq 26: common prefix 35/35, lost 0
    seq 26 -> seq 27: common prefix 37/37, lost 0
    seq 27 -> seq 28: common prefix 39/39, lost 0
    

    These are the 6 small exec appends after the aggregate quantum reductions. They preserved the full previous prefix, which is the intended hysteresis behavior.

  • Redacted runtime log excerpt, provider cache-read evidence from the same controlled session:

    session: agent:main:tui-fa8b100b-b024-40d1-a589-6fd489022a47
    runId: 17d7842f-dbd7-4a20-86bc-24454f17485b
    cacheRead: 1,641,621
    note: stable cache inputs
    
  • Redacted runtime log excerpt, deterministic synthetic timestamp trace over the current-head trace window:

    synthetic missing toolResults observed: 185
    unique synthetic toolCallIds: 13
    unstable timestamp groups: 0
    fallback 0 cases: 63
    
  • Overall cache-trace summary for the current-head proof window:

    records: 225
    stream:context: 104
    cache:result: 14
    cache hits: 12
    hit rate: 85.7%
    max cacheRead: 2,820,096
    controlled proof run cacheRead: 1,641,621
    

Observed result after fix:

  • Live prompt projection used 20% aggregate quantum reductions when the controlled read-heavy workload crossed the aggregate cap.
  • The reduction size was about 103k, matching a ~512k * 20% quantum, instead of exact overflow shaving of only a few thousand chars.
  • After the quantum reductions, subsequent small tool-result appends preserved the full previous prefix across all checked transitions.
  • Synthetic missing tool-result placeholders kept stable numeric timestamps: no synthetic toolCallId had multiple observed timestamp values across the trace window.
  • The controlled run produced provider cache reuse with cacheRead=1,641,621 and note: stable cache inputs.

What was not tested:

  • Full provider billing/cache behavior across every supported provider.
  • A long statistical A/B comparison against an unpatched gateway under identical workload.
  • Maintainer-hosted production deployment. The runtime proof is from a local NixOS gateway whose running dist was inspected and matched the current PR head behavior.

Proof limitations or environment constraints:

  • Live logs were summarized/redacted to avoid exposing private session content.
  • Cache-trace fingerprints are diagnostic and can differ from provider-projected payloads; therefore the proof combines runtime dist inspection, controlled workload deltas, and provider cacheRead fields.

Before evidence:

  • Before the aggregate reduction change, sessions with total tool-result text near the aggregate cap showed repeated old tool-result rewrites as new tool results were appended.

  • Example observed pattern: old tool-result projections at stable message indices changed lengths between adjacent prompt assemblies, breaking the common prefix far before the newly appended messages.

  • Before the timestamp change, makeMissingToolResult() emitted:

    timestamp: Date.now(),

Tests and validation

Which commands did you run?

node scripts/run-vitest.mjs src/agents/session-transcript-repair.test.ts src/agents/session-tool-result-guard.test.ts src/agents/session-file-repair.test.ts src/agents/embedded-agent-runner/run/attempt.test.ts src/agents/embedded-agent-runner/tool-result-truncation.test.ts
pnpm lint --threads=8
pnpm tsgo:prod
pnpm tsgo:core:test

Result:

Focused Vitest: 274 tests passed
pnpm lint --threads=8: 0 warnings, 0 errors
pnpm tsgo:prod: passed
pnpm tsgo:core:test: passed after rebasing onto origin/main, which includes d012d29e6f test(protocol): narrow literal union schemas

Additional source/runtime checks:

grep -n "AGGREGATE_REDUCTION_QUANTUM_RATIO\|aggregateReductionQuantum" <running-dist>/tool-result-truncation-*.js
grep -n "timestamp: Date.now()" src/agents/session-transcript-repair.ts src/agents/session-tool-result-guard.ts || true
python analyze /home/ltrump/.openclaw/logs/cache-trace.jsonl

What regression coverage was added or updated?

  • Added unit coverage for live aggregate tool-result truncation using coarse chunk reduction.
  • Added unit coverage that persisted/session recovery paths use exact aggregate shaving instead of the live prompt quantum.
  • Added/updated transcript repair coverage showing synthetic missing tool results inherit a stable source timestamp.
  • Kept embedded-agent expectations aligned with the ToolResultMessage.timestamp: number contract.

What failed before this fix, if known?

  • The previous aggregate truncation behavior reduced exactly totalChars - aggregateBudgetChars in all paths.
  • That meant small appended tool results could repeatedly force older live prompt tool-result projections to be rewritten by small amounts across adjacent prompt assemblies.
  • Synthetic missing tool-result repair also added Date.now(), making regenerated placeholders non-deterministic.

If no test was added, why not?

  • Tests were added/updated for both the aggregate reduction behavior and the deterministic timestamp propagation behavior.

Risk checklist

Did user-visible behavior change? (Yes/No)

No.

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

No.

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

No.

What is the highest-risk area?

  • Live prompt tool-result projection: chunked aggregate reductions may truncate more text than the exact overflow amount when the aggregate cap is exceeded.
  • Synthetic transcript repair: synthetic missing tool results now use source/fallback deterministic timestamps instead of wall-clock insertion time.

How is that risk mitigated?

  • The aggregate quantum only applies after aggregate tool-result text already exceeds the configured aggregate budget.
  • The quantum is bounded by the aggregate budget (20%) and preserves the existing oldest-first truncation strategy.
  • Persisted/session recovery paths intentionally keep exact shaving to minimize durable data loss.
  • The synthetic repair marker remains available through details.openclawSyntheticMissingToolResult, and message ordering/content fields are unchanged.
  • Synthetic tool results continue to include a numeric timestamp, preserving the shared message contract.
  • Existing tool-result truncation and transcript repair tests pass, with additional coverage for the new behavior.

Current review state

What is the next action?

Maintainer review and CI on the force-pushed current head.

What is still waiting on author, maintainer, CI, or external proof?

  • CI on current PR head b2278f63ee87805e60b188e8407a3bcb23c05017.
  • Maintainer judgment on whether 20% is the right default live prompt-projection quantum ratio.
  • Maintainer judgment on the deterministic source/fallback timestamp approach for synthetic missing tool results.

Which bot or reviewer comments were addressed?

  • ClawSweeper proof concern: addressed with exact current-head hash, running dist inspection, controlled runtime trace, provider cacheRead evidence, and explicit path split for quantum vs exact shaving.
  • ClawSweeper P1 timestamp contract concern: addressed by preserving numeric timestamps and deriving them deterministically from source assistant/tool-use turns, with fallback 0 instead of Date.now().
  • ClawSweeper P2 path concern: addressed by limiting the 20% aggregate quantum to live prompt projection and matching estimates, while keeping persisted recovery paths on exact shaving.
  • ClawSweeper P2 lint concern in the aggregate truncation test: addressed by removing unnecessary non-null assertions.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS proof: supplied External PR includes structured after-fix real behavior proof. labels Jun 15, 2026
@clawsweeper

clawsweeper Bot commented Jun 15, 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 should close because the cache-stability problem it targets is now covered by the merged maintainer implementation in #95624 on current main. The remaining timestamp idea is separable session-repair semantics, not a reason to keep this older conflicting cache branch open.

Canonical path: Keep the merged #95624 implementation; if deterministic synthetic timestamps are still desired, review them as a narrow standalone session-repair PR.

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

Review details

Best possible solution:

Keep the merged #95624 implementation; if deterministic synthetic timestamps are still desired, review them as a narrow standalone session-repair PR.

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

Yes. The original bug was source-reproducible through exact older-first aggregate prompt projection; current main now has a replacement implementation and regression coverage proving stable historical projections.

Is this the best way to solve the issue?

No. This PR is no longer the best fix because #95624 landed a more complete maintainer-owned per-attempt projection design, while the timestamp change should be split if still wanted.

Security review:

Security review cleared: No concrete security or supply-chain concern is visible; the diff touches agent prompt/session logic and tests only.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • vincentkoc: Authored the merged current-main projection-state implementation in fix(agents): keep long-context tool-result prompts cache-stable #95624 and owns the most recent central commits on the touched prompt-truncation path. (role: canonical fix author and recent area contributor; confidence: high; commits: 30925601aef7, ef6dc8f7e5b1, 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: Authored the merged aggregate prompt tool-result bounding work in Bound aggregate persisted tool results #87639, which is the adjacent behavior this cache-stability cluster builds on. (role: introduced adjacent aggregate-boundary behavior; confidence: high; commits: 4f54861333fb, f49a3e4c266c; files: src/agents/embedded-agent-runner/tool-result-truncation.ts, src/agents/embedded-agent-runner/run/attempt.ts)
  • steipete: Merged Bound aggregate persisted tool results #87639 and appears as a co-author on its aggregate prompt-boundary commit, making this a useful routing signal for the original behavior. (role: adjacent merger and co-author; confidence: medium; commits: 4f54861333fb, f49a3e4c266c; 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 a1828110704f; fix evidence: commit 3053cbc8a5d7, main fix timestamp 2026-06-22T09:48:14+08:00.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jun 15, 2026
@L-Trump
L-Trump force-pushed the fix/stable-tool-result-aggregate-truncation branch from 612b80a to 59456f4 Compare June 15, 2026 07:45
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 15, 2026
@L-Trump
L-Trump force-pushed the fix/stable-tool-result-aggregate-truncation branch 2 times, most recently from 59456f4 to 7c730ba Compare June 15, 2026 08:39
@openclaw-barnacle openclaw-barnacle Bot added triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. and removed proof: supplied External PR includes structured after-fix real behavior proof. labels Jun 15, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jun 15, 2026
@L-Trump

L-Trump commented Jun 15, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

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

Re-review progress:

@L-Trump

L-Trump commented Jun 15, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

@L-Trump
L-Trump force-pushed the fix/stable-tool-result-aggregate-truncation branch from 7c730ba to 2b80905 Compare June 15, 2026 13:51
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Jun 15, 2026
@L-Trump
L-Trump force-pushed the fix/stable-tool-result-aggregate-truncation branch from 2b80905 to b2278f6 Compare June 15, 2026 16:02
@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 15, 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 rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 15, 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. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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 20, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Jun 22, 2026
@clawsweeper

clawsweeper Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

  • Action: closed this PR.
  • Close reason: duplicate or superseded.
  • Evidence: durable ClawSweeper review.
  • Coverage proof: PR B clearly covers PR A's central useful cache-stability behavior and is the merged canonical place for that work. PR A's deterministic timestamp change is separable session-repair semantics that the source report itself says should be reviewed only as a narrow standalone PR if desired, not kept open through this obsolete cache branch. Covering PR: fix(agents): keep long-context tool-result prompts cache-stable #95624.

@clawsweeper clawsweeper Bot closed this Jun 22, 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: 🚨 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. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant