Files
headroom/tests/test_savings_ledger_before_forwarded.py
e92cccca00 feat(savings): show the new-input savings basis beside the whole-wire figure (#3485)
## Description

The proxy already computes two savings bases in `/stats`:
`savings_percent` (saved over everything forwarded, which recounts a
session's cached history every turn and drifts toward 0% on long
sessions) and `new_input_savings_percent` (compression-only saved over
the tokens that newly entered context: provider-billed uncached +
cache-write). Only the first one is shown anywhere: the dashboard
headline and `headroom savings` both render the whole-wire figure. A
user on a 300-turn Claude Code session sees 0.4% while compression is
working on every new turn, and a user comparing the CLI with a client
that reads the new-input field sees two unexplained numbers.

This surfaces the existing new-input figure as a second labelled view
next to the whole-wire one. No calculation changes.

- Dashboard: the headline "Tokens Saved" percentage leads with
`new_input_savings_percent` when the provider reported a cache breakdown
(`new_input_tokens > 0`), with a title explaining the basis; it falls
back to whole-wire otherwise (Bedrock, no cache data) so it never
collapses to 0% while compression is happening (#455). The "Of total
wire" line beneath it is unchanged.
- CLI `headroom savings`: each window line gains `· of new input NN.N%`
when that window has cache data, plus a one-line legend. Windows without
cache data print exactly what they print today.
- Ledger: `record_savings_event` takes optional `new_input_tokens` and
`deferred_tokens`; the proxy call site passes uncached + cache-write and
the tool-search deferral share. Events without a cache breakdown write
the same line as before and do not contribute to the new-input ratio on
either side, so the ratio never pairs one event's savings with another's
denominator. Numerator is compression-only (saved minus deferral),
matching `/stats`.

## Type of Change

- [x] New feature (non-breaking change that adds functionality)

## Changes Made

- `headroom/savings_ledger.py`: optional `new_input` / `deferred` event
fields; `_Bucket.new_input_tokens`, `new_input_saved`,
`new_input_savings_percent`; both exported in `to_dict()`.
- `headroom/proxy/prometheus_metrics.py`: ledger append passes
`new_input_tokens` (None when no cache breakdown) and `deferred_tokens`.
- `headroom/cli/savings.py`: `_window_line` appends the new-input figure
when present; legend line.
- `headroom/dashboard/templates/dashboard.html`: `headlineUsesNewInput`
gate, headline getter and title; stale "attempted denominator" comment
replaced.
- Tests: ledger pairing and no-cache-data isolation, CLI output with and
without cache data, proxy call-site kwargs with and without a cache
breakdown, dashboard headline order and titles.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
uv run --frozen --extra dev pytest tests/test_savings_ledger.py tests/test_dashboard_token_savings.py tests/test_savings_ledger_before_forwarded.py tests/test_savings_ledger_offload.py tests/test_proxy_project_savings.py tests/test_dashboard -q
46 passed, 3 skipped
uvx ruff check headroom/savings_ledger.py headroom/proxy/prometheus_metrics.py headroom/cli/savings.py tests/test_savings_ledger.py tests/test_dashboard_token_savings.py tests/test_savings_ledger_before_forwarded.py
All checks passed!
uv run --frozen --extra dev mypy headroom/savings_ledger.py headroom/cli/savings.py headroom/proxy/prometheus_metrics.py
Success: no issues found in 3 source files
```

## Real Behavior Proof

- Environment: macOS 15, Python 3.12, headroom-ai 0.37.0 as installed by
Headroom Desktop, real Claude Code traffic on 2026-09-08.
- Exact command / steps: Summed PERF lines for one opus-5 session (354
requests, 53.7M tokens forwarded, 45.0M cache reads, 1.17M cache writes)
and compared the two bases; ran `headroom savings` through `CliRunner`
against a temp ledger with one event carrying `new_input_tokens=900` and
one without.
- Observed result: whole-wire 0.42% versus new-input 2.9% on the same
session, which is the gap this view explains. CLI output: the window
line without cache data is byte-identical to today; with cache data it
ends in `· of new input 30.8%` and the legend prints once.
- Not tested: dashboard rendering in a browser (the template getters are
covered by the existing regex tests; no visual change beyond the number
and its tooltip).

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: Stable.
- Stable/default behavior changed: Yes. The dashboard headline
percentage and `headroom savings` lines show the new-input basis when
cache data exists; the whole-wire figure stays visible beside it. Ledger
lines gain two optional fields; old lines still parse.
- Kill switch / disable path: None; both figures are shown, nothing is
hidden.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert the commit; ledger lines with the extra fields
are ignored by the previous reader.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] I have updated the CHANGELOG.md if applicable

## Screenshots (if applicable)

N/A

## Additional Notes

Why a second view and not a toggle: the two numbers answer different
questions ("how much of what I sent was cut" versus "how much of what I
newly added was cut") and hiding either one is what caused the
confusion. Documentation: the CLI legend and the dashboard tooltip carry
the definition; happy to add a docs line if you point me at the page.

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
2026-09-24 16:47:03 -05:00

228 lines
7.2 KiB
Python

"""Proxy savings-ledger events record the original input as ``before``."""
from __future__ import annotations
from typing import Any
import pytest
from headroom.proxy import prometheus_metrics
class _FakeSavingsTracker:
def snapshot(self) -> dict[str, dict[str, int | float]]:
return {"lifetime": {"total_input_tokens": 0, "total_input_cost_usd": 0.0}}
def record_request(self, **kwargs: Any) -> None:
pass
def record_lifetime_request(self, **kwargs: Any) -> None:
pass
class _FakeOtelMetrics:
def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []
def record_proxy_request(self, **kwargs: Any) -> None:
self.calls.append(kwargs)
@pytest.mark.asyncio
async def test_record_savings_event_uses_original_input_as_before(
monkeypatch: pytest.MonkeyPatch,
) -> None:
calls: list[dict[str, Any]] = []
def record_savings_event(**kwargs: Any) -> None:
calls.append(kwargs)
monkeypatch.setattr(
prometheus_metrics.savings_ledger,
"record_savings_event",
record_savings_event,
)
metrics = prometheus_metrics.PrometheusMetrics(
savings_tracker=_FakeSavingsTracker(),
otel_metrics=_FakeOtelMetrics(),
)
await metrics.record_request(
provider="anthropic",
model="claude-opus-4-6",
input_tokens=600,
output_tokens=25,
tokens_saved=400,
latency_ms=10.0,
client="claude-code",
)
# 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
# With a provider cache breakdown the ledger also gets the /stats
# new-input denominator (uncached + cache write) and the deferral share of
# the saving, so `headroom savings` can pair compression-only with new input.
calls.clear()
await metrics.record_request(
provider="anthropic",
model="claude-opus-4-6",
input_tokens=600,
output_tokens=25,
tokens_saved=400,
latency_ms=10.0,
client="claude-code",
cache_read_tokens=5000,
cache_write_tokens=700,
uncached_input_tokens=200,
tool_search_saved=150,
)
assert calls[0]["tokens_before"] == 1000 + 150
assert calls[0]["new_input_tokens"] == 900
assert calls[0]["deferred_tokens"] == 150
@pytest.mark.asyncio
async def test_record_request_forwards_tool_savings_to_otel() -> None:
otel = _FakeOtelMetrics()
metrics = prometheus_metrics.PrometheusMetrics(
savings_tracker=_FakeSavingsTracker(),
otel_metrics=otel,
)
await metrics.record_request(
provider="anthropic",
model="claude-opus-4-6",
input_tokens=600,
output_tokens=25,
tokens_saved=400,
tool_search_saved=13182,
latency_ms=10.0,
)
assert len(otel.calls) == 1
assert otel.calls[0]["tokens_saved"] == 400
assert otel.calls[0]["tool_search_saved"] == 13182
def _capture_ledger(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
calls: list[dict[str, Any]] = []
monkeypatch.setattr(
prometheus_metrics.savings_ledger,
"record_savings_event",
lambda **kwargs: calls.append(kwargs),
)
return calls
@pytest.mark.asyncio
async def test_record_savings_event_includes_tool_search_deferral(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""tool_search_deferral savings must ride into the ledger delta so
`headroom savings` does not undercount tool-search sessions ~7-10x (#2795)."""
calls = _capture_ledger(monkeypatch)
metrics = prometheus_metrics.PrometheusMetrics(
savings_tracker=_FakeSavingsTracker(),
otel_metrics=_FakeOtelMetrics(),
)
await metrics.record_request(
provider="anthropic",
model="claude-opus-4-6",
input_tokens=109844, # forwarded (post-compression) message count
output_tokens=25,
tokens_saved=1896,
tool_search_saved=13182, # deferred tool schemas never sent
latency_ms=10.0,
client="claude-code",
)
assert len(calls) == 1
# saved = tokens_saved + tool_search_saved; before = forwarded + saved.
assert calls[0]["tokens_after"] == 109844
assert calls[0]["tokens_before"] == 109844 + 1896 + 13182 # == 124922
@pytest.mark.asyncio
async def test_record_savings_event_written_for_deferral_only_turn(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A tool-heavy turn can defer thousands of tool-schema tokens while
tokens_saved is 0 (deferral does not move the message-level count). It must
still be recorded, not dropped from the ledger (#2795)."""
calls = _capture_ledger(monkeypatch)
metrics = prometheus_metrics.PrometheusMetrics(
savings_tracker=_FakeSavingsTracker(),
otel_metrics=_FakeOtelMetrics(),
)
await metrics.record_request(
provider="anthropic",
model="claude-opus-4-6",
input_tokens=50000,
output_tokens=25,
tokens_saved=0,
tool_search_saved=13182,
latency_ms=10.0,
client="claude-code",
)
assert len(calls) == 1
assert calls[0]["tokens_before"] == 50000 + 13182
assert calls[0]["tokens_after"] == 50000
@pytest.mark.asyncio
async def test_zero_saving_request_with_cache_breakdown_reaches_the_ledger(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A request that saved nothing but newly billed input is a denominator
observation for the new-input basis, so it must reach the ledger. One
without any breakdown is skipped as before."""
calls: list[dict[str, Any]] = []
monkeypatch.setattr(
prometheus_metrics.savings_ledger,
"record_savings_event",
lambda **kwargs: calls.append(kwargs),
)
metrics = prometheus_metrics.PrometheusMetrics(
savings_tracker=_FakeSavingsTracker(),
otel_metrics=_FakeOtelMetrics(),
)
await metrics.record_request(
provider="anthropic",
model="claude-opus-4-6",
input_tokens=10_000,
output_tokens=25,
tokens_saved=0,
latency_ms=10.0,
client="claude-code",
cache_read_tokens=5_000,
uncached_input_tokens=10_000,
)
assert len(calls) == 1
assert calls[0]["tokens_before"] == calls[0]["tokens_after"]
assert calls[0]["new_input_tokens"] == 10_000
await metrics.record_request(
provider="bedrock",
model="claude-opus-4-6",
input_tokens=10_000,
output_tokens=25,
tokens_saved=0,
latency_ms=10.0,
client="claude-code",
)
assert len(calls) == 1