Commit Graph
2 Commits
Author SHA1 Message Date
074f0ae9df fix(stats): gate the output-shaping claim on the shaper being active (#3386)
## Description

`/stats` builds its `savings.by_layer.output_shaping` entry from the
persisted output-savings ledger (`get_recorder().estimate(...)`) without
checking whether the shaper is actually running. The ledger survives
restarts and can span periods or key schemas where the arms accumulated
unshaped traffic (the pre-#3209 coarse conversation keys locked whole
projects into one arm). Result, observed in the field: a stable-channel
install with the shaper `blocked_by_channel` published a "measured"
-147.9% output reduction over 19,644 requests — a claim about shaping
that deployment never performed. A user audit quoted that line back at
us as evidence the numbers can't be trusted, and they were right to.

This PR fixes it at both ends. The /stats claim is gated: when the
shaper is disabled (rollout-blocked channel, kill switch, config), the
layer reports `active: false, method: "inactive"` with a zero claim,
while active deployments publish exactly what they did before (including
honest negatives, which #3127's holdout gating owns). And the ledger no
longer accumulates the data that made the claim bogus: a treatment
observation is recorded only when the request was actually shaped.

That second half came out of review. The gate alone fixes the install
that reported the -147.9% and leaves the next install exposed, because a
ledger entry carries no shaper state - so unshaped traffic accumulated
while blocked republishes the same number on the first request after the
channel unblocks. The stratum label is attached whenever the shaper is
*configured* on, but the shaping itself can still be a no-op, and a
treatment arm holding unshaped output is precisely what manufactures a
reduction the deployment never performed.

Same spirit as #3377: Headroom only claims what it measured on this
deployment's traffic.

## Type of Change

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

## Changes Made

- New module-level `_output_reduction_payload(shaper_active, est)` in
`headroom/proxy/server.py`; the /stats route now tracks `_shaper_active`
from `OutputShaperSettings.from_env(...).enabled` and delegates payload
construction to it.
- Inactive shaper: `{"available": true, "active": false, "method":
"inactive", "tokens_saved": 0, ...}` so consumers can render "inactive"
instead of mistaking absence for a zero measurement.
- Active shaper: unchanged payload plus an additive `active: true` key.
- `SavingsRecorder.record_from_labels` records a treatment observation
only when the shaper's own `output_shaper:verbosity:` label is present
on the same channel. That label is appended only when `shape_request`
actually changed the request (`output_shaper.py` sets `changed` and the
label together, and every handler extends labels only on `changed`), so
it is the per-request proof that shaping happened. Control is unshaped
by definition and records unconditionally.
- `SavingsLedger` persists a `shaped_only` marker; arms written before
that rule are dropped on load with a warning, since they cannot be told
apart entry by entry. The offline baseline is kept - it is learned from
pre-shaper history, costs a `learn --verbosity` run to rebuild, and was
never the poisoned part.
- Every payload branch emits the same key set, nulls where a value does
not exist (`method`, `band_is_ci`, `ci_low_percent`, `ci_high_percent`),
so a consumer reading the band cannot KeyError on the inactive or
no-data paths. Numeric totals stay 0 rather than null because callers
already sum them.
- New `tests/test_stats_output_reduction_gate.py` covering the
blocked-install shape (the real -147.9% figures), the active
passthrough, the no-data case, key-set stability across all four
branches, the unshaped-treatment drop, and the legacy-ledger arm drop.
- Existing tests that recorded treatment from a bare stratum label now
attach the shaper label (`tests/test_output_savings.py`,
`tests/test_output_savings_cli.py`) - they encoded the old contract.

## Testing

- [x] Unit tests pass (`pytest`)

### Test Output

```text
uv run --frozen --extra dev pytest tests/test_stats_output_reduction_gate.py tests/test_routing_stats_seam.py tests/test_dashboard_token_savings.py -q
3 passed; 8 passed
```

## Real Behavior Proof

- Environment: macOS 15 (arm64), Python 3.12 via uv, this branch's
worktree.
- Exact command / steps: Reproduced the field payload by calling
`_output_reduction_payload` with the exact `SavingsEstimate` a blocked
stable install published (tokens_saved=-7,522,490, pct=-147.9,
n_requests=19,644, kind="measured"), shaper_active=False, then
shaper_active=True.
- Observed result: inactive path returns `method="inactive",
tokens_saved=0, reduction_percent=0.0`; active path returns the estimate
byte-identical to today's payload plus `active: true`.
- Not tested: an end-to-end /stats call on a live rollout-blocked
install (no blocked-channel machine at hand); the desktop app renders
from its own ledger recompute since 0.8.7 and does not consume this
field for its headline.

## Runtime Rollout Safety

- Rollout-managed feature(s): Reads the output-shaper's rollout state;
changes no rollout behavior itself.
- Minimum rollout channel: Stable.
- Stable/default behavior changed: Yes, for deployments where the shaper
is disabled: the /stats output_shaping layer reports inactive/zero
instead of the persisted ledger estimate. Deployments with the shaper
active are unchanged.
- Kill switch / disable path: Not applicable; the gate follows the
shaper's own enablement, which already has one.
- Unsafe override required: No.
- Qualification impact: Blocked-channel installs stop advertising
phantom (often negative) output savings in /stats and telemetry built on
it.
- Rollback path: Revert the commit; the payload shape addition
(`active`) is additive and the ledger format is untouched.

## Review Readiness

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
2026-09-09 22:55:12 -05:00
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