Skip to content

fix(agents): stop Anthropic session forks from caching their own suffix - #197224

Merged
obviyus merged 2 commits into
mainfrom
openclaw/fork-question-cache
Nov 11, 2026
Merged

obviyus merged 2 commits into
mainfrom
openclaw/fork-question-cache

Conversation

@obviyus

@obviyus obviyus commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

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 fork's appended question, and
  • whatever the parent appended after its latest response (the tool result the parent is about to send).

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

  • The fork marks its own suffix: everything after the parent's latest assistant response (late or placeholder tool results), plus the question. It marks shallow copies, so the parent's transcript is never changed.
  • The Anthropic transport treats a marked message like a non-retained runtime-context message and places no checkpoint on or after it. The existing opt-out-index path does this. The history checkpoints then move onto the parent's prefix. That prefix is the input of the parent's latest call, which the parent already cached.

Owner: buildAnthropicRequest → applyAnthropicRequestCacheControl (packages/ai/src/transports/anthropic-payload-policy.ts). The fork marks in runEmbeddedSessionFork (src/agents/embedded-agent-runner/session-fork.ts).

Live evidence

Isolated Gateway, real providers. One parent turn with 3 session_status calls, Advisor everyToolCalls: 1, thinkingDefault: high. Base is main with #197203 (fork thinking level) merged. Usage is per fork request from the provider response. Run A is on current main (merged #197203). Run B is on the earlier main with #197203's identical diff cherry-picked.

Direct Anthropic API (anthropic/claude-haiku-5-5), two runs per side

run fork before: input / cacheRead / cacheWrite after: input / cacheRead / cacheWrite
A 1st 4 / 4044 / 941 873 / 4044 / 0
A 2nd 4 / 5141 / 974 1020 / 5066 / 0
B 1st 4 / 4046 / 892 909 / 4055 / 0
B 2nd 4 / 5092 / 1002 1199 / 5121 / 0

Rebased 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.ts identical to the old head). Two fresh runs on the rebased head:

run fork input / cacheRead / cacheWrite parent's read for that prefix
C 1st 864 / 4103 / 0 4103
C 2nd 877 / 4589 / 0 4589
D 1st 957 / 4107 / 0 4107
D 2nd aborted by Advisor when the run ended (no usage) 4686
  • 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_choice is {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 cacheRead equals 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 way

The proxy adds its own trailing cache breakpoint: every request on this route, parent or fork, reports input 2–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

  • The session-fork.test.ts in-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 on main and 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 carries cache_control. The expectation is updated to match.
  • Also passing: the fork consumers (session-fork-run, embedded-agent-runner.session-fork, server-plugin-subagent-runtime.fork, llm-idle-timeout.codex-ws-chain) and anthropic-payload-policy.test.ts.
  • Net test lines: −1 (check-test-lines-ratchet), no allocation file.
  • OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 pnpm check:changed: clean.

Not covered

  • The OpenAI-compatible Anthropic cache format (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.
  • A fork taken before the parent's first response has no parent response to anchor on, so it marks only its question.

@clawsweeper

clawsweeper Bot commented Nov 11, 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 gateway Gateway runtime agents Agent runtime and tooling size: XS labels Nov 11, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 11, 2026
@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: The recorded first fork reads 4044 cached tokens and writes another 941 tokens.
  • After: The corresponding fixed run reads 4044 cached tokens and writes zero tokens.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, measured repair with relevant transport-boundary regression coverage and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied isolated-Gateway Advisor runs exercise the changed fork owner through real Anthropic requests, including the reviewed head, and record zero private-suffix cache writes while preserving parent-prefix reads; proxy limitations are explicitly distinguished.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Anthropic background reviews pay a cache-write premium for private suffix tokens that later parent requests do not reuse.
Reason: The collaborator-authored direction has owner approval under the review rules, and measured provider usage supports the narrow cost reduction.

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
Reviewed head: 012922835412dcd653b4af7ca687d559f97d4609

Before merge

None.

Findings

None.

Agent review details

How this fits together

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

Technical review

Best 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

  • Session-fork suffix changes intended behavior with a stated reason (164bd67: Full-context background questions reuse the parent's prepared prefix while remaining tool-free and ephemeral.)
  • Lazy fork preparation keeps the original intent (cb00966: Prepare forks only when requested, borrowing live context or reconstructing persisted history instead of capturing every parent request.)
  • Anthropic message projection and checkpoint policy keeps the original intent (f20d1f4: Reuse frozen message projections and request fragments while preserving editable payloads and request-specific cache checkpoints.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 164bd67 adds src/agents/embedded-agent-runner/session-fork.ts:202 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 164bd6756af1; files: src/agents/embedded-agent-runner/session-fork.ts)

PR surface

Source +28, Tests -1. Total +27 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 31 3 +28
Tests 2 6 7 -1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 37 10 +27

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Unnecessary cache-write charges affect direct Anthropic background forks, with limited scope and no demonstrated workflow outage.
  • 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.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-11T13:23:33.015Z sha cf46cdccf84bf43a038acd788ede9ee5b2ab0c06 :: needs maintainer review before merge. :: none

Reviewed November 11, 2026, 9:53 AM ET / 14:53 UTC (Revision 2).

@obviyus
obviyus force-pushed the openclaw/fork-question-cache branch from cf46cdc to 0129228 Compare November 11, 2026 14:20
@obviyus

obviyus commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 11, 2026
@obviyus
obviyus merged commit 83fd655 into main Nov 11, 2026
141 checks passed
@obviyus
obviyus deleted the openclaw/fork-question-cache branch November 11, 2026 15:04
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 12, 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 gateway Gateway runtime 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: XS 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