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): bypass compression for large admitted histories (#4142)

Mansurshakh Japarov50bf775e8c83
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6d8995af6..19c5317ff 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -102,6 +102,13 @@ Headroom uses a `pyproject.toml`/`maturin` build backend. Older `pip`
versions may fail editable installs by looking for `setup.py`; upgrade `pip`
first or use `uv sync --extra dev`.
+Handler tests that read request bodies should use a real Starlette `Request`
+with ASGI receive messages, including streamed chunks, rather than patching the
+body reader. Size-limit regressions must configure an explicit test ceiling;
+the production ceiling is independent of the compression admission threshold.
+Avoid replacing imported proxy packages in `sys.modules`: it can split live
+helper and exception identities across full-suite test orderings.
+
### Dev Containers
Two configs ship for VS Code / Codespaces:
diff --git a/docs/content/docs/configuration.mdx b/docs/content/docs/configuration.mdx
index 00999f5cb..325cff7cc 100644
--- a/docs/content/docs/configuration.mdx
+++ b/docs/content/docs/configuration.mdx
@@ -21,6 +21,53 @@ See [Runtime Rollouts](/docs/runtime-rollouts) for policy, provenance, and
contributor rules.
If Codex history disappeared after using an older wrapper, see [Recover Codex State](/docs/codex-recovery) before wrapping Codex again.
+## Proxy request-body admission
+
+| Variable | Default | Purpose |
+|----------|---------|---------|
+| `HEADROOM_REQUEST_BODY_MAX_BYTES` | `104857600` (100 MiB) | Hard whole-request ceiling, resolved at process startup. Must be a positive integer. |
+
+The ceiling applies to the complete history, not each message or text chunk.
+Declared oversized HTTP bodies are rejected before reading them; chunked bodies
+are metered as they arrive. Oversized wire bodies return HTTP 413 by default,
+before JSON parsing, image classification, tokenization, or compression.
+Decompressed gzip, deflate, Brotli, and Zstandard bodies obey the same ceiling;
+`/v1/compress` returns the same size refusal for oversized decoded bodies,
+including requests with `x-headroom-bypass: true`.
+
+The previous 100 MiB admission default is retained. Anthropic Messages,
+OpenAI Chat/Responses, Gemini generateContent, and Bedrock InvokeModel HTTP
+routes have a separate **16 MiB compression threshold**, measured on the decoded body.
+Larger admitted histories skip body normalization, image processing, memory
+injection, tokenization, and compression. Native upstreams receive the original
+decoded JSON bytes; obsolete compression headers are removed. Streaming and
+non-streaming responses retain their normal protocol.
+
+Required auth-specific wire settings still apply: ChatGPT Responses receives
+`store: false` even when the client omitted it or set it to true. This
+reserializes the body only when that setting needs rewriting; an already-valid
+body remains byte-faithful. Vertex route-forced streaming is retained even
+without a `stream` body field.
+
+Envelope/model routing currently requires one JSON parse. Configured or
+per-request translating backends still perform the necessary wire conversion,
+but do not run request-side compression. Passthrough outcomes report zero
+compression savings and use provider-reported usage when available; missing
+usage is not presented as a local token measurement.
+
+The soft threshold applies to HTTP forwarding, not explicit `/v1/compress`
+calls or WebSocket messages. Auth, routing, rate and budget gates remain in
+force. Operators can choose a different hard ceiling and restart the proxy:
+
+```bash
+HEADROOM_REQUEST_BODY_MAX_BYTES=33554432 headroom proxy
+```
+
+Neither threshold is a process-memory limit or a mechanism for cancelling
+workers already running. JSON decoding, transport buffers, protocol translation,
+and third-party ASGI middleware still require memory; bound concurrency
+separately on small hosts.
+
## SDK Modes (`default_mode` / `headroom_mode`)
These modes apply to SDK usage via `HeadroomClient(default_mode=...)` or per-request `headroom_mode=...`. They are **not** the same as the proxy `--mode` flag.
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.py
index 4fb3f85b5..b6c5e10a3 100644
--- a/headroom/proxy/handlers/anthropic.py
+++ b/headroom/proxy/handlers/anthropic.py
@@ -1164,11 +1164,13 @@ class AnthropicHandlerMixin:
from headroom.proxy.helpers import (
MAX_MESSAGE_ARRAY_LENGTH,
MAX_REQUEST_BODY_SIZE,
+ RequestBodyTooLarge,
_get_image_compressor,
compute_turn_id,
read_request_json_with_bytes,
)
from headroom.proxy.modes import is_cache_mode, is_token_mode
+ from headroom.proxy.request_limit_policy import COMPRESSION_BODY_MAX_BYTES
from headroom.utils import extract_user_query
start_time = time.time()
@@ -1317,6 +1319,115 @@ class AnthropicHandlerMixin:
},
)
+ # Extract headers and tags
+ headers = dict(request.headers.items())
+ headers.pop("host", None)
+ headers.pop("content-length", None)
+ # The body reader content-decodes the inbound body (zstd/gzip/deflate/br)
+ # before either forwarding path sends plain JSON upstream.
+ # A stale content-encoding makes the upstream try to decompress
+ # already-decoded JSON and reject it with HTTP 400 (#1542 — same
+ # fix the /v1/responses path already carries).
+ headers.pop("content-encoding", None)
+ headers.pop("transfer-encoding", None)
+ # Strip accept-encoding so httpx negotiates its own encoding.
+ # Edge proxies (Cloudflare Workers, etc.) may forward "br, zstd" which
+ # the upstream can honor; if httpx lacks brotli support the response
+ # body is undecipherable → 502.
+ headers.pop("accept-encoding", None)
+ tags = extract_tags(headers)
+ from headroom.proxy.savings_attribution import bind_scope
+
+ bind_scope(tags, request.scope)
+ # Identify the harness (codex / claude-code / aider / etc.)
+ # from User-Agent or X-Client. Surfaced via the funnel into
+ # PERF logs and RequestLog.tags — see RequestOutcome.client.
+ client = classify_client(headers, default="claude")
+ # PR-A5 (P5-49): strip internal x-headroom-* from upstream-bound
+ # headers AFTER `_extract_tags` reads them. Inbound bypass gating
+ # uses the original `request.headers`; memory user-id
+ # is read from `request.headers` below if needed. From this
+ # point on, `headers` is the upstream-bound copy.
+ from headroom.proxy.helpers import (
+ _strip_internal_headers,
+ apply_keep_last_turns,
+ log_outbound_headers,
+ merge_extra_headers,
+ )
+
+ _pre_strip_count = sum(1 for k in headers if k.lower().startswith("x-headroom-"))
+ headers = _strip_internal_headers(headers)
+ # `upstream_base_url` is the per-request `x-headroom-base-url`
+ # override when the client sent one. These headers are secrets, so
+ # they only travel to a host the operator designated.
+ headers = merge_extra_headers(
+ headers,
+ self.config.anthropic_extra_headers,
+ upstream_url=upstream_base_url,
+ config=self.config,
+ )
+ log_outbound_headers(
+ forwarder="anthropic_messages",
+ stripped_count=_pre_strip_count
+ - sum(1 for k in headers if k.lower().startswith("x-headroom-")),
+ request_id=request_id,
+ )
+
+ # Subscription tracker: notify on OAuth requests (not API-key requests)
+ _auth_header = headers.get("authorization", "")
+ if _auth_header.startswith("Bearer ") and not _auth_header.startswith(
+ "Bearer sk-ant-api"
+ ):
+ from headroom.subscription.tracker import (
+ get_subscription_tracker as _get_sub_tracker,
+ )
+
+ _sub_tracker = _get_sub_tracker()
+ if _sub_tracker is not None:
+ from headroom.subscription.credential_policy import (
+ is_local_operator_connection,
+ )
+
+ # Only the local operator's bearer may become the polled
+ # account; a network caller only marks activity (01-F16).
+ _sub_tracker.notify_active(
+ _auth_header,
+ from_local_operator=is_local_operator_connection(request),
+ )
+
+ # Rate limiting
+ if self.rate_limiter:
+ # One identity rule for every provider: peer-owned, and
+ # credential-scoped only for proxy-token / direct loopback
+ # callers (headroom/proxy/rate_limit_identity.py).
+ rate_key = rate_limit_identity(request, headers)
+ allowed, wait_seconds = await self.rate_limiter.check_request(rate_key)
+ if not allowed:
+ await self.metrics.record_rate_limited(
+ provider=provider_name, source="headroom"
+ )
+ # Unit 4: release the pre-upstream semaphore before we
+ # bail out of the handler via HTTPException — FastAPI's
+ # exception handler will NOT run our ``finally``.
+ await _finalize_pre_upstream()
+ raise HTTPException(
+ status_code=429,
+ detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
+ headers={"Retry-After": str(int(wait_seconds) + 1)},
+ )
+
+ # Budget check
+ cost_tracker = self.cost_tracker
+ if cost_tracker:
+ allowed, remaining = cost_tracker.check_budget()
+ if not allowed:
+ # Unit 4: release the pre-upstream semaphore before we
+ # bail out of the handler via HTTPException.
+ await _finalize_pre_upstream()
+ raise HTTPException(
+ status_code=429,
+ detail=cost_tracker.budget_denial_detail(),
+ )
# 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
@@ -1327,6 +1438,8 @@ class AnthropicHandlerMixin:
try:
async with stage_timer.measure("read_request_json"):
body, original_body_bytes = await read_request_json_with_bytes(request)
+ except RequestBodyTooLarge:
+ raise
except ClientDisconnect:
# The client (e.g. an interrupted/compacting Claude Code
# session) went away mid-read. There is no one left to answer
@@ -1348,6 +1461,56 @@ class AnthropicHandlerMixin:
},
},
)
+ if len(original_body_bytes) > COMPRESSION_BODY_MAX_BYTES:
+ logger.info(
+ "[%s] event=compression_passthrough reason=request_body_soft_limit "
+ "bytes=%d threshold=%d",
+ request_id,
+ len(original_body_bytes),
+ COMPRESSION_BODY_MAX_BYTES,
+ )
+ from headroom.proxy.route_advice import resolver_for
+
+ backend = resolver_for(self).for_request(request, body=body)
+ passthrough_model = body.get("model") or model_override or "unknown"
+ if not isinstance(passthrough_model, str):
+ passthrough_model = "unknown"
+ if backend is not None:
+ if model_override and not body.get("model"):
+ body["model"] = model_override
+ await _finalize_pre_upstream()
+ return await self._handle_backend_passthrough(
+ body,
+ headers,
+ backend,
+ "anthropic",
+ passthrough_model,
+ request_id,
+ start_time,
+ tags,
+ force_stream=force_stream,
+ )
+ passthrough_base = upstream_base_url or self.ANTHROPIC_API_URL
+ passthrough_url = build_anthropic_upstream_url(
+ passthrough_base, request.url.path, request.url.query
+ )
+ assert self.http_client is not None, "http_client must be initialized"
+ upstream_request = self.http_client.build_request(
+ request.method,
+ passthrough_url,
+ headers=headers,
+ content=original_body_bytes,
+ )
+ await _finalize_pre_upstream()
+ return await self.handle_passthrough(
+ request,
+ passthrough_base,
+ endpoint_name="messages",
+ provider=provider_name,
+ _upstream_request=upstream_request,
+ _model=passthrough_model,
+ _start_time=start_time,
+ )
# This is a boolean capability classification only. The
# safeguards value itself is never copied into logs, metrics, or
# any Headroom-owned state.
@@ -1480,115 +1643,6 @@ class AnthropicHandlerMixin:
# NOTE: Upstream temporarily disabled broad image compression due to
# token-counting inaccuracies. We only compress the latest non-frozen
# user turn later in this handler to preserve Anthropic prefix caching.
- # Extract headers and tags
- headers = dict(request.headers.items())
- headers.pop("host", None)
- headers.pop("content-length", None)
- # read_request_json_with_bytes already content-decoded the inbound
- # body (zstd/gzip/deflate/br), so the bytes we forward are plain.
- # A stale content-encoding makes the upstream try to decompress
- # already-decoded JSON and reject it with HTTP 400 (#1542 — same
- # fix the /v1/responses path already carries).
- headers.pop("content-encoding", None)
- headers.pop("transfer-encoding", None)
- # Strip accept-encoding so httpx negotiates its own encoding.
- # Edge proxies (Cloudflare Workers, etc.) may forward "br, zstd" which
- # the upstream can honor; if httpx lacks brotli support the response
- # body is undecipherable → 502.
- headers.pop("accept-encoding", None)
- tags = extract_tags(headers)
- from headroom.proxy.savings_attribution import bind_scope
-
- bind_scope(tags, request.scope)
- # Identify the harness (codex / claude-code / aider / etc.)
- # from User-Agent or X-Client. Surfaced via the funnel into
- # PERF logs and RequestLog.tags — see RequestOutcome.client.
- client = classify_client(headers, default="claude")
- # PR-A5 (P5-49): strip internal x-headroom-* from upstream-bound
- # headers AFTER `_extract_tags` reads them. Inbound bypass gating
- # uses `request.headers.get(...)` directly above; memory user-id
- # is read from `request.headers` below if needed. From this
- # point on, `headers` is the upstream-bound copy.
- from headroom.proxy.helpers import (
- _strip_internal_headers,
- apply_keep_last_turns,
- log_outbound_headers,
- merge_extra_headers,
- )
-
- _pre_strip_count = sum(1 for k in headers if k.lower().startswith("x-headroom-"))
- headers = _strip_internal_headers(headers)
- # `upstream_base_url` is the per-request `x-headroom-base-url`
- # override when the client sent one. These headers are secrets, so
- # they only travel to a host the operator designated.
- headers = merge_extra_headers(
- headers,
- self.config.anthropic_extra_headers,
- upstream_url=upstream_base_url,
- config=self.config,
- )
- log_outbound_headers(
- forwarder="anthropic_messages",
- stripped_count=_pre_strip_count
- - sum(1 for k in headers if k.lower().startswith("x-headroom-")),
- request_id=request_id,
- )
-
- # Subscription tracker: notify on OAuth requests (not API-key requests)
- _auth_header = headers.get("authorization", "")
- if _auth_header.startswith("Bearer ") and not _auth_header.startswith(
- "Bearer sk-ant-api"
- ):
- from headroom.subscription.tracker import (
- get_subscription_tracker as _get_sub_tracker,
- )
-
- _sub_tracker = _get_sub_tracker()
- if _sub_tracker is not None:
- from headroom.subscription.credential_policy import (
- is_local_operator_connection,
- )
-
- # Only the local operator's bearer may become the polled
- # account; a network caller only marks activity (01-F16).
- _sub_tracker.notify_active(
- _auth_header,
- from_local_operator=is_local_operator_connection(request),
- )
-
- # Rate limiting
- if self.rate_limiter:
- # One identity rule for every provider: peer-owned, and
- # credential-scoped only for proxy-token / direct loopback
- # callers (headroom/proxy/rate_limit_identity.py).
- rate_key = rate_limit_identity(request, headers)
- allowed, wait_seconds = await self.rate_limiter.check_request(rate_key)
- if not allowed:
- await self.metrics.record_rate_limited(
- provider=provider_name, source="headroom"
- )
- # Unit 4: release the pre-upstream semaphore before we
- # bail out of the handler via HTTPException — FastAPI's
- # exception handler will NOT run our ``finally``.
- await _finalize_pre_upstream()
- raise HTTPException(
- status_code=429,
- detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
- headers={"Retry-After": str(int(wait_seconds) + 1)},
- )
-
- # Budget check
- cost_tracker = self.cost_tracker
- if cost_tracker:
- allowed, remaining = cost_tracker.check_budget()
- if not allowed:
- # Unit 4: release the pre-upstream semaphore before we
- # bail out of the handler via HTTPException.
- await _finalize_pre_upstream()
- raise HTTPException(
- status_code=429,
- detail=cost_tracker.budget_denial_detail(),
- )
# Memory: Get user ID when memory is enabled (fallback to "default" for simple DevEx).
# Reads `request.headers` directly because the local `headers` dict was
diff --git a/headroom/proxy/handlers/bedrock.py b/headroom/proxy/handlers/bedrock.py
index 6933e605c..b2eedbc23 100644
--- a/headroom/proxy/handlers/bedrock.py
+++ b/headroom/proxy/handlers/bedrock.py
@@ -84,6 +84,7 @@ class BedrockHandlerMixin:
read_request_json_with_bytes,
)
from headroom.proxy.modes import is_cache_mode
+ from headroom.proxy.request_limit_policy import COMPRESSION_BODY_MAX_BYTES
from headroom.utils import extract_user_query
start_time = time.time()
@@ -176,12 +177,22 @@ class BedrockHandlerMixin:
messages = body.get("messages")
bypass = (
_headroom_bypass_enabled(request.headers)
+ or len(raw) > COMPRESSION_BODY_MAX_BYTES
or not getattr(self.config, "optimize", True) # type: ignore[attr-defined]
or is_cache_mode(getattr(self.config, "mode", "token")) # type: ignore[attr-defined]
or not isinstance(messages, list)
or not messages
or len(messages) > MAX_MESSAGE_ARRAY_LENGTH
)
+ if len(raw) > COMPRESSION_BODY_MAX_BYTES:
+ tags["passthrough_reason"] = "request_body_soft_limit"
+ logger.info(
+ "[%s] event=compression_passthrough reason=request_body_soft_limit "
+ "bytes=%d threshold=%d",
+ request_id,
+ len(raw),
+ COMPRESSION_BODY_MAX_BYTES,
+ )
outbound = raw
original_tokens = 0
diff --git a/headroom/proxy/handlers/gemini.py b/headroom/proxy/handlers/gemini.py
index beacd2bfb..30fb58ec5 100644
--- a/headroom/proxy/handlers/gemini.py
+++ b/headroom/proxy/handlers/gemini.py
@@ -344,7 +344,12 @@ class GeminiHandlerMixin:
from fastapi import HTTPException
from fastapi.responses import JSONResponse, Response
- from headroom.proxy.helpers import MAX_REQUEST_BODY_SIZE, _read_request_json
+ from headroom.proxy.helpers import (
+ MAX_REQUEST_BODY_SIZE,
+ RequestBodyTooLarge,
+ read_request_json_with_bytes,
+ )
+ from headroom.proxy.request_limit_policy import COMPRESSION_BODY_MAX_BYTES
from headroom.utils import extract_user_query
def _stream_url(base_url: str) -> str:
@@ -374,7 +379,9 @@ class GeminiHandlerMixin:
# Parse request
try:
- body = await _read_request_json(request)
+ body, original_body_bytes = await read_request_json_with_bytes(request)
+ except RequestBodyTooLarge:
+ raise
except (json.JSONDecodeError, ValueError) as e:
return JSONResponse(
status_code=400,
@@ -415,6 +422,64 @@ class GeminiHandlerMixin:
stripped_count=_pre_strip_count_gem,
request_id=request_id,
)
+ # Rate limiting: one identity rule for every provider
+ # (headroom/proxy/rate_limit_identity.py).
+ if self.rate_limiter:
+ rate_key = rate_limit_identity(request, headers)
+ allowed, wait_seconds = await self.rate_limiter.check_request(rate_key)
+ if not allowed:
+ await self.metrics.record_rate_limited(provider=provider_name, source="headroom")
+ raise HTTPException(
+ status_code=429,
+ detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
+ )
+
+ # Budget check
+ cost_tracker = self.cost_tracker
+ if cost_tracker:
+ allowed, remaining = cost_tracker.check_budget()
+ if not allowed:
+ raise HTTPException(
+ status_code=429,
+ detail=cost_tracker.budget_denial_detail(),
+ )
+ if len(original_body_bytes) > COMPRESSION_BODY_MAX_BYTES:
+ is_streaming = request.query_params.get("alt") == "sse" or request.url.path.endswith(
+ ":streamGenerateContent"
+ )
+ passthrough_path = request.url.path
+ if is_streaming:
+ passthrough_path = passthrough_path.replace(
+ ":generateContent", ":streamGenerateContent"
+ )
+ passthrough_base = upstream_base_url or self.GEMINI_API_URL
+ passthrough_url = build_copilot_upstream_url(passthrough_base, passthrough_path)
+ if is_streaming:
+ passthrough_url = _stream_url(passthrough_url)
+ elif request.url.query:
+ passthrough_url = f"{passthrough_url}?{request.url.query}"
+ headers.pop("content-encoding", None)
+ headers.pop("transfer-encoding", None)
+ assert self.http_client is not None, "http_client must be initialized"
+ upstream_request = self.http_client.build_request(
+ request.method, passthrough_url, headers=headers, content=original_body_bytes
+ )
+ logger.info(
+ "[%s] event=compression_passthrough reason=request_body_soft_limit "
+ "bytes=%d threshold=%d",
+ request_id,
+ len(original_body_bytes),
+ COMPRESSION_BODY_MAX_BYTES,
+ )
+ return await self.handle_passthrough(
+ request,
+ passthrough_base,
+ endpoint_name="streamGenerateContent" if is_streaming else "generateContent",
+ provider=provider_name,
+ _upstream_request=upstream_request,
+ _model=model,
+ _start_time=start_time,
+ )
# Memory: Get user ID when memory is enabled. Reads `request.headers`
# directly because `headers` was stripped of `x-headroom-*` (PR-A5).
@@ -472,28 +537,6 @@ class GeminiHandlerMixin:
)
memory_decision.apply_to_tags(tags)
- # Rate limiting: one identity rule for every provider
- # (headroom/proxy/rate_limit_identity.py).
- if self.rate_limiter:
- rate_key = rate_limit_identity(request, headers)
- allowed, wait_seconds = await self.rate_limiter.check_request(rate_key)
- if not allowed:
- await self.metrics.record_rate_limited(provider=provider_name, source="headroom")
- raise HTTPException(
- status_code=429,
- detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
- )
-
- # Budget check
- cost_tracker = self.cost_tracker
- if cost_tracker:
- allowed, remaining = cost_tracker.check_budget()
- if not allowed:
- raise HTTPException(
- status_code=429,
- detail=cost_tracker.budget_denial_detail(),
- )
-
# Convert Gemini format to messages for optimization
system_instruction = body.get("systemInstruction")
messages, preserved_indices = self._gemini_contents_to_messages(
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index 8d7dcc533..9e9c7a84e 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -31,6 +31,7 @@ from headroom.proxy.conversation_savings import savings_conversation_key
from headroom.proxy.handlers._failure_logging import log_hook_failure, log_request_failure
from headroom.proxy.helpers import (
COMPRESSION_TIMEOUT_SECONDS,
+ RequestBodyTooLarge,
_headroom_bypass_enabled,
extract_tags,
invalid_request_body_message,
@@ -41,6 +42,7 @@ from headroom.proxy.identity import resolve_memory_identity
from headroom.proxy.loopback_guard import is_loopback_host
from headroom.proxy.modes import is_cache_mode
from headroom.proxy.provider_usage import (
+ anthropic_cache_ttl_buckets,
billed_input_for_provider,
billed_input_from_usage,
usage_int,
@@ -513,6 +515,17 @@ def _resolve_openai_chat_handler_path(base_url: str, model: str | None) -> str:
return _OPENAI_CHAT_COMPLETIONS_PATH
+def _resolve_openai_chat_forward_path(
+ request_headers: dict[str, str], custom_upstream_base_url: str | None
+) -> str:
+ """Keep Chat Completions bodies on their effective Chat wire destination."""
+ if custom_upstream_base_url is not None:
+ return _resolve_openai_handler_path(
+ request_headers, handler_path=_OPENAI_CHAT_COMPLETIONS_PATH
+ )
+ return "/v1/chat/completions"
+
+
def _append_request_query(url: str, query: str) -> str:
if not query:
return url
@@ -627,6 +640,7 @@ def _passthrough_usage_from_json(payload: Any, provider: str | None = None) -> d
output_tokens = usage.get("completion_tokens")
details = usage.get("prompt_tokens_details") or usage.get("input_tokens_details") or {}
cache_read = details.get("cached_tokens") if isinstance(details, dict) else None
+ cache_5m, cache_1h = anthropic_cache_ttl_buckets(usage)
return {
# The billed total. Anthropic-shape usage reports input_tokens as
# the uncached tail only (cache buckets are disjoint); OpenAI's
@@ -642,6 +656,8 @@ def _passthrough_usage_from_json(payload: Any, provider: str | None = None) -> d
details.get("cache_write_tokens") if isinstance(details, dict) else None,
)
),
+ "cache_creation_ephemeral_5m_input_tokens": cache_5m,
+ "cache_creation_ephemeral_1h_input_tokens": cache_1h,
}
return {}
@@ -2068,6 +2084,20 @@ def _prefers_http1_passthrough(base_url: str) -> bool:
return host == "chatgpt.com" or host.endswith(".chatgpt.com")
+def _openai_outcome_provider(
+ method: str, path: str, custom_base_url: str | None, upstream_base_url: str
+) -> str:
+ """Keep native and opaque forwarding on the same bounded provider taxonomy."""
+ _, provider = _custom_base_passthrough_telemetry(method, path, custom_base_url or "")
+ return provider or (
+ CUSTOM_BASE_PROVIDER
+ if custom_base_url
+ else "xai"
+ if _is_xai_upstream(upstream_base_url)
+ else "openai"
+ )
+
+
class OpenAIHandlerMixin:
"""Mixin providing OpenAI API handler methods for HeadroomProxy."""
@@ -3500,9 +3530,10 @@ class OpenAIHandlerMixin:
COMPRESSION_TIMEOUT_SECONDS,
MAX_MESSAGE_ARRAY_LENGTH,
MAX_REQUEST_BODY_SIZE,
- _read_request_json,
+ read_request_json_with_bytes,
)
from headroom.proxy.modes import is_cache_mode, is_token_mode
+ from headroom.proxy.request_limit_policy import COMPRESSION_BODY_MAX_BYTES
from headroom.utils import extract_user_query
start_time = time.time()
@@ -3542,7 +3573,9 @@ class OpenAIHandlerMixin:
# Parse request
try:
- body = await _read_request_json(request)
+ body, original_body_bytes = await read_request_json_with_bytes(request)
+ except RequestBodyTooLarge:
+ raise
except (json.JSONDecodeError, ValueError) as e:
return JSONResponse(
status_code=400,
@@ -3556,16 +3589,6 @@ class OpenAIHandlerMixin:
)
model = body.get("model", "unknown")
messages = body.get("messages", [])
- # O1 (2026-09-27 perf audit): the snapshot of the original
- # conversation aliases the live list unless hooks, pipeline extensions
- # or turn hooks are configured; those can mutate `messages` in place
- # (pre_compress receives the live list), so then it is an
- # independently owned copy (see snapshot_original_messages).
- from headroom.proxy.helpers import snapshot_original_messages
-
- original_client_messages = snapshot_original_messages(
- messages, hooks=self.config.hooks, extensions=self.pipeline_extensions
- )
custom_upstream_base_url = _resolve_openai_upstream_base(request.headers)
upstream_base_url = self._resolve_openai_upstream(request)
# Ghost text and next edits: CAPI does not serve these models. A
@@ -3587,6 +3610,139 @@ class OpenAIHandlerMixin:
if custom_upstream_base_url is not None
else f"/v1{handler_path_suffix}"
)
+ headers = dict(request.headers.items())
+ headers.pop("host", None)
+ headers.pop("content-length", None)
+ # The parsed body was already content-decoded upstream, so the bytes we
+ # forward are plain JSON. A stale content-encoding makes OpenAI try to
+ # decompress already-decoded JSON and reject it with HTTP 400 (#1542 —
+ # same fix the /v1/responses path already carries).
+ headers.pop("content-encoding", None)
+ headers.pop("transfer-encoding", None)
+ # Strip accept-encoding so httpx negotiates its own encoding.
+ # Cloudflare Workers forward "br, zstd" which OpenAI may honor;
+ # if httpx lacks brotli support the response body is undecipherable → 502.
+ headers.pop("accept-encoding", None)
+ tags = extract_tags(headers)
+ from headroom.proxy.savings_attribution import bind_scope
+
+ bind_scope(tags, request.scope)
+ client = classify_client(headers)
+ # PR-A5 (P5-49): strip internal x-headroom-* from upstream-bound
+ # headers AFTER `_extract_tags` reads them. Inbound bypass gating
+ # uses `request.headers.get(...)` above; memory user-id reads
+ # `request.headers` below. From this point on, `headers` is the
+ # upstream-bound copy.
+ from headroom.proxy.helpers import (
+ _strip_internal_headers,
+ apply_keep_last_turns,
+ log_outbound_headers,
+ merge_extra_headers,
+ )
+
+ _pre_strip_count_chat = sum(1 for k in headers if k.lower().startswith("x-headroom-"))
+ headers = _strip_internal_headers(headers)
+ # Configured backends own their destination and authentication, so they
+ # retain the existing extra-header policy. The direct path selects
+ # extras from the resolved OpenAI-compatible upstream. Direct custom
+ # upstreams must also pass the operator-designated-host check before
+ # receiving those extras.
+ headers = merge_extra_headers(
+ headers,
+ self.config.openai_extra_headers
+ if self.anthropic_backend is not None
+ else self._openai_extra_headers_for_upstream(upstream_base_url),
+ upstream_url=(None if self.anthropic_backend is not None else custom_upstream_base_url),
+ config=self.config,
+ )
+ log_outbound_headers(
+ forwarder="openai_chat_completions",
+ stripped_count=_pre_strip_count_chat,
+ request_id=request_id,
+ )
+ openai_chat_outcome_provider = _openai_outcome_provider(
+ request.method, handler_path, custom_upstream_base_url, upstream_base_url
+ )
+ # Rate limiting
+ if self.rate_limiter:
+ rate_key = rate_limit_identity(request, headers)
+ allowed, wait_seconds = await self.rate_limiter.check_request(rate_key)
+ if not allowed:
+ await self.metrics.record_rate_limited(
+ provider=openai_chat_outcome_provider, source="headroom"
+ )
+ raise HTTPException(
+ status_code=429,
+ detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
+ )
+
+ # Budget check
+ cost_tracker = self.cost_tracker
+ if cost_tracker:
+ allowed, remaining = cost_tracker.check_budget()
+ if not allowed:
+ raise HTTPException(
+ status_code=429,
+ detail=cost_tracker.budget_denial_detail(),
+ )
+ if len(original_body_bytes) > COMPRESSION_BODY_MAX_BYTES:
+ from headroom.proxy.route_advice import resolver_for
+
+ logger.info(
+ "[%s] event=compression_passthrough reason=request_body_soft_limit "
+ "bytes=%d threshold=%d",
+ request_id,
+ len(original_body_bytes),
+ COMPRESSION_BODY_MAX_BYTES,
+ )
+ backend = resolver_for(self).for_request(
+ request, body=body, native_providers=("openai",)
+ )
+ passthrough_model = body.get("model", "unknown")
+ if not isinstance(passthrough_model, str):
+ passthrough_model = "unknown"
+ if backend is not None:
+ return await self._handle_backend_passthrough(
+ body,
+ headers,
+ backend,
+ "openai",
+ passthrough_model,
+ request_id,
+ start_time,
+ tags,
+ )
+ handler_path = _resolve_openai_chat_forward_path(
+ request.headers, custom_upstream_base_url
+ )
+ url = _append_request_query(
+ build_copilot_upstream_url(upstream_base_url, handler_path),
+ request.url.query,
+ )
+ assert self.http_client is not None, "http_client must be initialized"
+ upstream_request = self.http_client.build_request(
+ request.method, url, headers=headers, content=original_body_bytes
+ )
+ return await self.handle_passthrough(
+ request,
+ upstream_base_url,
+ endpoint_name="chat/completions",
+ provider=openai_chat_outcome_provider,
+ _upstream_request=upstream_request,
+ _model=passthrough_model,
+ _start_time=start_time,
+ )
+
+ # O1 (2026-09-27 perf audit): the snapshot of the original
+ # conversation aliases the live list unless hooks, pipeline extensions
+ # or turn hooks are configured; those can mutate `messages` in place
+ # (pre_compress receives the live list), so then it is an
+ # independently owned copy (see snapshot_original_messages).
+ from headroom.proxy.helpers import snapshot_original_messages
+
+ original_client_messages = snapshot_original_messages(
+ messages, hooks=self.config.hooks, extensions=self.pipeline_extensions
+ )
input_event = self.pipeline_extensions.emit(
PipelineStage.INPUT_RECEIVED,
operation="proxy.request",
@@ -3669,84 +3825,14 @@ class OpenAIHandlerMixin:
if compressor and hasattr(compressor, "close"):
compressor.close()
- headers = dict(request.headers.items())
- headers.pop("host", None)
- headers.pop("content-length", None)
- # The parsed body was already content-decoded upstream, so the bytes we
- # forward are plain JSON. A stale content-encoding makes OpenAI try to
- # decompress already-decoded JSON and reject it with HTTP 400 (#1542 —
- # same fix the /v1/responses path already carries).
- headers.pop("content-encoding", None)
- headers.pop("transfer-encoding", None)
- # Strip accept-encoding so httpx negotiates its own encoding.
- # Cloudflare Workers forward "br, zstd" which OpenAI may honor;
- # if httpx lacks brotli support the response body is undecipherable → 502.
- headers.pop("accept-encoding", None)
- tags = extract_tags(headers)
- from headroom.proxy.savings_attribution import bind_scope
-
- bind_scope(tags, request.scope)
- client = classify_client(headers)
# Surface the image-compression decision (computed earlier) into
# tags now that the tags dict exists. Same observability pattern
# the funnel uses for passthrough_reason + memory_skip_reason.
_image_decision.apply_to_tags(tags)
- # PR-A5 (P5-49): strip internal x-headroom-* from upstream-bound
- # headers AFTER `_extract_tags` reads them. Inbound bypass gating
- # uses `request.headers.get(...)` above; memory user-id reads
- # `request.headers` below. From this point on, `headers` is the
- # upstream-bound copy.
- from headroom.proxy.helpers import (
- _strip_internal_headers,
- apply_keep_last_turns,
- log_outbound_headers,
- merge_extra_headers,
- )
-
- _pre_strip_count_chat = sum(1 for k in headers if k.lower().startswith("x-headroom-"))
- headers = _strip_internal_headers(headers)
- # Configured backends own their destination and authentication, so they
- # retain the existing extra-header policy. The direct path selects
- # extras from the resolved OpenAI-compatible upstream. Direct custom
- # upstreams must also pass the operator-designated-host check before
- # receiving those extras.
- headers = merge_extra_headers(
- headers,
- self.config.openai_extra_headers
- if self.anthropic_backend is not None
- else self._openai_extra_headers_for_upstream(upstream_base_url),
- upstream_url=(None if self.anthropic_backend is not None else custom_upstream_base_url),
- config=self.config,
- )
- log_outbound_headers(
- forwarder="openai_chat_completions",
- stripped_count=_pre_strip_count_chat,
- request_id=request_id,
- )
custom_upstream_base_url = _resolve_openai_upstream_base(request.headers)
- handler_path = (
- _resolve_openai_handler_path(
- request.headers,
- handler_path=_OPENAI_CHAT_COMPLETIONS_PATH,
- )
- if custom_upstream_base_url is not None
- else "/v1/chat/completions"
- )
- _, custom_chat_provider = _custom_base_passthrough_telemetry(
- request.method,
- handler_path,
- custom_upstream_base_url or "",
- )
- # Fixed taxonomy from the shared helper (zen, zai, meta, openai, xai);
- # any other custom base is the shared "custom" bucket. Never derive the
- # label from the request-controlled hostname — see the review on #3759.
- # Grok CLI routed to xAI without a base-url header is still xai.
- openai_chat_outcome_provider = custom_chat_provider or (
- CUSTOM_BASE_PROVIDER
- if custom_upstream_base_url
- else "xai"
- if _is_xai_upstream(upstream_base_url)
- else "openai"
+ handler_path = _resolve_openai_chat_forward_path(request.headers, custom_upstream_base_url)
+ openai_chat_outcome_provider = _openai_outcome_provider(
+ request.method, handler_path, custom_upstream_base_url, upstream_base_url
)
# Memory: Get user ID when memory is enabled. Reads `request.headers`
@@ -3796,29 +3882,6 @@ class OpenAIHandlerMixin:
)
memory_decision.apply_to_tags(tags)
- # Rate limiting
- if self.rate_limiter:
- rate_key = rate_limit_identity(request, headers)
- allowed, wait_seconds = await self.rate_limiter.check_request(rate_key)
- if not allowed:
- await self.metrics.record_rate_limited(
- provider=openai_chat_outcome_provider, source="headroom"
- )
- raise HTTPException(
- status_code=429,
- detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
- )
-
- # Budget check
- cost_tracker = self.cost_tracker
- if cost_tracker:
- allowed, remaining = cost_tracker.check_budget()
- if not allowed:
- raise HTTPException(
- status_code=429,
- detail=cost_tracker.budget_denial_detail(),
- )
-
# Snapshot cache-key fields ONCE here (pre-upstream), reused verbatim
# at the cache.set site below — re-reading body at set risks a mutated
# body (e.g. tools reassigned) and a key mismatch (#327). OpenAI's
@@ -6076,6 +6139,7 @@ class OpenAIHandlerMixin:
MAX_REQUEST_BODY_SIZE,
read_request_json_with_bytes,
)
+ from headroom.proxy.request_limit_policy import COMPRESSION_BODY_MAX_BYTES
from headroom.utils import extract_user_query
start_time = time.time()
@@ -6120,6 +6184,8 @@ class OpenAIHandlerMixin:
# (#1542); byte-faithful passthrough avoids that.
try:
body, original_body_bytes = await read_request_json_with_bytes(request)
+ except RequestBodyTooLarge:
+ raise
except (json.JSONDecodeError, ValueError) as e:
return JSONResponse(
status_code=400,
@@ -6255,6 +6321,90 @@ class OpenAIHandlerMixin:
headers, is_chatgpt_auth = _resolve_codex_routing_headers(headers)
if is_chatgpt_auth:
client = "codex"
+ # Rate limiting
+ if self.rate_limiter:
+ rate_key = rate_limit_identity(request, headers)
+ allowed, wait_seconds = await self.rate_limiter.check_request(rate_key)
+ if not allowed:
+ await self.metrics.record_rate_limited(provider="openai", source="headroom")
+ raise HTTPException(
+ status_code=429,
+ detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
+ )
+
+ # Budget check
+ cost_tracker = self.cost_tracker
+ if cost_tracker:
+ allowed, remaining = cost_tracker.check_budget()
+ if not allowed:
+ raise HTTPException(
+ status_code=429,
+ detail=cost_tracker.budget_denial_detail(),
+ )
+ # Route to correct endpoint based on auth mode.
+ # ChatGPT session auth (codex login) uses chatgpt.com, not api.openai.com.
+ if is_chatgpt_auth:
+ url = codex_responses_http_url()
+ else:
+ handler_path = (
+ _resolve_openai_handler_path(request.headers, handler_path=_OPENAI_RESPONSES_PATH)
+ if custom_upstream_base_url is not None
+ else "/v1/responses"
+ )
+ # Reuse the OpenAI-compatible candidate resolved at request entry.
+ # In this non-ChatGPT branch it is also the actual upstream, keeping
+ # direct routing and header selection aligned.
+ url = build_copilot_upstream_url(
+ openai_upstream_base_url,
+ handler_path,
+ )
+ url = _append_request_query(url, request.url.query)
+ if len(original_body_bytes) > COMPRESSION_BODY_MAX_BYTES:
+ outbound_body_bytes = original_body_bytes
+ if _ensure_chatgpt_responses_store_false(body, is_chatgpt_auth=is_chatgpt_auth):
+ outbound_body_bytes = json.dumps(
+ body, separators=(",", ":"), ensure_ascii=False
+ ).encode("utf-8")
+ assert self.http_client is not None, "http_client must be initialized"
+ upstream_request = self.http_client.build_request(
+ request.method, url, headers=headers, content=outbound_body_bytes
+ )
+ logger.info(
+ "[%s] event=compression_passthrough reason=request_body_soft_limit "
+ "bytes=%d threshold=%d",
+ request_id,
+ len(original_body_bytes),
+ COMPRESSION_BODY_MAX_BYTES,
+ )
+ passthrough_provider = (
+ "openai"
+ if is_chatgpt_auth
+ else _openai_outcome_provider(
+ request.method, handler_path, custom_upstream_base_url, openai_upstream_base_url
+ )
+ )
+ return await self.handle_passthrough(
+ request,
+ openai_upstream_base_url,
+ endpoint_name="responses",
+ provider=passthrough_provider,
+ _upstream_request=upstream_request,
+ _model=model if isinstance(model, str) else "unknown",
+ _start_time=start_time,
+ )
+ from headroom.proxy.helpers import capture_codex_wire_debug
+
+ capture_codex_wire_debug(
+ "http_inbound_request",
+ request_id=request_id,
+ transport="http",
+ direction="client_to_headroom",
+ method=request.method,
+ url=str(request.url),
+ headers=dict(request.headers.items()),
+ body=body,
+ metadata={"path": request.url.path, "stream": stream},
+ )
codex_project = None
codex_project_root_override = (
getattr(getattr(self.memory_handler, "config", None), "project_root_override", "")
@@ -6384,27 +6534,6 @@ class OpenAIHandlerMixin:
request_context=memory_request_ctx,
)
- # Rate limiting
- if self.rate_limiter:
- rate_key = rate_limit_identity(request, headers)
- allowed, wait_seconds = await self.rate_limiter.check_request(rate_key)
- if not allowed:
- await self.metrics.record_rate_limited(provider="openai", source="headroom")
- raise HTTPException(
- status_code=429,
- detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
- )
-
- # Budget check
- cost_tracker = self.cost_tracker
- if cost_tracker:
- allowed, remaining = cost_tracker.check_budget()
- if not allowed:
- raise HTTPException(
- status_code=429,
- detail=cost_tracker.budget_denial_detail(),
- )
-
# Token counting on converted messages (offloaded off the event loop — GH #1701)
tokenizer, original_tokens = await self._count_tokens_offloaded(model, messages)
# Messages-only count, preserved for the output shaper's turn/size
@@ -6635,25 +6764,6 @@ class OpenAIHandlerMixin:
f"(backend '{self.anthropic_backend.name}' not used for Responses API)"
)
- # Route to correct endpoint based on auth mode.
- # ChatGPT session auth (codex login) uses chatgpt.com, not api.openai.com.
- if is_chatgpt_auth:
- url = codex_responses_http_url()
- else:
- handler_path = (
- _resolve_openai_handler_path(request.headers, handler_path=_OPENAI_RESPONSES_PATH)
- if custom_upstream_base_url is not None
- else "/v1/responses"
- )
- # Reuse the OpenAI-compatible candidate resolved at request entry.
- # In this non-ChatGPT branch it is also the actual upstream, keeping
- # direct routing and header selection aligned.
- url = build_copilot_upstream_url(
- openai_upstream_base_url,
- handler_path,
- )
- url = _append_request_query(url, request.url.query)
-
# Responses re-sends the whole transcript every turn and the router
# recompresses all of it, so ``tokens_saved`` below is the running
# total for the CONVERSATION, not for this turn. Carrying the key and
@@ -10929,7 +11039,7 @@ class OpenAIHandlerMixin:
from headroom.proxy.gateway_responses import build_view as build_responses_view
from headroom.proxy.gateway_responses import is_responses_body
from headroom.proxy.gateway_responses import mark_view as mark_responses_view
- from headroom.proxy.helpers import _read_request_json
+ from headroom.proxy.helpers import RequestBodyTooLarge, _read_request_json
def _gateway_invalid(e: CompressTurnError) -> JSONResponse:
return JSONResponse(
@@ -10951,6 +11061,8 @@ class OpenAIHandlerMixin:
if request.headers.get("x-headroom-bypass", "").lower() == "true":
try:
body = await _read_request_json(request)
+ except RequestBodyTooLarge:
+ raise
except (json.JSONDecodeError, ValueError) as e:
return JSONResponse(
status_code=400,
@@ -10976,6 +11088,8 @@ class OpenAIHandlerMixin:
try:
body = await _read_request_json(request)
+ except RequestBodyTooLarge:
+ raise
except Exception:
return JSONResponse(
status_code=400,
@@ -11922,12 +12036,116 @@ class OpenAIHandlerMixin:
except (TypeError, ValueError):
return body
+ async def _handle_backend_passthrough(
+ self,
+ body: dict[str, Any],
+ headers: dict[str, str],
+ backend: Any,
+ wire_provider: str,
+ model: str,
+ request_id: str,
+ start_time: float,
+ tags: dict[str, str],
+ *,
+ force_stream: bool = False,
+ ) -> Response:
+ """Retain configured backend translation without request-side transforms."""
+ from fastapi.responses import JSONResponse
+
+ tags["passthrough_reason"] = "request_body_soft_limit"
+ if body.get("stream", False) or force_stream:
+ # No local tokenization ran. Zero is the existing "unmeasured"
+ # convention; these finalizers separately record actual provider usage.
+ if wire_provider == "openai":
+ return await self._stream_openai_via_backend(
+ body,
+ headers,
+ model,
+ request_id,
+ start_time,
+ 0,
+ 0,
+ 0,
+ [],
+ tags,
+ 0,
+ backend=backend,
+ )
+ return await self._stream_response_bedrock(
+ body,
+ headers,
+ wire_provider,
+ model,
+ request_id,
+ 0,
+ 0,
+ 0,
+ [],
+ tags,
+ 0,
+ backend=backend,
+ )
+
+ try:
+ response = (
+ await backend.send_openai_message(body, headers)
+ if wire_provider == "openai"
+ else await backend.send_message(body, headers)
+ )
+ payload = response.body
+ status_code = response.status_code
+ response_headers = _sanitize_forwarded_response_headers(response.headers)
+ except Exception as exc:
+ logger.error("[%s] Backend passthrough failed: %s", request_id, exc)
+ error = public_errors.classify_or_internal(exc)
+ payload = (
+ public_errors.openai_error_body(error, error_type="api_error")
+ if wire_provider == "openai"
+ else public_errors.anthropic_error_body(
+ error, request_id=str(request_id), error_type="api_error"
+ )
+ )
+ status_code = 500
+ response_headers = {}
+
+ usage = _passthrough_usage_from_json(payload, wire_provider)
+ input_tokens = usage.get("input_tokens", 0)
+ cache_read = usage.get("cache_read_input_tokens", 0)
+ cache_write = usage.get("cache_creation_input_tokens", 0)
+ await self._record_request_outcome(
+ RequestOutcome(
+ request_id=request_id,
+ provider=backend.name,
+ model=model,
+ original_tokens=input_tokens,
+ optimized_tokens=input_tokens,
+ provider_input_tokens=input_tokens,
+ output_tokens=usage.get("output_tokens", 0),
+ tokens_saved=0,
+ attempted_input_tokens=0,
+ cache_read_tokens=cache_read,
+ cache_write_tokens=cache_write,
+ cache_write_5m_tokens=usage.get("cache_creation_ephemeral_5m_input_tokens", 0),
+ cache_write_1h_tokens=usage.get("cache_creation_ephemeral_1h_input_tokens", 0),
+ uncached_input_tokens=max(0, input_tokens - cache_read - cache_write),
+ status_code=status_code,
+ total_latency_ms=(time.time() - start_time) * 1000,
+ tags=tags,
+ client=classify_client(headers),
+ )
+ )
+ return JSONResponse(content=payload, status_code=status_code, headers=response_headers)
+
async def handle_passthrough(
self,
request: Request,
base_url: str,
endpoint_name: str | None = None,
provider: str | None = None,
+ *,
+ _upstream_request: httpx.Request | None = None,
+ _model: str | None = None,
+ _start_time: float | None = None,
) -> Response:
"""Pass through request unchanged.
@@ -11939,7 +12157,11 @@ class OpenAIHandlerMixin:
"""
from fastapi.responses import Response
- if endpoint_name in {"streamGenerateContent", "streamRawPredict"} and provider:
+ if (
+ _upstream_request is None
+ and endpoint_name in {"streamGenerateContent", "streamRawPredict"}
+ and provider
+ ):
return await self._handle_streaming_passthrough(
request=request,
base_url=base_url,
@@ -11947,7 +12169,7 @@ class OpenAIHandlerMixin:
provider=provider,
)
- start_time = time.time()
+ start_time = _start_time if _start_time is not None else time.time()
path = request.url.path
if provider == "anthropic" and endpoint_name == "models" and path.startswith("/v1/models/"):
from headroom.providers.anthropic import sanitize_anthropic_model_id
@@ -11991,26 +12213,40 @@ class OpenAIHandlerMixin:
from starlette.requests import ClientDisconnect
- try:
- body = await request.body()
- except ClientDisconnect:
- logger.debug("Client disconnected during body read for passthrough")
- return Response(status_code=204)
-
- # Hermes owns its scoped coding-agent protocols; keep that adapter out of
- # the generic OpenAI passthrough handler.
- from headroom.providers.hermes import compress_scoped_passthrough_body
-
- optimize_enabled = bool(getattr(getattr(self, "config", None), "optimize", False))
- original_body = body
- body = compress_scoped_passthrough_body(
- path,
- body,
- optimize=optimize_enabled,
- bypass=_headroom_bypass_enabled(request.headers),
- )
- if body is not original_body:
- headers["content-length"] = str(len(body))
+ from headroom.proxy.request_limit_policy import COMPRESSION_BODY_MAX_BYTES
+
+ if _upstream_request is None:
+ try:
+ body = await request.body()
+ except ClientDisconnect:
+ logger.debug("Client disconnected during body read for passthrough")
+ return Response(status_code=204)
+ else:
+ # Native handlers have already admitted and content-decoded this
+ # request. Keep their exact target and bytes, without reprocessing.
+ body = _upstream_request.content
+ headers = dict(_upstream_request.headers)
+ url = str(_upstream_request.url)
+ origin_passthrough_url = None
+
+ soft_passthrough = _upstream_request is not None or len(body) > COMPRESSION_BODY_MAX_BYTES
+ if soft_passthrough:
+ tags["passthrough_reason"] = "request_body_soft_limit"
+ if not soft_passthrough:
+ # Hermes owns its scoped coding-agent protocols; keep that adapter out of
+ # the generic OpenAI passthrough handler.
+ from headroom.providers.hermes import compress_scoped_passthrough_body
+
+ optimize_enabled = bool(getattr(getattr(self, "config", None), "optimize", False))
+ original_body = body
+ body = compress_scoped_passthrough_body(
+ path,
+ body,
+ optimize=optimize_enabled,
+ bypass=_headroom_bypass_enabled(request.headers),
+ )
+ if body is not original_body:
+ headers["content-length"] = str(len(body))
# Opt-in: compress requests that fall through here because their path
# doesn't match a built-in API route (custom wrapper-proxy paths like
@@ -12019,7 +12255,8 @@ class OpenAIHandlerMixin:
# the exact same ContentRouter/Kompress path the native handler runs.
_pt_config = getattr(self, "config", None)
if (
- getattr(_pt_config, "compress_passthrough", False)
+ not soft_passthrough
+ and getattr(_pt_config, "compress_passthrough", False)
and getattr(_pt_config, "optimize", False)
and request.method == "POST"
and path.rstrip("/").endswith("/responses")
@@ -12040,20 +12277,45 @@ class OpenAIHandlerMixin:
# Those endpoints answer fine over HTTP/1.1, so forward ChatGPT
# passthrough on the HTTP/1.1 client. Other hosts keep HTTP/2.
passthrough_client = self.http_client
- if _prefers_http1_passthrough(base_url):
+ if _prefers_http1_passthrough(url):
passthrough_client = self.http_client_h1 or self.http_client
try:
- # Retry once on a transient keep-alive close (httpx
- # RemoteProtocolError / "incomplete chunked read"): the upstream
- # closed a pooled connection httpx then reused. A fresh connection
- # succeeds, mirroring what a direct curl call does. See GH #1112.
- response = await request_with_transient_retry(
- passthrough_client, # type: ignore[arg-type]
- method=request.method,
- url=url,
- headers=headers,
- content=body,
- )
+ if _upstream_request is None:
+ # Retry once on a transient keep-alive close (httpx
+ # RemoteProtocolError / "incomplete chunked read"): the upstream
+ # closed a pooled connection httpx then reused. A fresh connection
+ # succeeds, mirroring what a direct curl call does. See GH #1112.
+ response = await request_with_transient_retry(
+ passthrough_client, # type: ignore[arg-type]
+ method=request.method,
+ url=url,
+ headers=headers,
+ content=body,
+ )
+ else:
+ assert passthrough_client is not None, "http_client must be initialized"
+ _upstream_request.headers = httpx.Headers(headers)
+ response = await passthrough_client.send(_upstream_request, stream=True)
+ if (
+ endpoint_name
+ and provider
+ and response.headers.get("content-type", "")
+ .lower()
+ .startswith("text/event-stream")
+ ):
+ return await self._handle_streaming_passthrough(
+ request,
+ base_url,
+ endpoint_name,
+ provider,
+ _upstream_response=response,
+ _model=_model,
+ _start_time=start_time,
+ )
+ try:
+ await response.aread()
+ finally:
+ await response.aclose()
except (httpx.ConnectError, httpx.TimeoutException) as e:
logger.warning(
"Passthrough request failed before upstream response: %s %s -> %s: %s",
@@ -12162,16 +12424,20 @@ class OpenAIHandlerMixin:
RequestOutcome(
request_id=request_id,
provider=provider,
- model=_passthrough_model_from_path(path, endpoint_name),
+ model=_model
+ if _model is not None
+ else _passthrough_model_from_path(path, endpoint_name),
status_code=response.status_code,
original_tokens=input_tokens,
optimized_tokens=input_tokens,
provider_input_tokens=input_tokens,
output_tokens=output_tokens,
tokens_saved=0,
- attempted_input_tokens=input_tokens,
+ attempted_input_tokens=0 if soft_passthrough else input_tokens,
cache_read_tokens=cache_read_tokens,
cache_write_tokens=cache_write_tokens,
+ cache_write_5m_tokens=usage.get("cache_creation_ephemeral_5m_input_tokens", 0),
+ cache_write_1h_tokens=usage.get("cache_creation_ephemeral_1h_input_tokens", 0),
uncached_input_tokens=uncached_input_tokens,
total_latency_ms=latency_ms,
tags=tags,
@@ -12191,13 +12457,17 @@ class OpenAIHandlerMixin:
base_url: str,
endpoint_name: str,
provider: str,
+ *,
+ _upstream_response: httpx.Response | None = None,
+ _model: str | None = None,
+ _start_time: float | None = None,
) -> Response:
"""Stream pass-through responses without buffering the upstream body."""
from fastapi.responses import Response, StreamingResponse
from headroom.proxy.helpers import MAX_SSE_BUFFER_SIZE
- start_time = time.time()
+ start_time = _start_time if _start_time is not None else time.time()
path = request.url.path
url = build_copilot_upstream_url(base_url, path)
if request.url.query:
@@ -12208,6 +12478,8 @@ class OpenAIHandlerMixin:
headers.pop("accept-encoding", None)
client = classify_client(headers)
tags = extract_tags(headers)
+ if _upstream_response is not None:
+ tags["passthrough_reason"] = "request_body_soft_limit"
from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers
@@ -12221,14 +12493,20 @@ class OpenAIHandlerMixin:
from starlette.requests import ClientDisconnect
- try:
- body = await request.body()
- except ClientDisconnect:
- logger.debug("Client disconnected during body read for streaming passthrough")
- return Response(status_code=204)
- headers = await apply_copilot_api_auth(headers, url=url)
+ if _upstream_response is None:
+ try:
+ body = await request.body()
+ except ClientDisconnect:
+ logger.debug("Client disconnected during body read for streaming passthrough")
+ return Response(status_code=204)
+ headers = await apply_copilot_api_auth(headers, url=url)
request_id = await self._next_request_id()
- stream_provider = "gemini" if provider == "vertex:google" else "anthropic"
+ if provider in {"gemini", "vertex:google"}:
+ stream_provider = "gemini"
+ elif endpoint_name in {"chat/completions", "responses"}:
+ stream_provider = "openai"
+ else:
+ stream_provider = "anthropic"
stream_state: dict[str, Any] = {
"input_tokens": None,
"output_tokens": None,
@@ -12241,37 +12519,40 @@ class OpenAIHandlerMixin:
"ttfb_ms": None,
}
- assert self.http_client is not None, "http_client must be initialized before streaming"
- try:
- upstream_request = self.http_client.build_request(
- request.method,
- url,
- headers=headers,
- content=body,
- )
- upstream_response = await self.http_client.send(upstream_request, stream=True)
- except (httpx.ConnectError, httpx.TimeoutException) as e:
- logger.warning(
- "Streaming passthrough failed before upstream response: %s %s -> %s: %s",
- request.method,
- path,
- url,
- e,
- )
- from headroom.proxy.tls_diagnostics import describe_upstream_failure_async
+ if _upstream_response is None:
+ assert self.http_client is not None, "http_client must be initialized before streaming"
+ try:
+ upstream_request = self.http_client.build_request(
+ request.method,
+ url,
+ headers=headers,
+ content=body,
+ )
+ upstream_response = await self.http_client.send(upstream_request, stream=True)
+ except (httpx.ConnectError, httpx.TimeoutException) as e:
+ logger.warning(
+ "Streaming passthrough failed before upstream response: %s %s -> %s: %s",
+ request.method,
+ path,
+ url,
+ e,
+ )
+ from headroom.proxy.tls_diagnostics import describe_upstream_failure_async
- tls_hint = await describe_upstream_failure_async(e, url)
- return Response(
- content=json.dumps(
- public_errors.openai_error_body(
- public_errors.classify_or_internal(e),
- error_type="connection_error",
- hint=tls_hint,
- )
- ),
- status_code=502,
- media_type="application/json",
- )
+ tls_hint = await describe_upstream_failure_async(e, url)
+ return Response(
+ content=json.dumps(
+ public_errors.openai_error_body(
+ public_errors.classify_or_internal(e),
+ error_type="connection_error",
+ hint=tls_hint,
+ )
+ ),
+ status_code=502,
+ media_type="application/json",
+ )
+ else:
+ upstream_response = _upstream_response
response_headers = _sanitize_forwarded_response_headers(
upstream_response.headers,
@@ -12362,13 +12643,17 @@ class OpenAIHandlerMixin:
RequestOutcome(
request_id=request_id,
provider=provider,
- model=_passthrough_model_from_path(path, endpoint_name),
+ model=_model
+ if _model is not None
+ else _passthrough_model_from_path(path, endpoint_name),
original_tokens=input_tokens,
optimized_tokens=input_tokens,
provider_input_tokens=input_tokens,
output_tokens=output_tokens,
tokens_saved=0,
- attempted_input_tokens=input_tokens,
+ attempted_input_tokens=0
+ if _upstream_response is not None
+ else input_tokens,
cache_read_tokens=cache_read_tokens,
cache_write_tokens=cache_write_tokens,
cache_write_5m_tokens=stream_state[
diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.py
index 6ffd4cf16..15441ae55 100644
--- a/headroom/proxy/helpers.py
+++ b/headroom/proxy/helpers.py
@@ -1327,8 +1327,11 @@ def append_text_to_latest_user_input_item(
return body_input, 0
-# Maximum request body size (100MB - increased to support image-heavy requests)
-MAX_REQUEST_BODY_SIZE = 100 * 1024 * 1024
+# Bound the entire history before JSON parsing or compression. Larger image-heavy
+# bodies can amplify far beyond their wire size during preprocessing (#4139).
+MAX_REQUEST_BODY_SIZE = request_limit_policy.resolve_request_body_max_bytes(
+ os.environ.get(request_limit_policy.REQUEST_BODY_MAX_BYTES_ENV)
+)
# A *decompressed* body obeys the same ceiling as an uncompressed one. The
# Content-Length gate at the handlers only ever saw the compressed wire size, so
@@ -3507,6 +3510,11 @@ async def read_request_json_with_bytes(request: Request) -> tuple[dict[str, Any]
"Request body must be a JSON object, not " + type(result).__name__
)
+ # Large histories are routed from their envelope only. Leave their content
+ # untouched for the soft-limit passthrough, before any normalization/copies.
+ if len(raw) > request_limit_policy.COMPRESSION_BODY_MAX_BYTES:
+ return result, raw
+
# Drop output-only blocks (see ``strip_output_only_request_blocks``) before
# any downstream deepcopy / compression / 400-retry path. This is the shared
# reader for the Anthropic, OpenAI, and Bedrock handlers, so one guard here
diff --git a/headroom/proxy/request_limit_policy.py b/headroom/proxy/request_limit_policy.py
index 0ceb8821a..4491e879d 100644
--- a/headroom/proxy/request_limit_policy.py
+++ b/headroom/proxy/request_limit_policy.py
@@ -5,6 +5,11 @@ from __future__ import annotations
SSE_EVENT_MAX_BYTES_ENV = "HEADROOM_SSE_BUFFER_MAX_BYTES"
SSE_EVENT_MAX_BYTES_DEFAULT = 1 * 1024 * 1024
+REQUEST_BODY_MAX_BYTES_ENV = "HEADROOM_REQUEST_BODY_MAX_BYTES"
+REQUEST_BODY_MAX_BYTES_DEFAULT = 100 * 1024 * 1024
+# Larger admitted histories bypass compression instead of failing admission.
+COMPRESSION_BODY_MAX_BYTES = 16 * 1024 * 1024
+
BODY_TOO_LARGE_STATUS_ENV = "HEADROOM_PROXY_BODY_TOO_LARGE_STATUS"
BODY_TOO_LARGE_STATUS_DEFAULT = 413
@@ -22,6 +27,19 @@ def resolve_sse_event_max_bytes(raw: str | None) -> int:
return value
+def resolve_request_body_max_bytes(raw: str | None) -> int:
+ """Resolve the whole-request ceiling before the proxy starts."""
+ if raw is None or raw == "":
+ return REQUEST_BODY_MAX_BYTES_DEFAULT
+ try:
+ value = int(raw)
+ except ValueError as exc:
+ raise ValueError(f"{REQUEST_BODY_MAX_BYTES_ENV} must be an integer, got {raw!r}") from exc
+ if value <= 0:
+ raise ValueError(f"{REQUEST_BODY_MAX_BYTES_ENV} must be positive, got {value}")
+ return value
+
+
def resolve_body_too_large_status(raw: str | None) -> int:
"""Resolve the HTTP status code for body-too-large rejections."""
if raw is None or raw == "":
diff --git a/tests/conftest.py b/tests/conftest.py
index 33a8cd19e..1a749360f 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -19,6 +19,37 @@ import pytest
from tests._skip_helpers import external_model_skip_reason
+def gemini_request():
+ """A real ASGI request whose JSON arrives in two stream messages."""
+ from starlette.requests import Request
+
+ body = json.dumps({"contents": [{"role": "user", "parts": [{"text": "hello"}]}]}).encode()
+ middle = len(body) // 2
+ messages = iter(
+ [
+ {"type": "http.request", "body": body[:middle], "more_body": True},
+ {"type": "http.request", "body": body[middle:], "more_body": False},
+ ]
+ )
+
+ async def receive():
+ return next(messages, {"type": "http.disconnect"})
+
+ return Request(
+ {
+ "type": "http",
+ "method": "POST",
+ "path": "/v1beta/models/gemini-pro:generateContent",
+ "query_string": b"",
+ "headers": [(b"content-type", b"application/json")],
+ "scheme": "https",
+ "server": ("gemini.example", 443),
+ },
+ receive,
+ )
+
+
@pytest.fixture(autouse=True)
def _undo_process_trust_injection():
"""Undo ``truststore.inject_into_ssl()`` after any test that triggered it.
diff --git a/tests/test_anthropic_messages_client_disconnect.py b/tests/test_anthropic_messages_client_disconnect.py
index 62bb8ffd1..9cfc3ea4a 100644
--- a/tests/test_anthropic_messages_client_disconnect.py
+++ b/tests/test_anthropic_messages_client_disconnect.py
@@ -25,18 +25,23 @@ import asyncio
from fastapi import Request
from headroom.proxy.handlers.anthropic import AnthropicHandlerMixin
+from headroom.proxy.models import ProxyConfig
class _MinimalAnthropicHandler(AnthropicHandlerMixin):
"""The smallest handler that can reach the ClientDisconnect guard.
- The guard sits before any of the heavier machinery (compression,
- memory, CCR, upstream dispatch) executes, so none of that needs
- stubbing here — only ``_next_request_id``, which the real
- implementation backs with an ``asyncio.Lock`` + counter this
- minimal handler never initializes.
+ Header policy and optional limit checks may precede body reading. Provide
+ their normal configuration while leaving rate/budget limiting disabled;
+ the disconnect still comes from the real ASGI receive channel, before
+ compression, memory, CCR, or upstream dispatch.
"""
+ def __init__(self) -> None:
+ self.config = ProxyConfig()
+ self.rate_limiter = None
+ self.cost_tracker = None
+
async def _next_request_id(self) -> str:
return "req-test"
diff --git a/tests/test_gemini_ccr_continuation_usage.py b/tests/test_gemini_ccr_continuation_usage.py
index f6cd394d4..357f6192a 100644
--- a/tests/test_gemini_ccr_continuation_usage.py
+++ b/tests/test_gemini_ccr_continuation_usage.py
@@ -20,17 +20,6 @@ import pytest
from headroom.proxy.handlers.gemini import GeminiHandlerMixin
-class _FakeRequest:
- def __init__(self) -> None:
- self.headers: dict[str, str] = {}
- self.query_params: dict[str, str] = {}
- self.url = SimpleNamespace(path="/v1beta/models/gemini-pro:generateContent", query="")
- # Every real Starlette Request carries a scope, and the Gemini handler
- # binds the savings-attribution ledger to it (#3051). Without this the
- # double is a shape that cannot occur in production.
- self.scope: dict = {"type": "http", "method": "POST"}
-
-
class _CcrToolCallResponse:
"""Initial 200 carrying a CCR tool call and a valid promptTokenCount."""
@@ -117,16 +106,9 @@ class _Handler(GeminiHandlerMixin):
@pytest.mark.asyncio
-async def test_ccr_continuation_present_null_usage_does_not_502(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- async def payload(request): # noqa: ANN001, ANN201
- return {"contents": [{"role": "user", "parts": [{"text": "hello"}]}]}
-
- monkeypatch.setattr("headroom.proxy.helpers._read_request_json", payload)
-
+async def test_ccr_continuation_present_null_usage_does_not_502(gemini_request) -> None:
handler = _Handler()
- response = await handler.handle_gemini_generate_content(_FakeRequest(), "gemini-pro")
+ response = await handler.handle_gemini_generate_content(gemini_request, "gemini-pro")
# Before the fix this raised TypeError on the None arithmetic and the outer
# handler returned a synthetic 502 with a recorded failure.
@@ -157,14 +139,7 @@ class _NoCcrHandler(_CcrHandler):
@pytest.mark.asyncio
-async def test_missing_prompt_token_count_is_not_reported_as_provider_input(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- async def payload(request): # noqa: ANN001, ANN201
- return {"contents": [{"role": "user", "parts": [{"text": "hello"}]}]}
-
- monkeypatch.setattr("headroom.proxy.helpers._read_request_json", payload)
-
+async def test_missing_prompt_token_count_is_not_reported_as_provider_input(gemini_request) -> None:
handler = _Handler()
handler.ccr_response_handler = _NoCcrHandler()
@@ -172,7 +147,7 @@ async def test_missing_prompt_token_count_is_not_reported_as_provider_input(
return _NoUsageResponse()
handler._retry_request = no_usage
- response = await handler.handle_gemini_generate_content(_FakeRequest(), "gemini-pro")
+ response = await handler.handle_gemini_generate_content(gemini_request, "gemini-pro")
assert response.status_code == 200
(outcome,) = handler.outcomes
@@ -183,17 +158,10 @@ async def test_missing_prompt_token_count_is_not_reported_as_provider_input(
@pytest.mark.asyncio
-async def test_reported_prompt_token_count_is_provider_input(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- async def payload(request): # noqa: ANN001, ANN201
- return {"contents": [{"role": "user", "parts": [{"text": "hello"}]}]}
-
- monkeypatch.setattr("headroom.proxy.helpers._read_request_json", payload)
-
+async def test_reported_prompt_token_count_is_provider_input(gemini_request) -> None:
handler = _Handler()
handler.ccr_response_handler = _NoCcrHandler()
- response = await handler.handle_gemini_generate_content(_FakeRequest(), "gemini-pro")
+ response = await handler.handle_gemini_generate_content(gemini_request, "gemini-pro")
assert response.status_code == 200
assert handler.outcomes[0].provider_input_tokens == 100
diff --git a/tests/test_gemini_nonjson_status.py b/tests/test_gemini_nonjson_status.py
index b0d2d5d6d..f40d27e57 100644
--- a/tests/test_gemini_nonjson_status.py
+++ b/tests/test_gemini_nonjson_status.py
@@ -10,14 +10,6 @@ import pytest
from headroom.proxy.handlers.gemini import GeminiHandlerMixin
-class _FakeRequest:
- def __init__(self) -> None:
- self.headers: dict[str, str] = {}
- self.query_params: dict[str, str] = {}
- self.url = SimpleNamespace(path="/v1beta/models/gemini-pro:generateContent", query="")
- self.scope: dict = {"type": "http", "method": "POST"}
-
-
class _NonJsonResponse:
status_code = 503
content = b"<html>temporarily unavailable</html>"
@@ -73,20 +65,17 @@ class _Handler(GeminiHandlerMixin):
@pytest.mark.asyncio
async def test_generate_content_forwards_non_json_upstream_status(
- monkeypatch: pytest.MonkeyPatch,
+ monkeypatch: pytest.MonkeyPatch, gemini_request
) -> None:
- async def payload(request): # noqa: ANN001, ANN201
- return {"contents": [{"role": "user", "parts": [{"text": "hello"}]}]}
class _Tokenizer:
def count_messages(self, messages): # noqa: ANN001, ANN201
return 7
- monkeypatch.setattr("headroom.proxy.helpers._read_request_json", payload)
monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _Tokenizer())
handler = _Handler()
- response = await handler.handle_gemini_generate_content(_FakeRequest(), "gemini-pro")
+ response = await handler.handle_gemini_generate_content(gemini_request, "gemini-pro")
assert response.status_code == 503
assert response.body == _NonJsonResponse.content
diff --git a/tests/test_org_scale_limits.py b/tests/test_org_scale_limits.py
index d9ceb4879..f0a89ac56 100644
--- a/tests/test_org_scale_limits.py
+++ b/tests/test_org_scale_limits.py
@@ -15,6 +15,12 @@ Registry TTL/LRU mechanics live in ``test_compression_cache_registry.py``.
from __future__ import annotations
+import json
+import os
+import subprocess
+import sys
+import textwrap
+
import pytest
pytest.importorskip("fastapi")
@@ -38,63 +44,47 @@ def _make_proxy():
return app.state.proxy
-# --------------------------------------------------------------------------- #
-# Per-session entry cap is plumbed through and env-tunable. #
-# --------------------------------------------------------------------------- #
-
-
-def test_compression_cache_entry_cap_is_plumbed(monkeypatch) -> None:
- import headroom.proxy.server as server_mod
-
- monkeypatch.setattr(server_mod, "COMPRESSION_CACHE_MAX_ENTRIES", 123)
- proxy = _make_proxy()
- assert proxy._get_compression_cache("s").max_entries == 123
-
-
-def test_compression_cache_entry_cap_env_parsing(monkeypatch) -> None:
- import importlib
-
- import headroom.proxy.helpers as helpers_mod
-
- monkeypatch.setenv("HEADROOM_COMPRESSION_CACHE_MAX_ENTRIES", "50000")
- importlib.reload(helpers_mod)
- assert helpers_mod.COMPRESSION_CACHE_MAX_ENTRIES == 50000
-
- # Floor: an absurdly small value cannot disable the cache.
- monkeypatch.setenv("HEADROOM_COMPRESSION_CACHE_MAX_ENTRIES", "1")
- importlib.reload(helpers_mod)
- assert helpers_mod.COMPRESSION_CACHE_MAX_ENTRIES == 100
-
- # Garbage falls back to the default.
- monkeypatch.setenv("HEADROOM_COMPRESSION_CACHE_MAX_ENTRIES", "banana")
- importlib.reload(helpers_mod)
- assert helpers_mod.COMPRESSION_CACHE_MAX_ENTRIES == 10000
-
- monkeypatch.delenv("HEADROOM_COMPRESSION_CACHE_MAX_ENTRIES")
- importlib.reload(helpers_mod)
- assert helpers_mod.COMPRESSION_CACHE_MAX_ENTRIES == 10000
-
-
-def test_compression_cache_ttl_env_rejects_non_finite(monkeypatch) -> None:
- """'nan'/'inf' parse as floats but poison every idle comparison — they
- must fall back to the default like any other unparseable value."""
- import importlib
-
- import headroom.proxy.helpers as helpers_mod
-
- for bad in ("nan", "inf", "-inf"):
- monkeypatch.setenv("HEADROOM_COMPRESSION_CACHE_TTL_SECONDS", bad)
- importlib.reload(helpers_mod)
- assert helpers_mod.COMPRESSION_CACHE_TTL_SECONDS == 3900.0, bad
-
- # Below the 600s floor clamps up; above it passes through.
- monkeypatch.setenv("HEADROOM_COMPRESSION_CACHE_TTL_SECONDS", "60")
- importlib.reload(helpers_mod)
- assert helpers_mod.COMPRESSION_CACHE_TTL_SECONDS == 600.0
-
- monkeypatch.delenv("HEADROOM_COMPRESSION_CACHE_TTL_SECONDS")
- importlib.reload(helpers_mod)
- assert helpers_mod.COMPRESSION_CACHE_TTL_SECONDS == 3900.0
[email protected]("raw", ["nan", "inf", "-inf"])
+def test_nonfinite_cache_ttl_still_reclaims_idle_sessions(raw, tmp_path) -> None:
+ program = textwrap.dedent(
+ """
+ import json
+ import time
+ from headroom.proxy.server import ProxyConfig, create_app
+
+ proxy = create_app(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,
+ )).state.proxy
+ proxy._get_compression_cache("stale")
+ proxy._get_compression_cache("fresh")
+ now = time.time()
+ proxy._compression_cache_last_seen["stale"] = now - 1_000_000
+ proxy._compression_caches_last_cleanup = (
+ now - proxy._COMPRESSION_CACHE_CLEANUP_INTERVAL_SECONDS - 1
+ )
+ proxy._get_compression_cache("trigger")
+ print(json.dumps({
+ "stale": "stale" in proxy._compression_caches,
+ "fresh": "fresh" in proxy._compression_caches,
+ }))
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", program],
+ env={
+ **os.environ,
+ "HEADROOM_COMPRESSION_CACHE_TTL_SECONDS": raw,
+ "HEADROOM_WORKSPACE_DIR": str(tmp_path),
+ },
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=120,
+ )
+ assert json.loads(result.stdout) == {"stale": False, "fresh": True}
# --------------------------------------------------------------------------- #
@@ -102,24 +92,6 @@ def test_compression_cache_ttl_env_rejects_non_finite(monkeypatch) -> None:
# --------------------------------------------------------------------------- #
-def test_frozen_verdicts_cap_env(monkeypatch) -> None:
- from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
-
- monkeypatch.setenv("HEADROOM_FROZEN_VERDICTS_MAX", "65536")
- assert ContentRouter(ContentRouterConfig())._frozen_verdicts_max == 65536
-
- # Floor: cannot be sized below 256.
- monkeypatch.setenv("HEADROOM_FROZEN_VERDICTS_MAX", "1")
- assert ContentRouter(ContentRouterConfig())._frozen_verdicts_max == 256
-
- # Garbage falls back to the default.
- monkeypatch.setenv("HEADROOM_FROZEN_VERDICTS_MAX", "banana")
- assert ContentRouter(ContentRouterConfig())._frozen_verdicts_max == 4096
-
- monkeypatch.delenv("HEADROOM_FROZEN_VERDICTS_MAX")
- assert ContentRouter(ContentRouterConfig())._frozen_verdicts_max == 4096
-
-
def test_frozen_verdicts_eviction_honors_configured_cap(monkeypatch) -> None:
from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
diff --git a/tests/test_proxy/test_compression_timeout_config.py b/tests/test_proxy/test_compression_timeout_config.py
index 2ae58ddb2..e9b001766 100644
--- a/tests/test_proxy/test_compression_timeout_config.py
+++ b/tests/test_proxy/test_compression_timeout_config.py
@@ -1,76 +1,60 @@
from __future__ import annotations
-import importlib
-import logging
+import json
import os
+import subprocess
+import sys
+import textwrap
import pytest
-import headroom.proxy.helpers as helpers
-
[email protected](autouse=True)
-def _restore_default_timeout():
- """Each test reloads helpers under a chosen env; reset to the default afterwards
- so the reloaded module constant doesn't leak into the rest of the suite."""
- yield
- os.environ.pop("HEADROOM_COMPRESSION_TIMEOUT_SECONDS", None)
- importlib.reload(helpers)
-
-
-def test_default_timeout_is_30(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.delenv("HEADROOM_COMPRESSION_TIMEOUT_SECONDS", raising=False)
- importlib.reload(helpers)
- assert helpers.COMPRESSION_TIMEOUT_SECONDS == 30.0
-
-
-def test_env_overrides_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setenv("HEADROOM_COMPRESSION_TIMEOUT_SECONDS", "75")
- importlib.reload(helpers)
- assert helpers.COMPRESSION_TIMEOUT_SECONDS == 75.0
-
-
-def test_fractional_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setenv("HEADROOM_COMPRESSION_TIMEOUT_SECONDS", "12.5")
- importlib.reload(helpers)
- assert helpers.COMPRESSION_TIMEOUT_SECONDS == 12.5
-
-
-def test_bad_env_falls_back_to_default(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setenv("HEADROOM_COMPRESSION_TIMEOUT_SECONDS", "not-a-number")
- importlib.reload(helpers)
- assert helpers.COMPRESSION_TIMEOUT_SECONDS == 30.0
-
-
-class _Capture(logging.Handler):
- def __init__(self) -> None:
- super().__init__(logging.DEBUG)
- self.messages: list[str] = []
-
- def emit(self, record: logging.LogRecord) -> None:
- if record.levelno == logging.WARNING:
- self.messages.append(record.getMessage())
-
-
-def _reload_warnings() -> list[str]:
- capture = _Capture()
- proxy_logger = logging.getLogger("headroom.proxy")
- proxy_logger.addHandler(capture)
- try:
- importlib.reload(helpers)
- finally:
- proxy_logger.removeHandler(capture)
- return [m for m in capture.messages if "HEADROOM_COMPRESSION_TIMEOUT_SECONDS" in m]
-
-
-def test_bad_env_says_it_was_ignored(monkeypatch: pytest.MonkeyPatch) -> None:
- """A typo in the knob used to revert to 30s without a word."""
- monkeypatch.setenv("HEADROOM_COMPRESSION_TIMEOUT_SECONDS", "not-a-number")
- assert _reload_warnings() == [
- "Ignoring invalid HEADROOM_COMPRESSION_TIMEOUT_SECONDS='not-a-number'; using 30.0"
- ]
-
-
-def test_valid_env_is_silent(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setenv("HEADROOM_COMPRESSION_TIMEOUT_SECONDS", "75")
- assert _reload_warnings() == []
+ ("deadline", "expected"),
+ [("0.001", {"timed_out": True}), ("1.0", {"value": 42})],
+)
+def test_startup_deadline_bounds_actual_compression_work(deadline, expected, tmp_path) -> None:
+ program = textwrap.dedent(
+ """
+ import asyncio
+ import json
+ import time
+ from headroom.proxy import helpers
+ from headroom.proxy.server import HeadroomProxy, ProxyConfig
+
+ proxy = HeadroomProxy(ProxyConfig(
+ optimize=False, cache_enabled=False, rate_limit_enabled=False,
+ cost_tracking_enabled=False, log_requests=False, image_optimize=False,
+ ))
+
+ def work():
+ time.sleep(0.05)
+ return 42
+
+ async def main():
+ try:
+ value = await proxy._run_compression_in_executor(
+ work, timeout=helpers.COMPRESSION_TIMEOUT_SECONDS
+ )
+ print(json.dumps({"value": value}))
+ except asyncio.TimeoutError:
+ print(json.dumps({"timed_out": True}))
+ finally:
+ proxy._compression_executor.shutdown(wait=True)
+
+ asyncio.run(main())
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", program],
+ env={
+ **os.environ,
+ "HEADROOM_COMPRESSION_TIMEOUT_SECONDS": deadline,
+ "HEADROOM_WORKSPACE_DIR": str(tmp_path),
+ },
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=120,
+ )
+ assert json.loads(result.stdout) == expected
diff --git a/tests/test_proxy_compress_endpoint.py b/tests/test_proxy_compress_endpoint.py
index 1a99fb75c..2ecc0a7b9 100644
--- a/tests/test_proxy_compress_endpoint.py
+++ b/tests/test_proxy_compress_endpoint.py
@@ -4,6 +4,7 @@ These tests verify that the compression-only endpoint works correctly
for the TypeScript SDK and other HTTP clients.
"""
+import gzip
import json
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
@@ -19,8 +20,13 @@ from headroom.proxy.server import ProxyConfig, create_app
@pytest.fixture
-def client():
+def client(request, monkeypatch):
"""Create test client with optimization enabled."""
+ if hasattr(request, "param"):
+ from headroom.proxy import helpers
+
+ monkeypatch.setattr(helpers, "MAX_REQUEST_BODY_SIZE", request.param)
+ monkeypatch.setattr(helpers, "MAX_DECOMPRESSED_BODY_SIZE", request.param)
config = ProxyConfig(
optimize=True,
cache_enabled=False,
@@ -83,6 +89,42 @@ class TestCompressEndpointValidation:
data = response.json()
assert data["error"]["type"] == "invalid_request"
+ @pytest.mark.parametrize("bypass", [False, True])
+ @pytest.mark.parametrize("client", [64 * 1024], indirect=True)
+ def test_expanded_image_history_is_refused_before_compression(
+ self, client, bypass, monkeypatch
+ ):
+ body = {
+ "model": "gpt-4o",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64," + "YQ==" * (32 * 1024)},
+ }
+ ],
+ }
+ ],
+ }
+
+ async def no_compression(*args, **kwargs):
+ pytest.fail("oversized history reached compression")
+
+ monkeypatch.setattr(client.app.state.proxy, "_run_compression_in_executor", no_compression)
+ headers = {"content-type": "application/json", "content-encoding": "gzip"}
+ if bypass:
+ headers["x-headroom-bypass"] = "true"
+ response = client.post(
+ "/v1/compress",
+ content=gzip.compress(json.dumps(body).encode()),
+ headers=headers,
+ )
+
+ assert response.status_code == 413
+ assert response.json()["error"]["code"] == "request_too_large"
+
class TestCompressEndpointBasic:
"""Test basic compress endpoint behavior."""
diff --git a/tests/test_proxy_compression_admission.py b/tests/test_proxy_compression_admission.py
new file mode 100644
index 000000000..8b3b58f2f
--- /dev/null
+++ b/tests/test_proxy_compression_admission.py
@@ -0,0 +1,418 @@
+"""Whole-history admission and compression passthrough behavior."""
+
+from __future__ import annotations
+
+import gzip
+import json
+import os
+import subprocess
+import sys
+import textwrap
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+
+
[email protected]("raw", ["0", "-1", "not-int", "1.5"])
+def test_invalid_request_body_ceiling_is_rejected(raw: str) -> None:
+ from headroom.proxy.request_limit_policy import resolve_request_body_max_bytes
+
+ with pytest.raises(ValueError):
+ resolve_request_body_max_bytes(raw)
+
+
+def test_startup_override_changes_http_admission_after_restart() -> None:
+ program = textwrap.dedent(
+ """
+ import json
+ from starlette.applications import Starlette
+ from starlette.responses import JSONResponse
+ from starlette.routing import Route
+ from starlette.testclient import TestClient
+ from headroom.proxy.request_body_limit import RequestBodyLimitMiddleware
+
+ async def preprocess(request):
+ await request.json()
+ return JSONResponse({"preprocessed": True})
+
+ app = Starlette(routes=[Route("/v1/compress", preprocess, methods=["POST"])])
+ app.add_middleware(RequestBodyLimitMiddleware)
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/compress",
+ json={"model": "gpt-4o", "messages": [{"role": "user", "content": "a" * 1500}]},
+ )
+ print(json.dumps({"status": response.status_code, "body": response.json()}))
+ """
+ )
+ results = []
+ for ceiling in (1024, 2048):
+ process = subprocess.run(
+ [sys.executable, "-c", program],
+ env={
+ **os.environ,
+ "HEADROOM_REQUEST_BODY_MAX_BYTES": str(ceiling),
+ "DO_NOT_TRACK": "1",
+ "HEADROOM_TELEMETRY": "off",
+ },
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=120,
+ )
+ results.append(json.loads(process.stdout))
+
+ assert results[0]["status"] == 413
+ assert results[0]["body"]["error"]["code"] == "request_too_large"
+ assert results[1] == {"status": 200, "body": {"preprocessed": True}}
+
+
+def admitted_proxy(monkeypatch, request):
+ from fastapi.testclient import TestClient
+
+ from headroom.proxy import request_limit_policy
+ from headroom.proxy.server import ProxyConfig, create_app
+
+ monkeypatch.setattr(request_limit_policy, "COMPRESSION_BODY_MAX_BYTES", 1024)
+ backend = getattr(request, "param", "anthropic")
+ sdk = pytest.importorskip("litellm") if backend != "anthropic" else None
+
+ class Provider(BaseHTTPRequestHandler):
+ def log_message(self, *_args):
+ pass
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers["content-length"])))
+ url = urlsplit(self.path)
+ path = url.path
+ if path.endswith("/responses"):
+ if "input" not in body or body.get("store") is not False:
+ self.send_error(400, "Unsupported Responses wire request")
+ return
+ response = json.dumps(
+ {
+ "id": "resp_admission",
+ "object": "response",
+ "output": [],
+ "usage": {"input_tokens": 101, "output_tokens": 1},
+ }
+ ).encode()
+ content_type = "application/json"
+ elif path.endswith("/chat/completions"):
+ payload = {
+ "id": "chat_admission",
+ "object": "chat.completion",
+ "created": 0,
+ "model": "gpt-4o",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "ok"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 101, "completion_tokens": 1, "total_tokens": 102},
+ }
+ if body.get("stream", False):
+ payload["object"] = "chat.completion.chunk"
+ payload["choices"] = [
+ {
+ "index": 0,
+ "delta": {"role": "assistant", "content": "ok"},
+ "finish_reason": "stop",
+ }
+ ]
+ usage = payload.pop("usage")
+ usage_chunk = {**payload, "choices": [], "usage": usage}
+ response = (
+ "".join(
+ "data: " + json.dumps(chunk) + "\n\n"
+ for chunk in (payload, usage_chunk)
+ )
+ + "data: [DONE]\n\n"
+ ).encode()
+ content_type = "text/event-stream"
+ else:
+ response = json.dumps(payload).encode()
+ content_type = "application/json"
+ elif path.endswith((":generateContent", ":streamGenerateContent")):
+ query = parse_qs(url.query)
+ if query.get("key") != ["synthetic-only"]:
+ self.send_error(401, "Gemini API key required")
+ return
+ streaming = path.endswith(":streamGenerateContent")
+ if streaming and query.get("alt") != ["sse"]:
+ self.send_error(400, "Streaming endpoint requires one alt=sse")
+ return
+ payload = {
+ "candidates": [
+ {
+ "content": {"role": "model", "parts": [{"text": "ok"}]},
+ "finishReason": "STOP",
+ }
+ ],
+ "usageMetadata": {
+ "promptTokenCount": 101,
+ "candidatesTokenCount": 1,
+ "totalTokenCount": 102,
+ },
+ }
+ if streaming:
+ response = ("data: " + json.dumps(payload) + "\n\n").encode()
+ content_type = "text/event-stream"
+ else:
+ response = json.dumps(payload).encode()
+ content_type = "application/json"
+ else:
+ response = json.dumps(
+ {
+ "id": "msg_admission",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-6",
+ "content": [{"type": "text", "text": "ok"}],
+ "stop_reason": "end_turn",
+ "usage": {"input_tokens": 101, "output_tokens": 1},
+ }
+ ).encode()
+ content_type = "application/json"
+ self.send_response(200)
+ self.send_header("content-type", content_type)
+ self.send_header("content-length", str(len(response)))
+ self.end_headers()
+ self.wfile.write(response)
+
+ provider = ThreadingHTTPServer(("127.0.0.1", 0), Provider)
+ thread = threading.Thread(target=provider.serve_forever, daemon=True)
+ thread.start()
+ if sdk is not None:
+ monkeypatch.setattr(sdk, "api_base", f"http://127.0.0.1:{provider.server_port}/v1")
+ monkeypatch.setattr(sdk, "api_key", "synthetic-only")
+ monkeypatch.setenv("OPENAI_API_KEY", "synthetic-only")
+ config = ProxyConfig(
+ anthropic_api_url=f"http://127.0.0.1:{provider.server_port}",
+ openai_api_url=f"http://127.0.0.1:{provider.server_port}",
+ gemini_api_url=f"http://127.0.0.1:{provider.server_port}",
+ bedrock_api_url=f"http://127.0.0.1:{provider.server_port}",
+ vertex_api_url=f"http://127.0.0.1:{provider.server_port}",
+ backend=backend,
+ cache_enabled=False,
+ rate_limit_enabled=False,
+ cost_tracking_enabled=False,
+ log_requests=False,
+ stateless=True,
+ disable_kompress=True,
+ )
+ try:
+ with TestClient(
+ create_app(config),
+ base_url="http://127.0.0.1",
+ client=("127.0.0.1", 50000),
+ ) as client:
+ yield client
+ finally:
+ provider.shutdown()
+ provider.server_close()
+ thread.join()
+
+
+def test_gzip_history_above_soft_threshold_stays_live_without_claiming_savings(admitted_proxy):
+ raw = json.dumps(
+ {
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 32,
+ "messages": [{"role": "user", "content": "history " * 3000}],
+ }
+ ).encode()
+ encoded = gzip.compress(raw)
+ assert len(encoded) < 1024 < len(raw)
+ response = admitted_proxy.post(
+ "/v1/messages",
+ content=encoded,
+ headers={"content-type": "application/json", "content-encoding": "gzip"},
+ )
+ assert response.status_code == 200
+ assert response.json()["content"] == [{"type": "text", "text": "ok"}]
+ stats = admitted_proxy.get("/stats").json()
+ assert stats["tokens"]["input_provider_reported"] == 101
+ assert stats["tokens"]["output"] == 1
+ assert stats["tokens"]["proxy_attempted_tokens"] == 0
+ assert stats["tokens"]["saved"] == 0
+ assert admitted_proxy.get("/livez").status_code == 200
+ following = admitted_proxy.post(
+ "/v1/messages",
+ json={
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 32,
+ "messages": [{"role": "user", "content": "next turn"}],
+ },
+ )
+ assert following.status_code == 200
+ assert admitted_proxy.get("/stats").json()["requests"]["failed"] == 0
+
+
+ "path",
+ [
+ "/v1/messages",
+ "/v1/chat/completions",
+ "/v1/responses",
+ "/v1beta/models/gemini-2.5-flash:generateContent",
+ "/model/anthropic.claude-v2/invoke",
+ ],
+)
+def test_soft_passthrough_still_obeys_decompressed_hard_ceiling(admitted_proxy, monkeypatch, path):
+ from headroom.proxy import helpers
+
+ monkeypatch.setattr(helpers, "MAX_DECOMPRESSED_BODY_SIZE", 8192)
+ monkeypatch.setattr(helpers, "MAX_REQUEST_BODY_SIZE", 8192)
+ content = "history " * 3000
+ body = {
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 32,
+ "messages": [{"role": "user", "content": content}],
+ }
+ if path == "/v1/responses":
+ body = {"model": "gpt-4o", "input": content}
+ elif "/models/" in path:
+ body = {"contents": [{"role": "user", "parts": [{"text": content}]}]}
+ elif "/model/" in path:
+ body["anthropic_version"] = "bedrock-2023-05-31"
+ raw = json.dumps(body).encode()
+ response = admitted_proxy.post(
+ path,
+ content=gzip.compress(raw),
+ headers={"content-type": "application/json", "content-encoding": "gzip"},
+ )
+ assert response.status_code == 413
+ assert admitted_proxy.get("/livez").status_code == 200
+
+
+def test_large_copilot_chat_remains_a_chat_completions_request(admitted_proxy, monkeypatch):
+ base = admitted_proxy.app.state.proxy.config.openai_api_url
+ monkeypatch.setenv("GITHUB_COPILOT_API_URL", base)
+ response = admitted_proxy.post(
+ "/v1/chat/completions",
+ json={
+ "model": "gpt-5",
+ "messages": [{"role": "user", "content": "history " * 3000}],
+ },
+ headers={"authorization": "Bearer tid_synthetic_client"},
+ )
+ assert response.status_code == 200
+ assert response.json()["choices"][0]["message"]["content"] == "ok"
+
+
+def test_large_codex_request_receives_the_required_store_setting(admitted_proxy, monkeypatch):
+ from headroom.providers.codex import endpoints
+
+ monkeypatch.setattr(
+ endpoints,
+ "CHATGPT_BACKEND_API_URL",
+ admitted_proxy.app.state.proxy.config.openai_api_url,
+ )
+ response = admitted_proxy.post(
+ "/v1/responses",
+ json={"model": "gpt-5-codex", "input": "history " * 3000},
+ headers={
+ "authorization": "Bearer synthetic_subscription",
+ "chatgpt-account-id": "synthetic_account",
+ },
+ )
+ assert response.status_code == 200
+ assert response.json()["object"] == "response"
+
+
[email protected]("admitted_proxy", ["litellm-openai"], indirect=True)
+def test_large_vertex_backend_retains_route_forced_streaming(admitted_proxy):
+ response = admitted_proxy.post(
+ "/v1/projects/synthetic/locations/us-central1/publishers/anthropic/models/gpt-4o:streamRawPredict",
+ json={
+ "max_tokens": 32,
+ "messages": [{"role": "user", "content": "history " * 3000}],
+ },
+ )
+ assert response.status_code == 200
+ assert response.headers["content-type"].startswith("text/event-stream")
+ events = [
+ json.loads(line.removeprefix("data: "))
+ for line in response.text.splitlines()
+ if line.startswith("data: ") and line != "data: [DONE]"
+ ]
+ assert events[-1]["type"] == "message_stop"
+
+
[email protected]("streaming", [False, True])
+def test_large_gemini_history_preserves_auth_and_streaming_contract(admitted_proxy, streaming):
+ endpoint = "streamGenerateContent" if streaming else "generateContent"
+ response = admitted_proxy.post(
+ f"/v1beta/models/gemini-2.5-flash:{endpoint}?key=synthetic-only&alt=json",
+ json={"contents": [{"role": "user", "parts": [{"text": "history " * 3000}]}]},
+ )
+ assert response.status_code == 200
+ if streaming:
+ assert response.headers["content-type"].startswith("text/event-stream")
+ events = [
+ json.loads(line.removeprefix("data: "))
+ for line in response.text.splitlines()
+ if line.startswith("data: ")
+ ]
+ assert (
+ "".join(
+ part["text"]
+ for event in events
+ for candidate in event.get("candidates", [])
+ for part in candidate["content"]["parts"]
+ )
+ == "ok"
+ )
+ assert events[-1]["candidates"][0]["finishReason"] == "STOP"
+ else:
+ assert response.json()["candidates"][0]["content"]["parts"][0]["text"] == "ok"
+ stats = admitted_proxy.get("/stats").json()
+ assert stats["tokens"]["input_provider_reported"] == 101
+ assert stats["tokens"]["output"] == 1
+ assert stats["tokens"]["proxy_attempted_tokens"] == 0
+ assert stats["tokens"]["saved"] == 0
+ assert stats["requests"]["failed"] == 0
+
+
[email protected]("admitted_proxy", ["litellm-openai"], indirect=True)
[email protected]("streaming", [False, True])
+def test_large_openai_backend_reports_usage_without_compression(admitted_proxy, streaming):
+ body = {
+ "model": "gpt-4o",
+ "messages": [{"role": "user", "content": "history " * 3000}],
+ "stream": streaming,
+ }
+ if streaming:
+ body["stream_options"] = {"include_usage": True}
+ response = admitted_proxy.post("/v1/chat/completions", json=body)
+ assert response.status_code == 200
+ if streaming:
+ assert response.headers["content-type"].startswith("text/event-stream")
+ events = [
+ json.loads(line.removeprefix("data: "))
+ for line in response.text.splitlines()
+ if line.startswith("data: ") and line != "data: [DONE]"
+ ]
+ assert (
+ "".join(
+ choice["delta"].get("content", "")
+ for event in events
+ for choice in event.get("choices", [])
+ )
+ == "ok"
+ )
+ assert response.text.endswith("data: [DONE]\n\n")
+ else:
+ assert response.json()["choices"][0]["message"]["content"] == "ok"
+ stats = admitted_proxy.get("/stats").json()
+ assert stats["tokens"]["input_provider_reported"] == 101
+ assert stats["tokens"]["output"] == 1
+ assert stats["tokens"]["proxy_attempted_tokens"] == 0
+ assert stats["tokens"]["saved"] == 0
+ assert stats["requests"]["failed"] == 0
diff --git a/tests/test_proxy_copilot_auth_hooks.py b/tests/test_proxy_copilot_auth_hooks.py
index abb1a0359..a1f4ec065 100644
--- a/tests/test_proxy_copilot_auth_hooks.py
+++ b/tests/test_proxy_copilot_auth_hooks.py
@@ -6,11 +6,11 @@ from starlette.requests import Request
from starlette.responses import StreamingResponse
from headroom import paths
+from headroom.proxy.handlers import openai as openai_mod
from headroom.proxy.server import HeadroomProxy, ProxyConfig
def test_openai_chat_routes_copilot_requests_per_model() -> None:
- from headroom.proxy.handlers import openai as openai_mod
copilot_base = "https://api.githubcopilot.com"
gpt54_mini_url = openai_mod.build_copilot_upstream_url(
diff --git a/tests/test_proxy_package_init.py b/tests/test_proxy_package_init.py
deleted file mode 100644
index 575828af6..000000000
--- a/tests/test_proxy_package_init.py
+++ /dev/null
@@ -1,54 +0,0 @@
-"""Unit tests for headroom.proxy lazy __getattr__ (PEP 562)."""
-
-from __future__ import annotations
-
-import importlib
-import sys
-import types
-
-import pytest
-
-
-def test_proxy_getattr_resolves_create_app_and_caches_it(monkeypatch) -> None:
- sentinel = object()
- fake_server = types.SimpleNamespace(create_app=sentinel, run_server=object())
- monkeypatch.setitem(sys.modules, "headroom.proxy.server", fake_server)
-
- import headroom.proxy as proxy
-
- module = importlib.reload(proxy)
- module.__dict__.pop("create_app", None)
- module.__dict__.pop("run_server", None)
- # Register teardown: monkeypatch notes these keys are absent now and will
- # remove them after the test, preventing sentinel leakage to later tests.
- monkeypatch.delitem(module.__dict__, "create_app", raising=False)
- monkeypatch.delitem(module.__dict__, "run_server", raising=False)
-
- result = module.__getattr__("create_app")
- assert result is sentinel
- assert module.__dict__["create_app"] is sentinel
-
-
-def test_proxy_getattr_resolves_run_server(monkeypatch) -> None:
- sentinel = object()
- fake_server = types.SimpleNamespace(create_app=object(), run_server=sentinel)
- monkeypatch.setitem(sys.modules, "headroom.proxy.server", fake_server)
-
- import headroom.proxy as proxy
-
- module = importlib.reload(proxy)
- module.__dict__.pop("create_app", None)
- module.__dict__.pop("run_server", None)
- monkeypatch.delitem(module.__dict__, "create_app", raising=False)
- monkeypatch.delitem(module.__dict__, "run_server", raising=False)
-
- result = module.__getattr__("run_server")
- assert result is sentinel
- assert module.__dict__["run_server"] is sentinel
-
-
-def test_proxy_getattr_raises_for_unknown_attribute() -> None:
- import headroom.proxy as proxy
-
- with pytest.raises(AttributeError, match="has no attribute 'nonexistent'"):
- proxy.__getattr__("nonexistent")
diff --git a/tests/test_request_body_decompression_limits.py b/tests/test_request_body_decompression_limits.py
index 5d9395c7a..648371c6b 100644
--- a/tests/test_request_body_decompression_limits.py
+++ b/tests/test_request_body_decompression_limits.py
@@ -126,16 +126,6 @@ def small_raw_cap(monkeypatch: pytest.MonkeyPatch) -> int:
# ───────────────────────────── the ceiling itself ──────────────────────────
-def test_decompressed_ceiling_matches_the_plain_body_ceiling() -> None:
- """A client must not get more room by arriving compressed."""
- assert _helpers().MAX_DECOMPRESSED_BODY_SIZE == _helpers().MAX_REQUEST_BODY_SIZE
-
-
-def test_too_large_is_a_value_error() -> None:
- """Every existing call site catches ValueError; the subclass must not escape it."""
- assert issubclass(_helpers().RequestBodyTooLarge, ValueError)
-
-
# ───────────────────────────── refusal, per codec ──────────────────────────