Files
headroom/tests/test_extension_attribution.py
1d112cd36c fix(proxy): show turn-hook savings in /stats extension_savings, incl. Codex WS (#4233)
## Description

### The test we ran

A Daytona sandbox running Headroom Enterprise 0.4.3 (core 0.39.1), with
Codex CLI 0.162.1 and Claude Code connected to real GitHub, Context7 and
Fetch MCP servers, working through the workshop tasks.

### What we found

- The tool-search plugin's turn hook rewrote the Codex `/v1/responses`
input and saved about **8K tokens per request**. `run_request_hooks`
booked that saving through `ctx.record_savings(hook.savings_source,
tokens=...)`.
- After many such requests, `GET /stats` still showed
**`extension_savings: {}`**.

There were two causes:

1. **`extension_savings` has no writer in core.** The only thing that
fills it is `PrometheusMetrics.record_extension_savings`, and core never
calls it. Attribution rows from `ctx.record_savings` /
`record_scope_savings` go to `savings_by_source`, which `/stats` shows
as `savings.by_source`.
2. **The Codex WebSocket path drops attribution entirely.** Both WS
compression calls (first frame and later frames) called
`_compress_openai_responses_payload_in_executor` without `savings_tags`.
So `TurnContext.tags` was a throwaway `{}`, and the hook's row (along
with the built-in tool-search deferral row) never reached
`savings.by_source` either. Codex uses the WS transport by default. The
HTTP `/v1/responses` path already passed `savings_tags`.

## Type of Change

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

## Changes Made

