Files
headroom/tests/test_persistent_metrics_integration.py
Tejas ChopraandClaude Opus 5 5ff4ea1ef9 fix(metrics): split rate-limited by source and label failures by provider (#3707)
Closes #3696. #3615 moved the outcome-funnel short-circuit from `>= 500`
to `>= 400` — correct, and staying — but it silently changed what two
metrics mean and the docs were never updated.

**⚠️ This changes exported series. See Migration.**

## What was wrong

- `headroom_requests_failed_total` was documented as "Upstream 5xx
errors"; it now counts 4xx too.
- `headroom_requests_rate_limited_total` was documented as "Requests
**Headroom** rejected via its own rate limiter (**not upstream 429s**)"
— #3615 inverted exactly that.
- 4xx also dropped out of `headroom_requests_by_provider` (only
`record_request` touches it), leaving Prometheus with no way to tell
which upstream was failing.

## Changes


**`headroom_requests_rate_limited_total{source="headroom"|"upstream"}`**
— two 429s mean opposite things to an operator: `headroom` is our
limiter refusing (raise the cap), `upstream` is the provider refusing
(back off / shard keys). Closed label set, so cardinality stays bounded;
unknown values clamp to `headroom`, the counter's pre-#3615 meaning, so
an un-updated caller cannot invent a label. Threaded at all five call
sites (`openai.py:3554, 5681`, `anthropic.py:1256`, `gemini.py:405` →
`headroom`; `outcome.py:543`, the #3615 funnel → `upstream`).

**`headroom_requests_failed_total{provider}`** — uses
`outcome.provider`, already Copilot-relabelled by the funnel, so no
second convention. Matches the existing
`upstream_connection_errors_by_provider` shape.

**All four backends**, so no sink reports a differently-shaped counter:
Prometheus, persistent/lifetime
(`SavingsTracker.record_lifetime_rate_limited`), OTel (attribute on
`headroom.proxy.requests.rate_limited`), and `/stats` JSON.
`SCHEMA_VERSION` stays 5 — the new maps are purely additive, and old
state files load with them empty rather than back-filling invented
history.

**Docs**: `docs/metrics-technical-guide.md`,
`docs/content/docs/metrics.mdx`, `wiki/metrics.md`, plus tooltips on the
dashboard's Failed / Rate Limited tiles so the UI stops implying "Rate
Limited" means Headroom only. `requests_total` is now documented as a
completed-request denominator with `inbound_requests_total` named as the
all-traffic counter, and the failure-rate PromQL carries a "why" on its
denominator so nobody "simplifies" it. Checked and found clean:
`examples/grafana/headroom-dashboard.json`, `docs/observability.md`,
`docs/content/docs/proxy.mdx`, `wiki/proxy.md`, `README.md`.

## Second commit: a bug found while reviewing the first

Adding the label turned `headroom_requests_failed_total` from a counter
that **always** exported `0` into one that exports **no sample at all**
on a healthy proxy — confirmed by rendering `/metrics` on a fresh
instance:

```
headroom_requests_failed_total:       0 sample(s)
headroom_requests_rate_limited_total: 2 sample(s)
```

That breaks the failure-rate query documented in this very PR: an empty
numerator empties the whole PromQL expression, so the panel reads "No
data" instead of 0% while everything is fine, and `absent()` alerts
would fire on healthy proxies. The rate-limit series avoided this by
seeding its closed label set; providers are open-ended so the same trick
does not apply.

Fix: seed the `unknown` bucket at zero. It is a real bucket —
`record_failed` uses it for unattributed failures — so this invents no
provider. Guarded by a new test.

## Migration

Both counters now export **only** labelled series; an unlabelled sample
alongside would double-count under `sum()`. Unaggregated queries return
multiple series — `sum without (source)` / `sum without (provider)`
reproduces the previous value exactly. Noted in the docs and an mdx
Callout.

## Verification

- **16 tests fail on pre-change source** (verified by reverting only
`headroom/`), pass after.
- Targeted metrics suites → **58 passed**. Broad sweep `-k "metric or
stats or outcome or rate_limit or savings_tracker or persistent"` → 634
passed / 44 skipped. Handler, dashboard and savings-history suites → 90
+ 79 passed.
- Ruff 0.16.7 (the CI pin, via `scripts/verify-ruff-version.py
--print-version`): clean.

`CHANGELOG.md` intentionally untouched — `changelog-guard.yml` fails any
PR that edits it.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 07:26:40 -07:00

78 lines
3.4 KiB
Python

"""Tests forwarding existing proxy metric events to Lifetime storage."""
from __future__ import annotations
import asyncio
from headroom.proxy.prometheus_metrics import PrometheusMetrics
from headroom.proxy.savings_tracker import SavingsTracker
def test_runtime_metric_events_feed_lifetime_without_resetting_runtime_counters(tmp_path) -> None:
tracker = SavingsTracker(path=str(tmp_path / "proxy_savings.json"), save_flush_every=25)
metrics = PrometheusMetrics(savings_tracker=tracker)
metrics.record_stack("codex")
asyncio.run(
metrics.record_request(
provider="anthropic",
model="claude-test",
input_tokens=10,
output_tokens=3,
tokens_saved=2,
latency_ms=1,
cached=True,
attempted_input_tokens=12,
cache_read_tokens=5,
cache_write_1h_tokens=2,
waste_signals={"repetition": 4},
)
)
asyncio.run(metrics.record_failed(provider="anthropic", model="claude-test"))
asyncio.run(metrics.record_rate_limited(provider="anthropic", model="claude-test"))
asyncio.run(metrics.record_cache_bust(tokens_lost=7))
asyncio.run(metrics.record_cache_miss_attribution("anthropic", "prefix_change"))
lifetime = tracker.lifetime_response()
assert lifetime["requests"]["total"] == 1
assert lifetime["requests"]["cached"] == 1
assert lifetime["requests"]["failed"] == 1
assert lifetime["requests"]["rate_limited"] == 1
# The Prometheus labels must not stop at Prometheus: lifetime carries the
# same two splits (issue #3696). No explicit source here, so it is ours.
assert lifetime["requests"]["failed_by_provider"] == {"anthropic": 1}
assert lifetime["requests"]["rate_limited_by_source"] == {"headroom": 1}
assert lifetime["requests"]["by_provider"] == {"anthropic": 1}
assert lifetime["requests"]["by_stack"] == {"codex": 1}
assert lifetime["tokens"]["output"] == 3
assert lifetime["tokens"]["attempted_input"] == 12
assert lifetime["prefix_cache"]["bust_tokens"] == 7
assert lifetime["prefix_cache"]["misses_by_reason"] == {"prefix_change": 1}
assert lifetime["waste_signals"] == {"repetition": 4}
assert metrics.requests_total == 1
def test_upstream_rate_limit_reaches_lifetime_labelled_upstream(tmp_path) -> None:
"""An upstream 429 must not be filed under Headroom's own limiter in lifetime.
The outcome funnel passes ``source="upstream"``; the whole chain
(PrometheusMetrics -> SavingsTracker -> PersistentMetricsState) has to carry
it, or the durable view re-merges what Prometheus splits (issue #3696).
"""
tracker = SavingsTracker(path=str(tmp_path / "proxy_savings.json"), save_flush_every=25)
metrics = PrometheusMetrics(savings_tracker=tracker)
asyncio.run(metrics.record_rate_limited(provider="anthropic", source="upstream"))
asyncio.run(metrics.record_rate_limited(provider="anthropic", source="headroom"))
asyncio.run(metrics.record_failed(provider="openai"))
lifetime = tracker.lifetime_response()
assert lifetime["requests"]["rate_limited"] == 2
assert lifetime["requests"]["rate_limited_by_source"] == {"upstream": 1, "headroom": 1}
assert lifetime["requests"]["failed_by_provider"] == {"openai": 1}
# Neither counter may touch the completed-request denominator.
assert lifetime["requests"]["total"] == 0
assert metrics.requests_total == 0