Skip to content

[ENG-22237] fix(agents): new user messages rewrite the whole conversation into the prompt cache - #328

Merged
orswn merged 6 commits into
boonfrom
okka/eng-22237/stable-prompt-cache
Nov 5, 2026
Merged

orswn merged 6 commits into
boonfrom
okka/eng-22237/stable-prompt-cache

Conversation

@orswn

@orswn orswn commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: ENG-22237, openclaw#86063, openclaw#186434

What Problem This Solves

Fixes an issue where every new user message in Boon Web, Slack, or MS Teams rewrote the whole conversation into the Bedrock prompt cache, even when the previous message was seconds old.

  • One week of fleet session data (81 hosts, 19,775 Sonnet 5.5 calls) shows a cost of $1,486/week. Cache writes are 73% of that.
  • When a new user message came within 5 minutes, the cache was lost on 1,225 of 1,825 turns. Web threads lost it on 841 of 859 turns. Slack lost it on 229 of 246 and MS Teams on 127 of 136.
  • On those calls the cache read dropped to a fixed per-host value, which is the system prompt and tools. The rest of the history was written again at 1.25x the input price.
  • Tool-loop calls inside one turn were not affected (1.7% break).

The cause: openclaw sent the active user message with its inbound metadata (Conversation info, Sender, delivery hint) and hook context (Boon Web page and live integration status). The transcript stores the bare text, so on the next turn the same message went out without them. The bytes changed, so every message-level cache entry written during the turn missed.

Why This Change Was Made

The user message now has the same bytes when it is the active turn and when it is replayed as history. The per-turn context still reaches the model, but in a separate block.

  • Upstream backport. openclaw/openclaw f5931f5 (with c718afe and e17bc58) moves current-turn inbound metadata into the hidden runtime-context carrier. The cherry-picks keep (cherry picked from ...) and credit the upstream authors.
  • Hook context. before_prompt_build prependContext and appendContext go into the same carrier for persisted, non-runtime-only user turns. Upstream still adds them inline, so this part diverges from upstream. Runtime-only turns, and turns whose user message is not persisted, keep hook context inline. Inbound metadata follows the upstream rule and goes into the carrier on all non-runtime-only turns.
  • Carrier placement. Upstream puts the carrier at the end of the request. Two failure modes rule that out on this route:
  • Where the carrier goes now. It is placed right after the active user message. The managed Anthropic transport adds it to that user message as trailing text blocks. Those blocks never get cache_control. If the active user message converts to nothing, for example an image-only message on a text-only model, the carrier stays a separate uncached user turn. It never follows a tool_result. The cache markers stay on the user text and the latest tool_result. The model reads the carrier once per turn, next to the request it describes.
  • Cost of this placement. The tool-loop span of the previous turn is written again once on the next turn. It does not contain the carrier any more. Modeled on the fleet week this costs about $40/week. The upstream tail placement would avoid it.

Not in this PR:

  • No TTL change. The fleet keeps the 5-minute cache. A 1-hour TTL is a separate decision, to be made after this fix has real numbers.
  • The Bedrock Converse transport (extensions/amazon-bedrock) and the SDK Anthropic provider are not on the fleet path. They keep upstream behavior.
  • The llm_input / before_agent_run hook prompt and trajectory prompt now show the bare user text. The carrier with the context is in their messages. No bundled or Boon plugin reads that prompt field.

User Impact

  • A new message in an existing Boon Web, Slack, or MS Teams thread reads the earlier conversation from the prompt cache instead of writing it again.
  • Modeled on one week of fleet data, Sonnet 5.5 spend drops from about $1,531 to about $1,115 per week (-27%). This needs prod numbers after release to confirm.
  • Replies do not change. The agent still sees the sender, conversation, page, and integration status for each message.

Evidence

Local smoke on a prod-matched paid profile through the Boon Web chat, with Claude Sonnet 5.5 on Bedrock via boon-llm-gateway. Usage numbers come from the session usage. They match the gateway llm_request_logs rows on 135 of 135 calls.

First model call of each new user message, in a 7-message thread:

