mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(proxy): log client-supplied model ids as one escaped token (#4854)
## Description
The Anthropic handler logged the request's `model` field raw in three
places (`RESPONSE-CACHE-HIT`, the `cache_mode_prefix_mismatch` skip
line, `UPSTREAM_ERROR`). `sanitize_anthropic_model_id` strips ANSI
styling but keeps an interior newline, so a model id with a newline
split one log record into two, and the second line could look like any
other record. The OpenAI handler had the same raw `model=` in its
cache-hit, upstream-error, `/v1/responses` passthrough (HTTP and WS) and
token-recount lines, and the Bedrock handler logged the model id from
the URL path the same way.
All of them now go through `headroom.log_safety.safe_id`, the helper
`providers/openai.py` already uses for model ids: the value is rendered
with `repr` (newlines escaped) and capped in length.
Closes #
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- `headroom/proxy/handlers/anthropic.py`: `safe_id(model)` in the
cache-hit, prefix-mismatch and upstream-error log lines.
- `headroom/proxy/handlers/openai.py`: `safe_id(...)` in the cache-hit,
upstream-error, `/v1/responses` HTTP and WS passthrough, and raw-payload
recount log lines.
- `headroom/proxy/handlers/bedrock.py`: `safe_id(model_id)` in the
compression log line.
- `tests/test_proxy/test_log_model_id.py`: drives `/v1/messages` and
`/v1/chat/completions` through `create_app` with a model id that
contains a newline and checks the `UPSTREAM_ERROR` and
`RESPONSE-CACHE-HIT` records stay on one line.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
# new test, with the fix
$ pytest -q tests/test_proxy/test_log_model_id.py
3 passed in 9.18s
# same test with the handler changes stashed (origin/main code)
FAILED tests/test_proxy/test_log_model_id.py::test_upstream_error_log_keeps_model_on_one_line[/v1/messages-headers0]
FAILED tests/test_proxy/test_log_model_id.py::test_upstream_error_log_keeps_model_on_one_line[/v1/chat/completions-headers1]
FAILED tests/test_proxy/test_log_model_id.py::test_anthropic_cache_hit_log_keeps_model_on_one_line
3 failed in 9.36s
# area tests
$ pytest -q tests/test_proxy tests/test_bedrock_*.py tests/test_log_safety.py
738 passed, 1 warning in 251.77s
$ ruff check / ruff format --check (0.17.3) on the 4 changed files: All checks passed, 4 files already formatted
$ mypy headroom/proxy/handlers/{anthropic,openai,bedrock}.py --ignore-missing-imports: Success: no issues found in 3 source files
```
## Real Behavior Proof
- Environment: macOS, Python 3.12, the real `headroom proxy` CLI
(`--stateless --no-telemetry`, isolated `HOME`) with
`--anthropic-api-url` pointed at a local HTTP server that answers every
request with an Anthropic-format 400. No mocks in the proxy process.
- Exact command / steps: `curl -X POST
http://127.0.0.1:<port>/v1/messages` with `"model": "claude-x\nINJECTED
fake log line"`; grep the proxy's stderr.
- Observed result:
- origin/main: `UPSTREAM_ERROR status=400 ... model=claude-x` followed
by a forged line starting `INJECTED fake log line compressed=no ...`;
the provider warning `Unknown Anthropic model 'claude-x` is also split,
with `INJECTED fake log line': using default Claude limit ...` on its
own line.
- this branch: `UPSTREAM_ERROR status=400 ... model='claude-x\nINJECTED
fake log line' compressed=no ...` and `Unknown Anthropic model
'claude-x\nINJECTED fake log line': using default Claude limit ...`,
each on one line; no line starts with the injected text.
- The live run found the provider warning, which the handler tests did
not cover; fixed in the second commit with its own regression test.
- Not tested: a live provider call. Separately observed on both trees
and not changed here: handlers echo the raw model into the
`x-headroom-model` response header, so a model id containing a newline
makes uvicorn/h11 drop the connection for that request.
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: log format only: `model=` values are
now quoted (`model='claude-sonnet-4-6'`).
- Kill switch / disable path: n/a
- Unsafe override required: no
- Qualification impact: none; anything that greps these lines for
`model=<id>` sees the id in quotes.
- Rollback path: revert this commit.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Additional Notes
Fix adapted from a proposal by HetCreep.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4854"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
ab1d0292df
commit
b9f6255395
@@ -25,6 +25,7 @@ from datetime import datetime
|
||||
from typing import Any, cast
|
||||
|
||||
from headroom import paths as _paths
|
||||
from headroom.log_safety import safe_id
|
||||
from headroom.offline import pin_litellm_cost_map_local
|
||||
from headroom.pricing.deepseek_tiers import (
|
||||
LEGACY_MODEL_IDS,
|
||||
@@ -914,7 +915,7 @@ class AnthropicProvider(Provider):
|
||||
if model not in _UNKNOWN_MODEL_WARNINGS:
|
||||
_UNKNOWN_MODEL_WARNINGS.add(model)
|
||||
logger.warning(
|
||||
f"Unknown Anthropic model '{model}': {reason} ({limit:,} tokens). "
|
||||
f"Unknown Anthropic model {safe_id(model)}: {reason} ({limit:,} tokens). "
|
||||
f"To configure explicitly, set HEADROOM_MODEL_LIMITS env var or "
|
||||
f"add to ~/.headroom/models.json"
|
||||
)
|
||||
|
||||
@@ -40,7 +40,7 @@ from headroom.ccr.marker_resolution import resolve_markers_in_response
|
||||
from headroom.ccr.tool_calls import has_ccr_retrieve_tool
|
||||
from headroom.config import resolve_omlx_target_api_url
|
||||
from headroom.copilot_auth import apply_copilot_api_auth, is_copilot_upstream_url
|
||||
from headroom.log_safety import describe_exception
|
||||
from headroom.log_safety import describe_exception, safe_id
|
||||
from headroom.pipeline import PipelineStage, summarize_routing_markers
|
||||
from headroom.proxy import public_errors
|
||||
from headroom.proxy.anthropic_wire import (
|
||||
@@ -2029,7 +2029,7 @@ class AnthropicHandlerMixin:
|
||||
# cache turn is indistinguishable from a turn that died
|
||||
# silently, which is exactly how #3019 stayed invisible.
|
||||
logger.info(
|
||||
f"[{request_id}] RESPONSE-CACHE-HIT: model={model} "
|
||||
f"[{request_id}] RESPONSE-CACHE-HIT: model={safe_id(model)} "
|
||||
f"bytes={len(cached.response_body)} "
|
||||
f"age_s={(datetime.now() - cached.created_at).total_seconds():.0f} "
|
||||
f"hits={cached.hit_count}"
|
||||
@@ -2837,7 +2837,7 @@ class AnthropicHandlerMixin:
|
||||
"[%s] Compression skipped: reason=cache_mode_prefix_mismatch "
|
||||
"model=%s current_len=%d previous_len=%d",
|
||||
request_id,
|
||||
model,
|
||||
safe_id(model),
|
||||
len(original_client_messages),
|
||||
len(previous_original_messages),
|
||||
)
|
||||
@@ -4951,7 +4951,7 @@ class AnthropicHandlerMixin:
|
||||
f"status={response.status_code} "
|
||||
f"error_type={err_type} "
|
||||
f"error_msg={err_msg!r} "
|
||||
f"model={model} "
|
||||
f"model={safe_id(model)} "
|
||||
f"compressed={'yes' if transforms_applied else 'no'} "
|
||||
f"transforms={transforms_applied} "
|
||||
f"original_tokens={original_tokens} "
|
||||
|
||||
@@ -33,6 +33,8 @@ import time
|
||||
from typing import TYPE_CHECKING
|
||||
from urllib.parse import quote
|
||||
|
||||
from headroom.log_safety import safe_id
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import Request
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
@@ -229,7 +231,7 @@ class BedrockHandlerMixin:
|
||||
result.tokens_before,
|
||||
result.tokens_after,
|
||||
tokens_saved,
|
||||
model_id,
|
||||
safe_id(model_id),
|
||||
)
|
||||
except Exception as err:
|
||||
# Fail open: never break a request because compression failed.
|
||||
|
||||
@@ -26,7 +26,7 @@ from types import MappingProxyType
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from urllib.parse import quote, unquote, urlparse
|
||||
|
||||
from headroom.log_safety import describe_exception
|
||||
from headroom.log_safety import describe_exception, safe_id
|
||||
from headroom.proxy.conversation_savings import savings_conversation_key, turn_conversation_key
|
||||
from headroom.proxy.handlers._failure_logging import log_hook_failure, log_request_failure
|
||||
from headroom.proxy.helpers import (
|
||||
@@ -4028,7 +4028,7 @@ class OpenAIHandlerMixin:
|
||||
# timings. Log it, or a served-from-cache turn looks exactly
|
||||
# like a turn that died silently (#3019).
|
||||
logger.info(
|
||||
f"[{request_id}] RESPONSE-CACHE-HIT: model={model} "
|
||||
f"[{request_id}] RESPONSE-CACHE-HIT: model={safe_id(model)} "
|
||||
f"bytes={len(cached.response_body)} "
|
||||
f"age_s={(datetime.now() - cached.created_at).total_seconds():.0f} "
|
||||
f"hits={cached.hit_count}"
|
||||
@@ -5688,7 +5688,7 @@ class OpenAIHandlerMixin:
|
||||
f"status={response.status_code} "
|
||||
f"error_type={err_type} "
|
||||
f"error_msg={err_msg!r} "
|
||||
f"model={model} "
|
||||
f"model={safe_id(model)} "
|
||||
f"compressed={'yes' if transforms_applied else 'no'} "
|
||||
f"transforms={transforms_applied} "
|
||||
f"original_tokens={original_tokens} "
|
||||
@@ -6965,7 +6965,7 @@ class OpenAIHandlerMixin:
|
||||
_reason or "no_compression",
|
||||
_bytes_before,
|
||||
auth_mode.value,
|
||||
model or "unknown",
|
||||
safe_id(model or "unknown"),
|
||||
)
|
||||
except Exception as _e:
|
||||
_http_body_bytes = len(json.dumps(body).encode("utf-8", errors="replace"))
|
||||
@@ -8317,7 +8317,7 @@ class OpenAIHandlerMixin:
|
||||
raw_bytes,
|
||||
frame_type or "unknown",
|
||||
classify_auth_mode(ws_headers).value,
|
||||
model or "unknown",
|
||||
safe_id(model or "unknown"),
|
||||
)
|
||||
|
||||
# Resolved before the frame helpers below, which read it.
|
||||
@@ -11651,7 +11651,7 @@ class OpenAIHandlerMixin:
|
||||
"model %s (%s: %s); savings for this turn are "
|
||||
"reported against the cache-swapped input",
|
||||
session_id,
|
||||
model_name,
|
||||
safe_id(model_name),
|
||||
type(e).__name__,
|
||||
e,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""A client-supplied model id is logged as one token, never as raw text.
|
||||
|
||||
``sanitize_anthropic_model_id`` keeps an interior newline, so the handlers must
|
||||
render the model with ``safe_id`` wherever they log it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
fastapi = pytest.importorskip("fastapi")
|
||||
httpx = pytest.importorskip("httpx")
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
from headroom.proxy.models import CacheEntry # noqa: E402
|
||||
from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
|
||||
|
||||
MULTILINE_MODEL = "claude-x\n2026-01-01 00:00:00 INFO headroom.other second-line"
|
||||
|
||||
|
||||
class _Capture(logging.Handler):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(level=logging.INFO)
|
||||
self.messages: list[str] = []
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
self.messages.append(record.getMessage())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proxy_logs():
|
||||
target = logging.getLogger("headroom.proxy")
|
||||
handler = _Capture()
|
||||
previous = target.level
|
||||
target.addHandler(handler)
|
||||
target.setLevel(logging.INFO)
|
||||
try:
|
||||
yield handler
|
||||
finally:
|
||||
target.removeHandler(handler)
|
||||
target.setLevel(previous)
|
||||
|
||||
|
||||
def _config(**overrides) -> ProxyConfig:
|
||||
base = {
|
||||
"optimize": False,
|
||||
"cache_enabled": False,
|
||||
"rate_limit_enabled": False,
|
||||
"cost_tracking_enabled": False,
|
||||
"log_requests": False,
|
||||
"image_optimize": False,
|
||||
}
|
||||
base.update(overrides)
|
||||
return ProxyConfig(**base)
|
||||
|
||||
|
||||
def _error_response() -> httpx.Response:
|
||||
return httpx.Response(
|
||||
400,
|
||||
content=json.dumps({"error": {"type": "invalid_request_error", "message": "bad"}}).encode(),
|
||||
headers={"content-type": "application/json"},
|
||||
)
|
||||
|
||||
|
||||
def _assert_single_line(handler: _Capture, marker: str) -> None:
|
||||
lines = [m for m in handler.messages if marker in m]
|
||||
assert lines, f"{marker} was not logged"
|
||||
for line in lines:
|
||||
assert "\n" not in line
|
||||
assert "claude-x\\n2026" in line
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "headers"),
|
||||
[
|
||||
("/v1/messages", {"x-api-key": "test-key", "anthropic-version": "2023-06-01"}),
|
||||
("/v1/chat/completions", {"authorization": "Bearer test-key"}),
|
||||
],
|
||||
)
|
||||
def test_upstream_error_log_keeps_model_on_one_line(proxy_logs, path, headers):
|
||||
body = {
|
||||
"model": MULTILINE_MODEL,
|
||||
"max_tokens": 16,
|
||||
"messages": [{"role": "user", "content": "hi"}],
|
||||
}
|
||||
with patch("headroom.proxy.server.AnyLLMBackend"):
|
||||
app = create_app(_config())
|
||||
with TestClient(app) as client:
|
||||
client.app.state.proxy._retry_request = AsyncMock(return_value=_error_response())
|
||||
client.post(path, headers=headers, json=body)
|
||||
|
||||
_assert_single_line(proxy_logs, "UPSTREAM_ERROR")
|
||||
|
||||
|
||||
def test_anthropic_cache_hit_log_keeps_model_on_one_line(proxy_logs):
|
||||
entry = CacheEntry(
|
||||
response_body=json.dumps(
|
||||
{
|
||||
"id": "msg_cached",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-sonnet-4-6",
|
||||
"content": [{"type": "text", "text": "cached"}],
|
||||
"stop_reason": "end_turn",
|
||||
"usage": {"input_tokens": 1, "output_tokens": 1},
|
||||
}
|
||||
).encode(),
|
||||
response_headers={},
|
||||
created_at=datetime.now(),
|
||||
ttl_seconds=3600,
|
||||
)
|
||||
body = {
|
||||
"model": MULTILINE_MODEL,
|
||||
"max_tokens": 16,
|
||||
"messages": [{"role": "user", "content": "hi"}],
|
||||
}
|
||||
with patch("headroom.proxy.server.AnyLLMBackend"):
|
||||
app = create_app(_config(cache_enabled=True))
|
||||
with TestClient(app) as client:
|
||||
proxy = client.app.state.proxy
|
||||
proxy.cache.get = AsyncMock(return_value=entry)
|
||||
proxy._retry_request = AsyncMock(side_effect=AssertionError("no upstream on a hit"))
|
||||
client.post(
|
||||
"/v1/messages",
|
||||
headers={"x-api-key": "test-key", "anthropic-version": "2023-06-01"},
|
||||
json=body,
|
||||
)
|
||||
|
||||
_assert_single_line(proxy_logs, "RESPONSE-CACHE-HIT")
|
||||
|
||||
|
||||
def test_unknown_anthropic_model_warning_logs_model_as_one_token() -> None:
|
||||
from headroom.providers.anthropic import AnthropicProvider
|
||||
|
||||
target = logging.getLogger("headroom.providers.anthropic")
|
||||
handler = _Capture()
|
||||
target.addHandler(handler)
|
||||
try:
|
||||
AnthropicProvider().get_context_limit(MULTILINE_MODEL + " provider-warning")
|
||||
finally:
|
||||
target.removeHandler(handler)
|
||||
|
||||
[message] = [m for m in handler.messages if "Unknown Anthropic model" in m]
|
||||
assert "\n" not in message
|
||||
assert repr(MULTILINE_MODEL + " provider-warning") in message
|
||||
Reference in New Issue
Block a user