Skip to content

fix: stabilize Anthropic cache marker through tool loops - #89488

Merged
obviyus merged 5 commits into
openclaw:mainfrom
Marvinthebored:fix-anthropic-cache-tool-tail
Jun 4, 2026
Merged

obviyus merged 5 commits into
openclaw:mainfrom
Marvinthebored:fix-anthropic-cache-tool-tail

Conversation

@Marvinthebored

@Marvinthebored Marvinthebored commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Stabilizes Anthropic conversation cache marker placement during tool loops.
  • Prefers the latest real user text/image block over trailing user-role tool_result carriers.
  • Keeps the previous fallback behavior for degenerate histories that contain only tool results.
  • Applies the same rule to the shared Anthropic payload policy and the native Anthropic message conversion path.

Fixes part of #86063.

Why

In tool-heavy sessions, OpenClaw currently attaches the conversation cache marker to the newest user-role tool_result. That marker moves on every tool call, so the historical prefix changes even when the actual conversation content is stable. This causes repeated large cache writes instead of cache reads.

A live current-version evidence comment with sanitized payload/cost data is here:
#86063 (comment)

Real behavior proof

  • Behavior or issue addressed: Anthropic conversation-history cache control no longer moves from stable user text onto each trailing synthetic tool_result during tool loops.
  • Real environment tested: MarvinMBP, macOS Sequoia 15.7.3, local OpenClaw 2026.6.1-beta.1 (13dd4e3), installed OpenClaw dist hotpatched from this PR, gateway restarted and running locally against a real Anthropic-compatible/Pioneer session payload captured from the affected setup.
  • Exact steps or command run after this patch: Applied the patch to the installed OpenClaw dist, restarted/checked the gateway with openclaw gateway status, syntax-checked the patched provider bundles with node --check, then replayed the captured 102-message real provider payload through the installed patched Anthropic cache policy to compare marker placement before and after the fix.
  • Evidence after fix: Terminal transcript from the local patched setup:
$ openclaw gateway status
Runtime: running pid 38894
Connectivity probe: ok
Version: 2026.6.1-beta.1 (13dd4e3)
Gateway: listening on 127.0.0.1:18789

$ node --check /usr/local/lib/node_modules/openclaw/dist/anthropic-payload-policy-D0z5Wqp1.js
$ node --check /usr/local/lib/node_modules/openclaw/dist/anthropic-CeIct-Vo.js

$ node replay-installed-anthropic-cache-policy.mjs
sample: 2026-06-02T09:30:05.130Z provider=pioneer model=claude-opus-4-8 messages=102
before patch marker locations:
  system[0]
  tool[33]
  msg[101] user block[0] tool_result
after patched installed policy:
  system[0]
  tool[33]
  msg[63] user block[0] text
  • Observed result after fix: The conversation cache marker stays on the latest real user text block instead of following the newest tool-result carrier, so a tool loop no longer invalidates the stable conversation prefix on every tool call. Existing tool-definition and system cache markers remain unchanged.
  • What was not tested: I did not force a fresh paid live provider call solely for this proof because the sanitized captured payload already came from the affected real setup and reproduces the marker movement deterministically. The broad local pnpm tsgo:test:src command hung with no output after several minutes and was stopped.

Tests

node scripts/run-vitest.mjs run --config test/vitest/vitest.agents.config.ts -- src/agents/anthropic-payload-policy.test.ts

Test Files  1 passed (1)
Tests       10 passed (10)

Also run:

git diff --check

pnpm tsgo:test:src was attempted locally but hung with no output after several minutes and was stopped, so I am not claiming that check passed.

AI assistance

This PR was prepared with AI assistance on a human-operated OpenClaw instance, using sanitized payload-location/counter evidence only. No user message contents, account identifiers, API keys, or private session transcript text are included.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 2, 2026
@clawsweeper

clawsweeper Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 4, 2026, 5:55 AM ET / 09:55 UTC.

Summary
The PR changes shared and native Anthropic payload shaping so conversation cache markers prefer the latest real user text/image block through trailing tool-result loops, with fallback tool-result marking and marker-budget tests.

