Skip to content

fix(anthropic): preserve tool cache when system prompts change - #140804

Merged
steipete merged 2 commits into
mainfrom
kv/managed-messages-tool-cache-marker
Sep 7, 2026
Merged

steipete merged 2 commits into
mainfrom
kv/managed-messages-tool-cache-marker

Conversation

@steipete

@steipete steipete commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor
Additional instructions

Maintainers can update this repository branch.

What Problem This Solves

Fixes an issue where users running managed Anthropic Messages requests would lose reuse of unchanged tool definitions when their system prompt changed, such as after a workspace edit or skills refresh. OAuth requests also spent a cache checkpoint on the billing preamble, leaving less room to cache conversation history.

Why This Change Was Made

Both Messages builders now share system shaping, cache capability and TTL resolution, and checkpoint allocation. Supported routes checkpoint the last projected tool separately from the stable system prompt, then use the remaining slots for the latest user and tool-result anchors, within Anthropic's four-marker limit. OAuth billing and identity text is preserved; the identity checkpoint is retained only when there is no stable application-system checkpoint.

The existing Fireworks defaults and explicit compatibility overrides gate tool markers and long TTLs. Implicit long retention follows the documented endpoint-host restriction in both paths. The generic plugin-SDK payload-policy helper retains its existing behavior. Production code is reduced by 75 lines.

User Impact

Stable tool definitions remain independently cacheable when the system prompt changes. OAuth tool loops retain both conversation anchors without marking the billing block. No configuration, storage, dependency, or changelog changes are introduced.

Evidence

  • Before the fix, the new HTTP-payload parity matrix failed 12 of 36 cases for missing tool checkpoints, OAuth allocation, and managed Fireworks TTL handling.
  • After the fix: 13 Anthropic package test files passed, 375 tests passed, including 44 payload-parity cases covering API keys, OAuth, Foundry, proxies, incompatible tool caching, tools/no tools, short/long/none retention, tool-loop advancement, stable-system edits, empty-system fallback, and implicit TTL host gating.
  • Command: node scripts/run-vitest.mjs with the Anthropic provider, transport, policy, replay, usage, inline-image, and parity test paths.
  • The Anthropic section of docs/reference/prompt-caching.md now documents the independent tool-prefix checkpoint.
  • Proof uses synthetic HTTP capture and existing loopback tests; no live provider cache-hit or billing measurements were taken.
  • Legacy exported policy: node scripts/run-vitest.mjs src/agents/anthropic-payload-policy.test.ts — 1 file passed, 17 tests passed. Together with the shared snapshot suite below, total focused proof is 15 files and 407 passing tests.
  • Final Codex autoreview: scoped-clean; zero accepted/actionable P0/P1 findings; overall verdict: patch is correct. No findings required disposition.

Focused output summaries:

Test Files  13 passed (13)
     Tests  375 passed (375)

Test Files  1 passed (1)
     Tests  17 passed (17)

Final policy/parity rerun after lint and export cleanup:
Test Files  2 passed (2)
     Tests  58 passed (58)

node scripts/check-changed.mjs completed successfully (exit 0), including production/test typechecking, lint, dead-export scans, and the final architecture guards. All three dead-export scans reported zero entries; runtime import-cycle checking reported zero cycles.

Validation follow-through: strict test-array typing and three test sort() calls were corrected, and the newly unused message-helper export was made module-private. One later gate run hit the existing managed-process cleanup error EPROCESSGROUP_CLEANUP_FAILED without a TypeScript diagnostic; the process group was verified terminated, the diagnostic typecheck passed, and the complete gate then passed without weakening guards or changing timeouts.

Final autoreview output:

autoreview scoped-clean: no accepted/actionable findings in the selected Git scope and priority
overall: patch is correct

CI follow-up: the first exact-head run failed only checks-node-compact-small-7 (and its aggregate gate) because the shared transport snapshot lacked the intended tool checkpoint. Vitest regenerated exactly three lines in anthropic-success.snap.txt, adding the last tool's ephemeral cache_control; no assertion was weakened.

