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
refactor(proxy): isolate body forwarding policy (#1935)
JD Davis1f3696a3d0c6
diff --git a/headroom/proxy/body_forwarding.py b/headroom/proxy/body_forwarding.pynew file mode 100644index 000000000..81acdbaf2--- /dev/null+++ b/headroom/proxy/body_forwarding.py@@ -0,0 +1,115 @@+"""Byte-faithful outbound request body forwarding policy.++This module owns the small algebra used by Python proxy forwarders to decide+which bytes leave Headroom:++* unmutated body with original bytes -> byte-for-byte passthrough+* mutated body or missing original bytes -> canonical JSON bytes+* explicit rollback mode -> legacy httpx-style JSON bytes+"""++from __future__ import annotations++import json+import os+from dataclasses import dataclass+from typing import Any, Literal, cast++_PYTHON_FORWARDER_MODE_ENV = "HEADROOM_PROXY_PYTHON_FORWARDER_MODE"++PythonForwarderMode = Literal["byte_faithful", "legacy_json_kwarg"]+OutboundBodySource = Literal["passthrough", "canonical", "legacy"]++_PYTHON_FORWARDER_MODE_DEFAULT: PythonForwarderMode = "byte_faithful"+++@dataclass(frozen=True, slots=True)+class OutboundBody:+ """Concrete outbound body bytes plus their provenance."""++ content: bytes+ source: OutboundBodySource+++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."""+ return json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")+++class BodyMutationTracker:+ """Records whether a request body was mutated and why."""++ __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 stable aggregation reason."""+ 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 select_outbound_body(+ *,+ body: dict[str, Any],+ original_body_bytes: bytes | None,+ body_mutated: bool,+ forwarder_mode: PythonForwarderMode | None = None,+) -> OutboundBody:+ """Select the exact bytes to forward upstream."""+ mode = forwarder_mode if forwarder_mode is not None else get_python_forwarder_mode()+ if mode == "legacy_json_kwarg":+ content = json.dumps(body, separators=(", ", ": "), ensure_ascii=True).encode("utf-8")+ return OutboundBody(content=content, source="legacy")++ if body_mutated or original_body_bytes is None:+ return OutboundBody(content=serialize_body_canonical(body), source="canonical")+ return OutboundBody(content=original_body_bytes, source="passthrough")+++def prepare_outbound_body_bytes(+ *,+ body: dict[str, Any],+ original_body_bytes: bytes | None,+ body_mutated: bool,+ forwarder_mode: PythonForwarderMode | None = None,+) -> tuple[bytes, OutboundBodySource]:+ """Compatibility tuple wrapper around :func:`select_outbound_body`."""+ outbound = select_outbound_body(+ body=body,+ original_body_bytes=original_body_bytes,+ body_mutated=body_mutated,+ forwarder_mode=forwarder_mode,+ )+ return outbound.content, outbound.sourcediff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 6494f035f..d159ee98a 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -532,10 +532,10 @@ class AnthropicHandlerMixin:from headroom.cache.compression_store import get_compression_storefrom headroom.ccr import CCRToolInjectorfrom headroom.providers.anthropic import sanitize_anthropic_model_id+ from headroom.proxy.body_forwarding import BodyMutationTrackerfrom headroom.proxy.helpers import (MAX_MESSAGE_ARRAY_LENGTH,MAX_REQUEST_BODY_SIZE,- BodyMutationTracker,_get_image_compressor,compute_turn_id,read_request_json_with_bytes,@@ -2770,10 +2770,10 @@ class AnthropicHandlerMixin:# 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,+ from headroom.proxy.body_forwarding import (prepare_outbound_body_bytes,)+ from headroom.proxy.helpers import log_outbound_requestccr_outbound_bytes, ccr_outbound_source = prepare_outbound_body_bytes(body=continuation_body,diff --git a/headroom/proxy/handlers/batch.py b/headroom/proxy/handlers/batch.pyindex 1888a2efa..9b66ccd23 100644--- a/headroom/proxy/handlers/batch.py+++ b/headroom/proxy/handlers/batch.py@@ -385,11 +385,12 @@ class BatchHandlerMixin:# 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,+ from headroom.proxy.body_forwarding import (+ get_python_forwarder_mode,prepare_outbound_body_bytes,serialize_body_canonical,)+ from headroom.proxy.helpers import log_outbound_requestif body is None:body_content = await request.body()@@ -411,8 +412,6 @@ class BatchHandlerMixin:)# ``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,@@ -921,10 +920,8 @@ class BatchHandlerMixin:# 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,- )+ from headroom.proxy.body_forwarding import prepare_outbound_body_bytes+ from headroom.proxy.helpers import log_outbound_requestoutbound_bytes, outbound_source = prepare_outbound_body_bytes(body=batch_body,@@ -1172,12 +1169,12 @@ class BatchHandlerMixin:"""from fastapi.responses import Response+ from headroom.proxy.body_forwarding import prepare_outbound_body_bytesfrom headroom.proxy.helpers import (_read_request_body_bytes,_strip_internal_headers,log_outbound_headers,log_outbound_request,- prepare_outbound_body_bytes,)headers = dict(request.headers.items())diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex 4a1d63f19..df65095ed 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -3616,9 +3616,9 @@ class OpenAIHandlerMixin:from fastapi import HTTPExceptionfrom fastapi.responses import JSONResponse, Response, StreamingResponse+ from headroom.proxy.body_forwarding import BodyMutationTrackerfrom headroom.proxy.helpers import (MAX_REQUEST_BODY_SIZE,- BodyMutationTracker,read_request_json_with_bytes,)from headroom.tokenizers import get_tokenizer@@ -7021,10 +7021,8 @@ class OpenAIHandlerMixin:# 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,- )+ from headroom.proxy.body_forwarding import prepare_outbound_body_bytes+ from headroom.proxy.helpers import log_outbound_requestoutbound_bytes, outbound_source = prepare_outbound_body_bytes(body=http_body,diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex e31caf491..6b291836a 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -1052,11 +1052,11 @@ class StreamingMixin:# 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.body_forwarding import prepare_outbound_body_bytesfrom headroom.proxy.helpers import (capture_codex_wire_debug,codex_wire_debug_enabled,log_outbound_request,- prepare_outbound_body_bytes,)outbound_bytes, outbound_source = prepare_outbound_body_bytes(diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.pyindex 3db67ef68..b6313424a 100644--- a/headroom/proxy/helpers.py+++ b/headroom/proxy/helpers.py@@ -24,6 +24,19 @@ from typing import TYPE_CHECKING, Any, Literal, castfrom headroom import paths as _pathsfrom headroom._subprocess import run+from headroom.proxy.body_forwarding import (+ BodyMutationTracker as BodyMutationTracker, # noqa: F401 - compatibility export+)+from headroom.proxy.body_forwarding import (+ PythonForwarderMode as PythonForwarderMode, # noqa: F401 - compatibility export+)+from headroom.proxy.body_forwarding import (+ get_python_forwarder_mode as get_python_forwarder_mode, # noqa: F401 - compatibility export+)+from headroom.proxy.body_forwarding import (+ prepare_outbound_body_bytes as prepare_outbound_body_bytes, # noqa: F401 - compatibility export+)+from headroom.proxy.body_forwarding import serialize_body_canonicalif TYPE_CHECKING:import httpx@@ -253,49 +266,6 @@ 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 extract_tags(headers: Any) -> dict[str, str]:"""Extract ``x-headroom-*`` tags from inbound headers.@@ -331,90 +301,6 @@ def _headroom_bypass_enabled(headers: Any) -> bool:return bypass or passthrough-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,diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex fe01960e4..2c0ea5695 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -1791,10 +1791,8 @@ class HeadroomProxy(construct their body from scratch, so canonical serialization iscorrect and original bytes do not exist)."""- from headroom.proxy.helpers import (- log_outbound_request,- prepare_outbound_body_bytes,- )+ from headroom.proxy.body_forwarding import prepare_outbound_body_bytes+ from headroom.proxy.helpers import log_outbound_requestlast_error = Nonereasons = list(mutation_reasons or [])diff --git a/tests/test_proxy_byte_faithful_forwarding.py b/tests/test_proxy_byte_faithful_forwarding.pyindex 74c77e8ba..1b13a3a79 100644--- a/tests/test_proxy_byte_faithful_forwarding.py+++ b/tests/test_proxy_byte_faithful_forwarding.py@@ -30,15 +30,19 @@ import pytestfrom fastapi.testclient import TestClientfrom headroom.pipeline import PipelineStage-from headroom.proxy.helpers import (+from headroom.proxy.body_forwarding import (BodyMutationTracker,+ OutboundBody,+ get_python_forwarder_mode,+ prepare_outbound_body_bytes,+ select_outbound_body,+ serialize_body_canonical,+)+from headroom.proxy.helpers import (_reset_session_beta_tracker_for_test,append_text_to_latest_user_chat_message,- get_python_forwarder_mode,get_session_beta_tracker,log_outbound_request,- prepare_outbound_body_bytes,- serialize_body_canonical,)from headroom.proxy.server import ProxyConfig, create_app@@ -129,6 +133,26 @@ def test_prepare_outbound_unmutated_returns_passthrough_bytes() -> None:assert source == "passthrough"+def test_select_outbound_body_returns_value_object() -> None:+ original = b'{"a":1}'+ outbound = select_outbound_body(+ body={"a": 1},+ original_body_bytes=original,+ body_mutated=False,+ forwarder_mode="byte_faithful",+ )+ assert outbound == OutboundBody(content=original, source="passthrough")+++def test_helpers_preserve_body_forwarding_compatibility_exports() -> None:+ from headroom.proxy import helpers++ assert helpers.BodyMutationTracker is BodyMutationTracker+ assert helpers.get_python_forwarder_mode is get_python_forwarder_mode+ assert helpers.prepare_outbound_body_bytes is prepare_outbound_body_bytes+ assert helpers.serialize_body_canonical is serialize_body_canonical++def test_prepare_outbound_mutated_uses_canonical() -> None:out, source = prepare_outbound_body_bytes(body={"a": 1, "b": "🔥"},