Skip to content

fix(anthropic): new sessions rewrite the whole dynamic system prompt to the prompt cache - #196461

Closed
scoootscooob wants to merge 2 commits into
mainfrom
fix/anthropic-session-shared-system-cache
Closed

scoootscooob wants to merge 2 commits into
mainfrom
fix/anthropic-session-shared-system-cache

Conversation

@scoootscooob

@scoootscooob scoootscooob commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Fixes: on Anthropic models, every new session writes the whole dynamic part of the system prompt (tooling, skills, memory, messaging guidance, about 27,000 characters in 2026.11.2) to the prompt cache again, even when another session of the same agent sent identical text moments earlier.

User Impact

User impact: starting a session on an Anthropic model costs less when another session of the same agent started recently. Deployments that open many short sessions (one per DM or channel, sub-agents, cron runs, evals) see the largest change. No configuration is needed and nothing changes for other providers.

Tradeoff to be aware of: a session's opening request now has one history checkpoint instead of two. Every later request is unchanged and keeps both.

Why This Change Was Made

The Anthropic transport places one checkpoint after the stable system prefix and leaves the dynamic suffix to the message checkpoints. That suffix ends with the Runtime: facts, which name the session, so the first cache entry that covers the suffix is always specific to one session.

The prompt builder already delimits the Runtime facts with the relocatable boundary. This change splits the dynamic suffix there and, only on a request with no assistant turn yet, spends one of the two history checkpoints on the text before it. All four checkpoints were already in use, so the opening request is the one place a checkpoint can be spared: it has no earlier history write to keep reachable. Once the session has history, the same three system blocks are sent with the checkpoint removed, and those requests still read the cached prefix through the history checkpoints.

Limits:

  • Dynamic sections that sit before the Runtime facts and differ per session (conversation context, watched sessions) still make the shared block session-specific for those sessions. They pay what they pay today. Moving those sections below the invariant ones would extend the benefit and is not part of this change.
  • The shared entry is refreshed when a session opens, not on every request, so the saving applies to sessions that start within the cache lifetime of the previous session start.
  • The system prompt is now sent as three text blocks instead of two, which is a one-time cache miss on upgrade.

Evidence

Where it showed up: a 320-trial harness comparison on claude-haiku-5-5 (20 short multi-conversation tasks, 2.25 sessions per trial), with provider-reported usage read at a metering proxy.

Build Cache-write tokens on a session's first request Share of trial cost
2026.10.6 2,643 10%
2026.11.2 10,995 31%

In the captured request bodies, the second system block of consecutive sessions was byte-identical up to session= in the Runtime line (offset 26,978 of 27,257 characters in 2026.11.2).

