headroom/tests/test_output_shaper.py
Tejas Chopra a99dc61424
feat: output-token reduction — verbosity shaper, per-user learning, counterfactual savings (#965)
## Description

Adds the first levers that reduce the tokens the model **writes back**
(output), complementing Headroom's existing input compression. Output
costs 5× input on Opus-class models and is full of waste (ceremony,
restated code, deep "thinking" on routine steps). Two phases in one
self-contained PR off `main`: the request-side output shaper, then
per-user verbosity learning plus an honest counterfactual savings
estimator and dashboard surfacing.

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- **Output shaper** (`output_shaper.py`, opt-in
`HEADROOM_OUTPUT_SHAPER=1`): cache-safe verbosity steering appended to
the system-prompt tail (5 levels); effort routing that lowers
`output_config.effort` on mechanical tool-result continuations; legacy
`thinking.budget_tokens` clamp. Never injects effort where absent, never
toggles `thinking.type`.
- **`headroom learn --verbosity`**: mines Claude Code transcripts for
behavioral signals (interrupts, length-adaptive fast-skips, echo ratio),
recommends a verbosity level (heuristic + optional `--llm-judge`), and
seeds the savings baseline.
- **Counterfactual estimator** (`output_savings.py`): per-stratum
synthetic-control (estimated) + A/B holdout (measured) with a propagated
95% CI; conversation-stable arm assignment for A/B validity and
prefix-cache safety.
- **AIMD verbosity controller** (`verbosity_controller.py`):
additive-increase / fast-back-off state machine; live signal emission
gated off by default.
- **Wiring + surfaces**: shaper resolves the learned level; recording
rides the existing `transforms_applied` channel through the outcome
funnel (no `RequestOutcome` changes); `headroom output-savings` CLI;
dashboard "Output Tokens Saved" card.
- **Docs**: simple-words user guide + design doc with the counterfactual
methodology.

## 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

### Test Output

```text
$ pytest tests/test_output_savings.py tests/test_output_savings_cli.py \
        tests/test_verbosity_learn.py tests/test_verbosity_controller.py \
        tests/test_output_shaper.py -q
94 passed in 0.54s

$ pytest tests/test_request_outcome.py tests/test_handler_outcome_tag_invariant.py \
        tests/test_proxy_dashboard_stats_cache.py -q
44 passed

$ ruff format --check .
831 files already formatted

$ mypy headroom --ignore-missing-imports
Success: no issues found in 361 source files
```

## Real Behavior Proof

- Environment: macOS, Python 3.12 (`.venv`), `anthropic` 0.76, live API
model `claude-opus-4-8`.
- Exact command / steps: `HEADROOM_OUTPUT_SHAPER=1`; `headroom learn
--verbosity --apply` (seeds level + baseline); `python
scripts/eval_output_shaper.py A` (live before/after); simulate holdout
traffic then `headroom output-savings`.
- Observed result: code-review ask — baseline 1,750 output tokens → L2
1,354 (−22.7%) → L3 599 (−65.8%), same bugs found. `learn --verbosity`
on 24 real sessions → 11% interrupt / 26% fast-skip → L3 (high
confidence). Measured A/B path → 31.7% reduction (95% CI 27.7%–35.7%).
94 new tests + 44 existing outcome/dashboard tests green; ruff + mypy
clean.
- Not tested: live streaming-path recording exercised only via unit
tests (the `transforms_applied` funnel is shared across paths); runtime
AIMD signal emission is gated off by default and not exercised live.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] I have updated the CHANGELOG.md if applicable

## Additional Notes

Output savings are counterfactual (we never observe what the model
*would* have written), so the estimator separates **estimated** (vs a
learned baseline) from **measured** (A/B holdout via
`HEADROOM_OUTPUT_HOLDOUT`) and always reports a confidence band — never
a single made-up number. CHANGELOG left unchecked (release-please
manages it). Runtime AIMD self-tuning is intentionally a TODO
(controller built/tested; live signal emission gated behind
`HEADROOM_VERBOSITY_AUTOTUNE`).
2026-06-16 21:06:43 -07:00

284 lines
11 KiB
Python

