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: measure and surface token throughput (tokens/sec) through the proxy (#983)
Shlok Tiwari0d89c674cd35
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53d47484e..ad3a33dca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,11 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Features+* **proxy:** measure and surface rolling and current token throughput metrics (active/wall-clock input, compression, effective forward, and streamed generation) in `headroom perf` CLI and the dashboard ([#959](https://github.com/chopratejas/headroom/issues/959)).* **vibe:** add Mistral Vibe CLI support with `headroom wrap vibe`.* **proxy:** per-project savings breakdown on the dashboard for all wrapped agents — Claude Code, Codex, aider, Copilot, and Cursor ([#802](https://github.com/chopratejas/headroom/issues/802)). `headroom wrap claude`/`codex` tag requests with an `X-Headroom-Project` header (launch-directory name); `wrap aider`/`copilot`/`cursor` — whose clients cannot send custom headers — use a `/p/<name>` base-URL prefix the proxy strips. Savings are aggregated per project (persisted, schema v3 with transparent v2 migration), exposed as `savings.per_project` in `/stats` and `projects` in `/stats-history`, and shown in a Per-Project Savings dashboard table.--### Features-* **memory:** opt-in Apple-GPU (MPS) embedding offload via `HEADROOM_EMBEDDER_RUNTIME=pytorch_mps`. When set (and Apple MPS is available), the memory embedder runs on the torch sentence-transformers backend on the Apple GPU instead of the default ONNX CPU embedder, freeing the CPU under load. If MPS or the dependencies are unavailable, Headroom logs a warning and uses the existing default embedder selection path (ONNX when available, then the pre-existing local fallback). MPS encode calls are serialized internally (torch-MPS is not thread-safe). Adds the new `[pytorch-mps]` extra (`pip install 'headroom-ai[pytorch-mps]'`). Default behavior is unchanged.### Featuresdiff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.htmlindex 1167d1968..3d3021046 100644--- a/headroom/dashboard/templates/dashboard.html+++ b/headroom/dashboard/templates/dashboard.html@@ -269,6 +269,50 @@TTFB <span x-text="((stats.ttfb?.average_ms || 0) / 1000).toFixed(2)"></span>s avg</div></div>++ <!-- Token Throughput -->+ <div class="bg-surface rounded-lg p-4 border border-border flex flex-col justify-between">+ <div>+ <div class="text-xs text-gray-500 uppercase tracking-wide mb-1.5">Throughput</div>+ <div class="flex flex-col gap-1 text-[11px] text-gray-300">+ <div class="flex justify-between items-baseline border-b border-border/40 pb-0.5">+ <span class="text-gray-500">Input (wall / active p50)</span>+ <span class="font-mono text-accent">+ <span x-text="(stats.throughput?.rolling?.input_wall_clock || 0).toFixed(1)"></span> /+ <span x-text="(stats.throughput?.rolling?.input_active_p50 || 0).toFixed(1)"></span> tok/s+ </span>+ </div>+ <div class="flex justify-between items-baseline border-b border-border/40 pb-0.5" x-show="(stats.throughput?.rolling?.compression_p50 || 0) > 0">+ <span class="text-gray-500">Compression (p50 / p95)</span>+ <span class="font-mono text-emerald-400">+ <span x-text="(stats.throughput?.rolling?.compression_p50 || 0).toFixed(1)"></span> /+ <span x-text="(stats.throughput?.rolling?.compression_p95 || 0).toFixed(1)"></span> tok/s+ </span>+ </div>+ <div class="flex justify-between items-baseline border-b border-border/40 pb-0.5">+ <span class="text-gray-500">Forward (p50 / p95)</span>+ <span class="font-mono text-cyan-400">+ <span x-text="(stats.throughput?.rolling?.forward_p50 || 0).toFixed(1)"></span> /+ <span x-text="(stats.throughput?.rolling?.forward_p95 || 0).toFixed(1)"></span> tok/s+ </span>+ </div>+ <div class="flex justify-between items-baseline" x-show="(stats.throughput?.rolling?.generation_p50 || 0) > 0">+ <span class="text-gray-500">Generation (p50 / p95)</span>+ <span class="font-mono text-yellow-400">+ <span x-text="(stats.throughput?.rolling?.generation_p50 || 0).toFixed(1)"></span> /+ <span x-text="(stats.throughput?.rolling?.generation_p95 || 0).toFixed(1)"></span> tok/s+ </span>+ </div>+ </div>+ </div>+ <div class="mt-2 pt-1.5 border-t border-border/40 text-[10px] text-gray-500 flex justify-between items-center">+ <span>Current 5m (active p50):</span>+ <span class="font-mono text-gray-400">+ In: <span x-text="(stats.throughput?.current?.input_active_p50 || 0).toFixed(0)"></span> ·+ Fwd: <span x-text="(stats.throughput?.current?.forward_p50 || 0).toFixed(0)"></span> tok/s+ </span>+ </div>+ </div></div><!-- Agent Usage -->diff --git a/headroom/perf/analyzer.py b/headroom/perf/analyzer.pyindex 366033be7..388e3a189 100644--- a/headroom/perf/analyzer.py+++ b/headroom/perf/analyzer.py@@ -48,6 +48,11 @@ _TOIN_RE = re.compile(r"(?P<retrievals>\d+) retrievals, (?P<rate>[\d.]+)% retrieval rate")+# Matches structured stage timing logs: [hr_...] STAGE_TIMINGS {"event": "stage_timings", ...}+_STAGE_TIMINGS_RE = re.compile(+ r"^(?P<ts>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d+) .* \[(?P<rid>[^\]]+)\] STAGE_TIMINGS (?P<payload>.+)$"+)+# ---------------------------------------------------------------------------# Cache-aware pricing via LiteLLM@@ -145,6 +150,10 @@ class PerfRecord:cache_hit_pct: int = 0optimization_ms: float = 0transforms: list[str] = field(default_factory=list)+ total_ms: float = 0.0+ tokens_out: int = 0+ ttfb_ms: float = 0.0+ stages: dict[str, float] = field(default_factory=dict)@dataclass@@ -234,6 +243,7 @@ def parse_log_files(last_n_hours: float = 168.0) -> PerfReport:"""report = PerfReport()report.requested_hours = last_n_hours+ stages_by_rid: dict[str, dict[str, float]] = {}log_dir = _paths.log_dir() if os.environ.get("HEADROOM_WORKSPACE_DIR") else LOG_DIRif not log_dir.exists():@@ -270,6 +280,27 @@ def parse_log_files(last_n_hours: float = 168.0) -> PerfReport:report.total_lines_parsed += 1line = line.rstrip()+ # STAGE_TIMINGS lines+ m_stage = _STAGE_TIMINGS_RE.match(line)+ if m_stage:+ ts = m_stage.group("ts")+ if not _within_window(ts):+ report.records_filtered_out += 1+ continue+ _track_window(ts)+ rid = m_stage.group("rid")+ try:+ import json++ payload = json.loads(m_stage.group("payload"))+ stages = payload.get("stages", {})+ stages_by_rid[rid] = {+ k: float(v) for k, v in stages.items() if v is not None+ }+ except Exception:+ pass+ continue+# PERF lines (richest data)m = _PERF_RE.match(line)if m:@@ -310,6 +341,10 @@ def parse_log_files(last_n_hours: float = 168.0) -> PerfReport:cache_hit_pct=int(kv.get("cache_hit_pct", 0)),optimization_ms=float(kv.get("opt_ms", 0)),transforms=transforms,+ total_ms=float(kv.get("total_ms", 0)),+ tokens_out=int(kv.get("tok_out", 0)),+ ttfb_ms=float(kv.get("ttfb_ms", 0)),+ stages=stages_by_rid.get(m.group("rid"), {}),))continue@@ -512,6 +547,37 @@ def format_report(report: PerfReport) -> str:lines.append(f" >500ms: {len(slow)} requests")lines.append("")+ # Throughput+ tp = calculate_throughput(report)+ rolling = tp["rolling"]+ current = tp["current"]+ if rolling["input_wall_clock"] > 0 or rolling["input_active_p50"] > 0:+ lines.append("Throughput")+ lines.append("-" * 40)+ lines.append(+ f" Input (wall-clock): {rolling['input_wall_clock']:.1f} tok/s"+ f" (current: {current['input_wall_clock']:.1f} tok/s)"+ )+ lines.append(+ f" Input (active p50/95): {rolling['input_active_p50']:.1f} / {rolling['input_active_p95']:.1f} tok/s"+ f" (current: {current['input_active_p50']:.1f} / {current['input_active_p95']:.1f} tok/s)"+ )+ if rolling["compression_p50"] > 0:+ lines.append(+ f" Compression (p50/95): {rolling['compression_p50']:.1f} / {rolling['compression_p95']:.1f} tok/s"+ f" (current: {current['compression_p50']:.1f} / {current['compression_p95']:.1f} tok/s)"+ )+ lines.append(+ f" Forward (p50/95): {rolling['forward_p50']:.1f} / {rolling['forward_p95']:.1f} tok/s"+ f" (current: {current['forward_p50']:.1f} / {current['forward_p95']:.1f} tok/s)"+ )+ if rolling["generation_p50"] > 0:+ lines.append(+ f" Generation (p50/95): {rolling['generation_p50']:.1f} / {rolling['generation_p95']:.1f} tok/s"+ f" (current: {current['generation_p50']:.1f} / {current['generation_p95']:.1f} tok/s)"+ )+ lines.append("")+# Conversation size distributionmsg_counts = [r.num_messages for r in records if r.num_messages > 0]if msg_counts:@@ -632,6 +698,10 @@ PERF_RECORD_FIELDS = ["cache_hit_pct","optimization_ms","transforms",+ "total_ms",+ "tokens_out",+ "ttfb_ms",+ "stages",]@@ -640,6 +710,124 @@ def _pct(saved: int, before: int) -> float:return round(saved / before * 100, 1) if before > 0 else 0.0+def _percentile(data: list[float], pct: float) -> float:+ if not data:+ return 0.0+ sorted_data = sorted(data)+ index = (len(sorted_data) - 1) * pct+ lower = int(index)+ upper = lower + 1+ weight = index - lower+ if upper < len(sorted_data):+ return sorted_data[lower] * (1.0 - weight) + sorted_data[upper] * weight+ return sorted_data[lower]+++def calculate_throughput(report: PerfReport) -> dict:+ records = report.perf_records+ parsed_records = []+ for r in records:+ ts = _parse_log_ts(r.timestamp)+ if ts:+ parsed_records.append((r, ts))++ if not parsed_records:+ empty = {+ "input_wall_clock": 0.0,+ "input_active_p50": 0.0,+ "input_active_p95": 0.0,+ "compression_p50": 0.0,+ "compression_p95": 0.0,+ "forward_p50": 0.0,+ "forward_p95": 0.0,+ "generation_p50": 0.0,+ "generation_p95": 0.0,+ }+ return {"rolling": empty.copy(), "current": empty.copy()}++ # Calculate window from PERF timestamps to prevent dilution from other log lines+ perf_timestamps = [pair[1] for pair in parsed_records]+ oldest = min(perf_timestamps)+ newest = max(perf_timestamps)+ window_seconds = max(1.0, (newest - oldest).total_seconds())++ rolling = _calculate_throughput_stats(records, window_seconds)++ # 5-minute window calculations+ current_records = []+ current_window_seconds = 0.0+ cutoff_5m = newest - timedelta(minutes=5)+ current_pairs = [pair for pair in parsed_records if pair[1] >= cutoff_5m]+ if current_pairs:+ current_records = [pair[0] for pair in current_pairs]+ cur_oldest = min(pair[1] for pair in current_pairs)+ current_window_seconds = max(1.0, (newest - cur_oldest).total_seconds())++ current = _calculate_throughput_stats(current_records, current_window_seconds)++ return {"rolling": rolling, "current": current}+++def _calculate_throughput_stats(records: list[PerfRecord], window_seconds: float) -> dict:+ if not records:+ return {+ "input_wall_clock": 0.0,+ "input_active_p50": 0.0,+ "input_active_p95": 0.0,+ "compression_p50": 0.0,+ "compression_p95": 0.0,+ "forward_p50": 0.0,+ "forward_p95": 0.0,+ "generation_p50": 0.0,+ "generation_p95": 0.0,+ }++ # 1. Input Wall-Clock+ total_tokens_before = sum(r.tokens_before for r in records)+ input_wall = total_tokens_before / window_seconds if window_seconds > 0 else 0.0++ # 2. Input Active+ input_active_rates = []+ for r in records:+ if r.total_ms > 0:+ input_active_rates.append(r.tokens_before / (r.total_ms / 1000.0))++ # 3. Compression+ compression_rates = []+ for r in records:+ duration_ms = r.stages.get("compression_first_stage") or r.stages.get("compression")+ if duration_ms is not None and duration_ms > 0:+ compression_rates.append(r.tokens_before / (duration_ms / 1000.0))++ # 4. Effective Forward+ forward_rates = []+ for r in records:+ if r.total_ms > 0:+ forward_rates.append(r.tokens_after / (r.total_ms / 1000.0))++ # 5. Output / Generation (Approximate generation throughput)+ generation_rates = []+ for r in records:+ if r.tokens_out > 0:+ duration_ms = r.total_ms+ if r.ttfb_ms > 0 and r.total_ms > r.ttfb_ms:+ duration_ms = r.total_ms - r.ttfb_ms+ if duration_ms > 0:+ generation_rates.append(r.tokens_out / (duration_ms / 1000.0))++ return {+ "input_wall_clock": round(input_wall, 2),+ "input_active_p50": round(_percentile(input_active_rates, 0.5), 2),+ "input_active_p95": round(_percentile(input_active_rates, 0.95), 2),+ "compression_p50": round(_percentile(compression_rates, 0.5), 2),+ "compression_p95": round(_percentile(compression_rates, 0.95), 2),+ "forward_p50": round(_percentile(forward_rates, 0.5), 2),+ "forward_p95": round(_percentile(forward_rates, 0.95), 2),+ "generation_p50": round(_percentile(generation_rates, 0.5), 2),+ "generation_p95": round(_percentile(generation_rates, 0.95), 2),+ }++def build_perf_summary(report: PerfReport) -> dict:"""Aggregate a ``PerfReport`` into a JSON-serialisable summary dict.@@ -714,6 +902,7 @@ def build_perf_summary(report: PerfReport) -> dict:"cache_hit_pct": cache_hit_pct,"by_model": by_model,"by_transform": by_transform,+ "throughput": calculate_throughput(report),"log_files_read": report.log_files_read,"total_lines_parsed": report.total_lines_parsed,}diff --git a/headroom/proxy/outcome.py b/headroom/proxy/outcome.pyindex 7a1a5c378..0f0ddfc11 100644--- a/headroom/proxy/outcome.py+++ b/headroom/proxy/outcome.py@@ -434,6 +434,9 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:f"cache_read={outcome.cache_read_tokens} cache_write={outcome.cache_write_tokens} "f"cache_hit_pct={outcome.cache_hit_pct} "f"opt_ms={outcome.overhead_ms:.0f} "+ f"total_ms={outcome.total_latency_ms:.0f} "+ f"tok_out={outcome.output_tokens} "+ f"ttfb_ms={outcome.ttfb_ms:.0f} "f"transforms={_summarize_transforms(list(outcome.transforms_applied))}"f"{client_part}")diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 4cd10e2d6..d4c147fc7 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -2328,6 +2328,10 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:_stats_snapshot_lock = asyncio.Lock()_stats_snapshot: dict[str, Any] = {"expires_at": 0.0, "value": None}+ THROUGHPUT_CACHE_TTL_SECONDS = 10.0+ _throughput_cache_lock = asyncio.Lock()+ _throughput_cache: dict[str, Any] = {"expires_at": 0.0, "value": None}+RECENT_REQUEST_LOG_WINDOW = 100def _build_recent_request_payload(limit: int = RECENT_REQUEST_LOG_WINDOW) -> dict[str, Any]:@@ -2371,6 +2375,28 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:"""m = proxy.metrics+ import time++ async with _throughput_cache_lock:+ now = time.time()+ if _throughput_cache["expires_at"] < now or _throughput_cache["value"] is None:++ def _compute_throughput():+ from headroom.perf.analyzer import build_perf_summary, parse_log_files++ perf_report = parse_log_files(last_n_hours=1.0)+ return build_perf_summary(perf_report).get("throughput")++ try:+ throughput = await asyncio.to_thread(_compute_throughput)+ _throughput_cache["value"] = throughput+ _throughput_cache["expires_at"] = now + THROUGHPUT_CACHE_TTL_SECONDS+ except Exception as e:+ logger.warning("Failed to calculate throughput for stats: %s", e, exc_info=True)+ if _throughput_cache["value"] is None:+ _throughput_cache["value"] = None+ throughput = _throughput_cache["value"]+# Calculate average latencyavg_latency_ms = round(m.latency_sum_ms / m.latency_count, 2) if m.latency_count > 0 else 0min_latency_ms = (@@ -2822,6 +2848,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:**recent_request_payload,"log_full_messages": proxy.config.log_full_messages if proxy else False,**get_quota_registry().get_all_stats(),+ "throughput": throughput,}def _dashboard_config_payload() -> dict[str, Any]:diff --git a/tests/test_cli_perf_format.py b/tests/test_cli_perf_format.pyindex a60c046fc..7e1941181 100644--- a/tests/test_cli_perf_format.py+++ b/tests/test_cli_perf_format.py@@ -239,3 +239,76 @@ def test_parse_perf_line_preserves_blank_client_field(assert len(report.perf_records) == 1assert report.perf_records[0].client == ""+++def test_throughput_parsing_and_calculations(monkeypatch, tmp_path):+ logs_dir = tmp_path / "logs"+ logs_dir.mkdir()+ monkeypatch.setattr(analyzer, "LOG_DIR", logs_dir)++ log_content = (+ '2026-06-10 10:00:00,000 - headroom.proxy - INFO - [req1] STAGE_TIMINGS {"event": "stage_timings", "stages": {"compression_first_stage": 100.0, "upstream_connect": 50.0}}\n'+ "2026-06-10 10:00:01,000 - headroom.proxy - INFO - [req1] PERF model=gpt-5 msgs=1 tok_before=1000 tok_after=400 tok_saved=600 opt_ms=10 total_ms=500 tok_out=500 ttfb_ms=100 transforms=test client=codex\n"+ '2026-06-10 10:00:02,000 - headroom.proxy - INFO - [req2] STAGE_TIMINGS {"event": "stage_timings", "stages": {"compression": 200.0, "upstream_connect": 50.0}}\n'+ "2026-06-10 10:00:03,000 - headroom.proxy - INFO - [req2] PERF model=gpt-5 msgs=1 tok_before=2000 tok_after=1000 tok_saved=1000 opt_ms=20 total_ms=1000 tok_out=1000 ttfb_ms=200 transforms=test client=codex\n"+ "2026-06-10 10:00:05,000 - headroom.proxy - INFO - [req3] PERF model=gpt-5 msgs=1 tok_before=1500 tok_after=500 tok_saved=1000 opt_ms=15 total_ms=600 tok_out=600 ttfb_ms=150 transforms=test client=codex\n"+ '2026-06-10 10:00:06,000 - headroom.proxy - INFO - [req4] STAGE_TIMINGS {"event": "stage_timings", "stages": {"compression_first_stage": 150.0, "upstream_connect": 50.0}}\n'+ "2026-06-10 10:00:07,000 - headroom.proxy - INFO - [req4] PERF model=gpt-5 msgs=1 tok_before=1200 tok_after=300 tok_saved=900 opt_ms=12 total_ms=400 tok_out=400 ttfb_ms=80 transforms=test client=codex\n"+ '2026-06-10 10:00:08,000 - headroom.proxy - INFO - [req5] STAGE_TIMINGS {"event": "stage_timings", "stages": {"compression_first_stage": 50.0, "upstream_connect": 50.0}}\n'+ "2026-06-10 10:00:09,000 - headroom.proxy - INFO - [req5] PERF model=gpt-5 msgs=1 tok_before=800 tok_after=200 tok_saved=600 opt_ms=5 total_ms=300 tok_out=300 ttfb_ms=50 transforms=test client=codex\n"+ )+ (logs_dir / "proxy.log").write_text(log_content, encoding="utf-8")++ report = analyzer.parse_log_files(last_n_hours=0)++ assert len(report.perf_records) == 5++ assert report.perf_records[0].request_id == "req1"+ assert report.perf_records[0].total_ms == 500.0+ assert report.perf_records[0].tokens_out == 500+ assert report.perf_records[0].ttfb_ms == 100.0+ assert report.perf_records[0].stages == {+ "compression_first_stage": 100.0,+ "upstream_connect": 50.0,+ }++ assert report.perf_records[2].request_id == "req3"+ assert report.perf_records[2].stages == {}++ summary = build_perf_summary(report)+ assert "throughput" in summary+ tp = summary["throughput"]++ rolling = tp["rolling"]+ assert rolling["input_wall_clock"] > 0+ assert rolling["input_active_p50"] == 2500.0+ assert rolling["compression_p50"] == 10000.0+++def test_throughput_empty_and_percentiles():+ from headroom.perf.analyzer import (+ PerfReport,+ _calculate_throughput_stats,+ _percentile,+ calculate_throughput,+ )++ # Empty percentiles+ assert _percentile([], 0.5) == 0.0++ # Percentiles boundary checks+ assert _percentile([10.0], 0.5) == 10.0+ assert _percentile([10.0, 20.0], 0.5) == 15.0+ assert _percentile([10.0, 20.0], 0.0) == 10.0+ assert _percentile([10.0, 20.0], 1.0) == 20.0+ assert _percentile([10.0, 20.0], 1.5) == 20.0++ # Empty calculate_throughput+ empty_report = PerfReport()+ tp = calculate_throughput(empty_report)+ assert tp["rolling"]["input_wall_clock"] == 0.0+ assert tp["current"]["input_wall_clock"] == 0.0++ # _calculate_throughput_stats with empty records+ stats = _calculate_throughput_stats([], 10.0)+ assert stats["input_wall_clock"] == 0.0diff --git a/tests/test_proxy_dashboard_stats_cache.py b/tests/test_proxy_dashboard_stats_cache.pyindex f7f2fa554..079dfb1f3 100644--- a/tests/test_proxy_dashboard_stats_cache.py+++ b/tests/test_proxy_dashboard_stats_cache.py@@ -76,7 +76,12 @@ def test_get_rtk_stats_memoizes_subprocess_calls(monkeypatch: pytest.MonkeyPatchdef _fake_run(args, **kwargs):calls["run"] += 1- assert args == ["/usr/bin/rtk", "gain", "--format", "json"]+ assert [str(args[0]).replace("\\", "/")] + args[1:] == [+ "/usr/bin/rtk",+ "gain",+ "--format",+ "json",+ ]summary = totals[min(calls["run"] - 1, len(totals) - 1)]return SimpleNamespace(returncode=0,@@ -152,7 +157,13 @@ def test_get_rtk_stats_can_read_project_scoped_gain(monkeypatch: pytest.MonkeyPadef _fake_run(args, **kwargs):calls["run"] += 1- assert args == ["/usr/bin/rtk", "gain", "--project", "--format", "json"]+ assert [str(args[0]).replace("\\", "/")] + args[1:] == [+ "/usr/bin/rtk",+ "gain",+ "--project",+ "--format",+ "json",+ ]return SimpleNamespace(returncode=0,stdout=json.dumps(@@ -187,7 +198,12 @@ def test_get_rtk_stats_invalid_scope_defaults_to_global(def _fake_run(args, **kwargs):calls["run"] += 1- assert args == ["/usr/bin/rtk", "gain", "--format", "json"]+ assert [str(args[0]).replace("\\", "/")] + args[1:] == [+ "/usr/bin/rtk",+ "gain",+ "--format",+ "json",+ ]return SimpleNamespace(returncode=0, stdout=json.dumps({"summary": {}}))mock_warning = MagicMock()@@ -228,7 +244,11 @@ def test_get_context_tool_stats_reads_lean_ctx_gain(monkeypatch: pytest.MonkeyPadef _fake_run(args, **kwargs):calls["run"] += 1- assert args == ["/usr/bin/lean-ctx", "gain", "--json"]+ assert [str(args[0]).replace("\\", "/")] + args[1:] == [+ "/usr/bin/lean-ctx",+ "gain",+ "--json",+ ]summary = totals[min(calls["run"] - 1, len(totals) - 1)]return SimpleNamespace(returncode=0, stdout=json.dumps({"summary": summary}))@@ -549,3 +569,68 @@ def test_dashboard_uses_cached_stats_and_lazy_history_feed_polling() -> None:assert "Lean-ctx" in htmlassert "Context Tool" in htmlassert "cliFilteringLabel + ' Filtered'" in html+++def test_proxy_throughput_in_stats_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:+ """Verify that the /stats endpoint includes a 'throughput' key in the response.++ The server's _compute_throughput closure does a fresh+ `from headroom.perf.analyzer import ...` on every call, so we patch the+ names directly on the `headroom.perf.analyzer` module so the local import+ inside the closure picks up our fakes.++ Skipped locally when headroom._core (Rust extension) is not compiled.+ """+ pytest.importorskip("fastapi")+ from fastapi.testclient import TestClient++ import headroom.perf.analyzer as _analyzer_mod++ try:+ from headroom.proxy.server import (+ _throughput_cache,+ create_app,+ require_loopback,+ )+ except (ImportError, ModuleNotFoundError) as exc:+ pytest.skip(f"headroom._core not available (Rust extension not compiled): {exc}")++ from headroom.config import ProxyConfig++ # Reset the module-level cache so CI doesn't reuse a stale value+ _throughput_cache.update({"expires_at": 0.0, "value": None})++ # Patch at the module level so the local import inside _compute_throughput+ # picks up our stubs instead of the real implementations.+ monkeypatch.setattr(+ _analyzer_mod,+ "parse_log_files",+ lambda last_n_hours=1.0: _analyzer_mod.PerfReport(),+ )+ monkeypatch.setattr(+ _analyzer_mod,+ "build_perf_summary",+ lambda report: {"throughput": {"input_wall_clock": 99.0}},+ )++ app = create_app(+ ProxyConfig(+ 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.dependency_overrides[require_loopback] = lambda: None++ with TestClient(app) as client:+ response = client.get("/stats")++ assert response.status_code == 200+ payload = response.json()+ assert "throughput" in payload+ assert payload["throughput"] == {"input_wall_clock": 99.0}