Live check of the mechanism against the Anthropic API (claude-haiku-5-5; system text of about 9,100 + 18,000 tokens, then a Runtime line, then one user message; token counts are the API's):

Request Cache write Cache read
Current layout, first session 29,549 0
Current layout, second session 20,430 9,119
With the checkpoint, second session after one write 2,424 27,125
Same session, next turn, checkpoint removed 9 29,549

The last row is the property the "opening request only" rule depends on: a later request without the system checkpoint still reads everything.

Tests:

  • The existing native-Anthropic system-block test in packages/ai/src/providers/anthropic.test.ts now pins the new layout. It fails on main's transport and passes with the change. It covers the opening request (three blocks, shared block marked, one history checkpoint) and a request with history (shared block unmarked, two history checkpoints). Net test lines: -2.
  • vitest run packages/ai/src/: 2,402 pass and 6 fail on my machine; the 6 are OpenAI WebSocket retention fixtures that need --expose-gc and fail the same way without the change.
  • oxlint and oxfmt --check on both files: clean. pnpm tsgo:core: clean.

Not done: I have not run an agent built from this branch end to end and measured its cost. The numbers above are from released builds plus the direct API check.

🤖 Generated with Claude Code

…to the prompt cache

The Anthropic transport puts one cache checkpoint after the stable system
prefix and leaves the dynamic suffix (tooling, skills, memory, messaging)
to the history checkpoints. That suffix ends with the Runtime facts, which
name the session, so every new session wrote all of it again even though
the text before the Runtime facts is the same for every session of an agent.

Split the suffix at the Runtime region and, on a session's opening request
only, spend one of the two history checkpoints on the part before it. Later
requests keep both history checkpoints and send the same blocks unmarked.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 10, 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
… system-block test

The provider test that pins native Anthropic system blocks expected the old
two-block layout. Assert the new layout there, for an opening request and for
a request with history, instead of adding a separate test, so the test-line
ceiling is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@vincentkoc vincentkoc self-assigned this Nov 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
@vincentkoc

vincentkoc commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Thanks, Scott. The checkpoint placement is useful, but the split currently trims the newline between the shared guidance and Runtime:. The provider test expects the trimmed blocks, so it cannot catch the prompt-text change. Maintainer edits are disabled on this branch, so I opened #196471 with the newline preserved, a prompt-text assertion, and your contribution credited in the commit. The replacement landed as e952893. I’m closing this superseded PR now.

@clawsweeper

clawsweeper Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR checkpoints reusable dynamic system text before session-specific Runtime facts on opening Anthropic requests.

Example: Sessions alpha and beta use identical agent instructions within the provider cache lifetime.

  • Before: The shared instructions and Runtime session identifier occupy one block, so beta rewrites the shared instructions.
  • After: An opening-request checkpoint lets beta reuse the instructions while writing its own Runtime facts and message.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused patch is coherent and has useful request-boundary coverage, while supplied live measurements establish the mechanism rather than the branch-built behavior.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Starting another Anthropic session can repeatedly pay to cache unchanged agent instructions.
Reason: The maintainer-authored direction addresses measured recurring cost, preserves instruction authority and existing settings, and explicitly accepts the opening-checkpoint and cold-cache tradeoffs.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a current cache-write inefficiency with a focused change; no introduced production correctness or security defect was found.

Priority: P2
Reviewed head: 7fd9039f4af323697647c088c6a375855e52b561

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Supply a branch-built OpenClaw agent capture covering two fresh same-agent sessions and a follow-up, with provider cache usage and emitted checkpoints; the body reports red-on-base/green-on-head regression results, which this read-only review did not rerun.
Agent review details

How this fits together

The Anthropic payload policy converts prepared system prompts, tools, and conversation history into provider request blocks and allocates their four cache checkpoints.

flowchart LR
A[Prepared agent prompt] --> B[Anthropic payload policy]
C[Tools and conversation history] --> B
B --> D[Stable system prefix]
B --> E[Shared dynamic instructions]
B --> F[Session Runtime facts]
D --> G[Anthropic request]
E --> G
F --> G
Loading

Technical review

Best possible solution:

Keep the existing payload owner and split only at the producer-delimited Runtime boundary, retaining both history checkpoints after assistant history exists.

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

Current-main source places shared dynamic instructions and session-specific Runtime facts in the same unchecked suffix, matching the reported cross-session rewrite mechanism; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The change uses the existing marker parser, prepared-prompt lifetime, and checkpoint allocator without relocating instructions or adding configuration; the added state is weakly held eligibility metadata rather than another prompt cache.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Stable-prefix and dynamic-suffix cache layout changes intended behavior with a stated reason (64f2890: Preserve stable system-prefix reuse when dynamic additions change, as explained in fix(agents): split system prompt cache prefix by transport #59054.)
  • Runtime marker cleanup and system authority keeps the original intent (5ae9013: Bound relocatable Runtime facts while keeping behavioral instructions at system authority and stripping internal markers on Anthropic requests.)
  • Two conversation checkpoints changes intended behavior with a stated reason (4895fbb: Keep previous conversation writes reachable when newly appended content exceeds the provider's lookup window.)
  • Prepared system-block reuse keeps the original intent (f1c9357: Normalize once per immutable prompt revision and cache policy while preserving editable request-local blocks.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit f1c9357 adds packages/ai/src/transports/anthropic-payload-policy.ts:213 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f1c935770852; files: packages/ai/src/transports/anthropic-payload-policy.ts)
  • Vincent Koc: Raw commit 64f2890 adds src/agents/anthropic-payload-policy.ts:73 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 64f28906de09; files: src/agents/anthropic-payload-policy.ts)
  • georg wiltschek: Raw commit 5ae9013 adds packages/ai/src/transports/anthropic-payload-policy.ts:274 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5ae901326b85; files: packages/ai/src/transports/anthropic-payload-policy.ts)

PR surface

Source +42, Tests -2. Total +40 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 59 17 +42
Tests 1 25 27 -2
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 84 44 +40

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.

Review metrics

Metric Value Why it matters
Production versus test delta Production +42 lines; tests −2 lines Production growth implements the additional split and carries checkpoint eligibility through editable prepared-prompt copies; regression coverage extends an existing test.

Labels

Label changes:

  • add P2: Repeated short Anthropic sessions incur avoidable cache-write costs, while message delivery and core availability remain intact.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Repeated short Anthropic sessions incur avoidable cache-write costs, while message delivery and core availability remain intact.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Provide branch-built agent request and usage evidence for two fresh sessions and a same-session follow-up.

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.

Reviewed November 10, 2026, 12:58 AM ET / 05:58 UTC.

@vincentkoc vincentkoc closed this Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S 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.

2 participants