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.

fix(dashboard): report Headroom-attributable cost savings, not the provider cache discount (#3356)

devin-ai-integration[bot]bfe3c7873f93
diff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.html
index 54c004919..4b255774d 100644
--- a/headroom/dashboard/templates/dashboard.html
+++ b/headroom/dashboard/templates/dashboard.html
@@ -240,24 +240,31 @@
</div>
</div>
- <!-- Cost Saved: single-pane dollars across every layer the
- session summary prices (compression, tool-schema
- deferral, prefix-cache net, extension-attributed
- dollars), split measured vs projected. -->
+ <!-- Cost Saved: dollars Headroom itself kept off the bill
+ (compression + tool-schema deferral + extension
+ attribution), split measured vs projected. The
+ provider's prefix-cache discount is shown on its own
+ line, outside the headline — it is paid on cache reads
+ with or without Headroom. -->
<div class="bg-surface rounded-lg p-4 border border-border">
<div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Cost Saved</div>
<div class="flex items-baseline gap-2">
<span class="text-3xl font-light tabular-nums text-emerald-400"
- x-text="'$' + formatCurrency(stats.summary?.cost?.total_saved_usd || 0)"></span>
+ x-text="'$' + formatCurrency(stats.summary?.cost?.total_saved_usd || 0)"
+ title="Dollars Headroom kept off the bill: message compression and tool-schema deferral, priced at what those tokens would actually have been billed given each request's cache mix."></span>
<span class="text-sm text-emerald-400"
x-text="(stats.summary?.cost?.savings_pct || 0).toFixed(1) + '%'"
title="Total saved as a fraction of the without-Headroom baseline"></span>
</div>
<div class="mt-1 text-xs text-gray-500 leading-relaxed"
x-text="'Measured $' + formatCurrency(stats.summary?.cost?.measured_saved_usd || 0) + ' · projected $' + formatCurrency(stats.summary?.cost?.projected_saved_usd || 0)"
- title="Measured: compression, tool-schema deferral, prefix-cache net. Projected: extension-attributed estimates such as model routing."></div>
+ title="Measured: compression and tool-schema deferral. Projected: extension-attributed estimates such as model routing."></div>
<div class="mt-1 text-xs text-gray-600 leading-relaxed"
- x-text="'$' + formatCurrency(stats.summary?.cost?.with_headroom_usd || 0) + ' spent vs $' + formatCurrency(stats.summary?.cost?.without_headroom_usd || 0) + ' baseline'"></div>
+ x-text="'$' + formatCurrency(stats.summary?.cost?.with_headroom_usd || 0) + ' spent vs $' + formatCurrency(stats.summary?.cost?.without_headroom_usd || 0) + ' baseline'"
+ title="Spend is input + output at the provider's billed rates."></div>
+ <div class="mt-1 text-xs text-cyan-600 leading-relaxed"
+ x-text="'+ $' + formatCurrency(stats.summary?.cost?.provider_cache_discount_usd || 0) + ' provider cache discount'"
+ title="Discount the provider gives on prompt-cache reads. Headroom's CacheAligner and prefix freeze raise the hit rate, but the discount is provider-native, so it is not counted as Headroom savings."></div>
</div>
<!-- Output Tokens Saved (counterfactual) -->
diff --git a/headroom/proxy/cost.py b/headroom/proxy/cost.py
index efe5a7169..fb41d3089 100644
--- a/headroom/proxy/cost.py
+++ b/headroom/proxy/cost.py
@@ -103,8 +103,12 @@ class CostEntry(NamedTuple):
basis: str
-# Provider-specific cache discount multipliers (what fraction of input price)
-# Used to calculate dollar savings from prefix caching
+# Provider-specific cache discount multipliers (what fraction of input price).
+# Fallback only: the per-model LiteLLM catalog
+# (cache_read_input_token_cost / cache_creation_input_token_cost) is the primary
+# source for cache economics, and these ratios stand in when a model publishes
+# no cache pricing. Hardcoded ratios go stale per model and per context tier
+# (Anthropic's >200k rates differ), so they are never preferred over the catalog.
_CACHE_ECONOMICS = {
"anthropic": {
"read_multiplier": 0.1,
@@ -129,6 +133,44 @@ _CACHE_ECONOMICS = {
}
+#: Context size at which the major catalogs publish a second, higher price
+#: tier (LiteLLM spells it ``*_above_200k_tokens``). A request's billed prompt
+#: is compared against this to pick which rate applies.
+_LONG_CONTEXT_THRESHOLD_TOKENS = 200_000
+
+
+def _bucket_by_cache_mix(
+ tokens: int,
+ *,
+ cache_read_tokens: int,
+ cache_write_tokens: int,
+ uncached_tokens: int,
+) -> tuple[float, float, float]:
+ """Split ``tokens`` into (read, write, list) shares by a request's cache mix.
+
+ Tokens Headroom kept off the wire would have ridden the SAME region of the
+ request as the mix passed in: cold-written at the provider's cache-write
+ rate, read at its cache-read rate on warm turns, re-written when the TTL
+ expired. The observed mix is the best available estimate of that rhythm (a
+ TTL expiry shows up as a write-heavy mix on the real request, so the
+ counterfactual re-write is captured per request rather than modelled).
+
+ Callers choose WHICH mix to pass, because the two savings layers live in
+ different regions of the request — see the call sites in ``record_tokens``.
+
+ A request with no billed input breakdown falls back to list price for the
+ whole amount.
+ """
+ billed_in = max(0, cache_read_tokens) + max(0, cache_write_tokens) + max(0, uncached_tokens)
+ if tokens <= 0:
+ return 0.0, 0.0, 0.0
+ if billed_in <= 0:
+ return 0.0, 0.0, float(tokens)
+ read_part = tokens * max(0, cache_read_tokens) / billed_in
+ write_part = tokens * max(0, cache_write_tokens) / billed_in
+ return read_part, write_part, tokens - read_part - write_part
+
+
def _summarize_transforms(transforms: list[str]) -> str:
"""Collapse repeated transforms into counted summary.
@@ -207,6 +249,11 @@ def build_prefix_cache_stats(
# to be seen first (e.g. Haiku's $0.80/M vs Sonnet's $3/M), skewing the
# dashboard's savings figure ~3.75x.
input_price_per_token = None
+ # Per-token cache rates for that same model, straight from LiteLLM's
+ # catalog. Preferred over the _CACHE_ECONOMICS ratios below: those are
+ # hardcoded per provider and can't express a model's or context tier's
+ # actual published cache rates.
+ cache_prices = None
if cost_tracker:
best_tokens = -1
for model_name, tokens_sent in cost_tracker._tokens_sent_by_model.items():
@@ -222,8 +269,19 @@ def build_prefix_cache_stats(
price_per_1m = cost_tracker._get_list_price(model_name)
if price_per_1m:
input_price_per_token = price_per_1m / 1_000_000
+ cache_prices = cost_tracker._get_cache_prices(model_name)
best_tokens = tokens_sent
+ # Catalog rates win; the provider ratio table is the fallback for a model
+ # that publishes no cache pricing.
+ pricing_source = "provider_default"
+ if cache_prices and input_price_per_token:
+ _cr_price, _cw_price, _uncached_price = cache_prices
+ if _uncached_price:
+ read_mult = _cr_price / _uncached_price
+ write_mult = _cw_price / _uncached_price
+ pricing_source = "catalog"
+
# Calculate savings:
# Cache reads save (1.0 - read_mult) per token vs uncached input price.
# Cache write premium stays visible as its own gross field, and net
@@ -272,6 +330,7 @@ def build_prefix_cache_stats(
"savings_usd": round(savings_usd, 4),
"write_premium_usd": round(write_premium_usd, 4),
"net_savings_usd": round(savings_usd - write_premium_usd, 4),
+ "cache_pricing_source": pricing_source,
"label": str(econ["label"]),
"observed_ttl_buckets": {
"5m": {
@@ -590,16 +649,31 @@ def build_session_summary(
best_compression = best["savings_pct"]
best_detail = f"{best['original']:,} → {best['optimized']:,} tokens"
- # Cost summary — every savings layer priced into one card. Measured layers
- # (compression, tool-schema deferral, prefix-cache net) and
- # extension-attributed dollars are itemized in ``breakdown``; rows the
- # attribution ledger flags ``realized=False`` (e.g. a model-routing
+ # Cost summary — what Headroom itself saved, priced into one card.
+ #
+ # The headline counts only layers Headroom causes: message compression,
+ # tool-schema deferral and extension-attributed dollars. The provider's
+ # prefix-cache discount is reported BESIDE it, never inside it: that
+ # discount is paid on cache reads whether or not Headroom is in the path
+ # (CacheAligner and prefix freeze improve the hit rate, they don't create
+ # the discount), and it is an order of magnitude larger than compression on
+ # a long agent session, so folding it in made a card that couldn't be
+ # reconciled with the Tokens Saved counter next to it.
+ #
+ # Rows the attribution ledger flags ``realized=False`` (e.g. a model-routing
# extension's decision-time delta) are summed under a ``projected`` key so
# a reader can still split measured from estimated. Budget enforcement
# keeps reading the unwidened ``savings_usd`` from the tracker.
cost_stats = proxy.cost_tracker.stats() if proxy.cost_tracker else {}
- cost_with = cost_stats.get("cost_with_headroom_usd", 0.0)
- compression_savings = cost_stats.get("savings_usd", 0.0)
+ cost_input = cost_stats.get("cost_with_headroom_usd", 0.0)
+ cost_output = cost_stats.get("output_cost_usd", 0.0)
+ cost_with = cost_stats.get("total_cost_usd", cost_input)
+ # Cache-aware valuation of the compressed-away tokens: what they would
+ # actually have been billed at, given the cache mix of the requests they
+ # were removed from. The list-priced figure feeds budgets and is kept in
+ # the breakdown for comparison.
+ compression_savings_list = cost_stats.get("savings_usd", 0.0)
+ compression_savings = cost_stats.get("cache_aware_savings_usd", compression_savings_list)
tool_savings = cost_stats.get("tool_savings_usd", 0.0)
cache_net = prefix_cache_stats.get("totals", {}).get("net_savings_usd", 0.0)
ext_realized_usd = 0.0
@@ -615,8 +689,11 @@ def build_session_summary(
ext_realized_usd += usd
else:
ext_projected_usd += usd
- measured_saved = compression_savings + tool_savings + cache_net + ext_realized_usd
+ measured_saved = compression_savings + tool_savings + ext_realized_usd
total_saved_usd = round(measured_saved + ext_projected_usd, 2)
+ # Baseline = what this session would have cost without Headroom, on the same
+ # 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
@@ -648,13 +725,20 @@ def build_session_summary(
"cost": {
"without_headroom_usd": round(cost_without, 2),
"with_headroom_usd": round(cost_with, 2),
+ "with_headroom_input_usd": round(cost_input, 2),
+ "with_headroom_output_usd": round(cost_output, 2),
"total_saved_usd": total_saved_usd,
"measured_saved_usd": round(measured_saved, 2),
"projected_saved_usd": round(ext_projected_usd, 2),
"savings_pct": savings_pct_cost,
+ # Provider-side, NOT part of total_saved_usd: the discount the
+ # provider gives on cache reads, which Headroom helps land but does
+ # not create. Already reflected in with_headroom_usd.
+ "provider_cache_discount_usd": round(cache_net, 2),
"breakdown": {
"cache_savings_usd": round(cache_net, 2),
"compression_savings_usd": round(compression_savings, 2),
+ "compression_savings_list_usd": round(compression_savings_list, 2),
"tool_search_savings_usd": round(tool_savings, 2),
"extension_realized_usd": round(ext_realized_usd, 2),
"extension_projected_usd": round(ext_projected_usd, 2),
@@ -731,6 +815,13 @@ class CostTracker:
# Token savings per model (exact, no dollar estimation)
self._tokens_saved_by_model: dict[str, int] = {}
+ # Cache-aware counterfactual buckets for compressed-away message tokens,
+ # the same treatment the deferred tool schemas get below. Floats: shares
+ # of a request's removed tokens, not whole tokens. Keyed by
+ # ``(model, long_context)`` so a >200k-context turn is priced at the tier
+ # the provider actually billed it at rather than the base rate.
+ self._saved_write_by_tier: dict[tuple[str, bool], float] = {}
+ self._saved_list_by_tier: dict[tuple[str, bool], float] = {}
# Tool-schema deferral per model, DISJOINT from _tokens_saved_by_model
# (deferred schemas are never in the message counts). Tracked separately
# so the compression-only figure stays available; `stats()` reports both
@@ -750,6 +841,9 @@ class CostTracker:
self._tool_saved_write_by_model: dict[str, float] = {}
self._tool_saved_list_by_model: dict[str, float] = {}
self._tokens_sent_by_model: dict[str, int] = {}
+ # Completion tokens keyed by ``(model, long_context)`` — same reason as
+ # the savings buckets: the >200k completion rate is a different number.
+ self._output_tokens_by_tier: dict[tuple[str, bool], int] = {}
self._requests_by_model: dict[str, int] = {}
# API-reported cache breakdown per model (for accurate cost calculation)
@@ -764,11 +858,14 @@ class CostTracker:
self._costs.clear()
self._last_prune_time = datetime.now()
self._tokens_saved_by_model.clear()
+ self._saved_write_by_tier.clear()
+ self._saved_list_by_tier.clear()
self._tool_saved_by_model.clear()
self._tool_saved_read_by_model.clear()
self._tool_saved_write_by_model.clear()
self._tool_saved_list_by_model.clear()
self._tokens_sent_by_model.clear()
+ self._output_tokens_by_tier.clear()
self._requests_by_model.clear()
self._api_cache_read_by_model.clear()
self._api_cache_write_by_model.clear()
@@ -902,21 +999,43 @@ class CostTracker:
self._tool_saved_by_model[model] = self._tool_saved_by_model.get(model, 0) + max(
0, tool_schema_saved
)
+ # A request the provider reported no cache data for (or whose write
+ # counter was inferred, not billed) falls back to list price for its
+ # full share.
+ write_eff = 0 if cache_inferred else max(0, cache_write_tokens)
+ billed_prompt = max(0, cache_read_tokens) + write_eff + max(0, uncached_tokens)
+ long_context = max(billed_prompt, tokens_sent) > _LONG_CONTEXT_THRESHOLD_TOKENS
+ if tokens_saved > 0:
+ # Message compression works the LIVE ZONE only: handlers freeze the
+ # cached prefix (system + prior turns) byte-for-byte for prefix-cache
+ # safety and compress the newly appended delta. The removed tokens
+ # therefore could never have been billed as cache reads — the read
+ # bucket is the frozen prefix, which Headroom did not touch. Pricing
+ # them by the WHOLE request's mix valued a warm turn's savings at
+ # ~0.1x, an order of magnitude under what the provider would have
+ # charged for that same content in the live zone. Split over the
+ # live-zone mix (write + uncached) instead; tool-schema deferral
+ # below keeps the full-request mix, because deferred schemas do sit
+ # in the cached prefix.
+ _read, c_write, c_list = _bucket_by_cache_mix(
+ tokens_saved,
+ cache_read_tokens=0,
+ cache_write_tokens=write_eff,
+ uncached_tokens=uncached_tokens,
+ )
+ wkey = (model, long_context)
+ self._saved_write_by_tier[wkey] = self._saved_write_by_tier.get(wkey, 0.0) + c_write
+ self._saved_list_by_tier[wkey] = self._saved_list_by_tier.get(wkey, 0.0) + c_list
if tool_schema_saved > 0:
# Split this request's deferred schema tokens by the request's own
# observed cache mix: the schemas would have shared the prefix, so
- # they inherit its read/write/uncached proportions. A request the
- # provider reported no cache data for (or whose write counter was
- # inferred, not billed) falls back to list price for its full share.
- write_eff = 0 if cache_inferred else max(0, cache_write_tokens)
- billed_in = max(0, cache_read_tokens) + write_eff + max(0, uncached_tokens)
- if billed_in > 0:
- read_part = tool_schema_saved * max(0, cache_read_tokens) / billed_in
- write_part = tool_schema_saved * write_eff / billed_in
- list_part = tool_schema_saved - read_part - write_part
- else:
- read_part = write_part = 0.0
- list_part = float(tool_schema_saved)
+ # they inherit its read/write/uncached proportions.
+ read_part, write_part, list_part = _bucket_by_cache_mix(
+ tool_schema_saved,
+ cache_read_tokens=cache_read_tokens,
+ cache_write_tokens=write_eff,
+ uncached_tokens=uncached_tokens,
+ )
self._tool_saved_read_by_model[model] = (
self._tool_saved_read_by_model.get(model, 0.0) + read_part
)
@@ -927,6 +1046,10 @@ class CostTracker:
self._tool_saved_list_by_model.get(model, 0.0) + list_part
)
self._tokens_sent_by_model[model] = self._tokens_sent_by_model.get(model, 0) + tokens_sent
+ okey = (model, long_context)
+ self._output_tokens_by_tier[okey] = self._output_tokens_by_tier.get(okey, 0) + max(
+ 0, output_tokens
+ )
self._requests_by_model[model] = self._requests_by_model.get(model, 0) + 1
self._api_cache_read_by_model[model] = (
self._api_cache_read_by_model.get(model, 0) + cache_read_tokens
@@ -971,7 +1094,7 @@ class CostTracker:
# ``uncached_tokens``. Adding it to the total would double-count the
# prompt, and charging it at the write premium would invent a cost OpenAI
# does not have — so it is excluded from both.
- effective_cache_write = 0 if cache_inferred else cache_write_tokens
+ effective_cache_write = write_eff
basis = COST_BASIS_MEASURED
input_tokens = uncached_tokens + cache_read_tokens + effective_cache_write
if not (uncached_tokens or cache_read_tokens or cache_write_tokens):
@@ -1116,11 +1239,38 @@ class CostTracker:
except Exception:
return None
- def _get_cache_prices(self, model: str) -> tuple[float, float, float] | None:
+ def _get_output_price(self, model: str, *, long_context: bool = False) -> float | None:
+ """Get the per-token completion price for a model, or None if unpriced.
+
+ ``long_context`` selects the catalog's above-200k completion rate where
+ the model publishes one (Anthropic charges 1.5x there).
+ """
+ litellm = _get_litellm_module()
+ if litellm is None:
+ return None
+ try:
+ from headroom.pricing.litellm_pricing import resolve_litellm_model
+
+ resolved = resolve_litellm_model(model)
+ info = litellm.model_cost.get(resolved, {})
+ base = info.get("output_cost_per_token")
+ if long_context:
+ return info.get("output_cost_per_token_above_200k_tokens") or base or None
+ return base or None
+ except Exception:
+ return None
+
+ def _get_cache_prices(
+ self, model: str, *, long_context: bool = False
+ ) -> tuple[float, float, float] | None:
"""Get per-token prices for cache read, cache write, and uncached input.
Returns (cache_read, cache_write, uncached) per-token costs, or None
if pricing is unavailable. Uses LiteLLM's native cache pricing data.
+
+ ``long_context`` picks the above-200k tier for each of the three rates,
+ falling back per rate to the base one for a model that publishes no
+ long-context price.
"""
litellm = _get_litellm_module()
if litellm is None:
@@ -1135,6 +1285,12 @@ class CostTracker:
return None
cache_read = info.get("cache_read_input_token_cost", uncached)
cache_write = info.get("cache_creation_input_token_cost", uncached)
+ if long_context:
+ uncached = info.get("input_cost_per_token_above_200k_tokens") or uncached
+ cache_read = info.get("cache_read_input_token_cost_above_200k_tokens") or cache_read
+ cache_write = (
+ info.get("cache_creation_input_token_cost_above_200k_tokens") or cache_write
+ )
return (cache_read, cache_write, uncached)
except Exception:
return None
@@ -1241,6 +1397,8 @@ class CostTracker:
# Compression savings: price saved tokens at the model's list input price.
# This is simple, monotonic, and transparent — each saved token is valued
# at the published $/token rate for its model. Not affected by cache mix.
+ # Budget enforcement reads this figure, so it stays as-is; the
+ # cache-aware valuation below is reported alongside it.
savings_usd = 0.0
for model in self._tokens_saved_by_model:
saved = self._tokens_saved_by_model[model]
@@ -1251,6 +1409,34 @@ class CostTracker:
_cr_price, _cw_price, uncached_price = prices
savings_usd += saved * uncached_price
+ # Completion spend. The input-only figure above is what a budget and the
+ # per-model table want; a card that says "$X spent" has to include the
+ # tokens the model emitted, or the spend it shows isn't the bill.
+ output_cost_usd = 0.0
+ for (model, long_context), out_tokens in self._output_tokens_by_tier.items():
+ price = self._get_output_price(model, long_context=long_context)
+ if price:
+ output_cost_usd += out_tokens * price
+
+ # Compression savings priced at the rate the removed tokens would have
+ # been billed at: live-zone content, so the provider's cache-write rate
+ # for the share that would have been cached on this turn and list for
+ # the rest, at the context tier the request was billed in. Flat list
+ # pricing (``savings_usd``) ignores both. Reported separately so budget
+ # enforcement keeps its monotonic list-priced basis; the dashboard's
+ # cost card prefers this one.
+ cache_aware_savings_usd = 0.0
+ for key in set(self._saved_write_by_tier) | set(self._saved_list_by_tier):
+ model, long_context = key
+ prices = self._get_cache_prices(model, long_context=long_context)
+ if not prices:
+ continue
+ _cr_price, cw_price, uncached_price = prices
+ cache_aware_savings_usd += (
+ self._saved_write_by_tier.get(key, 0.0) * cw_price
+ + self._saved_list_by_tier.get(key, 0.0) * uncached_price
+ )
+
# Tool-schema deferral, priced CACHE-AWARE rather than flat at list:
# had the schemas shipped they would have been part of the same prefix
# as the rest of the request — cold-written once at the provider's
@@ -1296,8 +1482,14 @@ class CostTracker:
"cache_write_5m_tokens": sum(self._api_cache_write_5m_by_model.values()),
"cache_write_1h_tokens": sum(self._api_cache_write_1h_by_model.values()),
"per_model": per_model,
+ # Input-only, unchanged: budgets, the per-model table and the
+ # persistent savings tracker all read it as input spend.
"cost_with_headroom_usd": round(cost_with_headroom, 4),
+ "output_cost_usd": round(output_cost_usd, 4),
+ # What the session actually cost, input + output.
+ "total_cost_usd": round(cost_with_headroom + output_cost_usd, 4),
"savings_usd": round(savings_usd, 4),
+ "cache_aware_savings_usd": round(cache_aware_savings_usd, 4),
"tool_savings_usd": round(tool_savings_usd, 4),
# Budget config passthrough — surfaces in /stats["cost"] so
# `headroom doctor` can report whether a budget is set.
diff --git a/tests/test_cost_card_attribution.py b/tests/test_cost_card_attribution.py
new file mode 100644
index 000000000..eb50f0ce3
--- /dev/null
+++ b/tests/test_cost_card_attribution.py
@@ -0,0 +1,257 @@
+"""The Cost Saved card must report what Headroom itself saved.
+
+Before this, the card summed compression + tool deferral + the provider's
+prefix-cache discount into one "Cost Saved" number, so a session that removed
+1.4M tokens showed ~$25 saved — 85% of which was the provider's cache discount,
+paid with or without Headroom. These tests pin the split, the cache-aware
+valuation of removed tokens, and the inclusion of completion spend.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from tests._dotenv import (
+ autouse_apply_env,
+ importorskip_no_env_leak,
+ load_env_overrides,
+)
+
+_env_overrides = load_env_overrides()
+apply_dotenv = autouse_apply_env(_env_overrides)
+
+importorskip_no_env_leak("litellm")
+
+MODEL = "claude-sonnet-4-20250514"
+
+
+def _prices(model: str = MODEL) -> tuple[float, float, float]:
+ import litellm
+
+ from headroom.pricing.litellm_pricing import resolve_litellm_model
+
+ info = litellm.model_cost.get(resolve_litellm_model(model), {})
+ uncached = info["input_cost_per_token"]
+ return (
+ info.get("cache_read_input_token_cost", uncached),
+ info.get("cache_creation_input_token_cost", uncached),
+ uncached,
+ )
+
+
+def test_compressed_tokens_priced_at_the_rate_they_would_have_been_billed():
+ """A cold turn's removed tokens would have been billed as cache writes."""
+ from headroom.proxy.server import CostTracker
+
+ ct = CostTracker()
+ ct.record_tokens(
+ MODEL,
+ tokens_saved=100_000,
+ tokens_sent=50_000,
+ cache_read_tokens=0,
+ cache_write_tokens=90_000,
+ uncached_tokens=10_000,
+ )
+ stats = ct.stats()
+
+ _cache_read, cache_write, uncached = _prices()
+ write_share = 90_000 / 100_000
+ expected = 100_000 * (write_share * cache_write + (1 - write_share) * uncached)
+
+ assert abs(stats["cache_aware_savings_usd"] - expected) < 1e-6
+ # Writes cost MORE than list, so flat list pricing understates a cold turn.
+ assert stats["cache_aware_savings_usd"] > stats["savings_usd"]
+ assert abs(stats["savings_usd"] - 100_000 * uncached) < 1e-6
+
+
+def test_warm_prefix_does_not_drag_the_live_delta_down_to_the_read_rate():
+ """Compression works the live zone; the frozen prefix is not its rate.
+
+ Handlers keep the cached prefix byte-identical for prefix-cache safety and
+ compress only the appended delta, so removed tokens could never have been
+ billed as cache reads. Splitting them across the WHOLE request's mix valued
+ a warm turn at ~a tenth of what the provider would have charged.
+ """
+ from headroom.proxy.server import CostTracker
+
+ ct = CostTracker()
+ ct.record_tokens(
+ MODEL,
+ tokens_saved=10_000,
+ tokens_sent=200_000,
+ cache_read_tokens=190_000,
+ cache_write_tokens=5_000,
+ uncached_tokens=5_000,
+ )
+ stats = ct.stats()
+
+ cache_read, cache_write, uncached = _prices()
+ expected = 10_000 * (0.5 * cache_write + 0.5 * uncached)
+ # stats() rounds dollars to 4dp.
+ assert abs(stats["cache_aware_savings_usd"] - expected) < 1e-4
+
+ # The whole-request mix is 95% cache reads; pricing the delta that way would
+ # have valued it near the read rate.
+ whole_request_mix = 10_000 * (0.95 * cache_read + 0.025 * cache_write + 0.025 * uncached)
+ assert stats["cache_aware_savings_usd"] > 5 * whole_request_mix
+
+
+def test_fully_uncached_request_values_removed_tokens_at_list():
+ """With no cache in play there is nothing to discount."""
+ from headroom.proxy.server import CostTracker
+
+ ct = CostTracker()
+ ct.record_tokens(
+ MODEL,
+ tokens_saved=40_000,
+ tokens_sent=20_000,
+ uncached_tokens=20_000,
+ )
+ stats = ct.stats()
+
+ assert abs(stats["cache_aware_savings_usd"] - stats["savings_usd"]) < 1e-6
+
+
+def test_completion_spend_is_reported_alongside_input_spend():
+ """`total_cost_usd` is the bill; `cost_with_headroom_usd` stays input-only."""
+ import litellm
+
+ from headroom.pricing.litellm_pricing import resolve_litellm_model
+ from headroom.proxy.server import CostTracker
+
+ ct = CostTracker()
+ ct.record_tokens(
+ MODEL,
+ tokens_saved=0,
+ tokens_sent=100_000,
+ uncached_tokens=100_000,
+ output_tokens=20_000,
+ )
+ stats = ct.stats()
+
+ info = litellm.model_cost.get(resolve_litellm_model(MODEL), {})
+ expected_output = 20_000 * info["output_cost_per_token"]
+
+ assert abs(stats["output_cost_usd"] - expected_output) < 1e-6
+ assert stats["cost_with_headroom_usd"] > 0
+ expected_total = stats["cost_with_headroom_usd"] + stats["output_cost_usd"]
+ assert abs(stats["total_cost_usd"] - expected_total) < 1e-6
+
+
+def test_long_context_turn_is_priced_at_the_above_200k_rates():
+ """Past 200k the catalog charges a second, higher tier for input and output."""
+ import litellm
+
+ from headroom.pricing.litellm_pricing import resolve_litellm_model
+ from headroom.proxy.server import CostTracker
+
+ info = litellm.model_cost.get(resolve_litellm_model(MODEL), {})
+ long_input = info["input_cost_per_token_above_200k_tokens"]
+ long_output = info["output_cost_per_token_above_200k_tokens"]
+ assert long_input > info["input_cost_per_token"]
+ assert long_output > info["output_cost_per_token"]
+
+ ct = CostTracker()
+ ct.record_tokens(
+ MODEL,
+ tokens_saved=10_000,
+ tokens_sent=300_000,
+ cache_read_tokens=0,
+ cache_write_tokens=0,
+ uncached_tokens=300_000,
+ output_tokens=5_000,
+ )
+ stats = ct.stats()
+
+ assert abs(stats["output_cost_usd"] - 5_000 * long_output) < 1e-6
+ assert abs(stats["cache_aware_savings_usd"] - 10_000 * long_input) < 1e-6
+
+
+def _summary(cache_net_usd: float, cost_stats: dict) -> dict:
+ from headroom.proxy.cost import build_session_summary
+
+ proxy = SimpleNamespace(
+ config=SimpleNamespace(mode="token"),
+ logger=SimpleNamespace(_logs=[]),
+ cost_tracker=SimpleNamespace(stats=lambda: cost_stats),
+ )
+ metrics = SimpleNamespace(requests_by_model={}, tokens_saved_total=0)
+ prefix_cache_stats = {"totals": {"net_savings_usd": cache_net_usd}}
+ return build_session_summary(proxy, metrics, prefix_cache_stats, total_tokens_before=0)
+
+
+def test_provider_cache_discount_is_reported_beside_the_headline_not_inside_it():
+ payload = _summary(
+ 23.62,
+ {
+ "cost_with_headroom_usd": 7.88,
+ "output_cost_usd": 3.60,
+ "total_cost_usd": 11.48,
+ "savings_usd": 4.20,
+ "cache_aware_savings_usd": 1.05,
+ "tool_savings_usd": 0.25,
+ },
+ )
+ cost = payload["cost"]
+
+ assert cost["total_saved_usd"] == 1.30 # compression (cache-aware) + tool deferral
+ assert cost["provider_cache_discount_usd"] == 23.62
+ assert cost["breakdown"]["compression_savings_usd"] == 1.05
+ assert cost["breakdown"]["compression_savings_list_usd"] == 4.2
+ # Spend is the whole bill, and the baseline is spend + what Headroom saved.
+ assert cost["with_headroom_usd"] == 11.48
+ assert cost["with_headroom_input_usd"] == 7.88
+ assert cost["with_headroom_output_usd"] == 3.6
+ assert cost["without_headroom_usd"] == 12.78
+
+
+def test_summary_falls_back_to_list_pricing_when_cache_aware_is_absent():
+ """An older tracker payload must still produce a coherent card."""
+ payload = _summary(1.0, {"cost_with_headroom_usd": 2.0, "savings_usd": 0.5})
+ cost = payload["cost"]
+
+ assert cost["total_saved_usd"] == 0.5
+ assert cost["with_headroom_usd"] == 2.0
+
+
+def test_prefix_cache_savings_use_the_model_catalog_rates():
+ """Cache economics come from LiteLLM per model, not hardcoded ratios."""
+ from headroom.proxy.cost import build_prefix_cache_stats
+ from headroom.proxy.prometheus_metrics import PrometheusMetrics
+ from headroom.proxy.server import CostTracker
+
+ ct = CostTracker()
+ ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=1_000_000, uncached_tokens=1_000_000)
+
+ metrics = PrometheusMetrics()
+ metrics.cache_by_provider["anthropic"] = {
+ "requests": 10,
+ "hit_requests": 8,
+ "cache_read_tokens": 1_000_000,
+ "cache_write_tokens": 0,
+ "cache_write_5m_tokens": 0,
+ "cache_write_1h_tokens": 0,
+ "cache_write_5m_requests": 0,
+ "cache_write_1h_requests": 0,
+ "uncached_input_tokens": 100_000,
+ "bust_count": 0,
+ "bust_write_tokens": 0,
+ }
+
+ stats = build_prefix_cache_stats(metrics, ct)
+ provider = stats["by_provider"]["anthropic"]
+
+ cache_read, _cache_write, uncached = _prices()
+ expected = 1_000_000 * (uncached - cache_read)
+
+ assert provider["cache_pricing_source"] == "catalog"
+ assert abs(provider["savings_usd"] - expected) < 1e-6
+
+
+def test_dashboard_card_shows_the_cache_discount_separately():
+ from headroom.dashboard import get_dashboard_html
+
+ html = get_dashboard_html()
+
+ assert "provider cache discount" in html
+ assert "cost?.provider_cache_discount_usd" in html