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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(ccr): inject headroom_retrieve before the prefix is warm, not after (#3810)
Tejas Choprabb8c285714b1
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 93bafdd1c..4e1b39d0f 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -2532,6 +2532,12 @@ class AnthropicHandlerMixin:existing_tools=tools,has_compressed_content_this_turn=injector.has_compressed_content,history_has_ccr_reference=history_references_ccr_tool(optimized_messages),+ # `preserve_tool_order` is this handler's existing name+ # for "leave the client's tools alone" (bypass, or+ # optimization off). Those requests never compress, so+ # injecting ahead of a compression that will not happen+ # would leave an unredeemable tool in the array.+ allow_eager=not preserve_tool_order,)if ccr_tool_injected:logger.debug(diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex be26a3b83..21b94d5ad 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -4202,6 +4202,9 @@ class OpenAIHandlerMixin:existing_tools=tools,has_compressed_content_this_turn=has_new_compressed_content,history_has_ccr_reference=history_references_ccr_tool(optimized_messages),+ # Same rule as the Anthropic handler: only pre-arm the tool+ # for a request that can actually compress.+ allow_eager=bool(self.config.optimize) and not _bypass,)if ccr_tool_injected:logger.debug(diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.pyindex 498514149..b7f502759 100644--- a/headroom/proxy/helpers.py+++ b/headroom/proxy/helpers.py@@ -93,8 +93,12 @@ from headroom.proxy.tool_definition_serialization import (serialize_tool_definition_canonical as _serialize_tool_definition_canonical,)from headroom.proxy.tool_injection_config import (+ CcrToolInjectionMode,ToolInjectionStickyMode,)+from headroom.proxy.tool_injection_config import (+ get_ccr_tool_injection_mode as _get_ccr_tool_injection_mode,+)from headroom.proxy.tool_injection_config import (get_tool_injection_sticky_mode as _get_tool_injection_sticky_mode,)@@ -2287,6 +2291,15 @@ def get_tool_injection_sticky_mode() -> ToolInjectionStickyMode:return _get_tool_injection_sticky_mode()+def get_ccr_tool_injection_mode() -> CcrToolInjectionMode:+ """Return when the CCR retrieval tool enters the tools array.++ Read at request time so operators can flip behaviour without a restart.+ Unknown values raise loudly per the no-silent-fallback build constraint.+ """+ return _get_ccr_tool_injection_mode()++def get_tool_tracker_max_sessions() -> int:"""Return the LRU bound for `SessionToolTracker` (sessions cap)."""return _get_tool_tracker_max_sessions()@@ -2686,6 +2699,7 @@ def apply_session_sticky_ccr_tool(existing_tools: list[dict[str, Any]] | None,has_compressed_content_this_turn: bool,history_has_ccr_reference: bool = False,+ allow_eager: bool = False,) -> tuple[list[dict[str, Any]], bool]:"""Apply sticky-on CCR retrieval-tool injection per :class:`SessionCcrTracker`.@@ -2741,7 +2755,9 @@ def apply_session_sticky_ccr_tool(# definition and the provider rejects the request because history still# references it (#2440).if not session_id:- if not (has_compressed_content_this_turn or history_has_ccr_reference):+ # See the fresh-session branch below for what gates eager injection.+ eager = allow_eager and bool(tools_out) and get_ccr_tool_injection_mode() == "eager"+ if not (eager or has_compressed_content_this_turn or history_has_ccr_reference):log_tool_injection_decision(provider=provider,session_id=None,@@ -2757,7 +2773,7 @@ def apply_session_sticky_ccr_tool(session_id=None,decision="inject_first_time"if has_compressed_content_this_turn- else "inject_history_reference",+ else ("inject_history_reference" if history_has_ccr_reference else "inject_eager"),tool_definition_bytes_count=len(replay.canonical_bytes),request_id=request_id,)@@ -2807,8 +2823,37 @@ def apply_session_sticky_ccr_tool()return tools_out, True- # Fresh session — only inject when this turn produced compressed content.- if not has_compressed_content_this_turn:+ # Fresh session. `tools` is the head of Anthropic's cache key, so the+ # moment this tool enters the array decides what it costs. Waiting for the+ # first compression means entering against a fully warm prefix and+ # invalidating all of it — measured on a customer session at 113,888 tokens+ # of cache write to save 2,205 tokens of content, a ~594-turn payback that+ # no session reaches. The definition is ~119 tokens; injecting it on the+ # first request instead folds that cost into the cache write the session+ # was always going to pay, and the array never changes again.+ #+ # The historical gate is still reachable via HEADROOM_CCR_TOOL_INJECTION=lazy+ # for operators who would rather keep the tool out of conversations that+ # never compress. A spurious call costs a round trip, not an error: an+ # unknown hash resolves to a structured {"status": "missing"} tool result+ # (see CCRResponseHandler._execute_retrieval), not an exception or a 400.+ #+ # Eager injection needs three things to be true, because it is the one path+ # that touches the tools array before anything has been compressed:+ #+ # allow_eager -- the caller confirms it may rewrite this request's tools+ # at all. Under `--no-optimize` or a bypass header nothing will ever be+ # compressed, so the tool would be permanently unredeemable; the old+ # gate got this for free because no compression meant no injection.+ # a non-empty client tools array -- adding the first entry would turn a+ # no-tools request into a tools request and let the model emit tool_use+ # blocks the client never expected (#728). Such a client also has no+ # tool results to compress, so there is no warm tools segment to+ # protect. The cache problem is a harness problem, and harnesses always+ # send tools.+ # the eager mode -- operators can restore the historical gate.+ eager = allow_eager and bool(tools_out) and get_ccr_tool_injection_mode() == "eager"+ if not (eager or has_compressed_content_this_turn):log_tool_injection_decision(provider=provider,session_id=session_id,@@ -2824,7 +2869,7 @@ def apply_session_sticky_ccr_tool(log_tool_injection_decision(provider=provider,session_id=session_id,- decision="inject_first_time",+ decision="inject_first_time" if has_compressed_content_this_turn else "inject_eager",tool_definition_bytes_count=len(replay.canonical_bytes),request_id=request_id,)diff --git a/headroom/proxy/tool_injection_config.py b/headroom/proxy/tool_injection_config.pyindex 5cb6a8b76..aa4dae3d6 100644--- a/headroom/proxy/tool_injection_config.py+++ b/headroom/proxy/tool_injection_config.py@@ -5,26 +5,40 @@ from __future__ import annotationsimport osfrom headroom.proxy.tool_injection_policy import (+ CCR_TOOL_INJECTION_DEFAULT,+ CCR_TOOL_INJECTION_ENV,TOOL_INJECTION_STICKY_DEFAULT,TOOL_INJECTION_STICKY_ENV,TOOL_TRACKER_MAX_SESSIONS_DEFAULT,TOOL_TRACKER_MAX_SESSIONS_ENV,+ CcrToolInjectionMode,ToolInjectionStickyMode,+ resolve_ccr_tool_injection_mode,resolve_tool_injection_sticky_mode,resolve_tool_tracker_max_sessions,)__all__ = [+ "CCR_TOOL_INJECTION_DEFAULT",+ "CCR_TOOL_INJECTION_ENV",+ "CcrToolInjectionMode","TOOL_INJECTION_STICKY_DEFAULT","TOOL_INJECTION_STICKY_ENV","TOOL_TRACKER_MAX_SESSIONS_DEFAULT","TOOL_TRACKER_MAX_SESSIONS_ENV","ToolInjectionStickyMode",+ "get_ccr_tool_injection_mode","get_tool_injection_sticky_mode","get_tool_tracker_max_sessions",]+def get_ccr_tool_injection_mode() -> CcrToolInjectionMode:+ """Return when the CCR retrieval tool enters the tools array."""++ return resolve_ccr_tool_injection_mode(os.environ.get(CCR_TOOL_INJECTION_ENV))++def get_tool_injection_sticky_mode() -> ToolInjectionStickyMode:"""Return the active memory-tool stickiness mode."""diff --git a/headroom/proxy/tool_injection_logging.py b/headroom/proxy/tool_injection_logging.pyindex b400bea7e..ad05554eb 100644--- a/headroom/proxy/tool_injection_logging.py+++ b/headroom/proxy/tool_injection_logging.py@@ -8,6 +8,12 @@ from typing import LiteralToolInjectionDecision = Literal["inject_first_time","inject_sticky_replay",+ # CCR, eager mode (the default): the retrieval tool is injected on the+ # session's first request, before anything has been compressed, so the+ # tools array — the head of the provider cache key — never changes+ # mid-session. Distinguished from inject_first_time so operators can tell+ # "entered the array cold" from "entered it against a warm prefix".+ "inject_eager",# Sessionless path: history already references headroom_retrieve, so the# tool definition is re-injected even without fresh compression (#2440)."inject_history_reference",diff --git a/headroom/proxy/tool_injection_policy.py b/headroom/proxy/tool_injection_policy.pyindex 428fab125..efd7970b4 100644--- a/headroom/proxy/tool_injection_policy.py+++ b/headroom/proxy/tool_injection_policy.py@@ -1,4 +1,4 @@-"""Policy helpers for memory tool injection stickiness configuration."""+"""Policy helpers for proxy tool injection configuration."""from __future__ import annotations@@ -8,6 +8,15 @@ TOOL_INJECTION_STICKY_ENV = "HEADROOM_TOOL_INJECTION_STICKY"ToolInjectionStickyMode = Literal["enabled", "disabled"]TOOL_INJECTION_STICKY_DEFAULT: ToolInjectionStickyMode = "enabled"+CCR_TOOL_INJECTION_ENV = "HEADROOM_CCR_TOOL_INJECTION"+CcrToolInjectionMode = Literal["eager", "lazy"]+#: Eager by default. ``tools`` is the head of Anthropic's cache key, so adding+#: ``headroom_retrieve`` at the first compression — typically many turns in,+#: against a fully warm prefix — invalidates the entire prefix behind it. The+#: definition is ~119 tokens; paying for it in the session's first (unavoidable)+#: cache write is orders of magnitude cheaper than a mid-session rewrite.+CCR_TOOL_INJECTION_DEFAULT: CcrToolInjectionMode = "eager"+TOOL_TRACKER_MAX_SESSIONS_ENV = "HEADROOM_TOOL_TRACKER_MAX_SESSIONS"TOOL_TRACKER_MAX_SESSIONS_DEFAULT = 1000@@ -25,6 +34,24 @@ def resolve_tool_injection_sticky_mode(raw: str | None) -> ToolInjectionStickyMo)+def resolve_ccr_tool_injection_mode(raw: str | None) -> CcrToolInjectionMode:+ """Resolve when the CCR retrieval tool enters the tools array.++ ``eager`` injects from the session's first request, so the tools array is+ byte-stable for the life of the session. ``lazy`` restores the historical+ behaviour of waiting for the first compression, which keeps the tool out of+ conversations that never compress at the cost of one full prefix+ invalidation in those that do.+ """++ normalized = (raw or "").strip().lower()+ if not normalized:+ return CCR_TOOL_INJECTION_DEFAULT+ if normalized in ("eager", "lazy"):+ return cast(CcrToolInjectionMode, normalized)+ raise ValueError(f"Invalid {CCR_TOOL_INJECTION_ENV}={normalized!r}; expected 'eager' or 'lazy'")++def resolve_tool_tracker_max_sessions(raw: str | None) -> int:"""Resolve the positive LRU session bound for tool injection tracking."""diff --git a/tests/test_ccr_tool_injection_cache_stability.py b/tests/test_ccr_tool_injection_cache_stability.pynew file mode 100644index 000000000..b5304b586--- /dev/null+++ b/tests/test_ccr_tool_injection_cache_stability.py@@ -0,0 +1,202 @@+"""The CCR retrieval tool must not enter the tools array mid-session.++``tools`` is the head of Anthropic's cache key — the prefix is ordered+tools → system → messages — so any change to the array invalidates every+cached token behind it. Injecting ``headroom_retrieve`` at the first+compression means entering the array against a fully warm prefix.++Measured against the live API with the real definition: a warm prefix reading+4,335 tokens dropped to 0 read and 4,458 written the moment the 478-byte tool+was appended. On a customer session the same effect cost 113,888 tokens of+cache write to save 2,205 tokens of content — a payback of ~594 turns *within+one session*, which no session reaches.++The fix is timing, not mechanism: inject on the first request, while the+prefix is still cold, and the array never changes again.+"""++from __future__ import annotations++import json++import pytest++from headroom.ccr.tool_injection import CCR_TOOL_NAME, create_ccr_tool_definition+from headroom.proxy.helpers import (+ _reset_session_ccr_tracker_for_test,+ apply_session_sticky_ccr_tool,+)++[email protected](autouse=True)+def _reset_tracker():+ _reset_session_ccr_tracker_for_test()+ yield+ _reset_session_ccr_tracker_for_test()++[email protected](autouse=True)+def _default_eager(monkeypatch):+ """Pin the default explicitly so a stray env cannot mask a regression."""+ monkeypatch.delenv("HEADROOM_CCR_TOOL_INJECTION", raising=False)+++CLIENT_TOOLS = [+ {+ "name": "Read",+ "description": "Read a file.",+ "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}},+ },+ {+ "name": "Bash",+ "description": "Run a command.",+ "input_schema": {"type": "object", "properties": {"cmd": {"type": "string"}}},+ },+]+++def _apply(session_id, *, compressed, provider="anthropic", allow_eager=True):+ """``allow_eager=True`` mirrors what both handlers pass for a request that+ can actually compress (optimization on, no bypass header)."""+ return apply_session_sticky_ccr_tool(+ provider=provider,+ session_id=session_id,+ request_id="req-1",+ existing_tools=CLIENT_TOOLS,+ has_compressed_content_this_turn=compressed,+ allow_eager=allow_eager,+ )+++def _names(tools):+ return [t.get("name") or t.get("function", {}).get("name") for t in tools]+++# ── the regression this file exists for ───────────────────────────────++[email protected]("provider", ["anthropic", "openai"])+def test_tools_array_is_byte_stable_across_the_first_compression(provider):+ """The turn that first compresses must not change the tools array.++ This is the whole bug. Before the fix, turn 1 returned two tools and turn 2+ returned three — and because tools sit first in the cache prefix, that one+ appended entry invalidated the entire warm prefix behind it.+ """+ session = f"sess-{provider}-stability"++ before, _ = _apply(session, compressed=False, provider=provider)+ during, _ = _apply(session, compressed=True, provider=provider)+ after, _ = _apply(session, compressed=False, provider=provider)++ assert json.dumps(before) == json.dumps(during) == json.dumps(after), (+ "tools array changed across the first compression — this invalidates "+ "the whole provider cache prefix"+ )++[email protected]("provider", ["anthropic", "openai"])+def test_the_tool_is_present_from_the_very_first_request(provider):+ """Cold prefix is the only cheap moment to add to the tools array."""+ tools, injected = _apply(f"sess-{provider}-first", compressed=False, provider=provider)+ assert injected is True+ assert CCR_TOOL_NAME in _names(tools)+++def test_the_tool_definition_is_small_enough_that_eager_is_obviously_right():+ """Guards the premise: if this ever grows large, revisit the trade."""+ size = len(json.dumps(create_ccr_tool_definition()))+ assert size < 2000, (+ f"headroom_retrieve is now {size} bytes; eager injection was justified "+ "on it being ~478 bytes (~119 tokens) of the session's first cache write"+ )+++# ── the escape hatch still works ──────────────────────────────────────+++def test_lazy_mode_restores_the_historical_gate(monkeypatch):+ monkeypatch.setenv("HEADROOM_CCR_TOOL_INJECTION", "lazy")+ session = "sess-lazy"++ tools, injected = _apply(session, compressed=False)+ assert injected is False+ assert CCR_TOOL_NAME not in _names(tools)++ tools, injected = _apply(session, compressed=True)+ assert injected is True+ assert CCR_TOOL_NAME in _names(tools)+++def test_an_invalid_mode_raises_rather_than_silently_defaulting(monkeypatch):+ from headroom.proxy.helpers import get_ccr_tool_injection_mode++ monkeypatch.setenv("HEADROOM_CCR_TOOL_INJECTION", "sometimes")+ with pytest.raises(ValueError, match="HEADROOM_CCR_TOOL_INJECTION"):+ get_ccr_tool_injection_mode()+++# ── properties the fix must not break ─────────────────────────────────++[email protected]("empty", [None, []])+def test_a_request_with_no_tools_is_not_armed_eagerly(empty):+ """Eager injection must not turn a no-tools request into a tools request.++ Adding the first entry to an absent tools array lets the model emit+ tool_use blocks the client never expected (#728). Such a client is also not+ a harness: it has no tool results to compress, so there is no warm tools+ segment for eager injection to protect. It keeps the historical gate.+ """+ tools, injected = apply_session_sticky_ccr_tool(+ provider="anthropic",+ session_id="sess-no-tools",+ request_id="req-1",+ existing_tools=empty,+ has_compressed_content_this_turn=False,+ allow_eager=True,+ )+ assert injected is False+ assert tools == []+++def test_a_client_provided_tool_still_wins(monkeypatch):+ """An MCP-registered headroom_retrieve must not be doubled up."""+ client_owned = [*CLIENT_TOOLS, {"name": CCR_TOOL_NAME, "description": "client's own"}]+ tools, injected = apply_session_sticky_ccr_tool(+ provider="anthropic",+ session_id="sess-client-owned",+ request_id="req-1",+ existing_tools=client_owned,+ has_compressed_content_this_turn=False,+ allow_eager=True,+ )+ assert injected is False+ assert _names(tools).count(CCR_TOOL_NAME) == 1+++def test_sticky_replay_is_byte_identical_to_the_eager_injection():+ """Later turns replay the golden bytes recorded by the eager injection."""+ session = "sess-golden"+ first, _ = _apply(session, compressed=False)+ later, _ = _apply(session, compressed=True)+ assert json.dumps(first) == json.dumps(later)+++def test_the_sessionless_path_is_also_stable():+ """No session id means no tracker, so the flag alone drove the toggle."""+ a, _ = _apply(None, compressed=False)+ b, _ = _apply(None, compressed=True)+ assert json.dumps(a) == json.dumps(b)+ assert CCR_TOOL_NAME in _names(a)+++def test_a_request_that_cannot_compress_is_not_armed():+ """`--no-optimize` or a bypass header means nothing will ever be compressed.++ Pre-arming there would leave a permanently unredeemable tool in the client's+ array. The old gate got this for free: no compression meant no injection.+ """+ tools, injected = _apply("sess-no-optimize", compressed=False, allow_eager=False)+ assert injected is False+ assert CCR_TOOL_NAME not in _names(tools)