headroom/tests/test_proxy/test_openai_backend_path.py
chopratejas 20dc1f28f3 fix(proxy): Strands MCP bundle + backend path fixes + Codex fail-closed protection
Three logically-related sets of proxy changes ship in this branch:

1. Strands integration on the Bedrock path (HeadroomBundle + 4 OpenAI
   handler fixes + LiteLLM cache stats + dep pin)
2. /stats MCP aggregation (cross-process events log → proxy summary)
3. Codex compression-failure fail-closed (WS + HTTP /v1/responses)

== 1. Strands integration on the Bedrock path ==

* HeadroomBundle (headroom/integrations/strands/bundle.py): single-helper
  MCP wiring for a Strands Agent — Headroom MCP server (headroom_compress
  / headroom_retrieve / headroom_stats) plus optional Serena MCP and
  optional in-process compression hook. Constructor builds unstarted
  MCPClient instances per server; Strands' Agent owns the subprocess
  lifecycle. Default config: MCP enabled, Serena enabled, hook OFF
  (proxy is the single source of truth for compression). User-side
  integration is two lines in any Strands app.

* headroom/proxy/handlers/openai.py — backend path now:
  - calls PrefixCacheTracker.update_from_response (was direct-OpenAI only)
  - intercepts CCR headroom_retrieve tool_calls server-side, mirroring
    the Anthropic handler pattern; NO silent fallback, re-raises on
    CCR errors (per feedback_no_silent_fallbacks)
  - works for both non-streaming and streaming paths

* headroom/proxy/handlers/streaming.py: _stream_openai_via_backend now
  accepts prefix_tracker + optimized_messages, parses cache stats from
  the SSE final-usage frame (cache_creation_input_tokens added to the
  state machine), records CCR retrieve feedback via a new
  _record_ccr_feedback_from_openai_sse helper. Streaming CCR intercept
  is intentionally out of scope (mirrors Anthropic streaming behaviour).

* headroom/backends/litellm.py: send_openai_message response usage block
  now carries cache_read_input_tokens / cache_creation_input_tokens
  (Anthropic/Bedrock dialect) and prompt_tokens_details.cached_tokens
  (OpenAI dialect). Backwards-compatible — cold-start callers see the
  same 3-key shape; cache keys appear only when the underlying provider
  returns them. Pinned by test_no_cache_fields_means_no_cache_keys.

* headroom/proxy/auth_mode.py: ("strands-agents/", "strands") added to
  CLIENT_UA_MAP. Production callers should also set X-Client: strands
  since the default openai-python UA carries no Strands signal.

* pyproject.toml: huggingface-hub>=1.5.0,<2.0 pinned in [ml] so a sibling
  install (e.g. strands-agents) can't drag the version below the floor
  transformers 5.x requires (otherwise Kompress silently goes
  "unavailable").

== 2. /stats MCP aggregation ==

* headroom/proxy/cost.py: _aggregate_mcp_events() reads the cross-process
  shared events file the Headroom MCP server already writes to and
  surfaces summary.mcp with three new keys:
    - compressions       (count of headroom_compress invocations)
    - tokens_removed     (sum of input - output across those)
    - retrievals         (count of headroom_retrieve — the load-bearing
                          over-compression alarm; if it grows linearly
                          with turn count, lossy compressors are
                          dropping info the model actually needs)
  Defensive on every axis — missing MCP SDK, missing file, malformed
  events, read errors — never blocks /stats.

* examples/strands_bundle_demo.py: stats panel prints the new fields so
  the demo shows the full proxy-HTTP + MCP-tool story in one view.

== 3. Codex compression-failure fail-closed protection ==

Reported by Camille (2026-05-21): Codex threads were locking with
"ran out of room in the model's context window" after Headroom's
compression timed out on an oversized response.create frame and
forwarded the original ~1.7 MB frame to the upstream, which then
rejected it. Codex's auto-compact heuristic gates on the upstream-
reported total_usage_tokens (which Headroom had been shrinking on
earlier turns), so its compaction never fired and the thread locked.

Validated against open Codex issues (CLI + Desktop share codex-rs/core):
* #16068 — confirms compaction gates on total_usage_tokens,
  estimated_token_count is computed but only logged
* #19806 — confirms image token estimator unbounded, contributes to
  the same ContextManager.get_total_token_usage → auto-compaction chain

