Files
headroom/tests/test_observability_metrics.py
2038fb2a36 fix(metrics): cap savings_by_source rows and fold the rest into other (#4257)
## Description

### What we found

`PrometheusMetrics.savings_by_source` keeps one row per `(source,
realized)` for the life of the process, and `/metrics` exports three
series per row (`headroom_savings_attribution_events_total`,
`headroom_savings_attributed_tokens_total`,
`headroom_savings_attributed_usd_total`). Source names come from
extensions and turn hooks (`ctx.record_savings`,
`record_scope_savings`). A plugin that puts something per-request into a
source name would grow the table, and the exported series, without
bound.

@JerrettDavis raised this in the review of #4233. #4233 bounds the
per-request ledger (256 named rows plus `other`). This PR applies the
same bound to the process-wide table, which #4233 deliberately left
alone.

## Type of Change

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

## Changes Made

- `MAX_DISTINCT_SAVINGS_ROWS = 256` in
`headroom/proxy/prometheus_metrics.py`, next to `MAX_DISTINCT_PATHS`. It
follows the same pattern as the model and path caps in that file:
  - an existing row keeps accumulating;
- past the cap, a new source is summed into an `other` row with the same
`realized` flag;
- one warning is logged the first time, and `reset_runtime` re-arms it.
- As in the per-request ledger, `tool_search` never folds here (shared
`UNFOLDED_SOURCES`): the documented headline query selects
`source="tool_search"`, so a tool-search saving first seen after the cap
keeps its named row.
- Only the source name is lost. Every token, dollar and event is still
booked. Every reader of `savings_by_source` (`cost.py`'s
realized/projected USD sums, `/stats` `savings.by_source`, the
`/metrics` export) adds rows together, so their totals are unchanged.

### Before / after

| 306 distinct sources, plus `tool_search` on every request |
origin/main | this PR |
|---|---|---|
| `savings_by_source` rows | 307 | 257 (255 named + `tool_search` +
`other`) |
| exported `headroom_savings_attributed_tokens_total` series | 307 | 257
|
| tokens / USD / events booked | all | all |

## 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

-
`tests/test_observability_metrics.py::test_prometheus_metrics_caps_savings_source_cardinality`:
306 requests each book a new realized source plus an estimated
`tool_search` row through `record_request`. The test asserts 257 rows,
257 exported series, `tool_search` keeps its own row, and tokens, USD
and events are conserved. It also checks that `reset_runtime` re-arms
the warning. With the cap disabled it fails with `assert 307 == (256 +
1)`.
-
`tests/test_observability_metrics.py::test_tool_search_first_seen_after_the_savings_cap_keeps_its_row[True|False]`:
256 plugin rows fill the table, then `tool_search` and another new
source arrive. `tool_search` keeps its own row and exported series with
all 100 tokens, while the other new source goes to `other`. Both cases
fail before 7196e28d.
- Known edge, past 256 sources only: once #4233 lands, a source folded
here that also calls `record_extension_savings` appears in
`extension_savings` both under its name and inside `other`.
- Related suites pass: `test_observability_metrics.py`,
`test_extension_attribution.py`, `test_compression_observability.py`,
`test_turn_hooks.py` (78 passed).
- `ruff check`, `ruff format --check` and `mypy` pass on the changed
files.

### Test Output

```text
# cap disabled:
E   AssertionError: assert 307 == (256 + 1)
# with the cap:
78 passed in 10.51s
```

## Real Behavior Proof

- Environment: macOS 26.7, Python 3.12, this branch running `headroom
proxy` on 127.0.0.1:8799 with an isolated HOME. Claude Code 2.1.302
(`claude-sonnet-5-5`) and Codex CLI 0.153.2 (`gpt-5.6-terra`, Responses
over WebSocket) ran through it with real API keys.
- Exact command / steps: both clients ran the same prompt ("read each
.py file in this directory one at a time, then list each file's
top-level functions") over three source files. Then `GET /stats` and
`GET /metrics`.
- Observed result: both clients completed (Claude 5 requests, Codex 9).
`/stats` `savings.by_source` and `/metrics` show the `tool_search` row
(5 events, 70,315 tokens) exactly as on main. No cap warning was logged,
because real traffic stays far below the cap.
- Not tested: a real plugin that mints unbounded source names. The cap
path is covered by the unit test.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: only past 256 distinct savings rows
in one process, where new sources report as `other`
- Kill switch / disable path: none needed; reporting only
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR

## Review Readiness

- [x] I have performed a self-review
  - plus the code-reviewer agent
- [x] This PR is ready for human review

## Additional Notes

- This PR touches a different hunk of `record_request` from #4233, which
changes `+ 1` to `+ event_count(item)` a few lines below. The two merge
cleanly in either order.

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

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4257"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

## Maintainer post-merge qualification
Published `883a1a1f6085ed84ef7bacff69bcbd9ffaa098d1` incorporates
upstream main `e4a60ed72f6ef5b28569f8bfbe2163cfda32c948`. 20
observability tests pass; both realized/non-realized late tool_search
probes still fold the semantic label into other after arbitrary-label
saturation. Ruff/format/diff pass; clean main sync, cap implementation
unchanged. Existing Changes Requested decision remains applicable;
unchanged findings are not reposted. Scoped Windows probes use the real
CLI configuration harness or actual metrics object, not live
cloud-provider traffic. Contributor correctness logic was not rewritten;
hosted checks are handled by maintainers. Nothing merged.


### Maintainer current-main requalification

Exact head `50514a724dd98ce672717eeb31344c88c13aeb1e`, upstream main
`ecbaf86d78cf52d185fbffa306157b9a4cc1b906`.

Mechanically updated from upstream/main
ecbaf86d78 with a clean merge and no
contributor cap-policy rewrite. Re-reviewed existing discussion and
integration delta. All 30 existing observability/Gemini cases pass;
Ruff0.17.3 lint/format and whitespace checks pass.

Both existing late-arriving semantic-source probes still fail after
filling the row budget with arbitrary plugin labels: tool_search:1 and
tool_search:0 are absent, with their 100 tokens folded into the
respective other row. The probe verifies aggregate tokens are retained
before asserting source identity, so this is the documented
semantic-source/consumer problem rather than total-token loss. Retain
the prior requested bounded tool_search source independently of
arbitrary labels, cover both realized flags after saturation, and
correct the claim that no consumer reads this table by source. This is
not an inherited-main CI failure. Maintainers handle hosted checks; no
contributor CI execution requested. Nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `20d7c9e9f00d83f7a5ec23dfbb2c30af6fa6aa06`, upstream main
`8d3e9e5ca7cd645eb73084b848edbea5fc796e1a`.

Clean mechanical sync with upstream
main8d3e9e5ca7cd645eb73084b848edbea5fc796e1a with no contributor cap
policy rewrite. Current discussion/source
reviewed.30observability/Gemini tests pass;2changed Python files
Ruff0.17.3check/format and whitespace pass.

Both late-source saturation probes freshly fail: after256arbitrary
plugin rows, late tool_search is absent for realized=true and false and
its100tokens fold into other. The aggregate356tokens survives, but
semantic source identity does not. Preserve important source identity
under saturation and qualify actual overflow behavior; existing
aggregate-only tests do not establish that contract. No inherited-main
pipeline defect is alleged. Copied extension supports Python startup,
not a new native build. Maintainers handle hosted checks; nothing
merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `4decdc96f1fa14fc8389bffd586ed15072a7b6fa`, upstream main
`2d3ee51846435ef5b320eea4806af14e602b0d8c`.

Clean integration with upstream/main
2d3ee51846. Re-reviewed current discussion
and composed metrics code. Exact comparison of prometheus_metrics.py and
its observability tests against prior reviewed 20d7c9e9f shows no
changes. All 107 observability/release/version/MCP/memory/Gemini tests
pass; whitespace passes. Earlier changed-file lint/format remains scoped
to identical inputs.

Existing source-identity saturation blocker remains: a late tool_search
source after 256 arbitrary plugin rows folds its 100 tokens into other
for either realized value. Total accounting survives, but important
source identity does not. The previous probes cover identical metrics
inputs and were not relabeled as rerun. Preserve the existing request to
retain important identities under overflow and test actual saturation
behavior. No contributor cap policy rewritten or inherited-main CI
defect attributed. Existing native extension used for Python startup,
not a fresh native build. Maintainers handle checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `d8f67f36052d270489a4ff26b1b36ab112d2afa3`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Clean integration with upstream/main
c01cf07d94 without changing contributor
cap/allocation policy. Re-reviewed current author discussion, metrics
consumers and Devin findings. All20 observability tests pass with the
fresh current-main native binding; Ruff and whitespace pass.

The existing late-source identity blocker freshly reproduces for both
realized=True and realized=False: after256 arbitrary plugin rows, a
first tool_search attribution of100 tokens becomes other. Aggregate
tokens remain correct, but no tool_search named row exists. The
documented headline query in docs/metrics-technical-guide.md still
filters source="tool_search", so it omits this saving. Please preserve
required semantic identities under saturation (or provide an equivalent
bounded headline counter), and cover first-seen-late realized/projected
tool-search events in regression/runtime proof. Numeric conservation
alone does not prove the documented metric contract.

The OpenTelemetry implementation is byte-identical to main; its existing
source-label behavior is not added as a PR-specific approval hold. No
contributor correctness logic rewritten, no live
collector/native-rebuild claim and no inherited-main pipeline defect
attributed. Maintainers handle hosted checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `d9c47a5521080675c4f6e0a0a3dc66fb8c72d79c`, upstream main
`da6d9736cd82074988c7d0a2360b49d9d8b6c0a0`.

Current-main requalification against
da6d9736cd. All69 integration patches
exactly match c01cf07-to-current-main delta after diff-location
normalization; contributor cap/allocation policy unchanged.20
observability tests pass.31 changed Python files pass Ruff lint/format;
offline lock and whitespace pass. Existing pr3982 native DLL verified
complete native input hashes/artifact checksum; no fresh build or live
collector claim. Author/Devin discussions and metric consumers
re-reviewed. Existing late-source identity blocker freshly reproduces
for realized=True and False: after256 plugin rows, first
tool_search100tokens becomes other; aggregate conserved but named
tool_search row absent. docs/metrics-technical-guide.md headline query
filters source=tool_search and omits that saving. Preserve required
semantic identities under saturation or supply equivalent bounded
headline counter; cover first-seen-late realized/projected tool_search
events. Main-identical OpenTelemetry behavior is not a PR-specific hold.
Maintainers handle hosted checks; no contributor correctness logic
rewritten or merge.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `fa88cf4bcab5e3db9448a1b3cc5f628b07a81a48`, upstream main
`0ddaa56c21cdc01c4774391fdcc69e987ecc4e5c`.

Clean integration with upstream/main
0ddaa56c21. All 19 integration patches
exactly match the prior-reviewed-main da6d9736 to current-main delta
after diff-location normalization; contributor cap/allocation policy is
unchanged. Fresh observability, doctor and incoming Vertex/backend/CLI
suite: 309 passed, 11 skipped, 1 warning. Fourteen changed Python files
pass Ruff lint/format; offline lock and whitespace checks pass.

Author/Devin discussion and metric-consumer contract reviewed. Both
synthetic saturation probes freshly reproduce the existing late-source
identity finding: after 256 plugin rows, first tool_search 100 tokens
folds into other for realized=True and False. Aggregate tokens are
conserved, but the documented source=tool_search query misses that
saving. Preserve required semantic identity under saturation or provide
an equivalent bounded headline counter, with first-seen-late
realized/projected regressions. No live collector behavior claimed.
Static production/test diff is scoped to metrics aggregation and
synthetic in-memory coverage; no new workflow/dependency/setup path. The
inherited flagged workflow-validation job is excluded by unchanged
workflow paths. Complete native input set/hashes and artifact checksum
verified before DLL reuse; no fresh build claimed. Main-identical
OpenTelemetry behavior is not attributed to this PR. Maintainers handle
exact-head checks; no PR merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-07 20:34:12 -06:00

729 lines
25 KiB
Python

"""Tests for OTEL-backed operational observability."""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import Any
import pytest
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from headroom.observability import (
HeadroomOtelMetrics,
get_otel_meter,
register_otel_metric_attribute_provider,
reset_otel_metrics,
set_otel_metrics,
unregister_otel_metric_attribute_provider,
)
from headroom.proxy.prometheus_metrics import (
MAX_DISTINCT_PATHS,
MAX_DISTINCT_SAVINGS_ROWS,
PrometheusMetrics,
)
from headroom.telemetry.context import MAX_DISTINCT_MODELS
from headroom.transforms.pipeline import TransformPipeline
def _collect_metrics(reader: InMemoryMetricReader) -> dict[str, Any]:
data = reader.get_metrics_data()
collected: dict[str, Any] = {}
for resource_metric in data.resource_metrics:
for scope_metric in resource_metric.scope_metrics:
for metric in scope_metric.metrics:
collected[metric.name] = metric
return collected
def _find_point(metric: Any, **expected_attributes: Any) -> Any:
for point in metric.data.data_points:
if all(point.attributes.get(key) == value for key, value in expected_attributes.items()):
return point
raise AssertionError(f"No datapoint matched attributes: {expected_attributes}")
def test_headroom_otel_metrics_records_proxy_and_pipeline_metrics() -> None:
reader = InMemoryMetricReader()
provider = MeterProvider(metric_readers=[reader])
otel_metrics = HeadroomOtelMetrics(meter_provider=provider)
otel_metrics.record_proxy_request(
provider="anthropic",
model="claude-opus-4-6",
input_tokens=120,
output_tokens=30,
tokens_saved=45,
tool_search_saved=15,
latency_ms=18.5,
cached=True,
overhead_ms=4.0,
ttfb_ms=12.0,
cache_read_tokens=25,
cache_write_tokens=35,
cache_write_5m_tokens=10,
cache_write_1h_tokens=25,
uncached_input_tokens=60,
attempted_input_tokens=165,
output_tokens_saved=8,
savings_usd={
"compression": 0.001,
"tool_schema": 0.0003,
"output_shaping": 0.0008,
"provider_cache": 0.0002,
},
project="checkout",
client="claude-code",
)
otel_metrics.record_proxy_cache_bust(tokens_lost=7)
otel_metrics.record_pipeline_run(
model="claude-opus-4-6",
provider="anthropic",
tokens_before=120,
tokens_after=75,
duration_ms=6.5,
timing={"_deep_copy": 0.2, "router": 3.5, "pipeline_total": 6.5},
transforms_applied=["router:smart_crusher:0.35"],
waste_signals={"json_bloat": 12},
)
metrics = _collect_metrics(reader)
requests = metrics["headroom.proxy.requests"]
request_point = _find_point(
requests,
provider="anthropic",
model="claude-opus-4-6",
cached=True,
)
assert request_point.value == 1
saved_tokens = metrics["headroom.proxy.tokens.saved"]
saved_point = _find_point(
saved_tokens,
provider="anthropic",
model="claude-opus-4-6",
cached=True,
)
assert saved_point.value == 60
tool_schema_saved = metrics["headroom.proxy.tokens.tool_schema_saved"]
tool_schema_point = _find_point(
tool_schema_saved,
provider="anthropic",
model="claude-opus-4-6",
cached=True,
)
assert tool_schema_point.value == 15
attempted_input = metrics["headroom.proxy.tokens.attempted_input"]
attempted_point = _find_point(
attempted_input,
**{
"headroom.project": "checkout",
"headroom.client": "claude-code",
},
)
assert attempted_point.value == 165
output_saved = metrics["headroom.proxy.tokens.output_saved"]
output_saved_point = _find_point(
output_saved,
**{
"headroom.project": "checkout",
"headroom.client": "claude-code",
},
)
assert output_saved_point.value == 8
savings_usd = metrics["headroom.proxy.savings.usd"]
compression_usd = _find_point(savings_usd, source="compression", estimated=True)
assert compression_usd.value == pytest.approx(0.001)
compression_saved = metrics["headroom.compression.tokens.saved"]
compression_saved_point = _find_point(
compression_saved,
provider="anthropic",
model="claude-opus-4-6",
)
assert compression_saved_point.value == 45
latency = metrics["headroom.proxy.request.duration"]
latency_point = _find_point(
latency,
provider="anthropic",
model="claude-opus-4-6",
cached=True,
)
assert latency_point.count == 1
assert latency_point.sum == pytest.approx(0.0185)
ttl_tokens = metrics["headroom.proxy.cache.write_ttl_tokens"]
five_minute_ttl = _find_point(
ttl_tokens,
provider="anthropic",
model="claude-opus-4-6",
ttl="5m",
)
assert five_minute_ttl.value == 10
compression_runs = metrics["headroom.compression.runs"]
compression_point = _find_point(
compression_runs,
provider="anthropic",
model="claude-opus-4-6",
)
assert compression_point.value == 1
stage_duration = metrics["headroom.compression.stage.duration"]
router_stage = _find_point(
stage_duration,
provider="anthropic",
model="claude-opus-4-6",
stage="router",
)
assert router_stage.count == 1
assert router_stage.sum == pytest.approx(0.0035)
assert len(stage_duration.data.data_points) == 1
waste_tokens = metrics["headroom.compression.waste.tokens"]
waste_point = _find_point(
waste_tokens,
provider="anthropic",
model="claude-opus-4-6",
signal="json_bloat",
)
assert waste_point.value == 12
def test_get_otel_meter_uses_headrooms_configured_provider() -> None:
reader = InMemoryMetricReader()
provider = MeterProvider(metric_readers=[reader])
set_otel_metrics(HeadroomOtelMetrics(meter_provider=provider))
try:
meter = get_otel_meter("example.integration", "1.0.0")
meter.create_counter("example.integration.events").add(1, {"source": "test"})
metric = _collect_metrics(reader)["example.integration.events"]
point = _find_point(metric, source="test")
assert point.value == 1
finally:
reset_otel_metrics()
def test_request_attribute_provider_enriches_core_and_savings_metrics() -> None:
reader = InMemoryMetricReader()
provider = MeterProvider(metric_readers=[reader])
otel_metrics = HeadroomOtelMetrics(meter_provider=provider)
def identity_attributes() -> dict[str, str]:
return {
"headroom.org": "acme",
"headroom.team": "payments",
"headroom.user": "alice",
# Canonical call-site dimensions must win over an extension.
"model": "must-not-override",
"source": "must-not-override",
}
register_otel_metric_attribute_provider(identity_attributes)
try:
otel_metrics.record_proxy_request(
provider="anthropic",
model="claude-sonnet-4-5",
input_tokens=100,
output_tokens=10,
tokens_saved=25,
latency_ms=20,
)
otel_metrics.record_savings_attribution(
[{"source": "tool_search", "tokens": 20, "usd": 0.001}]
)
metrics = _collect_metrics(reader)
request = _find_point(
metrics["headroom.proxy.requests"],
model="claude-sonnet-4-5",
**{
"headroom.org": "acme",
"headroom.team": "payments",
"headroom.user": "alice",
},
)
assert request.value == 1
attributed = _find_point(
metrics["headroom.savings.attributed.tokens"],
source="tool_search",
**{"headroom.user": "alice"},
)
assert attributed.value == 20
finally:
unregister_otel_metric_attribute_provider(identity_attributes)
def test_coalesced_savings_rows_count_every_event() -> None:
"""A row summed from 33 recordings is 33 events, not 1; a bare row is 1."""
reader = InMemoryMetricReader()
otel_metrics = HeadroomOtelMetrics(meter_provider=MeterProvider(metric_readers=[reader]))
otel_metrics.record_savings_attribution(
[
{"source": "tool_search", "tokens": 3_300, "events": 33},
{"source": "router", "tokens": 5},
]
)
events = _collect_metrics(reader)["headroom.savings.attribution.events"]
assert _find_point(events, source="tool_search").value == 33
assert _find_point(events, source="router").value == 1
def test_failing_request_attribute_provider_is_fail_open() -> None:
reader = InMemoryMetricReader()
provider = MeterProvider(metric_readers=[reader])
otel_metrics = HeadroomOtelMetrics(meter_provider=provider)
def broken_provider() -> dict[str, str]:
raise RuntimeError("identity unavailable")
register_otel_metric_attribute_provider(broken_provider)
try:
otel_metrics.record_proxy_failed(provider="openai", model="gpt-5")
point = _find_point(
_collect_metrics(reader)["headroom.proxy.requests.failed"],
provider="openai",
model="gpt-5",
)
assert point.value == 1
finally:
unregister_otel_metric_attribute_provider(broken_provider)
@dataclass
class _SpyMetrics:
pipeline_calls: list[dict[str, Any]] = field(default_factory=list)
def record_pipeline_run(self, **kwargs: Any) -> None:
self.pipeline_calls.append(kwargs)
@dataclass
class _SpyProxyMetrics:
request_calls: list[dict[str, Any]] = field(default_factory=list)
failed_calls: list[dict[str, Any]] = field(default_factory=list)
rate_limited_calls: list[dict[str, Any]] = field(default_factory=list)
def record_proxy_request(self, **kwargs: Any) -> None:
self.request_calls.append(kwargs)
def record_proxy_failed(self, **kwargs: Any) -> None:
self.failed_calls.append(kwargs)
def record_proxy_rate_limited(self, **kwargs: Any) -> None:
self.rate_limited_calls.append(kwargs)
def test_transform_pipeline_simulate_skips_metric_recording() -> None:
spy = _SpyMetrics()
set_otel_metrics(spy) # type: ignore[arg-type]
try:
pipeline = TransformPipeline(transforms=[])
messages = [{"role": "user", "content": "hello world"}]
pipeline.apply(messages, model="gpt-4o", model_limit=1024)
assert len(spy.pipeline_calls) == 1
pipeline.simulate(messages, model="gpt-4o", model_limit=1024)
assert len(spy.pipeline_calls) == 1
finally:
reset_otel_metrics()
def test_proxy_failure_and_rate_limit_metrics_include_provider_labels() -> None:
reader = InMemoryMetricReader()
provider = MeterProvider(metric_readers=[reader])
otel_metrics = HeadroomOtelMetrics(meter_provider=provider)
otel_metrics.record_proxy_failed(provider="openai")
otel_metrics.record_proxy_rate_limited(provider="anthropic", model="claude-sonnet")
metrics = _collect_metrics(reader)
failed_point = _find_point(metrics["headroom.proxy.requests.failed"], provider="openai")
assert failed_point.value == 1
rate_limited_point = _find_point(
metrics["headroom.proxy.requests.rate_limited"],
provider="anthropic",
model="claude-sonnet",
)
assert rate_limited_point.value == 1
@pytest.mark.asyncio
async def test_prometheus_metrics_reads_late_configured_otel_metrics() -> None:
spy = _SpyProxyMetrics()
metrics = PrometheusMetrics()
set_otel_metrics(spy) # type: ignore[arg-type]
try:
await metrics.record_failed(provider="openai")
await metrics.record_rate_limited(provider="anthropic", model="claude-sonnet")
assert spy.failed_calls == [{"provider": "openai", "model": None}]
# ``source`` reaches OTel too — the split must not exist in Prometheus only.
assert spy.rate_limited_calls == [
{"provider": "anthropic", "model": "claude-sonnet", "source": "headroom"}
]
finally:
reset_otel_metrics()
@pytest.mark.asyncio
async def test_prometheus_metrics_forwards_rate_limit_source_to_otel() -> None:
"""An upstream 429 must reach OTel labelled as upstream, not as our own limiter."""
spy = _SpyProxyMetrics()
metrics = PrometheusMetrics(stateless=True)
set_otel_metrics(spy) # type: ignore[arg-type]
try:
await metrics.record_rate_limited(provider="anthropic", source="upstream")
await metrics.record_rate_limited(provider="anthropic", source="headroom")
# An unrecognised value is clamped rather than exported as a new label.
await metrics.record_rate_limited(provider="anthropic", source="nonsense")
assert [call["source"] for call in spy.rate_limited_calls] == [
"upstream",
"headroom",
"headroom",
]
finally:
reset_otel_metrics()
def test_otel_rate_limited_counter_carries_source_attribute() -> None:
reader = InMemoryMetricReader()
provider = MeterProvider(metric_readers=[reader])
otel_metrics = HeadroomOtelMetrics(meter_provider=provider)
otel_metrics.record_proxy_rate_limited(provider="anthropic", source="upstream")
otel_metrics.record_proxy_rate_limited(provider="openai", source="headroom")
metrics = _collect_metrics(reader)
upstream = _find_point(
metrics["headroom.proxy.requests.rate_limited"], provider="anthropic", source="upstream"
)
headroom_side = _find_point(
metrics["headroom.proxy.requests.rate_limited"], provider="openai", source="headroom"
)
assert upstream.value == 1
assert headroom_side.value == 1
@pytest.mark.asyncio
async def test_prometheus_metrics_forwards_savings_drilldown_fields_to_otel(
monkeypatch: pytest.MonkeyPatch,
) -> None:
expected_usd = {
"compression": 0.003,
"tool_schema": 0.0,
"output_shaping": 0.004,
"provider_cache": 0.0,
}
monkeypatch.setattr(
"headroom.proxy.prometheus_metrics.estimate_request_savings_usd",
lambda *_args, **_kwargs: expected_usd,
)
spy = _SpyProxyMetrics()
metrics = PrometheusMetrics(stateless=True)
set_otel_metrics(spy) # type: ignore[arg-type]
try:
await metrics.record_request(
provider="anthropic",
model="claude-sonnet-4-5",
input_tokens=90,
output_tokens=12,
tokens_saved=30,
latency_ms=5.0,
attempted_input_tokens=120,
output_tokens_saved=4,
project="checkout",
client="claude-code",
)
assert len(spy.request_calls) == 1
call = spy.request_calls[0]
assert call["attempted_input_tokens"] == 120
assert call["output_tokens_saved"] == 4
assert call["savings_usd"] == expected_usd
assert call["project"] == "checkout"
assert call["client"] == "claude-code"
finally:
reset_otel_metrics()
@pytest.mark.asyncio
async def test_prometheus_metrics_clamps_negative_token_savings() -> None:
metrics = PrometheusMetrics()
await metrics.record_request(
provider="openai",
model="openai-compatible",
input_tokens=100,
output_tokens=5,
tokens_saved=-25,
latency_ms=1.0,
)
assert metrics.tokens_saved_total == 0
assert metrics.savings_history[-1][1] == 0
@pytest.mark.asyncio
async def test_prometheus_metrics_caps_model_cardinality() -> None:
"""A client sending unbounded distinct models cannot grow the per-model dicts
past MAX_DISTINCT_MODELS + the "other" sentinel, while accounting stays exact."""
metrics = PrometheusMetrics(stateless=True)
async def record(model: str) -> None:
await metrics.record_request(
provider="anthropic",
model=model,
input_tokens=10,
output_tokens=1,
tokens_saved=1,
latency_ms=1.0,
cache_read_tokens=1, # enter the prefix-cache block -> _cache_requests_by_model
)
# Fill exactly to the cap with distinct models: no bucketing yet.
for i in range(MAX_DISTINCT_MODELS):
await record(f"model_{i}")
assert len(metrics.requests_by_model) == MAX_DISTINCT_MODELS
assert len(metrics._cache_requests_by_model) == MAX_DISTINCT_MODELS
assert "other" not in metrics.requests_by_model
# New distinct models past the cap bucket into "other", never their own key.
for i in range(5):
await record(f"overflow_{i}")
assert "overflow_0" not in metrics.requests_by_model
assert metrics.requests_by_model["other"] == 5
assert metrics._cache_requests_by_model["other"] == 5
assert len(metrics.requests_by_model) == MAX_DISTINCT_MODELS + 1
assert len(metrics._cache_requests_by_model) == MAX_DISTINCT_MODELS + 1
# An already-tracked model keeps incrementing after the cap is reached.
await record("model_0")
assert metrics.requests_by_model["model_0"] == 2
# Accounting is preserved: every request is counted somewhere.
total_calls = MAX_DISTINCT_MODELS + 5 + 1
assert metrics.requests_total == total_calls
assert sum(metrics.requests_by_model.values()) == total_calls
@pytest.mark.asyncio
async def test_prometheus_metrics_model_cardinality_warns_once(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Bucketing into "other" logs exactly one warning, not one per request."""
metrics = PrometheusMetrics(stateless=True)
with caplog.at_level(logging.WARNING, logger="headroom.proxy"):
for i in range(MAX_DISTINCT_MODELS + 10):
await metrics.record_request(
provider="openai",
model=f"model_{i}",
input_tokens=10,
output_tokens=1,
tokens_saved=1,
latency_ms=1.0,
)
cap_warnings = [r for r in caplog.records if "cardinality cap" in r.getMessage()]
assert len(cap_warnings) == 1
@pytest.mark.asyncio
async def test_prometheus_metrics_reset_rearms_cardinality_warning() -> None:
"""reset_runtime clears the model dicts and re-arms the one-shot cap warning."""
metrics = PrometheusMetrics(stateless=True)
for i in range(MAX_DISTINCT_MODELS + 5):
await metrics.record_request(
provider="openai",
model=f"model_{i}",
input_tokens=1,
output_tokens=1,
tokens_saved=1,
latency_ms=1.0,
cache_read_tokens=1,
)
assert metrics._model_cardinality_warned is True
await metrics.reset_runtime()
assert metrics._model_cardinality_warned is False
assert len(metrics.requests_by_model) == 0
assert len(metrics._cache_requests_by_model) == 0
def test_prometheus_metrics_caps_inbound_path_cardinality() -> None:
"""A client hitting unbounded distinct paths (ID-bearing passthrough routes)
cannot grow inbound_requests_by_path past MAX_DISTINCT_PATHS + the "other"
sentinel, while the total request count stays exact."""
metrics = PrometheusMetrics(stateless=True)
# Fill exactly to the cap with distinct paths: no bucketing yet.
for i in range(MAX_DISTINCT_PATHS):
metrics.record_inbound_request(method="GET", path=f"/v1/files/file_{i}")
assert len(metrics.inbound_requests_by_path) == MAX_DISTINCT_PATHS
assert "other" not in metrics.inbound_requests_by_path
# New distinct paths past the cap bucket into "other", never their own key.
for i in range(5):
metrics.record_inbound_request(method="GET", path=f"/v1/responses/resp_{i}")
assert "/v1/responses/resp_0" not in metrics.inbound_requests_by_path
assert metrics.inbound_requests_by_path["other"] == 5
assert len(metrics.inbound_requests_by_path) == MAX_DISTINCT_PATHS + 1
# An already-tracked path keeps incrementing after the cap is reached.
metrics.record_inbound_request(method="GET", path="/v1/files/file_0")
assert metrics.inbound_requests_by_path["/v1/files/file_0"] == 2
# Accounting is preserved: every inbound request is counted somewhere.
total_calls = MAX_DISTINCT_PATHS + 5 + 1
assert metrics.inbound_requests_total == total_calls
assert sum(metrics.inbound_requests_by_path.values()) == total_calls
def test_prometheus_metrics_path_cardinality_warns_once(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Bucketing inbound paths into "other" logs exactly one warning."""
metrics = PrometheusMetrics(stateless=True)
with caplog.at_level(logging.WARNING, logger="headroom.proxy"):
for i in range(MAX_DISTINCT_PATHS + 10):
metrics.record_inbound_request(method="GET", path=f"/v1/files/file_{i}")
cap_warnings = [r for r in caplog.records if "path cardinality cap" in r.getMessage()]
assert len(cap_warnings) == 1
@pytest.mark.asyncio
async def test_prometheus_metrics_reset_rearms_path_cardinality_warning() -> None:
"""reset_runtime clears the path dict and re-arms the one-shot cap warning."""
metrics = PrometheusMetrics(stateless=True)
for i in range(MAX_DISTINCT_PATHS + 5):
metrics.record_inbound_request(method="GET", path=f"/v1/files/file_{i}")
assert metrics._path_cardinality_warned is True
await metrics.reset_runtime()
assert metrics._path_cardinality_warned is False
assert len(metrics.inbound_requests_by_path) == 0
@pytest.mark.asyncio
async def test_prometheus_metrics_caps_savings_source_cardinality() -> None:
"""An extension that names a new savings source per request cannot grow
savings_by_source, or its exported series, past MAX_DISTINCT_SAVINGS_ROWS plus
one "other" row per realized flag, and every token and dollar is still booked."""
metrics = PrometheusMetrics(stateless=True)
sources = MAX_DISTINCT_SAVINGS_ROWS + 50
for i in range(sources):
await metrics.record_request(
provider="openai",
model="gpt-4o",
input_tokens=10,
output_tokens=1,
tokens_saved=0,
latency_ms=1.0,
savings_attribution=[
{"source": f"plugin_{i}", "realized": True, "tokens": 100, "usd": 0.01},
{"source": "tool_search", "realized": False, "tokens": 10},
],
)
rows = metrics.savings_by_source
assert len(rows) == MAX_DISTINCT_SAVINGS_ROWS + 1
assert rows["tool_search:0"]["tokens"] == 10 * sources
assert sum(int(r["tokens"]) for r in rows.values()) == 110 * sources
assert sum(float(r["usd"]) for r in rows.values()) == pytest.approx(0.01 * sources)
assert sum(int(r["events"]) for r in rows.values()) == 2 * sources
exported = await metrics.export()
series = [
line
for line in exported.splitlines()
if line.startswith("headroom_savings_attributed_tokens_total{")
]
assert len(series) == MAX_DISTINCT_SAVINGS_ROWS + 1
assert metrics._savings_source_cardinality_warned is True
await metrics.reset_runtime()
assert metrics._savings_source_cardinality_warned is False
assert metrics.savings_by_source == {}
@pytest.mark.asyncio
@pytest.mark.parametrize("realized", [True, False])
async def test_tool_search_first_seen_after_the_savings_cap_keeps_its_row(realized) -> None:
"""The headline query selects source="tool_search", so a tool-search saving
that first arrives after the cap must keep its named row, not fold."""
metrics = PrometheusMetrics(stateless=True)
for i in range(MAX_DISTINCT_SAVINGS_ROWS):
await metrics.record_request(
provider="openai",
model="gpt-4o",
input_tokens=10,
output_tokens=1,
tokens_saved=0,
latency_ms=1.0,
savings_attribution=[{"source": f"plugin_{i}", "realized": realized, "tokens": 1}],
)
await metrics.record_request(
provider="openai",
model="gpt-4o",
input_tokens=10,
output_tokens=1,
tokens_saved=0,
latency_ms=1.0,
savings_attribution=[
{"source": "tool_search", "realized": realized, "tokens": 100},
{"source": "late_plugin", "realized": realized, "tokens": 7},
],
)
rows = metrics.savings_by_source
assert rows[f"tool_search:{int(realized)}"]["tokens"] == 100
assert rows[f"other:{int(realized)}"]["tokens"] == 7
exported = await metrics.export()
assert (
f'headroom_savings_attributed_tokens_total{{realized="{str(realized).lower()}",'
f'source="tool_search"}} 100' in exported
)
@pytest.mark.asyncio
async def test_prometheus_metrics_export_bounds_model_series() -> None:
"""export() emits at most MAX_DISTINCT_MODELS model series plus the 'other' bucket."""
metrics = PrometheusMetrics(stateless=True)
for i in range(MAX_DISTINCT_MODELS + 20):
await metrics.record_request(
provider="openai",
model=f"model_{i}",
input_tokens=1,
output_tokens=1,
tokens_saved=1,
latency_ms=1.0,
)
text = await metrics.export()
series = text.count("headroom_requests_by_model{")
assert series <= MAX_DISTINCT_MODELS + 1
assert 'headroom_requests_by_model{model="other"}' in text