PR surface: Source +120, Tests +158. Total +278 across 3 files.

Reproducibility: yes. from source inspection: current main marks the last user/tool_result block in both shared and native Anthropic paths, so trailing tool results move the conversation-history breakpoint during tool loops. I did not execute a live provider repro in this read-only review, but the linked issue and PR body include captured real-payload evidence.

Review metrics: 1 noteworthy metric.

  • Anthropic message cache markers: 0-2 message markers within 4 total breakpoints. The PR's compatibility-sensitive behavior is the new bounded marker layout, not just the three changed files.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P2] Add a native src/llm/providers/anthropic.test.ts payload-capture regression if maintainers want test proof for the streamAnthropic path before accepting the risk.

Risk before merge

  • [P1] The PR changes the default Anthropic-family request payload shape for existing users: when marker budget allows, requests can now carry both an older stable user text/image marker and a trailing tool_result marker instead of only the trailing user block.
  • [P1] Anthropic-compatible providers may not all match Anthropic's current cache_control tolerance, so green unit tests do not fully settle third-party provider compatibility.

Maintainer options:

  1. Accept the bounded payload-shape change (recommended)
    Merge after maintainers accept that existing Anthropic-compatible requests may include an additional stable conversation cache marker while remaining within the documented four-breakpoint budget.
  2. Add native provider coverage first
    Require a focused src/llm/providers/anthropic.test.ts case that captures streamAnthropic's final marker placement for stable text plus trailing tool_result before landing.
  3. Pause for custom-provider validation
    Pause if maintainers want explicit validation against Anthropic-compatible providers that may lag Anthropic's cache_control support on message or tool-result blocks.

Next step before merge

  • [P2] Keep this in the maintainer review lane because the code repair is concrete, but accepting the new default Anthropic-compatible payload shape is a human merge decision.

Security
Cleared: The diff changes TypeScript provider payload shaping and tests only; it does not alter dependencies, workflows, secrets handling, packaging, or supply-chain execution surfaces.

Review details

Best possible solution:

The end state should be one shared/native Anthropic payload policy that keeps conversation cache markers stable through tool-result loops while staying within Anthropic's four-breakpoint contract.

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

Yes from source inspection: current main marks the last user/tool_result block in both shared and native Anthropic paths, so trailing tool results move the conversation-history breakpoint during tool loops. I did not execute a live provider repro in this read-only review, but the linked issue and PR body include captured real-payload evidence.

Is this the best way to solve the issue?

Yes, this is an acceptable best current fix: it changes the existing Anthropic payload-shaping owners, preserves tool-result fallback behavior, and bounds message markers by the Anthropic breakpoint limit. The remaining question is maintainers accepting the compatibility impact, not a concrete patch defect.

AGENTS.md: found and applied where relevant.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 474d6e520aaf.

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies terminal proof from an installed patched OpenClaw dist replaying a captured real Anthropic-compatible payload and showing the marker move from trailing tool_result to stable user text.

Label justifications:

  • P2: This is a normal-priority provider prompt-cache bugfix with meaningful cost/performance impact but limited blast radius to Anthropic-family payload shaping.
  • merge-risk: 🚨 compatibility: The diff changes the default cache_control marker layout sent to Anthropic-compatible providers for existing users, which green CI alone cannot fully validate.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body supplies terminal proof from an installed patched OpenClaw dist replaying a captured real Anthropic-compatible payload and showing the marker move from trailing tool_result to stable user text.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies terminal proof from an installed patched OpenClaw dist replaying a captured real Anthropic-compatible payload and showing the marker move from trailing tool_result to stable user text.
Evidence reviewed

PR surface:

Source +120, Tests +158. Total +278 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 198 78 +120
Tests 1 159 1 +158
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 357 79 +278

