Repository navigation
fix(agents): stop Anthropic session forks from caching their own suffix - #197224
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. |
|
Codex review: needs maintainer review before merge. What this changesThis PR prevents Anthropic session forks from placing prompt-cache checkpoints on their private suffix. Example: An Advisor fork reviews an Anthropic parent conversation with thinking enabled.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR provides a focused reduction in Anthropic fork costs that current main lacks, with no actionable correctness or security findings. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherSession forks borrow parent conversation context, append a private question, and use the shared provider transport to return text and usage without executing tools. flowchart LR
A[Session fork request] --> B[Copy parent context]
B --> C[Mark private suffix]
C --> D[Anthropic message conversion]
D --> E[Existing checkpoint allocator]
E --> F[Provider response and usage]
Technical reviewBest possible solution: Keep suffix ownership in the fork and reuse the Anthropic checkpoint allocator to avoid private-tail writes while preserving parent requests. Do we have a high-confidence way to reproduce the issue? Current-main source places checkpoints on the fork question and trailing results, and supplied real-Gateway measurements demonstrate the resulting writes; no target code was executed during this review. Is this the best way to solve the issue? The change addresses unnecessary writes at their producer, preserves parent message objects through shallow copies, and reuses existing checkpoint policy without adding another cache owner. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against a0aa49cf4b9d. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +28, Tests -1. Total +27 across 6 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 11, 2026, 9:53 AM ET / 14:53 UTC (Revision 2). |
Co-authored-by: obviyus <[email protected]>
OpenClaw-Publication: c22450f5-5d00-4f09-99bb-7ac53e1253d6
cf46cdc to
0129228
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…ix (openclaw#197224) Co-authored-by: obviyus <[email protected]>
Problem
Every Anthropic session fork (Advisor review,
/btw) wrote about 900–1000 tokens of prompt cache that no later request reads.The transport puts the two history checkpoints on the last two user messages. In a fork, those are:
The parent's next call sends and writes that second part itself, at the same time as the fork (in every run here the two requests left within about 20 ms of each other). The question exists only in the fork. So the fork paid the cache-write premium (1.25x for the 5-minute TTL, 2x for 1 hour) on tokens nothing reads.
Fix
Owner:
buildAnthropicRequest→applyAnthropicRequestCacheControl(packages/ai/src/transports/anthropic-payload-policy.ts). The fork marks inrunEmbeddedSessionFork(src/agents/embedded-agent-runner/session-fork.ts).Live evidence
Isolated Gateway, real providers. One parent turn with 3
session_statuscalls, AdvisoreveryToolCalls: 1,thinkingDefault: high. Base ismainwith #197203 (fork thinking level) merged. Usage is per fork request from the provider response. Run A is on currentmain(merged #197203). Run B is on the earliermainwith #197203's identical diff cherry-picked.Direct Anthropic API (
anthropic/claude-haiku-5-5), two runs per sideRebased onto #197223 (head
012922835412), direct Anthropic API, same harness, after only#197223 changed the fork gate and passes an egress check to guarded fetch for non-Responses APIs. The rebase was conflict-free, and the Anthropic request body logic is unchanged (
anthropic-messages.ts,anthropic-payload-policy.ts,provider-options.tsidentical to the old head). Two fresh runs on the rebased head:Checkpoints in fork requests are on the same messages as at the old head:
system[0],tools[0]and only user messages the parent already cached (1st fork:m0; 2nd fork:m0,m3). None on the fork's tail or question.tool_choiceis{type:"none"}.Parent totals (read/write): 13780/6336 and 14003/6556, the same range as before.
The fork still reads the parent's full cached prefix. In every run its
cacheReadequals the parent's own read for that prefix (5141 vs 5066 is just two different conversations).Parent requests are unchanged. Breakpoint placement is identical, and per-request reads and writes are in the same range: totals 13796/6428 before vs 13649/6401 after.
Cost per fork with the 5-minute TTL: the tail moves from cache write (1.25x) to plain input (1x), saving 0.25 × ~900–1000 ≈ 230–250 input-token equivalents. That is about 19% of the fork's prompt cost (1st fork in run A: 1585 → 1277 input-token units). With the 1-hour TTL (2x write), the saving is 1.0 × tail, about 44%.
CLIProxy (
cliproxy/claude-haiku-5-5,cliproxy/claude-opus-5-5): no change, either wayThe proxy adds its own trailing cache breakpoint: every request on this route, parent or fork, reports
input2–4. So the fork's tail is cached no matter where OpenClaw puts its checkpoints. Before vs after, Haiku first fork: 4243/907 vs 4253/957 (read/write). Opus first fork: 4264/824 vs 4277/846. Reads are unchanged.Dependency on #197203 (already merged)
Without #197203, forks run with thinking disabled, so their prefix differs from the parent's from the first thinking block on. They then read cache entries written by earlier forks. On that base this change made later forks more expensive on the direct API (2nd fork read/write/input 4460/872/4 → 4033/423/866). With #197203 on
main, forks read the parent's prefix, and the numbers above apply.Tests
session-fork.test.tsin-flight tool-call case now checks that the Anthropic fork body keeps a checkpoint on the parent's message, and has none on the placeholder result or the question. It fails onmainand passes here.server-plugin-subagent-runtime.fork-transport.test.ts: the fork's question now goes out as plain string content because it no longer carriescache_control. The expectation is updated to match.session-fork-run,embedded-agent-runner.session-fork,server-plugin-subagent-runtime.fork,llm-idle-timeout.codex-ws-chain) andanthropic-payload-policy.test.ts.check-test-lines-ratchet), no allocation file.OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 pnpm check:changed: clean.Not covered
openai-completions-cache-control.ts, used by OpenRouter Anthropic) still marks the fork's last message. This was not measured live, so it is left as a follow-up.