"""Tests for headroom.proxy.output_shaper.
Covers turn classification (structural only), cache-safe verbosity steering,
effort routing on mechanical continuations, and the env-driven gate.
"""
from __future__ import annotations
import copy
from typing import Any
from headroom.proxy.output_shaper import (
LEGACY_THINKING_FLOOR,
OutputShaperSettings,
TurnKind,
apply_verbosity_steering,
classify_turn,
route_effort,
shape_request,
steering_text,
)
ENABLED = OutputShaperSettings(enabled=True)
def _tool_result(is_error: bool = False) -> dict[str, Any]:
block: dict[str, Any] = {
"type": "tool_result",
"tool_use_id": "toolu_01",
"content": "ok",
}
if is_error:
block["is_error"] = True
return block
def _mechanical_messages() -> list[dict[str, Any]]:
return [
{"role": "user", "content": "fix the bug in foo.py"},
{
"role": "assistant",
"content": [
{"type": "text", "text": "Reading the file."},
{"type": "tool_use", "id": "toolu_01", "name": "Read", "input": {}},
],
},
{"role": "user", "content": [_tool_result()]},
]
# ---------------------------------------------------------------------------
# classify_turn
# ---------------------------------------------------------------------------
class TestClassifyTurn:
def test_string_user_message_is_new_ask(self):
assert classify_turn([{"role": "user", "content": "explain this"}]) == TurnKind.NEW_USER_ASK
def test_clean_tool_result_is_mechanical(self):
assert classify_turn(_mechanical_messages()) == TurnKind.MECHANICAL_CONTINUATION
def test_multiple_clean_tool_results_are_mechanical(self):
msgs = _mechanical_messages()
msgs[-1]["content"].append(_tool_result())
assert classify_turn(msgs) == TurnKind.MECHANICAL_CONTINUATION
def test_error_tool_result_is_error_continuation(self):
msgs = _mechanical_messages()
msgs[-1]["content"] = [_tool_result(), _tool_result(is_error=True)]
assert classify_turn(msgs) == TurnKind.ERROR_CONTINUATION
def test_text_block_alongside_tool_result_is_new_ask(self):
msgs = _mechanical_messages()
msgs[-1]["content"].append({"type": "text", "text": "also check bar.py"})
assert classify_turn(msgs) == TurnKind.NEW_USER_ASK
def test_image_block_is_new_ask(self):
msgs = [{"role": "user", "content": [{"type": "image", "source": {}}]}]
assert classify_turn(msgs) == TurnKind.NEW_USER_ASK
def test_assistant_last_is_unknown(self):
msgs = [{"role": "assistant", "content": "hello"}]
assert classify_turn(msgs) == TurnKind.UNKNOWN
def test_empty_messages_is_unknown(self):
assert classify_turn([]) == TurnKind.UNKNOWN
def test_empty_content_list_is_unknown(self):
assert classify_turn([{"role": "user", "content": []}]) == TurnKind.UNKNOWN
def test_whitespace_string_content_is_unknown(self):
assert classify_turn([{"role": "user", "content": " "}]) == TurnKind.UNKNOWN
# ---------------------------------------------------------------------------
# apply_verbosity_steering
# ---------------------------------------------------------------------------
class TestVerbositySteering:
def test_level_zero_is_noop(self):
body = {"system": "You are helpful."}
assert apply_verbosity_steering(body, 0) is False
assert body["system"] == "You are helpful."
def test_string_system_converted_to_blocks_with_original_bytes_first(self):
body = {"system": "You are helpful."}
assert apply_verbosity_steering(body, 2) is True
assert body["system"][0] == {"type": "text", "text": "You are helpful."}
assert body["system"][1]["text"] == steering_text(2)
def test_missing_system_creates_steering_only_block(self):
body: dict[str, Any] = {}
assert apply_verbosity_steering(body, 2) is True
assert body["system"] == [{"type": "text", "text": steering_text(2)}]
def test_block_system_appends_after_cache_control(self):
cached = {
"type": "text",
"text": "Big system prompt.",
"cache_control": {"type": "ephemeral"},
}
body = {"system": [copy.deepcopy(cached)]}
assert apply_verbosity_steering(body, 2) is True
# The cached block is byte-identical and still first — prefix intact.
assert body["system"][0] == cached
assert body["system"][1] == {"type": "text", "text": steering_text(2)}
# Our block carries no cache_control (breakpoints are a scarce resource).
assert "cache_control" not in body["system"][1]
def test_idempotent_at_same_level(self):
body = {"system": [{"type": "text", "text": "Sys."}]}
assert apply_verbosity_steering(body, 2) is True
snapshot = copy.deepcopy(body)
assert apply_verbosity_steering(body, 2) is False
assert body == snapshot
def test_level_change_replaces_block_in_place(self):
body = {"system": [{"type": "text", "text": "Sys."}]}
apply_verbosity_steering(body, 2)
assert apply_verbosity_steering(body, 4) is True
steering_blocks = [
b for b in body["system"] if b["text"].startswith("<headroom_output_shaping>")
]
assert len(steering_blocks) == 1
assert steering_blocks[0]["text"] == steering_text(4)
def test_steering_text_is_deterministic(self):
for level in (1, 2, 3, 4):
assert steering_text(level) == steering_text(level)
# ---------------------------------------------------------------------------
# route_effort
# ---------------------------------------------------------------------------
class TestRouteEffort:
def test_lowers_explicit_effort_on_mechanical_turn(self):
body = {"output_config": {"effort": "xhigh"}}
labels = route_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED)
assert body["output_config"]["effort"] == "low"
assert labels == ["output_shaper:effort:xhigh->low"]
def test_never_injects_effort_when_absent(self):
body: dict[str, Any] = {"messages": []}
labels = route_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED)
assert "output_config" not in body
assert labels == []
def test_effort_untouched_on_new_ask(self):
body = {"output_config": {"effort": "xhigh"}}
assert route_effort(body, TurnKind.NEW_USER_ASK, ENABLED) == []
assert body["output_config"]["effort"] == "xhigh"
def test_effort_untouched_on_error_continuation(self):
body = {"output_config": {"effort": "xhigh"}}
assert route_effort(body, TurnKind.ERROR_CONTINUATION, ENABLED) == []
assert body["output_config"]["effort"] == "xhigh"
def test_effort_already_at_target_untouched(self):
body = {"output_config": {"effort": "low"}}
assert route_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED) == []
def test_unknown_effort_value_untouched(self):
body = {"output_config": {"effort": "turbo"}}
assert route_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED) == []
assert body["output_config"]["effort"] == "turbo"
def test_configurable_mechanical_effort(self):
settings = OutputShaperSettings(enabled=True, mechanical_effort="medium")
body = {"output_config": {"effort": "xhigh"}}
route_effort(body, TurnKind.MECHANICAL_CONTINUATION, settings)
assert body["output_config"]["effort"] == "medium"
def test_legacy_thinking_budget_clamped(self):
body = {"thinking": {"type": "enabled", "budget_tokens": 32000}}
labels = route_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED)
assert body["thinking"]["budget_tokens"] == LEGACY_THINKING_FLOOR
assert body["thinking"]["type"] == "enabled" # never toggled
assert labels == [f"output_shaper:thinking_budget:32000->{LEGACY_THINKING_FLOOR}"]
def test_legacy_budget_at_floor_untouched(self):
body = {"thinking": {"type": "enabled", "budget_tokens": LEGACY_THINKING_FLOOR}}
assert route_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED) == []
def test_adaptive_thinking_untouched(self):
body = {"thinking": {"type": "adaptive"}}
assert route_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED) == []
assert body["thinking"] == {"type": "adaptive"}
# ---------------------------------------------------------------------------
# shape_request (end to end)
# ---------------------------------------------------------------------------
class TestShapeRequest:
def test_disabled_is_noop(self):
body = {
"system": "Sys.",
"messages": _mechanical_messages(),
"output_config": {"effort": "xhigh"},
}
snapshot = copy.deepcopy(body)
result = shape_request(body, OutputShaperSettings(enabled=False))
assert result.changed is False
assert body == snapshot
def test_enabled_applies_steering_and_effort_routing(self):
body = {
"system": "Sys.",
"messages": _mechanical_messages(),
"output_config": {"effort": "xhigh"},
"thinking": {"type": "adaptive"},
}
result = shape_request(body, ENABLED)
assert result.changed is True
assert result.labels == [
"output_shaper:verbosity:L2",
"output_shaper:effort:xhigh->low",
]
assert body["output_config"]["effort"] == "low"
assert body["system"][1]["text"] == steering_text(2)
def test_new_ask_gets_steering_but_keeps_effort(self):
body = {
"system": "Sys.",
"messages": [{"role": "user", "content": "design a cache layer"}],
"output_config": {"effort": "xhigh"},
}
result = shape_request(body, ENABLED)
assert result.labels == ["output_shaper:verbosity:L2"]
assert body["output_config"]["effort"] == "xhigh"
def test_second_pass_is_stable(self):
body = {"system": "Sys.", "messages": _mechanical_messages()}
shape_request(body, ENABLED)
snapshot = copy.deepcopy(body)
result = shape_request(body, ENABLED)
assert result.changed is False
assert body == snapshot
def test_from_env_defaults_off(self, monkeypatch):
monkeypatch.delenv("HEADROOM_OUTPUT_SHAPER", raising=False)
assert OutputShaperSettings.from_env().enabled is False
def test_from_env_enabled_with_overrides(self, monkeypatch):
monkeypatch.setenv("HEADROOM_OUTPUT_SHAPER", "1")
monkeypatch.setenv("HEADROOM_VERBOSITY_LEVEL", "3")
monkeypatch.setenv("HEADROOM_MECHANICAL_EFFORT", "medium")
settings = OutputShaperSettings.from_env()
assert settings.enabled is True
assert settings.verbosity_level == 3
assert settings.mechanical_effort == "medium"
def test_from_env_clamps_bad_values(self, monkeypatch):
monkeypatch.setenv("HEADROOM_OUTPUT_SHAPER", "true")
monkeypatch.setenv("HEADROOM_VERBOSITY_LEVEL", "99")
monkeypatch.setenv("HEADROOM_MECHANICAL_EFFORT", "bogus")
settings = OutputShaperSettings.from_env()
assert settings.verbosity_level == 4
assert settings.mechanical_effort == "low"