Message Before: cache read / write After: cache read / write
2 57,183 / 4,332 60,280 / 1,035
3 57,183 / 5,378 61,315 / 1,045
4 57,183 / 6,424 62,360 / 1,048
5 57,183 / 7,485 63,408 / 1,058
6 57,183 / 8,754 64,466 / 1,208
  • Before: the read stays at the system prompt plus tools. The write grows with the whole history.
  • After: the read covers the full prefix through the previous message. The write is the new turn only.
  • Input-equivalent cost for messages 2 to 6 is 13.3% lower. The thread history here is only about 5k tokens, and the gain grows with longer threads (fleet median context is 107k tokens).
  • Message 7 misses in both builds. Boon Web adds a product-help line to the system prompt on that turn type. That is not changed here.

Prompt tokens per model call, before and after

Behavior checks after the change:

  • 5 new chats asking "What is 17*23? Answer with the number only." all answered 391.
  • A thread with three sequential tool calls in one message finished with one visible reply. No call ended with an empty response (0 of 135 calls).
  • Across 14 user messages there was exactly 1 visible reply per message. This matches the base build.
  • Hook context is live. In the Boon Web side panel on the Data Review page, the carrier carries [BOON_UI_CONTEXT] path=/data_review and the user text block does not.
    • The agent answered "Which page am I looking at right now?" with "You're on the Data Review page (/data_review)."
    • The next message read 68,002 cached tokens through the previous user message and wrote 884.
  • Wire shape on every call of a turn: user [text (cache_control), carrier text]. Tool results carry no extra text.

Boon Web chat after the change

Tests:

  • New tests cover these cases:
    • byte stability of user turns with inbound metadata and hook context;
    • carrier placement and merging in the managed transport;
    • cache marker placement with the carrier present;
    • a 3-request prefix check (turn N call 1, a tool call, turn N+1).
  • Focused Vitest (25 files, 948 tests, including the lint suppression allowlist), tsgo (core, core tests, extensions), oxlint, oxfmt --check, and git diff --check pass.

orswn and others added 5 commits November 5, 2026 17:11
…ntext message for byte-stable prompt caching

