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(proxy): skip the memory-context search in cache mode (#4606)
SD053925b03c6c
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 7fb61cc20..496516970 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -2970,7 +2970,7 @@ class AnthropicHandlerMixin:# Memory: Inject context and tools — gated on MemoryDecision.# ``inject`` is False under bypass, missing handler, missing- # user_id, or HEADROOM_MEMORY_INJECTION_MODE in disabled/tool.+ # user_id, or HEADROOM_MEMORY_INJECTION_MODE=disabled.# Pre-PR-this the gate was a raw conjunction that silently# ignored bypass; now bypass is honoured here on Anthropic# /v1/messages just as on /v1/responses.@@ -2980,8 +2980,21 @@ class AnthropicHandlerMixin:# streaming path withholds their calls from the client.server_memory_tool_names: frozenset[str] = frozenset()if memory_decision.inject:+ if self.memory_handler.config.inject_context and is_cache_mode(self.config.mode):+ # Cache mode never injects context, so the next-turn prefix+ # bytes stay byte-equal to this turn's bytes. Skip the search+ # too: its result could only be discarded (#4600).+ from headroom.proxy.helpers import log_memory_injection++ log_memory_injection(+ request_id=request_id,+ session_id=session_id,+ decision="skipped_cache_mode",+ bytes_injected=0,+ query=extract_user_query(optimized_messages) or "",+ )# Search and inject memory context- if self.memory_handler.config.inject_context:+ elif self.memory_handler.config.inject_context:try:async with stage_timer.measure("memory_context"):memory_context = await asyncio.wait_for(@@ -3019,16 +3032,6 @@ class AnthropicHandlerMixin:bytes_injected=0,query=user_query,)- elif is_cache_mode(self.config.mode):- # Cache mode: skip injection entirely so the next-turn- # prefix bytes remain byte-equal to this turn's bytes.- log_memory_injection(- request_id=request_id,- session_id=session_id,- decision="skipped_cache_mode",- bytes_injected=0,- query=user_query,- )else:# P0-1 fix: route exclusively to the live zone tail# (latest non-frozen user turn). System prompt + frozendiff --git a/tests/test_proxy_system_prompt_immutable.py b/tests/test_proxy_system_prompt_immutable.pyindex 3747ad16a..cb619018b 100644--- a/tests/test_proxy_system_prompt_immutable.py+++ b/tests/test_proxy_system_prompt_immutable.py@@ -193,6 +193,46 @@ def test_memory_context_appears_in_latest_user_message_tail() -> None:assert sent["messages"][2]["content"].endswith("MEMCTX")+def test_cache_mode_skips_memory_context_search() -> None:+ """Cache mode never injects memory context, so it must not search for it."""+ captured: dict[str, object] = {}+ with _make_proxy_client() as client:+ proxy = client.app.state.proxy+ proxy.config.mode = "cache"+ proxy.config.optimize = False+ proxy.config.image_optimize = False+ proxy.config.ccr_proactive_expansion = False++ _install_session_tracker(proxy, frozen_count=1)+ _install_memory_handler(proxy)+ _install_capture_retry(proxy, captured)++ response = client.post(+ "/v1/messages",+ headers={+ "x-api-key": "test-key",+ "anthropic-version": "2023-06-01",+ "x-headroom-user-id": "u1",+ },+ json={+ "model": "claude-sonnet-4-6",+ "max_tokens": 64,+ "system": "base system",+ "messages": [+ {"role": "user", "content": "frozen prefix"},+ {"role": "assistant", "content": "ack"},+ {"role": "user", "content": "latest user"},+ ],+ },+ )++ assert response.status_code == 200+ proxy.memory_handler.search_and_format_context.assert_not_awaited()+ sent = captured["body"]+ assert isinstance(sent, dict)+ assert sent["messages"][2]["content"] == "latest user"++def test_memory_context_byte_deterministic_for_same_query() -> None:"""Two identical inbound requests produce identical outbound bytes."""capture_a: dict[str, object] = {}