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(pricing): price savings against the cache mix, not flat list price (#3699)

Tejas Chopra89a58fd1526b
diff --git a/benchmarks/agent_cost_benchmark.py b/benchmarks/agent_cost_benchmark.py
index ce38dcb8f..789ddab17 100644
--- a/benchmarks/agent_cost_benchmark.py
+++ b/benchmarks/agent_cost_benchmark.py
@@ -48,6 +48,14 @@ from benchmarks.scenarios.tool_outputs import (
from headroom.transforms.smart_crusher import SmartCrusherConfig, smart_crush_tool_output
# =============================================================================
+#: Share of turns in a steady-state agent session whose prefix is already
+#: cached. A 50-turn session writes its prefix once and reads it on the other
+#: 49 turns, so 0.98 is the arithmetic rather than a guess; the round 0.95 below
+#: leaves room for the TTL expiries a real session hits mid-run. Used ONLY by
+#: this synthetic benchmark -- the proxy never assumes a hit rate, it reads the
+#: provider's reported mix per request (headroom.pricing.counterfactual).
+WARM_CACHE_SHARE = 0.95
+
# PRICING DATA (as of 2025)
# =============================================================================
@@ -77,6 +85,25 @@ PRICING = {
CHARS_PER_TOKEN = 4
+def _warm_savings(tokens_saved: int, pricing: dict) -> float:
+ """Value ``tokens_saved`` for a session whose prefix is mostly already cached.
+
+ The share given by :data:`WARM_CACHE_SHARE` would have been billed as cache
+ READS had those tokens been sent; the rest as ordinary input. For Anthropic
+ that is a 10x difference per token, which is why the cold-only figure this
+ benchmark used to print was the single most misleading number it produced.
+
+ Falls back to the list rate for a pricing row with no cached rate, which is
+ the correct answer for a provider that does not discount cache reads.
+ """
+ if tokens_saved <= 0:
+ return 0.0
+ cached_rate = pricing.get("cached_input", pricing["input"])
+ warm = tokens_saved * WARM_CACHE_SHARE * cached_rate
+ cold = tokens_saved * (1.0 - WARM_CACHE_SHARE) * pricing["input"]
+ return warm + cold
+
+
@dataclass
class CostAnalysis:
"""Cost analysis for a workload."""
@@ -93,6 +120,17 @@ class CostAnalysis:
savings_from_caching: float = 0.0
total_savings_percent: float = 0.0
+ # Compression savings under a WARM cache -- the realistic steady state for
+ # an agent session, where the prefix is written once and read on every
+ # later turn. `savings_from_compression` above is the COLD figure: it
+ # prices every removed token as a cache miss, which is true only for the
+ # first request of a cache window. Reporting the cold number alone
+ # overstates a long session's saving by up to 10x, so both are carried and
+ # the report names which assumption each one is under.
+ savings_from_compression_warm: float = 0.0
+ #: Fraction of turns whose prefix was already cached. See WARM_CACHE_SHARE.
+ cache_profile: str = "cold"
+
@dataclass
class BenchmarkResult:
@@ -221,6 +259,10 @@ def benchmark_coding_agent_explosion() -> BenchmarkResult:
cost_optimized=result.tokens_optimized * pricing["input"],
savings_from_compression=(result.tokens_original - result.tokens_optimized)
* pricing["input"],
+ savings_from_compression_warm=_warm_savings(
+ result.tokens_original - result.tokens_optimized, pricing
+ ),
+ cache_profile="cold+warm",
)
result.cost_analysis.total_savings_percent = result.compression_ratio * 100
@@ -402,6 +444,10 @@ def benchmark_rag_scaling() -> BenchmarkResult:
cost_optimized=result.tokens_optimized * pricing["input"],
savings_from_compression=(result.tokens_original - result.tokens_optimized)
* pricing["input"],
+ savings_from_compression_warm=_warm_savings(
+ result.tokens_original - result.tokens_optimized, pricing
+ ),
+ cache_profile="cold+warm",
total_savings_percent=result.compression_ratio * 100,
)
@@ -605,6 +651,7 @@ def _generate_terminal_report(results: list[BenchmarkResult]) -> str:
lines.append("=" * 80)
total_savings = 0.0
+ total_savings_warm = 0.0
total_baseline = 0.0
for result in results:
@@ -640,12 +687,31 @@ def _generate_terminal_report(results: list[BenchmarkResult]) -> str:
if ca.cost_with_cache > 0:
lines.append(f" Cost (with cache): ${ca.cost_with_cache:>11.4f}")
lines.append(f" Savings: {ca.total_savings_percent:>11.1f}%")
+ if ca.savings_from_compression > 0:
+ # Both assumptions, named. The cold figure prices every removed
+ # token as a cache miss (true only for the first request of a
+ # cache window); the warm one prices them the way a steady-state
+ # agent session is actually billed. Printing only the first is
+ # what made this benchmark's dollar claims unreproducible
+ # against a real invoice.
+ lines.append(f" $ saved (cold cache):${ca.savings_from_compression:>11.4f}")
+ lines.append(
+ f" $ saved (warm cache):{ca.savings_from_compression_warm:>11.4f}"
+ f" <- {WARM_CACHE_SHARE:.0%} of turns hit the prefix cache"
+ )
total_baseline += ca.cost_baseline
if ca.cost_optimized > 0:
total_savings += ca.cost_baseline - ca.cost_optimized
elif ca.cost_with_cache > 0:
total_savings += ca.cost_baseline - ca.cost_with_cache
+ # The warm total is what a steady-state agent session actually
+ # saves. It is tracked alongside the cold one rather than replacing
+ # it so the summary can show the range instead of asserting a point
+ # estimate the reader cannot reproduce from an invoice.
+ total_savings_warm += ca.savings_from_compression_warm or (
+ ca.cost_baseline - ca.cost_optimized if ca.cost_optimized > 0 else 0.0
+ )
# Performance
if result.optimization_latency_ms > 0:
@@ -658,13 +724,24 @@ def _generate_terminal_report(results: list[BenchmarkResult]) -> str:
lines.append("=" * 80)
if total_baseline > 0:
lines.append(f" Total Baseline Cost: ${total_baseline:.4f}")
- lines.append(f" Total Savings: ${total_savings:.4f}")
- lines.append(f" Overall Reduction: {(total_savings / total_baseline) * 100:.1f}%")
+ # A RANGE, not a point. The two ends are the same tokens under the two
+ # cache assumptions; which one a deployment lands on depends on how
+ # much of its prefix is warm, which only its own traffic can say.
+ lines.append(
+ f" Total Savings: ${total_savings_warm:.4f} (warm cache) "
+ f".. ${total_savings:.4f} (cold cache)"
+ )
+ lines.append(
+ f" Overall Reduction: {(total_savings_warm / total_baseline) * 100:.1f}%"
+ f" .. {(total_savings / total_baseline) * 100:.1f}%"
+ )
lines.append("")
- lines.append(" At 1M requests/month:")
+ lines.append(" At 1M requests/month (warm cache -- the steady-state case):")
lines.append(f" Without Headroom: ${total_baseline * 1_000_000:.2f}")
- lines.append(f" With Headroom: ${(total_baseline - total_savings) * 1_000_000:.2f}")
- lines.append(f" Monthly Savings: ${total_savings * 1_000_000:.2f}")
+ lines.append(
+ f" With Headroom: ${(total_baseline - total_savings_warm) * 1_000_000:.2f}"
+ )
+ lines.append(f" Monthly Savings: ${total_savings_warm * 1_000_000:.2f}")
lines.append("")
return "\n".join(lines)
diff --git a/headroom/cli/savings.py b/headroom/cli/savings.py
index 5e72a2eed..ff1bba78d 100644
--- a/headroom/cli/savings.py
+++ b/headroom/cli/savings.py
@@ -38,13 +38,50 @@ def _window_line(label: str, window: dict[str, Any]) -> str:
pct = float(window.get("savings_percent", 0.0) or 0.0)
saved = int(window.get("tokens_saved", 0) or 0)
before = int(window.get("tokens_before", 0) or 0)
- cost = float(window.get("cost_usd", 0.0) or 0.0)
+ # The cache-aware figure is the headline: what the removed tokens would
+ # actually have been billed at. `cost_usd` (flat list price) is shown after
+ # it as the ceiling, and only when the two differ enough to be worth the
+ # ink -- on a cold-cache workload they legitimately coincide.
+ cost = float(window.get("cost_effective_usd", window.get("cost_usd", 0.0)) or 0.0)
+ ceiling = float(window.get("cost_usd", 0.0) or 0.0)
+ money = _money(cost)
+ if ceiling > 0 and abs(ceiling - cost) / ceiling >= 0.01:
+ money = f"{money} (list {_money(ceiling)})"
return (
f"{label:<12} {_bar(pct)} {pct:5.1f}% "
- f"saved {_tokens(saved)} / {_tokens(before)} tokens {_money(cost)}"
+ f"saved {_tokens(saved)} / {_tokens(before)} tokens {money}"
)
+#: What each pricing basis means for a reader deciding how much to trust the
+#: number. Only the weaker ones are worth a line of output -- a catalog-priced
+#: total needs no apology.
+_BASIS_NOTES = {
+ "list": (
+ "Some events are priced at flat list price: either they predate "
+ "cache-aware pricing or their provider reported no cache breakdown. "
+ "The real saving is likely LOWER."
+ ),
+ "no-mix": (
+ "No provider cache breakdown was available, so savings are priced at "
+ "list. The real saving is likely LOWER."
+ ),
+ "unpriced": "Some events could not be priced at all and contribute $0.",
+ "provider-ratio": (
+ "Some models publish no cache pricing; their savings use a "
+ "provider-level ratio rather than a per-model rate."
+ ),
+}
+
+
+def _echo_basis_note(basis: Any) -> None:
+ """Print a caveat when the headline rests on something weaker than the catalog."""
+ note = _BASIS_NOTES.get(str(basis or ""))
+ if note:
+ click.echo("")
+ click.echo(f" note: {note}")
+
+
@main.command(name="savings")
@click.option("--json", "as_json", is_flag=True, help="Emit the raw report as JSON.")
@click.option(
@@ -93,7 +130,10 @@ def savings(as_json: bool, days: int, reset: bool) -> None:
click.echo("")
click.echo("Cost avoided per model:")
for row in report.by_model:
- click.echo(f" {str(row['model']):<24} {_money(float(row['cost_usd']))}")
+ effective = float(row.get("cost_effective_usd", row["cost_usd"]))
+ click.echo(f" {str(row['model']):<24} {_money(effective)}")
+
+ _echo_basis_note(report.lifetime.get("basis"))
if report.by_client:
click.echo("")
diff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.html
index a0d0a8c85..15661140c 100644
--- a/headroom/dashboard/templates/dashboard.html
+++ b/headroom/dashboard/templates/dashboard.html
@@ -1477,7 +1477,7 @@
<div class="grid grid-cols-1 gap-4 mb-6 lg:grid-cols-3">
<section class="bg-surface rounded-lg p-4 border border-border"><h3 class="mb-3 text-sm text-gray-300">Tokens</h3><dl class="space-y-2 text-sm"><div class="flex justify-between"><dt>Input</dt><dd x-text="formatNumber(lifetimeStats.tokens?.input || 0)"></dd></div><div class="flex justify-between"><dt>Output</dt><dd x-text="formatNumber(lifetimeStats.tokens?.output || 0)"></dd></div><div class="flex justify-between"><dt>Attempted Input</dt><dd x-text="formatNumber(lifetimeStats.tokens?.attempted_input || 0)"></dd></div><div class="flex justify-between"><dt>Saved</dt><dd class="text-emerald-400" x-text="formatNumber(lifetimeStats.tokens?.saved || 0)"></dd></div><div class="flex justify-between"><dt>Token Savings</dt><dd x-text="lifetimeStats.tokens?.token_savings_percent == null ? '—' : lifetimeStats.tokens.token_savings_percent.toFixed(1) + '%'"></dd></div></dl></section>
- <section class="bg-surface rounded-lg p-4 border border-border"><h3 class="mb-3 text-sm text-gray-300">Cost</h3><dl class="space-y-2 text-sm"><div class="flex justify-between"><dt>Input cost</dt><dd x-text="'$' + formatCurrency(lifetimeStats.cost?.input_usd || 0)"></dd></div><div class="flex justify-between"><dt>Compression saved</dt><dd class="text-emerald-400" x-text="'$' + formatCurrency(lifetimeStats.cost?.compression_savings_usd || 0)"></dd></div><div class="flex justify-between"><dt>Prefix Cache saved</dt><dd class="text-cyan-400" x-text="'$' + formatCurrency(lifetimeStats.cost?.cache_savings_usd || 0)"></dd></div></dl></section>
+ <section class="bg-surface rounded-lg p-4 border border-border"><h3 class="mb-3 text-sm text-gray-300">Cost</h3><dl class="space-y-2 text-sm"><div class="flex justify-between"><dt>Input cost</dt><dd x-text="'$' + formatCurrency(lifetimeStats.cost?.input_usd || 0)"></dd></div><div class="flex justify-between"><dt title="What the removed tokens would actually have been billed at, given the cache mix of the requests they came out of.">Compression saved</dt><dd class="text-emerald-400" x-text="'$' + formatCurrency(lifetimeStats.cost?.compression_savings_usd || 0)"></dd></div><div class="flex justify-between text-xs text-gray-500" x-show="showSavingsCeiling()"><dt title="The same tokens at flat list price. This is an upper bound: it assumes every removed token would have been a cache MISS, which is true only for the first request of a cache window.">at list price</dt><dd x-text="'$' + formatCurrency(lifetimeStats.cost?.compression_savings_list_usd || 0)"></dd></div><div class="flex justify-between text-xs text-amber-500" x-show="savingsBasisNote()"><dt>basis</dt><dd x-text="savingsBasisNote()"></dd></div><div class="flex justify-between"><dt>Prefix Cache saved</dt><dd class="text-cyan-400" x-text="'$' + formatCurrency(lifetimeStats.cost?.cache_savings_usd || 0)"></dd></div></dl></section>
<section class="bg-surface rounded-lg p-4 border border-border"><h3 class="mb-3 text-sm text-gray-300">Prefix Cache</h3><dl class="space-y-2 text-sm"><div class="flex justify-between"><dt>Hits / requests</dt><dd x-text="formatNumber(lifetimeStats.prefix_cache?.hit_requests || 0) + ' / ' + formatNumber(lifetimeStats.prefix_cache?.requests || 0)"></dd></div><div class="flex justify-between"><dt>Hit rate</dt><dd x-text="lifetimeStats.prefix_cache?.cache_hit_rate == null ? '—' : lifetimeStats.prefix_cache.cache_hit_rate.toFixed(1) + '%'"></dd></div><div class="flex justify-between"><dt>Read / write</dt><dd x-text="formatNumber(lifetimeStats.prefix_cache?.cache_read_tokens || 0) + ' / ' + formatNumber(lifetimeStats.prefix_cache?.cache_write_tokens || 0)"></dd></div><div class="flex justify-between"><dt>TTL 1h / 5m</dt><dd x-text="(lifetimeStats.prefix_cache?.ttl_1h_percent == null ? '—' : lifetimeStats.prefix_cache.ttl_1h_percent.toFixed(0) + '%') + ' / ' + (lifetimeStats.prefix_cache?.ttl_5m_percent == null ? '—' : lifetimeStats.prefix_cache.ttl_5m_percent.toFixed(0) + '%')"></dd></div><div class="flex justify-between"><dt>Cache bust</dt><dd x-text="formatNumber(lifetimeStats.prefix_cache?.bust_count || 0) + ' / ' + formatNumber(lifetimeStats.prefix_cache?.bust_tokens || 0)"></dd></div></dl></section>
</div>
@@ -2297,6 +2297,33 @@
return '0.00';
},
+ // Show the list-price ceiling only when it materially differs from
+ // the cache-aware headline. On a cold-cache workload the two
+ // legitimately coincide and a duplicate row is just noise.
+ showSavingsCeiling() {
+ const eff = this.lifetimeStats.cost?.compression_savings_usd || 0;
+ const list = this.lifetimeStats.cost?.compression_savings_list_usd || 0;
+ if (list <= 0) return false;
+ return Math.abs(list - eff) / list >= 0.01;
+ },
+
+ // Caveat the headline when it rests on something weaker than
+ // per-model catalog rates. A catalog-priced total needs none.
+ savingsBasisNote() {
+ const basis = this.lifetimeStats.cost?.savings_basis;
+ switch (basis) {
+ case 'list':
+ case 'no-mix':
+ return 'list-priced (no cache data) — real saving likely lower';
+ case 'provider-ratio':
+ return 'provider ratio (model publishes no cache pricing)';
+ case 'unpriced':
+ return 'partly unpriced';
+ default:
+ return '';
+ }
+ },
+
formatResetTime(seconds) {
if (seconds == null || seconds <= 0) return 'now';
const h = Math.floor(seconds / 3600);
diff --git a/headroom/observability/metrics.py b/headroom/observability/metrics.py
index 22d5da309..93bdd93ef 100644
--- a/headroom/observability/metrics.py
+++ b/headroom/observability/metrics.py
@@ -458,7 +458,9 @@ class HeadroomOtelMetrics:
uncached_input_tokens: int = 0,
attempted_input_tokens: int = 0,
output_tokens_saved: int = 0,
- savings_usd: Mapping[str, float] | None = None,
+ # Mixed value types: per-layer dollars plus a string `basis` label.
+ # The loop below skips anything non-numeric rather than coercing it.
+ savings_usd: Mapping[str, Any] | None = None,
project: str | None = None,
client: str | None = None,
) -> None:
@@ -482,12 +484,37 @@ class HeadroomOtelMetrics:
self._proxy_attempted_input_tokens.add(attempted_input_tokens, attrs)
if output_tokens_saved > 0:
self._proxy_output_saved_tokens.add(output_tokens_saved, attrs)
+ # ``savings_usd`` is the breakdown from
+ # ``savings_tracker.estimate_request_savings_usd``: per-layer dollars,
+ # plus two companions that must NOT become their own counter series.
+ #
+ # * ``basis`` — a string saying how soundly the layers were priced.
+ # It is a DIMENSION, not a measure, so it rides on the attributes
+ # where a consumer can group by it.
+ # * ``*_list`` — the same layers at flat list price (the upper bound).
+ # Exporting them as sources would make a dashboard summing `source`
+ # report roughly double the real saving, since each layer would
+ # appear twice.
+ #
+ # Anything non-numeric is skipped rather than coerced: this loop used to
+ # call `float()` on every value and would raise on a string, taking the
+ # whole request-metrics path down with it.
+ savings_basis = str((savings_usd or {}).get("basis") or "")[:32]
for source, value in (savings_usd or {}).items():
- amount = max(float(value or 0.0), 0.0)
+ if source == "basis" or str(source).endswith("_list"):
+ continue
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ continue
+ amount = max(float(value), 0.0)
if amount:
self._proxy_savings_usd.add(
amount,
- {**attrs, "source": str(source)[:64], "estimated": True},
+ {
+ **attrs,
+ "source": str(source)[:64],
+ "estimated": True,
+ "basis": savings_basis,
+ },
)
compression_saved = max(tokens_saved, 0)
tool_schema_saved = max(tool_search_saved, 0)
diff --git a/headroom/pricing/counterfactual.py b/headroom/pricing/counterfactual.py
new file mode 100644
index 000000000..6a90205b3
--- /dev/null
+++ b/headroom/pricing/counterfactual.py
@@ -0,0 +1,594 @@
+"""Pricing for tokens Headroom kept OFF the wire.
+
+Every savings figure Headroom reports is a counterfactual: *what would this
+request have cost had we not removed those tokens?* That question has one
+correct answer and one tempting wrong one.
+
+The wrong one — ``tokens_saved * input_cost_per_token`` — is true exactly once,
+for the first request of a cache window. After that the tokens we removed would
+have been served from the provider's prompt cache at a fraction of list price
+(Anthropic 0.10x, OpenAI 0.50x, Gemini 0.10x), so list pricing overstates the
+saving by up to an order of magnitude. Measured on a real 238M-input-token
+corpus that was 87.8% cache reads, list pricing valued the removed tokens at
+2.73x the rate actually paid for the tokens that *were* sent.
+
+The right answer depends on WHERE in the request the removed tokens sat, because
+a prompt is not uniformly priced:
+
+``Region.PREFIX``
+ The stable head of the prompt — tool definitions above all, since providers
+ serialize the tool array before the system prompt and the turns. These are
+ the most cacheable tokens in the entire request: written once, read on every
+ subsequent turn until the TTL lapses. On a warm turn they are cache *reads*,
+ not a pro-rata slice of the request's mix. Splitting them proportionally
+ hands them a share of the 1.25x write bucket they would never have occupied
+ — on a 90/10 read/write request that prices them at 0.215x instead of 0.10x,
+ still ~2x high. :func:`split_tokens` therefore fills the read bucket FIRST
+ (``min(tokens, mix.read)``) and only spills the remainder into write/list.
+
+``Region.LIVE_ZONE``
+ The freshly appended delta at the tail. Handlers freeze the cached prefix
+ byte-for-byte for prefix-cache safety and compress only this region, so the
+ tokens removed here could never have been billed as cache reads — the read
+ bucket belongs to the frozen prefix Headroom did not touch. Pricing these by
+ the whole-request mix values a warm turn's compression at ~0.1x, an order of
+ magnitude UNDER what the provider would have charged. The read bucket is
+ excluded outright.
+
+Both regions inherit the observed request's own cache mix for the buckets they
+do span, which is what makes TTL expiry fall out of real traffic instead of
+being modelled: an expired window shows up as a write-heavy mix on the actual
+request, so the counterfactual re-write is measured per request. That matters
+most for providers that publish no TTL at all (OpenAI) — there is nothing to
+model, only something to observe.
+
+Provider- and harness-agnostic by construction. Rates come from LiteLLM's
+per-model catalog; the structural multipliers in :mod:`headroom.pricing.cache_ttl`
+fill only the gaps the catalog leaves (notably the 1h write rate above the
+200k-context threshold, which no catalog row publishes). A request that reports
+no usable cache breakdown at all — the MCP tool path, a non-reporting gateway, a
+streaming turn with no usage frame — prices at list and says so via
+:attr:`PricedSavings.basis` rather than inventing a mix. Honest and labelled
+beats precise and wrong.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from enum import Enum
+from functools import lru_cache
+from typing import Any
+
+from headroom.pricing.cache_ttl import CACHE_WRITE_MULTIPLIERS
+
+logger = logging.getLogger(__name__)
+
+#: 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
+
+#: Provider-level cache discount ratios, as a fraction of the base input price.
+#: FALLBACK ONLY — the per-model LiteLLM catalog is always preferred, because
+#: these go stale per model and per context tier. Kept here (rather than in
+#: ``proxy/cost.py``, where they used to live) so every consumer shares one copy.
+CACHE_ECONOMICS: dict[str, dict[str, Any]] = {
+ "anthropic": {
+ "read_multiplier": 0.1,
+ "write_multiplier": 1.25,
+ "label": "Explicit breakpoints, 5-min TTL",
+ },
+ "openai": {
+ "read_multiplier": 0.5,
+ "write_multiplier": 1.0,
+ "label": "Automatic, no TTL control",
+ },
+ "gemini": {
+ "read_multiplier": 0.1,
+ "write_multiplier": 1.0,
+ "label": "Explicit cachedContent, configurable TTL",
+ },
+ "bedrock": {
+ "read_multiplier": 0.1,
+ "write_multiplier": 1.25,
+ "label": "Same as Anthropic (Bedrock)",
+ },
+}
+
+
+class Region(str, Enum):
+ """Where in the request the counterfactual tokens would have sat.
+
+ ``str`` mixin so a Region survives a JSON round-trip through the ledger and
+ the telemetry payloads without a custom encoder.
+ """
+
+ #: Stable head of the prompt: tool definitions, system prompt, frozen turns.
+ #: Cache reads first — see the module docstring.
+ PREFIX = "prefix"
+ #: Freshly appended tail. Never a cache read.
+ LIVE_ZONE = "live_zone"
+
+
+#: Why a set of rates is what it is, most to least trustworthy. Surfaced on
+#: every priced figure so a reader can tell a measured number from a guess.
+BASIS_CATALOG = "catalog"
+BASIS_CATALOG_TTL_RATIO = "catalog+ttl-ratio"
+BASIS_PROVIDER_RATIO = "provider-ratio"
+BASIS_LIST = "list"
+BASIS_NO_MIX = "no-mix"
+BASIS_UNPRICED = "unpriced"
+
+#: Ordered worst-to-best. Blending figures of differing provenance reports the
+#: WEAKEST basis present, so one unpriced request cannot launder a total into
+#: looking catalog-grade.
+_BASIS_RANK: dict[str, int] = {
+ BASIS_UNPRICED: 0,
+ BASIS_NO_MIX: 1,
+ BASIS_LIST: 2,
+ BASIS_PROVIDER_RATIO: 3,
+ BASIS_CATALOG_TTL_RATIO: 4,
+ BASIS_CATALOG: 5,
+}
+
+
+def weakest_basis(*bases: str | None) -> str:
+ """Return the least-trustworthy basis among ``bases``.
+
+ An aggregate is only as sound as its worst input, so totals report that
+ rather than the basis of whichever row happened to be priced best.
+ """
+ present = [b for b in bases if b]
+ if not present:
+ return BASIS_UNPRICED
+ return min(present, key=lambda b: _BASIS_RANK.get(b, 0))
+
+
+def _coerce_int(value: Any) -> int:
+ """Non-negative int, defaulting to 0. Never raises."""
+ if isinstance(value, bool):
+ return 0
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return 0
+
+
+@dataclass(frozen=True)
+class CacheMix:
+ """One request's provider-reported input breakdown.
+
+ Every field is optional because provider coverage genuinely differs, and the
+ difference is load-bearing rather than incidental (see
+ ``RequestOutcome``'s cache block, which this mirrors):
+
+ * Anthropic / Bedrock / Vertex — all five: read, write, the 5m/1h write
+ split, and uncached.
+ * OpenAI — read and uncached only. Its ``cached_tokens`` has no companion
+ write counter, so handlers DERIVE a write figure from the uncached slice
+ and set ``inferred_write``. That derived value is the same tokens as
+ ``uncached``, so counting it as a write would double-count it AND apply a
+ write premium OpenAI does not charge. :meth:`normalized` drops it.
+ * Gemini — read only.
+ * MCP tool path, non-reporting gateways, streaming turns with no usage
+ frame — nothing at all, which :meth:`has_signal` reports as False.
+ """
+
+ read: int = 0
+ write_5m: int = 0
+ write_1h: int = 0
+ #: Total writes when the provider reports no TTL split. Only the excess over
+ #: ``write_5m + write_1h`` is used, so passing all three is safe.
+ write_total: int = 0
+ uncached: int = 0
+ #: True when ``write_*`` was derived by Headroom rather than billed by the
+ #: provider. Such writes are dropped entirely — see the class docstring.
+ inferred_write: bool = False
+
+ @classmethod
+ def from_usage(
+ cls,
+ *,
+ cache_read_tokens: Any = 0,
+ cache_write_tokens: Any = 0,
+ cache_write_5m_tokens: Any = 0,
+ cache_write_1h_tokens: Any = 0,
+ uncached_input_tokens: Any = 0,
+ cache_inferred: Any = False,
+ ) -> CacheMix:
+ """Build from the keyword names every proxy call site already uses.
+
+ Keeps the handlers, ``RequestOutcome`` and the metrics path spelling
+ these the one way they always have, so adopting cache-aware pricing is a
+ constructor call rather than a rename across 18 emit sites.
+ """
+ return cls(
+ read=_coerce_int(cache_read_tokens),
+ write_5m=_coerce_int(cache_write_5m_tokens),
+ write_1h=_coerce_int(cache_write_1h_tokens),
+ write_total=_coerce_int(cache_write_tokens),
+ uncached=_coerce_int(uncached_input_tokens),
+ inferred_write=bool(cache_inferred),
+ )
+
+ def normalized(self) -> CacheMix:
+ """Resolve the write buckets into a consistent, billable shape.
+
+ Two corrections, both of which change the money:
+
+ 1. ``inferred_write`` zeroes every write bucket. A derived write is the
+ same tokens as ``uncached`` and carries no provider write premium.
+ 2. A provider that reports a write total but no TTL split (or splits
+ that undershoot the total) has the remainder attributed to 5m — the
+ default TTL a request gets when it does not ask for the extended one.
+ Attributing it to 1h instead would inflate the counterfactual by 60%
+ of the write premium on traffic that never asked for 1h.
+ """
+ if self.inferred_write:
+ return CacheMix(
+ read=self.read,
+ uncached=self.uncached,
+ inferred_write=True,
+ )
+ split = self.write_5m + self.write_1h
+ remainder = max(0, self.write_total - split)
+ return CacheMix(
+ read=self.read,
+ write_5m=self.write_5m + remainder,
+ write_1h=self.write_1h,
+ write_total=split + remainder,
+ uncached=self.uncached,
+ )
+
+ @property
+ def billed(self) -> int:
+ """Total billed input tokens implied by this mix, after normalization."""
+ n = self.normalized()
+ return n.read + n.write_5m + n.write_1h + n.uncached
+
+ def has_signal(self) -> bool:
+ """True when the provider reported enough to price a counterfactual.
+
+ False means list pricing is the only honest answer — reported as
+ ``BASIS_NO_MIX`` rather than silently assuming a cache hit rate.
+ """
+ return self.billed > 0
+
+ def is_long_context(self, *, local_tokens: int = 0) -> bool:
+ """True when this request billed above the catalogs' 200k price tier.
+
+ ``local_tokens`` lets a caller contribute its own forwarded-token count
+ for requests where the provider reported no breakdown; the larger of the
+ two decides, so a long request is never priced at the cheap tier merely
+ because usage was missing.
+ """
+ return max(self.billed, _coerce_int(local_tokens)) > LONG_CONTEXT_THRESHOLD_TOKENS
+
+
+@dataclass(frozen=True)
+class TokenSplit:
+ """Counterfactual tokens apportioned across the buckets that would bill them.
+
+ Floats, not ints: these are *shares* of a request's removed tokens, and
+ rounding each request to whole tokens would bias a long session's total.
+ """
+
+ read: float = 0.0
+ write_5m: float = 0.0
+ write_1h: float = 0.0
+ uncached: float = 0.0
+
+ @property
+ def total(self) -> float:
+ return self.read + self.write_5m + self.write_1h + self.uncached
+
+
+def split_tokens(tokens: int, mix: CacheMix, region: Region | str) -> TokenSplit:
+ """Apportion ``tokens`` across billing buckets for ``region``.
+
+ ``PREFIX`` fills the read bucket first, capped at the read tokens the
+ request actually reported: prefix content sits ahead of every cache
+ breakpoint, so on a warm turn it IS the read. ``LIVE_ZONE`` excludes reads
+ outright — the live zone is appended after the frozen prefix and has never
+ been cached.
+
+ Whatever a region cannot attribute falls to ``uncached`` (list price), which
+ is the conservative direction: it is the most expensive non-write bucket, so
+ an unpriceable request overstates rather than silently zeroes.
+ """
+ tokens = _coerce_int(tokens)
+ if tokens <= 0:
+ return TokenSplit()
+
+ mix = mix.normalized()
+ # Normalize before comparing. `Region` is a str enum, so a caller that
+ # passes the bare string "prefix" compares EQUAL to Region.PREFIX but is not
+ # IDENTICAL to it — and an `is` test would silently route it down the
+ # live-zone branch, pricing a cached prefix as if it had never been cached.
+ # Callers that cannot import Region at module scope (see `proxy/cost.py`,
+ # which must keep litellm off the startup path) pass the string.
+ region = Region(region)
+
+ read_part = float(min(tokens, mix.read)) if region is Region.PREFIX else 0.0
+ rest = tokens - read_part
+ if rest <= 0:
+ return TokenSplit(read=read_part)
+
+ denom = mix.write_5m + mix.write_1h + mix.uncached
+ if denom <= 0:
+ # Nothing left to apportion against. A warm PREFIX turn legitimately
+ # lands here once its reads absorb every token; otherwise this is the
+ # no-signal case and list price is the honest fallback.
+ return TokenSplit(read=read_part, uncached=rest)
+
+ w5 = rest * mix.write_5m / denom
+ w1h = rest * mix.write_1h / denom
+ # Subtract rather than compute independently so the parts sum to `tokens`
+ # exactly, with no float drift accumulating over a long session.
+ return TokenSplit(read=read_part, write_5m=w5, write_1h=w1h, uncached=rest - w5 - w1h)
+
+
+@dataclass(frozen=True)
+class CacheRates:
+ """Per-token prices for each input bucket, plus where they came from."""
+
+ read: float
+ write_5m: float
+ write_1h: float
+ uncached: float
+ basis: str = BASIS_CATALOG
+
+ def price(self, split: TokenSplit) -> float:
+ return (
+ split.read * self.read
+ + split.write_5m * self.write_5m
+ + split.write_1h * self.write_1h
+ + split.uncached * self.uncached
+ )
+
+
+def _litellm() -> Any | None:
+ """Import LiteLLM lazily; absent is a supported configuration, not an error.
+
+ Headroom's own dependency spec excludes litellm on Python 3.14, and gateway
+ deployments often run without it. Callers degrade to list pricing.
+ """
+ try:
+ import litellm
+ except Exception: # pragma: no cover - environment-dependent
+ return None
+ return litellm
+
+
+#: ``resolve_rates`` runs on every priced request and ``model`` comes straight
+#: off a client-supplied request body, so the memo is a BOUNDED LRU, never a
+#: plain dict: a request-facing proxy must not let a caller grow a cache for
+#: free by sending a fresh model string each time. LRU eviction means a model
+#: that stops being sent falls out and simply re-resolves if it returns — a cost
+#: question, never a correctness one. Mirrors the cap
+#: ``savings_tracker._resolve_litellm_model`` already applies for the same
+#: reason (and for the same noisy-probe symptom: LiteLLM prints its "Provider
+#: List" banner on every failed lookup).
+_RATE_CACHE_MAXSIZE = 256
+
+
+@lru_cache(maxsize=_RATE_CACHE_MAXSIZE)
+def resolve_rates(
+ model: str,
+ *,
+ long_context: bool = False,
+ provider: str | None = None,
+) -> CacheRates | None:
+ """Resolve per-bucket input rates for ``model``, or ``None`` if unpriceable.
+
+ Preference order, strongest first:
+
+ 1. **Catalog** — LiteLLM's per-model published rates, including the
+ long-context tier and, where the row has it,
+ ``cache_creation_input_token_cost_above_1hr``. Anthropic publishes a real
+ 1h write rate (Sonnet: 2.00x base), and reading it beats deriving it.
+ 2. **Catalog + TTL ratio** — a catalog row that prices 5m writes but not 1h
+ ones, which is every row at the above-200k tier. The 1h rate is derived
+ from the tier's base input price and the structural multiplier in
+ :mod:`headroom.pricing.cache_ttl`. Only applied when the row shows a real
+ write premium: a provider that does not bill for cache writes at all
+ (OpenAI, Gemini) has no 5m/1h trade to derive, and inventing one would
+ charge them a premium their invoice never shows.
+ 3. **Provider ratio** — :data:`CACHE_ECONOMICS`, for a model the catalog
+ prices for input but not for cache.
+ 4. ``None`` — model unknown to the catalog. The caller falls back to list.
+
+ A model whose input price is legitimately ``0.0`` (a free or local model)
+ returns all-zero rates rather than ``None``: free must cost nothing, not
+ fall through to a blended estimate.
+
+ Memoized — see :data:`_RATE_CACHE_MAXSIZE`. Tests that swap the LiteLLM
+ catalog between cases must call ``resolve_rates.cache_clear()`` in between,
+ or the previous case's rates leak into the next.
+ """
+ litellm = _litellm()
+ if litellm is None:
+ return None
+
+ try:
+ from headroom.pricing.litellm_pricing import resolve_litellm_model
+
+ info = litellm.model_cost.get(resolve_litellm_model(model), {}) or {}
+ except Exception:
+ return None
+
+ base = info.get("input_cost_per_token")
+ # `is None` distinguishes "unknown model" from "genuinely free". `not base`
+ # treated a real 0.0 as unavailable and billed a fallback rate — phantom
+ # savings on a model that costs nothing.
+ if base is None:
+ return None
+ if long_context:
+ base = info.get("input_cost_per_token_above_200k_tokens") or base
+ base = float(base)
+
+ def _tier(field: str, default: float) -> float:
+ """Read ``field``, preferring its above-200k variant on long requests."""
+ if long_context:
+ hi = info.get(f"{field}_above_200k_tokens")
+ if hi:
+ return float(hi)
+ value = info.get(field)
+ return float(value) if value is not None else default
+
+ read = _tier("cache_read_input_token_cost", base)
+ # A provider that does not bill cache writes leaves this absent; writes then
+ # cost the same as ordinary input, which is exactly OpenAI's and Gemini's
+ # actual behaviour.
+ write_5m = _tier("cache_creation_input_token_cost", base)
+
+ basis = BASIS_CATALOG
+ write_1h_raw = info.get("cache_creation_input_token_cost_above_1hr")
+ if long_context:
+ # No catalog publishes a combined 1h + above-200k rate, so the long
+ # tier always derives. Ratio basis, and labelled as such.
+ write_1h_raw = None
+ if write_1h_raw:
+ write_1h = float(write_1h_raw)
+ elif write_5m > base:
+ # Real write premium present but no 1h rate: derive structurally.
+ write_1h = base * CACHE_WRITE_MULTIPLIERS["1h"]
+ basis = BASIS_CATALOG_TTL_RATIO
+ else:
+ # No write premium at all (OpenAI, Gemini). There is no 1h trade to
+ # price; a 1h write costs what any write costs.
+ write_1h = write_5m
+
+ if read == base and write_5m == base and base > 0:
+ # Catalog priced the model but published no cache rates. Fall back to
+ # the provider ratio table if we can identify the provider.
+ econ = CACHE_ECONOMICS.get((provider or "").split(":")[-1].strip().lower())
+ if econ:
+ return CacheRates(
+ read=base * float(econ["read_multiplier"]),
+ write_5m=base * float(econ["write_multiplier"]),
+ write_1h=base * float(econ["write_multiplier"]),
+ uncached=base,
+ basis=BASIS_PROVIDER_RATIO,
+ )
+
+ return CacheRates(read=read, write_5m=write_5m, write_1h=write_1h, uncached=base, basis=basis)
+
+
+@dataclass(frozen=True)
+class PricedSavings:
+ """What a set of counterfactual tokens was worth, and how sure we are.
+
+ ``usd`` is the headline: what the provider would actually have charged for
+ these tokens given the cache mix of the request they were removed from.
+ ``usd_list`` is the same tokens at flat list price — the upper bound, what
+ Headroom reported before this module existed, and the figure budget
+ enforcement keeps using because it is monotonic in tokens and independent of
+ provider reporting.
+
+ ``usd <= usd_list`` always holds for PREFIX savings. It does NOT hold for
+ LIVE_ZONE savings on a cold turn: a token written into an Anthropic cache
+ costs 1.25x list, so removing it saves more than list. That is real money,
+ not an accounting artifact, and clamping it would under-report Headroom.
+ """
+
+ usd: float
+ usd_list: float
+ basis: str
+ tokens: int = 0
+ split: TokenSplit | None = None
+
+ @property
+ def ratio(self) -> float:
+ """``usd / usd_list`` — how far the honest figure sits below list.
+
+ 1.0 means list pricing happened to be right (a fully cold request).
+ Returns 1.0 when there is nothing to compare.
+ """
+ return self.usd / self.usd_list if self.usd_list else 1.0
+
+
+def price_savings(
+ tokens: int,
+ *,
+ model: str,
+ mix: CacheMix | None = None,
+ region: Region = Region.LIVE_ZONE,
+ long_context: bool | None = None,
+ local_tokens: int = 0,
+ provider: str | None = None,
+ fallback_rate_per_token: float | None = None,
+) -> PricedSavings:
+ """Price ``tokens`` that Headroom kept out of one request.
+
+ The single entry point every savings surface should call. ``region`` decides
+ the apportionment (see :func:`split_tokens`), ``mix`` supplies the observed
+ cache breakdown, and ``fallback_rate_per_token`` is the blended rate used
+ when the model cannot be priced at all — the MCP tool path, which never
+ learns the agent's upstream model, depends on it.
+
+ Never raises: a savings figure must not be able to fail a request.
+ """
+ tokens = _coerce_int(tokens)
+ if tokens <= 0:
+ return PricedSavings(usd=0.0, usd_list=0.0, basis=BASIS_CATALOG, tokens=0)
+
+ mix = (mix or CacheMix()).normalized()
+ if long_context is None:
+ long_context = mix.is_long_context(local_tokens=local_tokens)
+
+ try:
+ rates = resolve_rates(model, long_context=long_context, provider=provider)
+ except Exception: # pragma: no cover - defensive; pricing must never raise
+ logger.debug("counterfactual: rate resolution failed for %s", model, exc_info=True)
+ rates = None
+
+ if rates is None:
+ if fallback_rate_per_token is None:
+ return PricedSavings(usd=0.0, usd_list=0.0, basis=BASIS_UNPRICED, tokens=tokens)
+ flat = float(tokens) * float(fallback_rate_per_token)
+ return PricedSavings(usd=flat, usd_list=flat, basis=BASIS_LIST, tokens=tokens)
+
+ usd_list = float(tokens) * rates.uncached
+
+ if not mix.has_signal():
+ # No breakdown to apportion against. List price IS the answer here, but
+ # it is labelled so a reader knows it is a ceiling, not a measurement.
+ return PricedSavings(
+ usd=usd_list,
+ usd_list=usd_list,
+ basis=BASIS_NO_MIX,
+ tokens=tokens,
+ split=TokenSplit(uncached=float(tokens)),
+ )
+
+ split = split_tokens(tokens, mix, region)
+ return PricedSavings(
+ usd=rates.price(split),
+ usd_list=usd_list,
+ basis=rates.basis,
+ tokens=tokens,
+ split=split,
+ )
+
+
+__all__ = [
+ "BASIS_CATALOG",
+ "BASIS_CATALOG_TTL_RATIO",
+ "BASIS_LIST",
+ "BASIS_NO_MIX",
+ "BASIS_PROVIDER_RATIO",
+ "BASIS_UNPRICED",
+ "CACHE_ECONOMICS",
+ "LONG_CONTEXT_THRESHOLD_TOKENS",
+ "CacheMix",
+ "CacheRates",
+ "PricedSavings",
+ "Region",
+ "TokenSplit",
+ "price_savings",
+ "resolve_rates",
+ "split_tokens",
+ "weakest_basis",
+]
diff --git a/headroom/proxy/cost.py b/headroom/proxy/cost.py
index bd11f1465..75db096b8 100644
--- a/headroom/proxy/cost.py
+++ b/headroom/proxy/cost.py
@@ -145,30 +145,47 @@ def _bucket_by_cache_mix(
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.
+ cache_write_5m_tokens: int = 0,
+ cache_write_1h_tokens: int = 0,
+ # A plain string, not a `Region`, so this module keeps its module-scope
+ # imports free of `headroom.pricing` — that package eagerly imports litellm
+ # (~4s) and `cost.py` is on the proxy's startup path. `Region` is a str
+ # enum, so the value round-trips exactly.
+ region: str = "prefix",
+) -> tuple[float, float, float, float]:
+ """Split ``tokens`` into (read, write_5m, write_1h, list) shares.
+
+ Thin adapter over :func:`headroom.pricing.counterfactual.split_tokens`, kept
+ so this module's call sites read the way they always have. Two behaviours
+ changed with the move, both of which move money:
+
+ * ``Region.PREFIX`` now fills the READ bucket first rather than pro-rata.
+ Tool schemas sit ahead of every cache breakpoint, so on a warm turn they
+ are entirely a cache read; a proportional split handed them a slice of the
+ 1.25x write bucket they would never have occupied, pricing them ~2x high.
+ * Writes are split by TTL. The 1h bucket bills at 2.00x base against the 5m
+ bucket's 1.25x, and collapsing them charged every 1h write the 5m rate.
+
+ Callers choose the region, because the two savings layers live in different
+ parts of the request — see the call sites in ``record_tokens``.
+
+ A request with no billed input breakdown falls back to list for the whole
+ amount, exactly as before.
"""
- 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
+ from headroom.pricing.counterfactual import CacheMix, Region, split_tokens
+
+ split = split_tokens(
+ tokens,
+ CacheMix.from_usage(
+ cache_read_tokens=cache_read_tokens,
+ cache_write_tokens=cache_write_tokens,
+ cache_write_5m_tokens=cache_write_5m_tokens,
+ cache_write_1h_tokens=cache_write_1h_tokens,
+ uncached_input_tokens=uncached_tokens,
+ ),
+ Region(region),
+ )
+ return split.read, split.write_5m, split.write_1h, split.uncached
def _summarize_transforms(transforms: list[str]) -> str:
@@ -276,10 +293,18 @@ def build_prefix_cache_stats(
# 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
+ _cr_price, _cw5_price, _cw1h_price, _uncached_price = cache_prices
if _uncached_price:
read_mult = _cr_price / _uncached_price
- write_mult = _cw_price / _uncached_price
+ # Blend the two write rates by the TTL mix this provider
+ # actually wrote at, rather than charging every write the 5m
+ # rate. Falls back to the 5m rate when nothing was written yet.
+ _w1h = max(0, pc["cache_write_1h_tokens"])
+ _w_all = max(0, pc["cache_write_tokens"])
+ _w5 = max(0, _w_all - _w1h)
+ _w_cost = _w5 * _cw5_price + _w1h * _cw1h_price
+ _blended_write = (_w_cost / _w_all) if _w_all > 0 else _cw5_price
+ write_mult = _blended_write / _uncached_price
pricing_source = "catalog"
# Calculate savings:
@@ -836,7 +861,12 @@ class CostTracker:
# 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] = {}
+ # Write shares are kept APART BY TTL: a 1h write bills at 2.00x the base
+ # input rate against a 5m write's 1.25x, so one combined bucket charged
+ # every 1h write the 5m rate. The proxy already counted the 5m/1h split
+ # and displayed it; it simply never priced it.
+ self._saved_write_5m_by_tier: dict[tuple[str, bool], float] = {}
+ self._saved_write_1h_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
@@ -854,7 +884,8 @@ class CostTracker:
# LiteLLM's per-model catalog — so the rates stay provider-agnostic.
# Floats: shares of a request's schema tokens, not whole tokens.
self._tool_saved_read_by_model: dict[str, float] = {}
- self._tool_saved_write_by_model: dict[str, float] = {}
+ self._tool_saved_write_5m_by_model: dict[str, float] = {}
+ self._tool_saved_write_1h_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
@@ -874,11 +905,13 @@ 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_write_5m_by_tier.clear()
+ self._saved_write_1h_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_write_5m_by_model.clear()
+ self._tool_saved_write_1h_by_model.clear()
self._tool_saved_list_by_model.clear()
self._tokens_sent_by_model.clear()
self._output_tokens_by_tier.clear()
@@ -1019,6 +1052,14 @@ class CostTracker:
# 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)
+ # The TTL split must follow the same rule as the total it belongs to:
+ # an inferred write is the same tokens as `uncached_tokens` and was
+ # never billed as a write at any TTL, so its 5m/1h breakdown is not a
+ # breakdown of anything. Zeroing them keeps the mix internally
+ # consistent -- otherwise a provider-less write total of 0 would arrive
+ # alongside nonzero TTL buckets and be re-derived right back.
+ write_5m_eff = 0 if cache_inferred else max(0, cache_write_5m_tokens)
+ write_1h_eff = 0 if cache_inferred else max(0, cache_write_1h_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:
@@ -1033,30 +1074,42 @@ class CostTracker:
# 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(
+ _read, c_w5m, c_w1h, c_list = _bucket_by_cache_mix(
tokens_saved,
cache_read_tokens=0,
cache_write_tokens=write_eff,
+ cache_write_5m_tokens=write_5m_eff,
+ cache_write_1h_tokens=write_1h_eff,
uncached_tokens=uncached_tokens,
+ region="live_zone",
)
wkey = (model, long_context)
- self._saved_write_by_tier[wkey] = self._saved_write_by_tier.get(wkey, 0.0) + c_write
+ self._saved_write_5m_by_tier[wkey] = self._saved_write_5m_by_tier.get(wkey, 0.0) + c_w5m
+ self._saved_write_1h_by_tier[wkey] = self._saved_write_1h_by_tier.get(wkey, 0.0) + c_w1h
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.
- read_part, write_part, list_part = _bucket_by_cache_mix(
+ # Deferred schemas sit in the cached PREFIX, ahead of every cache
+ # breakpoint, so on a warm turn they are entirely a cache read --
+ # not a pro-rata slice of the request's mix. The region argument is
+ # what encodes that; splitting proportionally (as this did) handed
+ # them a share of the write bucket they never would have occupied.
+ read_part, w5m_part, w1h_part, list_part = _bucket_by_cache_mix(
tool_schema_saved,
cache_read_tokens=cache_read_tokens,
cache_write_tokens=write_eff,
+ cache_write_5m_tokens=write_5m_eff,
+ cache_write_1h_tokens=write_1h_eff,
uncached_tokens=uncached_tokens,
+ region="prefix",
)
self._tool_saved_read_by_model[model] = (
self._tool_saved_read_by_model.get(model, 0.0) + read_part
)
- self._tool_saved_write_by_model[model] = (
- self._tool_saved_write_by_model.get(model, 0.0) + write_part
+ self._tool_saved_write_5m_by_model[model] = (
+ self._tool_saved_write_5m_by_model.get(model, 0.0) + w5m_part
+ )
+ self._tool_saved_write_1h_by_model[model] = (
+ self._tool_saved_write_1h_by_model.get(model, 0.0) + w1h_part
)
self._tool_saved_list_by_model[model] = (
self._tool_saved_list_by_model.get(model, 0.0) + list_part
@@ -1276,40 +1329,58 @@ class CostTracker:
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.
+ def _write_cost_usd(self, model: str, w5m_price: float, w1h_price: float) -> float:
+ """Dollar cost of ``model``'s cache writes, split by the TTL they used.
- Returns (cache_read, cache_write, uncached) per-token costs, or None
- if pricing is unavailable. Uses LiteLLM's native cache pricing data.
+ The 1h count is what the provider reported explicitly; everything else
+ in the write total is 5m, which is the TTL a request gets when it does
+ not ask for the extended one. Clamped so a 1h count exceeding the total
+ (a malformed or partial usage frame) cannot manufacture negative 5m
+ tokens and refund money.
- ``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.
+ Previously all writes were charged the 5m rate, which under-bills a 1h
+ write by 60% of its premium — and, because this is the denominator the
+ savings percentages are taken against, quietly flattered every ratio on
+ a session using the extended TTL.
+ """
+ total = max(0, self._api_cache_write_by_model.get(model, 0))
+ w1h = min(max(0, self._api_cache_write_1h_by_model.get(model, 0)), total)
+ w5m = total - w1h
+ return w5m * w5m_price + w1h * w1h_price
+
+ def _get_cache_prices(
+ self, model: str, *, long_context: bool = False
+ ) -> tuple[float, float, float, float] | None:
+ """Per-token prices for (cache read, 5m write, 1h write, uncached input).
+
+ ``None`` when pricing is unavailable. Delegates to
+ :func:`headroom.pricing.counterfactual.resolve_rates`, which is the one
+ place cache rates are resolved — for the live cost card here, the
+ persisted tracker, and the durable ledger alike, so the three cannot
+ drift apart again.
+
+ The 1h write rate is new: LiteLLM publishes it per model as
+ ``cache_creation_input_token_cost_above_1hr`` (Sonnet: 2.00x base), and
+ where a row omits it the structural multiplier in
+ ``headroom.pricing.cache_ttl`` derives it. Previously every 1h write was
+ priced at the 5m rate.
+
+ ``long_context`` picks the above-200k tier for each rate, falling back
+ per rate to the base one for a model that publishes no long-context
+ price.
+
+ Imported at call time: ``headroom.pricing`` eagerly imports litellm
+ (~4s) and this module is on the proxy's startup path.
"""
- litellm = _get_litellm_module()
- if litellm is None:
- return None
try:
- from headroom.pricing.litellm_pricing import resolve_litellm_model
+ from headroom.pricing.counterfactual import resolve_rates
- resolved = resolve_litellm_model(model)
- info = litellm.model_cost.get(resolved, {})
- uncached = info.get("input_cost_per_token")
- if not uncached:
- 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)
+ rates = resolve_rates(model, long_context=long_context)
except Exception:
return None
+ if rates is None or not rates.uncached:
+ return None
+ return (rates.read, rates.write_5m, rates.write_1h, rates.uncached)
def totals(self) -> tuple[int, float]:
"""Return just ``(total_input_tokens, total_input_cost_usd)``.
@@ -1337,9 +1408,13 @@ class CostTracker:
prices = self._get_cache_prices(model)
if prices:
- cr_price, cw_price, uncached_price = prices
+ cr_price, cw5_price, cw1h_price, uncached_price = prices
if cr + cw + uncached > 0:
- cost_with_headroom += cr * cr_price + cw * cw_price + uncached * uncached_price
+ cost_with_headroom += (
+ cr * cr_price
+ + self._write_cost_usd(model, cw5_price, cw1h_price)
+ + uncached * uncached_price
+ )
else:
cost_with_headroom += sent * uncached_price
return total_input_tokens, round(cost_with_headroom, 4)
@@ -1398,10 +1473,15 @@ class CostTracker:
prices = self._get_cache_prices(model)
if prices:
- cr_price, cw_price, uncached_price = prices
+ cr_price, cw5_price, cw1h_price, uncached_price = prices
if cr + cw + uncached > 0:
- # Use API's real cache breakdown with LiteLLM pricing
- model_cost = cr * cr_price + cw * cw_price + uncached * uncached_price
+ # Use API's real cache breakdown with LiteLLM pricing,
+ # writes split by the TTL they were actually written at.
+ model_cost = (
+ cr * cr_price
+ + self._write_cost_usd(model, cw5_price, cw1h_price)
+ + uncached * uncached_price
+ )
billed_tokens = cr + cw + uncached
else:
# No cache data from API — fall back to list price
@@ -1422,7 +1502,7 @@ class CostTracker:
continue
prices = self._get_cache_prices(model)
if prices:
- _cr_price, _cw_price, uncached_price = prices
+ _cr_price, _cw5_price, _cw1h_price, uncached_price = prices
savings_usd += saved * uncached_price
# Completion spend. The input-only figure above is what a budget and the
@@ -1442,14 +1522,19 @@ class CostTracker:
# 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):
+ for key in (
+ set(self._saved_write_5m_by_tier)
+ | set(self._saved_write_1h_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
+ _cr_price, cw5_price, cw1h_price, uncached_price = prices
cache_aware_savings_usd += (
- self._saved_write_by_tier.get(key, 0.0) * cw_price
+ self._saved_write_5m_by_tier.get(key, 0.0) * cw5_price
+ + self._saved_write_1h_by_tier.get(key, 0.0) * cw1h_price
+ self._saved_list_by_tier.get(key, 0.0) * uncached_price
)
@@ -1458,11 +1543,15 @@ class CostTracker:
# as the rest of the request — cold-written once at the provider's
# cache-write rate, read at its cache-read rate on warm turns, and
# re-written on TTL expiry. Each request's schema tokens were bucketed
- # at record time by that request's observed read/write/uncached mix, so
- # expiry cycles are captured from real traffic instead of modelled.
- # Rates come from _get_cache_prices (LiteLLM per-model catalog:
- # cache_read_input_token_cost / cache_creation_input_token_cost, list
- # rate when a provider publishes no cache pricing) — the same
+ # at record time against that request's observed mix, READ-FIRST: the
+ # schemas sit ahead of every cache breakpoint, so a warm turn's are
+ # entirely a cache read rather than a pro-rata slice that would hand
+ # them a write premium they never paid. Expiry cycles still come from
+ # real traffic (an expired window is a write-heavy request) instead of
+ # being modelled.
+ # Rates come from _get_cache_prices (LiteLLM per-model catalog, with
+ # writes split 5m/1h, and the list rate when a provider publishes no
+ # cache pricing) — the same
# provider-agnostic source the real cost math uses, never a hardcoded
# multiplier. Reported as its OWN key rather than widening
# ``savings_usd``: that figure feeds budget enforcement, and the
@@ -1470,17 +1559,19 @@ class CostTracker:
tool_savings_usd = 0.0
tool_models = (
set(self._tool_saved_read_by_model)
- | set(self._tool_saved_write_by_model)
+ | set(self._tool_saved_write_5m_by_model)
+ | set(self._tool_saved_write_1h_by_model)
| set(self._tool_saved_list_by_model)
)
for model in tool_models:
prices = self._get_cache_prices(model)
if not prices:
continue
- cr_price, cw_price, uncached_price = prices
+ cr_price, cw5_price, cw1h_price, uncached_price = prices
tool_savings_usd += (
self._tool_saved_read_by_model.get(model, 0.0) * cr_price
- + self._tool_saved_write_by_model.get(model, 0.0) * cw_price
+ + self._tool_saved_write_5m_by_model.get(model, 0.0) * cw5_price
+ + self._tool_saved_write_1h_by_model.get(model, 0.0) * cw1h_price
+ self._tool_saved_list_by_model.get(model, 0.0) * uncached_price
)
diff --git a/headroom/proxy/outcome.py b/headroom/proxy/outcome.py
index b4c47ffd8..31c443fbd 100644
--- a/headroom/proxy/outcome.py
+++ b/headroom/proxy/outcome.py
@@ -671,6 +671,12 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:
tool_search_saved=tool_search_saved,
local_input_tokens=outcome.optimized_tokens,
savings_attribution=savings_breakdown,
+ # Already handed to the cost tracker below; the metrics path needs it
+ # too now that it prices savings cache-aware. An inferred write is the
+ # same tokens as `uncached_input_tokens` and carries no write premium,
+ # so counting it as a write would both double it and apply a premium
+ # OpenAI never charges.
+ cache_inferred=outcome.cache_inferred,
)
# 2. Cost tracker (optional).
diff --git a/headroom/proxy/persistent_metrics.py b/headroom/proxy/persistent_metrics.py
index 6028fe72c..9804d74a5 100644
--- a/headroom/proxy/persistent_metrics.py
+++ b/headroom/proxy/persistent_metrics.py
@@ -108,7 +108,18 @@ def _empty_state() -> dict[str, Any]:
"misses_by_reason": {},
"by_provider": {},
},
- "cost": {"input_usd": 0.0, "compression_savings_usd": 0.0, "cache_savings_usd": 0.0},
+ # ``compression_savings_usd`` is CACHE-AWARE: what the removed tokens
+ # would actually have been billed at. ``compression_savings_list_usd``
+ # is the same tokens at flat list price — the upper bound, and what the
+ # headline used to be. ``savings_basis`` says how soundly the first of
+ # those was derived (see headroom.pricing.counterfactual).
+ "cost": {
+ "input_usd": 0.0,
+ "compression_savings_usd": 0.0,
+ "compression_savings_list_usd": 0.0,
+ "cache_savings_usd": 0.0,
+ "savings_basis": "unknown",
+ },
"waste_signals": {},
"models": {"tracked": {}, "other": _model_entry()},
"persistence": {"last_saved_at": None},
@@ -119,6 +130,31 @@ def _dict_or_empty(value: Any) -> dict[Any, Any]:
return value if isinstance(value, dict) else {}
+def _blend_savings_basis(existing: Any, incoming: Any) -> str:
+ """Fold one request's pricing basis into the aggregate's label.
+
+ The aggregate is only as sound as its weakest contributing request, so the
+ worst basis seen wins. ``"unknown"`` means "nothing priced yet" and is
+ replaced outright rather than treated as weakest, or a fresh install would
+ report ``unknown`` forever after its first request.
+
+ Never raises, and imports the ranking lazily: ``headroom.pricing`` pulls in
+ litellm (~4s) and this module is on the proxy's startup path.
+ """
+ incoming_label = str(incoming or "").strip()
+ existing_label = str(existing or "").strip() or "unknown"
+ if not incoming_label:
+ return existing_label
+ if existing_label == "unknown" or existing_label == incoming_label:
+ return incoming_label
+ try:
+ from headroom.pricing.counterfactual import weakest_basis
+
+ return weakest_basis(existing_label, incoming_label)
+ except Exception: # pragma: no cover - defensive
+ return existing_label
+
+
class PersistentMetricsState:
"""In-memory Lifetime aggregate with deterministic, bounded dimensions."""
@@ -175,8 +211,29 @@ class PersistentMetricsState:
)
raw_cost = _dict_or_empty(source.get("cost"))
- for key in ("input_usd", "compression_savings_usd", "cache_savings_usd"):
+ for key in (
+ "input_usd",
+ "compression_savings_usd",
+ "compression_savings_list_usd",
+ "cache_savings_usd",
+ ):
result["cost"][key] = round(_coerce_float(raw_cost.get(key)), 6)
+ # A state written before cache-aware pricing has no list column and its
+ # dollars WERE list-priced, so that one figure seeds both and the
+ # aggregate stays honestly labelled.
+ #
+ # The `has_priced_history` guard matters: a FRESH state also has no list
+ # column, and labelling that "list" would tell every new install its
+ # untouched $0.00 total was list-priced. Only a state that actually
+ # accumulated dollars has history to migrate.
+ has_priced_history = result["cost"]["compression_savings_usd"] > 0
+ if "compression_savings_list_usd" in raw_cost:
+ result["cost"]["savings_basis"] = str(raw_cost.get("savings_basis") or "unknown")
+ elif has_priced_history:
+ result["cost"]["compression_savings_list_usd"] = result["cost"][
+ "compression_savings_usd"
+ ]
+ result["cost"]["savings_basis"] = "list"
# Record-time puts unrecognised names in ``other`` (see
# ``record_request``); load-time must do the same, or every restart
# relabels the whole ``other`` bucket as ``unknown`` and the two
@@ -328,6 +385,8 @@ class PersistentMetricsState:
uncached_input_tokens: Any = 0,
input_usd: Any = 0.0,
compression_savings_usd: Any = 0.0,
+ compression_savings_list_usd: Any = None,
+ savings_basis: Any = None,
cache_savings_usd: Any = 0.0,
waste_signals: dict[str, Any] | None = None,
) -> None:
@@ -369,6 +428,19 @@ class PersistentMetricsState:
cost["compression_savings_usd"] = round(
cost["compression_savings_usd"] + _coerce_float(compression_savings_usd), 6
)
+ # Defaults to the cache-aware figure when a caller supplies no ceiling,
+ # which is the truthful reading of "these are the same number" for a
+ # request that had no cache mix to price against.
+ list_delta = (
+ compression_savings_usd
+ if compression_savings_list_usd is None
+ else compression_savings_list_usd
+ )
+ cost["compression_savings_list_usd"] = round(
+ _coerce_float(cost.get("compression_savings_list_usd")) + _coerce_float(list_delta), 6
+ )
+ if savings_basis:
+ cost["savings_basis"] = _blend_savings_basis(cost.get("savings_basis"), savings_basis)
cost["cache_savings_usd"] = round(
cost["cache_savings_usd"] + _coerce_float(cache_savings_usd), 6
)
diff --git a/headroom/proxy/prometheus_metrics.py b/headroom/proxy/prometheus_metrics.py
index 6bc838b67..b0252f008 100644
--- a/headroom/proxy/prometheus_metrics.py
+++ b/headroom/proxy/prometheus_metrics.py
@@ -755,6 +755,13 @@ class PrometheusMetrics:
tool_search_saved: int = 0,
local_input_tokens: int | None = None,
savings_attribution: list[dict[str, Any]] | None = None,
+ # True when ``cache_write_tokens`` was DERIVED by a handler rather than
+ # billed by the provider (OpenAI exposes no write counter). Such a
+ # "write" is the same tokens as ``uncached_input_tokens`` and carries no
+ # write premium, so counterfactual pricing must drop it — see
+ # ``CacheMix.normalized``. Defaults False, preserving behaviour for the
+ # providers that report disjoint buckets.
+ cache_inferred: bool = False,
):
"""Record metrics for a request.
@@ -782,12 +789,28 @@ class PrometheusMetrics:
model,
)
tokens_saved = 0
+ # Priced CACHE-AWARE: the full provider breakdown goes in, and each
+ # layer is valued against the region of the request it actually came
+ # out of — compression against the live zone, tool-schema deferral
+ # against the cached prefix. The breakdown is already on this method's
+ # signature for every provider (see RequestOutcome's cache block); it
+ # simply was not reaching the pricer, so both layers were billed at flat
+ # list price regardless of how much of the prompt was a cache read.
savings_usd = estimate_request_savings_usd(
model,
compression_tokens_saved=tokens_saved,
tool_schema_tokens_saved=tool_search_saved,
output_tokens_saved=output_tokens_saved,
cache_read_tokens=cache_read_tokens,
+ cache_write_tokens=cache_write_tokens,
+ cache_write_5m_tokens=cache_write_5m_tokens,
+ cache_write_1h_tokens=cache_write_1h_tokens,
+ uncached_input_tokens=uncached_input_tokens,
+ cache_inferred=cache_inferred,
+ # Locally-counted forwarded tokens, used only to decide the
+ # above-200k price tier when the provider reported no breakdown.
+ local_input_tokens=ledger_input_tokens,
+ provider=provider,
)
async with self._lock:
self.requests_total += 1
@@ -928,6 +951,7 @@ class PrometheusMetrics:
cache_write_5m_tokens=cache_write_5m_tokens,
cache_write_1h_tokens=cache_write_1h_tokens,
uncached_input_tokens=uncached_input_tokens,
+ cache_inferred=cache_inferred,
waste_signals=waste_signals,
)
total_input_tokens, total_input_cost_usd = self._current_savings_tracker_totals()
@@ -1004,6 +1028,26 @@ class PrometheusMetrics:
model=model,
client=client or "proxy",
source="proxy",
+ # The two layers, kept APART on disk. They price against
+ # different regions of the request (live zone vs cached prefix)
+ # and therefore at different rates, so a ledger that stores only
+ # their sum can never be re-priced correctly — which is exactly
+ # why the pre-v2 ledger could not be corrected in place.
+ saved_compression=tokens_saved,
+ saved_tool_schema=deferral_saved,
+ # The observed cache mix. Storing the MIX rather than only the
+ # dollar it produced is the point of ledger v2: a stored dollar
+ # bakes in whatever basis was current when it was written, and
+ # every historical figure is then frozen wrong. Providers that
+ # report nothing leave these zero and the event prices at list,
+ # labelled `no-mix`.
+ cache_read_tokens=cache_read_tokens,
+ cache_write_5m_tokens=cache_write_5m_tokens,
+ cache_write_1h_tokens=cache_write_1h_tokens,
+ cache_write_tokens=cache_write_tokens,
+ uncached_input_tokens=uncached_input_tokens,
+ cache_inferred=cache_inferred,
+ provider=provider,
)
otel_metrics = self._get_otel_metrics()
diff --git a/headroom/proxy/savings_tracker.py b/headroom/proxy/savings_tracker.py
index 8f3fbd57b..37627b54b 100644
--- a/headroom/proxy/savings_tracker.py
+++ b/headroom/proxy/savings_tracker.py
@@ -34,7 +34,21 @@ logger = logging.getLogger(__name__)
HEADROOM_SAVINGS_PATH_ENV_VAR = _paths.HEADROOM_SAVINGS_PATH_ENV
DEFAULT_SAVINGS_DIR = ".headroom"
DEFAULT_SAVINGS_FILE = "proxy_savings.json"
-SCHEMA_VERSION = 5
+# v6: ``compression_savings_usd`` changed BASIS (not shape). It now holds the
+# cache-aware counterfactual — what the removed tokens would actually have been
+# billed at, given the cache mix of the requests they came out of — instead of
+# flat list price. ``compression_savings_list_usd`` carries the old list-priced
+# figure alongside it as the upper bound.
+#
+# The basis flip is deliberately made in place rather than in a new field. The
+# mix was never persisted, so pre-v6 dollars cannot be re-derived either way;
+# a parallel field would have to be SEEDED from the same list-priced history and
+# would blend exactly as much, only in a field nothing reads. Flipping in place
+# means every existing surface (dashboard tiles, per-model table, per-project
+# rows, the history chart) reports the right number with no change of its own.
+# ``savings_basis_migrated_at`` records when the flip happened so a reader can
+# tell which part of a lifetime total predates it.
+SCHEMA_VERSION = 6
DEFAULT_MAX_HISTORY_POINTS = 5000
DEFAULT_MAX_PROJECTS = 50
DEFAULT_MAX_HISTORY_AGE_DAYS = 365
@@ -44,10 +58,51 @@ DEFAULT_FALLBACK_INPUT_COST_PER_TOKEN = 3.0 / 1_000_000
# Blended output price used only when litellm cannot price the model.
DEFAULT_FALLBACK_OUTPUT_COST_PER_TOKEN = 15.0 / 1_000_000
+#: Basis label for a total that has not priced a single request yet. Not one of
+#: ``counterfactual``'s BASIS_* values on purpose: those all describe how a real
+#: figure was derived, and "no figure yet" is not a derivation. Treated as
+#: absent by :func:`_blend_basis`, so the first priced request sets the label
+#: outright instead of being dragged down to it forever.
+BASIS_UNKNOWN = "unknown"
+
+#: Basis stamped on state migrated from a schema older than v6. Those dollars
+#: were accumulated at flat list price and the cache mix that produced them was
+#: never persisted, so they cannot be re-derived — the total stays honestly
+#: labelled as containing list-priced history for the life of the install.
+BASIS_LIST = "list"
+
LITELLM_AVAILABLE = importlib.util.find_spec("litellm") is not None
litellm: Any | None = None
+def _blend_basis(existing: Any, incoming: Any) -> str:
+ """Fold one request's pricing basis into a running total's label.
+
+ A total is only as sound as its weakest contributing request, so this keeps
+ the worst basis seen. ``BASIS_UNKNOWN`` means "nothing priced yet" and is
+ replaced outright rather than treated as the weakest — otherwise a fresh
+ install would report ``unknown`` forever after its first request.
+
+ Ranking lives in ``counterfactual``; importing it here is deferred for the
+ same startup reason as ``estimate_request_savings_usd``, and a missing
+ incoming label leaves the existing one alone.
+ """
+ incoming_label = str(incoming or "").strip()
+ existing_label = str(existing or "").strip() or BASIS_UNKNOWN
+ if not incoming_label:
+ return existing_label
+ if existing_label == BASIS_UNKNOWN:
+ return incoming_label
+ if incoming_label == existing_label:
+ return existing_label
+ try:
+ from headroom.pricing.counterfactual import weakest_basis
+
+ return weakest_basis(existing_label, incoming_label)
+ except Exception: # pragma: no cover - defensive; labelling must not raise
+ return existing_label
+
+
def _get_litellm_module() -> Any | None:
"""Import LiteLLM only when cost metadata is requested."""
global litellm
@@ -336,27 +391,98 @@ def estimate_request_savings_usd(
tool_schema_tokens_saved: int = 0,
output_tokens_saved: int = 0,
cache_read_tokens: int = 0,
-) -> dict[str, float]:
+ cache_write_tokens: int = 0,
+ cache_write_5m_tokens: int = 0,
+ cache_write_1h_tokens: int = 0,
+ uncached_input_tokens: int = 0,
+ cache_inferred: bool = False,
+ local_input_tokens: int = 0,
+ provider: str | None = None,
+) -> dict[str, Any]:
"""Price one request's distinct savings layers for external telemetry.
- The values use the same pricing functions as the built-in dashboard. They
- stay separate because provider-cache benefit is not caused by compression,
- and extension attribution can be explanatory rather than additive.
+ The layers stay separate because provider-cache benefit is not caused by
+ compression, and extension attribution can be explanatory rather than
+ additive.
+
+ The two input-side layers are priced CACHE-AWARE, each against the region of
+ the request it actually came out of (see
+ :mod:`headroom.pricing.counterfactual`):
+
+ * ``compression`` — live-zone content, which was never a cache read.
+ * ``tool_schema`` — prefix content, which on a warm turn was *entirely* a
+ cache read.
+
+ Both also report a ``*_list`` companion: the same tokens at flat list price.
+ That is the upper bound, the figure this function used to return for both
+ layers, and what budget enforcement keeps consuming because it is monotonic
+ in tokens and needs no provider cooperation. ``basis`` says how sound the
+ cache-aware numbers are — see the BASIS_* constants.
+
+ Passing no cache breakdown at all is fully supported and is what every
+ non-reporting harness and the MCP tool path do: the effective figures then
+ equal the list figures and ``basis`` reads ``no-mix``.
"""
+ # Imported at CALL time, not module scope. `headroom.pricing.__init__`
+ # eagerly imports litellm, which measures 4.1s — and savings_tracker is
+ # imported during proxy startup, so a module-level import here would put
+ # that on every boot. No request can be priced without litellm anyway, so
+ # deferring to the first priced request costs nothing and keeps startup
+ # unchanged. Repeat calls are a `sys.modules` dict hit. Same idiom as
+ # `_resolve_litellm_model` below.
+ from headroom.pricing.counterfactual import (
+ CacheMix,
+ PricedSavings,
+ Region,
+ price_savings,
+ weakest_basis,
+ )
+
+ mix = CacheMix.from_usage(
+ cache_read_tokens=cache_read_tokens,
+ cache_write_tokens=cache_write_tokens,
+ cache_write_5m_tokens=cache_write_5m_tokens,
+ cache_write_1h_tokens=cache_write_1h_tokens,
+ uncached_input_tokens=uncached_input_tokens,
+ cache_inferred=cache_inferred,
+ )
+ long_context = mix.is_long_context(local_tokens=local_input_tokens)
+
+ def _price(tokens: Any, region: Region) -> PricedSavings:
+ return price_savings(
+ max(_coerce_int(tokens), 0),
+ model=model,
+ mix=mix,
+ region=region,
+ long_context=long_context,
+ provider=provider,
+ # Matches the blended rate the flat estimators fall back to, so an
+ # unpriceable model reports the same dollars it always has.
+ fallback_rate_per_token=DEFAULT_FALLBACK_INPUT_COST_PER_TOKEN,
+ )
+
+ compression = _price(compression_tokens_saved, Region.LIVE_ZONE)
+ tool_schema = _price(tool_schema_tokens_saved, Region.PREFIX)
+
return {
- "compression": _estimate_compression_savings_usd(
- model, max(_coerce_int(compression_tokens_saved), 0)
- ),
- "tool_schema": _estimate_compression_savings_usd(
- model, max(_coerce_int(tool_schema_tokens_saved), 0)
- ),
+ "compression": compression.usd,
+ "compression_list": compression.usd_list,
+ "tool_schema": tool_schema.usd,
+ "tool_schema_list": tool_schema.usd_list,
"output_shaping": _estimate_output_savings_usd(
model, max(_coerce_int(output_tokens_saved), 0)
),
"provider_cache": _estimate_cache_savings_usd(
model, max(_coerce_int(cache_read_tokens), 0)
),
+ # An aggregate is only as sound as its weakest input, so a request whose
+ # tool-schema layer priced from the catalog but whose compression layer
+ # had no mix to work with reports the weaker of the two.
+ "basis": weakest_basis(
+ compression.basis if compression.tokens else None,
+ tool_schema.basis if tool_schema.tokens else None,
+ ),
}
@@ -487,6 +613,8 @@ def _empty_display_session() -> dict[str, Any]:
"requests": 0,
"tokens_saved": 0,
"compression_savings_usd": 0.0,
+ "compression_savings_list_usd": 0.0,
+ "savings_basis": BASIS_UNKNOWN,
"cache_read_tokens": 0,
"cache_savings_usd": 0.0,
"total_input_tokens": 0,
@@ -602,13 +730,27 @@ def _normalize_display_session(entry: Any) -> dict[str, Any]:
2,
)
+ # Presence of the list column is what distinguishes a v6+ session from one
+ # written before cache-aware pricing existed. A pre-v6 session's single
+ # dollar figure WAS the list figure, so it seeds both columns exactly, and
+ # the session is labelled `list` because its mix was never persisted and
+ # cannot be recovered. Written out rather than inlined into the dict below:
+ # a money path should not hinge on the reader parsing a nested ternary.
+ is_pre_v6 = "compression_savings_list_usd" not in entry
+ savings_usd = _coerce_float(entry.get("compression_savings_usd"))
+ if is_pre_v6:
+ savings_list_usd = savings_usd
+ savings_basis = BASIS_LIST
+ else:
+ savings_list_usd = _coerce_float(entry.get("compression_savings_list_usd"))
+ savings_basis = str(entry.get("savings_basis") or BASIS_UNKNOWN)
+
return {
"requests": _coerce_int(entry.get("requests")),
"tokens_saved": tokens_saved,
- "compression_savings_usd": round(
- _coerce_float(entry.get("compression_savings_usd")),
- 6,
- ),
+ "compression_savings_usd": round(savings_usd, 6),
+ "compression_savings_list_usd": round(savings_list_usd, 6),
+ "savings_basis": savings_basis,
"cache_read_tokens": _coerce_int(entry.get("cache_read_tokens")),
"cache_savings_usd": round(
_coerce_float(entry.get("cache_savings_usd")),
@@ -766,7 +908,10 @@ class SavingsTracker:
uncached_input_tokens: int = 0,
total_input_tokens: int | None = None,
total_input_cost_usd: float | None = None,
- estimated_savings_usd: Mapping[str, float] | None = None,
+ # Mixed value types: per-layer dollars plus the string `basis` label
+ # that says how soundly they were priced. See
+ # ``estimate_request_savings_usd``, which produces it.
+ estimated_savings_usd: Mapping[str, Any] | None = None,
timestamp: datetime | str | None = None,
) -> bool:
"""Persist a canonical display-session update for every request."""
@@ -804,13 +949,29 @@ class SavingsTracker:
# statement rather than folded into the ternary below — a money path
# should not depend on the reader knowing that ``a + b if c else d``
# groups as ``(a + b) if c else d``.
+ #
+ # As of v6 these two arrive CACHE-AWARE and region-correct: the
+ # compression bucket priced against the live zone (never a cache
+ # read) and the tool-schema bucket against the prefix (on a warm
+ # turn, entirely a cache read). Neither is clamped at zero any more
+ # than it was — but note the floor below is load-bearing in a new
+ # way, since a live-zone token on a cold Anthropic turn is worth
+ # 1.25x list, not 1.0x, and that is real money rather than an
+ # artifact.
delta_savings_usd = max(_coerce_float(priced.get("compression")), 0.0) + max(
_coerce_float(priced.get("tool_schema")), 0.0
)
+ delta_savings_list_usd = max(_coerce_float(priced.get("compression_list")), 0.0) + max(
+ _coerce_float(priced.get("tool_schema_list")), 0.0
+ )
+ delta_basis = priced.get("basis")
else:
# No priced breakdown available: only message savings are known here,
- # so this path stays message-only exactly as before.
+ # so this path stays message-only exactly as before — and at list
+ # price, which is what "no mix to price against" honestly means.
delta_savings_usd = _estimate_compression_savings_usd(model, delta_tokens_saved)
+ delta_savings_list_usd = delta_savings_usd
+ delta_basis = BASIS_LIST if delta_tokens_saved > 0 else None
delta_output_savings_usd = (
max(_coerce_float(priced.get("output_shaping")), 0.0)
if priced is not None
@@ -866,6 +1027,12 @@ class SavingsTracker:
lifetime["compression_savings_usd"] + delta_savings_usd,
6,
)
+ lifetime["compression_savings_list_usd"] = round(
+ _coerce_float(lifetime.get("compression_savings_list_usd"))
+ + delta_savings_list_usd,
+ 6,
+ )
+ lifetime["savings_basis"] = _blend_basis(lifetime.get("savings_basis"), delta_basis)
lifetime["cache_read_tokens"] += delta_cache_read_tokens
lifetime["cache_savings_usd"] = round(
lifetime["cache_savings_usd"] + delta_cache_savings_usd,
@@ -897,6 +1064,11 @@ class SavingsTracker:
session["compression_savings_usd"] + delta_savings_usd,
6,
)
+ session["compression_savings_list_usd"] = round(
+ _coerce_float(session.get("compression_savings_list_usd")) + delta_savings_list_usd,
+ 6,
+ )
+ session["savings_basis"] = _blend_basis(session.get("savings_basis"), delta_basis)
session["cache_read_tokens"] += delta_cache_read_tokens
session["cache_savings_usd"] = round(
session["cache_savings_usd"] + delta_cache_savings_usd,
@@ -975,6 +1147,13 @@ class SavingsTracker:
cache_read_tokens = _coerce_int(metrics.get("cache_read_tokens"))
cache_write_tokens = _coerce_int(metrics.get("cache_write_tokens"))
uncached_input_tokens = _coerce_int(metrics.get("uncached_input_tokens"))
+ # POPPED, not read: `metrics` is forwarded verbatim to
+ # `PersistentMetricsState.record_request`, whose signature is an
+ # explicit keyword list with no **kwargs. `cache_inferred` is a pricing
+ # input (it tells the counterfactual to drop a write bucket the
+ # provider never billed), not a metric that aggregate stores, so it
+ # must not survive into that call.
+ cache_inferred = bool(metrics.pop("cache_inferred", False))
metrics.setdefault(
"input_usd",
_estimate_input_cost_usd(
@@ -985,10 +1164,28 @@ class SavingsTracker:
uncached_input_tokens=uncached_input_tokens,
),
)
- metrics.setdefault(
- "compression_savings_usd",
- _estimate_compression_savings_usd(model, _coerce_int(metrics.get("tokens_saved"))),
- )
+ # Cache-aware, like every other savings figure as of v6. ``tokens_saved``
+ # here is message compression, so it prices against the LIVE ZONE — the
+ # region handlers actually compress, and the one region that can never
+ # have been a cache read. The caller (prometheus_metrics.record_request)
+ # already hands us the full breakdown, so no new plumbing is needed;
+ # a caller that omits it degrades to list price and says so.
+ if "compression_savings_usd" not in metrics:
+ priced = estimate_request_savings_usd(
+ model,
+ compression_tokens_saved=_coerce_int(metrics.get("tokens_saved")),
+ cache_read_tokens=cache_read_tokens,
+ cache_write_tokens=cache_write_tokens,
+ cache_write_5m_tokens=_coerce_int(metrics.get("cache_write_5m_tokens")),
+ cache_write_1h_tokens=_coerce_int(metrics.get("cache_write_1h_tokens")),
+ uncached_input_tokens=uncached_input_tokens,
+ cache_inferred=cache_inferred,
+ local_input_tokens=input_tokens,
+ provider=metrics.get("provider"),
+ )
+ metrics["compression_savings_usd"] = priced["compression"]
+ metrics["compression_savings_list_usd"] = priced["compression_list"]
+ metrics["savings_basis"] = priced["basis"]
metrics.setdefault(
"cache_savings_usd", _estimate_cache_savings_usd(model, cache_read_tokens)
)
@@ -1292,6 +1489,8 @@ class SavingsTracker:
"requests": 0,
"tokens_saved": 0,
"compression_savings_usd": 0.0,
+ "compression_savings_list_usd": 0.0,
+ "savings_basis": BASIS_UNKNOWN,
"cache_read_tokens": 0,
"cache_savings_usd": 0.0,
"total_input_tokens": 0,
@@ -1358,6 +1557,10 @@ class SavingsTracker:
lifetime_cache_savings_usd = 0.0
lifetime_input_tokens = 0
lifetime_input_cost_usd = 0.0
+ lifetime_savings_list_usd = 0.0
+ lifetime_basis = BASIS_UNKNOWN
+ migrated_at = None
+ is_v6_lifetime = False
if isinstance(lifetime_raw, dict):
lifetime_requests = _coerce_int(lifetime_raw.get("requests"))
lifetime_tokens_saved = _coerce_int(lifetime_raw.get("tokens_saved"))
@@ -1366,6 +1569,13 @@ class SavingsTracker:
lifetime_cache_savings_usd = _coerce_float(lifetime_raw.get("cache_savings_usd"))
lifetime_input_tokens = _coerce_int(lifetime_raw.get("total_input_tokens"))
lifetime_input_cost_usd = _coerce_float(lifetime_raw.get("total_input_cost_usd"))
+ migrated_at = lifetime_raw.get("savings_basis_migrated_at")
+ is_v6_lifetime = "compression_savings_list_usd" in lifetime_raw
+ if is_v6_lifetime:
+ lifetime_savings_list_usd = _coerce_float(
+ lifetime_raw.get("compression_savings_list_usd")
+ )
+ lifetime_basis = str(lifetime_raw.get("savings_basis") or BASIS_UNKNOWN)
if normalized_history:
last = normalized_history[-1]
@@ -1386,12 +1596,35 @@ class SavingsTracker:
_coerce_float(last.get("total_input_cost_usd")),
)
+ # v6 migration seed. Runs HERE, after the history back-fill above, not
+ # beside the lifetime read: a state whose `lifetime` block is missing or
+ # empty still recovers its totals from the last history point, and
+ # seeding before that ran left the list column at 0 while the effective
+ # column carried the recovered dollars — a total that reads as a 100%
+ # cache-aware saving on data that was entirely list-priced.
+ #
+ # Everything a pre-v6 install accumulated was flat list price, so it
+ # seeds BOTH columns: for that history they genuinely are the same
+ # number. The cache mix that would let us re-derive the honest value was
+ # never persisted — which is the whole reason v6 exists — so the total
+ # stays labelled `list` for the life of the install, and
+ # `savings_basis_migrated_at` marks where the honest numbers begin.
+ if not is_v6_lifetime and (lifetime_requests or lifetime_savings_usd):
+ lifetime_savings_list_usd = lifetime_savings_usd
+ lifetime_basis = BASIS_LIST
+ if not migrated_at:
+ migrated_at = _to_utc_iso(_utc_now())
+ self._needs_schema_save = True
+
state = {
"schema_version": SCHEMA_VERSION,
"lifetime": {
"requests": lifetime_requests,
"tokens_saved": lifetime_tokens_saved,
"compression_savings_usd": round(lifetime_savings_usd, 6),
+ "compression_savings_list_usd": round(lifetime_savings_list_usd, 6),
+ "savings_basis": lifetime_basis,
+ "savings_basis_migrated_at": migrated_at,
"cache_read_tokens": lifetime_cache_read_tokens,
"cache_savings_usd": round(lifetime_cache_savings_usd, 6),
"total_input_tokens": lifetime_input_tokens,
diff --git a/headroom/savings_ledger.py b/headroom/savings_ledger.py
index 7cb33c2b6..8e3c6bb37 100644
--- a/headroom/savings_ledger.py
+++ b/headroom/savings_ledger.py
@@ -13,6 +13,29 @@ model pricing changes later. litellm list pricing is used where the model is
known; a blended input-token rate is used as a fallback (MCP-tool compressions
do not know the agent's upstream model, so they record ``model="unknown"`` and
fall back to the blended rate rather than recording ``$0``).
+
+Schema v2 additionally records the SHAPE of each event, not just the dollar it
+produced:
+
+* ``saved_compression`` / ``saved_tool_schema`` — the two savings layers kept
+ apart. They sit in different regions of the prompt and price at different
+ rates (see :mod:`headroom.pricing.counterfactual`), so an event storing only
+ their sum cannot be priced correctly at all.
+* ``cache`` — the request's observed read/write/uncached mix.
+* ``cost_effective_usd`` — the cache-aware figure, alongside the unchanged
+ list-priced ``cost_usd``.
+
+That distinction is what v1 got wrong and could not recover from. v1 stored one
+list-priced dollar and no mix, so its historical numbers were not merely
+overstated — they were *unfixable*, because nothing on disk said what fraction
+of the removed tokens would have been cache reads. Write-time pricing keeps its
+original virtue (numbers do not drift when a price list changes) without the
+vice (numbers cannot be corrected when the BASIS was wrong): the inputs are on
+disk, so a future basis change can re-derive the whole ledger.
+
+v1 events still read: they report their stored list dollar as both figures and
+carry ``basis="list"``, so a mixed ledger stays legible rather than silently
+blending two meanings.
"""
from __future__ import annotations
@@ -45,9 +68,14 @@ try:
except ImportError:
_HAS_FCNTL = False
-SCHEMA_VERSION = 1
+SCHEMA_VERSION = 2
UNKNOWN = "unknown"
+#: Basis recorded on a v1 event read back today: list-priced, mix unknown and
+#: unrecoverable. Mirrors ``counterfactual.BASIS_LIST`` without importing it —
+#: see ``_price_event`` for why that import is deferred.
+BASIS_LIST = "list"
+
# Report windows never look back further than 30 days, and events older than
# this are pruned from disk, keeping the JSONL small.
MAX_RETENTION_DAYS = 30
@@ -60,6 +88,12 @@ DEFAULT_FALLBACK_INPUT_COST_PER_TOKEN = 3.0 / 1_000_000
# also enforced on read, so accuracy never depends on compaction having run.
# Small because retention is only 30 days — the file should never be large.
_COMPACT_SIZE_BYTES = 1 * 1024 * 1024
+# How much the ledger must grow before a process that found nothing to compact
+# tries again. See _maybe_compact for why this exists.
+_COMPACT_GROWTH_BYTES = 1 * 1024 * 1024
+# Per-process floor for the next compaction attempt. Starts at the threshold and
+# ratchets up while compaction has nothing to drop; reset once it does.
+_compact_min_size = _COMPACT_SIZE_BYTES
def _utc_now() -> datetime:
@@ -116,6 +150,110 @@ def estimate_cost_usd(
return round(float(tokens_saved) * float(fallback_rate), 6)
+def _nonneg_int(value: Any) -> int:
+ """Non-negative int, defaulting to 0. Never raises."""
+ if isinstance(value, bool):
+ return 0
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return 0
+
+
+def _coerce_split(saved: int, compression: Any, tool_schema: Any) -> tuple[int, int] | None:
+ """Reconcile a caller's savings split against the authoritative ``saved``.
+
+ ``saved`` is derived from ``before - after`` and is what every existing
+ reader sums, so the split must add up to it exactly or the two views of one
+ event disagree. Rather than trust the caller, the compression share absorbs
+ any discrepancy: tool-schema deferral is the number a handler measures
+ directly (it counted the schemas it withheld), while compression is the
+ residual by construction.
+
+ Returns ``None`` when the caller supplied no split at all, which is how an
+ MCP-tool event and every v1 event are represented.
+ """
+ if compression is None and tool_schema is None:
+ return None
+ tool = min(_nonneg_int(tool_schema), saved)
+ return saved - tool, tool
+
+
+def _price_event(
+ event: dict[str, Any],
+ *,
+ fallback_rate: float = DEFAULT_FALLBACK_INPUT_COST_PER_TOKEN,
+) -> tuple[float, float, str] | None:
+ """Price one event's two layers. Returns ``(effective, list, basis)``.
+
+ ``None`` if unpriceable.
+
+ Each layer is valued against the region of the prompt it came out of —
+ compression against the live zone, tool-schema deferral against the cached
+ prefix — using the mix stored on the event itself. That is what makes a v2
+ ledger re-derivable: the inputs are on disk, so this function can change
+ without the history becoming a lie.
+
+ Imported at call time for the same reason the proxy tracker defers it:
+ ``headroom.pricing`` pulls in litellm (~4s), and this module is imported by
+ the MCP server and the CLI, neither of which should pay that to append a
+ line. Never raises — a ledger append must not fail because pricing did.
+ """
+ try:
+ from headroom.pricing.counterfactual import CacheMix, Region, price_savings
+ except Exception: # pragma: no cover - defensive
+ return None
+
+ cache = event.get("cache") or {}
+ mix = CacheMix.from_usage(
+ cache_read_tokens=cache.get("cr", 0),
+ cache_write_tokens=cache.get("cw", 0),
+ cache_write_5m_tokens=cache.get("cw5", 0),
+ cache_write_1h_tokens=cache.get("cw1h", 0),
+ uncached_input_tokens=cache.get("un", 0),
+ cache_inferred=cache.get("inf", False),
+ )
+ saved = _nonneg_int(event.get("saved"))
+ # Only the tool-schema half is stored; compression is the remainder. An
+ # event with no split at all is entirely message compression, which is what
+ # every v1 and MCP-tool event means. `saved_compression` is still read when
+ # present so an externally-written or older v2 line round-trips.
+ tool_schema = min(_nonneg_int(event.get("saved_tool_schema", 0)), saved)
+ compression = _nonneg_int(event.get("saved_compression", saved - tool_schema))
+ model = str(event.get("model") or UNKNOWN)
+ provider = event.get("provider")
+
+ try:
+ total = 0.0
+ total_list = 0.0
+ bases: list[str] = []
+ for tokens, region in (
+ (compression, Region.LIVE_ZONE),
+ (tool_schema, Region.PREFIX),
+ ):
+ if tokens <= 0:
+ continue
+ priced = price_savings(
+ tokens,
+ model=model,
+ mix=mix,
+ region=region,
+ provider=provider,
+ fallback_rate_per_token=fallback_rate,
+ )
+ total += priced.usd
+ total_list += priced.usd_list
+ bases.append(priced.basis)
+ except Exception: # pragma: no cover - defensive
+ return None
+
+ if not bases:
+ return None
+ from headroom.pricing.counterfactual import weakest_basis
+
+ return total, total_list, weakest_basis(*bases)
+
+
def record_savings_event(
*,
tokens_before: int,
@@ -127,11 +265,28 @@ def record_savings_event(
cost_usd: float | None = None,
fallback_rate: float = DEFAULT_FALLBACK_INPUT_COST_PER_TOKEN,
path: str | os.PathLike[str] | None = None,
+ # ── v2: savings shape + observed cache mix ────────────────────────────
+ # All optional. The MCP tool path supplies none of them and keeps writing
+ # exactly the events it always did, priced at list and labelled as such.
+ saved_compression: Any = None,
+ saved_tool_schema: Any = None,
+ cache_read_tokens: Any = 0,
+ cache_write_tokens: Any = 0,
+ cache_write_5m_tokens: Any = 0,
+ cache_write_1h_tokens: Any = 0,
+ uncached_input_tokens: Any = 0,
+ cache_inferred: Any = False,
+ provider: Any = None,
) -> bool:
"""Append one savings event to the durable ledger. Never raises.
Returns ``True`` when a line was written. ``cost_usd`` is computed from the
model + tokens saved when not supplied by the caller.
+
+ When the caller knows the savings split and the request's cache mix (the
+ proxy path does; the MCP path does not), both are recorded and the event
+ also carries a cache-aware ``cost_effective_usd``. ``cost_usd`` keeps its
+ original list-priced meaning either way, so existing readers are unaffected.
"""
try:
@@ -166,6 +321,56 @@ def record_savings_event(
"pid": os.getpid(),
}
+ # The savings split. Recorded only when the caller actually knows it —
+ # absent means "one undifferentiated figure", which is what every v1 event
+ # and every MCP-tool event is, and is priced as live-zone compression.
+ #
+ # Only the tool-schema half is stored: the two are guaranteed to sum to
+ # ``saved`` (see _coerce_split), so the compression half is derivable and
+ # writing it costs bytes on every line for no information. Its presence is
+ # also the marker that a split EXISTS, which is why it is written even when
+ # zero.
+ split = _coerce_split(saved, saved_compression, saved_tool_schema)
+ if split is not None:
+ event["saved_tool_schema"] = split[1]
+
+ # Short keys, and zero-valued ones omitted entirely. This file gets one line
+ # per request and is capped at 1 MB before compaction, so field names and
+ # empty buckets are a real share of it — and a bigger line means compaction
+ # fires at a lower request count (see _maybe_compact).
+ mix = {
+ "cr": _nonneg_int(cache_read_tokens),
+ "cw5": _nonneg_int(cache_write_5m_tokens),
+ "cw1h": _nonneg_int(cache_write_1h_tokens),
+ "cw": _nonneg_int(cache_write_tokens),
+ "un": _nonneg_int(uncached_input_tokens),
+ }
+ if any(mix.values()):
+ # `cw` is the write TOTAL and is redundant whenever the TTL buckets
+ # already account for it, which is the common Anthropic case. It is kept
+ # only when a provider reported a total it did not break down.
+ if mix["cw"] <= mix["cw5"] + mix["cw1h"]:
+ mix.pop("cw")
+ mix = {k: v for k, v in mix.items() if v}
+ if cache_inferred:
+ mix["inf"] = True
+ event["cache"] = mix
+ if provider:
+ event["provider"] = str(provider)[:64]
+ priced = _price_event(event, fallback_rate=fallback_rate)
+ if priced is not None:
+ effective_usd, list_usd, basis = priced
+ event["cost_effective_usd"] = round(effective_usd, 6)
+ event["basis"] = basis
+ # Take the list figure from the SAME pricing pass, so both columns
+ # use the same context tier. `estimate_cost_usd` above always
+ # prices at the base rate; a >200k request is billed at roughly
+ # double that, which left the "upper bound" column sitting BELOW
+ # the cache-aware one on long-context cold turns. Only when the
+ # caller did not pin `cost_usd` itself.
+ if cost_usd is None:
+ event["cost_usd"] = round(list_usd, 6)
+
target = _resolve_path(path)
try:
target.parent.mkdir(parents=True, exist_ok=True)
@@ -229,14 +434,36 @@ def _read_events(
class _Bucket:
tokens_saved: int = 0
tokens_before: int = 0
+ #: Flat list price — the upper bound, and what v1 reported as the headline.
cost_usd: float = 0.0
+ #: Cache-aware: what the removed tokens would actually have been billed at.
+ #: This is the headline as of v2.
+ cost_effective_usd: float = 0.0
calls: int = 0
-
- def add(self, *, saved: int, before: int, cost: float) -> None:
+ #: Weakest pricing basis among the events in this bucket, so a total cannot
+ #: read as better-grounded than its worst contributing event.
+ basis: str | None = None
+
+ def add(
+ self,
+ *,
+ saved: int,
+ before: int,
+ cost: float,
+ cost_effective: float | None = None,
+ basis: str | None = None,
+ ) -> None:
self.tokens_saved += saved
self.tokens_before += before
self.cost_usd += cost
+ # A v1 event has no cache-aware figure and never can have one, so it
+ # contributes its list dollar to both columns. That keeps the effective
+ # total complete (it is never missing an event) at the cost of being
+ # only as honest as the oldest event in the window — which `basis`
+ # reports, and which the 30-day retention cap bounds to a month.
+ self.cost_effective_usd += cost if cost_effective is None else cost_effective
self.calls += 1
+ self.basis = _weakest(self.basis, basis)
@property
def savings_percent(self) -> float:
@@ -249,11 +476,27 @@ class _Bucket:
"tokens_saved": self.tokens_saved,
"tokens_before": self.tokens_before,
"cost_usd": round(self.cost_usd, 6),
+ "cost_effective_usd": round(self.cost_effective_usd, 6),
+ "basis": self.basis or BASIS_LIST,
"calls": self.calls,
"savings_percent": self.savings_percent,
}
+def _weakest(existing: str | None, incoming: str | None) -> str | None:
+ """Keep the least-trustworthy of two pricing bases. Never raises."""
+ if incoming is None:
+ return existing
+ if existing is None or existing == incoming:
+ return incoming
+ try:
+ from headroom.pricing.counterfactual import weakest_basis
+
+ return weakest_basis(existing, incoming)
+ except Exception: # pragma: no cover - defensive
+ return existing
+
+
@dataclass
class SavingsReport:
path: str
@@ -281,7 +524,16 @@ def _ranked(buckets: dict[str, _Bucket], key_name: str) -> list[dict[str, Any]]:
for name, bucket in buckets.items():
row = {key_name: name, **bucket.to_dict()}
rows.append(row)
- rows.sort(key=lambda r: (r["cost_usd"], r["tokens_saved"]), reverse=True)
+ # Rank by the headline figure (cache-aware), not the list ceiling, so the
+ # order matches the column a reader is actually shown. List price is a
+ # near-constant multiple of tokens within one model, which made the old
+ # ranking almost a token sort; the effective figure reorders models whose
+ # savings sat in a cached prefix below ones whose savings were genuinely
+ # new input.
+ rows.sort(
+ key=lambda r: (r["cost_effective_usd"], r["cost_usd"], r["tokens_saved"]),
+ reverse=True,
+ )
return rows
@@ -321,19 +573,39 @@ def aggregate_savings(
cost = max(float(event.get("cost_usd", 0.0) or 0.0), 0.0)
except (TypeError, ValueError):
cost = 0.0
-
- windowed.add(saved=saved, before=before, cost=cost)
+ # Absent on every v1 event and on any v2 event the pricer could not
+ # value. `None` (not 0.0) so `_Bucket.add` can tell "no cache-aware
+ # figure exists" from "the cache-aware figure is zero" — collapsing
+ # those would silently drop old events out of the effective total and
+ # make the fix look far larger than it is.
+ raw_effective = event.get("cost_effective_usd")
+ try:
+ effective = None if raw_effective is None else max(float(raw_effective), 0.0)
+ except (TypeError, ValueError):
+ effective = None
+ basis = str(event.get("basis") or BASIS_LIST)
+
+ # Explicit keywords rather than a `**row` splat: the values are
+ # heterogeneous (ints, floats, an optional float, a string), so a dict
+ # built from them widens to a union that no longer type-checks against
+ # `add`'s signature. Listed out per bucket rather than via a local
+ # helper, which would close over these loop variables.
+ targets = [windowed]
if ts >= today_cutoff:
- today.add(saved=saved, before=before, cost=cost)
+ targets.append(today)
if ts >= week_cutoff:
- last_7.add(saved=saved, before=before, cost=cost)
-
- by_model.setdefault(str(event.get("model") or UNKNOWN), _Bucket()).add(
- saved=saved, before=before, cost=cost
- )
- by_client.setdefault(str(event.get("client") or UNKNOWN), _Bucket()).add(
- saved=saved, before=before, cost=cost
- )
+ targets.append(last_7)
+ targets.append(by_model.setdefault(str(event.get("model") or UNKNOWN), _Bucket()))
+ targets.append(by_client.setdefault(str(event.get("client") or UNKNOWN), _Bucket()))
+
+ for bucket in targets:
+ bucket.add(
+ saved=saved,
+ before=before,
+ cost=cost,
+ cost_effective=effective,
+ basis=basis,
+ )
model_rows = _ranked(by_model, "model")
top_model = model_rows[0]["model"] if model_rows else UNKNOWN
@@ -354,10 +626,26 @@ def aggregate_savings(
def _maybe_compact(target: Path) -> None:
- """Rewrite the ledger dropping out-of-retention events once it grows large."""
+ """Rewrite the ledger dropping out-of-retention events once it grows large.
+
+ Compaction can only remove events older than the retention window. A busy
+ install whose whole 30-day window exceeds the size threshold therefore has
+ NOTHING to drop — and without the back-off below, every subsequent append
+ would re-read and rewrite the entire (growing) file under an exclusive lock,
+ on every compressed request. At ~24k requests a month that is a multi-MB
+ rewrite per request.
+
+ The back-off is a per-process heuristic, not a correctness mechanism:
+ retention is also enforced on read (``aggregate_savings``), so a compaction
+ that is skipped or lost to a process restart changes nothing a user sees.
+ Each process simply re-checks once per additional ``_COMPACT_GROWTH_BYTES``
+ rather than once per append.
+ """
+ global _compact_min_size
try:
- if target.stat().st_size <= _COMPACT_SIZE_BYTES:
+ size = target.stat().st_size
+ if size <= _compact_min_size:
return
except OSError:
return
@@ -370,6 +658,7 @@ def _maybe_compact(target: Path) -> None:
fcntl.flock(handle, fcntl.LOCK_EX)
try:
kept: list[str] = []
+ dropped = 0
handle.seek(0)
for raw in handle:
stripped = raw.strip()
@@ -381,8 +670,16 @@ def _maybe_compact(target: Path) -> None:
continue
parsed = _parse_timestamp(event.get("ts"))
if parsed is None or parsed < cutoff:
+ dropped += 1
continue
kept.append(stripped)
+ if not dropped:
+ # Nothing aged out: the file is legitimately this big. Skip
+ # the rewrite (it would be byte-identical) and do not look
+ # again until it has grown appreciably.
+ _compact_min_size = size + _COMPACT_GROWTH_BYTES
+ return
+ _compact_min_size = _COMPACT_SIZE_BYTES
handle.seek(0)
handle.truncate()
if kept:
diff --git a/tests/test_counterfactual_pricing.py b/tests/test_counterfactual_pricing.py
new file mode 100644
index 000000000..ae395452c
--- /dev/null
+++ b/tests/test_counterfactual_pricing.py
@@ -0,0 +1,328 @@
+"""Cache-aware pricing of the tokens Headroom kept off the wire.
+
+The defect these cover: savings were priced at ``tokens * input_cost_per_token``
+— flat list price — which is correct only for the first request of a cache
+window. On traffic that is ~88% cache reads (measured on a real 238M-token
+corpus) that overstates the saving by ~2.7x overall and by ~10x for tool-schema
+deferral specifically, because tool definitions sit at the very front of the
+prompt and are the most cacheable tokens in it.
+
+The tests are organised around the three things that have to be true:
+region correctness, provider agnosticism, and honest labelling.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+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")
+
+from headroom.pricing.counterfactual import ( # noqa: E402
+ BASIS_CATALOG,
+ BASIS_CATALOG_TTL_RATIO,
+ BASIS_LIST,
+ BASIS_NO_MIX,
+ BASIS_UNPRICED,
+ CacheMix,
+ Region,
+ price_savings,
+ resolve_rates,
+ split_tokens,
+ weakest_basis,
+)
+
+SONNET = "claude-sonnet-4-20250514"
+
+
+def _warm_anthropic() -> CacheMix:
+ """A steady-state agent turn: big cached prefix, small appended delta."""
+ return CacheMix.from_usage(
+ cache_read_tokens=180_000,
+ cache_write_tokens=2_000,
+ cache_write_5m_tokens=2_000,
+ uncached_input_tokens=500,
+ )
+
+
+def _cold_anthropic() -> CacheMix:
+ """First turn of a window: everything is a cache write."""
+ return CacheMix.from_usage(
+ cache_write_tokens=50_000,
+ cache_write_5m_tokens=50_000,
+ )
+
+
+# ── Region correctness: the heart of the fix ──────────────────────────────
+
+
+def test_prefix_savings_on_a_warm_turn_price_at_the_cache_read_rate():
+ """Tool schemas sit ahead of every breakpoint, so a warm turn's are reads.
+
+ This is the 10x case. List pricing valued these at the full input rate; they
+ would actually have been billed at Anthropic's 0.10x read rate.
+ """
+ priced = price_savings(8_000, model=SONNET, mix=_warm_anthropic(), region=Region.PREFIX)
+
+ assert priced.ratio == pytest.approx(0.10, abs=1e-6)
+ assert priced.usd < priced.usd_list
+
+
+def test_prefix_split_is_read_first_not_pro_rata():
+ """Proportional bucketing hands prefix tokens a write premium they never paid.
+
+ On a 90/10 read/write request a pro-rata split prices them at
+ 0.9*0.1 + 0.1*1.25 = 0.215x instead of 0.10x — still ~2x high. Filling the
+ read bucket first is what makes the region argument mean anything.
+ """
+ mix = CacheMix.from_usage(
+ cache_read_tokens=90_000,
+ cache_write_tokens=10_000,
+ cache_write_5m_tokens=10_000,
+ )
+ split = split_tokens(5_000, mix, Region.PREFIX)
+
+ assert split.read == 5_000
+ assert split.write_5m == 0
+ assert split.write_1h == 0
+ assert split.uncached == 0
+
+
+def test_live_zone_savings_exclude_the_read_bucket_entirely():
+ """Compression works the appended delta, which was never cached.
+
+ Pricing it by the whole-request mix would value a warm turn's compression at
+ ~0.1x — an order of magnitude UNDER what the provider would have charged.
+ """
+ split = split_tokens(5_000, _warm_anthropic(), Region.LIVE_ZONE)
+
+ assert split.read == 0
+ assert split.total == pytest.approx(5_000)
+
+
+def test_live_zone_savings_on_a_cold_turn_exceed_list_price():
+ """A removed cache-write token saves 1.25x list, not 1.0x.
+
+ Deliberately NOT clamped to list: that is real money the provider would
+ have charged, and clamping it would under-report Headroom in exactly the
+ situation where compression is worth most.
+ """
+ priced = price_savings(8_000, model=SONNET, mix=_cold_anthropic(), region=Region.LIVE_ZONE)
+
+ assert priced.ratio == pytest.approx(1.25, abs=1e-6)
+ assert priced.usd > priced.usd_list
+
+
+def test_region_accepts_the_bare_string_form():
+ """``proxy/cost.py`` passes a string to keep litellm off the startup path.
+
+ ``Region`` is a str enum, so "prefix" compares EQUAL to Region.PREFIX but is
+ not IDENTICAL to it — an `is` test would route it down the live-zone branch
+ and price a cached prefix as if it had never been cached.
+ """
+ mix = _warm_anthropic()
+
+ assert split_tokens(5_000, mix, "prefix") == split_tokens(5_000, mix, Region.PREFIX)
+ assert split_tokens(5_000, mix, "live_zone") == split_tokens(5_000, mix, Region.LIVE_ZONE)
+
+
+# ── TTL: the 1h write rate that was never priced ──────────────────────────
+
+
+def test_one_hour_writes_price_above_five_minute_writes():
+ """A 1h write bills at 2.00x base against a 5m write's 1.25x.
+
+ The proxy counted and displayed the 5m/1h split all along but priced every
+ write at the 5m rate.
+ """
+ rates = resolve_rates(SONNET)
+
+ assert rates.write_1h > rates.write_5m > rates.uncached > rates.read
+ assert rates.write_1h / rates.uncached == pytest.approx(2.00, abs=1e-6)
+ assert rates.write_5m / rates.uncached == pytest.approx(1.25, abs=1e-6)
+
+
+def test_one_hour_ttl_savings_are_valued_at_the_one_hour_rate():
+ mix = CacheMix.from_usage(cache_write_tokens=50_000, cache_write_1h_tokens=50_000)
+ priced = price_savings(8_000, model=SONNET, mix=mix, region=Region.PREFIX)
+
+ assert priced.ratio == pytest.approx(2.00, abs=1e-6)
+
+
+def test_untagged_writes_default_to_the_five_minute_ttl():
+ """A provider reporting a write total but no split gets the DEFAULT TTL.
+
+ Attributing the remainder to 1h would inflate the counterfactual by 60% of
+ the write premium on traffic that never asked for the extended TTL.
+ """
+ mix = CacheMix.from_usage(cache_write_tokens=10_000).normalized()
+
+ assert mix.write_5m == 10_000
+ assert mix.write_1h == 0
+
+
+def test_long_context_derives_the_one_hour_rate_and_says_so():
+ """No catalog publishes a combined 1h + above-200k rate, so it derives."""
+ rates = resolve_rates(SONNET, long_context=True)
+
+ assert rates.basis == BASIS_CATALOG_TTL_RATIO
+ assert rates.write_1h / rates.uncached == pytest.approx(2.00, abs=1e-6)
+ # And it is the EXPENSIVE tier, not the base one.
+ assert rates.uncached > resolve_rates(SONNET).uncached
+
+
+# ── Provider agnosticism: every harness, every backend ────────────────────
+
+
+def test_openai_discounts_reads_and_charges_no_write_premium():
+ """OpenAI: 0.50x reads, writes at list. There is no 5m/1h trade to price."""
+ rates = resolve_rates("gpt-4o")
+
+ assert rates.read / rates.uncached == pytest.approx(0.50, abs=1e-6)
+ assert rates.write_5m == rates.uncached
+ assert rates.write_1h == rates.uncached
+
+
+def test_openai_inferred_writes_are_dropped_not_charged():
+ """An inferred write is the same tokens as ``uncached`` and bills as input.
+
+ Counting it as a write would both double-count those tokens and apply a
+ premium OpenAI does not charge.
+ """
+ mix = CacheMix.from_usage(
+ cache_read_tokens=90_000,
+ cache_write_tokens=10_000,
+ uncached_input_tokens=10_000,
+ cache_inferred=True,
+ ).normalized()
+
+ assert mix.write_5m == 0
+ assert mix.write_1h == 0
+ assert mix.read == 90_000
+ assert mix.uncached == 10_000
+
+
+def test_gemini_reports_reads_only_and_still_prices():
+ """Gemini populates the read bucket alone; that is enough for PREFIX."""
+ mix = CacheMix.from_usage(cache_read_tokens=100_000)
+ priced = price_savings(5_000, model="gemini/gemini-2.5-pro", mix=mix, region=Region.PREFIX)
+
+ assert priced.ratio == pytest.approx(0.10, abs=1e-6)
+ assert priced.basis == BASIS_CATALOG
+
+
+# ── Honest labelling: never a precise-looking guess ───────────────────────
+
+
+def test_no_cache_breakdown_prices_at_list_and_labels_it():
+ """The MCP tool path and non-reporting gateways land here.
+
+ List price is the honest answer when there is no mix; what must not happen
+ is it being reported as though it were measured.
+ """
+ priced = price_savings(8_000, model=SONNET, mix=None, region=Region.PREFIX)
+
+ assert priced.basis == BASIS_NO_MIX
+ assert priced.usd == priced.usd_list
+
+
+def test_unknown_model_without_a_fallback_is_unpriced_not_guessed():
+ priced = price_savings(8_000, model="not-a-real-model-xyz", mix=_warm_anthropic())
+
+ assert priced.basis == BASIS_UNPRICED
+ assert priced.usd == 0.0
+
+
+def test_unknown_model_with_a_fallback_uses_the_blended_rate():
+ priced = price_savings(
+ 8_000,
+ model="not-a-real-model-xyz",
+ fallback_rate_per_token=3.0 / 1_000_000,
+ )
+
+ assert priced.basis == BASIS_LIST
+ assert priced.usd == pytest.approx(0.024)
+
+
+def test_a_total_reports_its_weakest_contributing_basis():
+ """One unpriced request must not launder a total into looking catalog-grade."""
+ assert weakest_basis(BASIS_CATALOG, BASIS_NO_MIX) == BASIS_NO_MIX
+ assert weakest_basis(BASIS_CATALOG, BASIS_CATALOG) == BASIS_CATALOG
+ assert weakest_basis(BASIS_LIST, BASIS_UNPRICED) == BASIS_UNPRICED
+ assert weakest_basis(None, None) == BASIS_UNPRICED
+
+
+def test_a_free_model_saves_nothing_rather_than_falling_back():
+ """A real 0.0 price is not a missing price.
+
+ Treating it as missing bills the blended fallback and invents savings for a
+ model that costs nothing.
+ """
+ import litellm
+
+ from headroom.pricing.litellm_pricing import resolve_litellm_model
+
+ free_model = "free-local-model-for-test"
+ litellm.model_cost[resolve_litellm_model(free_model)] = {"input_cost_per_token": 0.0}
+ resolve_rates.cache_clear()
+ try:
+ priced = price_savings(
+ 10_000,
+ model=free_model,
+ mix=_warm_anthropic(),
+ fallback_rate_per_token=3.0 / 1_000_000,
+ )
+ assert priced.usd == 0.0
+ assert priced.usd_list == 0.0
+ finally:
+ litellm.model_cost.pop(resolve_litellm_model(free_model), None)
+ resolve_rates.cache_clear()
+
+
+# ── Invariants ────────────────────────────────────────────────────────────
+
+
[email protected]("region", [Region.PREFIX, Region.LIVE_ZONE])
+def test_a_split_always_conserves_its_tokens(region):
+ """Shares must sum to the input exactly, or a long session's total drifts."""
+ mixes = [
+ _warm_anthropic(),
+ _cold_anthropic(),
+ CacheMix(),
+ CacheMix.from_usage(cache_read_tokens=1, uncached_input_tokens=999_999),
+ CacheMix.from_usage(
+ cache_read_tokens=7,
+ cache_write_tokens=13,
+ cache_write_5m_tokens=5,
+ cache_write_1h_tokens=3,
+ uncached_input_tokens=11,
+ ),
+ ]
+ for mix in mixes:
+ for tokens in (1, 999, 40_000, 1_000_000):
+ split = split_tokens(tokens, mix, region)
+ assert split.total == pytest.approx(tokens)
+ assert min(split.read, split.write_5m, split.write_1h, split.uncached) >= 0
+
+
+def test_a_write_split_exceeding_its_total_cannot_go_negative():
+ """A malformed usage frame must not manufacture negative token shares."""
+ mix = CacheMix(write_5m=10, write_1h=10, write_total=5).normalized()
+
+ assert mix.write_5m >= 0
+ assert mix.write_1h >= 0
+
+
+def test_zero_and_negative_token_counts_price_at_zero():
+ for tokens in (0, -1, -10_000):
+ priced = price_savings(tokens, model=SONNET, mix=_warm_anthropic())
+ assert priced.usd == 0.0
+ assert priced.usd_list == 0.0
diff --git a/tests/test_persistent_metrics.py b/tests/test_persistent_metrics.py
index 2f517c23e..018c71bb6 100644
--- a/tests/test_persistent_metrics.py
+++ b/tests/test_persistent_metrics.py
@@ -73,6 +73,13 @@ def test_snapshot_accumulates_request_token_cache_cost_and_waste_metrics() -> No
assert snapshot["cost"] == {
"input_usd": 0.4,
"compression_savings_usd": 0.2,
+ # This call records no list ceiling, so the ceiling defaults to the
+ # cache-aware figure -- the truthful reading of "these are the same
+ # number" for a request with no cache mix to price against. The basis
+ # stays `unknown` because the caller named none: a fresh aggregate must
+ # not claim its untouched total was list-priced.
+ "compression_savings_list_usd": 0.2,
+ "savings_basis": "unknown",
"cache_savings_usd": 0.1,
}
assert snapshot["waste_signals"] == {"repetition": 7}
diff --git a/tests/test_persistent_metrics_persistence.py b/tests/test_persistent_metrics_persistence.py
index 4d35c604c..fe50d3c1d 100644
--- a/tests/test_persistent_metrics_persistence.py
+++ b/tests/test_persistent_metrics_persistence.py
@@ -55,15 +55,24 @@ def test_savings_tracker_migrates_v4_lifetime_to_v5_metrics_and_preserves_legacy
assert lifetime["prefix_cache"]["cache_read_tokens"] == 5
assert lifetime["cost"] == {
"input_usd": 1.5,
+ # Migrated from a pre-cache-aware state: its one dollar figure was
+ # list-priced, so it seeds both columns and the aggregate says so.
"compression_savings_usd": 0.5,
+ "compression_savings_list_usd": 0.5,
+ "savings_basis": "list",
"cache_savings_usd": 0.2,
}
assert lifetime["by_model"]["other"]["input_tokens"] == 80
tracker.flush()
saved = json.loads(path.read_text(encoding="utf-8"))
- assert saved["schema_version"] == 5
- assert saved["lifetime"] == legacy_state["lifetime"]
+ assert saved["schema_version"] == 6
+ # Every legacy field survives the migration untouched. Not exact equality:
+ # v6 ADDS the list-price ceiling and the basis label beside them, which is
+ # the point of the migration rather than a violation of it.
+ assert saved["lifetime"].items() >= legacy_state["lifetime"].items()
+ assert saved["lifetime"]["savings_basis"] == "list"
+ assert isinstance(saved["lifetime"]["savings_basis_migrated_at"], str)
assert saved["display_session"]["requests"] == 2
assert saved["projects"]["keep-me"]["requests"] == 1
assert saved["lifetime_metrics"]["models"]["other"]["input_tokens"] == 80
diff --git a/tests/test_providers/test_deepseek.py b/tests/test_providers/test_deepseek.py
index c7429141a..b8ba48d90 100644
--- a/tests/test_providers/test_deepseek.py
+++ b/tests/test_providers/test_deepseek.py
@@ -123,18 +123,34 @@ class TestDeepSeekLiteLLMInjection:
# get_llm_provider(). Bare model names without a provider prefix
# would fail with BadRequestError.
resolved = resolve_litellm_model("deepseek-v4-flash")
+ # The point of this test is RESOLUTION: an unprefixed name raises
+ # BadRequestError out of get_llm_provider(), so reaching a price at all
+ # is the assertion. Not raising is half of it.
input_cost, output_cost = litellm.cost_per_token(
model=resolved,
prompt_tokens=1_000_000,
completion_tokens=1_000_000,
)
active_pricing = litellm.model_cost["deepseek-v4-flash"]
- assert input_cost == pytest.approx(
- active_pricing["input_cost_per_token"] * 1_000_000,
- )
- assert output_cost == pytest.approx(
- active_pricing["output_cost_per_token"] * 1_000_000,
- )
+ list_input = active_pricing["input_cost_per_token"] * 1_000_000
+ list_output = active_pricing["output_cost_per_token"] * 1_000_000
+
+ # DeepSeek discounts 50% during its off-peak window (16:30-00:30 UTC),
+ # and litellm applies that inside cost_per_token
+ # (`apply_off_peak_pricing`) while leaving `model_cost` at list. So
+ # asserting equality with the catalog made this test pass for 16 hours a
+ # day and fail for the other 8 — it broke CI at 18:56 UTC having passed
+ # that morning. Wall-clock-dependent pricing has bitten this file before
+ # (#2428); assert the RELATIONSHIP that holds at every hour instead.
+ for cost, listed, label in (
+ (input_cost, list_input, "input"),
+ (output_cost, list_output, "output"),
+ ):
+ assert cost > 0, f"{label} cost should be priced, not zero"
+ assert cost == pytest.approx(listed) or cost == pytest.approx(listed * 0.5), (
+ f"{label} cost {cost} is neither list ({listed}) nor the "
+ f"documented off-peak half ({listed * 0.5})"
+ )
def test_resolve_litellm_model_prefixes_deepseek(self):
from headroom.pricing.litellm_pricing import resolve_litellm_model
diff --git a/tests/test_proxy_project_savings.py b/tests/test_proxy_project_savings.py
index e32fed007..1327d871a 100644
--- a/tests/test_proxy_project_savings.py
+++ b/tests/test_proxy_project_savings.py
@@ -257,7 +257,7 @@ def test_funnel_attributes_savings_from_context_and_stats_exposes_them(tmp_path,
assert stats["persistent_savings"]["projects_limit"] == DEFAULT_MAX_PROJECTS
history = client.get("/stats-history").json()
- assert history["schema_version"] == 5
+ assert history["schema_version"] == 6
assert history["projects"]["ctx-project"]["requests"] == 1
diff --git a/tests/test_proxy_savings_history.py b/tests/test_proxy_savings_history.py
index 9e9be57e8..0a91626c6 100644
--- a/tests/test_proxy_savings_history.py
+++ b/tests/test_proxy_savings_history.py
@@ -125,11 +125,19 @@ def test_savings_tracker_sanitizes_legacy_state_and_applies_retention(tmp_path):
)
snapshot = tracker.snapshot()
- assert snapshot["schema_version"] == 5
- assert snapshot["lifetime"] == {
+ assert snapshot["schema_version"] == 6
+ lifetime = dict(snapshot["lifetime"])
+ # Stamped at load time, so it can only be asserted for shape. Its presence
+ # is the point: this state predates v6, so its dollars are list-priced and
+ # the tracker records where the cache-aware numbers start.
+ assert isinstance(lifetime.pop("savings_basis_migrated_at"), str)
+ assert lifetime == {
"requests": 0,
"tokens_saved": 30,
+ # Pre-v6 state seeds both columns from the one list-priced figure it has.
"compression_savings_usd": pytest.approx(0.03),
+ "compression_savings_list_usd": pytest.approx(0.03),
+ "savings_basis": "list",
"cache_read_tokens": 0,
"cache_savings_usd": 0.0,
"total_input_tokens": 0,
@@ -169,6 +177,10 @@ def test_non_dict_savings_state_resets_to_default(tmp_path):
"requests": 0,
"tokens_saved": 0,
"compression_savings_usd": 0.0,
+ "compression_savings_list_usd": 0.0,
+ # Nothing priced yet, so there is no basis to report and nothing to
+ # migrate -- a fresh default, not a migrated pre-v6 state.
+ "savings_basis": "unknown",
"cache_read_tokens": 0,
"cache_savings_usd": 0.0,
"total_input_tokens": 0,
@@ -633,7 +645,12 @@ def test_display_session_rolls_after_inactivity_and_counts_zero_savings_requests
assert active_session == {
"requests": 2,
"tokens_saved": 20,
+ # This test records through a stubbed pricer with no cache breakdown,
+ # so the cache-aware and list columns coincide and the basis is `list`
+ # -- which is exactly what "no mix to price against" should report.
"compression_savings_usd": pytest.approx(0.02),
+ "compression_savings_list_usd": pytest.approx(0.02),
+ "savings_basis": "list",
"cache_read_tokens": 0,
"cache_savings_usd": 0.0,
"total_input_tokens": 200,
@@ -668,6 +685,8 @@ def test_display_session_rolls_after_inactivity_and_counts_zero_savings_requests
"requests": 1,
"tokens_saved": 5,
"compression_savings_usd": pytest.approx(0.005),
+ "compression_savings_list_usd": pytest.approx(0.005),
+ "savings_basis": "list",
"cache_read_tokens": 0,
"cache_savings_usd": 0.0,
"total_input_tokens": 50,
@@ -1073,7 +1092,9 @@ def test_stats_history_persists_across_restarts_and_stats_stays_compatible(tmp_p
# **kwargs so the stub keeps standing in for the real method as its
# signature grows: it takes a keyword-only `long_context` tier selector,
# which a positional-only stub turns into a TypeError inside /stats.
- lambda self, model, **kwargs: (0.001, 0.0015, 0.002),
+ # (cache_read, cache_write_5m, cache_write_1h, uncached). The 1h rate
+ # sits above the 5m one, as every real catalog row does.
+ lambda self, model, **kwargs: (0.001, 0.0015, 0.0024, 0.002),
)
config = ProxyConfig(
@@ -1103,7 +1124,7 @@ def test_stats_history_persists_across_restarts_and_stats_stays_compatible(tmp_p
history = client.get("/stats-history")
assert history.status_code == 200
history_data = history.json()
- assert history_data["schema_version"] == 5
+ assert history_data["schema_version"] == 6
assert history_data["storage_path"] == str(savings_path)
assert history_data["lifetime"]["tokens_saved"] == 40
assert history_data["lifetime"]["total_input_tokens"] == 120
@@ -1276,7 +1297,9 @@ def test_stats_history_csv_export_is_frontend_friendly(tmp_path, monkeypatch):
# **kwargs so the stub keeps standing in for the real method as its
# signature grows: it takes a keyword-only `long_context` tier selector,
# which a positional-only stub turns into a TypeError inside /stats.
- lambda self, model, **kwargs: (0.001, 0.0015, 0.002),
+ # (cache_read, cache_write_5m, cache_write_1h, uncached). The 1h rate
+ # sits above the 5m one, as every real catalog row does.
+ lambda self, model, **kwargs: (0.001, 0.0015, 0.0024, 0.002),
)
config = ProxyConfig(
@@ -1427,8 +1450,16 @@ def test_savings_tracker_loads_non_finite_persisted_state_without_crashing(tmp_p
lifetime = tracker.snapshot()["lifetime"]
# Non-finite fields fail open to safe defaults, not crash or NaN.
+ # `savings_basis` / `savings_basis_migrated_at` are provenance LABELS, not
+ # measures (v6) — they are strings by design and have no finiteness to
+ # check. Every numeric field still must be finite, which is the invariant
+ # this test exists to hold.
+ label_fields = {"savings_basis", "savings_basis_migrated_at"}
for key, value in lifetime.items():
- assert isinstance(value, int | float)
+ if key in label_fields:
+ assert value is None or isinstance(value, str), f"{key} should be a label: {value!r}"
+ continue
+ assert isinstance(value, int | float), f"{key} should be numeric: {value!r}"
assert math.isfinite(value), f"{key} is non-finite: {value}"
assert lifetime["tokens_saved"] == 0
assert lifetime["total_input_tokens"] == 0
@@ -1548,7 +1579,7 @@ def test_v3_state_without_cache_fields_loads_clean_and_saves_v4(tmp_path):
timestamp="2026-07-02T00:00:00Z",
)
persisted = json.loads(path.read_text(encoding="utf-8"))
- assert persisted["schema_version"] == 5
+ assert persisted["schema_version"] == 6
assert persisted["lifetime"]["cache_read_tokens"] == 5
assert persisted["lifetime"]["tokens_saved"] == 42181
diff --git a/tests/test_savings_ledger.py b/tests/test_savings_ledger.py
index b454946d2..1c7ec7b6a 100644
--- a/tests/test_savings_ledger.py
+++ b/tests/test_savings_ledger.py
@@ -263,7 +263,10 @@ def test_proxy_record_request_appends_ledger_event(tmp_path, monkeypatch):
monkeypatch.setenv("HEADROOM_SAVINGS_EVENTS_PATH", str(tmp_path / "savings_events.jsonl"))
monkeypatch.setattr(
"headroom.proxy.server.CostTracker._get_cache_prices",
- lambda self, model: (0.001, 0.0015, 0.002),
+ # (cache_read, cache_write_5m, cache_write_1h, uncached). **kwargs so
+ # the stub keeps standing in as the real signature grows -- it takes a
+ # keyword-only `long_context` tier selector.
+ lambda self, model, **kwargs: (0.001, 0.0015, 0.0024, 0.002),
)
config = ProxyConfig(cache_enabled=False, rate_limit_enabled=False, log_requests=False)
@@ -317,3 +320,130 @@ def test_cli_days_flag_capped_at_30(monkeypatch, tmp_path, bad_days):
result = CliRunner().invoke(savings, ["--days", bad_days])
assert result.exit_code != 0
assert "30" in result.output # IntRange error mentions the allowed max
+
+
+def test_compaction_backs_off_when_nothing_can_be_dropped(tmp_path, monkeypatch):
+ """A busy install's whole retention window can exceed the size threshold.
+
+ Compaction only removes events older than retention, so such a ledger has
+ NOTHING to drop — and without a back-off every subsequent append re-read and
+ rewrote the entire growing file under an exclusive lock, once per compressed
+ request. The back-off is per-process and purely a work-saver: retention is
+ enforced on read regardless.
+ """
+ import headroom.savings_ledger as sl
+
+ path = tmp_path / "events.jsonl"
+ # Tiny thresholds so a handful of in-retention events trips compaction.
+ monkeypatch.setattr(sl, "_COMPACT_SIZE_BYTES", 200)
+ monkeypatch.setattr(sl, "_COMPACT_GROWTH_BYTES", 10_000)
+ monkeypatch.setattr(sl, "_compact_min_size", 200)
+
+ for _ in range(5):
+ sl.record_savings_event(
+ tokens_before=1_000, tokens_after=600, model="unknown", source="mcp", path=path
+ )
+
+ assert path.stat().st_size > 200
+ # Every event is fresh, so none aged out and the floor ratcheted above the
+ # current size rather than staying at the threshold.
+ assert sl._compact_min_size > 200
+
+ # All five events survive: skipping the rewrite must never lose data.
+ assert sl.aggregate_savings(path=path).lifetime["calls"] == 5
+
+
+def test_compaction_still_drops_out_of_retention_events(tmp_path, monkeypatch):
+ """The back-off must not disable compaction for ledgers that CAN shrink."""
+ import json
+ from datetime import timedelta
+
+ import headroom.savings_ledger as sl
+
+ path = tmp_path / "events.jsonl"
+ stale = (sl._utc_now() - timedelta(days=sl.MAX_RETENTION_DAYS + 5)).isoformat()
+ with path.open("w", encoding="utf-8") as fh:
+ for _ in range(50):
+ fh.write(
+ json.dumps(
+ {
+ "v": 1,
+ "ts": stale,
+ "before": 1_000,
+ "after": 600,
+ "saved": 400,
+ "cost_usd": 0.0012,
+ "model": "unknown",
+ "client": "mcp",
+ "source": "mcp",
+ },
+ separators=(",", ":"),
+ )
+ + "\n"
+ )
+ before_size = path.stat().st_size
+ monkeypatch.setattr(sl, "_COMPACT_SIZE_BYTES", 200)
+ monkeypatch.setattr(sl, "_compact_min_size", 200)
+
+ sl.record_savings_event(
+ tokens_before=1_000, tokens_after=600, model="unknown", source="mcp", path=path
+ )
+
+ assert path.stat().st_size < before_size
+ # Only the fresh event remains; the floor reset so compaction stays armed.
+ assert sl.aggregate_savings(path=path).lifetime["calls"] == 1
+ assert sl._compact_min_size == 200
+
+
+def test_v1_events_still_aggregate_alongside_v2(tmp_path):
+ """A ledger written across the upgrade must stay legible, not silently blend.
+
+ A v1 event has no cache mix and never can have one, so it contributes its
+ list dollar to both columns — and drags the reported basis down to `list`,
+ which is how a reader learns the total is not fully cache-aware.
+ """
+ import json
+
+ import headroom.savings_ledger as sl
+
+ path = tmp_path / "events.jsonl"
+ with path.open("w", encoding="utf-8") as fh:
+ fh.write(
+ json.dumps(
+ {
+ "v": 1,
+ "ts": sl._utc_now().isoformat(),
+ "before": 10_000,
+ "after": 6_000,
+ "saved": 4_000,
+ "cost_usd": 0.012,
+ "model": "claude-sonnet-4-20250514",
+ "client": "claude-code",
+ "source": "proxy",
+ }
+ )
+ + "\n"
+ )
+ sl.record_savings_event(
+ tokens_before=108_000,
+ tokens_after=100_000,
+ model="claude-sonnet-4-20250514",
+ client="claude-code",
+ source="proxy",
+ saved_compression=1_000,
+ saved_tool_schema=7_000,
+ cache_read_tokens=95_000,
+ cache_write_tokens=4_000,
+ cache_write_5m_tokens=4_000,
+ uncached_input_tokens=1_000,
+ provider="anthropic",
+ path=path,
+ )
+
+ lifetime = sl.aggregate_savings(path=path).lifetime
+ assert lifetime["calls"] == 2
+ # The v2 event is discounted, so the effective total sits below the list one.
+ assert lifetime["cost_effective_usd"] < lifetime["cost_usd"]
+ # ...but the v1 event's list dollar is still counted, not dropped.
+ assert lifetime["cost_effective_usd"] > 0.012
+ assert lifetime["basis"] == "list"
diff --git a/tests/test_savings_ledger_before_forwarded.py b/tests/test_savings_ledger_before_forwarded.py
index c50f6b938..7e61940e4 100644
--- a/tests/test_savings_ledger_before_forwarded.py
+++ b/tests/test_savings_ledger_before_forwarded.py
@@ -57,15 +57,21 @@ async def test_record_savings_event_uses_original_input_as_before(
client="claude-code",
)
- assert calls == [
- {
- "tokens_before": 1000,
- "tokens_after": 600,
- "model": "claude-opus-4-6",
- "client": "claude-code",
- "source": "proxy",
- }
- ]
+ # Assert on the fields this test is ABOUT (the before/after reconstruction
+ # and attribution) rather than the whole kwargs dict. The ledger call also
+ # carries the savings split and the request's cache mix, which every future
+ # field addition would otherwise break this test on without saying anything
+ # about what it guards.
+ assert len(calls) == 1
+ call = calls[0]
+ assert call["tokens_before"] == 1000
+ assert call["tokens_after"] == 600
+ assert call["model"] == "claude-opus-4-6"
+ assert call["client"] == "claude-code"
+ assert call["source"] == "proxy"
+ # No deferral on this request, so the whole saving is message compression.
+ assert call["saved_compression"] == 400
+ assert call["saved_tool_schema"] == 0
@pytest.mark.asyncio
diff --git a/tests/test_savings_provider_matrix.py b/tests/test_savings_provider_matrix.py
new file mode 100644
index 000000000..c6755d804
--- /dev/null
+++ b/tests/test_savings_provider_matrix.py
@@ -0,0 +1,226 @@
+"""Cache-aware savings must hold for EVERY provider and every harness.
+
+Headroom sits in front of Anthropic, Bedrock, Vertex, OpenAI, Gemini, and
+arbitrary gateways, driven by Claude Code, Codex, Cursor, Copilot, Kiro and the
+MCP tool path. Those backends report their prompt-cache usage in genuinely
+different shapes, and the differences change the money:
+
+ Anthropic/Bedrock read + write + 5m/1h split + uncached
+ OpenAI read + uncached, write INFERRED (no write premium)
+ Gemini read only
+ gateway / MCP nothing at all
+
+The pricing fix lives at one chokepoint — ``emit_request_outcome`` feeds the
+single ``metrics.record_request``, which every one of the 32 handler emit sites
+routes through — so this file asserts the matrix rather than each handler. If
+pricing were ever forked per provider, these are the tests that would catch it.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+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")
+
+from headroom.proxy.savings_tracker import estimate_request_savings_usd # noqa: E402
+
+# One warm turn per provider, in that provider's own reporting shape.
+WARM_TURNS = {
+ "anthropic": {
+ "model": "claude-sonnet-4-20250514",
+ "cache_read_tokens": 180_000,
+ "cache_write_tokens": 2_000,
+ "cache_write_5m_tokens": 2_000,
+ "uncached_input_tokens": 500,
+ },
+ "bedrock": {
+ "model": "claude-sonnet-4-20250514",
+ "cache_read_tokens": 180_000,
+ "cache_write_tokens": 2_000,
+ "cache_write_5m_tokens": 2_000,
+ "uncached_input_tokens": 500,
+ },
+ "openai": {
+ "model": "gpt-4o",
+ "cache_read_tokens": 180_000,
+ "cache_write_tokens": 2_500,
+ "uncached_input_tokens": 2_500,
+ "cache_inferred": True,
+ },
+ "gemini": {
+ "model": "gemini/gemini-2.5-pro",
+ "cache_read_tokens": 180_000,
+ },
+}
+
+
[email protected]("provider", sorted(WARM_TURNS))
+def test_tool_schema_savings_are_discounted_on_a_warm_turn_for_every_provider(provider):
+ """Deferred tool schemas ride the cached prefix, whoever is serving it.
+
+ Every provider in the matrix discounts cache reads, so on a warm turn the
+ honest value of deferred schemas is strictly below list on all of them. This
+ is the defect in its purest form: list pricing charged the full input rate
+ for tokens that would have been read from cache.
+ """
+ priced = estimate_request_savings_usd(
+ tool_schema_tokens_saved=8_000,
+ provider=provider,
+ **WARM_TURNS[provider],
+ )
+
+ assert priced["tool_schema"] < priced["tool_schema_list"], (
+ f"{provider}: warm-turn tool-schema savings should be discounted"
+ )
+ assert priced["basis"] == "catalog"
+
+
[email protected]("provider", sorted(WARM_TURNS))
+def test_live_zone_compression_is_never_valued_at_the_cache_read_rate(provider):
+ """Compression works the appended delta, which no provider had cached.
+
+ The symmetric error: pricing compression by the whole-request mix would
+ value a warm turn's savings at ~0.1x, an order of magnitude UNDER what was
+ actually charged.
+ """
+ priced = estimate_request_savings_usd(
+ compression_tokens_saved=8_000,
+ provider=provider,
+ **WARM_TURNS[provider],
+ )
+
+ assert priced["compression"] >= priced["compression_list"] * 0.9, (
+ f"{provider}: live-zone savings must not be discounted as cache reads"
+ )
+
+
+def test_openai_inferred_write_carries_no_write_premium():
+ """OpenAI has no write counter, so handlers derive one. It must not be billed.
+
+ The derived figure is the same tokens as ``uncached_input_tokens``. Treating
+ it as a real write both double-counts them and applies a 1.25x premium
+ OpenAI does not charge.
+ """
+ common = {
+ "model": "gpt-4o",
+ "compression_tokens_saved": 5_000,
+ "cache_read_tokens": 100_000,
+ "uncached_input_tokens": 10_000,
+ "provider": "openai",
+ }
+ inferred = estimate_request_savings_usd(
+ cache_write_tokens=10_000, cache_inferred=True, **common
+ )
+ absent = estimate_request_savings_usd(**common)
+
+ assert inferred["compression"] == pytest.approx(absent["compression"])
+
+
+def test_a_provider_that_reports_no_cache_data_prices_at_list_and_says_so():
+ """Gateways, custom bases and streaming turns with no usage frame land here.
+
+ List price is the only honest answer with no mix — but it must be LABELLED,
+ not presented as a measurement.
+ """
+ priced = estimate_request_savings_usd(
+ model="claude-sonnet-4-20250514",
+ compression_tokens_saved=5_000,
+ tool_schema_tokens_saved=5_000,
+ )
+
+ assert priced["compression"] == pytest.approx(priced["compression_list"])
+ assert priced["tool_schema"] == pytest.approx(priced["tool_schema_list"])
+ assert priced["basis"] == "no-mix"
+
+
+def test_the_mcp_tool_path_still_records_without_any_cache_signal():
+ """``headroom mcp serve`` never learns the agent's model or its cache mix.
+
+ It must keep writing ledger events at the blended fallback rate rather than
+ failing or recording $0 — the path predates cache reporting entirely.
+ """
+ import tempfile
+ from pathlib import Path
+
+ from headroom import savings_ledger
+
+ path = Path(tempfile.mkdtemp()) / "events.jsonl"
+ assert savings_ledger.record_savings_event(
+ tokens_before=10_000,
+ tokens_after=4_000,
+ model="unknown",
+ client="mcp",
+ source="mcp",
+ path=path,
+ )
+
+ report = savings_ledger.aggregate_savings(path=path).to_dict()
+ lifetime = report["lifetime"]
+ assert lifetime["calls"] == 1
+ assert lifetime["cost_usd"] > 0
+ # No mix, so the cache-aware column falls back to the list figure rather
+ # than dropping the event out of the total.
+ assert lifetime["cost_effective_usd"] == pytest.approx(lifetime["cost_usd"])
+ assert lifetime["basis"] == "list"
+
+
+def test_the_headline_degrades_to_the_weakest_provider_in_a_mixed_session():
+ """Claude Code sends Sonnet and Haiku; a gateway may add an unpriceable model.
+
+ A session mixing a catalog-priced provider with one reporting nothing must
+ not present its total as catalog-grade.
+ """
+ priced = estimate_request_savings_usd(
+ model="claude-sonnet-4-20250514",
+ # Priced against a real mix...
+ compression_tokens_saved=5_000,
+ cache_read_tokens=100_000,
+ cache_write_tokens=1_000,
+ cache_write_5m_tokens=1_000,
+ uncached_input_tokens=1_000,
+ provider="anthropic",
+ )
+ assert priced["basis"] == "catalog"
+
+ # ...but the same layers with nothing reported cannot claim the same.
+ blind = estimate_request_savings_usd(
+ model="claude-sonnet-4-20250514",
+ compression_tokens_saved=5_000,
+ )
+ assert blind["basis"] == "no-mix"
+
+
+def test_long_context_requests_price_at_the_above_200k_tier():
+ """A >200k turn is billed at a different rate table; savings must follow.
+
+ Anthropic's above-200k input rate is 2x the base one, so valuing a long
+ request's savings at base rates understates them by half.
+ """
+ base = estimate_request_savings_usd(
+ model="claude-sonnet-4-20250514",
+ compression_tokens_saved=5_000,
+ cache_write_tokens=50_000,
+ cache_write_5m_tokens=50_000,
+ uncached_input_tokens=10_000,
+ provider="anthropic",
+ )
+ long_ctx = estimate_request_savings_usd(
+ model="claude-sonnet-4-20250514",
+ compression_tokens_saved=5_000,
+ cache_write_tokens=250_000,
+ cache_write_5m_tokens=250_000,
+ uncached_input_tokens=10_000,
+ provider="anthropic",
+ )
+
+ assert long_ctx["compression"] > base["compression"]
+ assert long_ctx["compression_list"] > base["compression_list"]