What I checked:

  • Repository policy read and applied: Root AGENTS.md and scoped src/agents/AGENTS.md were read fully; the review applied the provider compatibility, deep source-read, proof, and agent-test guidance. (AGENTS.md:7, 474d6e520aaf)
  • Current shared policy has the moving marker behavior: Current main applies Anthropic message cache_control only to the last user message block, including a trailing tool_result, which matches the reported moving breakpoint in tool loops. (src/agents/anthropic-payload-policy.ts:142, 474d6e520aaf)
  • Current native provider has the same moving marker behavior: Current main's native Anthropic converter adds cache_control after conversion to the last user message content block, so streamAnthropic shares the same trailing tool-result marker behavior. (src/llm/providers/anthropic.ts:1187, 474d6e520aaf)
  • PR shared policy repair: The PR head scans backward for real user text/image blocks, keeps a fallback tool_result, and subtracts system/tool markers from a four-marker cache-control budget before marking messages. (src/agents/anthropic-payload-policy.ts:138, b20e6b3b78e0)
  • PR native provider repair: The PR head builds system and tools before messages, counts existing cache_control markers, and applies message markers to a stable real user block plus fallback tool_result when budget allows. (src/llm/providers/anthropic.ts:937, b20e6b3b78e0)
  • Regression coverage added: The PR adds shared policy tests for stable user markers through trailing tool results, tool-result-only fallback, and the one-remaining-message-marker budget case. (src/agents/anthropic-payload-policy.test.ts:105, b20e6b3b78e0)

Likely related people:

  • vincentkoc: GitHub file history shows vincentkoc authored the shared Anthropic payload policy refactor and earlier system prompt cache-boundary transport work that centralize cache marker placement. (role: provider-cache feature-history owner; confidence: high; commits: 067496b12934, 64f28906de09; files: src/agents/anthropic-payload-policy.ts, docs/reference/prompt-caching.md)
  • steipete: Recent main history shows steipete touching Anthropic/provider prompt-cache boundaries and model-provider edge cases adjacent to this payload shape. (role: recent provider-cache contributor; confidence: medium; commits: eef24d452fb5, 732d6972d74c, 479df18caf26; files: src/llm/providers/anthropic.ts, src/agents/anthropic-payload-policy.ts, docs/reference/prompt-caching.md)
  • obviyus: The live PR timeline and commit list show obviyus assigned to the PR and force-pushing the latest repair commits that bound markers and restored the system cache boundary. (role: recent PR branch repair owner; confidence: high; commits: 253b53b1fa2a, 5e0411d44159, 5b26f5809f6e; files: src/agents/anthropic-payload-policy.ts, src/llm/providers/anthropic.ts, src/agents/anthropic-payload-policy.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@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 2, 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. P2 Normal backlog priority with limited blast radius. labels Jun 2, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 3, 2026
@obviyus obviyus self-assigned this Jun 3, 2026
@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. 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 3, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 3, 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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed 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 3, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 4, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 4, 2026
@obviyus
obviyus merged commit 9ed9af4 into openclaw:main Jun 4, 2026
287 of 291 checks passed
@obviyus

obviyus commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator

Landed via rebase onto main.

Thanks @Marvinthebored.

Verification:

  • Rebasing: PR head rebased on origin/main at c25800ccc1a6f1757d6bbad6499938fad5515eb1.
  • Focused regression: node scripts/run-vitest.mjs run --config test/vitest/vitest.agents.config.ts -- src/agents/anthropic-payload-policy.test.ts passed, 11 tests.
  • Diff hygiene: git diff --check origin/main...HEAD passed.
  • Autoreview: .agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main --parallel-tests "node scripts/run-vitest.mjs run --config test/vitest/vitest.agents.config.ts -- src/agents/anthropic-payload-policy.test.ts" reported no accepted/actionable findings; parallel tests passed.
  • CI on rebased SHA b20e6b3b78e007af2540ddc78be6536497b4eae2: relevant Anthropic/provider/test surface passed. Two rerun failures were outside this PR diff:
    • check-lint: src/plugins/host-hook-runtime.ts oxlint errors.
    • checks-fast-contracts-plugins-a: src/plugins/contracts/plugin-sdk-package-contract-guardrails.test.ts drift for packages/plugin-sdk/src/testing.ts.
  • Changelog not updated; this is a normal PR and release generation owns CHANGELOG.md.

Merged commit: 9ed9af4f393926667ae8e54e74ba0b095193f0c9.

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: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

3 participants