node scripts/run-vitest.mjs packages/ai/src/provider-transport-parity.test.ts --update regenerated the snapshot, then the same command without --update passed:

Test Files  1 passed (1)
     Tests  15 passed (15)

The follow-up node scripts/check-changed.mjs passed (exit 0), including full core lint. Fresh Codex autoreview remains scoped-clean with zero accepted/actionable P0/P1 findings.

Final CI: run 34085820808 completed successfully on f1479f54cdff533478b82028e9c7ba949949c98e: 77 successful jobs, 16 intentionally skipped jobs, zero failed or pending jobs. The exact-head watcher returned GREEN (exit 0), including the corrected snapshot shard and openclaw/ci-gate.

Share cache checkpoint allocation across managed and SDK Messages requests. Preserve OAuth billing text, reserve history anchors, and respect tool and TTL compatibility.
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M maintainer Maintainer-authored PR labels Sep 7, 2026
@steipete
steipete marked this pull request as ready for review September 7, 2026 04:44
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Sep 7, 2026
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 7, 2026, 1:27 AM ET / 05:27 UTC.

ClawSweeper review

What this changes

Shares Anthropic request-cache allocation across both Messages builders so unchanged tools remain independently cacheable when system prompts change.

Merge readiness

⛔ Blocked before merge - 1 item remains

The PR remains useful: current main still lacks the managed tool checkpoint. The introduced changes have no identified blocking correctness defects, and the prior review contains no unresolved findings.

Priority: P2
Reviewed head: f1479f54cdff533478b82028e9c7ba949949c98e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused consolidation with meaningful boundary coverage and no identified blocking defect.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-author exemption applies. Reported HTTP payload tests exercise both production builders with mocked fetch and cover checkpoint allocation, but do not demonstrate live Anthropic cache reuse.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-author exemption applies. Reported HTTP payload tests exercise both production builders with mocked fetch and cover checkpoint allocation, but do not demonstrate live Anthropic cache reuse.
Evidence reviewed 7 items Introduced implementation: The shared allocator marks the last supported tool, counts tool and system checkpoints, and allocates the remaining budget to conversation anchors. OAuth billing and identity text remain intact.
Current-main necessity: Fetched main still constructs OAuth system blocks separately and calls the generic payload policy without adding a tool checkpoint in the managed builder.
Existing plugin contract preserved: The exported generic policy passes false for tool checkpoint allocation, retaining its existing behavior; the new allocator is used directly by the two internal Messages builders.
Findings None None.
Security None None.

How this fits together

OpenClaw’s Anthropic request builders convert tools, system instructions, and conversation history into provider requests. Cache checkpoints identify reusable prefixes while respecting route capabilities and Anthropic’s four-checkpoint limit.

flowchart LR
  A[Tools and system instructions] --> C[Messages request builders]
  B[Conversation history] --> C
  D[Retention and route capabilities] --> E[Shared checkpoint allocation]
  C --> E
  E --> F[Anthropic API request]
Loading

Before merge

  • Resolve merge risk (P1) - Actual provider cache-hit and billing improvements remain unmeasured; the supplied validation establishes outgoing checkpoint placement.
Agent review details

Security

None.

PR surface

Source -75, Tests +205, Docs +1. Total +131 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 4 106 181 -75
Tests 3 205 0 +205
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 312 181 +131

Review metrics

Metric Value Why it matters
Production consolidation Production −75 lines; tests and test support +205 lines Shared request shaping removes duplicated production logic while adding coverage across both builders.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep one shared checkpoint allocator while preserving explicit retention settings, route compatibility overrides, and the existing plugin payload-policy contract.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep one shared checkpoint allocator while preserving explicit retention settings, route compatibility overrides, and the existing plugin payload-policy contract.

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

Yes, at the request boundary: current main’s managed builder omits the independent tool checkpoint and consumes extra OAuth system slots. Live cache-hit effects were not reproduced during this review.

Is this the best way to solve the issue?