* headroom/proxy/helpers.py: decide_compression_failure_action() with a
  unit-tested decision matrix:
    - asyncio.TimeoutError                              → refuse, always
    - non-timeout failure + frame > 256 KiB (configurable) → refuse
    - non-timeout failure + small frame                 → forward (legacy)
  Operator escape hatches:
    - HEADROOM_WS_FAIL_OPEN_ON_COMPRESSION_FAILURE=1 restores legacy
    - HEADROOM_WS_COMPRESSION_FAIL_THRESHOLD_BYTES tunes the threshold

* headroom/proxy/handlers/openai.py (WS /v1/responses): consults the
  helper after compression failure. On refuse: close client websocket
  code 1009 with "headroom: compression <reason> — please compact
  context and retry" reason; set termination_cause for the outer
  lifecycle finally; return.

* headroom/proxy/handlers/openai.py (HTTP /v1/responses): same helper.
  On refuse: raise HTTPException(413) with a structured error body so
  FastAPI's HTTPException handler emits a clean 413. The existing
  `except HTTPException: raise` guard in this handler already ensures
  the 413 propagates without being swallowed by the 502 catch-all.

Anthropic /v1/messages NOT changed in this branch: no equivalent bug
report on Anthropic-protocol clients, Claude Code (Anthropic-owned)
handles context overflow via its own cache_control/ephemeral
primitives, and Cursor/Aider don't maintain the local-Y estimate the
Codex bug requires. Deferred until a real report lands; the patch is
a one-liner reusing the same helper.

== Tests + verification ==

* tests/test_backends/test_litellm_cache_stats.py — 3 tests pinning
  cache-stat surfacing across Anthropic/OpenAI dialects + backwards-
  compat for no-cache responses.
* tests/test_proxy/test_openai_backend_path.py — 5 tests (Bedrock cache
  fields, OpenAI fallback shape, CCR intercept with provider="openai",
  CCR re-raise on exception, streaming signature contract).
* tests/test_proxy/test_mcp_stats_aggregation.py — 5 tests pinning the
  aggregator across compress+retrieve mixes, empty events, unknown event
  types, missing token fields, and read failures.
* tests/test_proxy/test_compression_failure_action.py — 12 tests pinning
  the fail-closed decision matrix (timeout always refuses, small
  transient passes through, oversize refuses, env override variants,
  custom threshold, invalid threshold falls back, 0/negative ignored).

* examples/strands_bedrock_demo.py — model_id bumped from deprecated
  Claude 3 Haiku to Sonnet 4.5 (the deprecated model now errors on
  account access).
* examples/strands_via_proxy_demo.py — proxy + Bedrock cache + streaming
  smoke test.
* examples/strands_mcp_dispatch_test.py — pure MCP round-trip probe.
* examples/strands_bundle_demo.py — full Strands + HeadroomBundle E2E
  demo (this is the shape a real Strands user copies into their app).

Full pytest: 5327 passed, 178 skipped. The previously-failing
test_core_operations.py::TestAddBatch::test_add_batch_basic passes now
that the huggingface-hub pin in pyproject.toml unblocks transformers
imports.

E2E verified live against AWS Bedrock (Sonnet 4.5):
* cache_write=10,438 on turn A → cache_read=10,438 on turn B
* streaming SSE final usage frame carries cache_read_input_tokens
* 78.7% reduction on a 50 KB JSON tool_result via SmartCrusher (
  dispatched per-content-type by ContentRouter)
* Strands Agent + HeadroomBundle: model autonomously called
  headroom_compress + headroom_retrieve via MCP; CompressionStore
  round-trip succeeded; final answer correct.
2026-05-21 11:00:14 -07:00

367 lines
14 KiB
Python

