Skip to content

The agent that grows with you

refactor(prompt_caching): shallow strip copy, exact-count guards, dedupe idempotency tests

kshitijk4poorc26357ad6ada
diff --git a/agent/prompt_caching.py b/agent/prompt_caching.py
index 433da9ae664..2304c9ddd21 100644
--- a/agent/prompt_caching.py
+++ b/agent/prompt_caching.py
@@ -446,10 +446,12 @@ def apply_anthropic_cache_control(
is retained.
Idempotent: pre-existing ``cache_control`` markers are stripped from a
- deep copy before new ones are placed, so calling this twice (or handing
- it messages a prior call already marked) can never accumulate past 4
- markers. Only messages that already carry a marker pay the deep-copy
- cost; the rest of the copy-on-write contract is unchanged (#90971).
+ per-message copy before new ones are placed, so calling this twice (or
+ handing it messages a prior call already marked) can never accumulate
+ past 4 markers. Only messages that already carry a marker pay the copy
+ cost — a shallow top-level copy suffices because
+ :func:`strip_anthropic_cache_control` is copy-on-write on content parts —
+ and the rest of the copy-on-write contract is unchanged (#90971).
Returns:
Shallow copy of message list with selective deep copies of modified messages.
@@ -469,7 +471,10 @@ def apply_anthropic_cache_control(
and any(isinstance(part, dict) and "cache_control" in part for part in content)
)
if has_marker:
- messages[i] = strip_anthropic_cache_control([copy.deepcopy(msg)])[0]
+ # Shallow top-level copy is enough: strip pops the top-level key
+ # and rebuilds content lists/part dicts copy-on-write, so the
+ # caller's message (and any aliased parts) are never mutated.
+ messages[i] = strip_anthropic_cache_control([dict(msg)])[0]
breakpoints_used = 0
diff --git a/tests/agent/test_prompt_caching.py b/tests/agent/test_prompt_caching.py
index 59a253edbae..1e7a47709f8 100644
--- a/tests/agent/test_prompt_caching.py
+++ b/tests/agent/test_prompt_caching.py
@@ -1,10 +1,12 @@
"""Tests for agent/prompt_caching.py — Anthropic cache control injection."""
+import copy
from agent.prompt_caching import (
_apply_cache_marker,
_build_marker,
_can_carry_marker,
+ _count_cache_markers,
apply_anthropic_cache_control,
build_prompt_cache_plan,
effective_cache_ttl,
@@ -206,6 +208,12 @@ class TestCanCarryMarker:
assert _can_carry_marker({"role": "tool", "content": "result"}, native_anthropic=False) is True
assert _can_carry_marker({"role": "tool", "content": ""}, native_anthropic=False) is False
+ def test_native_anthropic_empty_assistant_still_carries_marker(self):
+ """Native envelope can attach a top-level marker even to an empty
+ assistant turn; only the OpenRouter-style layout must skip it.
+ """
+ assert _can_carry_marker({"role": "assistant", "content": None}, native_anthropic=True) is True
+
def test_openrouter_list_carrier_requires_last_part_dict(self):
"""Carrier predicate must agree with _apply_cache_marker, which only marks
the LAST content part. A list whose last element isn't a dict cannot carry
@@ -503,5 +511,98 @@ class TestEffectiveCacheTtl:
assert marker == {"type": "ephemeral", "ttl": "1h"}
+class TestApplyIdempotency:
+ """apply_anthropic_cache_control on pre-decorated input (#90971).
+
+ Before the idempotency fix, a second call on already-marked messages
+ pushed the marker total to 5, reproducing the ``cache_control can only
+ be specified up to 4 times`` HTTP 400.
+ """
+
+ @staticmethod
+ def _fixture_messages():
+ messages = [{"role": "system", "content": "STATIC_PREFIX rest of the prompt"}]
+ for i in range(8):
+ messages.append({"role": "user", "content": f"Hello {i}"})
+ messages.append({"role": "assistant", "content": f"Hi {i}"})
+ return messages
+
+ def test_empty_messages_is_noop(self):
+ assert apply_anthropic_cache_control([]) == []
+
+ def test_repeated_apply_is_idempotent_and_keeps_exact_layout(self):
+ """Repeated calls on the function's own output (no intervening
+ strip_anthropic_cache_control) must converge to the exact same
+ marker placement AND keep the intended four-breakpoint layout.
+ Structural equality alone would still pass if a later round moved
+ the breakpoints or dropped every marker; the exact count pins the
+ layout.
+ """
+ messages = self._fixture_messages()
+
+ round1 = apply_anthropic_cache_control(messages, static_system_prefix="STATIC_PREFIX")
+ round2 = apply_anthropic_cache_control(round1, static_system_prefix="STATIC_PREFIX")
+ round3 = apply_anthropic_cache_control(round2, static_system_prefix="STATIC_PREFIX")
+
+ assert round1 == round2 == round3
+ assert _count_cache_markers(round1, []) == 4
+
+ def test_does_not_mutate_caller_messages_with_stale_top_level_markers(self):
+ """A caller's live message list must never be mutated in place, even
+ when it already carries stale cache_control markers (e.g. replayed
+ history). The function's contract is copy-on-write.
+ """
+ caller_history = [
+ {"role": "user", "content": f"u{i}", "cache_control": {"type": "ephemeral"}}
+ for i in range(5)
+ ]
+ snapshot = copy.deepcopy(caller_history)
+
+ apply_anthropic_cache_control(caller_history)
+
+ assert caller_history == snapshot
+
+ def test_does_not_mutate_caller_messages_with_stale_part_markers(self):
+ """Same contract for the other detection branch: markers living on
+ content parts (the shape decoration itself produces), where part-dict
+ aliasing is the mutation risk.
+ """
+ caller_history = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": f"u{i}", "cache_control": {"type": "ephemeral"}},
+ {"type": "text", "text": "tail"},
+ ],
+ }
+ for i in range(5)
+ ]
+ snapshot = copy.deepcopy(caller_history)
+
+ result = apply_anthropic_cache_control(caller_history)
+
+ assert caller_history == snapshot
+ assert _count_cache_markers(result, []) <= 4
+
+ def test_direct_tool_cache_with_no_tools_falls_back_safely(self):
+ """direct_native_tool_cache=True with an empty tools list must fall
+ back to the message-only layout: exactly one marker per message here
+ (system + user + assistant), none on tools.
+ """
+ messages = [
+ {"role": "system", "content": "System prompt"},
+ {"role": "user", "content": "Question"},
+ {"role": "assistant", "content": "Answer"},
+ ]
+ plan = build_prompt_cache_plan(
+ messages,
+ [],
+ native_anthropic=True,
+ direct_native_tool_cache=True,
+ )
+ assert plan.marker_count == 3
+ assert len(plan.tools) == 0
+
+
diff --git a/tests/run_agent/test_prompt_caching_idempotency.py b/tests/run_agent/test_prompt_caching_idempotency.py
deleted file mode 100644
index b04f954a2b9..00000000000
--- a/tests/run_agent/test_prompt_caching_idempotency.py
+++ /dev/null
@@ -1,121 +0,0 @@
-"""Tests for Anthropic prompt caching idempotency and breakpoint bounds (#90971)."""
-
-import copy
-
-from agent.prompt_caching import (
- apply_anthropic_cache_control,
- build_prompt_cache_plan,
- _count_cache_markers,
- _can_carry_marker,
-)
-
-
-class TestPromptCachingIdempotency:
- def test_apply_anthropic_cache_control_empty_messages(self):
- """Empty messages list is a safe no-op."""
- assert apply_anthropic_cache_control([]) == []
-
- def test_apply_anthropic_cache_control_never_exceeds_four_markers(self):
- """Realistic conversations never push breakpoints_used past what
- _apply_system_cache_markers can return ({0, 1, 2}), so the marker
- total always stays within the 4-breakpoint API limit.
- """
- messages = [{"role": "system", "content": "STATIC_PREFIX rest of the prompt"}]
- for i in range(8):
- messages.append({"role": "user", "content": f"Hello {i}"})
- messages.append({"role": "assistant", "content": f"Hi {i}"})
-
- result = apply_anthropic_cache_control(messages, static_system_prefix="STATIC_PREFIX")
- assert _count_cache_markers(result, []) <= 4
-
- def test_apply_anthropic_cache_control_is_idempotent(self):
- """Calling apply_anthropic_cache_control repeatedly on its own output
- (no intervening strip_anthropic_cache_control) must converge to the
- exact same marker placement, not merely stay under budget: a test
- that only checks `<= 4` would still pass if a later round moved the
- breakpoints somewhere else, or dropped every marker. Before the
- idempotency fix, a second call on already-marked messages pushed the
- total to 5, reproducing the `cache_control can only be specified up
- to 4 times` HTTP 400 (#90971).
- """
- messages = [{"role": "system", "content": "STATIC_PREFIX rest of the prompt"}]
- for i in range(8):
- messages.append({"role": "user", "content": f"Hello {i}"})
- messages.append({"role": "assistant", "content": f"Hi {i}"})
-
- round1 = apply_anthropic_cache_control(messages, static_system_prefix="STATIC_PREFIX")
- round2 = apply_anthropic_cache_control(round1, static_system_prefix="STATIC_PREFIX")
- round3 = apply_anthropic_cache_control(round2, static_system_prefix="STATIC_PREFIX")
-
- assert round1 == round2 == round3
- assert _count_cache_markers(round1, []) <= 4
-
- def test_apply_anthropic_cache_control_does_not_mutate_caller_messages(self):
- """A caller's live message list must never be mutated in place, even
- when it already carries stale cache_control markers (e.g. replayed
- history). The function's contract is copy-on-write.
- """
- caller_history = [
- {"role": "user", "content": f"u{i}", "cache_control": {"type": "ephemeral"}}
- for i in range(5)
- ]
- snapshot = copy.deepcopy(caller_history)
-
- apply_anthropic_cache_control(caller_history)
-
- assert caller_history == snapshot
-
- def test_build_prompt_cache_plan_dynamic_tool_accounting(self):
- """build_prompt_cache_plan never exceeds 4 markers with tool-cache layout."""
- tools = [
- {"type": "function", "function": {"name": "tool_a"}},
- {"type": "function", "function": {"name": "tool_b"}},
- {"type": "function", "function": {"name": "tool_c"}},
- ]
- messages = [
- {"role": "system", "content": "PREFIX_STATIC System prompt"},
- {"role": "user", "content": "Run tool"},
- {"role": "assistant", "content": "Calling", "tool_calls": [{"name": "tool_a"}]},
- {"role": "tool", "content": "output", "tool_name": "tool_a"},
- {"role": "assistant", "content": "Done!"},
- ]
-
- plan = build_prompt_cache_plan(
- messages,
- tools,
- native_anthropic=True,
- direct_native_tool_cache=True,
- static_system_prefix="PREFIX_STATIC",
- )
-
- assert plan.marker_count <= 4
- # Exactly 1 tool marker on the last tool
- assert "cache_control" in plan.tools[-1]
- assert "cache_control" not in plan.tools[0]
- assert "cache_control" not in plan.tools[1]
-
- def test_build_prompt_cache_plan_direct_tool_cache_with_no_tools(self):
- """When direct_native_tool_cache=True but tools is empty, falls back safely."""
- messages = [
- {"role": "system", "content": "System prompt"},
- {"role": "user", "content": "Question"},
- {"role": "assistant", "content": "Answer"},
- ]
- plan = build_prompt_cache_plan(
- messages,
- [],
- native_anthropic=True,
- direct_native_tool_cache=True,
- )
- assert plan.marker_count <= 4
- assert len(plan.tools) == 0
-
- def test_can_carry_marker_envelope_vs_native(self):
- """_can_carry_marker properly filters empty turns on non-native layouts."""
- empty_assistant = {"role": "assistant", "content": None}
- assert _can_carry_marker(empty_assistant, native_anthropic=False) is False
- assert _can_carry_marker(empty_assistant, native_anthropic=True) is True
-
- normal_user = {"role": "user", "content": "Hello"}
- assert _can_carry_marker(normal_user, native_anthropic=False) is True
- assert _can_carry_marker(normal_user, native_anthropic=True) is True