headroom/tests/test_cost_budget_basis.py
Parideboy 01df245252
fix(proxy/cost): mark estimated-basis budget records and add an enforcement policy (#2713) (#2725)
## Description

`CostTracker.check_budget()` is a hard spend control — the Anthropic
handler refuses the request with a 429 once the period budget is gone.
The ledger that control reads could not tell a measured dollar from a
guessed one.

When a provider response carries no input-token breakdown,
`record_tokens()` substitutes Headroom's own `tokens_sent` estimate for
the input count so input cost isn't silently dropped from the budget.
That fallback is the right call, but the resulting record was
byte-identical to a provider-measured one: no field, no log line, no
separation in `/stats`. `RequestOutcome.uncached_input_tokens` defaults
to `0`, so any route whose response omits usage lands on this branch in
production. An estimate can drift in either direction, so a budget check
could pass after real spend had already gone over — with nothing saying
the decision rested on an estimate.

This keeps the fallback and makes it visible, then lets operators decide
what an estimate is allowed to do to a hard limit.

Closes #2713

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- New `headroom/proxy/budget_basis_policy.py` (pure policy module,
matching the existing `*_policy.py` convention): the
`measured`/`estimated` basis constants, the `count`/`ignore`/`block`
policy values, and `resolve_estimated_basis_policy()` (explicit value →
`HEADROOM_BUDGET_ESTIMATED_BASIS` → `count`; an unknown value warns once
and falls back rather than failing proxy startup).
- `headroom/proxy/cost.py`: ledger entries are now `CostEntry(timestamp,
cost_usd, basis)` instead of a bare tuple; `record_tokens()` marks the
fallback branch `estimated` and logs one WARNING per model (deduped the
same way pricing warnings are, per #2504 — an unguarded warning on this
path fires once per request for a provider that never reports usage);
new `period_cost_breakdown()` and an optional `basis` filter on
`get_period_cost()`; new `budget_denial_detail()` builds the 429 body
where the ledger lives; `check_budget()` honors the policy while keeping
its `(allowed, remaining)` signature.
- `stats()` gains `budget_estimated_basis` (the active policy) and
`budget_basis` (the period split: `total_usd`, `measured_usd`,
`estimated_usd`, `estimated_pct`, `records`, `estimated_records`).
`merge_cost_stats()` already spreads `**cost_stats`, so both reach
`/stats["cost"]` with no extra plumbing.
- Operator knob wired through every config layer:
`ProxyConfig.budget_estimated_basis` (`models.py`), the Click
`--budget-estimated-basis` option with `envvar=` (`cli/proxy.py`), the
argparse `--budget-estimated-basis` flag (`server.py`, `default=None` so
the env var stays reachable), and a `SettingField` in the `Budget` group
(`settings_store.py`).
- `headroom/proxy/handlers/anthropic.py`: the 429 body now comes from
`budget_denial_detail()`, which names how much of the period's spend was
booked from an estimate and distinguishes "you overspent" from "I refuse
to enforce a hard limit on a guess".
- `headroom/cli/doctor.py`: the budget check stays **PASS** and appends
the estimated share (and the policy, when it isn't the default). No new
WARN state — a provider that never reports usage would otherwise sit at
a permanent WARN. Every new read is `.get()` + type-guarded so `doctor`
still works against an older running proxy.
- `docs/content/docs/metrics.mdx`: a "Measured vs Estimated Spend"
subsection with the `/stats` shape and the three policy values.
- Tests: new `tests/test_cost_budget_basis.py` (20 tests) plus 4 new
`doctor` tests; `tests/test_anthropic_pre_upstream_backpressure.py`'s
cost-tracker double gained `budget_denial_detail()` to match the
handler's duck-typed contract.

### Policy values

| `HEADROOM_BUDGET_ESTIMATED_BASIS` | Effect on the hard limit |
|---|---|
| `count` (default) | Unchanged behavior — estimated spend consumes the
budget. |
| `ignore` | Booked and reported, but only measured spend enforces. |
| `block` | Fail closed — refuse rather than enforce a hard limit on a
guess. |

Default enforcement is unchanged. `CHANGELOG.md` is untouched.

## Testing

- [x] Unit tests pass (`pytest`) — every test covering the changed
modules; see `Not tested` for this machine's pre-existing environment
failures
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`) — clean on every file this
PR touches
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ python -m pytest tests/test_cost_budget_basis.py tests/test_cost_tracker_counterfactual.py tests/test_cost_pricing_warning_dedup.py -q
31 passed

$ python -m pytest tests/test_cli_doctor.py -q
72 passed

$ python -m pytest tests/test_anthropic_pre_upstream_backpressure.py -q
25 passed

$ python -m pytest tests/test_proxy_settings_endpoints.py tests/test_proxy/test_settings_store.py -q
50 passed

# full suite (see "Not tested" below for the excluded modules and the pre-existing failures)
$ python -m pytest -q
...
tests\test_cost_budget_basis.py ....................                     [ 25%]
tests\test_cost_pricing_warning_dedup.py ...                             [ 25%]
tests\test_cost_tracker_counterfactual.py ........                       [ 25%]
...
217 failed, 8807 passed, 657 skipped, 5318 warnings, 59 errors in 716.30s (0:11:56)

# same failing files re-run on clean upstream/main with the change stashed -> identical count
$ git stash push -u -- headroom tests docs
$ python -m pytest tests/test_log_compressor.py tests/test_cache/test_client_integration.py \
    tests/test_fsutil.py tests/test_savings_ledger.py tests/test_ccr_mcp_http.py \
    tests/test_router_registry_dispatch.py tests/test_proxy_savings_history.py \
    tests/test_text_compressors.py tests/test_builtin_compressor_adapters.py \
    tests/test_cli_proxy_env.py -q
73 failed, 182 passed in 34.82s     # 40+16+2+2+1+1+1+4+3+3 = 73, matching the run above

$ python -m mypy headroom --ignore-missing-imports --python-version 3.13
# 12 errors, all in release_version.py / ccr/mcp_server.py / memory/mcp_server.py
# (stale local `mcp` stubs) — none in any file this PR touches

$ python -m ruff check headroom/proxy/budget_basis_policy.py headroom/proxy/cost.py headroom/proxy/server.py headroom/proxy/models.py headroom/proxy/handlers/anthropic.py headroom/cli/proxy.py headroom/cli/doctor.py headroom/settings_store.py tests/test_cost_budget_basis.py tests/test_cli_doctor.py tests/test_anthropic_pre_upstream_backpressure.py
All checks passed!

$ python -m ruff format --check <same 11 files>
11 files already formatted
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.13.11, branch
`fix/budget-estimated-basis-2713` off `upstream/main` @ `232fb49c`,
`PYTHONPATH` pointed at the working tree so the repo copy of `headroom`
is imported rather than the installed one.
- Exact command / steps: ran the repro script from the issue body
verbatim, then extended it to print `stats()["budget_basis"]` for both
trackers, to construct the same tracker with
`estimated_basis_policy="block"` and with `"ignore"`, and to record
twice against the same model to check the warning dedup. Separately
drove `headroom doctor`'s `check_budget` against stub `/stats` payloads
(mixed basis, all-measured, non-default policy, and an older proxy that
omits the new keys).
- Observed result: the issue's two figures are unchanged, so the
fallback still works — no breakdown `$0.008100`, with breakdown
`$0.005100`, ratio `1.59x`. The two are now separable: the no-breakdown
tracker reports `{'total_usd': 0.0081, 'measured_usd': 0.0,
'estimated_usd': 0.0081, 'estimated_pct': 100.0, 'records': 1,
'estimated_records': 1}` and the with-breakdown tracker reports
`estimated_usd: 0.0, estimated_pct: 0.0, estimated_records: 0`. One
`WARNING headroom.proxy: budget basis estimated: no usage breakdown from
provider for gpt-4o-mini — input cost booked from Headroom's own token
count` fires across repeated records, not one per request. With
`policy=block`, `check_budget()` returns `(False, 0.0)` and the 429
detail reads `Budget enforcement blocked for daily period: $0.0081 of
$0.0081 was booked from Headroom's own token estimate because the
provider returned no usage breakdown, and
HEADROOM_BUDGET_ESTIMATED_BASIS=block refuses to enforce a budget on an
estimate. Set it to 'count' or 'ignore' to serve these requests.` With
`policy=ignore`, `check_budget()` returns `(True, 0.0001)` while the
spend is still booked and reported (`0.7506`). `doctor` prints `pass
$10.0/daily budget enforced — 62% of period spend ($1.2400) booked from
Headroom token estimates`, appends `— estimated-basis policy: block` for
a non-default policy, and degrades to the plain `$10.0/daily budget
enforced` against a proxy that doesn't report the new fields.
`--budget-estimated-basis [count|ignore|block]` shows in `headroom proxy
--help`; the argparse path resolves the env var when the flag is absent
and an explicit flag wins over the env.
- Not tested: no live end-to-end run against a real provider that omits
usage in its response — the estimated basis was exercised through
`record_tokens()` directly, which is the single funnel
`emit_request_outcome()` uses. The `settings_store` field was not
exercised through the settings UI. The full-suite run above excludes
three things this machine cannot run, none of which touch the changed
files: `tests/test_hermes_passthrough_compression.py` (`respx` not
installed), `tests/test_memory/test_embedder_mps_serialization.py`
(`sentence_transformers` pins `tokenizers<=0.23.0`, local has `0.23.1`),
and `tests/test_cli/` (its subprocess-spawning tests wedge against a
leftover local proxy on :8787; each file passes in isolation, e.g.
`test_wrap_bridge.py` 7/7). Its 217 failures are all pre-existing
environment breakage — a stale local Rust `_core` build
(`test_log_compressor.py`, `test_text_compressors.py`,
`test_builtin_compressor_adapters.py`, `test_cli_proxy_env.py`, the
`test_transforms*` files) and the broken `sentence_transformers` install
(`tests/test_memory/*`, `test_memory_system.py`,
`test_sqlite_graph_store.py`) — with zero overlap with the modules this
PR changes; the stashed baseline above reproduces them 1:1. CI is the
authority for a green full suite.

## 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
- [x] 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 — the
only local failures are pre-existing and reproduce with the change
stashed
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

The estimated-basis WARNING is deduped per model rather than emitted per
request, following the precedent set by #2504 for pricing warnings — the
whole point of this code path is that it fires on every request for a
provider that never reports usage, so an unguarded `logger.warning`
would flood `proxy.log`.

`headroom doctor` deliberately stays PASS. A WARN would be permanent,
not actionable, for anyone whose provider simply doesn't report usage;
the note tells them the number, and the `block` policy is there for
operators who want the hard failure.

`check_budget()` keeps its `(allowed, remaining)` signature and its
default `count` semantics, so
`tests/test_cost_tracker_counterfactual.py` — including
`test_budget_input_cost_counted_without_usage_breakdown`, the contract
that the fallback keeps working — passes unmodified.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 23:05:44 -07:00

306 lines
11 KiB
Python

"""Budget records must say whether their input count was measured or estimated.
#2713: when a provider response carries no input-token breakdown,
``record_tokens`` substitutes Headroom's own ``tokens_sent`` for the input
count. The fallback is right — dropping input cost would under-enforce far
worse — but the resulting record used to be indistinguishable from a
provider-measured one, so ``check_budget`` (a hard control) could refuse or
allow on the strength of a guess with nothing saying so.
These tests pin the marking, the deduped warning, the separable ledger, and
the three operator policies.
"""
from __future__ import annotations
import logging
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")
MODEL = "claude-sonnet-4-20250514"
@pytest.fixture(autouse=True)
def _reset_warning_dedup():
"""The per-model warn-once set is module-global; keep tests order-independent."""
import headroom.proxy.cost as cost_mod
cost_mod._warned_estimated_basis_models.clear()
yield
cost_mod._warned_estimated_basis_models.clear()
def _tracker(**kwargs):
from headroom.proxy.server import CostTracker
return CostTracker(**kwargs)
# ── Basis marking ────────────────────────────────────────────────────
def test_missing_usage_breakdown_books_estimated_basis():
"""No breakdown → the record is marked estimated and reported as such."""
ct = _tracker(budget_limit_usd=100.0)
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=50_000, output_tokens=1_000)
basis = ct.stats()["budget_basis"]
assert basis["estimated_usd"] > 0
assert basis["measured_usd"] == 0
assert basis["estimated_records"] == 1
assert basis["estimated_pct"] == 100.0
def test_provider_breakdown_books_measured_basis():
"""A reported breakdown → measured; nothing lands in the estimated bucket."""
ct = _tracker(budget_limit_usd=100.0)
ct.record_tokens(
MODEL,
tokens_saved=0,
tokens_sent=50_000,
uncached_tokens=30_000,
output_tokens=1_000,
)
basis = ct.stats()["budget_basis"]
assert basis["measured_usd"] > 0
assert basis["estimated_usd"] == 0
assert basis["estimated_records"] == 0
assert basis["estimated_pct"] == 0.0
def test_cache_read_only_response_counts_as_measured():
"""A fully cache-read turn reports usage, so it is not an estimate."""
ct = _tracker(budget_limit_usd=100.0)
ct.record_tokens(
MODEL,
tokens_saved=0,
tokens_sent=50_000,
cache_read_tokens=40_000,
output_tokens=1_000,
)
assert ct.stats()["budget_basis"]["estimated_usd"] == 0
def test_mixed_records_stay_separable_and_sum_to_total():
"""Default policy is unchanged: the budget still sees every booked dollar."""
ct = _tracker(budget_limit_usd=100.0)
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=50_000, output_tokens=1_000)
ct.record_tokens(
MODEL,
tokens_saved=0,
tokens_sent=50_000,
uncached_tokens=30_000,
output_tokens=1_000,
)
basis = ct.stats()["budget_basis"]
assert basis["records"] == 2
assert basis["estimated_records"] == 1
assert basis["measured_usd"] > 0
assert basis["estimated_usd"] > 0
assert basis["total_usd"] == pytest.approx(basis["measured_usd"] + basis["estimated_usd"])
# Regression guard: `count` (the default) enforces against total spend
# exactly as it did before this change.
assert ct.get_period_cost() == pytest.approx(basis["total_usd"])
def test_get_period_cost_can_filter_by_basis():
ct = _tracker(budget_limit_usd=100.0)
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=50_000, output_tokens=1_000)
ct.record_tokens(
MODEL, tokens_saved=0, tokens_sent=50_000, uncached_tokens=30_000, output_tokens=1_000
)
measured = ct.get_period_cost("measured")
estimated = ct.get_period_cost("estimated")
assert measured > 0
assert estimated > 0
assert ct.get_period_cost() == pytest.approx(measured + estimated)
# ── Warning ──────────────────────────────────────────────────────────
def test_estimated_basis_warns_once_per_model(caplog):
"""A route that never reports usage must not flood proxy.log (cf. #2504)."""
ct = _tracker(budget_limit_usd=100.0)
with caplog.at_level(logging.WARNING, logger="headroom.proxy"):
for _ in range(5):
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=10_000, output_tokens=100)
hits = [r for r in caplog.records if "budget basis estimated" in r.getMessage()]
assert len(hits) == 1
assert MODEL in hits[0].getMessage()
def test_distinct_models_each_warn_once(caplog):
ct = _tracker(budget_limit_usd=100.0)
other = "claude-haiku-4-5-20251001"
with caplog.at_level(logging.WARNING, logger="headroom.proxy"):
for model in (MODEL, MODEL, other, other):
ct.record_tokens(model, tokens_saved=0, tokens_sent=10_000, output_tokens=100)
msgs = [r.getMessage() for r in caplog.records if "budget basis estimated" in r.getMessage()]
assert sum(MODEL in m for m in msgs) == 1
assert sum(other in m for m in msgs) == 1
def test_measured_records_do_not_warn(caplog):
ct = _tracker(budget_limit_usd=100.0)
with caplog.at_level(logging.WARNING, logger="headroom.proxy"):
ct.record_tokens(
MODEL, tokens_saved=0, tokens_sent=10_000, uncached_tokens=9_000, output_tokens=100
)
assert not [r for r in caplog.records if "budget basis estimated" in r.getMessage()]
# ── Enforcement policies ─────────────────────────────────────────────
def test_count_policy_lets_estimated_spend_exhaust_the_budget():
"""Default: an estimate consumes the budget, as it always has."""
ct = _tracker(budget_limit_usd=0.0001, estimated_basis_policy="count")
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=500_000, output_tokens=10_000)
allowed, remaining = ct.check_budget()
assert not allowed
assert remaining == 0
def test_ignore_policy_keeps_estimated_spend_out_of_enforcement():
"""`ignore`: the record is still booked and reported, but doesn't enforce."""
ct = _tracker(budget_limit_usd=0.0001, estimated_basis_policy="ignore")
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=500_000, output_tokens=10_000)
allowed, _remaining = ct.check_budget()
assert allowed
# Still visible in the ledger — ignored for enforcement, not dropped.
assert ct.stats()["budget_basis"]["estimated_usd"] > 0
def test_ignore_policy_still_enforces_measured_spend():
ct = _tracker(budget_limit_usd=0.0001, estimated_basis_policy="ignore")
ct.record_tokens(
MODEL,
tokens_saved=0,
tokens_sent=500_000,
uncached_tokens=500_000,
output_tokens=10_000,
)
allowed, _remaining = ct.check_budget()
assert not allowed
def test_block_policy_refuses_once_any_estimated_spend_exists():
"""`block`: fail closed rather than enforce a hard limit on a guess."""
ct = _tracker(budget_limit_usd=1_000_000.0, estimated_basis_policy="block")
allowed, _remaining = ct.check_budget()
assert allowed # nothing booked yet
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=1_000, output_tokens=10)
allowed, remaining = ct.check_budget()
assert not allowed
assert remaining == 0.0
def test_block_policy_is_inert_without_a_budget_limit():
"""No limit configured means no hard control to protect."""
ct = _tracker(budget_limit_usd=None, estimated_basis_policy="block")
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=1_000, output_tokens=10)
allowed, remaining = ct.check_budget()
assert allowed
assert remaining == float("inf")
def test_block_policy_allows_purely_measured_traffic():
ct = _tracker(budget_limit_usd=1_000_000.0, estimated_basis_policy="block")
ct.record_tokens(
MODEL, tokens_saved=0, tokens_sent=1_000, uncached_tokens=900, output_tokens=10
)
allowed, _remaining = ct.check_budget()
assert allowed
def test_invalid_policy_falls_back_to_count():
ct = _tracker(budget_limit_usd=0.0001, estimated_basis_policy="nonsense")
assert ct.estimated_basis_policy == "count"
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=500_000, output_tokens=10_000)
allowed, _remaining = ct.check_budget()
assert not allowed
# ── Denial message ───────────────────────────────────────────────────
def test_denial_detail_names_the_estimated_share():
ct = _tracker(budget_limit_usd=0.0001)
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=500_000, output_tokens=10_000)
detail = ct.budget_denial_detail()
assert "Budget exceeded for daily period" in detail
assert "Headroom token estimates" in detail
def test_denial_detail_unchanged_for_purely_measured_spend():
ct = _tracker(budget_limit_usd=0.0001)
ct.record_tokens(
MODEL,
tokens_saved=0,
tokens_sent=500_000,
uncached_tokens=500_000,
output_tokens=10_000,
)
assert ct.budget_denial_detail() == "Budget exceeded for daily period"
def test_block_denial_is_distinguishable_from_overspend():
ct = _tracker(budget_limit_usd=1_000_000.0, estimated_basis_policy="block")
ct.record_tokens(MODEL, tokens_saved=0, tokens_sent=1_000, output_tokens=10)
detail = ct.budget_denial_detail()
assert "Budget enforcement blocked" in detail
assert "HEADROOM_BUDGET_ESTIMATED_BASIS=block" in detail
# ── Policy resolver ──────────────────────────────────────────────────
def test_resolver_precedence_and_fallback():
from headroom.proxy.budget_basis_policy import resolve_estimated_basis_policy
env = {"HEADROOM_BUDGET_ESTIMATED_BASIS": "ignore"}
assert resolve_estimated_basis_policy("block", env) == "block" # explicit wins
assert resolve_estimated_basis_policy(None, env) == "ignore" # env next
assert resolve_estimated_basis_policy(None, {}) == "count" # default
assert resolve_estimated_basis_policy(None, None) == "count"
assert resolve_estimated_basis_policy("BLOCK", None) == "block" # normalized
assert resolve_estimated_basis_policy("nope", None) == "count" # fallback
def test_stats_reports_the_active_policy():
ct = _tracker(budget_limit_usd=10.0, estimated_basis_policy="block")
assert ct.stats()["budget_estimated_basis"] == "block"
assert ct.stats()["budget_basis"]["policy"] == "block"