Files
headroom/tests/test_persistent_metrics_persistence.py
Tejas ChopraandClaude Opus 5 89a58fd152 fix(pricing): price savings against the cache mix, not flat list price (#3699)
## The problem

Every savings figure Headroom reports is a counterfactual: *what would
this request have cost had we not removed those tokens?* We answered it
with `tokens_saved * input_cost_per_token` — flat list price — which 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).

Measured on a real 238M-input-token corpus that was **87.8% cache
reads**:

| | |
|---|---|
| effective rate actually **paid** | $1.592/M |
| rate savings were **priced at** | $4.339/M — **2.73x** |
| reported compression savings | **$330.89** |
| same tokens at the observed mix | ~$121 |

For **tool-schema deferral** the gap is ~10x: tool definitions sit at
the very front of the prompt and are the most cacheable tokens in it.

## The fix

The correct rate depends on **where in the request** the tokens sat:

| Region | What | Pricing |
|---|---|---|
| `PREFIX` | tool schemas — ahead of every cache breakpoint | warm turn
= **entirely a cache read** (read-first, not pro-rata) |
| `LIVE_ZONE` | the appended delta handlers compress | **never** a cache
read; cold turn saves 1.25x list, not 1.0x |

`headroom/pricing/counterfactual.py` is now the single place cache rates
are resolved and counterfactual tokens are priced — for the live cost
card, the persisted tracker and the durable ledger alike, so the three
cannot drift apart again. It replaces three separate implementations,
two of which were list-only.

Verified, warm Anthropic turn, 8k deferred tool-schema tokens: `$0.0240
list → $0.0057` (4.2x correction). Cold turn: `$0.0240 → $0.0300` —
correctly **above** list, the case list pricing *under*-reported.

## Also fixed

- **1h-TTL writes were priced at the 5m rate.** The proxy counted and
displayed the 5m/1h split but never priced it. LiteLLM publishes the 1h
rate per model (Sonnet: 2.00x base); `pricing/cache_ttl.py` — written
for exactly this and never imported by the cost path — derives it where
a row omits one.
- **Prefix tokens were bucketed pro-rata**, handing them a share of the
1.25x write premium they never paid (~2x high on a warm turn).
- **OTel exporter crash risk**: it called `float()` over every value in
the savings breakdown, so a non-numeric field would take the whole
request-metrics path down.
- **Ledger compaction thrash** (pre-existing, amplified here):
`_maybe_compact` rewrote the entire file under `flock` on *every append*
once it passed 1 MB with nothing out of retention to drop. Added a
per-process back-off; retention is still enforced on read.

## Schema changes

**Ledger v1 → v2**, **savings state v5 → v6.**

v1 stored one list-priced dollar and no mix, so its history was not
merely overstated — it was **unfixable**, because nothing on disk said
what fraction of the removed tokens would have been cache reads. v2
stores the savings split and the observed mix, so a future basis change
can re-derive the whole ledger.

Pre-v6 state seeds both columns from the single figure it has and is
labelled `list` for good; `savings_basis_migrated_at` marks where the
honest numbers start. v1 ledger events still read and aggregate
alongside v2.

## Honesty over precision

Every figure now ships with its list-price ceiling and a `basis` label
saying how soundly it was derived (`catalog`, `catalog+ttl-ratio`,
`provider-ratio`, `list`, `no-mix`, `unpriced`). Totals report their
**weakest** contributing basis, so one unpriceable request can't launder
a total into looking catalog-grade. A request with no cache breakdown —
the MCP tool path, a non-reporting gateway, a streaming turn with no
usage frame — still prices at list and **says so**.

## Harness- and provider-agnostic

The fix sits at the single `emit_request_outcome` → `record_request`
chokepoint that all **32** handler emit sites route through (anthropic
6, openai 11, batch 5, gemini 3, streaming 3, bedrock 1, gateway_turn 2,
server 1) — no per-handler work.

`tests/test_savings_provider_matrix.py` asserts the matrix directly:

| Provider | Reports | Handled |
|---|---|---|
| Anthropic / Bedrock / Vertex | read + write + 5m/1h + uncached | full
|
| OpenAI | read + uncached, write **inferred** | inferred write dropped
— no premium OpenAI doesn't charge |
| Gemini | read only | prices from reads alone |
| gateway / MCP | nothing | list + labelled `no-mix` |

## Tests

- **New:** 21 pricing + 13 provider-matrix + 3 ledger (compaction
back-off, v1/v2 mixing)
- **Updated:** 6 files for the deliberate schema change
- Local sweep across everything touching savings/cost/pricing/metrics:
**904 passed**; targeted re-run after review fixes: **125 passed**
- `ruff check` + `format` clean under the **CI-pinned 0.16.7** (local
0.16.3 missed 5 C408s)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 14:41:30 -07:00

99 lines
3.7 KiB
Python

"""Tests schema v5 persistence around the pure Lifetime aggregate."""
from __future__ import annotations
import json
from headroom.proxy.savings_tracker import SavingsTracker
def test_savings_tracker_migrates_v4_lifetime_to_v5_metrics_and_preserves_legacy_state(tmp_path):
path = tmp_path / "proxy_savings.json"
legacy_state = {
"schema_version": 4,
"lifetime": {
"requests": 7,
"tokens_saved": 20,
"compression_savings_usd": 0.5,
"cache_read_tokens": 5,
"cache_savings_usd": 0.2,
"total_input_tokens": 80,
"total_input_cost_usd": 1.5,
},
"display_session": {
"requests": 2,
"tokens_saved": 4,
"compression_savings_usd": 0.1,
"cache_read_tokens": 1,
"cache_savings_usd": 0.01,
"total_input_tokens": 10,
"total_input_cost_usd": 0.2,
"started_at": "2026-07-01T00:00:00Z",
"last_activity_at": "2026-07-02T00:00:00Z",
},
"history": [
{
"timestamp": "2026-07-02T00:00:00Z",
"total_tokens_saved": 20,
"compression_savings_usd": 0.5,
"total_input_tokens": 80,
"total_input_cost_usd": 1.5,
}
],
"projects": {"keep-me": {"requests": 1}},
}
path.write_text(json.dumps(legacy_state), encoding="utf-8")
tracker = SavingsTracker(path=str(path), save_flush_every=25)
lifetime = tracker.lifetime_response()
assert lifetime["schema_version"] == 5
assert lifetime["requests"]["total"] == 7
assert lifetime["tokens"]["input"] == 80
assert lifetime["tokens"]["attempted_input"] == 100
assert lifetime["tokens"]["saved"] == 20
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"] == 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
assert isinstance(saved["lifetime_metrics"]["persistence"]["last_saved_at"], str)
def test_lifetime_response_reports_stateless_mode_without_writing(tmp_path):
path = tmp_path / "proxy_savings.json"
tracker = SavingsTracker(path=str(path), stateless=True, save_flush_every=1)
tracker.record_lifetime_request(
provider="openai", stack="codex", model="gpt-test", input_tokens=3
)
response = tracker.lifetime_response()
assert response["persistence"] == {
"enabled": False,
"healthy": True,
"error": "Lifetime metrics unavailable in stateless mode",
"pending_records": 0,
"last_saved_at": None,
}
assert path.exists() is False