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
fix(proxy,dashboard): correct savings reporting for backend-routed traffic and drop broken Compression Quality widget
Tejas Chopra6643266ec02a
diff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.htmlindex 97263980e..18e0346d5 100644--- a/headroom/dashboard/templates/dashboard.html+++ b/headroom/dashboard/templates/dashboard.html@@ -99,8 +99,8 @@<main class="p-6 max-w-7xl mx-auto"><template x-if="viewMode === 'session'"><div>- <!-- Hero Metrics (reordered: Savings $ -> Compression % -> Quality Confidence -> Overhead) -->- <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">+ <!-- Hero Metrics: Savings $ -> Compression % -> Overhead -->+ <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6"><!-- Savings ($) - proxy compression only, priced at model list rate --><div class="bg-surface rounded-lg p-4 border border-border"><div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Proxy $ Saved</div>@@ -120,12 +120,13 @@<div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Token Savings</div><div class="flex items-baseline gap-2"><span class="text-3xl font-light tabular-nums text-accent" x-text="formatNumber(stats.tokens?.saved || 0)"></span>- <!-- Active compression ratio: savings as fraction of what we *attempted*- to compress (extracted units + tool schema). Excludes frozen-prefix- bytes (user messages, system prompt, prior turns) we never touch for- prefix-cache safety. The whole-request ratio is stored as- `savings_percent` and shown as a small footnote for transparency. -->- <span class="text-sm text-accent" x-text="(stats.tokens?.active_savings_percent || 0).toFixed(1) + '%'" title="Of compressible tokens attempted"></span>+ <!-- Active compression ratio: savings as a fraction of tokens we+ *attempted* to compress (extracted units + tool schema). When+ the attempted denominator is missing (backend-routed paths+ that don't yet wire per-message live-zone tracking), fall back+ to the whole-request ratio so the headline doesn't collapse to+ 0% while compression is happening (issue #455). -->+ <span class="text-sm text-accent" x-text="headlineSavingsPercent.toFixed(1) + '%'" :title="headlineSavingsTitle"></span></div><div class="mt-1 text-xs text-gray-500 leading-relaxed"><span x-text="'Proxy ' + formatNumber(stats.tokens?.proxy_compression_saved || 0) + ' (' + proxyShareOfTotal.toFixed(1) + '%)'"></span>@@ -149,16 +150,6 @@</div></div>- <!-- Quality Confidence -->- <div class="bg-surface rounded-lg p-4 border border-border">- <div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Compression Quality</div>- <div class="flex items-baseline gap-2">- <span class="w-3 h-3 rounded-full mt-1" :class="confidenceColor"></span>- <span class="text-3xl font-light tabular-nums" :class="confidenceTextColor" x-text="confidenceLabel"></span>- </div>- <div class="mt-2 text-xs text-gray-500" x-text="confidenceDetail"></div>- </div>-<!-- Headroom Overhead --><div class="bg-surface rounded-lg p-4 border border-border"><div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Overhead</div>@@ -844,14 +835,13 @@<th class="px-4 py-3 font-medium text-right">Input</th><th class="px-4 py-3 font-medium text-right">Output</th><th class="px-4 py-3 font-medium text-right">Saved</th>- <th class="px-4 py-3 font-medium text-right">Quality</th><th class="px-4 py-3 font-medium text-right">Latency</th></tr></thead><tbody class="divide-y divide-border"><template x-for="req in (stats.recent_requests || [])" :key="req.request_id"><tr>- <td colspan="8" class="p-0">+ <td colspan="7" class="p-0"><div class="cursor-pointer" @click="toggleExpanded(req.request_id)"><div class="flex hover:bg-border/30 transition-colors"><div class="px-4 py-3 w-6 text-gray-500">@@ -866,9 +856,6 @@<div class="px-4 py-3 text-right flex-1"><span class="text-accent font-mono" x-text="req.savings_percent.toFixed(0) + '%'"></span></div>- <div class="px-4 py-3 text-right flex-1">- <span class="w-2 h-2 rounded-full inline-block" :class="getRequestConfidenceColor(req)"></span>- </div><div class="px-4 py-3 text-right font-mono text-gray-400 flex-1" x-text="(req.total_latency_ms || 0).toFixed(0) + 'ms'"></div></div></div>@@ -1792,52 +1779,28 @@return (this.stats.tokens?.rtk_saved || 0) / total * 100;},- // --- Compression Confidence ----- get confidenceLevel() {- const saved = this.stats.tokens?.proxy_compression_saved || 0;- if (saved === 0) return 'none';- const signals = this.stats.waste_signals || {};- const totalWaste = Object.values(signals).reduce((a, b) => a + b, 0);- if (totalWaste === 0) return 'unknown';- const wasteRatio = totalWaste / saved;- if (wasteRatio >= 0.7) return 'high';- if (wasteRatio >= 0.3) return 'medium';- return 'low';- },-- get confidenceColor() {- const c = { high: 'bg-emerald-400', medium: 'bg-yellow-400', low: 'bg-red-400', none: 'bg-gray-500', unknown: 'bg-gray-500' };- return c[this.confidenceLevel];- },-- get confidenceTextColor() {- const c = { high: 'text-emerald-400', medium: 'text-yellow-400', low: 'text-red-400', none: 'text-gray-500', unknown: 'text-gray-500' };- return c[this.confidenceLevel];- },-- get confidenceLabel() {- const l = { high: 'High', medium: 'Medium', low: 'Low', none: '-', unknown: '-' };- return l[this.confidenceLevel];- },-- get confidenceDetail() {- const saved = this.stats.tokens?.proxy_compression_saved || 0;- if (saved === 0) return 'No compression yet';- const signals = this.stats.waste_signals || {};- const totalWaste = Object.values(signals).reduce((a, b) => a + b, 0);- if (totalWaste === 0) return 'No waste signals detected';- const pct = Math.round((totalWaste / saved) * 100);- return pct + '% of removed tokens were identified waste';- },-- getRequestConfidenceColor(req) {- if (!req.waste_signals || req.tokens_saved === 0) return 'bg-gray-500';- const totalWaste = Object.values(req.waste_signals).reduce((a, b) => a + b, 0);- const ratio = totalWaste / req.tokens_saved;- if (ratio >= 0.7) return 'bg-emerald-400';- if (ratio >= 0.3) return 'bg-yellow-400';- return 'bg-red-400';+ // --- Headline savings percent ---+ //+ // Active ratio (saved / attempted) is the right metric when we have+ // a working denominator. Some backend-routed paths don't yet+ // populate `proxy_attempted_tokens` consistently — in that case+ // the active number reads 0% even when compression is happening,+ // so fall back to the whole-request ratio (`proxy_savings_percent`)+ // instead of showing a misleading zero. Issue #455.+ get headlineSavingsPercent() {+ const attempted = this.stats.tokens?.proxy_attempted_tokens || 0;+ const active = this.stats.tokens?.active_savings_percent || 0;+ if (attempted > 0 && active > 0) return active;+ return this.stats.tokens?.proxy_savings_percent || 0;+ },++ get headlineSavingsTitle() {+ const attempted = this.stats.tokens?.proxy_attempted_tokens || 0;+ const active = this.stats.tokens?.active_savings_percent || 0;+ if (attempted > 0 && active > 0) {+ return 'Of compressible tokens attempted';+ }+ return 'Of whole pre-compression request (attempted-tokens metric unavailable)';},// --- Expandable Rows ---diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex 0b875d923..0f2146b4b 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -703,6 +703,14 @@ class StreamingMixin:)if getattr(self, "metrics", None) is not None:+ # Active-compression denominator. No frozen_message_count is+ # propagated to the streaming finalizer yet, so we fall+ # back to the pre-comp request size (effective_optimized ++ # tokens_saved). Per-message live-zone tracking is a+ # follow-up; without this fallback the dashboard headline+ # collapses to 0% for streaming traffic even though+ # compression is happening (issue #455).+ attempted_input_tokens = effective_optimized_tokens + tokens_savedawait self.metrics.record_request(provider=provider,model=model,@@ -718,6 +726,7 @@ class StreamingMixin:cache_write_5m_tokens=cache_write_5m_tokens,cache_write_1h_tokens=cache_write_1h_tokens,uncached_input_tokens=uncached_input_tokens,+ attempted_input_tokens=attempted_input_tokens,)# Log the request to the in-memory request logger so it shows up in@@ -1346,6 +1355,11 @@ class StreamingMixin:_backend_name = (self.anthropic_backend.name if self.anthropic_backend else "anthropic")+ # Active-compression denominator: pre-comp request size.+ # Bedrock streaming doesn't propagate frozen_message_count+ # here either; without this, attempted_input_tokens_total+ # stays 0 and the dashboard headline reads 0% (#455).+ attempted_input_tokens = optimized_tokens + tokens_savedawait self.metrics.record_request(provider=_backend_name,model=model,@@ -1357,6 +1371,7 @@ class StreamingMixin:overhead_ms=optimization_latency,ttfb_ms=stream_state["ttfb_ms"] or 0,pipeline_timing=pipeline_timing,+ attempted_input_tokens=attempted_input_tokens,)if self.cost_tracker:@@ -1459,6 +1474,14 @@ class StreamingMixin:yield b"data: [DONE]\n\n"finally:total_latency = (time.time() - start_time) * 1000+ # Active-compression denominator for backend-routed+ # streaming. No per-message live-zone tracking is wired+ # for this path yet (see the non-streaming sibling in+ # openai.py for the same caveat), so use the full pre-+ # comp request size. This keeps active_savings_percent+ # in sync with proxy_savings_percent for this provider+ # instead of collapsing the dashboard headline to 0%.+ attempted_input_tokens = optimized_tokens + tokens_savedawait self.metrics.record_request(provider=self.anthropic_backend.name,model=model,@@ -1470,6 +1493,7 @@ class StreamingMixin:overhead_ms=optimization_latency,pipeline_timing=pipeline_timing,waste_signals=waste_signals,+ attempted_input_tokens=attempted_input_tokens,)# Mirror the Anthropic-stream path: log to RequestLogger sodiff --git a/headroom/proxy/models.py b/headroom/proxy/models.pyindex 6289808a6..7eb1c1d39 100644--- a/headroom/proxy/models.py+++ b/headroom/proxy/models.py@@ -136,6 +136,14 @@ class ProxyConfig:# Per-tool compression profilestool_profiles: dict[str, Any] | None = None+ # Opt in to compressing `user` role messages. Off by default because user+ # content is typically the subject of the request and is part of the+ # prefix-cache zone. Enable for OpenAI/Azure chat workloads where the bulk+ # of input lives in user messages (pasted code/text, RAG context) and the+ # router would otherwise have nothing eligible to compress.+ # CLI: --compress-user-messages; env: HEADROOM_COMPRESS_USER_MESSAGES=1.+ compress_user_messages: bool = False+# Read lifecycle managementread_lifecycle: bool = Truediff --git a/headroom/proxy/prometheus_metrics.py b/headroom/proxy/prometheus_metrics.pyindex 81656d15a..4c5aee0d1 100644--- a/headroom/proxy/prometheus_metrics.py+++ b/headroom/proxy/prometheus_metrics.py@@ -150,6 +150,16 @@ class PrometheusMetrics:# Aggregate waste signalsself.waste_signals_total: dict[str, int] = defaultdict(int)+ # Cumulative ContentRouter protection counts. Each routing pass+ # categorises every message — `user_msg`, `system_msg`,+ # `recent_code`, `excluded_tool`, `analysis_ctx`, `small`,+ # `ratio_too_high`, `already_compressed`, `non_string`,+ # `content_blocks`. Surfacing these in `/stats` gives operators a+ # way to diagnose "why is my compression rate low?" — e.g. a high+ # `user_msg` count on OpenAI/Azure traffic explains why most+ # input was protected and never reached the compressor (#454).+ self.router_route_counts: dict[str, int] = defaultdict(int)+# Provider-specific prefix cache tracking# Each provider has different cache economics:# Anthropic: cache_read=0.1x, cache_write=1.25x, explicit breakpoints@@ -360,6 +370,19 @@ class PrometheusMetrics:if saved > 0:self.tokens_saved_by_strategy[strategy] += saved+ def record_router_route_counts(self, counts: dict[str, int]) -> None:+ """Accumulate ContentRouter routing-category counts for a single+ pass. The router emits a dict like ``{"user_msg": 12,+ "recent_code": 4, ...}`` summarising how it categorised each+ message in that request. Adding these into a long-running+ counter gives `/stats` a session-level breakdown so operators+ can see, e.g., that 80% of messages were protected as+ `user_msg` and only 5% reached the compressor (#454).+ """+ for category, count in counts.items():+ if count > 0:+ self.router_route_counts[category] += int(count)+def record_inbound_request(self, *, method: str, path: str) -> None:self.inbound_requests_total += 1self.inbound_requests_active += 1diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 2ec8f2723..cb0dbeaaa 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -355,6 +355,12 @@ class HeadroomProxy(# Token mode: allow compression of older excluded-tool results.if is_token_mode(config.mode):router_config.protect_recent_reads_fraction = 0.3+ # `--compress-user-messages` flips the router's default skip rule.+ # Off by default for prefix-cache safety; enabled for workloads where+ # user-message content dominates input (OpenAI/Azure chat with pasted+ # code/RAG context — see issue #454).+ if config.compress_user_messages:+ router_config.skip_user_messages = Falsetransforms = [CacheAligner(CacheAlignerConfig(enabled=False)),ContentRouter(router_config, observer=self.metrics),@@ -1986,6 +1992,14 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:"compressions_by_strategy": dict(m.compressions_by_strategy),"tokens_saved_by_strategy": dict(m.tokens_saved_by_strategy),"waste_signals": dict(m.waste_signals_total) if m.waste_signals_total else {},+ # ContentRouter protection categories aggregated across the+ # session. Lets operators see, e.g., that 80% of messages+ # were `user_msg` (protected) and only 5% reached the+ # compressor — explains why compression rate is low and+ # whether `--compress-user-messages` would help (#454).+ "router": {+ "route_counts": dict(m.router_route_counts) if m.router_route_counts else {},+ },"savings_history": m.savings_history[-100:], # Last 100 data points"display_session": display_session,"persistent_savings": persistent_savings,@@ -3028,6 +3042,18 @@ if __name__ == "__main__":help="Per-tool compression profile: ToolName:level (e.g., Grep:conservative, Bash:moderate, WebFetch:aggressive). ""Can be specified multiple times. Also settable via HEADROOM_TOOL_PROFILES env var.",)+ parser.add_argument(+ "--compress-user-messages",+ action="store_true",+ help=(+ "Opt in to compressing `user` role messages. Default is off because "+ "user content is typically the subject of the request and is part of "+ "the prefix-cache zone. Enable this for OpenAI/Azure chat workloads "+ "where the bulk of input lives in user messages (pasted content, "+ "RAG context, etc.) and you want the router to consider it eligible. "+ "Also settable via HEADROOM_COMPRESS_USER_MESSAGES=1."+ ),+ )# Cachingparser.add_argument("--no-cache", action="store_true", help="Disable caching")@@ -3116,6 +3142,8 @@ if __name__ == "__main__":http2=not args.no_http2 and _get_env_bool("HEADROOM_HTTP2", True),tool_profiles=tool_profiles if tool_profiles else None,mode=normalize_proxy_mode(_get_env_str("HEADROOM_MODE", PROXY_MODE_TOKEN)),+ compress_user_messages=args.compress_user_messages+ or _get_env_bool("HEADROOM_COMPRESS_USER_MESSAGES", False),)# Get worker and concurrency settingsdiff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.pyindex f45273a93..06539b52a 100644--- a/headroom/transforms/content_router.py+++ b/headroom/transforms/content_router.py@@ -2168,6 +2168,19 @@ class ContentRouter(Transform):", ".join(parts),)+ # Forward route_counts to the observer so `/stats` can surface a+ # session-level protection breakdown (issue #454). The observer+ # may not implement this method on older versions; ignore+ # AttributeError so a non-conforming observer doesn't poison+ # routing.+ if self._observer is not None and route_counts:+ try:+ self._observer.record_router_route_counts(route_counts)+ except AttributeError:+ pass+ except Exception as e: # pragma: no cover - defensive+ logger.debug("Router observer raised (non-fatal): %s", e)+all_transforms = lifecycle_transforms + transforms_appliedreturn TransformResult(messages=transformed_messages,