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(proxy): skip memory-context search on OpenAI paths in cache mode (#4634)

Luis Araya36540379e0de
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index 14eec5c01..cd627c461 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -4372,15 +4372,12 @@ class OpenAIHandlerMixin:
# /v1/responses) — pre-PR-this site was the only chat
# path without one.
try:
- 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, #4622).
+ if self.memory_handler.config.inject_context and is_cache_mode(
+ getattr(getattr(self, "config", None), "mode", "token")
+ ):
from headroom.proxy.helpers import log_memory_injection
- from headroom.utils import extract_user_query
- if tags is not None:
- tags["memory_skip_reason"] = "cache_mode"
+ tags["memory_skip_reason"] = "cache_mode"
log_memory_injection(
request_id=request_id,
session_id=None,
@@ -6228,15 +6225,12 @@ class OpenAIHandlerMixin:
# (latest non-frozen user item). Instructions are part of the
# cache hot zone and must never be mutated — invariant I2.
# See REALIGNMENT/03-phase-A-lockdown.md PR-A2.
- 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, #4622).
+ if self.memory_handler.config.inject_context and is_cache_mode(
+ getattr(getattr(self, "config", None), "mode", "token")
+ ):
from headroom.proxy.helpers import log_memory_injection
- from headroom.utils import extract_user_query
- if tags is not None:
- tags["memory_skip_reason"] = "cache_mode"
+ tags["memory_skip_reason"] = "cache_mode"
log_memory_injection(
request_id=request_id,
session_id=None,
@@ -8311,20 +8305,24 @@ class OpenAIHandlerMixin:
# Inject memory context into instructions
if self.memory_handler.config.inject_context and is_cache_mode(
- self.config.mode
+ getattr(getattr(self, "config", None), "mode", "token")
):
- # 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, #4622).
- if ws_tags is not None:
- ws_tags["memory_skip_reason"] = "cache_mode"
+ from headroom.utils import extract_user_query
+
+ ws_tags["memory_skip_reason"] = "cache_mode"
ws_input = ws_response_body.get("input", "")
+ ws_instructions = ws_response_body.get("instructions")
+ ws_msgs: list[dict[str, Any]] = []
+ if ws_instructions:
+ ws_msgs.append({"role": "system", "content": ws_instructions})
+ if isinstance(ws_input, str) and ws_input:
+ ws_msgs.append({"role": "user", "content": ws_input})
log_memory_injection(
request_id=request_id,
session_id=session_id,
decision="skipped_cache_mode",
bytes_injected=0,
- query=ws_input if isinstance(ws_input, str) else "",
+ query=extract_user_query(ws_msgs) or "",
tags=ws_tags,
)
elif self.memory_handler.config.inject_context:
diff --git a/tests/test_codex_ws_per_frame_memory.py b/tests/test_codex_ws_per_frame_memory.py
index a705e96f4..cec1e5a2d 100644
--- a/tests/test_codex_ws_per_frame_memory.py
+++ b/tests/test_codex_ws_per_frame_memory.py
@@ -296,6 +296,51 @@ async def test_memory_lookup_skips_input_bearing_non_create_first_frame():
assert f"current memory: {later_input}" in forwarded_later["response"]["input"]
+async def test_cache_mode_skips_memory_context_search_ws():
+ upstream = _FakeUpstream(
+ [
+ json.dumps({"type": "response.created", "response": {"id": "r_1"}}),
+ json.dumps({"type": "response.completed", "response": {"id": "r_1"}}),
+ json.dumps({"type": "response.created", "response": {"id": "r_2"}}),
+ json.dumps({"type": "response.completed", "response": {"id": "r_2"}}),
+ ],
+ hold_after_events=True,
+ )
+ first_turn, later_turn = _issue_2059_turns()
+ client_frames = [
+ _turn_with_tools(json.loads(first_turn)["response"]["input"], _client_response_tools()),
+ _turn_with_tools(json.loads(later_turn)["response"]["input"], _client_response_tools()),
+ ]
+ client_ws = _FakeWebSocket(frames=client_frames)
+ handler = _DummyOpenAIHandler()
+ handler.config.mode = "cache"
+ memory = _MemoryHandler()
+ handler.memory_handler = memory
+ recorded_outcomes = []
+
+ async def _capture_outcome(outcome):
+ recorded_outcomes.append(outcome)
+
+ handler._record_request_outcome = _capture_outcome
+
+ with patch.dict(sys.modules, {"websockets": _make_fake_websockets_module(upstream)}):
+ await handler.handle_openai_responses_ws(client_ws)
+
+ assert memory.queries == []
+ assert len(upstream.sent) == 2
+ for i, sent_raw in enumerate(upstream.sent):
+ sent = json.loads(sent_raw)
+ original = json.loads(client_frames[i])
+ assert sent["response"]["input"] == original["response"]["input"]
+ expected_tools = [*_client_response_tools(), *_expected_memory_response_tools()]
+ assert sent["response"]["tools"] == expected_tools
+
+ assert len(recorded_outcomes) >= 1
+ for outcome in recorded_outcomes:
+ assert outcome.tags.get("memory_skip_reason") == "cache_mode"
+
+
@pytest.mark.asyncio
async def test_memory_lookup_skips_bypassed_frames():
upstream = _FakeUpstream(
diff --git a/tests/test_proxy_system_prompt_immutable.py b/tests/test_proxy_system_prompt_immutable.py
index bb5a435f2..65b2da729 100644
--- a/tests/test_proxy_system_prompt_immutable.py
+++ b/tests/test_proxy_system_prompt_immutable.py
@@ -583,3 +583,133 @@ def test_cache_mode_skips_memory_context_search_openai_responses() -> None:
assert isinstance(sent, dict)
assert sent.get("input") == "latest user string input"
assert sent.get("instructions") == "You are a Codex assistant."
+
+
+def test_cache_mode_chat_preserves_tools_and_outcome_skip_reason() -> None:
+ """Cache mode never injects memory context on OpenAI /v1/chat/completions."""
+ captured: dict[str, object] = {}
+ recorded_outcomes = []
+ 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
+
+ async def _capture_outcome(outcome):
+ recorded_outcomes.append(outcome)
+
+ proxy._record_request_outcome = _capture_outcome
+
+ _install_session_tracker(proxy, frozen_count=1)
+ _install_memory_handler(proxy)
+ proxy.memory_handler.config.inject_tools = True
+ proxy.memory_handler.compute_memory_tool_definitions = lambda _provider: [
+ {"type": "function", "function": {"name": "mem_search", "parameters": {}}}
+ ]
+ _install_capture_retry(proxy, captured)
+
+ response = client.post(
+ "/v1/chat/completions",
+ headers={
+ "authorization": "Bearer sk-test",
+ "x-headroom-user-id": "u1",
+ },
+ json={
+ "model": "gpt-4o",
+ "messages": [
+ {"role": "system", "content": "base system"},
+ {"role": "user", "content": "latest user"},
+ ],
+ "tools": [
+ {
+ "type": "function",
+ "function": {"name": "client_tool", "parameters": {}},
+ }
+ ],
+ },
+ )
+
+ 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"][1]["content"] == "latest user"
+ # Memory tools remain present even when context search is skipped
+ assert "tools" in sent
+ tool_names = [t.get("function", {}).get("name") for t in sent["tools"]]
+ assert "client_tool" in tool_names
+ assert "mem_search" in tool_names
+ # Outcome tags must record memory_skip_reason="cache_mode"
+ assert len(recorded_outcomes) >= 1
+ assert recorded_outcomes[0].tags.get("memory_skip_reason") == "cache_mode"
+
+
+def test_cache_mode_responses_preserves_tools_and_outcome_skip_reason() -> None:
+ """Cache mode never injects memory context on OpenAI /v1/responses."""
+ captured: dict[str, object] = {}
+ recorded_outcomes = []
+ with _make_responses_proxy_client() as client:
+ proxy = client.app.state.proxy
+ proxy.config.mode = "cache"
+ proxy.config.optimize = False
+ proxy.config.image_optimize = False
+
+ async def _capture_outcome(outcome):
+ recorded_outcomes.append(outcome)
+
+ proxy._record_request_outcome = _capture_outcome
+ _install_memory_handler(proxy)
+ proxy.memory_handler.config.inject_tools = True
+ proxy.memory_handler.compute_memory_tool_definitions = lambda _provider: [
+ {"type": "function", "function": {"name": "mem_search", "parameters": {}}}
+ ]
+
+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001
+ captured["body"] = body
+ return httpx.Response(
+ 200,
+ json={
+ "id": "resp_1",
+ "object": "response",
+ "model": "gpt-5.4",
+ "output": [],
+ "usage": {"input_tokens": 5, "output_tokens": 1, "total_tokens": 6},
+ },
+ )
+
+ proxy._retry_request = _fake_retry
+
+ response = client.post(
+ "/v1/responses",
+ headers={
+ "authorization": "Bearer sk-test",
+ "x-headroom-user-id": "u1",
+ },
+ json={
+ "model": "gpt-5.4",
+ "instructions": "You are a Codex assistant.",
+ "input": "latest user prompt",
+ "tools": [
+ {
+ "type": "function",
+ "name": "client_tool",
+ "description": "client tool",
+ "parameters": {},
+ }
+ ],
+ },
+ )
+
+ assert response.status_code == 200
+ proxy.memory_handler.search_and_format_context.assert_not_awaited()
+ assert "body" in captured
+ sent = captured["body"]
+ assert isinstance(sent, dict)
+ assert sent.get("input") == "latest user prompt"
+ assert "tools" in sent
+ tool_names = [t.get("name") for t in sent["tools"]]
+ assert "client_tool" in tool_names
+ assert "mem_search" in tool_names
+ assert len(recorded_outcomes) >= 1
+ assert recorded_outcomes[0].tags.get("memory_skip_reason") == "cache_mode"