Skip to content

fix(ai): anchor Anthropic cache checkpoints on earlier user turns while reserving the tool-result slot - #147248

Closed
Lubaoshuai wants to merge 4 commits into
openclaw:mainfrom
Lubaoshuai:fix/anthropic-cache-control-oauth
Closed

Lubaoshuai wants to merge 4 commits into
openclaw:mainfrom
Lubaoshuai:fix/anthropic-cache-control-oauth

Conversation

@Lubaoshuai

@Lubaoshuai Lubaoshuai commented Sep 13, 2026 •

Copy link
Copy Markdown

Closes #147168

Revision 3. Revision 1's system-helper adjustment was reverted in revision 2 (the OAuth preamble repair already shipped in #140804); the net diff against main is confined to the shared message allocator and its tests.

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 second tool_result in one message lost its cache_control), and ClawSweeper's revision-2 review flagged the same shape.

The Change

applyAnthropicCacheControlToMessages — the shared allocator both production builders reach through applyAnthropicRequestCacheControl — now allocates in priority order:

  1. Reserve the trailing tool result's slot first (new findTrailingToolResult pre-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.
  2. Keep walking backwards past the newest user turn, anchoring previous eligible user turns while marker budget remains. A reshaped newest message now only invalidates its own tail marker instead of the whole cached history.

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

  • Contract harness through the real applyAnthropicRequestCacheControl (this branch, bundled and run): 6/6 checks pass
    • starvation case (2 history slots, two user turns + trailing tool result): tool result keeps its slot, newest turn takes the other, older turn unmarked
    • full 4-marker budget: tool result + both user turns anchored
    • single history slot + tool result: fallback-only contract preserved
    • no tool results in history: newest two text turns anchored
    • opted-out newest turn: previous turn anchored, tool slot intact
    • two tool_result blocks in one message (the exact CI regression shape): the last block keeps its checkpoint
  • Live cache evidence v2 (every request deep-cloned fresh, built by this branch's allocator, sent to an Anthropic-compatible endpoint open.bigmodel.cn/api/anthropic, model glm-5.2; the provider reports cache_read_input_tokens but not cache_creation_input_tokens; keys redacted; the harness asserts <= 4 markers per request):
    • R1 cold (2 markers [system, messages[0]]): input=6427 cache_read=0
    • R2 grow (3 markers [system, messages[0], messages[2]]): earlier turn A anchored alongside newest C1 — cache_read=6400
    • R3 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 + trailing tool_result take their checkpoints, newest turn keeps one slot — cache_read=0 input=6616 (inserting tools changes 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=6592
    • An earlier revision of this trace printed five markers in one round; that was an artifact of the harness reusing mutated message objects across rounds (markers leaked from the previous round's payload), not allocator behavior. The harness now deep-clones every request and asserts the four-marker budget, which holds in all rounds above.
  • CI: revision 2's packages/ai/src/anthropic-cache-carrier-parity.test.ts failure and the oxfmt format failures are fixed by this revision. The remaining failing shards in the last run were src/infra / gateway tests (delivery-queue, transcripts, gateway server) unrelated to packages/ai.
  • New regression tests: production-entrypoint starvation + spare-slot tests in packages/ai/src/transports/anthropic-payload-policy.test.ts, and provider+transport builder coverage for two user turns followed by successive tool calls in packages/ai/src/anthropic-cache-transport-parity.test.ts.

@clawsweeper

clawsweeper Bot commented Sep 13, 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.

@Lubaoshuai
Lubaoshuai force-pushed the fix/anthropic-cache-control-oauth branch from ed96706 to 5ae8e5d Compare September 13, 2026 18:08
@Lubaoshuai
Lubaoshuai force-pushed the fix/anthropic-cache-control-oauth branch from 5ae8e5d to d12f167 Compare September 13, 2026 18:22
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 5, 2026, 10:47 AM ET / 14:47 UTC (Revision 8).

ClawSweeper review

What this changes

The 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
Reviewed head: 344bc60ba605b26d43dd05b4adb7d6406a8f17a8
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with meaningful boundary coverage and sufficient compatible-provider proof; policy acceptance and conflicts are separate landing blockers.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The revised live trace exercises branch-built requests through the shared allocator against an Anthropic-compatible GLM endpoint, preserves 6400 cached tokens after reshaping a user turn, and advances the reserved tool-result checkpoint within four markers. Direct Anthropic billing is outside this proof's scope. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The revised live trace exercises branch-built requests through the shared allocator against an Anthropic-compatible GLM endpoint, preserves 6400 cached tokens after reshaping a user turn, and advances the reserved tool-result checkpoint within four markers. Direct Anthropic billing is outside this proof's scope. No stored-data contract changes.
Evidence reviewed 10 items Pinned introduced change: The merge-base-to-head delta changes only the shared message allocator and three test files. The system-header repair is absent from the introduced production diff.
Still absent from current main: Current main retains the allocator's immediate return after marking the newest eligible user text/image block, optionally also marking a trailing tool result. Spare slots do not reach earlier ordinary user turns.
Latest release still uses the existing policy: The v2026.9.8 source at fc23bc8 retains the same single-user-anchor scan and early return. The release blob was inspected through GitHub REST because its local object was unavailable.
Findings None None.
Security None None.

How this fits together

OpenClaw 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]
Loading

Decision needed

Question Recommendation
Should the shared Anthropic allocator spend spare checkpoints on earlier eligible user turns? Adopt earlier-turn anchors: Accept the bounded placement improvement while retaining tool-result priority and the existing checkpoint budget.

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

  • Resolve merge risk (P1) - Owner acceptance is still needed for spending spare checkpoints on earlier user turns rather than retaining the established placement policy.
  • Resolve merge risk (P1) - The pinned branch has merge conflicts; the resolved integration must be reviewed against current main.
  • Complete next step (P2) - Obtain owner acceptance for earlier-user checkpoint placement and resolve the branch conflicts against current main.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +41, Tests +230. Total +271 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 1 70 29 +41
Tests 3 230 0 +230
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 300 29 +271

Review metrics

Metric Value Why it matters
Allocator growth and regression coverage production net +41 lines; tests net +230 lines Production growth supplies the tool-result reservation pre-pass and bounded history allocation, with coverage at policy and request-builder boundaries.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #147168
Summary: This PR is the candidate implementation for the linked issue's surviving history-anchor request.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    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.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This bounded cache-cost improvement affects persistent Anthropic sessions without blocking message delivery or core availability.
  • 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 (live_output): The revised live trace exercises branch-built requests through the shared allocator against an Anthropic-compatible GLM endpoint, preserves 6400 cached tokens after reshaping a user turn, and advances the reserved tool-result checkpoint within four markers. Direct Anthropic billing is outside this proof's scope. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The revised live trace exercises branch-built requests through the shared allocator against an Anthropic-compatible GLM endpoint, preserves 6400 cached tokens after reshaping a user turn, and advances the reserved tool-result checkpoint within four markers. Direct Anthropic billing is outside this proof's scope. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduced change: The merge-base-to-head delta changes only the shared message allocator and three test files. The system-header repair is absent from the introduced production diff. (packages/ai/src/transports/anthropic-payload-policy.ts:323, 344bc60ba605)
  • Still absent from current main: Current main retains the allocator's immediate return after marking the newest eligible user text/image block, optionally also marking a trailing tool result. Spare slots do not reach earlier ordinary user turns. (packages/ai/src/transports/anthropic-payload-policy.ts, 495c243be11a)
  • Latest release still uses the existing policy: The v2026.9.8 source at fc23bc8 retains the same single-user-anchor scan and early return. The release blob was inspected through GitHub REST because its local object was unavailable. (packages/ai/src/transports/anthropic-payload-policy.ts:320, fc23bc864e45)
  • Both production builders use the changed owner: The provider and managed transport convert history into fresh wire messages, record transient-carrier opt-outs, and call applyAnthropicRequestCacheControl. The patch preserves those opt-outs, retention settings, and the four-marker budget. (packages/ai/src/providers/anthropic.ts:667, 344bc60ba605)
  • Revised real-provider proof: The captured PR body and fix(ai): anchor Anthropic cache checkpoints on earlier user turns while reserving the tool-result slot #147248 (comment) describe freshly cloned requests built by this branch's allocator and sent to an Anthropic-compatible GLM endpoint. R2 and reshaped R3 both report cache_read=6400; R4 and R5 use four checkpoints, advance the tool-result checkpoint, and R5 reports cache_read=6592. This supersedes the earlier five-marker harness trace. It demonstrates compatible-provider behavior, not direct Anthropic billing. Captured sourceRevision: 71cb9e1ede66bb9b0abce4a31b788ad342b692a234fb7e203e0b7e2e83fffa74. (344bc60ba605)
  • Prior starvation finding addressed: The current pre-pass reserves the latest eligible tool result before allocating user checkpoints. Added tests cover the two-history-slot starvation case and spare-slot anchoring; builder parity coverage exercises successive tool calls. The previous completed review at this same head had no findings. Tests were inspected, not executed. (packages/ai/src/transports/anthropic-payload-policy.ts:373, 344bc60ba605)

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Resolve the current-main conflicts and validate the integrated allocator and both request builders.

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 (7 earlier review cycles)
  • reviewed 2026-09-13T18:32:31.648Z sha d12f167 :: needs real behavior proof before merge. :: [P1] [P1] Target the active history allocator instead of duplicating the header fix | [P2] [P2] Retain a stable checkpoint before a dynamic-only split
  • reviewed 2026-09-20T02:38:15.420Z sha 9e041c4 :: needs real behavior proof before merge. :: [P2] [P2] Reserve the trailing tool-result checkpoint before older anchors
  • reviewed 2026-09-22T16:00:53.836Z sha 50ae84a :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-22T16:35:11.025Z sha 50ae84a :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-22T17:34:41.690Z sha 50ae84a :: needs changes before merge. :: none
  • reviewed 2026-09-22T17:47:58.482Z sha 50ae84a :: needs maintainer review before merge. :: none
  • reviewed 2026-09-22T18:20:19.004Z sha 344bc60 :: needs maintainer review before merge. :: none

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.
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Sep 20, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. and removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Sep 20, 2026
…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
@Lubaoshuai Lubaoshuai changed the title fix(ai): stop spending cache_control breakpoints on OAuth preamble blocks fix(ai): anchor Anthropic cache checkpoints on earlier user turns while reserving the tool-result slot Sep 22, 2026
@Lubaoshuai

Copy link
Copy Markdown
Author

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 tool_result up front (findTrailingToolResult) and reserves its slot before spending any marker on user turns. The exact starvation shape from the review — one system + one tool checkpoint, two user text turns followed by a tool result — now yields system[0] tools[0] messages[2].content[0] messages[4].content[0] (tool result + newest turn; older turn unmarked). The single-slot fallback contract is unchanged. This also fixes the CI failure in anthropic-cache-carrier-parity.test.ts (second tool_result in one message losing its checkpoint), which was the same regression.

Regression coverage. New production-entrypoint tests in packages/ai/src/transports/anthropic-payload-policy.test.ts (starvation, spare-slot anchoring with the full 4-marker budget) and provider+transport builder coverage in packages/ai/src/anthropic-cache-transport-parity.test.ts (two user turns followed by successive tool calls). A 6-check contract harness through the real applyAnthropicRequestCacheControl passes 6/6.

Real behavior proof (redacted). Request built by this branch's allocator, sent to an Anthropic-compatible endpoint (open.bigmodel.cn/api/anthropic, glm-5.2 — no Anthropic key on this machine; provider reports cache_read_input_tokens, not cache_creation_input_tokens):

round 1 (cold): markers=[system[0] messages[0].content[0]]
  usage: input=6423 cache_creation=undefined cache_read=0
round 2: markers=[system[0] messages[0].content[0] messages[2].content[0] messages[4].content[0]]
  usage: input=59 cache_creation=undefined cache_read=6400
round 3: markers=[system[0] messages[0].content[0] messages[2].content[0] messages[4].content[0] messages[6].content[0]]
  usage: input=83 cache_creation=undefined cache_read=6400

The stable prefix stays cache-served (cache_read=6400) across rounds while the newest user turn advances from messages[4] to messages[6] — the anchors this PR adds survive the reshaped newest turn.

Body and title updated to describe the revised history allocator. oxfmt clean on all touched files.

@openclaw-barnacle openclaw-barnacle Bot added triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. size: M and removed size: S labels Sep 22, 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. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Sep 22, 2026
@Lubaoshuai

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 22, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Lubaoshuai

Copy link
Copy Markdown
Author

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 <= 4 markers, which holds in all rounds. Fresh trace (request built by this branch's allocator, Anthropic-compatible endpoint, keys redacted):

R1 cold         : 2 markers [system[0] messages[0].content[0]]
  usage: input=6427 cache_read=0
R2 grow         : 3 markers [system[0] messages[0].content[0] messages[2].content[0]]
  usage: input=46 cache_read=6400
R3 reshape C    : 3 markers [system[0] messages[0].content[0] messages[2].content[0]]
  usage: input=59 cache_read=6400
R4 tool loop    : 4 markers [system[0] tools[0] messages[2].content[0] messages[4].content[0]]
  usage: input=6616 cache_read=0
R5 advance+shape: 4 markers [system[0] tools[0] messages[2].content[0] messages[6].content[0]]
  usage: input=48 cache_read=6592

2. Reshaping an existing user turn. R3 rewrites the existing mid-conversation turn C1 into a reshaped block while conversation history otherwise stands: the marker layout is unchanged ([system, messages[0], messages[2]]), and cache_read=6400 is identical to R2 — the prefix through the earlier-turn anchor stayed cache-served and only the reshaped turn's tail re-created (input=59).

Tool rounds: R4 shows the reserved tool-result checkpoint (messages[4]) alongside tool definitions and the newest turn at exactly 4 markers; R5 advances the tool-result checkpoint to the newest tool result (messages[6]) and still cache-serves 6592 tokens of the prefix. (R4's cache_read=0 is the expected prefix-head change from inserting tools, which precede system in Anthropic's cache ordering.)

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 22, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 22, 2026
@clawsweeper clawsweeper Bot added 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 status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 22, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Sep 22, 2026
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.
@htuyer121

Copy link
Copy Markdown
Contributor

Data point + a tested allocator rule for this PR (OpenClaw 2026.9.8, anthropic provider, claude-opus-5-5, OAuth, cacheRetention: long, long-lived direct-message session ~309K tokens).

What we saw. First model call after each new user message: cacheRead ~41.4K (tools + system only), cacheWrite 267K-301K. Follow-up calls inside the same turn read ~308K and write <1K. Not a TTL effect (gaps of seconds to minutes).

Why an anchor on the previous user turn still misses. A two-run diagnostics.cacheTrace shows the whole previous turn (user message, runtime-context carrier, assistant message, tool result) fingerprints differently in-turn, after persist and after the next session:sanitized, while every message before that turn is byte-identical across all four stages:

per-message fingerprints, msgs 470..474 (470 = last message before the turn; 471/472 user + carrier; 473 assistant; 474 toolResult)
run1 stream:context    49501367 9473f34e 6093fe07 32c13585 e7a90a16
run1 session:after     49501367 c03441c5 091dd272 32c13585 9daf70be
run2 session:sanitized 49501367 43408188 61fbd9a7 fcd3778a 1547cdec
run2 stream:context    49501367 94213eed 785ab531 fcd3778a 1547cdec
run2 first call: read 41437, write 266962 -> next call read 308399, write 572

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) — Pcur, written now — and, if budget remains, the same point before the previous run — Pprev, which equals the previous request's Pcur, so it is read now. Priority in a tool loop [tail tool_result, Pcur, Pprev, older user marker]; on a first call [Pcur, Pprev, tail]; never more than 4 markers; no-op without cache_control, for non-Anthropic APIs, or without an earlier turn. Request N writes an entry at exactly the boundary request N+1 marks, so the hit does not rely on the 20-block lookback.

Results.

  • Offline (real converter/allocator, trace-shaped fixtures): first-call cached share 3/642 blocks -> 633/642; never above 4 markers over 1,100 randomised conversations; a property test confirms "request N+1 always reads through the boundary request N wrote".
  • Live, applied as a payload-wrapper patch on 2026.9.8: a warm first call of a new user message now reads 68,694 and writes 648 (98.5% cached), versus ~41K read / 267K+ written before. Turns after a gap longer than the cache TTL still start cold, as expected.

Happy to share the patch and tests if useful for this PR.

@htuyer121

Copy link
Copy Markdown
Contributor

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.

htuyer121 added a commit to htuyer121/openclaw that referenced this pull request Oct 11, 2026
…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
htuyer121 added a commit to htuyer121/openclaw that referenced this pull request Oct 11, 2026
…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
@Lubaoshuai

Copy link
Copy Markdown
Author

Closing this as superseded. Main now ships the same family of fixes and went further:

Special thanks to @htuyer121 — the cacheTrace fingerprint data point on this PR was excellent, showing that even a previous-user-turn anchor sits inside the part that changes during a turn, which is what pushed the final solution to the stable assistant-boundary thinking that landed in main. The starvation regression caught by CI and ClawSweeper during this PR's review also fed directly into what shipped.

Appreciate the reviews from ClawSweeper across six rounds — they materially improved the final allocator.

@Lubaoshuai Lubaoshuai closed this Oct 13, 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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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.

Anthropic transport spends 3 of 4 cache_control breakpoints on the OAuth system header, leaving the whole history one anchor on the last user message

2 participants