The active user turn was decorated at request-build time with an inbound
metadata block (Conversation info / reply-target / sender / forwarded /
chat-history), but the session store persists the bare text and the LLM boundary
strips that block from historical replay. So a user message's serialized bytes
changed retroactively — decorated as the active turn, bare as history — on every
turn, invalidating any prefix/exact-match provider prompt cache from that point
onward, every turn. (openclaw#90811 fixed the timestamp half of this same asymmetry.)

Rework of the earlier "strip the active turn" approach (which lost model-visible
context — ClawSweeper's P1) into one that keeps the context AND recovers the
cache cost:

- Route current-turn inbound metadata out of the user prompt and into the hidden
  runtime-context custom message (the mechanism from openclaw#89428), and
  relocate that carrier to the ABSOLUTE TAIL of the wire request (after the
  active user turn and any tool-call scaffolding). The user turn stays bare and
  byte-identical in both the active and historical positions; the volatile
  carrier vanishes next turn exactly where the assistant reply begins anyway, so
  the request is an append-only prefix-extension through the active user turn.
- A durable marker (UserMessage.runtimeContextCarrier, set by convertToLlm from
  the carrier's details) lets the Anthropic SDK transport, the managed Anthropic
  transport (anthropic-transport-stream / anthropic-payload-policy), and
  OpenAI-completions skip the carrier when selecting the deepest cache_control
  breakpoint, keeping the anchor on the last stable user turn.

Storage stays BARE (invariant preserved); runtime-only turns (room events) keep
their existing inline behavior, which is byte-stable because room-event/system
context is not strip-eligible; legacy bare-stored sessions are unchanged.

Reviewed with adversarial gpt-5.5/codex sweeps (correctness, byte-identity,
compatibility, test adequacy): found + fixed the managed Anthropic transport
cache-anchor path and added the missing OpenAI-completions/managed-transport
breakpoint tests; a theoretical runtime-only mutation was verified unreachable
and pinned with a test. Final sweep clean.

Co-authored-by: openclaw#89428 (runtime-context handoff approach)
(cherry picked from commit f5931f5)

Co-authored-by: Peter Lindsey <[email protected]>
(cherry picked from commit c718afe)

Co-authored-by: Ayaan Zaidi <[email protected]>
* fix(agents): apply image context to current turn

* fix(agents): align runtime context with prompt order

* fix(agents): make turn context position independent

* fix(agents): bind internal context to the active user turn

Keep current-turn runtime context position-independent while preserving the shared privacy notice, runtime events, prompt-cache placement, and historical preface sanitization. Consolidate header detection in its existing owner and retain the original real turn-boundary regression.

Fixes openclaw#110672

Co-authored-by: chernoff-code <[email protected]>

---------

Co-authored-by: chernoff-code <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit e17bc58)

Co-authored-by: ℭ𝔥𝔢𝔯𝔫𝔬𝔣𝔣 <[email protected]>
The before_prompt_build hook prependContext and appendContext were
added only to the active user message. The transcript stores the bare
prompt, so the next turn replayed that user message without the hook
text. Its bytes changed between the two requests, and every
message-level prompt cache entry written during the turn missed. On
Boon Web every turn carries hook context (UI page and live integration
status), so each new user turn rewrote the whole conversation history
into the cache.

Route hook prompt context for persisted, non-runtime-only user turns
into the current-turn runtime-context carrier, next to the inbound
metadata. The active user message now has the same bytes as its
replayed form. Runtime-only turns and turns whose user message is not
persisted keep the hook context inline as before.

The carrier sits at the tail of the request. Claude 5.x on non-direct
anthropic-messages routes can answer a standalone trailing carrier
turn instead of the user (openclaw#186434). The managed Anthropic
transport therefore appends the carrier as trailing text blocks of the
preceding user message, and those blocks never receive cache_control.
Cache markers stay on the user text and the latest tool_result, so the
cached prefix of turn N is a prefix of every later request.

Refs: ENG-22237
…turn

The upstream cache fix moves the current-turn runtime-context carrier to
the absolute tail of every request. In a tool loop that puts the carrier
after each tool result. The carrier tells the model to continue
answering the active request and carries the channel delivery hint, so
after a message tool result Sonnet 5.5 sent the same answer again. A
local Boon Web run showed three message tool calls in one turn.

Place the carrier right after the active user message instead. The
managed Anthropic transport merges it into that user message as
uncached trailing text, so the model reads it once per turn, next to
the request it describes, and tool results carry no extra text.

The user message stays byte-identical across turns, so the next turn
still reads the cached prefix through it. The tool-loop span of the
previous turn is written again once, because the carrier is no longer
in it.

Refs: ENG-22237
@orswn
orswn requested a review from a team November 5, 2026 10:40

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 21 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/llm/providers/anthropic.ts Resolved
When the active user message converts to nothing, for example an
image-only message on a text-only model, the previous transport param
can be a tool result turn. The carrier then merged into it as text
after the tool results. That is the shape that made the model repeat
its answer. Merge the carrier only into a param that came from a user
message. Otherwise keep it as a separate uncached user turn.

Also drop the stale Bedrock Converse cache point note. With the
carrier placed after the active user message, tool loop requests end
with tool results, so the cache point no longer lands on the carrier.

Refs: ENG-22237
@orswn
orswn merged commit 12a6b79 into boon Nov 5, 2026
151 of 157 checks passed
@orswn
orswn deleted the okka/eng-22237/stable-prompt-cache branch November 5, 2026 11:40
orswn added a commit that referenced this pull request Nov 9, 2026
Cut the fork release for the PRs merged to boon after the
v2026.6.35-boon.4 tag:

- #328 (ENG-22237): replayed user turns keep the same bytes, so a new
  user message in Boon Web, Slack and MS Teams reads the previous
  prompt from cache instead of writing the whole history again.
- #280 (ENG-21157): opt-in model compat flag
  requiresGoogleThoughtSignatures, so Gemini 3 tool loops work behind
  an OpenAI-compatible proxy. No fleet model config sets it yet.
- #327: the v2026.6.35-boon.4 tag was cut from the PR branch. The
  review fixes that merged after it change tests and one comment only.

Bump the root package.json and npm-shrinkwrap.json, all 136 bundled
plugin manifests (scripts/sync-plugin-versions.ts), and the version and
openclaw peer floor in every extension npm-shrinkwrap.json
(scripts/generate-npm-shrinkwrap.mjs --all). The regeneration also
picks up the registry's updated deprecation text for @smithy/core
3.24.6 in amazon-bedrock, amazon-bedrock-mantle and tlon; no resolved
version or integrity changes. Add the 2026.6.35-boon.5 CHANGELOG.md
section. No source or dependency change beyond the merged PRs above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants