Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(compression): compress cache_control blocks in the request's final message (#3483)

gglucass55d7e647e957
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.py
index 0ed1324a5..a72470afb 100644
--- a/headroom/proxy/handlers/anthropic.py
+++ b/headroom/proxy/handlers/anthropic.py
@@ -1796,6 +1796,7 @@ class AnthropicHandlerMixin:
model_limit=context_limit,
context=extract_user_query(working_messages),
frozen_message_count=frozen_message_count,
+ prefix_replay_guaranteed=True,
idle_seconds=idle_seconds,
biases=biases,
request_id=request_id,
@@ -1841,6 +1842,7 @@ class AnthropicHandlerMixin:
model_limit=context_limit,
context=extract_user_query(working_messages),
frozen_message_count=frozen_message_count,
+ prefix_replay_guaranteed=True,
idle_seconds=idle_seconds,
biases=biases,
request_id=request_id,
@@ -1892,6 +1894,7 @@ class AnthropicHandlerMixin:
model_limit=context_limit,
context=extract_user_query(working_messages),
frozen_message_count=frozen_message_count,
+ prefix_replay_guaranteed=True,
idle_seconds=idle_seconds,
biases=biases,
request_id=request_id,
@@ -1935,6 +1938,7 @@ class AnthropicHandlerMixin:
model_limit=context_limit,
context=extract_user_query(messages),
frozen_message_count=frozen_message_count,
+ prefix_replay_guaranteed=True,
biases=biases,
request_id=request_id,
compression_policy=compression_policy,
@@ -1996,6 +2000,7 @@ class AnthropicHandlerMixin:
model_limit=context_limit,
context=extract_user_query(messages),
frozen_message_count=frozen_message_count,
+ prefix_replay_guaranteed=True,
biases=biases,
request_id=request_id,
compression_policy=compression_policy,
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index 36063e42f..c2132a51f 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -3849,6 +3849,7 @@ class OpenAIHandlerMixin:
if is_cache_mode(self.config.mode)
else openai_frozen_count
),
+ prefix_replay_guaranteed=True,
biases=_hook_biases,
compression_policy=compression_policy,
cross_turn_dedup_recoverable=_dedup_pointers_recoverable,
@@ -3890,6 +3891,7 @@ class OpenAIHandlerMixin:
model_limit=context_limit,
context=extract_user_query(messages),
frozen_message_count=apply_frozen_count,
+ prefix_replay_guaranteed=True,
biases=_hook_biases,
compression_policy=compression_policy,
cross_turn_dedup_recoverable=_dedup_pointers_recoverable,
@@ -9963,6 +9965,10 @@ class OpenAIHandlerMixin:
)
session_frozen = prep.frozen_message_count
pipeline_kwargs["frozen_message_count"] = session_frozen
+ # finalize_turn below replays last turn's forwarded prefix,
+ # which is what lets the router compress the final
+ # message's cache_control tool_result (contract 1).
+ pipeline_kwargs["prefix_replay_guaranteed"] = True
result = pipeline.apply(
messages=prep.pipeline_input, model=model, **pipeline_kwargs
)
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.py
index e335fb745..ebe21afbe 100644
--- a/headroom/transforms/content_router.py
+++ b/headroom/transforms/content_router.py
@@ -4809,6 +4809,11 @@ class ContentRouter(Transform):
"compress_assistant_text_blocks",
self.config.compress_assistant_text_blocks,
)
+ # Set only by callers that replay last turn's forwarded prefix over
+ # this turn's output (the proxy handlers, via finalize_turn). It
+ # unlocks compression of a cache_control tool_result in the final
+ # message; see contract 1 in _process_content_blocks.
+ prefix_replay_guaranteed = kwargs.get("prefix_replay_guaranteed") is True
min_chars_for_block_compression = kwargs.get(
"min_chars_for_block_compression",
self.config.min_chars_for_block_compression,
@@ -5159,6 +5164,7 @@ class ContentRouter(Transform):
skip_user=skip_user,
skip_system=skip_system,
compress_assistant_text_blocks=compress_assistant_text_blocks,
+ prefix_replay_guaranteed=prefix_replay_guaranteed,
)
result_slots[i] = transformed_message
route_counts["content_blocks"] += 1
@@ -6048,6 +6054,7 @@ class ContentRouter(Transform):
skip_user: bool = True,
skip_system: bool = True,
compress_assistant_text_blocks: bool = False,
+ prefix_replay_guaranteed: bool = False,
) -> dict[str, Any]:
"""Process content blocks (Anthropic format) for compression.
@@ -6057,7 +6064,26 @@ class ContentRouter(Transform):
the cache key the upstream provider matches against, turning
a 90% read discount into a 25% write penalty (Anthropic).
We never modify cache_control'd blocks, regardless of role
- or block type.
+ or block type -- EXCEPT a tool_result in the request's final
+ user/tool message. That message has never been forwarded, so
+ no provider key exists for it yet; the marker there is the
+ client staking out NEXT turn's breakpoint (Claude Code
+ stamps its newest tool_result every turn). Compressing it
+ now is what the marker gets cached as, and the frozen-prefix
+ guard replays those bytes from the next turn on. Skipping it
+ meant the freshest tool output was protected on the one turn
+ it was fresh (measured 1,229 cache_control_protected visits
+ across 650 Claude Code requests in a day, ~2 per request).
+ The exception is only sound for a caller that replays last
+ turn's FORWARDED bytes over this turn's pipeline output (the
+ proxy's frozen-prefix overlay, session_engine.finalize_turn):
+ next turn the block is no longer final, this contract
+ hard-skips it again, and the router alone would forward the
+ client's original bytes and bust the key it just wrote.
+ Such callers pass ``prefix_replay_guaranteed=True``; every
+ other caller (SDK client, evals, a bare router) keeps the
+ hard skip. Text blocks keep the hard skip everywhere: a
+ marked user prompt is the user's words, not tool output.
2. Assistant text blocks are echoed back by the client in
subsequent turns and become part of the upstream provider's
auto-prefix cache (DeepSeek, OpenAI). Default-skip; opt in
@@ -6112,6 +6138,15 @@ class ContentRouter(Transform):
else:
protect_text_blocks = True
+ # The final user/tool message is this turn's fresh content: not yet
+ # forwarded, so its cache_control marker names a key the provider has
+ # not written. Everything earlier may already be cached under its
+ # marker and stays byte-exact (contract 1). Only tool_result blocks
+ # are released; a marked text block is the user's prompt.
+ fresh_turn = (
+ prefix_replay_guaranteed and messages_from_end == 1 and role in ("user", "tool")
+ )
+
for block in content_blocks:
if not isinstance(block, dict):
new_blocks.append(block)
@@ -6121,7 +6156,7 @@ class ContentRouter(Transform):
# cache breakpoint. Frozen-message-count is a coarse
# message-level approximation; this is the per-block
# guarantee that we never bust an explicit cache key.
- if "cache_control" in block:
+ if "cache_control" in block and not (fresh_turn and block.get("type") == "tool_result"):
new_blocks.append(block)
if route_counts is not None:
route_counts.setdefault("cache_control_protected", 0)
diff --git a/tests/test_transforms_content_router.py b/tests/test_transforms_content_router.py
index ac298a3d6..c8994cb0b 100644
--- a/tests/test_transforms_content_router.py
+++ b/tests/test_transforms_content_router.py
@@ -989,6 +989,7 @@ def test_tool_result_cache_control_protected(monkeypatch: pytest.MonkeyPatch) ->
}
],
}
+ counts: dict[str, int] = {}
result = router._process_content_blocks(
msg,
msg["content"],
@@ -996,9 +997,194 @@ def test_tool_result_cache_control_protected(monkeypatch: pytest.MonkeyPatch) ->
[],
set(),
set(),
+ route_counts=counts,
+ messages_from_end=3,
)
- # cache_control hard-skip applies to tool_result too
+ # cache_control hard-skip applies to tool_result too, on any message the
+ # provider may already hold under that key (anything but the final one).
assert result["content"][0]["content"] == long_text
+ assert counts["cache_control_protected"] == 1
+
+
+def test_tool_result_cache_control_compressed_in_final_message(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The request's final user message has never been forwarded, so its
+ # cache_control marker is the client staking out NEXT turn's breakpoint,
+ # not a key the provider holds. Claude Code stamps its newest tool_result
+ # every turn; protecting it here skipped the freshest tool output on the
+ # one turn it was fresh.
+ router = ContentRouter(ContentRouterConfig())
+
+ def fake_compress(content, context: str = "", bias: float = 1.0, precomputed_detection=None):
+ # A real (hashable) lossless strategy: tool_result compression runs the
+ # reversibility gate, which looks the strategy up in a frozenset.
+ return SimpleNamespace(
+ compressed=content[: len(content) // 2] + "[compressed]",
+ compression_ratio=0.5,
+ strategy_used=CompressionStrategy.LOG,
+ )
+
+ monkeypatch.setattr(router, "compress", fake_compress)
+ long_text = "Z" * 1000
+ msg = {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "abc",
+ "content": long_text,
+ "cache_control": {"type": "ephemeral"},
+ }
+ ],
+ }
+ counts: dict[str, int] = {}
+ result = router._process_content_blocks(
+ msg,
+ msg["content"],
+ "",
+ [],
+ set(),
+ set(),
+ route_counts=counts,
+ messages_from_end=1,
+ prefix_replay_guaranteed=True,
+ )
+ out = result["content"][0]
+ assert out["content"].endswith("[compressed]")
+ # The marker rides on the compressed block: that is what the provider
+ # caches, and what the frozen prefix replays next turn.
+ assert out["cache_control"] == {"type": "ephemeral"}
+ assert "cache_control_protected" not in counts
+ # Assistant blocks in the final position keep the hard skip: they are
+ # echoed back and were not the tool output this exception is for.
+ amsg = {
+ "role": "assistant",
+ "content": [{"type": "text", "text": long_text, "cache_control": {"type": "ephemeral"}}],
+ }
+ aresult = router._process_content_blocks(
+ amsg,
+ amsg["content"],
+ "",
+ [],
+ set(),
+ set(),
+ messages_from_end=1,
+ compress_assistant_text_blocks=True,
+ prefix_replay_guaranteed=True,
+ )
+ assert aresult["content"][0]["text"] == long_text
+ # A marked user TEXT block in the final position is the user's prompt,
+ # not tool output: it keeps the hard skip even with user compression on.
+ umsg = {
+ "role": "user",
+ "content": [{"type": "text", "text": long_text, "cache_control": {"type": "ephemeral"}}],
+ }
+ uresult = router._process_content_blocks(
+ umsg,
+ umsg["content"],
+ "",
+ [],
+ set(),
+ set(),
+ messages_from_end=1,
+ skip_user=False,
+ prefix_replay_guaranteed=True,
+ )
+ assert uresult["content"][0]["text"] == long_text
+
+
+_FRESH_CC_OUTPUT = "tool output line " * 200
+
+
+def _fresh_cc_router(monkeypatch: pytest.MonkeyPatch) -> tuple[ContentRouter, list[str]]:
+ router = ContentRouter(ContentRouterConfig())
+ calls: list[str] = []
+
+ def fake_compress(content, context: str = "", bias: float = 1.0, precomputed_detection=None):
+ calls.append(content)
+ return SimpleNamespace(
+ compressed=content[: len(content) // 2] + "[compressed]",
+ compression_ratio=0.5,
+ strategy_used=CompressionStrategy.LOG,
+ )
+
+ monkeypatch.setattr(router, "compress", fake_compress)
+ return router, calls
+
+
+def _fresh_cc_turn1() -> list[dict]:
+ return [
+ {"role": "user", "content": "run the tests"},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "t1", "name": "bash", "input": {}}],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": _FRESH_CC_OUTPUT,
+ "cache_control": {"type": "ephemeral"},
+ }
+ ],
+ },
+ ]
+
+
+def _fresh_cc_turn2() -> list[dict]:
+ return _fresh_cc_turn1() + [
+ {"role": "assistant", "content": "done"},
+ {"role": "user", "content": "now fix the lint"},
+ ]
+
+
+def test_fresh_cache_control_stays_hard_skipped_without_replay_guarantee(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A caller that hands apply() the client's raw transcript every turn with
+ # no frozen-prefix overlay (SDK client, evals, a bare router). Had turn 1
+ # compressed the marked block, turn 2 would hard-skip it (no longer final)
+ # and forward the original bytes, busting the key the marker names. So
+ # without the guarantee the block is never touched, on either turn.
+ router, calls = _fresh_cc_router(monkeypatch)
+ t1 = router.apply(_fresh_cc_turn1(), _ChurnTokenizer(), model_limit=100_000)
+ assert t1.messages[2]["content"][0]["content"] == _FRESH_CC_OUTPUT
+ t2 = router.apply(_fresh_cc_turn2(), _ChurnTokenizer(), model_limit=100_000)
+ assert t2.messages[2]["content"][0]["content"] == _FRESH_CC_OUTPUT
+ assert calls == []
+
+
+def test_fresh_cache_control_compressed_under_replay_guarantee_is_stable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from headroom.cache.prefix_tracker import overlay_cached_prefix
+
+ router, _ = _fresh_cc_router(monkeypatch)
+ kw = {"model_limit": 100_000, "prefix_replay_guaranteed": True}
+ t1 = router.apply(_fresh_cc_turn1(), _ChurnTokenizer(), **kw)
+ forwarded = t1.messages[2]["content"][0]
+ assert forwarded["content"].endswith("[compressed]")
+ assert forwarded["cache_control"] == {"type": "ephemeral"}
+ # Retried final message (the client resends the same transcript, e.g.
+ # after a 529): byte-identical, so the key written on the first attempt
+ # still matches.
+ retry = router.apply(_fresh_cc_turn1(), _ChurnTokenizer(), **kw)
+ assert retry.messages[2] == t1.messages[2]
+ # Next turn the block is no longer final and contract 1 hard-skips it, so
+ # the router alone emits the client's original bytes: this is the reversal
+ # the guarantee exists for.
+ t2_original = _fresh_cc_turn2()
+ t2 = router.apply(t2_original, _ChurnTokenizer(), **kw)
+ assert t2.messages[2]["content"][0]["content"] == _FRESH_CC_OUTPUT
+ # The guaranteeing caller replays last turn's forwarded prefix over the
+ # pipeline output (what the proxy does in finalize_turn), restoring the
+ # compressed bytes the provider cached under that marker.
+ replayed = overlay_cached_prefix(t2.messages, t2_original, _fresh_cc_turn1(), t1.messages)
+ assert replayed[2] == t1.messages[2]
+ assert replayed[3:] == t2.messages[3:]
def test_assistant_text_blocks_skipped_by_default(