mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 15:10:00 +08:00
## 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>
505 lines
18 KiB
Python
505 lines
18 KiB
Python
"""Per-strategy compression observability tests.
|
|
|
|
These guard the forcing function: when any compressor runs in
|
|
production, a `CompressionObserver` notification fires once per real
|
|
compression event, and `PrometheusMetrics` accumulates per-strategy
|
|
counters that the test suite asserts on directly.
|
|
|
|
The TOIN→SmartCrusher silent disconnect (caught three weeks late by
|
|
manual audit) was invisible because no signal distinguished by
|
|
strategy. These tests exist so the next regression of that shape
|
|
fails the suite the day it lands instead of waiting on an audit.
|
|
|
|
The counters live ONLY as in-process state on the metrics instance;
|
|
they are deliberately NOT exported as new Prometheus metric names
|
|
(to avoid unbounded metric-series growth) — they remain observable
|
|
via /stats. CI-level
|
|
observability via these tests is enough to catch silent regressions;
|
|
production export waits on a non-column-adding pipeline.
|
|
|
|
Coverage:
|
|
|
|
1. `ContentRouter.compress(...)` calls observer once per RoutingDecision.
|
|
2. `SmartCrusher.apply(...)` calls observer once per crushed message.
|
|
3. Both transforms tolerate an observer that raises (compression must
|
|
still succeed).
|
|
4. `PrometheusMetrics` correctly satisfies the `CompressionObserver`
|
|
protocol — `record_compression` increments per-strategy counters
|
|
and `tokens_saved_by_strategy` accumulates only positive savings.
|
|
5. The Prometheus scrape output (`export()`) does NOT emit any new
|
|
metric names — the per-strategy state stays internal.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from headroom.transforms.content_detector import ContentType
|
|
from headroom.transforms.content_router import (
|
|
CompressionStrategy,
|
|
ContentRouter,
|
|
ContentRouterConfig,
|
|
RouterCompressionResult,
|
|
RoutingDecision,
|
|
)
|
|
from headroom.transforms.observability import CompressionObserver
|
|
from headroom.transforms.smart_crusher import SmartCrusher, SmartCrusherConfig
|
|
|
|
# ─── Test doubles ──────────────────────────────────────────────────────
|
|
|
|
|
|
@dataclass
|
|
class SpyObserver:
|
|
"""Captures every `record_compression` call for assertion."""
|
|
|
|
calls: list[tuple[str, int, int]] = field(default_factory=list)
|
|
|
|
def record_compression(
|
|
self,
|
|
strategy: str,
|
|
original_tokens: int,
|
|
compressed_tokens: int,
|
|
) -> None:
|
|
self.calls.append((strategy, original_tokens, compressed_tokens))
|
|
|
|
|
|
@dataclass
|
|
class ExplodingObserver:
|
|
"""Raises on every call. Used to assert observer failures don't
|
|
propagate out and break compression."""
|
|
|
|
raised: int = 0
|
|
|
|
def record_compression(self, *_a: Any, **_kw: Any) -> None:
|
|
self.raised += 1
|
|
raise RuntimeError("simulated observer outage")
|
|
|
|
|
|
# ─── Protocol conformance ──────────────────────────────────────────────
|
|
|
|
|
|
def test_spy_satisfies_observer_protocol():
|
|
spy = SpyObserver()
|
|
# `runtime_checkable` Protocol — isinstance check works.
|
|
assert isinstance(spy, CompressionObserver)
|
|
|
|
|
|
def test_prometheus_metrics_satisfies_observer_protocol():
|
|
from headroom.proxy.prometheus_metrics import PrometheusMetrics
|
|
|
|
m = PrometheusMetrics()
|
|
assert isinstance(m, CompressionObserver)
|
|
|
|
|
|
# ─── ContentRouter wiring ──────────────────────────────────────────────
|
|
|
|
|
|
def test_content_router_records_observer_call_per_routing_decision():
|
|
spy = SpyObserver()
|
|
router = ContentRouter(ContentRouterConfig(), observer=spy)
|
|
|
|
# Forge a routing log directly via the result object — the observer
|
|
# call site walks `result.routing_log`, so we assert the contract
|
|
# without depending on which compressor would actually fire.
|
|
result = RouterCompressionResult(
|
|
compressed="x",
|
|
original="x",
|
|
strategy_used=CompressionStrategy.SMART_CRUSHER,
|
|
routing_log=[
|
|
RoutingDecision(
|
|
content_type=ContentType.JSON_ARRAY,
|
|
strategy=CompressionStrategy.SMART_CRUSHER,
|
|
original_tokens=200,
|
|
compressed_tokens=50,
|
|
),
|
|
RoutingDecision(
|
|
content_type=ContentType.SOURCE_CODE,
|
|
strategy=CompressionStrategy.CODE_AWARE,
|
|
original_tokens=300,
|
|
compressed_tokens=300, # passthrough — still recorded
|
|
),
|
|
],
|
|
)
|
|
router._observe(result)
|
|
|
|
assert spy.calls == [
|
|
("smart_crusher", 200, 50),
|
|
("code_aware", 300, 300),
|
|
]
|
|
|
|
|
|
def test_content_router_with_no_observer_is_silent():
|
|
router = ContentRouter(ContentRouterConfig()) # observer defaults None
|
|
result = RouterCompressionResult(
|
|
compressed="x",
|
|
original="x",
|
|
strategy_used=CompressionStrategy.PASSTHROUGH,
|
|
routing_log=[
|
|
RoutingDecision(
|
|
content_type=ContentType.PLAIN_TEXT,
|
|
strategy=CompressionStrategy.TEXT,
|
|
original_tokens=10,
|
|
compressed_tokens=5,
|
|
)
|
|
],
|
|
)
|
|
# Should not raise.
|
|
router._observe(result)
|
|
|
|
|
|
def test_content_router_swallows_observer_failures():
|
|
boom = ExplodingObserver()
|
|
router = ContentRouter(ContentRouterConfig(), observer=boom)
|
|
result = RouterCompressionResult(
|
|
compressed="x",
|
|
original="x",
|
|
strategy_used=CompressionStrategy.TEXT,
|
|
routing_log=[
|
|
RoutingDecision(
|
|
content_type=ContentType.PLAIN_TEXT,
|
|
strategy=CompressionStrategy.TEXT,
|
|
original_tokens=10,
|
|
compressed_tokens=5,
|
|
)
|
|
],
|
|
)
|
|
# Must not raise — observability failures are not compression failures.
|
|
router._observe(result)
|
|
assert boom.raised == 1
|
|
|
|
|
|
# ─── SmartCrusher wiring (legacy direct-pipeline path) ─────────────────
|
|
|
|
|
|
def _bigger_array(n: int = 60) -> str:
|
|
import json as _json
|
|
|
|
items = [{"status": "ok", "tag": "x", "n": i} for i in range(n)]
|
|
return _json.dumps(items)
|
|
|
|
|
|
@pytest.fixture
|
|
def isolated_toin(tmp_path, monkeypatch):
|
|
"""Point TOIN at a tempdir for the duration of the test.
|
|
|
|
SmartCrusher.apply() feeds the global TOIN learning store via
|
|
`record_compression`. Its default storage path is
|
|
`~/.headroom/toin.json`, which persists across pytest invocations.
|
|
On Python 3.11 CI runs the suite twice (regular + coverage); a
|
|
pattern written in run #1 changes which rows the lossy sampler
|
|
keeps in run #2 and breaks `test_first_last_items_always_preserved`
|
|
in `test_evals.py`.
|
|
|
|
Isolating the TOIN file per test contains the side effect.
|
|
"""
|
|
from pathlib import Path
|
|
|
|
from headroom.telemetry.toin import TOIN_PATH_ENV_VAR, reset_toin
|
|
|
|
storage = str(Path(tmp_path) / "toin.json")
|
|
monkeypatch.setenv(TOIN_PATH_ENV_VAR, storage)
|
|
reset_toin()
|
|
yield
|
|
reset_toin()
|
|
|
|
|
|
def test_smart_crusher_apply_records_observer_per_crushed_message(isolated_toin):
|
|
"""End-to-end: SmartCrusher.apply() walks messages, crushes the
|
|
big tool_result, fires the observer with strategy='smart_crusher'."""
|
|
from headroom.providers.openai import OpenAITokenCounter
|
|
from headroom.tokenizer import Tokenizer
|
|
|
|
spy = SpyObserver()
|
|
crusher = SmartCrusher(SmartCrusherConfig(), observer=spy)
|
|
tok = Tokenizer(OpenAITokenCounter("gpt-4o-mini"), model="gpt-4o-mini")
|
|
|
|
messages = [
|
|
{"role": "user", "content": "what's in the data?"},
|
|
{"role": "tool", "content": _bigger_array(60)},
|
|
]
|
|
result = crusher.apply(messages, tok)
|
|
# If the analyzer chose passthrough this run, the observer wasn't
|
|
# fired; that's fine for the wiring test — we only assert it WAS
|
|
# fired in the case it crushed.
|
|
if "smart_crush:" in ",".join(result.transforms_applied):
|
|
assert spy.calls, "smart_crusher crushed but observer wasn't notified"
|
|
for strategy, original, compressed in spy.calls:
|
|
assert strategy == "smart_crusher"
|
|
assert original > 0
|
|
assert compressed >= 0
|
|
|
|
|
|
def test_smart_crusher_apply_swallows_observer_failures(isolated_toin):
|
|
"""Observer raises → compression still completes, returns valid
|
|
TransformResult, count of raises matches the crushed_count."""
|
|
from headroom.providers.openai import OpenAITokenCounter
|
|
from headroom.tokenizer import Tokenizer
|
|
|
|
boom = ExplodingObserver()
|
|
crusher = SmartCrusher(SmartCrusherConfig(), observer=boom)
|
|
tok = Tokenizer(OpenAITokenCounter("gpt-4o-mini"), model="gpt-4o-mini")
|
|
messages = [{"role": "tool", "content": _bigger_array(60)}]
|
|
result = crusher.apply(messages, tok)
|
|
# Either the analyzer didn't crush (boom.raised == 0) or it did
|
|
# (boom.raised >= 1) — but in both cases compression returned a
|
|
# valid TransformResult. No exception escaped.
|
|
assert result.messages is not None
|
|
|
|
|
|
# ─── PrometheusMetrics implementation ──────────────────────────────────
|
|
|
|
|
|
def test_prometheus_metrics_accumulates_per_strategy_counters():
|
|
from headroom.proxy.prometheus_metrics import PrometheusMetrics
|
|
|
|
m = PrometheusMetrics()
|
|
|
|
m.record_compression("smart_crusher", original_tokens=200, compressed_tokens=50)
|
|
m.record_compression("smart_crusher", original_tokens=100, compressed_tokens=40)
|
|
m.record_compression("diff", original_tokens=80, compressed_tokens=80) # no savings
|
|
m.record_compression("code_aware", original_tokens=50, compressed_tokens=70) # negative savings
|
|
|
|
assert m.compressions_by_strategy == {
|
|
"smart_crusher": 2,
|
|
"diff": 1,
|
|
"code_aware": 1,
|
|
}
|
|
# Tokens saved is `max(0, original - compressed)` per strategy.
|
|
# smart_crusher: 150 + 60 = 210; diff: 0 (no savings, dict entry omitted);
|
|
# code_aware: 0 (negative).
|
|
assert m.tokens_saved_by_strategy == {"smart_crusher": 210}
|
|
|
|
|
|
def test_prometheus_metrics_accumulates_extension_savings_per_key() -> None:
|
|
from headroom.proxy.prometheus_metrics import PrometheusMetrics
|
|
|
|
m = PrometheusMetrics()
|
|
|
|
m.record_extension_savings("tool_router", 120)
|
|
m.record_extension_savings("tool_router", 30)
|
|
m.record_extension_savings("skill_search", 45)
|
|
m.record_extension_savings("skill_search", 0) # no savings, ignored
|
|
m.record_extension_savings("noop_ext", -10) # negative, ignored
|
|
|
|
# Savings accumulate per key; non-positive values never create or
|
|
# bump an entry.
|
|
assert m.extension_savings == {"tool_router": 150, "skill_search": 45}
|
|
|
|
|
|
def test_extension_savings_surface_in_stats(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
from fastapi.testclient import TestClient
|
|
|
|
from headroom.proxy.server import ProxyConfig, create_app
|
|
|
|
monkeypatch.setenv("HEADROOM_SAVINGS_PATH", str(tmp_path / "proxy_savings.json"))
|
|
config = ProxyConfig(
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
log_requests=False,
|
|
)
|
|
app = create_app(config)
|
|
with TestClient(app) as client:
|
|
proxy = app.state.proxy
|
|
proxy.metrics.record_extension_savings("tool_router", 200)
|
|
proxy.metrics.record_extension_savings("tool_router", 50)
|
|
proxy.metrics.record_extension_savings("skill_search", 75)
|
|
|
|
stats = client.get("/stats")
|
|
assert stats.status_code == 200
|
|
assert stats.json()["extension_savings"] == {
|
|
"tool_router": 250,
|
|
"skill_search": 75,
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_turn_hook_savings_surface_in_stats_extension_savings(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""``ctx.record_savings`` from a turn hook must reach ``/stats.extension_savings``.
|
|
|
|
Before, only ``record_extension_savings`` filled the field and core never
|
|
calls it, so ``/stats`` showed ``{}`` while a hook saved ~8K tokens a request.
|
|
Estimated rows stay out, and a plugin reporting through both APIs (hdr) is
|
|
not counted twice.
|
|
"""
|
|
from fastapi.testclient import TestClient
|
|
|
|
from headroom.proxy.server import ProxyConfig, create_app
|
|
|
|
monkeypatch.setenv("HEADROOM_SAVINGS_PATH", str(tmp_path / "proxy_savings.json"))
|
|
app = create_app(ProxyConfig(cache_enabled=False, rate_limit_enabled=False, log_requests=False))
|
|
with TestClient(app) as client:
|
|
metrics = app.state.proxy.metrics
|
|
for _ in range(2):
|
|
await metrics.record_request(
|
|
provider="openai",
|
|
model="gpt-5.4",
|
|
input_tokens=1000,
|
|
output_tokens=10,
|
|
tokens_saved=0,
|
|
latency_ms=1.0,
|
|
savings_attribution=[
|
|
{"source": "tool_search", "realized": True, "tokens": 8000},
|
|
{"source": "tool_search", "realized": False, "estimated": True, "tokens": 500},
|
|
{"source": "hdr", "realized": True, "tokens": 300},
|
|
],
|
|
)
|
|
metrics.record_extension_savings("hdr", 300)
|
|
|
|
stats = client.get("/stats").json()
|
|
|
|
assert stats["extension_savings"] == {"tool_search": 16000, "hdr": 600}
|
|
by_source = {
|
|
(row["source"], row["realized"]): row["tokens"] for row in stats["savings"]["by_source"]
|
|
}
|
|
assert by_source[("tool_search", False)] == 1000
|
|
|
|
|
|
def test_prometheus_metrics_accumulates_codex_ws_unit_and_frame_counters():
|
|
from headroom.proxy.prometheus_metrics import PrometheusMetrics
|
|
|
|
m = PrometheusMetrics()
|
|
|
|
m.record_codex_ws_unit(
|
|
strategy="mixed",
|
|
reason_category="applied",
|
|
elapsed_ms=1250,
|
|
text_bytes=10_000,
|
|
tokens_before=2500,
|
|
tokens_after=1000,
|
|
tokens_saved=1500,
|
|
modified=True,
|
|
strategy_chain=["mixed", "kompress"],
|
|
content_type="text",
|
|
text_shape="jsonl_like",
|
|
)
|
|
m.record_codex_ws_unit(
|
|
strategy="passthrough",
|
|
reason_category="size_floor",
|
|
elapsed_ms=2,
|
|
text_bytes=100,
|
|
tokens_before=20,
|
|
tokens_after=20,
|
|
tokens_saved=0,
|
|
modified=False,
|
|
strategy_chain=["passthrough"],
|
|
content_type="unknown",
|
|
text_shape="plain_text_like",
|
|
)
|
|
m.record_codex_ws_frame(
|
|
elapsed_ms=1260,
|
|
bytes_before=20_000,
|
|
bytes_after=8_000,
|
|
attempted_tokens=2500,
|
|
tokens_saved=1500,
|
|
modified=True,
|
|
strategy_chain=["mixed", "kompress"],
|
|
final_strategies=["mixed"],
|
|
)
|
|
m.record_codex_ws_frame(
|
|
elapsed_ms=30_000,
|
|
bytes_before=426_318,
|
|
failed=True,
|
|
)
|
|
|
|
assert m.codex_ws_units_total == 2
|
|
assert m.codex_ws_units_modified_total == 1
|
|
assert m.codex_ws_units_by_strategy == {"mixed": 1, "passthrough": 1}
|
|
assert m.codex_ws_units_by_category == {"applied": 1, "size_floor": 1}
|
|
assert m.codex_ws_units_by_content_type == {"text": 1, "unknown": 1}
|
|
assert m.codex_ws_units_by_text_shape == {"jsonl_like": 1, "plain_text_like": 1}
|
|
assert m.codex_ws_units_to_kompress_total == 0
|
|
assert m.codex_ws_units_kompress_attempted_total == 1
|
|
assert m.codex_ws_unit_elapsed_ms_max == 1250
|
|
assert m.codex_ws_unit_tokens_saved_sum == 1500
|
|
|
|
assert m.codex_ws_frames_attempted_total == 2
|
|
assert m.codex_ws_frames_compressed_total == 1
|
|
assert m.codex_ws_frames_failed_total == 1
|
|
assert m.codex_ws_frames_to_kompress_total == 0
|
|
assert m.codex_ws_frames_kompress_attempted_total == 1
|
|
assert m.codex_ws_frame_elapsed_ms_max == 30_000
|
|
assert m.codex_ws_frame_tokens_saved_sum == 1500
|
|
|
|
|
|
def test_prometheus_export_does_not_leak_per_strategy_metrics():
|
|
"""Per-strategy state is tracked in-process only. The Prometheus
|
|
scrape output deliberately must NOT emit new metric names (to avoid
|
|
unbounded metric-series growth); the state stays observable via
|
|
/stats. This test guards that constraint: if a future change adds
|
|
the metric to the scrape, this fails and forces a conscious
|
|
decision."""
|
|
import asyncio
|
|
|
|
from headroom.proxy.prometheus_metrics import PrometheusMetrics
|
|
|
|
m = PrometheusMetrics()
|
|
m.record_compression("smart_crusher", original_tokens=200, compressed_tokens=50)
|
|
m.record_compression("diff", original_tokens=120, compressed_tokens=70)
|
|
|
|
output = asyncio.run(m.export())
|
|
|
|
assert "headroom_compressions_total" not in output
|
|
assert "headroom_tokens_saved_by_strategy_total" not in output
|
|
|
|
|
|
# ─── End-to-end smoke (router + metrics together) ──────────────────────
|
|
|
|
|
|
def test_router_with_prometheus_observer_increments_counters():
|
|
"""Plumbing test: a router wired to a real PrometheusMetrics
|
|
instance lights up the per-strategy counters as routing decisions
|
|
accumulate. This is the production wiring shape from
|
|
`headroom/proxy/server.py`."""
|
|
from headroom.proxy.prometheus_metrics import PrometheusMetrics
|
|
|
|
m = PrometheusMetrics()
|
|
router = ContentRouter(ContentRouterConfig(), observer=m)
|
|
|
|
fake_result = RouterCompressionResult(
|
|
compressed="x",
|
|
original="x",
|
|
strategy_used=CompressionStrategy.MIXED,
|
|
routing_log=[
|
|
RoutingDecision(
|
|
content_type=ContentType.JSON_ARRAY,
|
|
strategy=CompressionStrategy.SMART_CRUSHER,
|
|
original_tokens=300,
|
|
compressed_tokens=80,
|
|
),
|
|
RoutingDecision(
|
|
content_type=ContentType.SOURCE_CODE,
|
|
strategy=CompressionStrategy.CODE_AWARE,
|
|
original_tokens=200,
|
|
compressed_tokens=120,
|
|
),
|
|
RoutingDecision(
|
|
content_type=ContentType.JSON_ARRAY,
|
|
strategy=CompressionStrategy.SMART_CRUSHER,
|
|
original_tokens=100,
|
|
compressed_tokens=40,
|
|
),
|
|
],
|
|
)
|
|
router._observe(fake_result)
|
|
|
|
assert m.compressions_by_strategy == {"smart_crusher": 2, "code_aware": 1}
|
|
assert m.tokens_saved_by_strategy == {
|
|
"smart_crusher": (300 - 80) + (100 - 40), # 280
|
|
"code_aware": (200 - 120), # 80
|
|
}
|
|
|
|
|
|
# IntelligentContextManager observability tests retired with PR-B1 —
|
|
# the manager itself was deleted along with the message-dropping
|
|
# strategy. Inner-router observability is now exercised solely
|
|
# through ContentRouter, covered by
|
|
# `test_content_router_records_observer_call_per_routing_decision`.
|