Files
headroom/tests/test_turn_hooks.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

251 lines
7.2 KiB
Python

"""Turn-hook registry + runners (headroom/proxy/turn_hooks.py).
The hook surface is opt-in: with nothing registered the runners must be exact
no-ops (the property the proxy relies on to stay byte-identical for everyone who
has no extension installed). These tests pin that, plus request-mutation,
response-replacement, the re-drive (``call_model``) loop, and the
never-raise guarantee.
"""
from __future__ import annotations
import pytest
from headroom.proxy.turn_hooks import (
TurnContext,
clear_turn_hooks,
register_turn_hook,
registered_turn_hooks,
run_request_hooks,
run_response_hooks,
)
@pytest.fixture(autouse=True)
def _clean_registry():
clear_turn_hooks()
yield
clear_turn_hooks()
def _ctx(**kw):
base = {"provider": "anthropic", "model": "claude-x", "messages": [], "tools": None}
base.update(kw)
return TurnContext(**base)
async def _noop_call_model(_messages): # pragma: no cover - never invoked in no-op tests
raise AssertionError("call_model must not be invoked when no hook re-drives")
# --- inert-when-empty (the load-bearing guarantee) ---------------------------
def test_request_runner_inert_when_empty():
assert registered_turn_hooks() == []
ctx = _ctx(tools=[{"name": "a"}])
before = ctx.tools
run_request_hooks(ctx) # must not raise, must not touch ctx
assert ctx.tools is before
@pytest.mark.asyncio
async def test_response_runner_returns_input_unchanged_when_empty():
resp = {"id": "orig", "content": []}
out = await run_response_hooks(_ctx(), resp, _noop_call_model)
assert out is resp # same object, untouched
# --- on_request mutation -----------------------------------------------------
def test_stream_safe_filter_runs_only_optted_in_hooks_on_stream():
"""On a streamed turn only ``stream_safe`` hooks' on_request runs (fold-only,
no re-drive); buffered runs all. A hook that may re-drive stays buffered-only."""
ran: list[str] = []
class Fold:
name = "fold"
stream_safe = True # opts in — safe on streaming
def on_request(self, ctx: TurnContext) -> None:
ran.append("fold")
class Redrive: # no stream_safe attr → buffered-only (default)
name = "redrive"
def on_request(self, ctx: TurnContext) -> None:
ran.append("redrive")
register_turn_hook(Fold())
register_turn_hook(Redrive())
ran.clear()
run_request_hooks(_ctx(), stream_safe_only=True) # streaming turn
assert ran == ["fold"]
ran.clear()
run_request_hooks(_ctx()) # buffered turn (default)
assert ran == ["fold", "redrive"]
def test_on_request_may_mutate_ctx():
class Shrink:
name = "shrink"
def on_request(self, ctx: TurnContext) -> None:
ctx.tools = [t for t in (ctx.tools or []) if t["name"] != "drop_me"]
register_turn_hook(Shrink())
ctx = _ctx(tools=[{"name": "keep"}, {"name": "drop_me"}])
run_request_hooks(ctx)
assert ctx.tools == [{"name": "keep"}]
def test_request_runner_attributes_savings_with_handler_counters():
class Shrink:
name = "internal-hook-name"
savings_source = "tool_search"
def on_request(self, ctx: TurnContext) -> None:
ctx.tools = (ctx.tools or [])[:1]
ctx.messages[0]["content"] = "short"
register_turn_hook(Shrink())
tags = {}
ctx = _ctx(
messages=[{"role": "user", "content": "a much longer value"}],
tools=[{"name": "keep"}, {"name": "drop"}],
tags=tags,
count_messages=lambda messages: len(messages[0]["content"]),
count_tools=lambda tools: len(tools or []),
)
run_request_hooks(ctx)
from headroom.proxy.savings_attribution import from_tags
assert from_tags(tags) == [
{
"source": "tool_search",
"realized": True,
"estimated": False,
"tokens": 15,
"usd": 0.0,
"details": {"message_tokens_saved": 14, "tool_tokens_saved": 1},
"events": 1,
}
]
# --- on_response replacement + re-drive loop ---------------------------------
@pytest.mark.asyncio
async def test_on_response_can_replace_via_call_model():
calls: list[list] = []
async def call_model(messages):
calls.append(messages)
return {"id": "resolved", "content": [{"type": "text", "text": "done"}]}
class ResolveOnce:
name = "resolve"
async def on_response(self, ctx, response, call_model):
if response.get("id") == "needs-work":
return await call_model(ctx.messages + [{"role": "user", "content": "go"}])
return None
register_turn_hook(ResolveOnce())
out = await run_response_hooks(
_ctx(messages=[{"role": "user", "content": "hi"}]), {"id": "needs-work"}, call_model
)
assert out["id"] == "resolved"
assert len(calls) == 1
@pytest.mark.asyncio
async def test_on_response_none_leaves_response_unchanged():
class Observer:
name = "observe"
async def on_response(self, ctx, response, call_model):
return None # observe only
register_turn_hook(Observer())
resp = {"id": "orig"}
out = await run_response_hooks(_ctx(), resp, _noop_call_model)
assert out is resp
@pytest.mark.asyncio
async def test_replacements_chain_across_hooks():
class First:
name = "first"
async def on_response(self, ctx, response, call_model):
return {"id": "after-first", "seen": response["id"]}
class Second:
name = "second"
async def on_response(self, ctx, response, call_model):
return {"id": "after-second", "seen": response["id"]}
register_turn_hook(First())
register_turn_hook(Second())
out = await run_response_hooks(_ctx(), {"id": "orig"}, _noop_call_model)
assert out == {"id": "after-second", "seen": "after-first"} # Second saw First's output
# --- a failing hook must never break the proxy -------------------------------
def test_failing_on_request_is_swallowed():
class Boom:
name = "boom"
def on_request(self, ctx: TurnContext) -> None:
raise RuntimeError("kaboom")
register_turn_hook(Boom())
run_request_hooks(_ctx()) # must not raise
@pytest.mark.asyncio
async def test_failing_on_response_is_skipped_and_original_survives():
class Boom:
name = "boom"
async def on_response(self, ctx, response, call_model):
raise RuntimeError("kaboom")
class Good:
name = "good"
async def on_response(self, ctx, response, call_model):
return {"id": "recovered"}
register_turn_hook(Boom())
register_turn_hook(Good())
out = await run_response_hooks(_ctx(), {"id": "orig"}, _noop_call_model)
assert out == {"id": "recovered"} # Boom skipped, Good still ran
# --- hooks with only one method defined --------------------------------------
@pytest.mark.asyncio
async def test_hook_without_on_response_is_skipped():
class OnlyRequest:
name = "only-request"
def on_request(self, ctx: TurnContext) -> None:
pass
register_turn_hook(OnlyRequest())
resp = {"id": "orig"}
out = await run_response_hooks(_ctx(), resp, _noop_call_model)
assert out is resp