"""Tests for the OpenAI chat-completions backend (LiteLLM/Bedrock) path.
Covers Fix #1 (PrefixCacheTracker.update_from_response on backend path)
and Fix #2 (CCR response intercept for the OpenAI provider shape) on the
non-streaming backend path of ``handle_openai_chat``.
All three scenarios mock ``anthropic_backend.send_openai_message`` so we
don't need a real provider:
1. Backend response with cache_read_input_tokens > 0 → tracker.update_from_response
is called with the right cache_read_tokens and cache_write_tokens.
2. Backend response with headroom_retrieve tool call → ccr_response_handler.handle_response
is awaited with provider="openai", and the final body returned.
3. CCR intercept exception path → re-raises (NOT swallowed).
"""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
fastapi = pytest.importorskip("fastapi")
httpx = pytest.importorskip("httpx")
from fastapi.testclient import TestClient # noqa: E402
from headroom.backends.base import BackendResponse # noqa: E402
from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
class _RecordingTracker:
"""Stub PrefixCacheTracker that records ``update_from_response`` calls."""
def __init__(self, provider: str = "openai") -> None:
self.provider = provider
self.calls: list[dict] = []
self._frozen = 0
self._last_original: list[dict] = []
self._last_forwarded: list[dict] = []
def update_from_response(
self,
cache_read_tokens: int,
cache_write_tokens: int,
messages: list[dict],
message_token_counts: list[int] | None = None,
original_messages: list[dict] | None = None,
) -> None:
self.calls.append(
{
"cache_read_tokens": cache_read_tokens,
"cache_write_tokens": cache_write_tokens,
"messages": messages,
}
)
self._last_original = list(original_messages or messages)
self._last_forwarded = list(messages)
# Minimal surface used by handle_openai_chat — return 0 so we never freeze.
def get_frozen_message_count(self) -> int:
return self._frozen
def get_last_original_messages(self) -> list[dict]:
return list(self._last_original)
def get_last_forwarded_messages(self) -> list[dict]:
return list(self._last_forwarded)
def _make_config() -> ProxyConfig:
return ProxyConfig(
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
backend="anyllm",
anyllm_provider="openai",
)
def _make_mock_backend(response_body: dict, status_code: int = 200) -> MagicMock:
backend = MagicMock()
backend.name = "anyllm-openai"
backend.send_openai_message = AsyncMock(
return_value=BackendResponse(
body=response_body,
status_code=status_code,
headers={"content-type": "application/json"},
)
)
return backend
def _install_tracker_stub(client: TestClient) -> _RecordingTracker:
"""Force the session_tracker_store to hand out our recording tracker."""
tracker = _RecordingTracker(provider="openai")
# Find the proxy instance behind the app — it's stored as app.state.proxy.
proxy = client.app.state.proxy
proxy.session_tracker_store.get_or_create = MagicMock(return_value=tracker)
return tracker
def test_backend_response_updates_prefix_tracker_with_bedrock_cache_fields():
"""Bedrock/Anthropic-shape cache fields → tracker sees authoritative read/write counts."""
config = _make_config()
response_body = {
"id": "chatcmpl-bedrock-1",
"object": "chat.completion",
"model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "Hi!"},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 1000,
"completion_tokens": 20,
"total_tokens": 1020,
# Bedrock/Anthropic top-level keys
"cache_read_input_tokens": 700,
"cache_creation_input_tokens": 100,
# OpenAI shape (always populated by the LiteLLM normalizer)
"prompt_tokens_details": {"cached_tokens": 700},
},
}
mock_backend = _make_mock_backend(response_body)
with patch("headroom.proxy.server.AnyLLMBackend", return_value=mock_backend):
app = create_app(config)
with TestClient(app) as client:
tracker = _install_tracker_stub(client)
resp = client.post(
"/v1/chat/completions",
json={
"model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"messages": [{"role": "user", "content": "hi"}],
"stream": False,
},
headers={"Authorization": "Bearer test-key"},
)
assert resp.status_code == 200, resp.text
assert mock_backend.send_openai_message.await_count == 1
assert len(tracker.calls) == 1, tracker.calls
call = tracker.calls[0]
# Prefer the Bedrock authoritative top-level read/write counts.
assert call["cache_read_tokens"] == 700
assert call["cache_write_tokens"] == 100
def test_backend_response_falls_back_to_openai_cached_tokens_when_bedrock_keys_absent():
"""Pure OpenAI shape (no top-level Anthropic keys) → fall back to prompt_tokens_details + infer write."""
config = _make_config()
response_body = {
"id": "chatcmpl-openai-1",
"object": "chat.completion",
"model": "gpt-4o-mini",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "Hi!"},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 500,
"completion_tokens": 10,
"total_tokens": 510,
# No top-level Anthropic keys, only OpenAI shape
"prompt_tokens_details": {"cached_tokens": 200},
},
}
mock_backend = _make_mock_backend(response_body)
with patch("headroom.proxy.server.AnyLLMBackend", return_value=mock_backend):
app = create_app(config)
with TestClient(app) as client:
tracker = _install_tracker_stub(client)
resp = client.post(
"/v1/chat/completions",
json={
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "hi"}],
"stream": False,
},
headers={"Authorization": "Bearer test-key"},
)
assert resp.status_code == 200, resp.text
assert len(tracker.calls) == 1
call = tracker.calls[0]
assert call["cache_read_tokens"] == 200
# No cache_creation_input_tokens → inferred = prompt_tokens - cache_read = 500 - 200 = 300
assert call["cache_write_tokens"] == 300
def test_backend_response_with_ccr_tool_call_is_intercepted_and_resolved():
"""OpenAI-shape response carrying headroom_retrieve → CCR handler resolves it."""
config = _make_config()
# First response: tool_call for headroom_retrieve
tool_call_response = {
"id": "chatcmpl-ccr-1",
"object": "chat.completion",
"model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_abc",
"type": "function",
"function": {
"name": "headroom_retrieve",
"arguments": '{"hash": "deadbeef"}',
},
}
],
},
"finish_reason": "tool_calls",
}
],
"usage": {
"prompt_tokens": 100,
"completion_tokens": 10,
"total_tokens": 110,
},
}
final_resp_json = {
"id": "chatcmpl-ccr-final",
"object": "chat.completion",
"model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "Resolved!"},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 100,
"completion_tokens": 5,
"total_tokens": 105,
},
}
mock_backend = _make_mock_backend(tool_call_response)
with patch("headroom.proxy.server.AnyLLMBackend", return_value=mock_backend):
app = create_app(config)
with TestClient(app) as client:
_install_tracker_stub(client)
proxy = client.app.state.proxy
# Replace the response handler with a recording mock.
recording_handler = MagicMock()
recording_handler.has_ccr_tool_calls = MagicMock(return_value=True)
recording_handler.handle_response = AsyncMock(return_value=final_resp_json)
proxy.ccr_response_handler = recording_handler
resp = client.post(
"/v1/chat/completions",
json={
"model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"messages": [{"role": "user", "content": "hi"}],
"stream": False,
},
headers={"Authorization": "Bearer test-key"},
)
assert resp.status_code == 200, resp.text
# handle_response was awaited with provider="openai"
recording_handler.handle_response.assert_awaited_once()
_args, kwargs = recording_handler.handle_response.call_args
assert kwargs.get("provider") == "openai"
# Resolved body propagated back to the client
assert resp.json()["choices"][0]["message"]["content"] == "Resolved!"
def test_backend_ccr_intercept_exception_is_reraised_not_swallowed():
"""CCR resolution failure on the backend path → 500, NOT silent fallback to original body."""
config = _make_config()
tool_call_response = {
"id": "chatcmpl-ccr-fail",
"object": "chat.completion",
"model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_bad",
"type": "function",
"function": {
"name": "headroom_retrieve",
"arguments": '{"hash": "badhash"}',
},
}
],
},
"finish_reason": "tool_calls",
}
],
"usage": {"prompt_tokens": 50, "completion_tokens": 5, "total_tokens": 55},
}
mock_backend = _make_mock_backend(tool_call_response)
with patch("headroom.proxy.server.AnyLLMBackend", return_value=mock_backend):
app = create_app(config)
with TestClient(app) as client:
_install_tracker_stub(client)
proxy = client.app.state.proxy
failing_handler = MagicMock()
failing_handler.has_ccr_tool_calls = MagicMock(return_value=True)
failing_handler.handle_response = AsyncMock(
side_effect=RuntimeError("ccr-store-blew-up")
)
proxy.ccr_response_handler = failing_handler
resp = client.post(
"/v1/chat/completions",
json={
"model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"messages": [{"role": "user", "content": "hi"}],
"stream": False,
},
headers={"Authorization": "Bearer test-key"},
)
# The outer `try/except Exception` on the backend block converts the
# re-raise into a 500 response. The critical assertion is that the
# original tool_call body is NOT returned to the client — which is
# what a silent fallback would do.
failing_handler.handle_response.assert_awaited_once()
assert resp.status_code == 500, (
f"expected 500 (CCR error re-raised), got {resp.status_code}: {resp.text[:200]}"
)
body = resp.json()
# Confirm we didn't propagate the original tool_call body.
assert (
"choices" not in body
or body.get("choices", [{}])[0].get("message", {}).get("tool_calls") is None
)
assert "error" in body
assert "ccr-store-blew-up" in body["error"]["message"]
def test_backend_streaming_passes_prefix_tracker_through():
"""Streaming backend path should accept and use prefix_tracker — non-regression smoke."""
# The wiring contract is structural — just confirm the parameter exists.
import inspect
from headroom.proxy.handlers.streaming import StreamingMixin
sig = inspect.signature(StreamingMixin._stream_openai_via_backend)
assert "prefix_tracker" in sig.parameters, (
"_stream_openai_via_backend must accept prefix_tracker to match the direct path"
)
assert "optimized_messages" in sig.parameters, (
"_stream_openai_via_backend must accept optimized_messages so the "
"tracker can record the messages that were sent"
)