Files
headroom/tests/test_cost_cache_prices.py
Tejas ChopraandClaude Opus 5.5 72302a3998 fix(proxy): say why proxy.log is missing and why a knob or extension was ignored (#4088)
## Description

Several failures an operator needs to see are swallowed silently or
logged only at DEBUG. This PR makes each of them visible with one
warning. It does not change defaults or control flow.

1. **Missing runtime log.** `_setup_file_logging` caught `OSError` with
`pass`. On a read-only workspace, a wrong owner, or a file where the
logs directory belongs, `proxy.log` simply never appeared and nothing
said why. It now logs `Headroom runtime log disabled: cannot write the
log file: <OSError>. Point HEADROOM_WORKSPACE_DIR at a writable
directory to restore proxy.log.` The OSError text names the path. The
symlink case just above it already warned this way.
2. **Six import-time numeric knobs.** Each one fell back to its default
on an unparseable value, without a word:
   - `HEADROOM_COMPRESSION_TIMEOUT_SECONDS`
   - `HEADROOM_COLD_START_FAST_PASS_TIMEOUT_SECONDS`
   - `HEADROOM_EAGER_PRELOAD_TIMEOUT_SECONDS`
   - `HEADROOM_COMPRESSION_CACHE_MAX_SESSIONS`
   - `HEADROOM_COMPRESSION_CACHE_TTL_SECONDS`
   - `HEADROOM_COMPRESSION_CACHE_MAX_ENTRIES`

Each now logs `Ignoring invalid NAME='value'; using DEFAULT` once, at
import. That matches the idiom in `hard_watchdog.py`.
3. **Extension discovery failure.** When entry-point enumeration fails,
every proxy extension is dropped, Enterprise plugins included. That was
logged at DEBUG. It is now a warning: `proxy extensions: entry-point
enumeration failed (<describe_exception>), so no proxy extensions will
be installed`. `describe_exception` gives the exception types and code
locations, never the message, and no traceback is logged at any level.
It runs at startup only: once in `install_all`, and once more for the
CLI banner.
4. **Pricing lookups in `cost.py`.** `_get_list_price`,
`_get_output_price`, `_get_cache_prices` and the cache-rate lookup in
the savings summary returned `None` on any exception. A pricing bug
therefore showed up as a $0 cost with no trace. All four, plus the
existing `estimate_cost` path, go through one helper,
`_warn_pricing_once(lookup, what, model, exc)`. Example line: `Failed to
get pricing for model 'gpt-4o': RuntimeError at
headroom/proxy/cost.py:... in estimate_cost`. It logs the lookup name,
`safe_id(model)` and `describe_exception(exc)` (types and code
locations, never the message), at WARNING only. No level carries the raw
exception or a traceback, because a pricing backend error can quote
provider responses or credentials. Dedupe is by `(lookup, model)`
through the shared `WarnOnce(1024, "unpriceable models")`. Each pair
warns at most once an hour (the `WarnOnce` window). Past 1024 models,
one overflow notice is logged, and a key is not used up while WARNING is
disabled.
5. **Malformed `HEADROOM_OPENAI_TOOL_SEARCH_MODELS` regex.** The
override was ignored on every request with no log. It now warns once per
bad pattern, and still falls back to the version gate as before. A valid
pattern re-arms the warning, so bad A, then valid B, then bad A again
warns twice.

None of the new lines logs header values, request content or
credentials. They log only knob names, their raw values (operator-set
env), model names, regex patterns, exception type names, the `re.error`
text, and `OSError` text naming a local path. No exception message or
traceback from pricing or extension discovery reaches any log level.

Refs #4136

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/proxy/helpers.py`:
- add `_warn_invalid_env_number(name, default)` and call it from the six
import-time `except ValueError` branches;
  - log the `OSError` in `_setup_file_logging`;
- add a once-per-pattern warning for a malformed
`HEADROOM_OPENAI_TOOL_SEARCH_MODELS`.
- `headroom/proxy/extensions.py`: entry-point enumeration failure logs
at warning with `describe_exception(exc)` instead of at debug.
- `headroom/proxy/cost.py`:
- the four silent pricing `except Exception` branches call
`_warn_pricing_once`;
- `_warn_pricing_once(lookup, what, model, exc)` logs `safe_id(model)`
plus `describe_exception(exc)` at WARNING, with nothing at DEBUG. It
dedupes through `log_safety.WarnOnce`.
- `tests/test_cost_pricing_warning_dedup.py`: the tests reset with a
fresh `WarnOnce`, and match the quoted model id (`for model
'glm-5.2':`).
- Regression tests. Each one attaches a handler to the module logger
directly, because caplog misses `headroom.*` records after proxy
startup. Each positive test fails on main and is paired with a negative
case that passes on both.
  - `tests/test_cache_breakpoint_diagnostics.py`:
- `test_runtime_log_says_why_it_is_missing` makes the logs directory a
regular file. It asserts one warning that names the path and
`HEADROOM_WORKSPACE_DIR`.
    - Negative: `test_runtime_log_stays_quiet_when_writable`.
  - `tests/test_openai_tool_search_deferral.py`:
- `test_malformed_override_warns_once_not_per_request` calls the gate 5
times with a bad pattern. It asserts exactly one warning and that the
version-gate result is unchanged.
    - Negative: a valid override is silent (same test).
- `test_valid_override_rearms_the_malformed_warning`: bad, valid, bad
gives two warnings.
  - `tests/test_proxy/test_compression_timeout_config.py`:
- `test_bad_env_says_it_was_ignored` reloads `helpers` with
`HEADROOM_COMPRESSION_TIMEOUT_SECONDS=not-a-number` and asserts the
exact warning.
- Negative: `test_valid_env_is_silent`. The existing fixture reloads
`helpers` afterwards.
  - `tests/test_proxy_extensions.py`:
- `test_discover_warns_when_entry_point_enumeration_fails` makes
`importlib.metadata.entry_points` raise. It asserts one WARNING that
says no extensions will be installed and names `RuntimeError` but not
the exception text.
    - Negative: `test_discover_is_quiet_when_nothing_is_installed`.
  - `tests/test_cost_cache_prices.py`:
- `test_cache_rate_failure_warns_once_per_model` makes `resolve_rates`
raise. It asserts two `_get_cache_prices` calls give one warning naming
the model and `RuntimeError`, without the exception text.
    - Negative: a resolvable model is silent (same test).
- `test_pricing_error_never_logs_its_text_at_any_level` runs the real
`CostTracker.estimate_cost('gpt-4o', 100, 10)` with a pricing error
whose text holds an Authorization credential canary, with
`headroom.proxy` at DEBUG. It formats every captured record with
`logging.Formatter` (which renders `exc_info`), asserts the canary is
absent and the result is `None`, and asserts the warning is present. On
the previous commit it fails: the formatted DEBUG traceback contains the
canary.

## 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
$ pytest -q tests/test_cost_cache_prices.py -k never_logs   # previous commit 3202058c (test adapted to its old dedupe set)
E     RuntimeError: upstream rejected request (Authorization: Bearer sk-canary-7f3a9c)']
======================= 1 failed, 25 deselected in 3.48s =======================
$ pytest -q -p no:cacheprovider tests/test_pr208_changes.py tests/test_cost_budget_basis.py tests/test_cost_tracker_counterfactual.py tests/test_cost_tracker_totals.py tests/test_tool_search_client_deferral.py tests/test_cache_breakpoint_diagnostics.py tests/test_proxy_cache_ttl_metrics.py tests/test_proxy_byte_faithful_forwarding.py tests/test_memory_tool_mode.py tests/test_codex_ws_compression_scheduler.py tests/test_proxy_savings_history.py tests/test_compression_cache_registry.py tests/test_proxy_extension_ordering.py tests/test_proxy_eager_preload_bind.py tests/test_perf_per_port_logs.py tests/test_cost_cache_prices.py tests/test_openai_tool_search_deferral.py tests/test_proxy_extensions.py tests/test_direct_chat_ccr_resolution.py tests/test_org_scale_limits.py tests/test_savings_ledger.py tests/test_cost_pricing_warning_dedup.py tests/test_proxy/test_compression_timeout_config.py tests/test_log_safety.py   # 64ff3f03
================== 517 passed, 1 skipped in 85.70s (0:01:25) ===================
$ pytest -q (same pricing/extension/regex/log/knob/log_safety files) after merging log-safety-helpers @ 0ce74a63   # 4ff57af4
======================== 139 passed, 1 skipped in 4.23s ========================
$ uvx ruff@0.16.8 check / format --check headroom/proxy/cost.py headroom/proxy/extensions.py tests/test_cost_cache_prices.py tests/test_cost_pricing_warning_dedup.py tests/test_proxy_extensions.py
All checks passed! / 5 files already formatted
$ mypy headroom/proxy/cost.py headroom/proxy/extensions.py --ignore-missing-imports
Success: no issues found in 2 source files
```

## Real Behavior Proof

- Environment: macOS, Python 3.12.13, branch checkout at 4ff57af4
(log-safety-helpers merged at 0ce74a63), using the repo .venv. A temp
HOME, workspace and CODEX_HOME were used each time; the real HOME was
not touched.
- Exact command / steps:
1. Ran the shared smoke harness, which starts a real proxy from this
checkout against a local fake upstream and sends one Anthropic and one
OpenAI request.
2. Ran the real `CostTracker.estimate_cost('gpt-4o', 100, 10)` twice,
with every logger at DEBUG and a LiteLLM stand-in whose `cost_per_token`
raises an error quoting `Authorization: Bearer sk-canary-7f3a9c`.
3. The earlier forced-failure run for the knob, log-directory and regex
warnings (d83e7d5c, below) is unchanged by this commit.
- Observed result:
```text
branch: cleanup/proxy-core-a-surface-ignored-config @ 4ff57af4
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines (<tmp>):
(smoke dir: <tmp>)
```
```text
WARNING headroom.proxy: Failed to get pricing for model 'gpt-4o': RuntimeError at <string>:8 in cost_per_token <- headroom/proxy/cost.py:999 in estimate_cost
result: None None
```
- One payload-safe WARNING appears, with the exception type and code
location, and both calls return `None`.
- The canary appears in no output line at any level: `grep -c canary`
over the whole run, LiteLLM's own DEBUG chatter included, gives 0.
  - Earlier forced-failure run:
```text
branch: cleanup/proxy-core-a-surface-ignored-config @ d83e7d5c
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines (<tmp>):
(smoke dir: <tmp>)
```
The harness also printed two pre-existing WARNING lines, which I left
out above: offline-mode air-gap active, and the Kompress model prefetch
refused offline. Neither comes from this PR. Output of the direct
command:
```text
WARNING headroom.proxy: Ignoring invalid HEADROOM_COMPRESSION_TIMEOUT_SECONDS='abc'; using 30.0
WARNING headroom.proxy: Headroom runtime log disabled: cannot write the log file: [Errno 17] File exists: '<tmp>/ws/logs'. Point HEADROOM_WORKSPACE_DIR at a writable directory to restore proxy.log.
WARNING headroom.proxy: Ignoring invalid HEADROOM_OPENAI_TOOL_SEARCH_MODELS regex '[bad' (unterminated character set at position 0); using the gpt-5.4+ version gate
gate: True True
```
- The proxy serves both providers, and the normal path adds no new
warnings.
- Each forced failure gives exactly one warning, even though the regex
gate ran twice. The fallbacks are unchanged: 30.0, and the version gate
is True for gpt-5.4.
- Not tested: A real read-only filesystem, a real broken
`importlib.metadata` and a live pricing-catalog failure (the stand-in
above raises from the same call). Each goes through the same `except`
branch that the unit tests force.

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A; log output only.
- Stable/default behavior changed: No. Every fallback value and code
path is the same; only new WARNING lines appear, when something was
already failing.
- Kill switch / disable path: N/A. A pricing warning fires at most once
an hour per (lookup, model), through `WarnOnce`; the regex warning fires
once per bad pattern.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.

## 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
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

Part of a maintainer-requested codebase cleanup (dead code, duplication,
debuggability), split into small PRs for review. It is part of
maintainer-requested cleanup #4136.

Depends on #4138; its two files show in this diff until it merges. #4137
also edits `_setup_file_logging`, so whichever of the two merges second
rebases.

Docs are unchanged because no knob's meaning changed. The doc impacts
are recorded in the cleanup docs ledger for the follow-up docs PR. The
six import-time knob warnings have no test: testing them would need
`importlib.reload(helpers)`, which would reset the module globals other
tests depend on.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:51:06 -07:00

439 lines
17 KiB
Python

"""Reconcile reported cache slices with model-specific LiteLLM billing.
Explicit catalog rates win independently. Missing rates use the canonical
calculator, whose fallback differs across supported versions and models;
unavailable calculations do not invent Headroom provider-wide prices.
Counterfactual savings and cache-card provenance remain separate from billing,
and inferred writes cannot double-charge the uncached input bucket.
"""
from __future__ import annotations
import logging
from types import SimpleNamespace
import pytest
from headroom.log_safety import WarnOnce
from headroom.pricing.counterfactual import resolve_rates
from headroom.proxy.cost import CostTracker
@pytest.fixture(autouse=True)
def clear_rate_cache():
resolve_rates.cache_clear()
yield
resolve_rates.cache_clear()
def _patch_litellm(monkeypatch: pytest.MonkeyPatch, model_cost: dict) -> None:
resolve_rates.cache_clear()
monkeypatch.setattr(
"headroom.pricing.counterfactual._litellm",
lambda: SimpleNamespace(model_cost=model_cost),
)
monkeypatch.setattr(
"headroom.pricing.litellm_pricing.resolve_litellm_model",
lambda model: model,
)
class TestGetCachePrices:
def test_uses_explicit_litellm_cache_fields_when_present(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
_patch_litellm(
monkeypatch,
{
"m": {
"input_cost_per_token": 1e-6,
"cache_read_input_token_cost": 1e-7,
"cache_creation_input_token_cost": 1.25e-6,
"litellm_provider": "anthropic",
}
},
)
assert CostTracker()._get_cache_prices("m") == (1e-7, 1.25e-6, 2e-6, 1e-6)
def test_missing_cache_fields_priced_at_zero_not_full_rate(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
# A model with an input price but no cache fields: exactly the 1600+
# long-tail models the bug affects. Before the fix both slices billed at
# the full uncached rate; now they fail closed at $0, reconciling with
# what litellm.cost_per_token books for the same slice.
_patch_litellm(
monkeypatch,
{"m": {"input_cost_per_token": 5e-7, "litellm_provider": "mistral"}},
)
assert CostTracker()._get_cache_prices("m") == (0.0, 0.0, 0.0, 5e-7)
def test_only_the_missing_field_is_zeroed(self, monkeypatch: pytest.MonkeyPatch) -> None:
# Explicit read cost present, write cost absent: keep the real read,
# fail closed on the write.
_patch_litellm(
monkeypatch,
{
"m": {
"input_cost_per_token": 1e-6,
"cache_read_input_token_cost": 3e-7,
"litellm_provider": "openai",
}
},
)
assert CostTracker()._get_cache_prices("m") == (3e-7, 0.0, 0.0, 1e-6)
def test_no_input_price_returns_none(self, monkeypatch: pytest.MonkeyPatch) -> None:
_patch_litellm(monkeypatch, {"m": {"litellm_provider": "anthropic"}})
assert CostTracker()._get_cache_prices("m") is None
@pytest.mark.parametrize(
"litellm_provider",
["bedrock", "bedrock_converse", "mistral", "fireworks_ai", "cohere_chat", None, "made-up"],
)
def test_heterogeneous_and_unknown_providers_do_not_inherit_anthropic_rates(
self, monkeypatch: pytest.MonkeyPatch, litellm_provider
) -> None:
# Regression: a missing cache field must never be back-filled with
# Anthropic's 0.1x/1.25x economics. Bedrock fronts Anthropic, Amazon,
# Meta, Mistral, Cohere and others; unknown OpenAI-compatible providers
# are likewise not Anthropic-priced.
uncached = 4e-6
info = {"input_cost_per_token": uncached}
if litellm_provider is not None:
info["litellm_provider"] = litellm_provider
_patch_litellm(monkeypatch, {"m": info})
cache_read, cache_write, cache_write_1h, got_uncached = CostTracker()._get_cache_prices("m")
assert got_uncached == uncached
assert cache_read == 0.0
assert cache_write == 0.0
assert cache_write_1h == 0.0
# Explicitly not the Anthropic multipliers the old fallback would apply.
assert cache_read != pytest.approx(uncached * 0.1)
assert cache_write != pytest.approx(uncached * 1.25)
def test_missing_cache_slices_match_canonical_zero_pricing(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The missing cache slices are priced at $0, the same amount the canonical
litellm.cost_per_token path books for a slice LiteLLM cannot price, so the
cache breakdown reconciles with the primary accounting instead of diverging.
"""
_patch_litellm(
monkeypatch,
{"m": {"input_cost_per_token": 5e-7, "litellm_provider": "fireworks_ai"}},
)
cr_price, cw_price, _, uncached_price = CostTracker()._get_cache_prices("m")
cr_tokens, cw_tokens = 20_000, 5_000
# Cache-slice cost contributed to totals() is exactly $0, matching canonical.
assert cr_tokens * cr_price + cw_tokens * cw_price == 0.0
assert uncached_price == 5e-7
def test_totals_and_stats_charge_only_known_slices(self, monkeypatch):
_patch_litellm(monkeypatch, {"m": {"input_cost_per_token": 5e-7}})
tracker = CostTracker()
tracker.record_tokens(
model="m",
tokens_saved=0,
tokens_sent=26_000,
cache_read_tokens=20_000,
cache_write_tokens=5_000,
uncached_tokens=1_000,
)
assert tracker.totals() == (26_000, 0.0005)
assert tracker.stats()["total_input_cost_usd"] == 0.0005
def test_missing_read_preserves_explicit_write_and_ttl_tier(self, monkeypatch):
_patch_litellm(
monkeypatch,
{
"m": {
"input_cost_per_token": 1e-6,
"input_cost_per_token_above_200k_tokens": 2e-6,
"cache_creation_input_token_cost": 1.25e-6,
"cache_creation_input_token_cost_above_200k_tokens": 2.5e-6,
"cache_creation_input_token_cost_above_1hr": 2e-6,
}
},
)
assert CostTracker()._get_cache_prices("m") == (0.0, 1.25e-6, 2e-6, 1e-6)
assert CostTracker()._get_cache_prices("m", long_context=True) == (
0.0,
2.5e-6,
4e-6,
2e-6,
)
def test_savings_provider_ratio_remains_separate_from_billed_prices(self, monkeypatch):
_patch_litellm(monkeypatch, {"m": {"input_cost_per_token": 1e-6}})
assert resolve_rates("m", provider="anthropic").read == 1e-7
assert CostTracker()._get_cache_prices("m")[0] == 0.0
def test_missing_write_price_keeps_live_zone_and_tool_savings(self, monkeypatch):
_patch_litellm(monkeypatch, {"m": {"input_cost_per_token": 1e-6}})
tracker = CostTracker()
tracker.record_tokens(
model="m",
tokens_saved=10_000,
tokens_sent=10_000,
cache_write_tokens=10_000,
tool_schema_saved=5_000,
)
stats = tracker.stats()
assert stats["total_input_cost_usd"] == 0.0
assert stats["cache_aware_savings_usd"] == pytest.approx(0.01)
assert stats["tool_savings_usd"] == pytest.approx(0.005)
@pytest.mark.parametrize("cache_read_price", [None, "invalid"])
def test_unknown_read_rate_is_not_advertised_as_catalog_free_cache(
self, monkeypatch, cache_read_price
):
from headroom.proxy.cost import build_prefix_cache_stats
from headroom.proxy.prometheus_metrics import PrometheusMetrics
_patch_litellm(
monkeypatch,
{
"gpt-unknown": {
"input_cost_per_token": 1e-6,
"cache_read_input_token_cost": cache_read_price,
}
},
)
tracker = CostTracker()
tracker._tokens_sent_by_model["gpt-unknown"] = 1_000_000
monkeypatch.setattr(tracker, "_get_list_price", lambda model: 1.0)
metrics = PrometheusMetrics()
metrics.cache_by_provider["openai"].update(
{
"requests": 1,
"hit_requests": 1,
"cache_read_tokens": 1_000_000,
}
)
row = build_prefix_cache_stats(metrics, tracker)["by_provider"]["openai"]
assert row["cache_pricing_source"] == "provider_default"
assert row["savings_usd"] == pytest.approx(0.5)
def test_canonical_litellm_cache_only_cost_matches_dashboard(self, monkeypatch):
import litellm
from headroom.pricing.litellm_pricing import resolve_litellm_model
# Keep the actual canonical calculator, with a deterministic catalog
# row: the shared test suite enriches real model rows with cache rates.
model = "openai/headroom-missing-cache-rate-regression"
monkeypatch.setitem(
litellm.model_cost,
model,
{
"input_cost_per_token": 5e-7,
"output_cost_per_token": 1e-6,
"litellm_provider": "openai",
"mode": "chat",
},
)
resolved = resolve_litellm_model(model)
info = litellm.model_cost[resolved]
assert info.get("cache_read_input_token_cost") is None
assert info.get("cache_creation_input_token_cost") is None
canonical, _ = litellm.cost_per_token(
model=resolved,
prompt_tokens=10_000,
completion_tokens=0,
cache_read_input_tokens=10_000,
)
tracker = CostTracker()
tracker.record_tokens(
model=model, tokens_saved=0, tokens_sent=10_000, cache_read_tokens=10_000
)
assert tracker.totals()[1] == round(canonical, 4)
@pytest.mark.parametrize("long_context", [False, True])
def test_missing_catalog_rates_use_the_model_specific_canonical_calculation(
self, monkeypatch, long_context
):
resolve_rates.cache_clear()
monkeypatch.setattr(
"headroom.pricing.litellm_pricing.resolve_litellm_model", lambda model: model
)
calls = []
def canonical(**kwargs):
calls.append(kwargs)
factor = 2 if kwargs["prompt_tokens"] > 200_000 else 1
return (
factor
* (
kwargs.get("cache_read_input_tokens", 0) * 4e-7
+ kwargs.get("cache_creation_input_tokens", 0) * 1e-6
),
0.0,
)
monkeypatch.setattr(
"headroom.pricing.counterfactual._litellm",
lambda: SimpleNamespace(
model_cost={
"m": {
"input_cost_per_token": 1e-6,
"input_cost_per_token_above_200k_tokens": 2e-6,
}
},
cost_per_token=canonical,
),
)
factor = 2 if long_context else 1
assert CostTracker()._get_cache_prices("m", long_context=long_context) == (
4e-7 * factor,
1e-6 * factor,
1e-6 * factor,
1e-6 * factor,
)
assert len(calls) == 2
assert all(
call["model"] == "m" and call["prompt_tokens"] == (200_001 if long_context else 1)
for call in calls
)
def test_inferred_writes_are_not_billed_twice_with_canonical_rates(self, monkeypatch):
_patch_litellm(
monkeypatch,
{
"m": {
"input_cost_per_token": 1e-6,
"cache_read_input_token_cost": 5e-7,
"cache_creation_input_token_cost": 1e-6,
}
},
)
tracker = CostTracker()
tracker.record_tokens(
model="m",
tokens_saved=0,
tokens_sent=20_000,
cache_read_tokens=10_000,
cache_write_tokens=10_000,
cache_write_5m_tokens=10_000,
uncached_tokens=10_000,
cache_inferred=True,
)
assert tracker.totals()[1] == pytest.approx(0.015)
assert tracker.stats()["total_input_cost_usd"] == pytest.approx(0.015)
assert tracker._api_cache_write_by_model["m"] == 0
assert tracker._api_cache_write_5m_by_model["m"] == 0
def test_explicit_zero_cache_tier_and_one_hour_prices_are_authoritative(self, monkeypatch):
_patch_litellm(
monkeypatch,
{
"m": {
"input_cost_per_token": 1e-6,
"input_cost_per_token_above_200k_tokens": 2e-6,
"cache_read_input_token_cost": 1e-7,
"cache_read_input_token_cost_above_200k_tokens": 0.0,
"cache_creation_input_token_cost": 1.25e-6,
"cache_creation_input_token_cost_above_200k_tokens": 0.0,
"cache_creation_input_token_cost_above_1hr": 0.0,
}
},
)
assert CostTracker()._get_cache_prices("m")[2] == 0.0
assert CostTracker()._get_cache_prices("m", long_context=True) == (
0.0,
0.0,
0.0,
2e-6,
)
def test_explicit_list_rate_cache_prices_do_not_inherit_provider_discounts(self, monkeypatch):
_patch_litellm(
monkeypatch,
{
"m": {
"input_cost_per_token": 1e-6,
"cache_read_input_token_cost": 1e-6,
"cache_creation_input_token_cost": 1e-6,
}
},
)
rates = resolve_rates("m", provider="anthropic")
assert rates.read == rates.write_5m == 1e-6
assert rates.read_is_catalog and rates.write_is_catalog
class _Capture(logging.Handler):
def __init__(self) -> None:
super().__init__(logging.DEBUG)
self.records: list[logging.LogRecord] = []
def emit(self, record: logging.LogRecord) -> None:
self.records.append(record)
def test_cache_rate_failure_warns_once_per_model(monkeypatch: pytest.MonkeyPatch) -> None:
"""A raising rate resolver used to read as 'unpriced' ($0) with no trace."""
from headroom.proxy import cost
monkeypatch.setattr(cost, "_pricing_warnings", WarnOnce(1024, "unpriceable models"))
_patch_litellm(
monkeypatch,
{"m": {"input_cost_per_token": 1e-6, "litellm_provider": "anthropic"}},
)
capture = _Capture()
cost.logger.addHandler(capture)
try:
assert CostTracker()._get_cache_prices("m") is not None
assert not capture.records # a resolvable model is silent
def broken(*_args, **_kwargs):
raise RuntimeError("pricing table corrupt")
monkeypatch.setattr("headroom.pricing.counterfactual.resolve_rates", broken)
assert CostTracker()._get_cache_prices("m") is None
assert CostTracker()._get_cache_prices("m") is None
finally:
cost.logger.removeHandler(capture)
warnings = [r.getMessage() for r in capture.records if r.levelno == logging.WARNING]
assert len(warnings) == 1
assert "for model 'm'" in warnings[0] and "RuntimeError" in warnings[0]
assert "pricing table corrupt" not in warnings[0]
_CREDENTIAL_CANARY = "Authorization: Bearer sk-canary-7f3a9c"
def test_pricing_error_never_logs_its_text_at_any_level(monkeypatch: pytest.MonkeyPatch) -> None:
"""A pricing backend error quoting a credential must not reach any log record.
Formats every WARNING and DEBUG record with a real Formatter, which renders
exc_info too, so a traceback carrying the text would be caught.
"""
from headroom.proxy import cost
class _LeakyLiteLLM:
model_cost: dict = {}
@staticmethod
def cost_per_token(**_kwargs):
raise RuntimeError(f"upstream rejected request ({_CREDENTIAL_CANARY})")
monkeypatch.setattr(cost, "_pricing_warnings", WarnOnce(1024, "unpriceable models"))
monkeypatch.setattr(cost, "_get_litellm_module", lambda: _LeakyLiteLLM())
monkeypatch.delenv("HEADROOM_DEBUG_DUMP", raising=False)
capture = _Capture()
previous_level = cost.logger.level
cost.logger.setLevel(logging.DEBUG)
cost.logger.addHandler(capture)
try:
assert CostTracker().estimate_cost("gpt-4o", 100, 10) is None
finally:
cost.logger.removeHandler(capture)
cost.logger.setLevel(previous_level)
formatter = logging.Formatter()
rendered = [formatter.format(r) for r in capture.records if r.levelno >= logging.DEBUG]
assert any("Failed to get pricing for model 'gpt-4o'" in line for line in rendered)
assert all("sk-canary" not in line for line in rendered), rendered