- **`/stats.extension_savings`** now reports measured savings per
source: the **realized** attribution rows, plus
`record_extension_savings` totals. If a source also calls
`record_extension_savings` (`headroom-hdr` reports through both APIs on
every request), it shows the larger of its two totals rather than their
sum, so hdr is not double-counted. Nothing ties an attribution row to a
`record_extension_savings` call, so a plugin that used the two APIs on
different turns would be under-reported, never over-reported.
Unrealized/estimated rows (tool-search deferral, `realized=False`) stay
out and remain visible in `savings.by_source`.
- **Codex WS:** each frame compresses into its own `savings_tags` dict.
Its rows are merged into the session's pending list on the event loop,
and only when that frame was actually rewritten and sent. Each per-turn
`RequestOutcome` carries the pending rows and then clears them. A turn
whose `response.completed` has no input usage leaves its rows pending,
the same gate as its headline `saved_delta`
(`_deferrable_savings_delta`). Rows no turn claimed go out with the
session-end residual outcome, and only if the residual has input usage.
A fresh dict per frame matters because a timed-out compression thread
keeps running (`_run_compression_in_executor` can't cancel it), and it
must not book rows for a frame that went out uncompressed.

**Realized vs estimated:** `savings.by_source` already keeps one row per
`(source, realized)`, so realized and unrealized savings are shown
separately. `extension_savings` now carries only the realized ones.

**Review fix (@JerrettDavis, bounded WS pending list):** the
session-wide pending list grew one row per rewritten frame, while
`savings_attribution.from_tags` read only the first `MAX_SOURCES` (32)
rows. After 33 frames that each booked a 100-token `tool_search` row,
the handoff cleared all 33 rows but booked only 3,200 of the 3,300
tokens. `savings_attribution.accumulate(rows, items)` replaces the
`extend` at both WS frame paths.

**Bounded rows, nothing dropped (follow-up to @JerrettDavis's two
reviews):** the 32-row cap that silently dropped rows is gone from
`record_savings`, `from_tags` and `accumulate`. Storage is bounded by
coalescing plus one overflow row:
- every writer goes through the one `accumulate` helper: the per-request
ledger (`record_savings`, so every handler) and the WS pending list.
Rows with the same `(source, realized, estimated)` key are summed into
one row (`tokens`, `usd`, `events`). `details` are kept only while every
summed row has the same `details`.
- **cardinality bound:** a ledger keeps at most `MAX_NAMED_ROWS` (256)
named rows. A new source past that bound is summed into an `other` row
with the same `(realized, estimated)`, and its `details` are dropped.
Tokens, dollars and events are conserved: nothing is dropped, only the
source name. `tool_search` never folds, because
`tool_schema_savings_policy` finds the deferral's row by name to lower
it when hooks un-defer tools.
- **finite sums:** a row's `usd` saturates at ±`MAX_ROW_USD` (1e15) and
its `tokens` stay within 0..`MAX_ROW_TOKENS` (10^15). A row that was
clipped, or summed from one that was, carries `saturated: true`. Every
total stays finite, so the Prometheus exposition and
`json.dumps(allow_nan=False)` never see `inf`/`nan`.
- each row carries `events`: how many recordings it stands for (1 on a
fresh row, summed on merge). `PrometheusMetrics.record_request`
(`headroom_savings_attribution_events_total`), the OTel
`headroom.savings.attribution.events` counter and the perf analyzer's
"Savings by Source" add that count instead of 1 per row, so 33 coalesced
frames are 33 events, not 1 (Devin's finding). A row without `events`
(older PERF logs, rows built by hand) counts as 1.
- a row that a reader edited in place (`reconcile_deferred_tokens`, the
tool-search plugin) is summed defensively, so a junk value counts as 0
instead of raising inside the handler. The core deferral and the native
deferral hook both book `tool_search` as estimated, so they now share
one row, and the reconcile debits that row; totals are unchanged.
- `MAX_SOURCES` is no longer used. No importer was found outside this
repo's own test, but `savings_attribution` is imported by plugins, so
the name is kept behind a module `__getattr__` that raises a
`DeprecationWarning`.
- **Scope of the bound:** it is per ledger (one request, or one WS
session's pending list). The process-wide
`PrometheusMetrics.savings_by_source` table has no source cap yet; that
is a separate PR.

### Before / after

| | origin/main | this PR |
|---|---|---|
| A turn hook books 8,000 tokens on 2 requests →
`/stats.extension_savings` | `{}` | `{"tool_search": 16000}` |
| An hdr-style plugin calls both APIs (300 tokens × 2) | `{"hdr": 600}`
| `{"hdr": 600}` (not 1200) |
| A Codex WS turn with a folding hook → attribution rows on the turn
outcome | `[]` | `[("ws_fold", realized=True)]` |
| 33 WS frames, each booking `tool_search` 100 tokens, then one billed
turn → booked `tool_search` tokens (helper-level, the reviewer's
scenario) | 3,200 of 3,300, 33 rows stored | 3,300, 1 row stored |
| Real WS handler, 33 frames each with a folding hook (`ws_fold` row)
plus a 100-token hook row → non-`ws_fold` tokens booked | 1,600 of 3,300
(66 rows stored) | 3,300 |
| Same, repeated source → rows stored / hook events in
`headroom_savings_attribution_events_total` | aecae31b: 2 rows / 1 event
| 2 rows / 33 events |
| Same, 33 distinct sources → rows stored / hook events / `other` row |
aecae31b: 29 rows / 28 events / yes (6 sources folded) | 34 rows (33 +
`ws_fold`) / 33 events / no |
| Same, 300 distinct sources → rows stored / tokens and USD booked |
rows past 32 dropped | 257 rows (256 named + `other`), every token and
dollar booked |
| One ledger, 2,000 distinct sources plus repeats | rows past 32 dropped
| 256 named rows + 2 `other` rows (realized, estimated); tokens, USD and
events conserved |
| Same source booked 1e308 USD twice, then 1.0 | `inf` in `/stats` and
Prometheus | `usd` = 1e15, `saturated: true`, exposition finite |
| One HTTP request, 40 distinct sources + 1 repeat, 100 tokens each
(`record_savings`, every handler) → booked tokens / events | 3,200 of
4,100 / 32 (8 rows dropped) | 4,100 / 41, 40 rows stored |

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

-
`tests/test_compression_observability.py::test_turn_hook_savings_surface_in_stats_extension_savings`:
fails on origin/main, passes here.
-
`tests/test_openai_codex_ws_lifecycle.py::test_ws_turn_hook_savings_reach_the_turn_outcome[billed|usage_less]`:
drives the real WS handler with a registered hook. `billed` fails on
origin/main (no rows). `usage_less` fails if the input-usage gate is
removed.
- Related suites pass: the WS lifecycle, per-frame memory, savings
deferral and compression scheduler tests, extension attribution,
responses context compaction, tool-search repair after hooks, and the
handler outcome tag invariant (136 passed).
- ruff check, ruff format --check and mypy pass.
-
`tests/test_openai_codex_ws_lifecycle.py::test_ws_pending_savings_beyond_32_rows_are_all_booked`
(review fix, renamed from `..._beyond_max_sources_...`), parametrized
over a repeated source × 33 frames, 33 distinct sources, and 300
distinct sources (folds into `other`, 257 rows, USD conserved): drives
the real WS handler through the rewritten frames. The upstream holds its
events until all 33 frames arrive, so every row is pending when the one
billed outcome claims it. The rows are booked through the real
`from_tags` → `PrometheusMetrics.record_request`. The test asserts that
every token is booked (3,300), that the hook rows count 33 events, that
there is no `other` row, and that the stored row count equals the
distinct keys (2 for a repeated source, 34 for 33 distinct sources plus
`ws_fold`).
-
`tests/test_extension_attribution.py::test_a_request_with_40_sources_books_every_token`:
one request's ledger with 40 distinct sources and one repeat books 4,100
tokens and 41 events through `PrometheusMetrics.record_request`.
-
`tests/test_extension_attribution.py::test_rows_coalesce_per_source_realized_and_estimated`:
same source with different `realized`/`estimated` stays in separate
rows; same key sums tokens and events.
-
`tests/test_observability_metrics.py::test_coalesced_savings_rows_count_every_event`:
the OTel events counter adds a row's `events` (33), and a row without
the field counts as 1.
-
`tests/test_cli_perf_format.py::test_coalesced_savings_rows_count_every_event_in_text_and_summary`:
both perf folds (`headroom perf` text report and the JSON `by_source`
summary) add a row's `events`.
-
`tests/test_extension_attribution.py::test_merging_into_a_junk_row_does_not_raise_inside_the_handler`:
a ledger row edited in place with junk (`tokens=None`) is summed as 0
instead of raising out of `record_savings`.
-
`tests/test_extension_attribution.py::test_distinct_sources_past_the_bound_fold_into_other_and_conserve_totals`:
2,000 sources plus estimated repeats give 258 rows, with tokens, USD and
events conserved.
-
`tests/test_extension_attribution.py::test_same_source_usd_saturates_instead_of_overflowing`,
`test_an_infinite_total_already_in_the_ledger_stays_saturated[±1.0]`,
`test_tokens_stay_within_zero_and_the_bound`: sums stay finite and are
flagged `saturated`.
-
`tests/test_extension_attribution.py::test_tool_search_keeps_its_own_row_past_the_bound`:
the deferral row is never folded, so the reconcile still finds it.
-
`tests/test_extension_attribution.py::test_max_sources_is_deprecated_not_removed`:
the old name still imports, with a `DeprecationWarning`.
-
`tests/test_turn_hooks.py::test_request_runner_attributes_savings_with_handler_counters`:
expected row now includes `events: 1`.

### Test Output

```text
# review fix, savings_attribution.py + openai.py reverted to the previous commit, new test:
FAILED tests/test_openai_codex_ws_lifecycle.py::test_ws_pending_savings_beyond_max_sources_are_all_booked[repeated_source]   (assert 1600 == (100 * 33))
FAILED tests/test_openai_codex_ws_lifecycle.py::test_ws_pending_savings_beyond_max_sources_are_all_booked[distinct_sources]  (assert 1600 == (100 * 33))
# helper-level, the reviewer's scenario (33 frames x tool_search 100):
append:     33 rows stored, 3200 booked
accumulate:  1 row stored,  3300 booked
40 distinct sources x 100: 29 rows stored, 4000 booked ("other" = 1200)
# no-cap follow-up, the 5 source files reverted to aecae31b, new/updated tests:
FAILED tests/test_extension_attribution.py::test_a_request_with_40_sources_books_every_token
FAILED tests/test_extension_attribution.py::test_rows_coalesce_per_source_realized_and_estimated
FAILED tests/test_observability_metrics.py::test_coalesced_savings_rows_count_every_event
FAILED tests/test_openai_codex_ws_lifecycle.py::test_ws_pending_savings_beyond_32_rows_are_all_booked[repeated_source]
FAILED tests/test_openai_codex_ws_lifecycle.py::test_ws_pending_savings_beyond_32_rows_are_all_booked[distinct_sources]
# with the no-cap follow-up: every test file that touches the savings ledger (21 files)
# plus gateway, perf format/per-port logs and /stats suites: 831 passed, 5 skipped (90d5e132)
# with the fix (aecae31b):
WS lifecycle, per-frame memory, savings deferral, compression scheduler, WS timings, pyo3 WS compression,
outcome tag invariant, extension attribution, compression observability, tool-search aggregation,
responses context compaction, proxy openai: 189 passed
ruff 0.17.0 check + format --check: clean on changed files
mypy headroom --ignore-missing-imports: no new errors (1 pre-existing local error in integrations/langchain/chat_model.py:380, untouched)
```

## Real Behavior Proof

- Environment: macOS 26.7, Python 3.12.13, this branch. The WS handler
is driven through the repo's fake-upstream harness
(`tests/test_openai_codex_ws_lifecycle.py`), which runs the real
`handle_openai_responses_ws`, `run_request_hooks` and outcome funnel
with only the upstream socket scripted; `/stats` runs on the real app
via `TestClient`; OTel uses the real `HeadroomOtelMetrics` with an
in-memory reader.
- Exact command / steps: `pytest tests/test_openai_codex_ws_lifecycle.py
tests/test_extension_attribution.py tests/test_observability_metrics.py
tests/test_compression_observability.py tests/test_turn_hooks.py` (plus
the other ledger suites listed under Testing), each run once on this
branch and once with the source files reverted.
- Observed result: with a registered folding hook, the hook really
rewrites the forwarded `input` (the upstream received only `"new"`) and
the turn outcome carries `[("ws_fold", realized=True, tokens>0)]`.
`/stats.extension_savings` reports `{"tool_search": 16000, "hdr": 600}`
for the two-request scenario above. 33 rewritten WS frames book 3,300
hook tokens and 33 events with no `other` row; 300 distinct sources fold
into 256 named rows plus `other` with every token and dollar booked; one
request with 40 distinct sources plus a repeat books 4,100 tokens and 41
events in 40 rows.
- Not tested: a real Codex CLI session against OpenAI on this branch, a
real Codex session with more than 32 rewritten frames before a billed
turn, and the real `headroom-tool-search` plugin were not re-run after
the patch. The sandbox numbers above (about 8K tokens/request,
`extension_savings: {}`) are from 0.39.1 before the fix.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: `/stats.extension_savings` now
includes realized attribution rows, and Codex WS turns now carry
attribution rows. Request bodies and headline totals are unchanged.
- Kill switch / disable path: none needed; the change only affects
reporting
- 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 on each review fix. Its earlier SHOULD on
the collapsed `events` count is now fixed (rows carry `events`).
- [x] This PR is ready for human review

## Additional Notes

- `record_extension_savings` stays public and unchanged.
- The Prometheus exposition format is unchanged;
`headroom_savings_attribution_events_total` now counts recordings, which
is what it counted before rows were coalesced.
- Ledger rows now carry an `events` field. Readers that ignore unknown
keys are unaffected.
- A reader that finds "rows a hook added" by slicing the ledger at its
old length (`ledger[before:]`) can miss a hook's tokens when the hook
books a key that already had a row. Core has no such reader;
`headroom-kiro`'s handler does and should switch to a before/after sum.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-17 11:29:04 -07:00

553 lines
19 KiB
Python

"""Attribution and timing contributed by proxy extensions.
An extension that changes the bill has to be able to say so, or the operator
sees a different total with nothing to explain it. The savings half of this
already existed but only reached two of the three handler families; the timing
half did not exist at all, so an extension's own latency was invisible —
``overhead_ms`` is measured inside the handler that the extension wraps.
"""
from __future__ import annotations
import math
import pytest
from headroom.proxy.savings_attribution import (
MAX_STAGE_MS,
MAX_STAGES,
SAVINGS_ATTRIBUTION_TAG,
STAGE_PREFIX,
STAGE_TIMING_TAG,
bind_scope,
from_tags,
public_tags,
record_scope_savings,
record_scope_timing,
timings_from_tags,
)
def _scope() -> dict:
return {"type": "http", "method": "POST"}
# --- savings, from middleware ------------------------------------------------
def test_middleware_savings_reach_the_handlers_tags() -> None:
"""The contract: middleware records into the scope before the handler runs,
the handler binds, and the outcome funnel reads one ledger."""
scope = _scope()
record_scope_savings(scope, "routemegood", usd=0.42)
tags: dict = {}
bind_scope(tags, scope)
(row,) = from_tags(tags)
assert row["source"] == "routemegood"
assert row["usd"] == 0.42
def test_savings_can_be_money_without_being_tokens() -> None:
"""The gap this closes. Every other savings channel computes
``saved = before - after`` and three of them refuse a non-positive value,
so an extension that routes a request to a cheaper model — same tokens,
smaller bill — could only report by inventing a token count nobody saved."""
scope = _scope()
record_scope_savings(scope, "model_router", tokens=0, usd=1.75)
tags: dict = {}
bind_scope(tags, scope)
(row,) = from_tags(tags)
assert row["tokens"] == 0
assert row["usd"] == 1.75
def test_a_projection_is_not_a_measurement() -> None:
scope = _scope()
record_scope_savings(scope, "guess", usd=1.0, realized=False)
record_scope_savings(scope, "guess", usd=1.0, realized=True)
tags: dict = {}
bind_scope(tags, scope)
assert sorted(row["realized"] for row in from_tags(tags)) == [False, True]
# --- timing ------------------------------------------------------------------
def test_middleware_timing_reaches_the_handlers_tags() -> None:
scope = _scope()
record_scope_timing(scope, "routemegood", 12.5)
tags: dict = {}
bind_scope(tags, scope)
assert timings_from_tags(tags) == {f"{STAGE_PREFIX}routemegood": 12.5}
def test_timing_is_additive_within_one_request() -> None:
"""A middleware works in two passes — before ``call_next`` and after — and
should be able to report each without tracking the total itself."""
scope = _scope()
record_scope_timing(scope, "ext", 4.0)
record_scope_timing(scope, "ext", 2.5)
tags: dict = {}
bind_scope(tags, scope)
assert timings_from_tags(tags) == {f"{STAGE_PREFIX}ext": 6.5}
def test_extension_stages_are_namespaced() -> None:
"""``deep_copy`` reported by a plugin and ``deep_copy`` measured by the
pipeline must not accumulate into the same series."""
scope = _scope()
record_scope_timing(scope, "deep_copy", 1.0)
tags: dict = {}
bind_scope(tags, scope)
assert list(timings_from_tags(tags)) == [f"{STAGE_PREFIX}deep_copy"]
@pytest.mark.parametrize(
"bad",
[
0,
-1.0,
None,
"slow",
float("nan"),
float("inf"),
float("-inf"),
1e400,
MAX_STAGE_MS + 1,
],
)
def test_a_non_measurement_is_not_recorded(bad) -> None:
"""Zero and negative are clock artifacts, not observations; averaging them
in would drag the mean down exactly where the stage is cheapest to skip.
Non-finite is worse than skew. Starlette encodes ``/stats`` with
``allow_nan=False``, so one ``inf`` raises out of the JSON encoder — and it
lands in process-wide metrics totals, so the endpoint stays broken until
restart while the request that caused it returns 200.
"""
scope = _scope()
record_scope_timing(scope, "ext", bad)
tags: dict = {}
bind_scope(tags, scope)
assert timings_from_tags(tags) == {}
def test_a_poisoned_ledger_is_rejected_on_read_too() -> None:
"""The ledger is a plain dict reachable through ``tags``, so a handler can
be handed one this module never wrote. The guarantee holds at the read."""
assert timings_from_tags({STAGE_TIMING_TAG: {"ext:a": float("inf"), "ext:b": 2.0}}) == {
"ext:b": 2.0
}
def test_accumulation_cannot_overflow_to_infinity() -> None:
"""Two finite values can sum to ``inf``. Bounding each SAMPLE makes that
unreachable rather than merely unlikely."""
scope = _scope()
for _ in range(4):
record_scope_timing(scope, "ext", MAX_STAGE_MS)
tags: dict = {}
bind_scope(tags, scope)
(total,) = timings_from_tags(tags).values()
assert math.isfinite(total)
def test_an_accumulated_total_may_exceed_the_per_sample_bound() -> None:
"""The bound is on one sample, not on the sum. Testing it against the
accumulated total would silently discard a stage that legitimately ran
longer across many samples — throwing away real data to guard a value the
write path cannot produce."""
scope = _scope()
for _ in range(3):
record_scope_timing(scope, "ext", MAX_STAGE_MS)
tags: dict = {}
bind_scope(tags, scope)
assert timings_from_tags(tags) == {f"{STAGE_PREFIX}ext": MAX_STAGE_MS * 3}
@pytest.mark.parametrize("bad", [float("inf"), float("-inf"), float("nan")])
def test_a_non_finite_amount_is_not_a_saving(bad) -> None:
"""Pre-existing, and the same crash: ``usd=inf`` reaches ``/stats`` and
raises out of the JSON encoder."""
scope = _scope()
record_scope_savings(scope, "buggy", usd=bad)
tags: dict = {}
bind_scope(tags, scope)
assert from_tags(tags) == []
@pytest.mark.parametrize("bad", [float("inf"), float("nan")])
def test_a_non_finite_token_count_does_not_raise_inside_the_handler(bad) -> None:
"""``int(inf)`` is an OverflowError, raised on a request that would
otherwise have succeeded. A plugin's arithmetic bug must not become the
proxy's 500."""
scope = _scope()
record_scope_savings(scope, "buggy", tokens=bad)
tags: dict = {}
bind_scope(tags, scope)
assert from_tags(tags) == []
def test_a_real_saving_still_records_after_the_guards() -> None:
"""The direction that must not be lost while hardening the other one."""
scope = _scope()
record_scope_savings(scope, "routemegood", tokens=10, usd=0.5)
record_scope_timing(scope, "routemegood", 3.0)
tags: dict = {}
bind_scope(tags, scope)
assert from_tags(tags)[0]["usd"] == 0.5
assert timings_from_tags(tags) == {f"{STAGE_PREFIX}routemegood": 3.0}
def test_stage_cardinality_is_capped() -> None:
"""Stage names are extension-supplied, so they are bounded like every other
client-influenced label in this proxy."""
scope = _scope()
for i in range(MAX_STAGES * 4):
record_scope_timing(scope, f"stage-{i}", 1.0)
tags: dict = {}
bind_scope(tags, scope)
assert len(timings_from_tags(tags)) == MAX_STAGES
def test_an_existing_stage_still_accumulates_at_the_cap() -> None:
"""The cap bounds distinct names, not measurements. A stage already being
tracked must keep accumulating or its total silently stops growing."""
scope = _scope()
for i in range(MAX_STAGES):
record_scope_timing(scope, f"stage-{i}", 1.0)
record_scope_timing(scope, "stage-0", 5.0)
tags: dict = {}
bind_scope(tags, scope)
assert timings_from_tags(tags)[f"{STAGE_PREFIX}stage-0"] == 6.0
def test_recording_before_any_bind_still_works() -> None:
"""Ordering is not guaranteed: middleware runs first, and on a path where
the handler never binds, nothing should raise."""
scope = _scope()
record_scope_timing(scope, "ext", 1.0)
record_scope_savings(scope, "ext", usd=1.0)
assert scope["state"]
def test_recording_after_bind_is_seen_by_the_already_bound_tags() -> None:
"""A middleware measures its own post-response work AFTER the handler has
bound. Sharing one object rather than copying is what makes that land."""
tags: dict = {}
scope = _scope()
bind_scope(tags, scope)
record_scope_timing(scope, "ext", 3.0)
record_scope_savings(scope, "ext", usd=0.5)
assert timings_from_tags(tags) == {f"{STAGE_PREFIX}ext": 3.0}
assert from_tags(tags)[0]["usd"] == 0.5
def test_bind_is_idempotent() -> None:
tags: dict = {}
scope = _scope()
bind_scope(tags, scope)
record_scope_timing(scope, "ext", 1.0)
bind_scope(tags, scope)
record_scope_timing(scope, "ext", 1.0)
assert timings_from_tags(tags) == {f"{STAGE_PREFIX}ext": 2.0}
def test_timings_from_tags_tolerates_junk() -> None:
for junk in (
None,
{},
{STAGE_TIMING_TAG: "nope"},
{STAGE_TIMING_TAG: []},
{STAGE_TIMING_TAG: {"a": "b"}},
):
assert timings_from_tags(junk) == {}
# --- the ledgers are structures, not labels ---------------------------------
def test_neither_ledger_leaks_into_request_log_tags() -> None:
"""They ride on ``tags`` because that is the one dict reaching the outcome
funnel from every handler. A list and a dict must not land in a
string-keyed label store."""
tags: dict = {"client": "claude-code"}
scope = _scope()
bind_scope(tags, scope)
record_scope_savings(scope, "ext", usd=1.0)
record_scope_timing(scope, "ext", 1.0)
assert public_tags(tags) == {"client": "claude-code"}
assert SAVINGS_ATTRIBUTION_TAG not in public_tags(tags)
assert STAGE_TIMING_TAG not in public_tags(tags)
# --- through the outcome funnel ---------------------------------------------
pytest.importorskip("fastapi")
class _Harness:
"""Just enough of HeadroomProxy to drive the real funnel method.
Mirrors ``tests/test_request_outcome.py::_FunnelHarness`` — the real
implementation is bound to the harness, so nothing under test is mocked.
"""
def __init__(self) -> None:
from unittest.mock import AsyncMock, MagicMock
from headroom.proxy.server import HeadroomProxy
self.metrics = MagicMock()
self.metrics.record_request = AsyncMock()
self.cost_tracker = MagicMock()
self.logger = None
self._record_request_outcome = HeadroomProxy._record_request_outcome.__get__(
self, type(self)
)
def _outcome(**overrides):
from headroom.proxy.outcome import RequestOutcome
defaults = {
"request_id": "req-1",
"provider": "anthropic",
"model": "claude-sonnet-4",
"original_tokens": 1000,
"optimized_tokens": 1000,
"output_tokens": 50,
"tokens_saved": 0,
"attempted_input_tokens": 1000,
}
defaults.update(overrides)
return RequestOutcome(**defaults)
@pytest.mark.asyncio
async def test_extension_timing_reaches_pipeline_timing() -> None:
"""The whole point of the timing half: ``pipeline_timing`` is what
``/stats``, the dashboard's Performance panel and
``headroom_transform_timing_ms_*`` are all built on."""
scope = _scope()
record_scope_timing(scope, "routemegood", 8.0)
tags: dict = {}
bind_scope(tags, scope)
h = _Harness()
await h._record_request_outcome(_outcome(tags=tags, pipeline_timing={"deep_copy": 1.0}))
timing = h.metrics.record_request.await_args.kwargs["pipeline_timing"]
assert timing == {"deep_copy": 1.0, f"{STAGE_PREFIX}routemegood": 8.0}
@pytest.mark.asyncio
async def test_a_handler_timing_wins_a_name_collision() -> None:
"""Namespacing makes this unreachable today; it is asserted so that if the
prefix ever goes, a plugin still cannot overwrite a measurement the
pipeline made of itself."""
tags = {STAGE_TIMING_TAG: {"deep_copy": 99.0}}
h = _Harness()
await h._record_request_outcome(_outcome(tags=tags, pipeline_timing={"deep_copy": 1.0}))
timing = h.metrics.record_request.await_args.kwargs["pipeline_timing"]
assert timing["deep_copy"] == 1.0
@pytest.mark.asyncio
async def test_no_extension_timing_leaves_pipeline_timing_untouched() -> None:
"""Including identity: a request with no extension must pass the handler's
own dict through, not a rebuilt copy of it."""
original = {"deep_copy": 1.0}
h = _Harness()
await h._record_request_outcome(_outcome(pipeline_timing=original))
assert h.metrics.record_request.await_args.kwargs["pipeline_timing"] is original
@pytest.mark.asyncio
async def test_extension_savings_reach_the_metrics_call() -> None:
scope = _scope()
record_scope_savings(scope, "routemegood", usd=0.42, tokens=0)
tags: dict = {}
bind_scope(tags, scope)
h = _Harness()
await h._record_request_outcome(_outcome(tags=tags))
attribution = h.metrics.record_request.await_args.kwargs["savings_attribution"]
assert [(row["source"], row["usd"]) for row in attribution] == [("routemegood", 0.42)]
# --- no row cap: every recording is booked -------------------------------------
@pytest.mark.asyncio
async def test_a_request_with_40_sources_books_every_token() -> None:
"""The ledger used to stop at 32 rows and drop the 33rd recording on."""
from headroom.proxy.prometheus_metrics import PrometheusMetrics
from headroom.proxy.savings_attribution import record_savings
tags: dict = {}
for i in range(40):
record_savings(tags, f"plugin{i}", tokens=100, usd=0.01)
record_savings(tags, "plugin0", tokens=100, usd=0.01)
rows = from_tags(tags)
metrics = PrometheusMetrics()
await metrics.record_request(
provider="openai",
model="gpt-5.4",
input_tokens=10,
output_tokens=1,
tokens_saved=0,
latency_ms=1.0,
savings_attribution=rows,
)
assert len(rows) == 40
booked = metrics.savings_by_source.values()
assert sum(int(row["tokens"]) for row in booked) == 4_100
assert sum(int(row["events"]) for row in booked) == 41
assert metrics.savings_by_source["plugin0:1"]["events"] == 2
def test_rows_coalesce_per_source_realized_and_estimated() -> None:
from headroom.proxy.savings_attribution import record_savings
tags: dict = {}
for _ in range(3):
record_savings(tags, "router", tokens=1, realized=True)
record_savings(tags, "router", tokens=1, realized=False)
record_savings(tags, "router", tokens=1, estimated=True)
rows = from_tags(tags)
assert [(r["realized"], r["estimated"], r["tokens"], r["events"]) for r in rows] == [
(True, False, 3, 3),
(False, False, 3, 3),
(True, True, 3, 3),
]
def test_merging_into_a_junk_row_does_not_raise_inside_the_handler() -> None:
from headroom.proxy.savings_attribution import record_savings
tags: dict = {SAVINGS_ATTRIBUTION_TAG: [{"source": "x", "tokens": None, "usd": "junk"}]}
record_savings(tags, "x", tokens=5, usd=0.5)
assert [(r["tokens"], r["usd"], r["events"]) for r in from_tags(tags)] == [(5, 0.5, 2)]
def test_distinct_sources_past_the_bound_fold_into_other_and_conserve_totals() -> None:
"""Source names are plugin-supplied; their count must not grow the ledger."""
from headroom.proxy.savings_attribution import MAX_NAMED_ROWS, record_savings
tags: dict = {}
for i in range(2_000):
record_savings(tags, f"extension_{i}", tokens=100, usd=0.01)
record_savings(tags, f"extension_{i}", tokens=1, estimated=True)
record_savings(tags, "extension_0", tokens=100, usd=0.01) # a named row still merges
rows = from_tags(tags)
assert len(rows) == MAX_NAMED_ROWS + 2 # plus one ``other`` row per estimated flag
assert sum(r["tokens"] for r in rows) == 2_000 * 101 + 100
assert sum(r["events"] for r in rows) == 4_001
assert math.isclose(sum(r["usd"] for r in rows), 2_001 * 0.01)
named = {(r["source"], r["estimated"]): r for r in rows}
assert named[("extension_0", False)]["events"] == 2
assert {(r["source"], r["estimated"]) for r in rows if r["source"] == "other"} == {
("other", False),
("other", True),
}
@pytest.mark.asyncio
async def test_same_source_usd_saturates_instead_of_overflowing() -> None:
"""Two finite amounts must not sum to ``inf`` on the way to the metrics."""
import json
from headroom.proxy.prometheus_metrics import PrometheusMetrics
from headroom.proxy.savings_attribution import MAX_ROW_USD, record_savings
tags: dict = {}
record_savings(tags, "same", tokens=1, usd=1e308)
record_savings(tags, "same", tokens=1, usd=1e308)
record_savings(tags, "same", tokens=1, usd=1.0) # must not reset the total
rows = from_tags(tags)
assert [(r["tokens"], r["events"], r["usd"], r["saturated"]) for r in rows] == [
(3, 3, MAX_ROW_USD, True)
]
metrics = PrometheusMetrics()
await metrics.record_request(
provider="openai",
model="gpt-5.4",
input_tokens=10,
output_tokens=1,
tokens_saved=0,
latency_ms=1.0,
savings_attribution=rows,
)
booked = metrics.savings_by_source["same:1"]["usd"]
assert math.isfinite(booked)
json.dumps(metrics.savings_by_source, allow_nan=False) # what /stats does
@pytest.mark.parametrize("then_usd", [1.0, -1.0])
def test_an_infinite_total_already_in_the_ledger_stays_saturated(then_usd) -> None:
from headroom.proxy.savings_attribution import MAX_ROW_USD, record_savings
tags: dict = {SAVINGS_ATTRIBUTION_TAG: [{"source": "x", "usd": math.inf}]}
record_savings(tags, "x", usd=then_usd)
[row] = from_tags(tags)
assert row["saturated"] is True
assert row["usd"] >= MAX_ROW_USD - 1.0
def test_tokens_stay_within_zero_and_the_bound() -> None:
from headroom.proxy.savings_attribution import MAX_ROW_TOKENS, accumulate
rows: list = [{"source": "x", "tokens": -(10**400)}, {"source": "y", "tokens": 10**400}]
accumulate(rows, [{"source": "x", "tokens": 5}, {"source": "y", "tokens": 5}])
assert [(r["tokens"], r["saturated"]) for r in rows] == [(5, True), (MAX_ROW_TOKENS, True)]
def test_tool_search_keeps_its_own_row_past_the_bound() -> None:
"""Deferral reconcile finds the ``tool_search`` row by name to lower it."""
from headroom.proxy.savings_attribution import MAX_NAMED_ROWS, record_savings
tags: dict = {}
for i in range(MAX_NAMED_ROWS):
record_savings(tags, f"extension_{i}", tokens=1)
record_savings(tags, "tool_search", tokens=900, realized=False, estimated=True)
assert [r["tokens"] for r in from_tags(tags) if r["source"] == "tool_search"] == [900]
def test_max_sources_is_deprecated_not_removed() -> None:
from headroom.proxy import savings_attribution
with pytest.warns(DeprecationWarning, match="MAX_SOURCES"):
assert savings_attribution.MAX_SOURCES == 32