Yes. Consolidating the two builders around the existing caching rules repairs their divergence without introducing another configuration path or changing the exported plugin policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 61d957a9cb64.

Labels

Label justifications:

  • P2: This is a bounded cache-efficiency repair without evidence of an urgent user-facing outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-author exemption applies. Reported HTTP payload tests exercise both production builders with mocked fetch and cover checkpoint allocation, but do not demonstrate live Anthropic cache reuse.

Evidence

What I checked:

  • Introduced implementation: The shared allocator marks the last supported tool, counts tool and system checkpoints, and allocates the remaining budget to conversation anchors. OAuth billing and identity text remain intact. (packages/ai/src/transports/anthropic-payload-policy.ts:194, f1479f54cdff)
  • Current-main necessity: Fetched main still constructs OAuth system blocks separately and calls the generic payload policy without adding a tool checkpoint in the managed builder. (packages/ai/src/transports/anthropic-transport-stream.ts:572, 61d957a9cb64)
  • Existing plugin contract preserved: The exported generic policy passes false for tool checkpoint allocation, retaining its existing behavior; the new allocator is used directly by the two internal Messages builders. (packages/ai/src/transports/anthropic-payload-policy.ts:627, f1479f54cdff)
  • Payload coverage and proof boundary: The 44-case matrix covers both builders, six route variants, retention settings, advancing tool turns, system edits, and OAuth fallback. Its shared helper mocks fetch. The supplied PR body reports 407 focused passing tests and successful exact-head CI, explicitly without live cache-hit measurements; these executions were not rerun during this read-only review. (packages/ai/src/anthropic-cache-transport-parity.test.ts:77, f1479f54cdff)
  • Anthropic protocol contract: The patch’s cache_control payloads depend on Anthropic’s Messages caching contract. Official documentation specifies tools before system before messages, permits four breakpoints, and recommends separate checkpoints for sections changing at different frequencies: Prompt caching. No Codex dependency signal was found.
  • Area history: Current-main history records Peter Steinberger’s shared Anthropic protocol refactor and subsequent cache/pruning work, supporting routing to steipete independently of authorship of this proposal. Missing older objects prevented reliable source-line introduction attribution. (packages/ai/src/transports/anthropic-transport-stream.ts, 2dfd3c3daba9)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

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

History

Review history (2 earlier review cycles)
  • reviewed 2026-09-07T04:52:10.784Z sha d5a8801 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-07T05:17:02.738Z sha f1479f5 :: needs maintainer review before merge. :: none

@steipete
steipete merged commit 5a4f24e into main Sep 7, 2026
137 of 138 checks passed
@steipete
steipete deleted the kv/managed-messages-tool-cache-marker branch September 7, 2026 05:28
@steipete

steipete commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 8, 2026
…law#140804)

* fix(anthropic): preserve tool cache when system prompts change

Share cache checkpoint allocation across managed and SDK Messages requests. Preserve OAuth billing text, reserve history anchors, and respect tool and TTL compatibility.

* test(anthropic): refresh managed tool cache payload snapshot
Lubaoshuai added a commit to Lubaoshuai/openclaw that referenced this pull request Sep 20, 2026
Reworked after review. The earlier revision adjusted the legacy exported
system helper in @openclaw/ai, duplicating the OAuth-preamble repair that
openclaw#140804 already shipped in the production builders and altering the
helper's checkpoint contract for SDK consumers.

This revision reverts the helper to its main behavior and fixes the
remaining gap from openclaw#147168 where it actually lives: the message
allocator. applyAnthropicCacheControlToMessages now keeps walking
backwards past the newest user turn and anchors the previous eligible
user turn while marker budget remains, so a reshaped newest message only
invalidates its own tail marker instead of the whole cached history.

Evidence: new unit tests assert the three-anchor wire layout (previous
user turn, latest tool result, newest user turn) through
applyAnthropicPayloadPolicyToParams, plus the preserved single-marker
tool-result fallback contract.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. 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.

1 participant