mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-08-27 14:17:10 -04:00
Closes #861 ## What First piece of compression quality measurement on **real proxied sessions** (vs the existing public-benchmark evals): an opt-in recorder captures (original, compressed) message pairs at each compression event, and a deterministic offline prober scores what survived. **Recorder** (`headroom/proxy/probe_recorder.py`) - `CompressionEventRecorder` implements the existing `PipelineExtension` protocol, subscribed to `INPUT_COMPRESSED`. Registered ONLY when `HEADROOM_PROBE_RECORD_DIR` is set — off means not even constructed, zero request-path overhead. - One JSONL line per compression event that changed tokens: `{ts, request_id, provider, model, tokens_before, tokens_after, transforms_applied, original_messages, compressed_messages}`. One file per PID (no interleaving), directory mode 0700. - Fail-open everywhere: construction failure logs a warning and disables recording; runtime exceptions are already swallowed by `PipelineExtensionManager.emit`. - Enabling handler change: the two `INPUT_COMPRESSED` emit sites (anthropic + openai) add a read-only `original_messages` reference to event metadata. No copies, no behavior change for other consumers. **Probes** (`headroom/evals/session_probes.py` + `headroom evals probes` CLI) - Probe targets extracted from ORIGINAL tool-result content across three dimensions: **exact numerics** (number + key context, incl. JSON-quoted keys), **artifact trail** (paths, URLs, hex hashes, UUIDs), **error evidence** (lines matching the existing `is_error_content` heuristic). - Each target classified as **retained** (verbatim, or surviving a legitimate format conversion — punctuation-normalized match; numerics require key AND value to survive; error lines tolerate dropped JSON key prefixes), **recoverable** (absent but a CCR retrieval marker is present), or **lost** (gone with no retrieval path). - Report: aggregate retention per dimension, bucketed by compression ratio (the quality-per-ratio curve), and grouped per transform. `--json-output` for machine-readable results. - Fully offline: no LLM, no API key. The recording format is designed to feed an LLM-judge pass later (out of scope per #861). ## Tests 33 new tests (red before, green after): `tests/test_probe_recorder.py` (11 — event filtering, JSONL shape, env activation, fail-open on unusable path, 0700 dir mode) and `tests/test_session_probes.py` (22 — extraction per dimension incl. JSON-quoted numerics, retained/recoverable/lost classification, format-change survival for numerics and error lines, ratio bucketing, transform dedup, malformed-line skipping, report rendering/serialization). Both proxy lifecycle tests additionally assert the INPUT_COMPRESSED `original_messages` metadata contract end-to-end through the real anthropic/openai handlers, so a refactor cannot silently disable the recorder. Local runs: new tests + `tests/test_proxy_pipeline_lifecycle.py` + `tests/test_canonical_pipeline.py` + `tests/test_pipeline.py` — 45 passed. `ruff check` + `uvx ruff format --check` clean. ### Self-review hardening (second commit) - Hex artifact regex now requires at least one `a-f`, so bare decimal runs (timestamps, counters) no longer inflate the artifact dimension. - Inflation events (ratio > 1, the #847 territory) get an explicit `1.00+ (inflated)` ratio bucket instead of silently dropping out of the bucketed view. - `run_probes` streams recording files line by line instead of slurping them. - Documented honestly: marker recoverability is event-scoped (comparative metric, not absolute); recorder writes synchronously on the request path (diagnostic sessions, not always-on). - `headroom/evals/README.md` gained a Session Probes usage section. ## Real behavior proof **Setup:** macOS (Darwin 25.5), Python 3.11.9, this branch, real proxy (`python -m headroom.proxy.server --port 18994 --anthropic-api-url http://127.0.0.1:18995`) with a local mock Anthropic upstream (no key), `HEADROOM_PROBE_RECORD_DIR=/tmp/headroom-probe-proof/recordings`. **Steps:** POSTed three Anthropic-format conversations whose tool results carry large JSON arrays (220-row uniform logs, 3000-row logs, 800 heterogeneous events), each containing known numerics, paths, trace hashes, and one error line. **Observed** — recorder wrote `compression-events-<pid>.jsonl` (one line per event); `headroom evals probes --recordings ...`: ``` Probed 3 compression events Aggregate retention: numerics 97.7% retained, 2.3% recoverable, 0.0% lost (527 targets) artifacts 100.0% retained, 0.0% recoverable, 0.0% lost (6555 targets) errors 100.0% retained, 0.0% recoverable, 0.0% lost (3 targets) By compression ratio (tokens_after / tokens_before): ratio 0.50-0.75: numerics 100.0% retained (CSV compaction — lossless, correctly recognized) ratio 0.75-1.00: numerics 95.7% retained, 4.3% recoverable (SmartCrusher sampling — dropped values carried a CCR marker) ``` All three classifications exercised: verbatim/format-change retention on the CSV-compacted events, **recoverable** on the heterogeneous event where SmartCrusher sampled rows out behind a `Retrieve more: hash=` marker, and the injected error lines retained in every event (the error-protection gate held). The `lost` path is covered by unit tests. The first iteration of this proof exposed two real bugs — naive verbatim matching misreported lossless JSON→CSV compaction as 100% lost, and duplicated transform markers double-counted tallies — both fixed with regression tests. **Not tested live:** Gemini path (no `INPUT_COMPRESSED` emit parity — pre-existing, same gap as #819); LLM-judge scoring (out of scope per #861). ## Security Recordings contain full conversation content in plaintext: opt-in env var only, local disk only, dir mode 0700, documented in CLI help. ## Out of scope (per #861) LLM-judge dimensions (decisions/intent, next steps), ACON-style counterfactual replay, automatic rule revision. --------- Co-authored-by: Ash Rhodes <ashley.rhodes@king.com>
237 lines
8 KiB
Python
237 lines
8 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, call, patch
|
|
|
|
import httpx
|
|
from fastapi.testclient import TestClient
|
|
|
|
from headroom.pipeline import PipelineStage
|
|
from headroom.proxy.server import ProxyConfig, create_app
|
|
|
|
|
|
class _RecordingExtension:
|
|
def __init__(self) -> None:
|
|
self.stages: list[PipelineStage] = []
|
|
self.events: list = []
|
|
|
|
def on_pipeline_event(self, event):
|
|
self.stages.append(event.stage)
|
|
self.events.append(event)
|
|
return None
|
|
|
|
|
|
class _DummyTokenizer:
|
|
def count_messages(self, messages):
|
|
return len(messages)
|
|
|
|
|
|
def _assert_compressed_event_carries_originals(events: list) -> None:
|
|
"""INPUT_COMPRESSED must expose the pre-compression messages to extensions.
|
|
|
|
The probe recorder (headroom.proxy.probe_recorder) depends on this
|
|
metadata contract; dropping it silently disables session recording.
|
|
"""
|
|
compressed = [event for event in events if event.stage is PipelineStage.INPUT_COMPRESSED]
|
|
assert compressed
|
|
original = compressed[0].metadata.get("original_messages")
|
|
assert isinstance(original, list)
|
|
assert any(
|
|
message.get("role") == "user" and "hello" in str(message.get("content"))
|
|
for message in original
|
|
if isinstance(message, dict)
|
|
)
|
|
|
|
|
|
def _assert_stage_order(stages: list[PipelineStage]) -> None:
|
|
expected = [
|
|
PipelineStage.SETUP,
|
|
PipelineStage.PRE_START,
|
|
PipelineStage.POST_START,
|
|
PipelineStage.INPUT_RECEIVED,
|
|
PipelineStage.INPUT_ROUTED,
|
|
PipelineStage.INPUT_COMPRESSED,
|
|
PipelineStage.INPUT_REMEMBERED,
|
|
PipelineStage.PRE_SEND,
|
|
PipelineStage.POST_SEND,
|
|
PipelineStage.RESPONSE_RECEIVED,
|
|
]
|
|
positions = [stages.index(stage) for stage in expected]
|
|
assert positions == sorted(positions)
|
|
|
|
|
|
def test_proxy_shutdown_unloads_image_models() -> None:
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
image_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,
|
|
)
|
|
app = create_app(config)
|
|
proxy = app.state.proxy
|
|
proxy.http_client = None
|
|
proxy.memory_handler = None
|
|
|
|
quota_registry = SimpleNamespace(stop_all=AsyncMock())
|
|
with (
|
|
patch("headroom.proxy.server.get_quota_registry", return_value=quota_registry),
|
|
patch("headroom.models.ml_models.MLModelRegistry.unload_prefix") as unload_prefix,
|
|
):
|
|
asyncio.run(proxy.shutdown())
|
|
|
|
assert unload_prefix.call_args_list == [
|
|
call("technique_router:"),
|
|
call("siglip:"),
|
|
]
|
|
quota_registry.stop_all.assert_awaited_once()
|
|
|
|
|
|
def test_openai_chat_pipeline_events_cover_proxy_lifecycle(monkeypatch) -> None:
|
|
recorder = _RecordingExtension()
|
|
config = ProxyConfig(
|
|
optimize=True,
|
|
image_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,
|
|
pipeline_extensions=[recorder],
|
|
discover_pipeline_extensions=False,
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as client:
|
|
proxy = client.app.state.proxy
|
|
proxy.openai_pipeline = SimpleNamespace(
|
|
apply=lambda messages, model, **kwargs: SimpleNamespace(
|
|
messages=[
|
|
{"role": "system", "content": "memory"},
|
|
{"role": "user", "content": "hello"},
|
|
],
|
|
transforms_applied=["router:text:kompress"],
|
|
tokens_before=10,
|
|
tokens_after=6,
|
|
)
|
|
)
|
|
proxy.memory_handler = SimpleNamespace(
|
|
config=SimpleNamespace(inject_context=True, inject_tools=False),
|
|
search_and_format_context=AsyncMock(return_value="memory"),
|
|
has_memory_tool_calls=lambda response, provider: False,
|
|
)
|
|
|
|
monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _DummyTokenizer())
|
|
|
|
async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001
|
|
return httpx.Response(
|
|
200,
|
|
json={
|
|
"id": "chatcmpl_1",
|
|
"object": "chat.completion",
|
|
"choices": [{"message": {"role": "assistant", "content": "ok"}}],
|
|
"usage": {"prompt_tokens": 10, "completion_tokens": 3, "total_tokens": 13},
|
|
},
|
|
)
|
|
|
|
proxy._retry_request = _fake_retry
|
|
|
|
response = client.post(
|
|
"/v1/chat/completions",
|
|
headers={"Authorization": "Bearer sk-test", "x-headroom-user-id": "user-1"},
|
|
json={
|
|
"model": "gpt-5.4",
|
|
"messages": [{"role": "user", "content": "hello"}],
|
|
"tools": [{"type": "function", "function": {"name": "tool_a"}}],
|
|
},
|
|
)
|
|
|
|
assert response.status_code == 200
|
|
_assert_stage_order(recorder.stages)
|
|
_assert_compressed_event_carries_originals(recorder.events)
|
|
|
|
|
|
def test_anthropic_messages_pipeline_events_cover_proxy_lifecycle(monkeypatch) -> None:
|
|
recorder = _RecordingExtension()
|
|
config = ProxyConfig(
|
|
optimize=True,
|
|
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,
|
|
pipeline_extensions=[recorder],
|
|
discover_pipeline_extensions=False,
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as client:
|
|
proxy = client.app.state.proxy
|
|
proxy.anthropic_pipeline = SimpleNamespace(
|
|
apply=lambda messages, model, **kwargs: SimpleNamespace(
|
|
messages=[
|
|
{"role": "system", "content": "memory"},
|
|
{"role": "user", "content": "hello"},
|
|
],
|
|
transforms_applied=["router:text:kompress"],
|
|
tokens_before=10,
|
|
tokens_after=6,
|
|
)
|
|
)
|
|
proxy.memory_handler = SimpleNamespace(
|
|
config=SimpleNamespace(inject_context=True, inject_tools=False),
|
|
search_and_format_context=AsyncMock(return_value="memory"),
|
|
has_memory_tool_calls=lambda response, provider: False,
|
|
)
|
|
|
|
monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _DummyTokenizer())
|
|
|
|
async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001
|
|
return httpx.Response(
|
|
200,
|
|
json={
|
|
"id": "msg_1",
|
|
"type": "message",
|
|
"role": "assistant",
|
|
"content": [{"type": "text", "text": "ok"}],
|
|
"usage": {
|
|
"input_tokens": 10,
|
|
"output_tokens": 3,
|
|
"cache_read_input_tokens": 0,
|
|
"cache_creation_input_tokens": 0,
|
|
},
|
|
},
|
|
)
|
|
|
|
proxy._retry_request = _fake_retry
|
|
|
|
response = client.post(
|
|
"/v1/messages",
|
|
headers={
|
|
"x-api-key": "test-key",
|
|
"anthropic-version": "2023-06-01",
|
|
"x-headroom-user-id": "user-1",
|
|
},
|
|
json={
|
|
"model": "claude-sonnet-4-6",
|
|
"max_tokens": 128,
|
|
"messages": [{"role": "user", "content": "hello"}],
|
|
"tools": [
|
|
{"name": "tool_a", "description": "a", "input_schema": {"type": "object"}}
|
|
],
|
|
},
|
|
)
|
|
|
|
assert response.status_code == 200
|
|
_assert_stage_order(recorder.stages)
|
|
_assert_compressed_event_carries_originals(recorder.events)
|