The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): restrict strip flatten to decoration-produced shapes
kshitijk4poor2322f0dcca68
diff --git a/agent/prompt_caching.py b/agent/prompt_caching.pyindex 9efd9d8c647..2e606cd377c 100644--- a/agent/prompt_caching.py+++ b/agent/prompt_caching.py@@ -122,19 +122,25 @@ def _apply_system_cache_markers(def strip_anthropic_cache_control(api_messages: List[Dict[str, Any]],) -> List[Dict[str, Any]]:- """Remove ``cache_control`` markers and flatten pure-text content lists.+ """Remove ``cache_control`` markers and undo decoration-produced list shapes.Used before re-applying decoration after a mid-turn provider failover sothe mutated, undecorated shape (image shrink / ASCII cleanup / etc.) ispreserved while markers match the *new* provider's cache policy (#72626).- Pure-text content lists (including the ``[static, volatile]`` system- layout) are flattened back to a single string so- :func:`apply_anthropic_cache_control` can re-split them. Multimodal- content lists keep their part structure; only per-part markers are- removed.-- Mutates ``api_messages`` in place and returns the same list.+ Flattening back to a plain string is restricted to the exact shapes+ :func:`apply_anthropic_cache_control` produces from string content —+ a single ``{"type": "text"}`` part, or the two-part ``[static, volatile]``+ system split — so the ``""``-join is provably byte-exact. Organic+ multi-part text (merged user turns, imported transcripts) and parts+ carrying extra keys (``citations`` etc.) keep their structure; only+ per-part markers are removed. Marker removal is copy-on-write on the+ part dicts: content parts may alias the persistent conversation history+ (the per-call copy is shallow), and stripping must never rewrite the+ stored transcript.++ Mutates the top-level message dicts of ``api_messages`` in place and+ returns the same list."""for msg in api_messages:if not isinstance(msg, dict):@@ -143,15 +149,25 @@ def strip_anthropic_cache_control(content = msg.get("content")if not isinstance(content, list):continue- for part in content:- if isinstance(part, dict):- part.pop("cache_control", None)- if content and all(+ if any(isinstance(part, dict) and "cache_control" in part for part in content):+ content = [+ {k: v for k, v in part.items() if k != "cache_control"}+ if isinstance(part, dict) and "cache_control" in part+ else part+ for part in content+ ]+ msg["content"] = content+ decoration_shape = content and all(isinstance(part, dict)and part.get("type", "text") == "text"and isinstance(part.get("text"), str)+ and set(part.keys()) <= {"type", "text"}for part in content- ):+ ) and (+ len(content) == 1+ or (msg.get("role") == "system" and len(content) == 2)+ )+ if decoration_shape:msg["content"] = "".join(part["text"] for part in content)return api_messagesdiff --git a/tests/agent/test_prompt_caching.py b/tests/agent/test_prompt_caching.pyindex 039a6626b7b..9f8a034d2ae 100644--- a/tests/agent/test_prompt_caching.py+++ b/tests/agent/test_prompt_caching.py@@ -393,3 +393,57 @@ class TestStripAnthropicCacheControl:assert content[0] == {"type": "text", "text": "see"}assert content[1]["type"] == "image_url"+ def test_preserves_organic_multipart_text_lists(self):+ # Multi-part pure-text lists NOT produced by decoration (merged user+ # turns, imported transcripts) must keep their structure — a ""-join+ # would fuse "Hello"+"world" into "Helloworld" and change wire bytes+ # on the common no-failover path (redecoration runs every attempt).+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Hello"},+ {"type": "text", "text": "world"},+ ],+ }+ ]+ strip_anthropic_cache_control(messages)+ content = messages[0]["content"]+ assert isinstance(content, list) and len(content) == 2+ assert [p["text"] for p in content] == ["Hello", "world"]++ def test_preserves_extra_part_keys_like_citations(self):+ # anthropic_adapter deliberately whitelists citations on text blocks;+ # strip must not destroy them by flattening the part away.+ messages = [+ {+ "role": "assistant",+ "content": [+ {+ "type": "text",+ "text": "answer",+ "citations": [{"src": "doc"}],+ "cache_control": {"type": "ephemeral"},+ }+ ],+ }+ ]+ strip_anthropic_cache_control(messages)+ content = messages[0]["content"]+ assert isinstance(content, list)+ assert content[0]["citations"] == [{"src": "doc"}]+ assert "cache_control" not in content[0]++ def test_marker_removal_is_copy_on_write_for_part_dicts(self):+ # The per-call api_messages copy is SHALLOW (msg.copy()) — content+ # part dicts alias the persistent history. Stripping a marker must+ # never rewrite the stored transcript's part dicts in place.+ shared_part = {"type": "text", "text": "hi", "cache_control": {"type": "ephemeral"}}+ history = [{"role": "user", "content": [shared_part]}]+ api_messages = [m.copy() for m in history]+ strip_anthropic_cache_control(api_messages)+ assert "cache_control" in shared_part # history untouched+ api_content = api_messages[0]["content"]+ if isinstance(api_content, list):+ assert all("cache_control" not in p for p in api_content)+