Skip to content

The agent that grows with you

perf(prompt-caching): copy only mutable cache-plan rows

Xipong774df367ee92
diff --git a/agent/prompt_caching.py b/agent/prompt_caching.py
index eeab76297bd..05491f00669 100644
--- a/agent/prompt_caching.py
+++ b/agent/prompt_caching.py
@@ -262,10 +262,14 @@ def build_prompt_cache_plan(
cache_ttl: str = "5m", native_anthropic: bool = False, static_system_prefix: str | None = None,
direct_native_tool_cache: bool = False, tool_part_markers: bool = True,
) -> PromptCachePlan:
- """Build isolated cache sections for one resolved request destination
+ """Build copy-on-write cache sections for one resolved request destination
(``tool_part_markers=False`` keeps markers off role:tool parts on LiteLLM-style routes)."""
- messages = copy.deepcopy(api_messages or [])
- strip_anthropic_cache_control(messages)
+ messages = list(api_messages or [])
+ for i, msg in enumerate(messages):
+ if isinstance(msg, dict) and (
+ "cache_control" in msg or isinstance(msg.get("content"), list)
+ ):
+ messages[i] = strip_anthropic_cache_control([dict(msg)])[0]
planned_tools = strip_anthropic_tool_cache_control(tools)
if not direct_native_tool_cache or not planned_tools:
@@ -278,10 +282,12 @@ def build_prompt_cache_plan(
if messages and isinstance(messages[0], dict) and messages[0].get("role") == "system":
# Tool-cache layout: only the static prefix carries a system-side marker; the
# volatile suffix's budget is spent on the tools array.
+ messages[0] = copy.deepcopy(messages[0])
_apply_system_cache_markers(messages[0], marker, static_system_prefix,
native_anthropic=True, mark_suffix=False, fallback_to_whole=False)
planned_tools[-1]["cache_control"] = dict(marker)
for endpoint in _completed_transaction_endpoint_indexes(messages, native_anthropic=True)[-2:]:
+ messages[endpoint] = copy.deepcopy(messages[endpoint])
_apply_cache_marker(messages[endpoint], marker, native_anthropic=True)
return PromptCachePlan(messages=messages, tools=planned_tools)
diff --git a/tests/agent/test_prompt_caching.py b/tests/agent/test_prompt_caching.py
index ea317196339..f4179ac5bea 100644
--- a/tests/agent/test_prompt_caching.py
+++ b/tests/agent/test_prompt_caching.py
@@ -116,6 +116,60 @@ class TestPromptCachePlan:
assert plan.tools[-1]["cache_control"] == MARKER
assert _count_cache_markers(plan.messages, plan.tools) == 4
+ def test_shares_only_unmodified_history_rows(self):
+ """Request-local planning copies marker carriers, not the entire transcript."""
+ messages = _tool_heavy_native_history() + [
+ {"role": "user", "content": "third request"},
+ {
+ "role": "assistant", "content": "",
+ "tool_calls": [{
+ "id": "third",
+ "function": {"name": "tool_02", "arguments": "{}"},
+ }],
+ },
+ {"role": "tool", "tool_call_id": "third", "content": "third result"},
+ ]
+ tools = _tool_heavy_native_tools()
+
+ for direct_tool_cache in (False, True):
+ original = copy.deepcopy(messages)
+ plan = build_prompt_cache_plan(
+ messages,
+ tools,
+ native_anthropic=True,
+ static_system_prefix="stable prefix",
+ direct_native_tool_cache=direct_tool_cache,
+ )
+
+ assert messages == original
+ assert plan.messages is not messages
+ assert plan.messages[1] is messages[1]
+ assert plan.messages[0] is not messages[0]
+ assert plan.messages[-1] is not messages[-1]
+
+ def test_unmarked_text_parts_keep_string_equivalent_cache_plan(self):
+ """Planner cleanup preserves plain-text canonicalization without stale markers."""
+ plain = _tool_heavy_native_history()
+ part_form = copy.deepcopy(plain)
+ part_form[0]["content"] = [
+ {"type": "text", "text": "stable prefix"},
+ {"type": "text", "text": plain[0]["content"][len("stable prefix"):]},
+ ]
+ part_form[1]["content"] = [{"type": "text", "text": plain[1]["content"]}]
+ original = copy.deepcopy(part_form)
+ for native in (False, True):
+ for direct in (False, True):
+ actual = build_prompt_cache_plan(
+ part_form, _tool_heavy_native_tools(), native_anthropic=native,
+ direct_native_tool_cache=direct, static_system_prefix="stable prefix",
+ )
+ expected = build_prompt_cache_plan(
+ plain, _tool_heavy_native_tools(), native_anthropic=native,
+ direct_native_tool_cache=direct, static_system_prefix="stable prefix",
+ )
+ assert actual == expected
+ assert part_form == original
+
def test_unmarkable_endpoint_does_not_consume_a_slot(self):
messages = [
{"role": "system", "content": "stable prefix\nvolatile"},