Skip to content

fix(agents): pin the session system prompt on every Anthropic Messages route - #197925

Merged
obviyus merged 3 commits into
mainfrom
fix/prompt-cache-frozen-system-prompt
Nov 13, 2026
Merged

obviyus merged 3 commits into
mainfrom
fix/prompt-cache-frozen-system-prompt

Conversation

@obviyus

@obviyus obviyus commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Anthropic caches tools, then system, then messages. Any byte change in the system prompt therefore re-writes the whole conversation at cache-write price.

OpenClaw already has the right mechanism: a per-session system prompt series (session-prompt-state.ts, prepareSessionSystemPrompt). It pins the admitted prompt and appends only changed, added or removed sections as a prompt-update delta after the conversation prefix. But the series was gated on inHistorySystemUpdates, which is true only for direct API-key Claude 5 routes (api.anthropic.com, no OAuth) and native OpenAI Responses (transcript-policy.ts). Every other Anthropic Messages route re-rendered the full prompt on every attempt (attempt-session-runtime-prepare.ts): proxies and custom base URLs, OAuth, Vertex and Foundry.

On a production gateway behind a proxy route, 82 of 95 cache breaks that happened within the 5-minute cache window on one day were system-prompt changes. The causes included exec and tool-handoff wakes, sessions_send and subagent-settle turns, skill snapshot refreshes (including remote-node availability), and workspace-file edits.

Fix

  • The transcript policy gets a separate pinnedSystemPrompt flag. It is true for every anthropic-messages route and for every route that already had inHistorySystemUpdates.
  • The series, its route-retirement check (beginSessionSystemPrompt) and its checkpoint persistence key on pinnedSystemPrompt. Without the checkpoint, the pin would not survive a gateway restart.
  • inHistorySystemUpdates keeps meaning "this route accepts mid-conversation system messages". Where it is false, the existing LLM boundary already projects the delta as a plain user-role note. No new wire format is needed.
  • Bedrock Converse is not included. I did not verify its transport with the user-role delta.

Proof

Real route, before vs after. Isolated throwaway Gateway (scratch state, no channels), Claude Opus 5.5 through an Anthropic-compatible custom base URL proxy (the previously ungated case), cacheRetention: short. A logging proxy recorded the provider's own cache_read_input_tokens / cache_creation_input_tokens and a digest of the sent system prompt. User turns were sent as an operator UI client through chat.send.

One target session went through:

  1. a user turn;
  2. a turn that starts a background exec, then its completion wake;
  3. another session's sessions_send into it;
  4. a skill added to the workspace;
  5. a workspace bootstrap file (USER.md) edited;
  6. a subagent spawned and settled;
  7. a final user turn.
target-session requests (11) before (main) after
distinct system prompts 6 1
requests that re-wrote > 15k tokens 6 2
total cache read / write 255.0k / 146.5k 425.0k / 76.3k
  • Before: the wake, sessions_send, skill add, file edit and subagent settle each re-wrote 20–28k tokens (the whole conversation).
  • After: each later request reads the full previous prefix. The writes at those points are the appended delta, 0.4k–10k.
  • The two remaining large writes are turn 1 (cold) and turn 2. Turn 2's request is byte-identical to turn 1's prefix (system text, tools and messages compared from captured bodies). The same turn-2 miss appeared intermittently in other arms, and it hit in the baseline arm. It is upstream routing on this proxy, not OpenClaw bytes.
  • In production, each avoided break is a re-write of the whole conversation (median about 420k tokens), not ~25k.
  • The deltas arrive as user-role notes holding only the changed sections, for example ## Tooling, ## Session routing after a sessions_send turn and ## Skills after the skill add.

Focused tests:

  • transcript-policy.test.ts: the route table now asserts pinnedSystemPrompt for direct API key, OAuth, proxy base URL, Vertex and Foundry Anthropic Messages, and not for Bedrock. inHistorySystemUpdates is unchanged.
  • attempt-session-runtime-prepare.test.ts (fails on the base, passes here): with the policy resolved for a proxy Anthropic Messages route (inHistorySystemUpdates: false), session runtime preparation keeps the admitted system prompt when the next turn renders without the task-suggestion grant, and emits the Tooling delta.
  • embedded-agent-runner.prompt-cache.test.ts (existing request-prefix suite, both Anthropic Messages variants) and the session runtime / prompt-phase / LLM boundary suites pass.

Not covered (follow-ups)

@clawsweeper

clawsweeper Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@obviyus

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: anthropic size: S labels Nov 12, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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. labels Nov 12, 2026
@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR pins session system prompts across Anthropic Messages routes and sends subsequent instruction changes as appended notes.

Example: A custom-base-URL Anthropic session receives completion wakes, skill updates, and workspace edits across 11 provider requests.

  • Before: The supplied Gateway comparison recorded six distinct system prompts and 146.5k cache-write tokens.
  • After: The comparison recorded one system prompt and 76.3k cache-write tokens, with changed instructions delivered as appended notes.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused repair with real proxy-route evidence, a meaningful caller regression, and no remaining findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied before/after output exercises chat.send through an isolated Gateway and real custom-base-URL Anthropic route, including wakes, inter-session input, skill and workspace updates, and subagent settlement; request comparisons show a stable system prompt with appended instruction deltas.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Anthropic Messages sessions behind proxies and other excluded routes repeatedly pay to rewrite cached conversation prefixes when instructions change.
Reason: The measured cache-write reduction supports a small repair to existing infrastructure, and collaborator authorship supplies the direction decision.

Merge readiness

✅ Ready for maintainer review

This PR addresses a demonstrated prompt-cache problem using the existing session owner; the prior typing finding is fixed, and no actionable defects remain.

Priority: P2
Reviewed head: 30aea6f4516fdf0a3eb946c039d3f49b15a22dbd

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded agent runner resolves transport capabilities, prepares a transcript-backed session prompt, and projects instruction updates into provider-compatible messages.

flowchart LR
  A[Provider and model route] --> B[Transcript policy]
  B --> C[Session runtime preparation]
  C --> D[Session prompt owner]
  D --> E[Transcript checkpoint]
  D --> F[Message projection]
  F --> G[Anthropic Messages request]
Loading

Technical review

Best possible solution:

Use the existing transcript-backed prompt series for Anthropic Messages routes while retaining transport-specific message projection.

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

Current-main source exposes the narrow capability gate, and the supplied real Gateway comparison demonstrates the affected proxy flow; this review executed no target code.

Is this the best way to solve the issue?

Separating prompt pinning from system-message support is the smallest complete repair because the session owner, checkpoint format, and user-role projection already exist.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Anthropic route eligibility changes intended behavior with a stated reason (46ab36a: The original implementation limited in-history system messages to supported direct API-key routes and preserved other transports.)
  • Complete session prompt and checkpoint ownership keeps the original intent (a79e29e: Preserve the complete admitted system prompt across instruction refreshes and restore the series from transcript checkpoints.)
  • Prompt versus ranking-only persistence keeps the original intent (8a328bf: Ranking can install a prompt updater without enabling a pinned prompt series.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +13, Tests +38, Docs +4. Total +55 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 21 8 +13
Tests 2 46 8 +38
Docs 1 5 1 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 72 17 +55

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 changes Production +21/-8 lines; tests +46/-8 lines The modest growth separates two transport capabilities and adds a focused caller regression while reusing existing state and projection machinery.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Repeated system-prompt changes cause avoidable full-conversation cache writes on affected Anthropic Messages routes.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • 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 (3 earlier review cycles)
  • reviewed 2026-11-12T21:34:08.370Z sha c04b926 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-12T21:44:37.638Z sha 73bb9f5 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-13T04:01:14.610Z sha e1cac43 :: needs changes before merge. :: [P2] Narrow the optional commit callback before invoking it

Reviewed November 12, 2026, 11:12 PM ET / November 13, 2026, 04:12 UTC (Revision 4).

@obviyus

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 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. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 12, 2026
obviyus and others added 2 commits November 13, 2026 09:20
…s route

Anthropic caches tools, then system, then messages, so any system-prompt change re-writes the whole conversation. The session prompt series (pinned prompt plus appended section deltas) ran only on direct API-key Claude 5 routes and native OpenAI Responses. Every other Anthropic Messages route (proxies and custom base URLs, OAuth, Vertex, Foundry) re-rendered the prompt each attempt, so wakes, inter-session turns, skill or node changes and workspace edits each re-wrote the conversation.

The transcript policy now has a separate pinnedSystemPrompt flag, true for every anthropic-messages route. The series, its retirement check and its checkpoint persistence key on that flag. Where the route cannot send mid-conversation system messages, the existing LLM boundary already projects the delta as a user-role note. The in-history system capability itself is unchanged.

Real route (custom base URL proxy, cacheRetention short): one target session through user turns, an exec wake, sessions_send, a skill add, a workspace-file edit and a subagent settle. System prompts per session 6 -> 1; full re-writes 6 -> 2; session cache writes 146.5k -> 76.3k.

Co-authored-by: obviyus <[email protected]>
…e preparation

The helper-level loop exercised unchanged code. The runtime test resolves the policy for a proxy Anthropic Messages route and fails on the base.

Co-authored-by: obviyus <[email protected]>
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus force-pushed the fix/prompt-cache-frozen-system-prompt branch from 73bb9f5 to e1cac43 Compare November 13, 2026 03:54
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Nov 13, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 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. 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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@obviyus
obviyus merged commit d4577ec into main Nov 13, 2026
126 checks passed
@obviyus
obviyus deleted the fix/prompt-cache-frozen-system-prompt branch November 13, 2026 04:29
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 14, 2026
RomneyDa added a commit that referenced this pull request Nov 16, 2026
…s route (#197925)

Co-authored-by: obviyus <[email protected]>
(cherry picked from commit d4577ec)
Co-authored-by: RomneyDa <[email protected]>
Backport-adaptation: Preserve beta.4 transcript branch reader and existing tool-pin lifecycle; exclude main-only usage-ranking and GitHub-listing features. Apply pinned prompt condition and canonical proxy regression only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: anthropic 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: 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.

1 participant