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/anthropic): preserve non-2xx upstream status through security scan (#2100)

Abhay Singhaa788164fd5a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 538bef2e4..85b360cff 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -102,6 +102,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug Fixes
+* **proxy/anthropic:** don't launder a non-2xx upstream into HTTP 200 when enterprise security scans the response. On the non-streaming `/v1/messages` path the response-scan branch rebuilt the reply as `httpx.Response(status_code=200)` and returned it without checking the upstream status, so a rate-limit (429), overloaded (529), or other 4xx error whose JSON body was scanned reached the client as an HTTP 200 — the client's retry/backoff never fired and an error looked like success. The branch is now gated on a 200 upstream, matching the sibling CCR/cache/buffered-stream blocks in the same handler; non-2xx responses fall through and keep their real status.
* **learn:** classify timeout and connection tool failures correctly instead of as generic runtime errors. In `classify_error` the generic `RUNTIME_ERROR` pattern (`Traceback|Exception:|Error:`) was checked before the dedicated `TIMEOUT` and `CONNECTION_ERROR` patterns. Because every Python exception repr is `XxxError: ...`, a `TimeoutError: ...` or `ConnectionError: ...` matched the catch-all first and was miscategorized as `RUNTIME_ERROR`, leaving those two categories unreachable for the common colon-repr form (they only fired for tokenless phrasings like `deadline exceeded`). The `TIMEOUT` and `CONNECTION_ERROR` patterns are now checked before the generic catch-all; tokenless generic errors still classify as `RUNTIME_ERROR`.
* **tokenizers:** resolve HuggingFace tokenizer names by the most-specific prefix. `get_tokenizer_name` scanned `MODEL_TO_TOKENIZER` in dict-insertion order and returned the first key the model merely starts with, so a short family key shadowed a more-specific one — `qwen2-7b-instruct` matched `qwen` before `qwen2`/`qwen2-7b` and resolved to the Qwen1 tokenizer (a different vocabulary, hence wrong token counts); `qwen2.5-*` and `deepseek-v2.x` were mis-resolved the same way. It now picks the longest matching prefix, mirroring the order-dependent-prefix guard the sibling tiktoken `get_encoding_for_model` already documents.
* **pricing:** map retired `claude-3-sonnet-20240229` to a Sonnet-tier price instead of Haiku. When LiteLLM's cost DB lacks the retired model, resolution falls through to `MODEL_ALIASES`, which pointed Claude 3 Sonnet (a $3/$15-per-1M model) at `claude-3-haiku-20240307` ($0.25/$1.25) — a different tier that underpriced every cost/savings figure for that model ~12x on both input and output. It now aliases to `claude-sonnet-4-20250514`, the same-price target the other retired-Sonnet aliases already use.
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.py
index d02d09afc..8afdc6049 100644
--- a/headroom/proxy/handlers/anthropic.py
+++ b/headroom/proxy/handlers/anthropic.py
@@ -3170,8 +3170,19 @@ class AnthropicHandlerMixin:
if _compression_failed:
response_headers["x-headroom-compression-failed"] = "true"
- # Enterprise Security: scan response + de-anonymize
- if self.security and _security_ctx and resp_json:
+ # Enterprise Security: scan response + de-anonymize.
+ # Gate on a 200 upstream like the sibling CCR/cache/buffered
+ # blocks below: without this, a non-2xx upstream (rate limit
+ # 429, overloaded 529, 5xx) whose JSON body is scanned was
+ # rebuilt as httpx.Response(status_code=200) and returned as
+ # HTTP 200, so the client's retry/backoff never triggered and
+ # an error looked like success.
+ if (
+ self.security
+ and _security_ctx
+ and resp_json
+ and response.status_code == 200
+ ):
try:
resp_json = self.security.scan_response(resp_json, _security_ctx)
response = httpx.Response(
diff --git a/tests/test_anthropic_pre_upstream_backpressure.py b/tests/test_anthropic_pre_upstream_backpressure.py
index 7e2160006..c0327a004 100644
--- a/tests/test_anthropic_pre_upstream_backpressure.py
+++ b/tests/test_anthropic_pre_upstream_backpressure.py
@@ -26,6 +26,7 @@ import logging
import os
import time
from types import SimpleNamespace
+from typing import Any
from unittest.mock import MagicMock
import anyio
@@ -74,8 +75,8 @@ class _DummyMetrics:
class _ResponseStub:
- def __init__(self) -> None:
- self.status_code = 200
+ def __init__(self, status_code: int = 200) -> None:
+ self.status_code = status_code
self.headers = {"content-type": "application/json"}
self._text = json.dumps(
{
@@ -115,6 +116,8 @@ class _DummyAnthropicHandler(AnthropicHandlerMixin):
anthropic_pre_upstream_sem: asyncio.Semaphore | None = None,
upstream_delay_s: float = 0.0,
raise_during_critical: bool = False,
+ security: Any = None,
+ upstream_status: int = 200,
) -> None:
self.rate_limiter = None
self.metrics = _DummyMetrics()
@@ -140,7 +143,8 @@ class _DummyAnthropicHandler(AnthropicHandlerMixin):
self.cost_tracker = None
self.memory_handler = None
self.cache = None
- self.security = None
+ self.security = security
+ self._upstream_status = upstream_status
self.ccr_context_tracker = None
self.ccr_injector = None
self.ccr_response_handler = None
@@ -258,7 +262,7 @@ class _DummyAnthropicHandler(AnthropicHandlerMixin):
if self._upstream_delay_s > 0:
await asyncio.sleep(self._upstream_delay_s)
self.upstream_exit_times.append(time.perf_counter())
- return _ResponseStub()
+ return _ResponseStub(status_code=self._upstream_status)
def _get_compression_cache(self, session_id):
return SimpleNamespace(
@@ -931,3 +935,73 @@ def test_early_exit_paths_release_semaphore_under_contention(scenario):
with _tokenizer_patch():
anyio.run(_run)
+
+
+# --------------------------------------------------------------------------- #
+# Enterprise security response scan must not launder a non-2xx upstream #
+# --------------------------------------------------------------------------- #
+
+
+class _PassthroughSecurity:
+ """Minimal enterprise-security stub: scan_request returns a truthy context
+ (so the response-scan branch is armed) and scan_response leaves the body
+ unchanged."""
+
+ def scan_request(self, messages, ctx):
+ return messages, {"anonymization": {}}
+
+ def scan_response(self, resp_json, ctx):
+ return resp_json
+
+
[email protected]("upstream_status", [429, 529, 400])
+def test_security_scan_preserves_non_200_upstream_status(upstream_status):
+ """A non-2xx upstream must reach the client with its real status even when
+ enterprise security is scanning responses.
+
+ The response-scan branch rebuilt the reply as httpx.Response(status_code=200)
+ and returned it without checking the upstream status, so a rate-limit (429),
+ overloaded (529), or 4xx error was laundered into an HTTP 200 and the
+ client's retry/backoff never fired. The branch is now gated on a 200 upstream
+ like the sibling CCR/cache blocks.
+ """
+ sem = asyncio.Semaphore(2)
+ handler = _DummyAnthropicHandler(
+ anthropic_pre_upstream_sem=sem,
+ security=_PassthroughSecurity(),
+ upstream_status=upstream_status,
+ )
+ request = _build_request(
+ {
+ "model": "claude-3-5-sonnet-latest",
+ "messages": [{"role": "user", "content": "hello"}],
+ },
+ {"authorization": "Bearer sk-ant-api-test"},
+ )
+
+ with _tokenizer_patch():
+ response = anyio.run(handler.handle_anthropic_messages, request)
+
+ assert response.status_code == upstream_status
+
+
+def test_security_scan_still_returns_200_for_ok_upstream():
+ """Guard the positive case: a 200 upstream is still scanned and returned 200."""
+ sem = asyncio.Semaphore(2)
+ handler = _DummyAnthropicHandler(
+ anthropic_pre_upstream_sem=sem,
+ security=_PassthroughSecurity(),
+ upstream_status=200,
+ )
+ request = _build_request(
+ {
+ "model": "claude-3-5-sonnet-latest",
+ "messages": [{"role": "user", "content": "hello"}],
+ },
+ {"authorization": "Bearer sk-ant-api-test"},
+ )
+
+ with _tokenizer_patch():
+ response = anyio.run(handler.handle_anthropic_messages, request)
+
+ assert response.status_code == 200