Skip to content

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.

Combine rtk and compression savings in dashboard

Tejas Chopra6eec38767bd1
diff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.html
index 12ca34b87..a1db508b6 100644
--- a/headroom/dashboard/templates/dashboard.html
+++ b/headroom/dashboard/templates/dashboard.html
@@ -175,13 +175,6 @@
<div class="text-xs text-gray-500">Provider-native caching</div>
</div>
</template>
- <template x-if="(stats.cost?.cli_tokens_avoided || 0) > 0">
- <div>
- <div class="text-xs text-gray-500 mb-1">CLI Filtering (rtk)</div>
- <div class="text-2xl font-light tabular-nums text-violet-400" x-text="formatNumber(stats.cost?.cli_tokens_avoided || 0)"></div>
- <div class="text-xs text-gray-500">tokens avoided</div>
- </div>
- </template>
</div>
</div>
</template>
diff --git a/headroom/proxy/cost.py b/headroom/proxy/cost.py
index 40e747d53..99855802a 100644
--- a/headroom/proxy/cost.py
+++ b/headroom/proxy/cost.py
@@ -302,9 +302,13 @@ def merge_cost_stats(
- cache_savings_usd: prefix cache discount from provider (separate)
- cli_tokens_avoided: tokens filtered by rtk (token count only, no $ estimate)
- The hero metric (savings_usd) is ONLY compression savings priced at
- the model's published input rate. Cache and CLI are shown separately.
- This avoids the non-monotonic moving-average repricing bug (#83).
+ The dollar metric (savings_usd) remains ONLY proxy compression savings
+ priced at the model's published input rate. RTK is folded into the
+ dashboard's compression token total, but it has no reliable model-specific
+ dollar estimate because those tokens never reached the proxy request.
+ Prefix cache savings stay separate because they are a provider discount,
+ not token removal. This avoids the non-monotonic moving-average repricing
+ bug (#83).
"""
if cost_stats is None:
return None
@@ -318,6 +322,7 @@ def merge_cost_stats(
"compression_savings_usd": round(compression_savings, 4),
"cache_savings_usd": round(cache_net, 4),
"cli_tokens_avoided": cli_tokens_avoided,
+ "cli_tokens_included_in_compression": True,
}
diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.py
index 2cb757c7e..dc7c503b8 100644
--- a/headroom/proxy/helpers.py
+++ b/headroom/proxy/helpers.py
@@ -749,38 +749,32 @@ def _get_rtk_stats() -> dict[str, Any] | None:
Results are memoized briefly so dashboard polling does not spawn a new
subprocess on every refresh.
"""
- import shutil
import subprocess as _sp
+ from headroom.rtk import get_rtk_path
+
now = time.monotonic()
with _rtk_stats_cache_lock:
if _rtk_stats_cache["has_value"] and now < float(_rtk_stats_cache["expires_at"]):
return cast(dict[str, Any] | None, _rtk_stats_cache["value"])
payload: dict[str, Any] | None
- rtk_bin = shutil.which("rtk")
- if not rtk_bin:
- # Check headroom-managed install. Preserve the historical Unix-name
- # behavior here (bin_dir()/"rtk") rather than switching to
- # paths.rtk_path() which would become rtk.exe on Windows.
- rtk_managed = _paths.bin_dir() / "rtk"
- if rtk_managed.exists():
- rtk_bin = str(rtk_managed)
- else:
- payload = None
- with _rtk_stats_cache_lock:
- _rtk_stats_cache.update(
- {
- "expires_at": time.monotonic() + RTK_STATS_CACHE_TTL_SECONDS,
- "has_value": True,
- "value": payload,
- }
- )
- return payload
+ rtk_path = get_rtk_path()
+ if not rtk_path:
+ payload = None
+ with _rtk_stats_cache_lock:
+ _rtk_stats_cache.update(
+ {
+ "expires_at": time.monotonic() + RTK_STATS_CACHE_TTL_SECONDS,
+ "has_value": True,
+ "value": payload,
+ }
+ )
+ return payload
try:
result = _sp.run(
- [rtk_bin, "gain", "--format", "json"],
+ [str(rtk_path), "gain", "--format", "json"],
capture_output=True,
text=True,
timeout=5,
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index b7ffcfc0f..592aa77cb 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -1730,8 +1730,12 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
cli_filtering_stats.get("tokens_saved", 0) if cli_filtering_stats else 0
)
- # Calculate total tokens before compression
- total_tokens_before = m.tokens_input_total + m.tokens_saved_total
+ # Calculate total tokens before Headroom-side reduction. Proxy
+ # compression and rtk both remove tokens before they reach model
+ # context, so dashboard-facing compression savings combines them.
+ proxy_compression_tokens = m.tokens_saved_total
+ compression_tokens = proxy_compression_tokens + cli_tokens_avoided
+ total_tokens_before = m.tokens_input_total + compression_tokens
# Build human-readable summary
summary = _build_session_summary(
@@ -1775,9 +1779,8 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
compression_cache_stats = {"mode": proxy.config.mode}
# Build unified savings summary (all layers)
- compression_tokens = m.tokens_saved_total
cache_net_usd = prefix_cache_stats.get("totals", {}).get("net_savings_usd", 0.0)
- total_tokens_all_layers = compression_tokens + cli_tokens_avoided
+ total_tokens_all_layers = compression_tokens
persistent_savings = m.savings_tracker.stats_preview()
display_session = persistent_savings.get("display_session", {})
@@ -1788,11 +1791,19 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"by_layer": {
"cli_filtering": {
"tokens": cli_tokens_avoided,
- "description": "Tokens avoided by CLI output filtering (rtk) before reaching context",
+ "included_in": "compression",
+ "description": (
+ "Tokens avoided by CLI output filtering (rtk) before reaching context. "
+ "Included in dashboard compression savings."
+ ),
},
"compression": {
"tokens": compression_tokens,
- "description": "Tokens removed by proxy compression (SmartCrusher, ContentRouter, etc.)",
+ "proxy_tokens": proxy_compression_tokens,
+ "rtk_tokens": cli_tokens_avoided,
+ "description": (
+ "Tokens removed before model context by proxy compression plus rtk CLI filtering."
+ ),
},
"prefix_cache": {
"discount_usd": round(cache_net_usd, 4),
@@ -1816,11 +1827,13 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"tokens": {
"input": m.tokens_input_total,
"output": m.tokens_output_total,
- "saved": m.tokens_saved_total,
+ "saved": compression_tokens,
+ "proxy_compression_saved": proxy_compression_tokens,
+ "rtk_saved": cli_tokens_avoided,
"cli_tokens_avoided": cli_tokens_avoided,
"total_before_compression": total_tokens_before,
"savings_percent": round(
- (m.tokens_saved_total / total_tokens_before * 100)
+ (compression_tokens / total_tokens_before * 100)
if total_tokens_before > 0
else 0,
2,
diff --git a/headroom/subscription/models.py b/headroom/subscription/models.py
index cf14c25ee..45b17620b 100644
--- a/headroom/subscription/models.py
+++ b/headroom/subscription/models.py
@@ -395,6 +395,11 @@ class HeadroomContribution:
def total_saved(self) -> int:
return self.tokens_saved_compression + self.tokens_saved_rtk + self.tokens_saved_cache_reads
+ def compression_saved(self) -> int:
+ """Tokens removed before model context by compression plus rtk."""
+
+ return self.tokens_saved_compression + self.tokens_saved_rtk
+
def total_savings_usd(self) -> float:
return self.compression_savings_usd + self.cache_savings_usd
@@ -411,7 +416,8 @@ class HeadroomContribution:
return {
"tokens_submitted": self.tokens_submitted,
"tokens_saved": {
- "compression": self.tokens_saved_compression,
+ "compression": self.compression_saved(),
+ "proxy_compression": self.tokens_saved_compression,
"rtk": self.tokens_saved_rtk,
"cache_reads": self.tokens_saved_cache_reads,
"total": self.total_saved(),
diff --git a/headroom/subscription/tracker.py b/headroom/subscription/tracker.py
index 5aabc082f..95260646b 100644
--- a/headroom/subscription/tracker.py
+++ b/headroom/subscription/tracker.py
@@ -478,7 +478,12 @@ class SubscriptionTracker(QuotaTracker):
c = self._state.contribution
c.tokens_submitted = int(contrib.get("tokens_submitted", 0))
saved = contrib.get("tokens_saved", {})
- c.tokens_saved_compression = int(saved.get("compression", 0))
+ # Newer state writes dashboard-facing ``compression`` as
+ # proxy-compression + rtk. Prefer the raw proxy field when present
+ # so loading does not double-count rtk into the internal counter.
+ c.tokens_saved_compression = int(
+ saved.get("proxy_compression", saved.get("compression", 0))
+ )
c.tokens_saved_rtk = int(saved.get("rtk", 0))
c.tokens_saved_cache_reads = int(saved.get("cache_reads", 0))
savings_usd = contrib.get("savings_usd", {})
diff --git a/tests/test_proxy_dashboard_stats_cache.py b/tests/test_proxy_dashboard_stats_cache.py
index eb071b406..e41f4a087 100644
--- a/tests/test_proxy_dashboard_stats_cache.py
+++ b/tests/test_proxy_dashboard_stats_cache.py
@@ -132,6 +132,11 @@ def test_stats_cached_query_reuses_short_ttl_snapshot(monkeypatch: pytest.Monkey
assert calls == {"store": 3, "telemetry": 3, "feedback": 3, "rtk": 3}
assert first.json()["cli_filtering"]["tokens_saved"] == 5
+ assert first.json()["tokens"]["saved"] == 5
+ assert first.json()["tokens"]["proxy_compression_saved"] == 0
+ assert first.json()["tokens"]["rtk_saved"] == 5
+ assert first.json()["savings"]["by_layer"]["compression"]["tokens"] == 5
+ assert first.json()["savings"]["by_layer"]["compression"]["rtk_tokens"] == 5
def test_dashboard_uses_cached_stats_and_lazy_history_feed_polling() -> None:
@@ -142,3 +147,4 @@ def test_dashboard_uses_cached_stats_and_lazy_history_feed_polling() -> None:
assert '@click="toggleFeed()"' in html
assert "this.viewMode === 'history'" in html
assert "this.feedOpen" in html
+ assert "CLI Filtering (rtk)" not in html
diff --git a/tests/test_subscription_tracker.py b/tests/test_subscription_tracker.py
index d246f438b..b591283f0 100644
--- a/tests/test_subscription_tracker.py
+++ b/tests/test_subscription_tracker.py
@@ -66,6 +66,8 @@ def test_tracker_notify_active_update_and_basic_state(monkeypatch: pytest.Monkey
assert contribution.tokens_saved_compression == 5
assert contribution.tokens_saved_rtk == 0
assert contribution.tokens_saved_cache_reads == 3
+ assert contribution.to_dict()["tokens_saved"]["compression"] == 5
+ assert contribution.to_dict()["tokens_saved"]["proxy_compression"] == 5
assert contribution.compression_savings_usd == 1.25
assert contribution.cache_savings_usd == 0.0
@@ -189,6 +191,8 @@ def test_persist_and_load_state_round_trip(tmp_path: Path) -> None:
assert loader._state.contribution.tokens_saved_compression == 2
assert loader._state.contribution.tokens_saved_rtk == 3
assert loader._state.contribution.tokens_saved_cache_reads == 4
+ assert loader._state.contribution.to_dict()["tokens_saved"]["compression"] == 5
+ assert loader._state.contribution.to_dict()["tokens_saved"]["proxy_compression"] == 2
assert loader._state.contribution.compression_savings_usd == 1.5
assert loader._state.contribution.cache_savings_usd == 2.5
assert loader._state.poll_count == 7