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(dashboard): show routing savings for this session and all time (#3362)
Tejas Chopraa811984ffb62
diff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.htmlindex 4b255774d..c6d16cf82 100644--- a/headroom/dashboard/templates/dashboard.html+++ b/headroom/dashboard/templates/dashboard.html@@ -895,11 +895,62 @@registered (stats.routing; see headroom.proxy.routing_stats). --><template x-if="(stats.routing?.pairs || []).length > 0"><div class="bg-surface rounded-lg p-4 border border-border mb-6">- <div class="flex items-center justify-between mb-3">+ <div class="flex items-center justify-between mb-1"><span class="text-sm font-medium text-gray-300">Model Routing</span><span class="text-xs text-gray-500 font-mono"x-text="(stats.routing.downgrades || 0) + ' downgraded · ' + (stats.routing.upgrades || 0) + ' upgraded · ' + (stats.routing.unchanged || 0) + ' unchanged · ' + formatNumber(stats.routing.decisions || 0) + ' decisions'"></span></div>+ <!-- Two windows, one box. Session answers "is this working for ME,+ right now"; lifetime answers "what has this layer been worth".+ Neither substitutes for the other: routing savings accrue across+ sessions, so session-only understates the layer badly, while a+ lifetime total moves ~0.1% per turn and looks frozen during a+ live demo. -->+ <div class="grid grid-cols-2 gap-3 mb-4">+ <!-- THIS SESSION -->+ <div class="bg-bg rounded px-3 py-2 border border-border">+ <div class="flex items-center gap-1.5 mb-1">+ <span class="relative flex h-2 w-2" x-show="(stats.routing.session?.decisions || 0) > 0">+ <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>+ <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>+ </span>+ <span class="text-xs text-gray-400 uppercase tracking-wide">This session</span>+ </div>+ <div class="text-xl font-semibold tabular-nums"+ :class="(stats.routing.session?.savings_usd || 0) > 0 ? 'text-emerald-400' : 'text-gray-500'"+ x-text="'$' + formatCurrency(stats.routing.session?.savings_usd || 0)"></div>+ <div class="text-xs text-gray-500 font-mono mt-0.5"+ x-text="formatNumber(stats.routing.session?.decisions || 0) + ' decisions · '+ + (stats.routing.session?.downgrades || 0) + ' downgraded · '+ + (stats.routing.session?.unchanged || 0) + ' kept'"></div>+ <!-- "Kept" is the router working, not idling: against a warm+ prefix cache, switching costs a cold write on the target+ that usually exceeds the cheaper per-token rate. Without+ this the panel reads as broken during exactly the+ sessions where the router is behaving correctly. -->+ <div class="text-xs text-gray-600 mt-1 leading-snug"+ x-show="(stats.routing.session?.decisions || 0) > 0+ && (stats.routing.session?.downgrades || 0) === 0"+ title="Every turn was evaluated. Keeping the model is the correct call when the prefix cache is warm — switching would pay a cold write on the target.">+ Evaluating every turn; cache is warm, so switching would cost more than it saves.+ </div>+ </div>+ <!-- ALL TIME -->+ <div class="bg-bg rounded px-3 py-2 border border-border">+ <div class="text-xs text-gray-400 uppercase tracking-wide mb-1">All time</div>+ <div class="text-xl font-semibold tabular-nums"+ :class="(stats.routing.savings_usd || 0) > 0 ? 'text-emerald-400' : 'text-gray-500'"+ x-text="'$' + formatCurrency(stats.routing.savings_usd || 0)"></div>+ <div class="text-xs text-gray-500 font-mono mt-0.5"+ x-text="formatNumber(stats.routing.decisions || 0) + ' decisions · '+ + (stats.routing.downgrades || 0) + ' downgraded · '+ + (stats.routing.unchanged || 0) + ' kept'"></div>+ <div class="text-xs text-gray-600 mt-1 leading-snug">+ Survives restarts — kept in routemegood's decision log, not proxy memory.+ </div>+ </div>+ </div>+ <div class="text-xs text-gray-500 mb-2">Every decision on record, by requested → served pair</div><div class="overflow-x-auto"><table class="w-full text-sm"><thead>diff --git a/headroom/proxy/cost.py b/headroom/proxy/cost.pyindex fb41d3089..812854a71 100644--- a/headroom/proxy/cost.py+++ b/headroom/proxy/cost.py@@ -695,7 +695,16 @@ def build_session_summary(# provider terms (cache discount included on both sides, since it applies# either way).cost_without = cost_with + measured_saved + ext_projected_usd- savings_pct_cost = round(total_saved_usd / cost_without * 100, 1) if cost_without > 0 else 0.0+ # `> 0` is not a sufficient guard. ext_projected_usd is SIGNED -- routing+ # reports an upgrade as a negative saving -- so a session that routed up can+ # drive the baseline arbitrarily close to zero while real money was spent:+ # $1.59 spent + $0.63 measured - $2.21 projected left a $0.01 baseline, and+ # the card read "-39666.1%". A baseline that small is a cancellation+ # artifact, not a measurement, so report no percentage rather than one that+ # is wrong by three orders of magnitude.+ _baseline_is_meaningful = cost_without > max(0.01, 0.05 * cost_with)+ savings_pct_cost = (round(total_saved_usd / cost_without * 100, 1)+ if _baseline_is_meaningful else 0.0)# Primary models usedmodels = dict(metrics.requests_by_model)diff --git a/headroom/proxy/routing_stats.py b/headroom/proxy/routing_stats.pyindex 6e815aec4..b9e3be091 100644--- a/headroom/proxy/routing_stats.py+++ b/headroom/proxy/routing_stats.py@@ -24,8 +24,23 @@ Provider contract — return ``None`` (nothing to show) or::"savings_usd": float}, # signed; negative for upgrades...],++ # Optional, and strongly preferred. Routing savings accrue ACROSS+ # sessions, so a durable provider should report all time above -- scoping+ # the table to one proxy process understates the layer badly. But a+ # lifetime total moves ~0.1% per turn, so on its own it looks frozen while+ # the router is in fact evaluating every request. Send ``session`` too and+ # the dashboard renders a live counter beside the table.+ "window": "lifetime" | "session", # scope of the numbers above+ "session": {"decisions": int, "downgrades": int, "upgrades": int,+ "unchanged": int, "since": float}, # this process only}+Unknown keys are passed through untouched, so a provider may add fields ahead+of the dashboard learning to render them. Absent ``window``, the dashboard+labels the table "all decisions on record" rather than claiming a scope it+cannot verify.+The provider is called on ``/stats`` builds (the dashboard polls a cachedsnapshot), so it should be cheap — an aggregate query, not a table walk."""diff --git a/tests/test_routing_stats_seam.py b/tests/test_routing_stats_seam.pynew file mode 100644index 000000000..98fe409b9--- /dev/null+++ b/tests/test_routing_stats_seam.py@@ -0,0 +1,99 @@+"""The routing-stats seam: what makes the dashboard's Model Routing panel appear.++The panel is gated on a non-empty ``pairs`` list, so anything that empties it+removes the whole section from the dashboard with no error anywhere. That is+not hypothetical: scoping a durable provider to the current proxy process made+``pairs`` empty on every fresh start, and the panel silently vanished.+"""++from __future__ import annotations++import pytest++from headroom.proxy.routing_stats import (+ clear_routing_stats_provider,+ get_routing_stats,+ set_routing_stats_provider,+)++[email protected](autouse=True)+def _clean():+ clear_routing_stats_provider()+ yield+ clear_routing_stats_provider()+++def _matrix(**over):+ base = {+ "decisions": 3,+ "downgrades": 1,+ "upgrades": 0,+ "unchanged": 2,+ "pairs": [{"requested": "claude-opus-5", "served": "claude-sonnet-5",+ "direction": "downgrade", "count": 1, "enforced": 1,+ "holdout": 0, "measured": 1, "savings_usd": 0.42}],+ }+ base.update(over)+ return base+++def test_no_provider_is_inert():+ assert get_routing_stats() is None+++def test_provider_payload_passes_through():+ set_routing_stats_provider(lambda: _matrix())+ out = get_routing_stats()+ assert out["decisions"] == 3+ assert out["pairs"][0]["served"] == "claude-sonnet-5"+++def test_empty_pairs_hides_the_section():+ """The rule the dashboard depends on -- and the trap it sets."""+ set_routing_stats_provider(lambda: _matrix(pairs=[], decisions=0))+ assert get_routing_stats() is None+++def test_a_broken_provider_never_breaks_stats():+ def boom():+ raise RuntimeError("decision log is locked")++ set_routing_stats_provider(boom)+ assert get_routing_stats() is None+++def test_unknown_keys_survive_so_providers_can_lead_the_dashboard():+ """`window` and `session` reach the template even on an older core."""+ set_routing_stats_provider(lambda: _matrix(+ window="lifetime",+ session={"decisions": 4, "downgrades": 3, "upgrades": 0,+ "unchanged": 1, "since": 1788140194.8},+ ))+ out = get_routing_stats()+ assert out["window"] == "lifetime"+ assert out["session"]["downgrades"] == 3+++def test_live_session_counter_can_be_zero_while_the_panel_still_renders():+ """The regression this file exists for.++ A durable provider reports lifetime pairs (so the panel renders and shows+ accrued savings) while the session block legitimately reads zero on a proxy+ that has only just started. Reporting the SESSION in ``pairs`` instead+ emptied it and took the whole section down.+ """+ set_routing_stats_provider(lambda: _matrix(+ window="lifetime",+ session={"decisions": 0, "downgrades": 0, "upgrades": 0,+ "unchanged": 0, "since": 1788140194.8},+ ))+ out = get_routing_stats()+ assert out is not None, "panel must survive a session with no decisions yet"+ assert out["pairs"], "lifetime pairs keep the section on screen"+ assert out["session"]["decisions"] == 0+++def test_non_dict_payload_is_ignored():+ set_routing_stats_provider(lambda: ["not", "a", "matrix"])+ assert get_routing_stats() is None