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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
feat(proxy): add client (harness) identification — per-harness analytics across every handler
chopratejas96a674f1b9c7
diff --git a/headroom/proxy/auth_mode.py b/headroom/proxy/auth_mode.pyindex baff7bdda..794a24b40 100644--- a/headroom/proxy/auth_mode.py+++ b/headroom/proxy/auth_mode.py@@ -180,4 +180,76 @@ def classify_auth_mode(headers: Mapping[str, Any] | Any) -> AuthMode:return AuthMode.PAYG-__all__ = ["AuthMode", "SUBSCRIPTION_UA_PREFIXES", "classify_auth_mode"]+# Client (harness) identification — maps a User-Agent substring to a+# short normalized client name. The dashboard / `headroom perf` use+# this to slice traffic by harness ("aider is 30% of cache writes",+# "codex p99 latency vs claude-code", etc).+#+# Adding a new client: one line. Same surface as+# :data:`SUBSCRIPTION_UA_PREFIXES`. The classifier is intentionally+# substring-based (not regex) so a tuple of literals stays the+# extension point.+CLIENT_UA_MAP: tuple[tuple[str, str], ...] = (+ # Anthropic ecosystem+ ("claude-code/", "claude-code"),+ ("claude-cli/", "claude-code"),+ ("claude-vscode/", "claude-vscode"),+ ("anthropic-cli/", "anthropic-cli"),+ # OpenAI ecosystem+ ("codex-cli/", "codex"),+ # Editors / IDEs+ ("cursor/", "cursor"),+ ("zed/", "zed"),+ # Other AI coding harnesses+ ("aider/", "aider"),+ ("droid/", "droid"),+ ("opencode/", "opencode"),+ ("github-copilot/", "copilot"),+ # Google's experimental harness+ ("antigravity/", "antigravity"),+)+++def classify_client(headers: Mapping[str, Any] | Any) -> str | None:+ """Identify the client harness (Codex / Claude Code / aider / etc).++ Decision order:++ 1. **``X-Client`` header** (explicit override) — clients that+ know they're talking to Headroom can self-identify with a+ short name. Trimmed, lowercased. Wins over UA matching.+ 2. **User-Agent substring match** against :data:`CLIENT_UA_MAP`+ — covers the unmodified-client case. Substring, not prefix,+ because some clients prepend a corporate-wrapper UA before+ their own.+ 3. **None** when neither produces a hit. ``None`` is the loud+ "unknown harness" signal; downstream consumers can group+ these as "unidentified" rather than silently bucketing them+ into a default.++ Returns ``str | None`` rather than a string default so future+ code can distinguish "no client identified" from "client is the+ empty string". The :class:`RequestOutcome` field has the same+ type for the same reason.+ """+ # 1. Explicit override+ explicit = _header_get(headers, "x-client").strip().lower()+ if explicit:+ return explicit+ # 2. User-Agent substring match+ ua_lower = _header_get(headers, "user-agent").lower()+ if not ua_lower:+ return None+ for needle, name in CLIENT_UA_MAP:+ if needle in ua_lower:+ return name+ return None+++__all__ = [+ "AuthMode",+ "CLIENT_UA_MAP",+ "SUBSCRIPTION_UA_PREFIXES",+ "classify_auth_mode",+ "classify_client",+]diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 8df17f320..8f5015fe7 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -24,7 +24,7 @@ if TYPE_CHECKING:import httpxfrom headroom.pipeline import PipelineStage, summarize_routing_markers-from headroom.proxy.auth_mode import classify_auth_mode+from headroom.proxy.auth_mode import classify_auth_mode, classify_clientfrom headroom.proxy.outcome import RequestOutcomelogger = logging.getLogger("headroom.proxy")@@ -589,6 +589,10 @@ class AnthropicHandlerMixin:# body is undecipherable → 502.headers.pop("accept-encoding", None)tags = self._extract_tags(headers)+ # 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)# 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@@ -720,6 +724,7 @@ class AnthropicHandlerMixin:total_latency_ms=optimization_latency,overhead_ms=optimization_latency,num_messages=len(messages),+ client=client,))@@ -1645,6 +1650,7 @@ class AnthropicHandlerMixin:transforms_applied=tuple(transforms_applied),num_messages=len(body.get("messages", [])),tags=tags,+ client=client,turn_id=compute_turn_id(model, body.get("system"), body.get("messages")),@@ -2157,6 +2163,7 @@ class AnthropicHandlerMixin:transforms_applied=tuple(transforms_applied),num_messages=len(messages),tags=tags,+ client=client,turn_id=compute_turn_id(model, body.get("system"), body.get("messages")),@@ -2330,6 +2337,7 @@ class AnthropicHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)headers.pop("content-length", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -2497,6 +2505,7 @@ class AnthropicHandlerMixin:overhead_ms=optimization_latency,pipeline_timing=pipeline_timing,num_messages=len(compressed_requests),+ client=client,))@@ -2578,6 +2587,7 @@ class AnthropicHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -2613,6 +2623,7 @@ class AnthropicHandlerMixin:tokens_saved=0,attempted_input_tokens=0,total_latency_ms=latency_ms,+ client=client,))@@ -2697,6 +2708,7 @@ class AnthropicHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -2788,6 +2800,7 @@ class AnthropicHandlerMixin:tokens_saved=0,attempted_input_tokens=0,total_latency_ms=latency_ms,+ client=client,))diff --git a/headroom/proxy/handlers/batch.py b/headroom/proxy/handlers/batch.pyindex 97b0678df..4009783f3 100644--- a/headroom/proxy/handlers/batch.py+++ b/headroom/proxy/handlers/batch.py@@ -14,6 +14,7 @@ if TYPE_CHECKING:from fastapi import Requestfrom fastapi.responses import Response+from headroom.proxy.auth_mode import classify_clientfrom headroom.proxy.outcome import RequestOutcomelogger = logging.getLogger("headroom.proxy")@@ -101,6 +102,7 @@ class BatchHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)headers.pop("content-length", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -280,6 +282,7 @@ class BatchHandlerMixin:total_latency_ms=optimization_latency,overhead_ms=optimization_latency,pipeline_timing=pipeline_timing,+ client=client,))@@ -349,6 +352,7 @@ class BatchHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)headers.pop("content-length", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -428,6 +432,7 @@ class BatchHandlerMixin:tokens_saved=0,attempted_input_tokens=0,total_latency_ms=latency_ms,+ client=client,))@@ -465,6 +470,7 @@ class BatchHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -509,6 +515,7 @@ class BatchHandlerMixin:tokens_saved=0,attempted_input_tokens=0,total_latency_ms=latency_ms,+ client=client,))@@ -604,6 +611,7 @@ class BatchHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -725,6 +733,7 @@ class BatchHandlerMixin:tokens_saved=0,attempted_input_tokens=0,total_latency_ms=latency_ms,+ client=client,))@@ -801,6 +810,7 @@ class BatchHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)headers.pop("content-length", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -944,6 +954,7 @@ class BatchHandlerMixin:attempted_input_tokens=stats["total_compressed_tokens"]+ stats["total_tokens_saved"],total_latency_ms=total_latency,+ client=client,))diff --git a/headroom/proxy/handlers/gemini.py b/headroom/proxy/handlers/gemini.pyindex b02ec82a6..26372dfcf 100644--- a/headroom/proxy/handlers/gemini.py+++ b/headroom/proxy/handlers/gemini.py@@ -15,6 +15,7 @@ if TYPE_CHECKING:from fastapi import Requestfrom fastapi.responses import JSONResponse, Response, StreamingResponse+from headroom.proxy.auth_mode import classify_clientfrom headroom.proxy.outcome import RequestOutcomelogger = logging.getLogger("headroom.proxy")@@ -193,6 +194,7 @@ class GeminiHandlerMixin:headers.pop("host", None)headers.pop("content-length", None)tags = self._extract_tags(headers)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* from upstream-bound# headers AFTER `_extract_tags` reads them. Memory user-id reads# `request.headers` below.@@ -499,6 +501,7 @@ class GeminiHandlerMixin:transforms_applied=tuple(transforms_applied),num_messages=len(body.get("contents", [])),tags=tags or {},+ client=client,)await self._record_request_outcome(outcome)@@ -591,6 +594,8 @@ class GeminiHandlerMixin:headers.pop("content-length", None)headers.pop("accept-encoding", None)tags = self._extract_tags(headers)+ # Note: streaming handlers delegate to _stream_response, which+ # does its own classify_client. No need to compute here.is_antigravity = self._is_cloudcode_antigravity_request(body, headers)# PR-A5 (P5-49): strip internal x-headroom-* from upstream-bound headers# AFTER `_extract_tags` and `is_cloudcode_antigravity` reads.@@ -718,6 +723,8 @@ class GeminiHandlerMixin:headers.pop("host", None)headers.pop("content-length", None)tags = self._extract_tags(headers)+ # Streaming variant — delegates to _stream_response which+ # classifies the client itself from headers.# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -802,6 +809,7 @@ class GeminiHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)headers.pop("content-length", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -923,6 +931,7 @@ class GeminiHandlerMixin:attempted_input_tokens=compressed_tokens + tokens_saved,total_latency_ms=total_latency,transforms_applied=tuple(transforms_applied),+ client=client,))diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex 0eed1a9b8..f65c0cb07 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -38,7 +38,7 @@ import httpxfrom headroom.copilot_auth import apply_copilot_api_auth, build_copilot_upstream_urlfrom headroom.pipeline import PipelineStage, summarize_routing_markers-from headroom.proxy.auth_mode import classify_auth_mode+from headroom.proxy.auth_mode import classify_auth_mode, classify_clientfrom headroom.proxy.cost import _summarize_transformsfrom headroom.proxy.outcome import RequestOutcome@@ -1226,6 +1226,7 @@ class OpenAIHandlerMixin:# if httpx lacks brotli support the response body is undecipherable → 502.headers.pop("accept-encoding", None)tags = self._extract_tags(headers)+ 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@@ -1311,6 +1312,7 @@ class OpenAIHandlerMixin:from_response_cache=True,total_latency_ms=_cache_hit_latency,num_messages=len(messages),+ client=client,))@@ -1826,6 +1828,7 @@ class OpenAIHandlerMixin:request_messages=body.get("messages")if getattr(self.config, "log_full_messages", False)else None,+ client=client,))@@ -2142,6 +2145,7 @@ class OpenAIHandlerMixin:request_messages=body.get("messages")if getattr(self.config, "log_full_messages", False)else None,+ client=client,))@@ -2299,6 +2303,7 @@ class OpenAIHandlerMixin:# if httpx lacks brotli support the response body is undecipherable → 502.headers.pop("accept-encoding", None)tags = self._extract_tags(headers)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* from upstream-bound# headers AFTER `_extract_tags` reads them. Memory user-id reads# `request.headers` below.@@ -2847,6 +2852,7 @@ class OpenAIHandlerMixin:request_messages=messagesif getattr(self.config, "log_full_messages", False)else None,+ client=client,))@@ -2922,6 +2928,9 @@ class OpenAIHandlerMixin:# Forward client headers to upstream, adding required OpenAI-Beta headerws_headers = dict(websocket.headers)+ # Identify the WS harness before downstream auth/header rewrites.+ # Captured in closure so per-turn RequestOutcome can stamp it.+ client = classify_client(ws_headers)_ws_url_obj = getattr(websocket, "url", None)_ws_url = str(_ws_url_obj) if _ws_url_obj is not None else ""_ws_path = getattr(_ws_url_obj, "path", "") if _ws_url_obj is not None else ""@@ -4247,6 +4256,7 @@ class OpenAIHandlerMixin:)if isinstance(body, dict)else 0,+ client=client,))@@ -4817,6 +4827,7 @@ class OpenAIHandlerMixin:pipeline_timing=final_pipeline_timing,transforms_applied=tuple(transforms_applied),tags=ws_session_tags,+ client=client,))ws_recorded_overhead_ms_total = _current_ws_overhead_ms()@@ -5309,6 +5320,7 @@ class OpenAIHandlerMixin:headers = dict(request.headers.items())headers.pop("host", None)headers.pop("accept-encoding", None)+ client = classify_client(headers)# PR-A5 (P5-49): strip internal x-headroom-* before forwarding upstream.from headroom.proxy.helpers import _strip_internal_headers, log_outbound_headers@@ -5374,6 +5386,7 @@ class OpenAIHandlerMixin:tokens_saved=0,attempted_input_tokens=0,total_latency_ms=latency_ms,+ client=client,))diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex 72e274096..b79af5d85 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -12,6 +12,7 @@ import loggingimport timefrom typing import TYPE_CHECKING, Any+from headroom.proxy.auth_mode import classify_clientfrom headroom.proxy.helpers import compute_turn_id, jitter_delay_msif TYPE_CHECKING:@@ -583,6 +584,7 @@ class StreamingMixin:original_messages: list[dict] | None = None,full_sse_data: str = "",parsed_response: dict[str, Any] | None = None,+ client: str | None = None,) -> None:from headroom.proxy.outcome import RequestOutcome@@ -704,6 +706,7 @@ class StreamingMixin:transforms_applied=tuple(transforms_applied),num_messages=len(body.get("messages", [])),tags=tags or {},+ client=client,request_messages=body.get("messages")if getattr(self.config, "log_full_messages", False)else None,@@ -749,6 +752,10 @@ class StreamingMixin:from headroom.proxy.helpers import MAX_SSE_BUFFER_SIZE+ # Identify the harness (codex / claude-code / aider / cursor /+ # ...) from the *client's* User-Agent before copilot-auth+ # potentially rewrites headers for upstream.+ client = classify_client(headers)headers = await apply_copilot_api_auth(headers, url=url)start_time = time.time()@@ -962,6 +969,7 @@ class StreamingMixin:pipeline_timing=pipeline_timing,prefix_tracker=prefix_tracker,original_messages=original_messages,+ client=client,)return Response(content=error_content,@@ -1218,6 +1226,7 @@ class StreamingMixin:original_messages=original_messages,full_sse_data=_final_full_sse_data,parsed_response=parsed_response,+ client=client,)return StreamingResponse(@@ -1249,6 +1258,8 @@ class StreamingMixin:from headroom.proxy.outcome import RequestOutcome+ client = classify_client(headers)+start_time = time.time()# Mutable state for the generator. Cache fields mirror the@@ -1343,6 +1354,7 @@ class StreamingMixin:transforms_applied=tuple(transforms_applied),num_messages=len(body.get("messages", [])),tags=tags or {},+ client=client,turn_id=compute_turn_id(model, body.get("system"), body.get("messages")),request_messages=body.get("messages")if getattr(self.config, "log_full_messages", False)@@ -1392,6 +1404,7 @@ class StreamingMixin:from headroom.proxy.outcome import RequestOutcomeassert self.anthropic_backend is not None+ client = classify_client(headers)async def generate():stream_state: dict[str, Any] = {@@ -1488,6 +1501,7 @@ class StreamingMixin:transforms_applied=tuple(transforms_applied),num_messages=len(body.get("messages", [])),tags=tags or {},+ client=client,request_messages=body.get("messages")if getattr(self.config, "log_full_messages", False)else None,diff --git a/headroom/proxy/outcome.py b/headroom/proxy/outcome.pyindex a501c4c00..104a92393 100644--- a/headroom/proxy/outcome.py+++ b/headroom/proxy/outcome.py@@ -111,12 +111,24 @@ class RequestOutcome:# request_messages: only populated when ``config.log_full_messages``# is enabled (off by default — message bodies are sensitive).# tags: client-provided routing/identification tags.+ # client: identified harness driving the request (codex /+ # claude-code / aider / cursor / opencode / zed / ...).+ # ``None`` when neither the ``X-Client`` header nor the+ # User-Agent matched a known harness. Populated by handlers+ # via :func:`headroom.proxy.auth_mode.classify_client`. The+ # funnel surfaces this in the PERF log (``client=X``) and+ # copies it into ``RequestLog.tags["client"]`` so dashboards+ # can slice by harness without a separate column. This is the+ # one-field-add that proves the refactor pays out: per-+ # harness visibility appears across EVERY handler with zero+ # new bookkeeping at the call sites.transforms_applied: tuple[str, ...] = ()waste_signals: dict[str, int] | None = Nonenum_messages: int = 0turn_id: str | None = Nonerequest_messages: list[dict[str, Any]] | None = Nonetags: dict[str, str] = field(default_factory=dict)+ client: str | None = None# ── Derived (computed once, no caching needed — properties are cheap) ─@@ -227,9 +239,16 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:uncached_tokens=outcome.uncached_input_tokens,)- # 3. Per-request log (optional).+ # 3. Per-request log (optional). The ``client`` outcome field is+ # copied into ``tags["client"]`` so the dashboard's existing+ # tag-based filtering surfaces per-harness slicing for free —+ # no new RequestLog column needed. The original ``outcome.tags``+ # dict is not mutated (frozen dataclass + defensive copy).request_logger = getattr(handler, "logger", None)if request_logger is not None:+ log_tags = dict(outcome.tags)+ if outcome.client:+ log_tags["client"] = outcome.clientrequest_logger.log(RequestLog(request_id=outcome.request_id,@@ -243,7 +262,7 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:savings_percent=outcome.savings_pct,optimization_latency_ms=outcome.overhead_ms,total_latency_ms=outcome.total_latency_ms,- tags=outcome.tags,+ tags=log_tags,cache_hit=outcome.cache_hit,transforms_applied=list(outcome.transforms_applied),waste_signals=outcome.waste_signals,@@ -252,7 +271,11 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:))- # 4. Structured PERF log line.+ # 4. Structured PERF log line. ``client=X`` is appended only when+ # a harness was identified — keeps the unidentified-traffic+ # line unchanged, and gives ``headroom perf --client X``+ # parsers a clean key to filter on.+ client_part = f" client={outcome.client}" if outcome.client else ""logger.info(f"[{outcome.request_id}] PERF "f"model={outcome.model} msgs={outcome.num_messages} "@@ -262,4 +285,5 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:f"cache_hit_pct={outcome.cache_hit_pct} "f"opt_ms={outcome.overhead_ms:.0f} "f"transforms={_summarize_transforms(list(outcome.transforms_applied))}"+ f"{client_part}")diff --git a/tests/test_request_outcome.py b/tests/test_request_outcome.pyindex 4a2f1d9b0..53e50e026 100644--- a/tests/test_request_outcome.py+++ b/tests/test_request_outcome.py@@ -104,6 +104,55 @@ def test_optional_fields_default_to_neutral_values() -> None:assert o.turn_id is Noneassert o.request_messages is Noneassert o.tags == {}+ assert o.client is None # unidentified harness+++def test_client_field_round_trips() -> None:+ """The ``client`` field is the proof point that the refactor pays+ out across harnesses — one field-add gives every dashboard a+ per-harness dimension for free.+ """+ o = _outcome(client="codex")+ assert o.client == "codex"+++# ── classify_client — the harness ID source ─────────────────────────+++def test_classify_client_recognises_known_harness_user_agents() -> None:+ from headroom.proxy.auth_mode import classify_client++ cases = [+ ({"User-Agent": "codex-cli/0.30.0 (osx)"}, "codex"),+ ({"User-Agent": "claude-code/1.4.2"}, "claude-code"),+ ({"User-Agent": "claude-cli/2.0"}, "claude-code"), # aliased+ ({"User-Agent": "cursor/0.42.1 (electron)"}, "cursor"),+ ({"User-Agent": "aider/0.50.0"}, "aider"),+ ({"User-Agent": "zed/0.143.0"}, "zed"),+ ({"User-Agent": "opencode/1.0"}, "opencode"),+ ({"User-Agent": "github-copilot/x.y.z"}, "copilot"),+ ]+ for headers, expected in cases:+ assert classify_client(headers) == expected, headers+++def test_classify_client_x_client_header_wins_over_user_agent() -> None:+ from headroom.proxy.auth_mode import classify_client++ # X-Client wins even when UA matches a different harness+ h = {"User-Agent": "codex-cli/0.30.0", "X-Client": "my-custom-harness"}+ assert classify_client(h) == "my-custom-harness"+++def test_classify_client_returns_none_for_unknown_traffic() -> None:+ """``None`` is the loud "unidentified" signal — downstream consumers+ can group these as "unknown" rather than silently bucketing into+ a default that would mislead dashboards."""+ from headroom.proxy.auth_mode import classify_client++ assert classify_client({"User-Agent": "Mozilla/5.0"}) is None+ assert classify_client({}) is None+ assert classify_client({"User-Agent": ""}) is None# ── Funnel contract (_record_request_outcome) ──────────────────────────@@ -303,3 +352,72 @@ async def test_funnel_emits_perf_log_with_canonical_shape(assert "cache_write=100" in lineassert "cache_hit_pct=67" in line # 200/(200+100) * 100 = 67assert "opt_ms=12" in line+++# ── Funnel: per-client analytics surface ─────────────────────────────+++async def test_funnel_appends_client_to_perf_log_when_set() -> None:+ """``headroom perf --client X`` filtering relies on the ``client=X``+ token at the end of the PERF line. Absent client means no token —+ the PERF line stays clean for unidentified traffic."""+ h = _FunnelHarness()+ target = logging.getLogger("headroom.proxy")+ captured: list[logging.LogRecord] = []++ class _H(logging.Handler):+ def emit(self, record: logging.LogRecord) -> None:+ captured.append(record)++ handler = _H(level=logging.INFO)+ target.addHandler(handler)+ prior_level = target.level+ target.setLevel(logging.INFO)+ try:+ await h._record_request_outcome(_outcome(client="codex"))+ finally:+ target.removeHandler(handler)+ target.setLevel(prior_level)++ perf_lines = [r.getMessage() for r in captured if " PERF " in r.getMessage()]+ assert len(perf_lines) == 1+ assert "client=codex" in perf_lines[0]+++async def test_funnel_omits_client_from_perf_log_when_unidentified() -> None:+ """When ``client`` is None the PERF line must NOT include a+ bogus ``client=`` token — that would mislead the parser into+ bucketing unidentified traffic as the empty string."""+ h = _FunnelHarness()+ target = logging.getLogger("headroom.proxy")+ captured: list[logging.LogRecord] = []++ class _H(logging.Handler):+ def emit(self, record: logging.LogRecord) -> None:+ captured.append(record)++ handler = _H(level=logging.INFO)+ target.addHandler(handler)+ prior_level = target.level+ target.setLevel(logging.INFO)+ try:+ await h._record_request_outcome(_outcome(client=None))+ finally:+ target.removeHandler(handler)+ target.setLevel(prior_level)++ perf_lines = [r.getMessage() for r in captured if " PERF " in r.getMessage()]+ assert len(perf_lines) == 1+ assert "client=" not in perf_lines[0]+++async def test_funnel_stamps_client_into_request_log_tags() -> None:+ """Dashboards already filter on RequestLog.tags. Copying ``client``+ into tags gives per-harness slicing for free with no new column."""+ h = _FunnelHarness()+ await h._record_request_outcome(_outcome(client="aider"))+ assert len(h.logger.logs) == 1+ assert h.logger.logs[0].tags.get("client") == "aider"