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>
This commit is contained in:
Tejas Chopra
2026-11-07 20:34:12 -06:00
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent eb9932a671
commit 2038fb2a36
3 changed files with 116 additions and 10 deletions
+25 -1
View File
@@ -22,7 +22,7 @@ if TYPE_CHECKING:
from headroom import savings_ledger
from headroom.observability import get_otel_metrics
from headroom.proxy.savings_attribution import event_count
from headroom.proxy.savings_attribution import UNFOLDED_SOURCES, event_count
from headroom.proxy.savings_tracker import SavingsTracker, estimate_request_savings_usd
logger = logging.getLogger("headroom.proxy")
@@ -40,6 +40,15 @@ _OTHER_MODEL = "other"
MAX_DISTINCT_PATHS = 256
_OTHER_PATH = "other"
# Same idea for savings attribution rows (see record_request). Source names come
# from extensions and turn hooks, so one that mints a name per request would grow
# savings_by_source, and its three exported series, without bound. Past this many
# rows, new sources are summed into ``_OTHER_SOURCE``: only the name is lost,
# never a token or a dollar. As in the per-request ledger, ``UNFOLDED_SOURCES``
# never fold: the documented headline query selects ``source="tool_search"``.
MAX_DISTINCT_SAVINGS_ROWS = 256
_OTHER_SOURCE = "other"
# Closed label set for headroom_requests_rate_limited_total{source}. Two 429s
# mean opposite things to an operator: "headroom" is OUR limiter refusing the
# request (raise the cap), "upstream" is the provider refusing it (back off or
@@ -209,6 +218,7 @@ class PrometheusMetrics:
self.extension_savings: dict[str, int] = defaultdict(int)
# Named savings attribution; realized and projected rows stay separate.
self.savings_by_source: dict[str, dict[str, str | int | float | bool]] = {}
self._savings_source_cardinality_warned = False
# Fail-open compression failures, keyed by reason ("timeout",
# "error"). The proxy fails open on any optimization error so the
@@ -449,6 +459,7 @@ class PrometheusMetrics:
self.tokens_saved_by_strategy.clear()
self.extension_savings.clear()
self.savings_by_source.clear()
self._savings_source_cardinality_warned = False
with self._obs_counter_lock:
self.compression_failed_by_reason.clear()
self.upstream_connection_errors_by_provider.clear()
@@ -984,6 +995,19 @@ class PrometheusMetrics:
source = str(item.get("source") or "other")[:64]
realized = bool(item.get("realized", True))
key = f"{source}:{int(realized)}"
if (
key not in self.savings_by_source
and source not in UNFOLDED_SOURCES
and len(self.savings_by_source) >= MAX_DISTINCT_SAVINGS_ROWS
):
source, key = _OTHER_SOURCE, f"{_OTHER_SOURCE}:{int(realized)}"
if not self._savings_source_cardinality_warned:
self._savings_source_cardinality_warned = True
logger.warning(
"metrics.record: savings source cardinality cap (%d) reached; "
'summing further sources into "other"',
MAX_DISTINCT_SAVINGS_ROWS,
)
row = self.savings_by_source.setdefault(
key,
{
+5 -8
View File
@@ -58,8 +58,9 @@ MAX_STAGE_MS = 3_600_000.0
MAX_NAMED_ROWS = 256
OVERFLOW_SOURCE = "other"
# Core-booked sources never fold: ``tool_schema_savings_policy`` finds the
# deferral's row by name to lower it when hooks un-defer tools.
_UNFOLDED_SOURCES = frozenset({"tool_search"})
# deferral's row by name to lower it when hooks un-defer tools, and the
# metrics headline query selects ``source="tool_search"``.
UNFOLDED_SOURCES = frozenset({"tool_search"})
# A row's sums saturate here instead of overflowing to ``inf`` (see
# MAX_STAGE_MS for what a non-finite value does downstream). Both are far
@@ -232,16 +233,12 @@ def accumulate(rows: list[dict[str, Any]], items: Iterable[dict[str, Any]]) -> N
``tokens``, ``usd`` and ``events``; ``details`` stay only while every
summed row agrees. Once ``rows`` holds ``MAX_NAMED_ROWS`` rows, a new
source folds into ``OVERFLOW_SOURCE`` (which also takes unnamed savings),
so the list grows by at most the overflow and ``_UNFOLDED_SOURCES`` keys.
so the list grows by at most the overflow and ``UNFOLDED_SOURCES`` keys.
"""
for item in items:
key = _key(item)
target = _row_for(rows, key)
if (
target is None
and key[0] not in _UNFOLDED_SOURCES
and _row_count(rows) >= MAX_NAMED_ROWS
):
if target is None and key[0] not in UNFOLDED_SOURCES and _row_count(rows) >= MAX_NAMED_ROWS:
if key[0] != OVERFLOW_SOURCE:
# Details describe one source; the overflow row mixes several.
item = {k: v for k, v in item.items() if k != "details"}
+86 -1
View File
@@ -18,7 +18,11 @@ from headroom.observability import (
set_otel_metrics,
unregister_otel_metric_attribute_provider,
)
from headroom.proxy.prometheus_metrics import MAX_DISTINCT_PATHS, PrometheusMetrics
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
@@ -624,6 +628,87 @@ async def test_prometheus_metrics_reset_rearms_path_cardinality_warning() -> Non
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."""