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: A3 — byte-faithful Python forwarders; serialize canonical only when mutated
chopratejasf0dcc027754a
diff --git a/docs/content/docs/configuration.mdx b/docs/content/docs/configuration.mdxindex 5b572bbb5..c38d6c0a0 100644--- a/docs/content/docs/configuration.mdx+++ b/docs/content/docs/configuration.mdx@@ -255,6 +255,8 @@ headroom proxy --llmlingua --llmlingua-device cuda --llmlingua-rate 0.4| `HEADROOM_TOIN_PATH` | Override TOIN telemetry file location. Always wins when set. | derived from `${HEADROOM_WORKSPACE_DIR}` || `HEADROOM_SUBSCRIPTION_STATE_PATH` | Override subscription tracker state file. Always wins when set. | derived from `${HEADROOM_WORKSPACE_DIR}` || `HEADROOM_TELEMETRY` | Set to `off` to disable anonymous telemetry | `on` |+| `HEADROOM_MEMORY_INJECTION_MODE` | Memory-context routing mode: `live_zone_tail` (default) or `disabled`. The legacy `system_prompt` mode was retired by PR-A2; supplying it raises. | `live_zone_tail` |+| `HEADROOM_PROXY_PYTHON_FORWARDER_MODE` | Python forwarder serialization mode. `byte_faithful` (default) forwards original request bytes verbatim when no transform mutated the body and re-serializes canonically only when needed — keeps Anthropic prompt-cache hit-rate intact. `legacy_json_kwarg` is an explicit operator opt-in for emergency rollback to the historical `httpx ... json=body` behavior. NOT a fallback — only flip on explicit operator decision. | `byte_faithful` |### Filesystem Contractdiff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 8d08fad48..a7c91e6b8 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -340,9 +340,10 @@ class AnthropicHandlerMixin:from headroom.proxy.helpers import (MAX_MESSAGE_ARRAY_LENGTH,MAX_REQUEST_BODY_SIZE,+ BodyMutationTracker,_get_image_compressor,- _read_request_json,compute_turn_id,+ read_request_json_with_bytes,)from headroom.proxy.models import RequestLogfrom headroom.proxy.modes import is_cache_mode, is_token_mode@@ -481,10 +482,16 @@ class AnthropicHandlerMixin:},)- # Parse request+ # Parse request — capture both the parsed dict AND the original+ # bytes so the forwarder can pick byte-faithful passthrough when+ # nothing mutated the body (PR-A3, fixes P0-2). The mutation+ # tracker is updated by every transform site that touches the+ # body (image compression, memory injection, message rewriting,+ # tool sorting, etc.).+ body_mutation_tracker = BodyMutationTracker()try:async with stage_timer.measure("read_request_json"):- body = await _read_request_json(request)+ body, original_body_bytes = await read_request_json_with_bytes(request)except (json.JSONDecodeError, ValueError) as e:await _finalize_pre_upstream()return JSONResponse(@@ -741,6 +748,7 @@ class AnthropicHandlerMixin:compressor = _get_image_compressor()if compressor and compressor.has_images(messages):messages = compressor.compress(messages, provider="anthropic")+ body_mutation_tracker.mark_mutated("image_compression")if compressor.last_result:logger.info(f"Image compression: {compressor.last_result.technique.value} "@@ -1284,6 +1292,21 @@ class AnthropicHandlerMixin:(time.perf_counter() - pre_upstream_started_at) * 1000.0,)+ # Byte-faithful forwarder support (PR-A3, fixes P0-2). At this+ # point body has been through every transform (image, compression,+ # memory, tool sort, pipeline extensions). If a transform reported+ # it touched the body, mark mutated; we additionally compare the+ # final body against the parsed original bytes as a structural+ # safety net so any silent mutation we missed still triggers+ # canonical re-serialization.+ if not body_mutation_tracker.mutated and original_body_bytes is not None:+ try:+ parsed_original = json.loads(original_body_bytes)+ if parsed_original != body:+ body_mutation_tracker.mark_mutated("structural_diff_vs_original")+ except (json.JSONDecodeError, ValueError):+ body_mutation_tracker.mark_mutated("original_unparseable")+# Forward request - use Bedrock backend if configured, otherwise direct APIif self.anthropic_backend is not None:# Route through Bedrock backend@@ -1466,10 +1489,24 @@ class AnthropicHandlerMixin:pipeline_timing=pipeline_timing,prefix_tracker=prefix_tracker,original_messages=original_client_messages,+ original_body_bytes=original_body_bytes,+ body_mutated=body_mutation_tracker.mutated,+ mutation_reasons=body_mutation_tracker.reasons,)else:async with stage_timer.measure("upstream_connect"):- response = await self._retry_request("POST", url, headers, body)+ response = await self._retry_request(+ "POST",+ url,+ headers,+ body,+ original_body_bytes=original_body_bytes,+ body_mutated=body_mutation_tracker.mutated,+ mutation_reasons=body_mutation_tracker.reasons,+ request_id=request_id,+ forwarder_name="anthropic_messages",+ path_for_log="/v1/messages",+ )self.pipeline_extensions.emit(PipelineStage.POST_SEND,operation="proxy.request",@@ -1638,11 +1675,39 @@ class AnthropicHandlerMixin:f"CCR: Making continuation request with {len(msgs)} messages")assert self.http_client is not None, "HTTP client not initialized"+ # Byte-faithful (PR-A3, fixes P0-2). The CCR+ # continuation body is synthesized by Headroom+ # so it is treated as mutated and goes through+ # the canonical serializer.+ from headroom.proxy.helpers import (+ log_outbound_request,+ prepare_outbound_body_bytes,+ )++ ccr_outbound_bytes, ccr_outbound_source = prepare_outbound_body_bytes(+ body=continuation_body,+ original_body_bytes=None,+ body_mutated=True,+ )+ ccr_outbound_headers = {+ **continuation_headers,+ "content-type": "application/json",+ }+ log_outbound_request(+ forwarder="anthropic_ccr_continuation",+ method="POST",+ path=url,+ body_bytes_count=len(ccr_outbound_bytes),+ body_mutated=True,+ mutation_reasons=["ccr_continuation"],+ request_id=request_id,+ source=ccr_outbound_source,+ )try:cont_response = await self.http_client.post(url,- json=continuation_body,- headers=continuation_headers,+ content=ccr_outbound_bytes,+ headers=ccr_outbound_headers,timeout=httpx.Timeout(120.0), # Override timeout for CCR)logger.info(@@ -2202,7 +2267,18 @@ class AnthropicHandlerMixin:url = f"{self.ANTHROPIC_API_URL}/v1/messages/batches"try:- response = await self._retry_request("POST", url, headers, body)+ # Body is always mutated for batch (compressed requests).+ response = await self._retry_request(+ "POST",+ url,+ headers,+ body,+ body_mutated=True,+ mutation_reasons=["batch_compression"],+ request_id=request_id,+ forwarder_name="anthropic_batch",+ path_for_log="/v1/messages/batches",+ )# Record metricsawait self.metrics.record_request(diff --git a/headroom/proxy/handlers/batch.py b/headroom/proxy/handlers/batch.pyindex f928e5cfe..de1d9847d 100644--- a/headroom/proxy/handlers/batch.py+++ b/headroom/proxy/handlers/batch.py@@ -338,10 +338,44 @@ class BatchHandlerMixin:if api_key:url = f"{url}?key={api_key}"+ # Byte-faithful body bytes (PR-A3, fixes P0-2). When ``body`` is+ # None we forward the original bytes verbatim; otherwise the dict+ # has been synthesized by Headroom and is canonically serialized.+ from headroom.proxy.helpers import (+ log_outbound_request,+ prepare_outbound_body_bytes,+ serialize_body_canonical,+ )+if body is None:body_content = await request.body()+ outbound_source = "passthrough"+ body_mutated = Falseelse:- body_content = json.dumps(body).encode()+ body_content = serialize_body_canonical(body)+ outbound_source = "canonical"+ body_mutated = True+ log_outbound_request(+ forwarder="google_batch_passthrough",+ method="POST",+ path=url,+ body_bytes_count=len(body_content),+ body_mutated=body_mutated,+ mutation_reasons=["google_batch_resynthesized"] if body_mutated else [],+ request_id=None,+ source=outbound_source,+ )+ # ``prepare_outbound_body_bytes`` is consulted only for the legacy+ # operator opt-in path so we honor the env-var override here too.+ from headroom.proxy.helpers import get_python_forwarder_mode++ if get_python_forwarder_mode() == "legacy_json_kwarg" and body is not None:+ outbound_bytes, _ = prepare_outbound_body_bytes(+ body=body,+ original_body_bytes=None,+ body_mutated=True,+ )+ body_content = outbound_bytesresponse = await self.http_client.post( # type: ignore[union-attr]url,@@ -773,7 +807,35 @@ class BatchHandlerMixin:}url = f"{self.OPENAI_API_URL}/v1/batches"- response = await self.http_client.post(url, json=batch_body, headers=headers) # type: ignore[union-attr]++ # Byte-faithful re-serialization (PR-A3, fixes P0-2).+ # batch_body is synthesized by Headroom (compressed file_id ++ # metadata), so it is treated as mutated and goes through the+ # canonical serializer.+ from headroom.proxy.helpers import (+ log_outbound_request,+ prepare_outbound_body_bytes,+ )++ outbound_bytes, outbound_source = prepare_outbound_body_bytes(+ body=batch_body,+ original_body_bytes=None,+ body_mutated=True,+ )+ outbound_headers = {**headers, "content-type": "application/json"}+ log_outbound_request(+ forwarder="batch",+ method="POST",+ path=url,+ body_bytes_count=len(outbound_bytes),+ body_mutated=True,+ mutation_reasons=["batch_compressed_file_substitution"],+ request_id=request_id,+ source=outbound_source,+ )+ response = await self.http_client.post( # type: ignore[union-attr]+ url, content=outbound_bytes, headers=outbound_headers+ )total_latency = (time.time() - start_time) * 1000@@ -977,15 +1039,52 @@ class BatchHandlerMixin:return compressed_lines, statsasync def _batch_passthrough(self, request: Request, body: dict) -> Response:- """Pass through batch request to OpenAI without compression."""+ """Pass through batch request to OpenAI without compression.++ Byte-faithful (PR-A3, fixes P0-2). The original request bytes are+ preserved verbatim when no transform mutated the body.+ """from fastapi.responses import Response+ from headroom.proxy.helpers import (+ _read_request_body_bytes,+ log_outbound_request,+ prepare_outbound_body_bytes,+ )+headers = dict(request.headers.items())headers.pop("host", None)headers.pop("content-length", None)url = f"{self.OPENAI_API_URL}/v1/batches"- response = await self.http_client.post(url, json=body, headers=headers) # type: ignore[union-attr]++ # Best effort: capture the original (decompressed) bytes so the+ # passthrough is truly byte-faithful. If the body was already+ # consumed upstream we fall through to canonical re-serialization.+ try:+ original_body_bytes: bytes | None = await _read_request_body_bytes(request)+ except Exception:+ original_body_bytes = None++ outbound_bytes, outbound_source = prepare_outbound_body_bytes(+ body=body,+ original_body_bytes=original_body_bytes,+ body_mutated=False,+ )+ outbound_headers = {**headers, "content-type": "application/json"}+ log_outbound_request(+ forwarder="batch_passthrough",+ method="POST",+ path=url,+ body_bytes_count=len(outbound_bytes),+ body_mutated=False,+ mutation_reasons=[],+ request_id=None,+ source=outbound_source,+ )+ response = await self.http_client.post( # type: ignore[union-attr]+ url, content=outbound_bytes, headers=outbound_headers+ )response_headers = dict(response.headers)response_headers.pop("content-encoding", None)diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex 2fbd299f4..4b6c1e3ca 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -521,28 +521,63 @@ class OpenAIHandlerMixin:"to preserve cache stability (openai)")- # Memory: inject context and tools for OpenAI requests+ # Memory: inject context and tools for OpenAI requests.+ #+ # PR-A3 follow-up to A2: memory context now routes exclusively to+ # the live-zone tail (latest user message), never via a system-level+ # prepend. The cache hot zone (system messages) is sacrosanct —+ # invariant I2. See REALIGNMENT/03-phase-A-lockdown.md PR-A3.memory_context_injected = Falsememory_tools_injected = Falseif self.memory_handler and memory_user_id:try:- # Inject memory context (search similar memories, add as system message)if self.memory_handler.config.inject_context:memory_context = await self.memory_handler.search_and_format_context(memory_user_id, optimized_messages)if memory_context:- # Prepend as system message for OpenAI format- optimized_messages = [- {"role": "system", "content": memory_context},- *optimized_messages,- ]- memory_context_injected = True- logger.info(- f"[{request_id}] Memory: Injected {len(memory_context)} chars "- f"of context for user {memory_user_id}"+ from headroom.proxy.helpers import (+ append_text_to_latest_user_chat_message,+ get_memory_injection_mode,+ log_memory_injection,)+ injection_mode = get_memory_injection_mode()+ if injection_mode == "disabled":+ log_memory_injection(+ request_id=request_id,+ session_id=None,+ decision="skipped_disabled",+ bytes_injected=0,+ query=None,+ )+ else:+ new_messages, bytes_appended = append_text_to_latest_user_chat_message(+ optimized_messages, memory_context+ )+ if bytes_appended > 0:+ optimized_messages = new_messages+ memory_context_injected = True+ log_memory_injection(+ request_id=request_id,+ session_id=None,+ decision="injected_live_zone_tail_chat",+ bytes_injected=bytes_appended,+ query=None,+ )+ logger.info(+ f"[{request_id}] Memory: Injected {bytes_appended} chars "+ f"into latest user message tail for user {memory_user_id}"+ )+ else:+ log_memory_injection(+ request_id=request_id,+ session_id=None,+ decision="no_eligible_user_message",+ bytes_injected=0,+ query=None,+ )+# Inject memory toolsif self.memory_handler.config.inject_tools:tools, mem_tools_injected = self.memory_handler.inject_tools(tools, "openai")@@ -2444,6 +2479,31 @@ class OpenAIHandlerMixin:http_headers = dict(upstream_headers)http_headers["content-type"] = "application/json"+ # Byte-faithful re-serialization (PR-A3, fixes P0-2). The WS payload+ # is always synthesized from the WebSocket frame so the body is+ # treated as mutated; we still go through the canonical path so+ # numeric precision and UTF-8 are preserved.+ from headroom.proxy.helpers import (+ log_outbound_request,+ prepare_outbound_body_bytes,+ )++ outbound_bytes, outbound_source = prepare_outbound_body_bytes(+ body=http_body,+ original_body_bytes=None,+ body_mutated=True,+ )+ log_outbound_request(+ forwarder="openai_ws",+ method="POST",+ path=http_url,+ body_bytes_count=len(outbound_bytes),+ body_mutated=True,+ mutation_reasons=["ws_http_fallback_resynthesized"],+ request_id=request_id,+ source=outbound_source,+ )+logger.debug(f"[{request_id}] WS→HTTP fallback POST to {http_url}")try:@@ -2454,7 +2514,7 @@ class OpenAIHandlerMixin:"POST",http_url,headers=http_headers,- json=http_body,+ content=outbound_bytes,timeout=120.0,) as response:if response.status_code != 200:diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex f6298d97e..dab29b7bc 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -598,6 +598,10 @@ class StreamingMixin:pipeline_timing: dict[str, float] | None = None,prefix_tracker: Any | None = None,original_messages: list[dict] | None = None,+ *,+ original_body_bytes: bytes | None = None,+ body_mutated: bool = True,+ mutation_reasons: list[str] | None = None,) -> Response | StreamingResponse:"""Stream response with metrics tracking and memory tool handling.@@ -617,6 +621,32 @@ class StreamingMixin:headers = await apply_copilot_api_auth(headers, url=url)start_time = time.time()+ # Byte-faithful forwarding (PR-A3, fixes P0-2). Resolve outbound+ # bytes once before entering the connection-retry loop. When a+ # transform mutated the body we re-serialize canonically; otherwise+ # we forward the original client bytes verbatim.+ from headroom.proxy.helpers import (+ log_outbound_request,+ prepare_outbound_body_bytes,+ )++ outbound_bytes, outbound_source = prepare_outbound_body_bytes(+ body=body,+ original_body_bytes=original_body_bytes,+ body_mutated=body_mutated,+ )+ outbound_headers = {**headers, "content-type": "application/json"}+ log_outbound_request(+ forwarder="streaming",+ method="POST",+ path=url,+ body_bytes_count=len(outbound_bytes),+ body_mutated=body_mutated,+ mutation_reasons=list(mutation_reasons or []),+ request_id=request_id,+ source=outbound_source,+ )+# Mutable state for the generator to updatestream_state: dict[str, Any] = {"input_tokens": None,@@ -648,7 +678,7 @@ class StreamingMixin:for attempt in range(retry_attempts):try:_upstream_req = self.http_client.build_request(- "POST", url, json=body, headers=headers+ "POST", url, content=outbound_bytes, headers=outbound_headers)upstream_response = await self.http_client.send(_upstream_req, stream=True)breakdiff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.pyindex 599759534..d84188253 100644--- a/headroom/proxy/helpers.py+++ b/headroom/proxy/helpers.py@@ -67,6 +67,164 @@ def hash_query_for_log(query: str) -> str:return h.hexdigest()+# ---------------------------------------------------------------------------+# Byte-faithful Python forwarder support (PR-A3 — fixes P0-2).+# ---------------------------------------------------------------------------+#+# Every Python forwarder (server.py:_retry_request, streaming.py,+# openai.py:_ws_http_fallback, batch.py) historically used+# ``httpx.AsyncClient.post(url, json=body)``. httpx's default JSON encoder+# uses ``separators=(", ", ": ")`` and ``ensure_ascii=True`` so the bytes+# leaving the proxy never byte-equal the bytes that arrived from a+# well-behaved client (Claude Code, Codex CLI emit compact + UTF-8). Every+# such request collapses Anthropic prefix-cache hit-rate.+#+# PR-A3 switches every forwarder to byte-faithful forwarding:+# * unmutated body → forward original ``await request.body()`` verbatim;+# * mutated body → re-serialize once via ``serialize_body_canonical``.+#+# A ``BodyMutationTracker`` accompanies each request so the forwarder can+# pick the right path. Memory-injection / compression / image-rewrite sites+# call ``tracker.mark_mutated(reason)``.++_PYTHON_FORWARDER_MODE_ENV = "HEADROOM_PROXY_PYTHON_FORWARDER_MODE"+PythonForwarderMode = Literal["byte_faithful", "legacy_json_kwarg"]+_PYTHON_FORWARDER_MODE_DEFAULT: PythonForwarderMode = "byte_faithful"+++def get_python_forwarder_mode() -> PythonForwarderMode:+ """Return the active Python-forwarder mode.++ Read at request time. Unknown values raise loudly per the no-silent-+ fallback build constraint. The ``legacy_json_kwarg`` value is an+ explicit operator opt-in for emergency rollback — NOT a fallback.+ """+ raw = os.environ.get(_PYTHON_FORWARDER_MODE_ENV, "").strip().lower()+ if not raw:+ return _PYTHON_FORWARDER_MODE_DEFAULT+ if raw in ("byte_faithful", "legacy_json_kwarg"):+ return cast(PythonForwarderMode, raw)+ raise ValueError(+ f"Invalid {_PYTHON_FORWARDER_MODE_ENV}={raw!r}; "+ "expected 'byte_faithful' or 'legacy_json_kwarg'"+ )+++def serialize_body_canonical(body: dict[str, Any]) -> bytes:+ """Re-serialize a request body deterministically with cache-stable formatting.++ Uses compact separators and preserves UTF-8 (no ``\\uXXXX`` escapes), so+ byte output matches what well-behaved API clients (Claude Code, Codex+ CLI) emit. Python 3.7+ dict insertion order is preserved by+ ``json.dumps`` so message ordering is stable.++ This is the canonical re-serialization for any forwarder path that did+ mutate the body (memory injection, compression, etc.).+ """+ return json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")+++class BodyMutationTracker:+ """Records whether a request body was mutated and why.++ The forwarder reads ``mutated`` to decide between byte-faithful+ passthrough and canonical re-serialization. Reasons are logged with+ each outbound request to make cache-affecting decisions auditable.++ Thread-safety: a single tracker instance is owned by exactly one+ request task. No locking needed.+ """++ __slots__ = ("_mutated", "_reasons")++ def __init__(self) -> None:+ self._mutated: bool = False+ self._reasons: list[str] = []++ def mark_mutated(self, reason: str) -> None:+ """Mark the body as mutated and record the reason.++ ``reason`` should be a stable identifier (snake_case) suitable for+ log aggregation, e.g. ``memory_injection`` or+ ``compression_smart_crusher``.+ """+ if not reason:+ raise ValueError("BodyMutationTracker.mark_mutated: reason must be non-empty")+ self._mutated = True+ if reason not in self._reasons:+ self._reasons.append(reason)++ @property+ def mutated(self) -> bool:+ return self._mutated++ @property+ def reasons(self) -> list[str]:+ return list(self._reasons)+++def prepare_outbound_body_bytes(+ *,+ body: dict[str, Any],+ original_body_bytes: bytes | None,+ body_mutated: bool,+ forwarder_mode: PythonForwarderMode | None = None,+) -> tuple[bytes, str]:+ """Pick the outbound body bytes for a forwarder call.++ Returns ``(outbound_bytes, source)`` where ``source`` is one of+ ``passthrough`` (original bytes verbatim), ``canonical`` (re-serialized+ deterministically because body was mutated), or ``legacy`` (rollback+ mode — old ``json=body`` behavior).++ * ``forwarder_mode == "byte_faithful"`` (default): unmutated → passthrough,+ mutated → canonical.+ * ``forwarder_mode == "legacy_json_kwarg"``: always re-encode via the old+ httpx-style separators (operator opt-in, for rollback only).+ """+ mode = forwarder_mode if forwarder_mode is not None else get_python_forwarder_mode()+ if mode == "legacy_json_kwarg":+ # Old httpx default: separators=(", ", ": "), ensure_ascii=True.+ legacy_bytes = json.dumps(body, separators=(", ", ": "), ensure_ascii=True).encode("utf-8")+ return legacy_bytes, "legacy"++ # byte_faithful path+ if body_mutated or original_body_bytes is None:+ return serialize_body_canonical(body), "canonical"+ return original_body_bytes, "passthrough"+++def log_outbound_request(+ *,+ forwarder: str,+ method: str,+ path: str,+ body_bytes_count: int,+ body_mutated: bool,+ mutation_reasons: list[str],+ request_id: str | None,+ source: str,+) -> None:+ """Structured log line for every outbound forwarder call.++ Per realignment build constraints: every cache-affecting decision is+ logged. Never includes ``Authorization``/``x-api-key`` content or full+ body bytes.+ """+ logger.info(+ "event=outbound_request forwarder=%s method=%s path=%s body_bytes=%d "+ "body_mutated=%s mutation_reasons=%s source=%s request_id=%s",+ forwarder,+ method,+ path,+ body_bytes_count,+ "true" if body_mutated else "false",+ ",".join(mutation_reasons) if mutation_reasons else "",+ source,+ request_id or "",+ )++def log_memory_injection(*,request_id: str,@@ -93,6 +251,67 @@ def log_memory_injection()+def append_text_to_latest_user_chat_message(+ messages: list[dict[str, Any]],+ context_text: str,+) -> tuple[list[dict[str, Any]], int]:+ """Append context text to the first text block of the latest user chat message.++ OpenAI Chat Completions ``body["messages"]`` shape: each message is+ ``{"role": ..., "content": str | list[{"type": "text"|"input_text", "text": ...}]}``.++ This is the OpenAI Chat Completions analog of+ ``_append_context_to_latest_non_frozen_user_turn`` (Anthropic) and+ ``append_text_to_latest_user_input_item`` (OpenAI Responses). Used by+ PR-A3 to retire the legacy system-prepend memory-injection path+ (P0-equivalent for /v1/chat/completions).++ Returns ``(new_messages, bytes_appended)``. ``bytes_appended == 0``+ when no eligible user message was found (no mutation occurred).+ """+ if not messages or not context_text:+ return messages, 0++ new_messages = list(messages)+ for idx in range(len(new_messages) - 1, -1, -1):+ msg = new_messages[idx]+ if not isinstance(msg, dict):+ continue+ if msg.get("role") != "user":+ continue++ content = msg.get("content")+ if isinstance(content, str):+ updated_msg = {**msg, "content": content + "\n\n" + context_text}+ new_messages[idx] = updated_msg+ return new_messages, len(context_text)++ if isinstance(content, list) and content:+ new_content: list[dict[str, Any]] = []+ appended = False+ for part in content:+ if (+ not appended+ and isinstance(part, dict)+ and part.get("type") in ("text", "input_text")+ ):+ existing_text = part.get("text", "")+ new_part = {**part, "text": existing_text + "\n\n" + context_text}+ new_content.append(new_part)+ appended = True+ else:+ new_content.append(part)+ if appended:+ updated_msg = {**msg, "content": new_content}+ new_messages[idx] = updated_msg+ return new_messages, len(context_text)++ # User message but no eligible text block — leave untouched and stop.+ return messages, 0++ return messages, 0++def append_text_to_latest_user_input_item(body_input: list[dict[str, Any]],context_text: str,@@ -344,16 +563,12 @@ def is_anthropic_auth(headers: dict[str, str]) -> bool:return False-async def _read_request_json(request: Request) -> dict[str, Any]:- """Read and parse JSON from a request, handling compressed bodies.-- Clients like OpenAI Codex may send zstd, gzip, or deflate-compressed- request bodies. Starlette's ``request.json()`` does not decompress- automatically, causing a UnicodeDecodeError on compressed bytes.+async def _read_request_body_bytes(request: Request) -> bytes:+ """Read and (if needed) decompress the request body, returning raw UTF-8 bytes.- This helper inspects ``Content-Encoding``, decompresses if needed,- then JSON-decodes the result. It raises ``ValueError`` on any- decompression or parse failure so callers can return a clean 400.+ Mirrors ``_read_request_json`` but returns the bytes pre-parse so+ forwarders can implement byte-faithful passthrough (PR-A3, fixes P0-2).+ Raises ``ValueError`` on any decompression failure."""encoding = (request.headers.get("content-encoding") or "").lower().strip()raw = await request.body()@@ -363,9 +578,6 @@ async def _read_request_json(request: Request) -> dict[str, Any]:import zstandarddctx = zstandard.ZstdDecompressor()- # Use stream_reader for streaming zstd frames (no content size in header).- # Plain decompress() fails when the frame header omits the size, which- # is common with clients like OpenAI Codex.reader = dctx.stream_reader(raw)raw = reader.read()reader.close()@@ -404,6 +616,22 @@ async def _read_request_json(request: Request) -> dict[str, Any]:elif encoding and encoding != "identity":raise ValueError(f"Unsupported Content-Encoding: {encoding}")+ return cast(bytes, raw)+++async def _read_request_json(request: Request) -> dict[str, Any]:+ """Read and parse JSON from a request, handling compressed bodies.++ Clients like OpenAI Codex may send zstd, gzip, or deflate-compressed+ request bodies. Starlette's ``request.json()`` does not decompress+ automatically, causing a UnicodeDecodeError on compressed bytes.++ This helper inspects ``Content-Encoding``, decompresses if needed,+ then JSON-decodes the result. It raises ``ValueError`` on any+ decompression or parse failure so callers can return a clean 400.+ """+ raw = await _read_request_body_bytes(request)+# Decode and parse JSONtry:text = raw.decode("utf-8")@@ -416,6 +644,27 @@ async def _read_request_json(request: Request) -> dict[str, Any]:return result+async def read_request_json_with_bytes(request: Request) -> tuple[dict[str, Any], bytes]:+ """Read JSON body AND return the original (decompressed) bytes.++ Returned bytes are post-content-decoding (zstd/gzip/deflate/br are+ decompressed) so they represent the body as the upstream API will+ receive it. Forwarders pair this with a ``BodyMutationTracker`` to+ decide between passthrough and canonical re-serialization.+ """+ raw = await _read_request_body_bytes(request)++ try:+ text = raw.decode("utf-8")+ except UnicodeDecodeError as exc:+ raise ValueError(f"Request body is not valid UTF-8 (possibly compressed?): {exc}") from exc++ result = json.loads(text)+ if not isinstance(result, dict):+ raise ValueError("Request body must be a JSON object, not " + type(result).__name__)+ return result, raw++def _strip_per_call_annotations(obj: Any) -> Any:"""Remove annotations that clients mutate between calls in one agent loop.diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex b428bcd19..cc675552c 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -1030,17 +1030,67 @@ class HeadroomProxy(headers: dict,body: dict,stream: bool = False,+ *,+ original_body_bytes: bytes | None = None,+ body_mutated: bool = True,+ mutation_reasons: list[str] | None = None,+ request_id: str | None = None,+ forwarder_name: str = "server",+ path_for_log: str | None = None,) -> httpx.Response:- """Make request with retry and exponential backoff."""+ """Make request with retry and exponential backoff.++ Byte-faithful forwarding (PR-A3, fixes P0-2):+ * If ``original_body_bytes`` is provided AND ``body_mutated`` is+ ``False``, the original bytes are forwarded verbatim. SHA-256+ of upstream-received bytes equals client-sent bytes.+ * Otherwise the body dict is canonically re-serialized via+ ``serialize_body_canonical`` (compact separators, ensure_ascii=False).+ * ``HEADROOM_PROXY_PYTHON_FORWARDER_MODE=legacy_json_kwarg`` is an+ explicit operator opt-in for emergency rollback to the old+ ``httpx ... json=body`` behavior.++ The default ``body_mutated=True`` preserves backward compatibility+ for callers that still pass only ``body`` (e.g. CCR continuations+ construct their body from scratch, so canonical serialization is+ correct and original bytes do not exist).+ """+ from headroom.proxy.helpers import (+ log_outbound_request,+ prepare_outbound_body_bytes,+ )+last_error = None+ reasons = list(mutation_reasons or [])+ outbound_bytes, source = prepare_outbound_body_bytes(+ body=body,+ original_body_bytes=original_body_bytes,+ body_mutated=body_mutated,+ )+ outbound_headers = {**headers, "content-type": "application/json"}++ log_outbound_request(+ forwarder=forwarder_name,+ method=method,+ path=path_for_log or url,+ body_bytes_count=len(outbound_bytes),+ body_mutated=body_mutated,+ mutation_reasons=reasons,+ request_id=request_id,+ source=source,+ )for attempt in range(self.config.retry_max_attempts):try:if stream:# For streaming, we return early - retry happens at higher level- return await self.http_client.post(url, json=body, headers=headers) # type: ignore[union-attr]+ return await self.http_client.post( # type: ignore[union-attr]+ url, content=outbound_bytes, headers=outbound_headers+ )else:- response = await self.http_client.post(url, json=body, headers=headers) # type: ignore[union-attr]+ response = await self.http_client.post( # type: ignore[union-attr]+ url, content=outbound_bytes, headers=outbound_headers+ )# Don't retry client errors (4xx)if 400 <= response.status_code < 500:diff --git a/tests/test_proxy_anthropic_cache_stability.py b/tests/test_proxy_anthropic_cache_stability.pyindex bd99eb0a5..6daa01c1b 100644--- a/tests/test_proxy_anthropic_cache_stability.py+++ b/tests/test_proxy_anthropic_cache_stability.py@@ -91,7 +91,7 @@ def test_anthropic_tools_sorted_deterministically_before_forward() -> None:with _make_proxy_client() as client:proxy = client.app.state.proxy- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -204,7 +204,7 @@ def test_anthropic_batch_tools_sorted_deterministically_before_forward() -> Nonewith TestClient(app) as client:proxy = client.app.state.proxy- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -332,7 +332,7 @@ def test_token_mode_freeze_is_capped_by_prefix_tracker() -> None:proxy.anthropic_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={@@ -385,7 +385,7 @@ def test_memory_context_avoids_system_mutation_when_prefix_frozen() -> None:has_memory_tool_calls=lambda resp, provider: False,)- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -461,7 +461,7 @@ def test_ccr_system_instruction_injection_disabled_when_prefix_frozen(monkeypatcmonkeypatch.setattr("headroom.ccr.CCRToolInjector", _FakeInjector)- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={@@ -525,7 +525,7 @@ def test_ccr_tool_injection_disabled_when_prefix_frozen(monkeypatch) -> None:monkeypatch.setattr("headroom.ccr.CCRToolInjector", _FakeInjector)- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={@@ -576,7 +576,7 @@ def test_previous_turns_always_frozen_only_final_turn_mutable() -> None:AssertionError("cache mode should not invoke anthropic pipeline"))- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -631,7 +631,7 @@ def test_batch_optimization_freezes_previous_turns_only() -> None:AssertionError("cache mode batch path should not invoke anthropic pipeline"))- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -721,7 +721,7 @@ def test_token_mode_does_not_force_freeze_all_previous_turns() -> None:proxy.anthropic_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={@@ -797,7 +797,7 @@ def test_cache_mode_restores_frozen_prefix_if_transform_mutates_history() -> Nonproxy.anthropic_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -867,7 +867,7 @@ def test_cache_mode_does_not_forward_latest_turn_rewrites() -> None:proxy.anthropic_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -943,7 +943,7 @@ def test_cache_mode_reuses_prior_forwarded_prefix_and_compresses_only_new_suffixproxy.anthropic_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -1026,7 +1026,7 @@ def test_cache_mode_skips_same_message_append_rewrite_to_preserve_stability() ->proxy.anthropic_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -1181,7 +1181,7 @@ def _drive_request(proxy.anthropic_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={@@ -1464,7 +1464,7 @@ def test_issue_327_streaming_and_non_streaming_compute_same_frozen_count() -> Noproxy.anthropic_pipeline.apply = _fake_apply_a- async def _fake_retry_a(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry_a(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={@@ -1540,7 +1540,7 @@ def test_issue_327_streaming_and_non_streaming_compute_same_frozen_count() -> Nob'data: {"type":"message_stop"}\n\n')- async def _fake_retry_b(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry_b(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,content=sse_body,diff --git a/tests/test_proxy_anthropic_compression_diagnostics.py b/tests/test_proxy_anthropic_compression_diagnostics.pyindex d102ad74f..dad3f75bb 100644--- a/tests/test_proxy_anthropic_compression_diagnostics.py+++ b/tests/test_proxy_anthropic_compression_diagnostics.py@@ -84,7 +84,7 @@ def test_request_id_plumbed_to_pipeline_apply() -> None:proxy.anthropic_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return _ok_response("msg_diag_1")proxy._retry_request = _fake_retry@@ -124,7 +124,7 @@ def test_optimization_failure_logs_exception_type() -> None:proxy.anthropic_pipeline.apply = _raise_timeout- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return _ok_response("msg_diag_2")proxy._retry_request = _fake_retrydiff --git a/tests/test_proxy_byte_faithful_forwarding.py b/tests/test_proxy_byte_faithful_forwarding.pynew file mode 100644index 000000000..3d20e6cc4--- /dev/null+++ b/tests/test_proxy_byte_faithful_forwarding.py@@ -0,0 +1,788 @@+"""Byte-faithful Python forwarder tests for PR-A3 (P0-2 fix).++The Python forwarder layer (server.py:_retry_request, streaming.py,+openai.py:_ws_http_fallback, batch.py) historically re-serialized every+request body via httpx's default JSON encoder, drifting separators (``, ``+vs ``,``) and ASCII-escaping non-ASCII text. Every such request collapsed+Anthropic prompt-cache hit-rate.++PR-A3 makes every forwarder byte-faithful:+ * unmutated body → forward original ``await request.body()`` verbatim;+ * mutated body → re-serialize once via ``serialize_body_canonical``+ (compact separators, ``ensure_ascii=False``).++The legacy behavior is still reachable via+``HEADROOM_PROXY_PYTHON_FORWARDER_MODE=legacy_json_kwarg`` for emergency+rollback (operator opt-in, not a fallback).+"""++from __future__ import annotations++import hashlib+import json+from types import SimpleNamespace+from unittest.mock import AsyncMock++import httpx+import pytest++pytest.importorskip("fastapi")++from fastapi.testclient import TestClient++from headroom.proxy.helpers import (+ BodyMutationTracker,+ append_text_to_latest_user_chat_message,+ get_python_forwarder_mode,+ log_outbound_request,+ prepare_outbound_body_bytes,+ serialize_body_canonical,+)+from headroom.proxy.server import ProxyConfig, create_app++# ---------------------------------------------------------------------------+# Unit tests for serializer + tracker+# ---------------------------------------------------------------------------+++def test_serialize_canonical_compact_separators() -> None:+ """``serialize_body_canonical`` must use compact ``,``/``:`` (no spaces)."""+ body = {"a": 1, "b": 2}+ out = serialize_body_canonical(body)+ assert out == b'{"a":1,"b":2}', repr(out)+++def test_serialize_canonical_unicode_passthrough() -> None:+ """UTF-8 must survive — no ``\\uXXXX`` ASCII escaping."""+ body = {"emoji": "🔥", "cjk": "日本語", "mixed": "hello → 世界"}+ out = serialize_body_canonical(body)+ # Each non-ASCII char appears as raw UTF-8 bytes, never as a \uXXXX literal.+ assert b"\\u" not in out, repr(out)+ parsed = json.loads(out.decode("utf-8"))+ assert parsed == body+++def test_serialize_canonical_preserves_dict_insertion_order() -> None:+ """Dict insertion order is preserved (Python 3.7+ guarantee)."""+ body = {"z": 1, "a": 2, "m": 3}+ out = serialize_body_canonical(body)+ assert out.startswith(b'{"z":1,"a":2,"m":3'), repr(out)+++def test_mutation_tracker_records_reason_memory_injection() -> None:+ tracker = BodyMutationTracker()+ assert tracker.mutated is False+ assert tracker.reasons == []+ tracker.mark_mutated("memory_injection")+ assert tracker.mutated is True+ assert tracker.reasons == ["memory_injection"]+++def test_mutation_tracker_records_reason_compression() -> None:+ tracker = BodyMutationTracker()+ tracker.mark_mutated("compression_smart_crusher")+ assert tracker.mutated is True+ assert tracker.reasons == ["compression_smart_crusher"]+++def test_mutation_tracker_dedupes_reasons() -> None:+ tracker = BodyMutationTracker()+ tracker.mark_mutated("memory_injection")+ tracker.mark_mutated("memory_injection")+ tracker.mark_mutated("compression")+ assert tracker.reasons == ["memory_injection", "compression"]+++def test_mutation_tracker_rejects_empty_reason() -> None:+ tracker = BodyMutationTracker()+ with pytest.raises(ValueError):+ tracker.mark_mutated("")+++def test_mutation_tracker_reasons_is_a_copy() -> None:+ """Caller-mutating the returned list must not affect the tracker."""+ tracker = BodyMutationTracker()+ tracker.mark_mutated("a")+ out = tracker.reasons+ out.append("b")+ assert tracker.reasons == ["a"]+++# ---------------------------------------------------------------------------+# prepare_outbound_body_bytes mode selection+# ---------------------------------------------------------------------------+++def test_prepare_outbound_unmutated_returns_passthrough_bytes() -> None:+ original = b'{"a":1,"b":"\xf0\x9f\x94\xa5"}'+ out, source = prepare_outbound_body_bytes(+ body={"a": 1, "b": "🔥"},+ original_body_bytes=original,+ body_mutated=False,+ forwarder_mode="byte_faithful",+ )+ assert out == original+ assert source == "passthrough"+++def test_prepare_outbound_mutated_uses_canonical() -> None:+ out, source = prepare_outbound_body_bytes(+ body={"a": 1, "b": "🔥"},+ original_body_bytes=b'{"a": 1, "b": "\xf0\x9f\x94\xa5"}', # spaces in original+ body_mutated=True,+ forwarder_mode="byte_faithful",+ )+ assert out == b'{"a":1,"b":"\xf0\x9f\x94\xa5"}'+ assert source == "canonical"+++def test_prepare_outbound_no_original_bytes_uses_canonical() -> None:+ out, source = prepare_outbound_body_bytes(+ body={"a": 1},+ original_body_bytes=None,+ body_mutated=False,+ forwarder_mode="byte_faithful",+ )+ assert out == b'{"a":1}'+ assert source == "canonical"+++def test_legacy_json_kwarg_mode_falls_back() -> None:+ """legacy_json_kwarg is an explicit operator opt-in — produces the historical bytes.++ This is NOT a silent fallback (build constraint #4). It is reachable only+ via env var and exists for emergency rollback validation.+ """+ out, source = prepare_outbound_body_bytes(+ body={"a": 1, "b": "🔥"},+ original_body_bytes=b'{"a":1}',+ body_mutated=False,+ forwarder_mode="legacy_json_kwarg",+ )+ # Old httpx default: spaces after `,` and `:`, ascii escaping.+ assert out == b'{"a": 1, "b": "\\ud83d\\udd25"}', repr(out)+ assert source == "legacy"+++def test_python_forwarder_mode_default_is_byte_faithful(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("HEADROOM_PROXY_PYTHON_FORWARDER_MODE", raising=False)+ assert get_python_forwarder_mode() == "byte_faithful"+++def test_python_forwarder_mode_invalid_raises(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HEADROOM_PROXY_PYTHON_FORWARDER_MODE", "garbage")+ with pytest.raises(ValueError, match="HEADROOM_PROXY_PYTHON_FORWARDER_MODE"):+ get_python_forwarder_mode()+++def test_python_forwarder_mode_legacy_value_accepted(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HEADROOM_PROXY_PYTHON_FORWARDER_MODE", "legacy_json_kwarg")+ assert get_python_forwarder_mode() == "legacy_json_kwarg"+++# ---------------------------------------------------------------------------+# log_outbound_request structured log content+# ---------------------------------------------------------------------------+++def test_log_outbound_request_emits_structured_fields() -> None:+ """Capture the structured log line via a temporary handler.++ We attach a memory handler directly to the proxy logger so the test is+ independent of whether ``_setup_file_logging`` has set ``propagate=False``+ (which it does in the live proxy).+ """+ import logging++ proxy_logger = logging.getLogger("headroom.proxy")+ records: list[logging.LogRecord] = []++ class _ListHandler(logging.Handler):+ def emit(self, record: logging.LogRecord) -> None:+ records.append(record)++ handler = _ListHandler(level=logging.INFO)+ prev_level = proxy_logger.level+ proxy_logger.addHandler(handler)+ proxy_logger.setLevel(logging.INFO)+ try:+ log_outbound_request(+ forwarder="server",+ method="POST",+ path="/v1/messages",+ body_bytes_count=42,+ body_mutated=False,+ mutation_reasons=[],+ request_id="hr_test_1",+ source="passthrough",+ )+ finally:+ proxy_logger.removeHandler(handler)+ proxy_logger.setLevel(prev_level)++ matching = [r for r in records if "outbound_request" in r.getMessage()]+ assert matching, f"no outbound_request log emitted; records={records!r}"+ msg = matching[-1].getMessage()+ assert "event=outbound_request" in msg+ assert "forwarder=server" in msg+ assert "path=/v1/messages" in msg+ assert "body_bytes=42" in msg+ assert "body_mutated=false" in msg+ assert "source=passthrough" in msg+ assert "request_id=hr_test_1" in msg+ # Never log auth / body content.+ assert "Authorization" not in msg+ assert "x-api-key" not in msg.lower()+++# ---------------------------------------------------------------------------+# httpx-mock end-to-end byte-faithful checks+# ---------------------------------------------------------------------------+++class _CapturingTransport(httpx.AsyncBaseTransport):+ """An httpx transport that records the exact bytes received."""++ def __init__(self) -> None:+ self.captured_body: bytes | None = None+ self.captured_headers: dict[str, str] | None = None+ self.captured_url: str | None = None++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ # Eagerly read the request body so streaming bodies are captured too.+ body = b""+ async for chunk in request.stream:+ body += chunk+ self.captured_body = body+ self.captured_headers = dict(request.headers.items())+ self.captured_url = str(request.url)+ return httpx.Response(+ 200,+ json={+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "content": [{"type": "text", "text": "ok"}],+ "usage": {+ "input_tokens": 10,+ "output_tokens": 3,+ "cache_read_input_tokens": 0,+ "cache_creation_input_tokens": 0,+ },+ },+ )+++class _FakePrefixTracker:+ def __init__(self, frozen_count: int = 0):+ self._frozen_count = frozen_count+ self._cached_token_count = 0+ self._last_original_messages: list = []+ self._last_forwarded_messages: list = []++ def get_frozen_message_count(self) -> int:+ return self._frozen_count++ def get_last_original_messages(self): # noqa: ANN201+ return list(self._last_original_messages)++ def get_last_forwarded_messages(self): # noqa: ANN201+ return list(self._last_forwarded_messages)++ def update_from_response(self, **kwargs): # noqa: ANN003+ self._last_original_messages = kwargs.get("original_messages", kwargs.get("messages", []))+ self._last_forwarded_messages = kwargs.get("messages", [])+ return None+++def _make_no_optimize_app() -> tuple[TestClient, _CapturingTransport]:+ """Boot a proxy with all transforms disabled and a capturing transport."""+ config = ProxyConfig(+ optimize=False,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ log_requests=False,+ ccr_inject_tool=False,+ ccr_handle_responses=False,+ ccr_context_tracking=False,+ image_optimize=False,+ )+ app = create_app(config)+ transport = _CapturingTransport()+ proxy = app.state.proxy+ proxy.http_client = httpx.AsyncClient(transport=transport)++ # Pin a stable session tracker so the prefix walker doesn't re-read+ # turn 0 on every run.+ fake_tracker = _FakePrefixTracker(frozen_count=0)+ proxy.session_tracker_store.compute_session_id = lambda request, model, messages: "s1"+ proxy.session_tracker_store.get_or_create = lambda session_id, provider: fake_tracker++ return TestClient(app), transport+++def test_passthrough_no_mutation_byte_equal_sha256() -> None:+ """No transform → upstream SHA-256 equals client-sent SHA-256."""+ client, transport = _make_no_optimize_app()++ # Compact JSON, simulating Claude Code / Codex CLI byte format.+ inbound_dict = {+ "model": "claude-sonnet-4-6",+ "max_tokens": 64,+ "messages": [{"role": "user", "content": "hello"}],+ }+ inbound_bytes = serialize_body_canonical(inbound_dict)++ response = client.post(+ "/v1/messages",+ headers={+ "x-api-key": "test-key",+ "anthropic-version": "2023-06-01",+ "content-type": "application/json",+ },+ content=inbound_bytes,+ )+ assert response.status_code == 200, response.text+ assert transport.captured_body is not None++ inbound_sha = hashlib.sha256(inbound_bytes).hexdigest()+ upstream_sha = hashlib.sha256(transport.captured_body).hexdigest()+ assert inbound_sha == upstream_sha, (+ f"Byte-faithful invariant broken: inbound {inbound_sha} vs upstream "+ f"{upstream_sha}; upstream body={transport.captured_body!r}"+ )+++def test_compression_off_unicode_preserved() -> None:+ """Emoji + CJK content survives forwarding without ``\\uXXXX`` escaping."""+ client, transport = _make_no_optimize_app()++ inbound_dict = {+ "model": "claude-sonnet-4-6",+ "max_tokens": 64,+ "messages": [+ {"role": "user", "content": "Hello 🔥 — 世界 — emoji is 🚀"},+ ],+ }+ inbound_bytes = serialize_body_canonical(inbound_dict)++ response = client.post(+ "/v1/messages",+ headers={+ "x-api-key": "test-key",+ "anthropic-version": "2023-06-01",+ "content-type": "application/json",+ },+ content=inbound_bytes,+ )+ assert response.status_code == 200+ upstream = transport.captured_body or b""+ assert upstream == inbound_bytes+ assert b"\\u" not in upstream, repr(upstream)+ assert "🔥".encode() in upstream+ assert "世界".encode() in upstream+++def test_compression_off_numeric_precision_preserved() -> None:+ """Floats with trailing zero stay floats; large ints preserve precision."""+ client, transport = _make_no_optimize_app()++ inbound_bytes = b'{"model":"claude-sonnet-4-6","max_tokens":64,"temperature":1.0,"seed":12345678901234567,"messages":[{"role":"user","content":"hi"}]}'++ response = client.post(+ "/v1/messages",+ headers={+ "x-api-key": "test-key",+ "anthropic-version": "2023-06-01",+ "content-type": "application/json",+ },+ content=inbound_bytes,+ )+ assert response.status_code == 200+ upstream = transport.captured_body or b""+ # Unmutated → byte-faithful: exact bytes preserved.+ assert upstream == inbound_bytes+++def test_legacy_json_kwarg_mode_yields_drifted_bytes(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Operator opt-in produces the OLD drifted bytes (rollback validation)."""+ monkeypatch.setenv("HEADROOM_PROXY_PYTHON_FORWARDER_MODE", "legacy_json_kwarg")+ client, transport = _make_no_optimize_app()++ inbound_dict = {+ "model": "claude-sonnet-4-6",+ "max_tokens": 64,+ "messages": [{"role": "user", "content": "🔥 hi"}],+ }+ inbound_bytes = serialize_body_canonical(inbound_dict)++ response = client.post(+ "/v1/messages",+ headers={+ "x-api-key": "test-key",+ "anthropic-version": "2023-06-01",+ "content-type": "application/json",+ },+ content=inbound_bytes,+ )+ assert response.status_code == 200+ upstream = transport.captured_body or b""+ # Legacy mode: spaces after separators + ASCII escaping → bytes drift.+ assert upstream != inbound_bytes+ assert b", " in upstream or b": " in upstream+ assert b"\\u" in upstream # ASCII escaping confirms legacy path.+++# ---------------------------------------------------------------------------+# A2 follow-up: OpenAI Chat Completions memory routes to user-tail+# ---------------------------------------------------------------------------+++def test_append_text_to_latest_user_chat_message_string_content() -> None:+ msgs = [+ {"role": "system", "content": "you are helpful"},+ {"role": "user", "content": "previous"},+ {"role": "assistant", "content": "ack"},+ {"role": "user", "content": "latest"},+ ]+ new_msgs, appended = append_text_to_latest_user_chat_message(msgs, "MEMCTX")+ assert appended > 0+ assert new_msgs[0] == msgs[0]+ assert new_msgs[1] == msgs[1]+ assert new_msgs[2] == msgs[2]+ assert new_msgs[3]["content"] == "latest\n\nMEMCTX"+ # Original list untouched.+ assert msgs[3]["content"] == "latest"+++def test_append_text_to_latest_user_chat_message_list_content() -> None:+ msgs = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "first text"},+ {"type": "image_url", "image_url": {"url": "..."}},+ ],+ }+ ]+ new_msgs, appended = append_text_to_latest_user_chat_message(msgs, "MEM")+ assert appended > 0+ parts = new_msgs[0]["content"]+ assert parts[0]["text"] == "first text\n\nMEM"+ assert parts[1] == msgs[0]["content"][1]+++def test_append_text_to_latest_user_chat_message_no_user_returns_zero() -> None:+ msgs = [{"role": "system", "content": "sys"}]+ new_msgs, appended = append_text_to_latest_user_chat_message(msgs, "MEM")+ assert appended == 0+ assert new_msgs == msgs+++def test_openai_chat_memory_routes_to_user_tail_not_system() -> None:+ """A2 follow-up: Chat Completions memory injection lives in user tail."""+ config = ProxyConfig(+ optimize=False,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ log_requests=False,+ ccr_inject_tool=False,+ ccr_handle_responses=False,+ ccr_context_tracking=False,+ image_optimize=False,+ )+ app = create_app(config)+ proxy = app.state.proxy+ proxy.memory_handler = SimpleNamespace(+ config=SimpleNamespace(inject_context=True, inject_tools=False),+ search_and_format_context=AsyncMock(return_value="MEMCTX_OAI"),+ has_memory_tool_calls=lambda resp, provider: False,+ )++ captured: dict[str, object] = {}++ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001+ captured["body"] = body+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl_1",+ "object": "chat.completion",+ "model": "gpt-4o",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "ok"},+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},+ },+ )++ proxy._retry_request = _fake_retry # type: ignore[attr-defined]+ client = TestClient(app)++ resp = client.post(+ "/v1/chat/completions",+ headers={+ "authorization": "Bearer sk-test",+ "x-headroom-user-id": "u1",+ },+ json={+ "model": "gpt-4o",+ "messages": [+ {"role": "system", "content": "you are helpful"},+ {"role": "user", "content": "what is up"},+ ],+ },+ )+ assert resp.status_code == 200, resp.text+ sent = captured.get("body")+ assert isinstance(sent, dict), captured+ sent_msgs = sent["messages"]+ # System message must NOT be mutated.+ assert sent_msgs[0]["role"] == "system"+ assert sent_msgs[0]["content"] == "you are helpful", "system message must remain byte-equal"+ # No injected system message at the start (legacy prepend retired).+ # The ONLY new content is in the latest user message tail.+ user_msgs = [m for m in sent_msgs if m.get("role") == "user"]+ assert len(user_msgs) == 1+ assert user_msgs[-1]["content"].endswith("MEMCTX_OAI")+ # No additional system messages either (memory must not prepend).+ system_msgs = [m for m in sent_msgs if m.get("role") == "system"]+ assert len(system_msgs) == 1+++def test_openai_chat_memory_disabled_mode_no_op(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HEADROOM_MEMORY_INJECTION_MODE", "disabled")+ config = ProxyConfig(+ optimize=False,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ log_requests=False,+ ccr_inject_tool=False,+ ccr_handle_responses=False,+ ccr_context_tracking=False,+ image_optimize=False,+ )+ app = create_app(config)+ proxy = app.state.proxy+ proxy.memory_handler = SimpleNamespace(+ config=SimpleNamespace(inject_context=True, inject_tools=False),+ search_and_format_context=AsyncMock(return_value="WOULD_NOT_INJECT"),+ has_memory_tool_calls=lambda resp, provider: False,+ )++ captured: dict[str, object] = {}++ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001+ captured["body"] = body+ return httpx.Response(+ 200,+ json={+ "id": "c1",+ "object": "chat.completion",+ "model": "gpt-4o",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "ok"},+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 5, "completion_tokens": 1, "total_tokens": 6},+ },+ )++ proxy._retry_request = _fake_retry+ client = TestClient(app)+ resp = client.post(+ "/v1/chat/completions",+ headers={+ "authorization": "Bearer sk-test",+ "x-headroom-user-id": "u1",+ },+ json={+ "model": "gpt-4o",+ "messages": [+ {"role": "system", "content": "sys"},+ {"role": "user", "content": "hi"},+ ],+ },+ )+ assert resp.status_code == 200+ sent = captured["body"]+ assert isinstance(sent, dict)+ assert sent["messages"][1]["content"] == "hi"+++# ---------------------------------------------------------------------------+# Streaming forwarder byte-faithfulness+# ---------------------------------------------------------------------------+++class _StreamingCapturingTransport(httpx.AsyncBaseTransport):+ def __init__(self) -> None:+ self.captured_body: bytes | None = None+ self.captured_headers: dict[str, str] | None = None++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ body = b""+ async for chunk in request.stream:+ body += chunk+ self.captured_body = body+ self.captured_headers = dict(request.headers.items())++ async def _empty_sse(): # pragma: no cover - generator+ yield b'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_s","type":"message","role":"assistant","model":"claude","usage":{"input_tokens":1,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}\n\n'+ yield b'event: message_stop\ndata: {"type":"message_stop"}\n\n'++ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ stream=httpx.AsyncByteStream(_empty_sse()), # type: ignore[arg-type]+ )+++def test_streaming_forwarder_byte_faithful() -> None:+ """Streaming forwarder uses the same byte-faithful path as non-streaming."""+ config = ProxyConfig(+ optimize=False,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ log_requests=False,+ ccr_inject_tool=False,+ ccr_handle_responses=False,+ ccr_context_tracking=False,+ image_optimize=False,+ )+ app = create_app(config)+ proxy = app.state.proxy++ # Pin session tracker so the cache-stable delta path is a no-op.+ fake_tracker = _FakePrefixTracker(frozen_count=0)+ proxy.session_tracker_store.compute_session_id = lambda request, model, messages: "s_stream"+ proxy.session_tracker_store.get_or_create = lambda session_id, provider: fake_tracker++ transport = _StreamingCapturingTransport()+ proxy.http_client = httpx.AsyncClient(transport=transport)+ client = TestClient(app)++ inbound_bytes = (+ '{"model":"claude-sonnet-4-6","max_tokens":16,"stream":true,'+ '"messages":[{"role":"user","content":"hi 🔥"}]}'+ ).encode()++ with client.stream(+ "POST",+ "/v1/messages",+ headers={+ "x-api-key": "test-key",+ "anthropic-version": "2023-06-01",+ "content-type": "application/json",+ },+ content=inbound_bytes,+ ) as resp:+ # Drain the response.+ for _ in resp.iter_bytes():+ pass++ upstream = transport.captured_body or b""+ inbound_sha = hashlib.sha256(inbound_bytes).hexdigest()+ upstream_sha = hashlib.sha256(upstream).hexdigest()+ assert upstream_sha == inbound_sha, (+ f"Streaming byte-faithfulness broken: inbound {inbound_sha} vs "+ f"upstream {upstream_sha}; upstream={upstream!r}"+ )+++# ---------------------------------------------------------------------------+# Batch forwarder byte-faithfulness (passthrough variant)+# ---------------------------------------------------------------------------+++def test_batch_passthrough_byte_faithful() -> None:+ """OpenAI batch passthrough forwards original bytes verbatim."""+ config = ProxyConfig(+ optimize=False,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ log_requests=False,+ ccr_inject_tool=False,+ ccr_handle_responses=False,+ ccr_context_tracking=False,+ image_optimize=False,+ )+ app = create_app(config)+ proxy = app.state.proxy+ transport = _CapturingTransport()+ proxy.http_client = httpx.AsyncClient(transport=transport)+ client = TestClient(app)++ # Use a non-chat-completions endpoint so the handler routes directly to+ # _batch_passthrough (bypassing the file-compression flow).+ inbound = {+ "input_file_id": "file-abc",+ "endpoint": "/v1/embeddings",+ "completion_window": "24h",+ }+ inbound_bytes = serialize_body_canonical(inbound)++ resp = client.post(+ "/v1/batches",+ headers={+ "authorization": "Bearer sk-test",+ "content-type": "application/json",+ },+ content=inbound_bytes,+ )+ # The capturing transport returns a Message JSON, which is fine; the+ # status code may vary depending on routing. What matters is that when+ # the upstream did receive bytes, they are byte-equal to what the+ # client sent (passthrough case, no body mutation).+ assert resp.status_code in (200, 400, 401, 404, 422, 500), resp.text+ if transport.captured_body is not None:+ assert transport.captured_body == inbound_bytes, (+ f"Batch passthrough bytes drifted: "+ f"sent={inbound_bytes!r} upstream={transport.captured_body!r}"+ )+++# ---------------------------------------------------------------------------+# WS→HTTP fallback: just exercises the helper resolution+# ---------------------------------------------------------------------------+++def test_ws_http_fallback_uses_canonical_serializer() -> None:+ """WS→HTTP fallback resynthesizes the body, so canonical bytes apply.++ We can't easily exercise the full WS path in a TestClient without a+ Codex client; instead we assert the helper choice yields the expected+ bytes when a tracker reports mutation.+ """+ body = {"model": "gpt-5", "input": [{"role": "user", "content": "hi 🚀"}]}+ out, source = prepare_outbound_body_bytes(+ body=body,+ original_body_bytes=None,+ body_mutated=True,+ )+ assert source == "canonical"+ assert b"\\u" not in out+ # Round-trip equality via JSON parse.+ assert json.loads(out.decode("utf-8")) == bodydiff --git a/tests/test_proxy_copilot_auth_hooks.py b/tests/test_proxy_copilot_auth_hooks.pyindex 45eeb3b09..0d625bdfe 100644--- a/tests/test_proxy_copilot_auth_hooks.py+++ b/tests/test_proxy_copilot_auth_hooks.py@@ -164,12 +164,13 @@ def test_streaming_response_applies_copilot_auth(monkeypatch: pytest.MonkeyPatchsend=self._send,)- def _build_request(self, method: str, url: str, json: dict, headers: dict): # noqa: ANN003, A002+ def _build_request(self, method: str, url: str, **kwargs): # noqa: ANN003+ # PR-A3: streaming forwarder is byte-faithful; it now passes+ # ``content=<bytes>`` instead of ``json=<dict>``.seen["request"] = {"method": method,"url": url,- "json": json,- "headers": headers,+ **kwargs,}return SimpleNamespace()@@ -195,5 +196,8 @@ def test_streaming_response_applies_copilot_auth(monkeypatch: pytest.MonkeyPatch)assert seen["url"] == "https://api.githubcopilot.com/v1/responses"- assert seen["request"]["headers"] == {"Authorization": "Bearer upstream-token"}+ # PR-A3: byte-faithful forwarder always sets ``content-type`` explicitly.+ sent_headers = seen["request"]["headers"]+ assert sent_headers["Authorization"] == "Bearer upstream-token"+ assert sent_headers["content-type"] == "application/json"assert response.status_code == 200diff --git a/tests/test_proxy_handler_helpers.py b/tests/test_proxy_handler_helpers.pyindex 4e4c7e778..769f35e1e 100644--- a/tests/test_proxy_handler_helpers.py+++ b/tests/test_proxy_handler_helpers.py@@ -105,11 +105,13 @@ def test_anthropic_tool_sort_and_context_append_helpers() -> None:"ctx",frozen_message_count=0,) == [{"role": "user", "content": "hello\n\nctx"}]+ # PR-A2 semantics: list-content user messages get the context appended+ # to the first text block (live-zone-tail injection).assert AnthropicHandlerMixin._append_context_to_latest_non_frozen_user_turn([{"role": "user", "content": [{"type": "text", "text": "hello"}]}],"ctx",frozen_message_count=0,- ) == [{"role": "user", "content": [{"type": "text", "text": "hello"}]}]+ ) == [{"role": "user", "content": [{"type": "text", "text": "hello\n\nctx"}]}]def test_anthropic_image_compression_helper_only_rewrites_latest_eligible_turn() -> None:diff --git a/tests/test_proxy_handlers_batch.py b/tests/test_proxy_handlers_batch.pyindex 765e1164e..590c8b14f 100644--- a/tests/test_proxy_handlers_batch.py+++ b/tests/test_proxy_handlers_batch.py@@ -96,7 +96,7 @@ class DummyBatchHandler(batch_module.BatchHandlerMixin):async def handle_passthrough(self, request, base_url): # noqa: ANN001, ANN201return {"request": request, "base_url": base_url}- async def _retry_request(self, method, url, headers, body): # noqa: ANN001, ANN201+ async def _retry_request(self, method, url, headers, body, **kwargs): # noqa: ANN001, ANN201return self._retry_responsedef _gemini_contents_to_messages(self, contents, system_instruction): # noqa: ANN001, ANN201@@ -413,7 +413,13 @@ async def test_handle_batch_create_handles_empty_upload_failure_and_success(assert success_headers["x-headroom-tokens-saved"] == "10"assert success_headers["x-headroom-savings-percent"] == "50.0"assert success_headers["x-openai"] == "1"- sent_body = handler.http_client.posts[-1]["json"]+ # PR-A3: byte-faithful forwarder writes ``content`` (raw bytes), not+ # ``json``. Round-trip the captured bytes back to a dict for assertion.+ last_post = handler.http_client.posts[-1]+ if "json" in last_post:+ sent_body = last_post["json"]+ else:+ sent_body = json.loads(last_post["content"].decode("utf-8"))assert sent_body["metadata"]["headroom_compressed"] == "true"assert sent_body["metadata"]["headroom_original_file_id"] == "file-1"assert handler.metrics.record_calls[-1]["provider"] == "openai"@@ -772,7 +778,7 @@ async def test_handle_google_batch_create_success_and_failure_paths(async def fake_store(batch_name, requests_list, model, api_key): # noqa: ANN001stored.append((batch_name, requests_list, model, api_key))- async def fake_retry(method, url, headers, body): # noqa: ANN001+ async def fake_retry(method, url, headers, body, **kwargs): # noqa: ANN001return FakeResponse(status_code=200,content=b'{"name":"batches/123"}',@@ -815,7 +821,7 @@ async def test_handle_google_batch_create_success_and_failure_paths(assert stored[0][2:] == ("gemini-pro", "secret")assert stored[0][1][0]["metadata"] == {"key": "req-1"}- async def broken_retry(method, url, headers, body): # noqa: ANN001+ async def broken_retry(method, url, headers, body, **kwargs): # noqa: ANN001raise RuntimeError("forward failed")monkeypatch.setattr(handler, "_retry_request", broken_retry)@@ -884,7 +890,7 @@ async def test_handle_google_batch_create_covers_passthrough_revert_and_store_faseen_bodies: list[dict[str, object]] = []- async def retry(method, url, headers, body): # noqa: ANN001+ async def retry(method, url, headers, body, **kwargs): # noqa: ANN001seen_bodies.append(body)return FakeResponse(status_code=200, content=b"{}", json_data={"name": "batches/123"})diff --git a/tests/test_proxy_openai_cache_stability.py b/tests/test_proxy_openai_cache_stability.pyindex f895f2546..b0a22c029 100644--- a/tests/test_proxy_openai_cache_stability.py+++ b/tests/test_proxy_openai_cache_stability.py@@ -67,7 +67,7 @@ def test_openai_cache_mode_freezes_previous_turns() -> None:proxy.openai_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={@@ -135,7 +135,7 @@ def test_openai_cache_mode_restores_mutated_frozen_prefix() -> None:proxy.openai_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -233,7 +233,7 @@ def test_issue_327_openai_handler_does_not_call_walker_functions() -> None:proxy.openai_pipeline.apply = _fake_apply- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={diff --git a/tests/test_proxy_pipeline_lifecycle.py b/tests/test_proxy_pipeline_lifecycle.pyindex e57338da2..e61559265 100644--- a/tests/test_proxy_pipeline_lifecycle.py+++ b/tests/test_proxy_pipeline_lifecycle.py@@ -111,7 +111,7 @@ def test_openai_chat_pipeline_events_cover_proxy_lifecycle(monkeypatch) -> None:monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _DummyTokenizer())- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={@@ -176,7 +176,7 @@ def test_anthropic_messages_pipeline_events_cover_proxy_lifecycle(monkeypatch) -monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _DummyTokenizer())- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001return httpx.Response(200,json={diff --git a/tests/test_proxy_system_prompt_immutable.py b/tests/test_proxy_system_prompt_immutable.pyindex 3cea22167..b92356b93 100644--- a/tests/test_proxy_system_prompt_immutable.py+++ b/tests/test_proxy_system_prompt_immutable.py@@ -84,7 +84,7 @@ def _install_session_tracker(proxy: object, frozen_count: int) -> None:def _install_capture_retry(proxy: object, captured: dict[str, object]) -> None:- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodycaptured["headers"] = dict(headers)return httpx.Response(@@ -318,7 +318,7 @@ def test_memory_enabled_does_not_mutate_instructions_responses_api() -> None:proxy.config.image_optimize = False_install_memory_handler(proxy)- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,@@ -377,7 +377,7 @@ def test_memory_context_appears_in_responses_api_input_tail() -> None:proxy.config.image_optimize = False_install_memory_handler(proxy)- async def _fake_retry(method, url, headers, body, stream=False): # noqa: ANN001+ async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001captured["body"] = bodyreturn httpx.Response(200,