Repository navigation
fix(ai): anchor Anthropic cache checkpoints on earlier user turns while reserving the tool-result slot - #147248
Lubaoshuai wants to merge 4 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
ed96706 to
5ae8e5d
Compare
5ae8e5d to
d12f167
Compare
|
Codex review: blocked before merge. Reviewed October 5, 2026, 10:47 AM ET / 14:47 UTC (Revision 8). ClawSweeper reviewWhat this changesThe shared Anthropic request allocator reserves the latest tool-result checkpoint and uses remaining checkpoint slots for earlier eligible user turns, with regression coverage for both request builders. Merge readiness⛔ Blocked before merge - 4 items remain This PR still addresses a distinct improvement absent from main and the latest release. The revised proof is sufficient and no blocking code defect was found, but checkpoint-policy acceptance remains unresolved. Likely related people: steipete — relevant merged allocator work; medium-confidence routing candidate. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw converts conversation history, system instructions, and tools into Anthropic Messages requests. The shared cache allocator places checkpoints in those requests to control which prompt prefixes the provider can reuse. flowchart TD
A[Conversation history] --> C[Messages request builders]
B[System instructions and tools] --> C
C --> D[Shared cache allocator]
D --> E[Reserve tool-result checkpoint]
E --> F[Allocate remaining user checkpoints]
F --> G[Provider request and cache reuse]
Decision needed
Why: The existing placement policy is intentional, and the linked reporter explicitly requested owner confirmation; successful cache proof does not establish that acceptance. Before merge
Agent review detailsSecurityNone. PR surfaceSource +41, Tests +230. Total +271 across 4 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Use one owner-approved allocator that preserves tool-result priority, transient-carrier opt-outs, and the four-checkpoint limit while retaining older reusable history anchors. Do we have a high-confidence way to reproduce the issue? Yes for checkpoint placement: current-main source returns after the newest eligible user block despite spare budget. No current-main live billing reproduction was executed. Is this the best way to solve the issue? Yes, extending the existing shared allocator is a focused solution, and the revised ordering addresses the prior starvation defect; adoption still depends on owner acceptance. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 495c243be11a. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (7 earlier review cycles)
|
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.
…nchors ClawSweeper revision-2 review + CI both flagged the same starvation case: with one system and one tool checkpoint, two history slots remain, and a history scan that marks two user text turns first left the saved trailing tool result unmarked, dropping the advancing tool-loop checkpoint (openclaw#147168). anthropic-cache-carrier-parity.test.ts failed on CI for exactly this shape (second tool_result in one message lost its cache_control). applyAnthropicCacheControlToMessages now locates the trailing tool_result up front and reserves its slot before spending any marker on user turns. The single-slot contract is unchanged (a lone marker still caches the longer-lived tool-output prefix), and spare slots still anchor earlier user turns once the tool slot is reserved. Validation: - evidence harness through the real applyAnthropicRequestCacheControl: 6/6 contract checks pass (starvation, spare anchors, single-slot, no-tool-result, opt-out, carrier two-tool_result layout) - live cache evidence through an Anthropic-compatible endpoint: marker layout system + previous user turn + tool result + newest user turn, cache_read=6400 on rounds 2-3 while the newest turn advances - oxfmt clean on all touched files
|
Revision 3 pushed (50ae84a) — addresses the tool-loop checkpoint regression and adds the requested real-behavior proof. Starvation fix. The allocator now locates the trailing Regression coverage. New production-entrypoint tests in Real behavior proof (redacted). Request built by this branch's allocator, sent to an Anthropic-compatible endpoint ( The stable prefix stays cache-served (cache_read=6400) across rounds while the newest user turn advances from Body and title updated to describe the revised history allocator. oxfmt clean on all touched files. |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Re-ran the live evidence to address the two open proof points (body updated): 1. Marker budget. The five-marker line in the previous trace was an artifact of the harness reusing mutated message objects across rounds (markers leaked from the previous round's payload into the next request) — not allocator behavior. The harness now deep-clones every request and asserts 2. Reshaping an existing user turn. Tool rounds: @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
The baseline-ratchet check counts uncommented non-const type assertions per file; the findTrailingToolResult helper added three. Annotate each with the invariant the preceding typeof/object checks establish.
|
Data point + a tested allocator rule for this PR (OpenClaw 2026.9.8, What we saw. First model call after each new user message: Why an anchor on the previous user turn still misses. A two-run So a marker on the previous/newest user turn sits inside the part that changes (related causes: #166271, #164515, #140129, #166272), and with no earlier anchor Anthropic can only read the system block. Allocator rule we tested. Keep the existing tail rules, and spend the spare budget on the stable boundary: the last cacheable (non-thinking, non-empty) block of the assistant message that precedes the newest user run (consecutive user messages incl. the carrier = one run) — Results.
Happy to share the patch and tests if useful for this PR. |
|
Follow-up: the stable-boundary allocator rule from the comment above is now proposed as a source change with tests in #166667, for comparison with this PR. |
…message The message cache allocator only marked user checkpoints (the newest and the previous user message). Those sit inside the part of the conversation that is re-rendered between requests, so the first call after each new user message found no usable anchor and re-wrote the whole history. Spend the cache_control budget on the stable boundary on the first call of a new user turn: the last cacheable block of the assistant message before the newest user turn (written now) and before the previous turn (the boundary the previous request wrote), then the user checkpoints. Tool-loop calls, and runs that begin with a tool result, keep the user checkpoints first, so the previous request's checkpoint stays reachable after a long append. Nothing at or after the earliest transient message takes a marker, and the 4-marker budget, single-turn placement and no-cache_control behavior are unchanged. The checkpoint helpers live in anthropic-cache-checkpoints.ts to keep the policy module under its line cap. Related: openclaw#147168, openclaw#147248
…message The message cache allocator only marked user checkpoints (the newest and the previous user message). Those sit inside the part of the conversation that is re-rendered between requests, so the first call after each new user message found no usable anchor and re-wrote the whole history. Spend the cache_control budget on the stable boundary on the first call of a new user turn: the last cacheable block of the assistant message before the newest user turn (written now) and before the previous turn (the boundary the previous request wrote), then the user checkpoints. Tool-loop calls, and runs that begin with a tool result, keep the user checkpoints first, so the previous request's checkpoint stays reachable after a long append. Nothing at or after the earliest transient message takes a marker, and the 4-marker budget, single-turn placement and no-cache_control behavior are unchanged. The checkpoint helpers live in anthropic-cache-checkpoints.ts to keep the policy module under its line cap. Related: openclaw#147168, openclaw#147248
|
Closing this as superseded. Main now ships the same family of fixes and went further:
Special thanks to @htuyer121 — the Appreciate the reviews from ClawSweeper across six rounds — they materially improved the final allocator. |
Closes #147168
What Problem This Solves
The Anthropic message allocator stopped after the latest eligible user turn plus the trailing
tool_result. A reshaped newest user message (inbound image stored back as text, shortened heartbeat poll, dropped context carrier) invalidates its own marker, and with no earlier history anchor the whole conversation prefix is re-written at cache-write price on every request — the core complaint in #147168.Revision 2 fixed that but introduced a starvation regression: with one system checkpoint and one tool checkpoint (two history slots remain), a backward scan that marks two user text turns first left the saved trailing tool result unmarked, dropping the advancing tool-loop checkpoint. CI caught it (
anthropic-cache-carrier-parity.test.ts: a secondtool_resultin one message lost itscache_control), and ClawSweeper's revision-2 review flagged the same shape.The Change
applyAnthropicCacheControlToMessages— the shared allocator both production builders reach throughapplyAnthropicRequestCacheControl— now allocates in priority order:findTrailingToolResultpre-pass). The tool-result checkpoint is the advancing tool-loop anchor; spare history checkpoints can no longer starve it. The single-slot contract is unchanged: with one history marker, the lone marker still caches the longer-lived tool-output prefix instead of the newest (most volatile) user turn.Net effect with one system + one tool checkpoint (two history slots): trailing tool result + newest user turn — matching the pre-regression contract. With more slots, previous user turns gain anchors too.
Evidence
applyAnthropicRequestCacheControl(this branch, bundled and run): 6/6 checks passtool_resultblocks in one message (the exact CI regression shape): the last block keeps its checkpointopen.bigmodel.cn/api/anthropic, modelglm-5.2; the provider reportscache_read_input_tokensbut notcache_creation_input_tokens; keys redacted; the harness asserts<= 4markers per request):R1 cold(2 markers[system, messages[0]]):input=6427 cache_read=0R2 grow(3 markers[system, messages[0], messages[2]]): earlier turn A anchored alongside newest C1 —cache_read=6400R3 reshape C(existing user turn C1 rewritten to a reshaped block, 3 markers unchanged[system, messages[0], messages[2]]):cache_read=6400— the prefix through the earlier-turn anchor stayed cache-served; only the reshaped turn's tail re-created (input=59)R4 tool loop(4 markers[system, tools, messages[2], messages[4]]): tool definitions + trailingtool_resulttake their checkpoints, newest turn keeps one slot —cache_read=0 input=6616(insertingtoolschanges the prefix head — tools precede system in Anthropic's cache ordering — so this round legitimately re-writes)R5 advance+shape(second tool round, 4 markers[system, tools, messages[2], messages[6]]): the tool-result checkpoint advances to the newest tool result —cache_read=6592packages/ai/src/anthropic-cache-carrier-parity.test.tsfailure and theoxfmtformat failures are fixed by this revision. The remaining failing shards in the last run weresrc/infra/ gateway tests (delivery-queue, transcripts, gateway server) unrelated topackages/ai.packages/ai/src/transports/anthropic-payload-policy.test.ts, and provider+transport builder coverage for two user turns followed by successive tool calls inpackages/ai/src/anthropic-cache-transport-parity.test.ts.