feat(shaper): let an extension replace a level's steering text; default to L3 (#4877)

## Description

Output steering's default level moves from 2 to 3, and core gains two
extension hooks so a licensed extension can install its own benchmarked
steering text and make that level the default.

- `register_verbosity_text(level, text)` in `output_verbosity_policy`:
replaces the text for an existing level. It rejects unknown levels,
empty text, and text containing the sentinel or suffix.
- `register_default_verbosity_level(level)` in `output_shaper`: sets the
level used when `HEADROOM_VERBOSITY_LEVEL` is unset. An explicit env var
still wins, and a proxy without the extension keeps core's default.

OSS steering texts are unchanged.

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [x] Breaking change (fix or feature that would cause existing
functionality to change): the default level changes from 2 to 3 for
proxies with output steering on
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/proxy/output_shaper.py`: `DEFAULT_VERBOSITY_LEVEL = 3` with
the measurement in its comment, plus `register_default_verbosity_level`.
- `headroom/proxy/output_verbosity_policy.py`:
`register_verbosity_text`.
- Tests:
  - The pinned default now asserts 3.
- New tests cover both hooks: replacement, rejection, and an env-pinned
level winning over a registered default.
- `test_verbosity_apply_reads_an_unparseable_pin_as_the_default_level`
now picks a learned level that differs from the default. It had silently
assumed the two were different.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`): clean on the touched
files. Pre-existing errors remain in `prefix_tracker.py` and
`mcp_server.py`.
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest -q tests/test_output_*.py tests/gateway/test_output_steering.py tests/test_cli_learn.py \
    tests/test_verbosity_*.py tests/test_openai_responses_output_shaper.py tests/test_stats_output_reduction_gate.py
343 passed in 16.21s
$ ruff check headroom && ruff format --check headroom
All checks passed!
```

## Real Behavior Proof

Two pieces of evidence: (1) the real proxy from this branch shaping
requests, and (2) the SWE-bench run behind the L2 → L3 default change.
Part 2 now has its exact commands and config, artifacts you can open,
and its raw output, all re-checked on 2026-11-18 (see "Reproduction
check").

### 1. Proxy request shaping

- Environment: macOS, Python 3.12, the real `headroom proxy` from this
branch (`0.45.0-dev`) with an isolated `HEADROOM_WORKSPACE_DIR` and a
local fake Anthropic upstream that records each request body.
- Exact command / steps: `HEADROOM_OUTPUT_SHAPER=1 headroom proxy --port
18799 --anthropic-api-url http://127.0.0.1:18798`, then 3 `POST
/v1/messages` calls with different prompts. Repeated with a licensed
extension calling both hooks, with `HEADROOM_VERBOSITY_LEVEL=3` pinned,
and with the extension requested but unlicensed.

- Observed result: the proxy log and the upstream body for each
scenario:

| Proxy scenario | Proxy log | What the upstream received |
|---|---|---|
| Core, steering on | `OutputShaper(L3/cache_mode_default)` ×3 | core L3
steering block |
| Extension registers a default level and text |
`OutputShaper(L<registered>/cache_mode_default)` ×3 | core L3 block plus
the extension's text |
| Extension loaded, `HEADROOM_VERBOSITY_LEVEL=3` |
`OutputShaper(L3/env_pinned)` ×3 | core L3 block; the extension's text
absent (0 of 3) |
| Extension requested, no licence | `proxy extension ... failed to
install and was skipped: no license configured …`, then
`OutputShaper(L3/cache_mode_default)` ×3 | core L3 block |

### 2. SWE-bench Verified: L3 against no steering

**Artifacts.** Everything is pinned to one commit, so it cannot drift:

- Configs, task list, steering texts, scripts and every output:
[`headroom-bench@8fa90e9:artifacts/output-steering-2026-11-14`](https://github.com/headroomlabs-ai/headroom-bench/tree/8fa90e916dc835b6eac4110203f4fe50d73c3fed/artifacts/output-steering-2026-11-14)
(private repo; reviewers have access).
- L3 arm config:
[`configs/full_l3.yaml`](https://github.com/headroomlabs-ai/headroom-bench/blob/8fa90e916dc835b6eac4110203f4fe50d73c3fed/artifacts/output-steering-2026-11-14/configs/full_l3.yaml)
- Vanilla arm config:
[`configs/full_a0.yaml`](https://github.com/headroomlabs-ai/headroom-bench/blob/8fa90e916dc835b6eac4110203f4fe50d73c3fed/artifacts/output-steering-2026-11-14/configs/full_a0.yaml)
- Per-trial results:
[`analysis/trials_a0_vs_l3.csv`](https://github.com/headroomlabs-ai/headroom-bench/blob/8fa90e916dc835b6eac4110203f4fe50d73c3fed/artifacts/output-steering-2026-11-14/analysis/trials_a0_vs_l3.csv)
- Raw trajectories for all 200 L3/A0 trials: release
[`output-steering-2026-11-14`](https://github.com/headroomlabs-ai/headroom-bench/releases/tag/output-steering-2026-11-14),
asset `output-steering-2026-11-14-jobs.tar.gz`, sha256
`40623d407d9ff3a5e934eae0cfca8f23af08a92dfc08b0cb7a0eceae09a55a0c`. It
holds every trial's `result.json`, `config.json`, Claude Code transcript
and verifier log. It was scanned for credentials before upload.
- Mirror of the L3-only files, including the judge verdicts:
https://gist.github.com/chopratejas/998f645d639d074e4dfc7676a4f03806

**Configuration.**

| Field | Value |
|---|---|
| Runner | Harbor 0.20.0 (`headroom-bench/integrations/harbor`), Daytona
sandboxes, `auto_snapshot: false` |
| Agent | Claude Code `2.1.325`, model `anthropic/claude-opus-5-5`,
`max_turns: 120`, `max_budget_usd: 15` |
| Dataset | `swe-bench/swe-bench-verified` @
`sha256:b934b0cc3dc800fe945eaf9f1623329db97ee3133c706d20644524c7759fb341`
|
| Tasks | 50 drawn at random with seed `20261114`
([`tasks50.txt`](https://github.com/headroomlabs-ai/headroom-bench/blob/8fa90e916dc835b6eac4110203f4fe50d73c3fed/artifacts/output-steering-2026-11-14/tasks50.txt));
2 attempts per task per arm |
| L3 arm | `append_system_prompt` = core's L3 block, the position the
proxy uses |
| A0 arm | identical config with no `append_system_prompt` |

The L3 text matches this PR byte for byte. On head `b10aac36`,
`headroom.proxy.output_shaper.steering_text(3)` equals the benchmark's
`steering/l3.txt` exactly (after trimming the trailing newline). Checked
with `steering_text(3).strip() ==
open("steering/l3.txt").read().strip()`, which prints `True`.

**Exact commands.**

```bash
# headroom-bench @ 8fa90e9, integrations/harbor venv (Harbor 0.20.0)
# .env.local provides DAYTONA_API_KEY and ANTHROPIC_API_KEY
set -a; . .env.local; set +a
D=artifacts/output-steering-2026-11-14
harbor run -c $D/configs/full_a0.yaml -n 10 -k 2      # -> jobs-full/a0/full-a0
harbor run -c $D/configs/full_l3.yaml -n 10 -k 2      # -> jobs-full/l3/full-l3

python3 $D/harness/analyze.py jobs-full/a0/full-a0 jobs-full/l3/full-l3 --csv trials_a0_vs_l3.csv
python3 $D/harness/quality.py jobs-full/a0/full-a0 jobs-full/l3/full-l3
python  $D/harness/judge.py   jobs-full/a0/full-a0 jobs-full/l3/full-l3 <swe-bench-verified task dir>   # needs `anthropic`

# Re-derive the tables without re-running the agents (no API keys needed):
gh release download output-steering-2026-11-14 -R headroomlabs-ai/headroom-bench
tar -xzf output-steering-2026-11-14-jobs.tar.gz      # -> jobs-full/<arm>/...
python3 $D/harness/analyze.py jobs-full/a0/full-a0 jobs-full/l3/full-l3
python3 $D/harness/quality.py jobs-full/a0/full-a0 jobs-full/l3/full-l3
```

**Observed output** (verbatim. `analyze.py` and `quality.py` label the
steered arm "L4" whichever arm is compared; here it is L3):

```text
$ python3 harness/analyze.py jobs-full/a0/full-a0 jobs-full/l3/full-l3
trials: 200  excluded (infra/no result): 4  paired tasks: 49
solved  A0 45.0  L4 44.5  of 49
metric          A0 total     L4 total  reduction  95% CI
output         160,219.0    141,551.0     11.7%  [7.3%, 16.1%]
prose           37,857.3     30,850.6     18.5%  [15.5%, 21.3%]
tool_input     103,630.7     95,519.4      7.8%  [3.0%, 12.8%]
thinking        18,731.0     15,181.0     19.0%  [0.3%, 33.4%]
turns              521.0        483.5      7.2%  [1.7%, 12.4%]
cost                 8.0          7.3      9.5%  [5.3%, 13.4%]
cache_read  10,639,496.0  9,624,361.0      9.5%  [2.2%, 16.1%]
tasks where L4 output < A0: 35/49
models seen: ['claude-opus-5-5']

$ python3 harness/quality.py jobs-full/a0/full-a0 jobs-full/l3/full-l3
paired trials: 98 over 49 tasks
solved A0 90/98 (92%)  L4 89/98 (91%)
  L4 - A0 = -1.0%  95% CI [-3.0%, +1.0%]  discordant A0-only 1 / L4-only 0  McNemar p=1.00
test runs / trial: A0 4.2  L4 4.1
no test run at all: A0 0  L4 1  (of 98)
final message chars (median): A0 1276  L4 1050
PLACEBO A0 a1 vs a2 output 'reduction': -2.4%  95% CI [-9.3%, +5.1%]  (49 tasks)

$ python harness/judge.py ...   (98 pairs, gist judge_a0_vs_l3.txt / .jsonl)
judged 98 pairs x 2 orders = 196 verdicts
a0: clarity 4.72  any blocker 21/196  missing_location 0  missing_why 0  missing_verification 5  missing_caveat 16
l3: clarity 4.49  any blocker 28/196  missing_location 1  missing_why 0  missing_verification 7  missing_caveat 24
preferred: A0 108  L3 51  tie 37
order-inconsistent pairs (judge noise): 30/98
```

**Reproduction check (2026-11-18).** I downloaded the release asset
(sha256 above) into a clean directory and re-ran `analyze.py` and
`quality.py` from `headroom-bench@8fa90e9`:

- Both outputs were byte-identical to the committed
`analysis/analyze_a0_vs_l3.txt` and `analysis/quality_a0_vs_l3.txt`.
- The regenerated `trials_a0_vs_l3.csv` was identical to the committed
one (`cmp` clean).
- In the raw trajectories, all 100 L3 trials launch Claude Code with
`--append-system-prompt '<headroom_output_shaping>…`, and 0 of the 100
A0 trials contain `headroom_output_shaping`.
- Recounting the 98 judge verdicts gives the same tallies as above.

**Reading it.**

- **Output tokens:** L3 cuts them 11.7% (95% CI 7.3–16.1%) and cost 9.5%
(5.3–13.4%).
- **Solved tasks:** no measurable change, −1.0 pt, McNemar p = 1.00.
- **Reply quality:** the blind judge wants a follow-up on 14% of L3
final replies against 11% unsteered, mostly for missing caveats. It also
prefers the unsteered reply about 2:1.
- **Noise:** the within-arm placebo (A0 attempt 1 vs attempt 2) is −2.4%
(−9.3% to +5.1%), so the L3 effect is outside run-to-run noise.
- **Drift check:** a vanilla rerun on a later day (10 tasks,
`configs/drift_a0.yaml`) came out at 7.8% (−13.1% to +19.2%). Its CI
spans 0, and it is reported in the bench README.

L3 therefore trades a little reply completeness for the saving. That is
why it stays behind `HEADROOM_OUTPUT_SHAPER`, which is off by default.

- Not tested: these five cases.
- Codex and GPT-family models. L3 applies to them, but the saving is not
measured.
  - Chat-style, non-agentic traffic.
  - Claude Code versions other than 2.1.325.
- The SWE-bench arms put the text in with `append_system_prompt`, not
through the proxy. Part 1 shows the proxy puts the same block in the
same place.
- A conversation whose prefix cache was warm when the proxy upgraded.
One cache rewrite is expected; it was not measured.

## Runtime Rollout Safety

- Rollout-managed feature(s): `proxy_output_shaper`
(`HEADROOM_OUTPUT_SHAPER`); it stays opt-in and this PR does not enable
it.
- Minimum rollout channel: unchanged.
- Stable/default behavior changed: only for proxies with steering
already on, which steer at L3 instead of L2 when no level is pinned.
Steering stays off by default.
- Kill switch / disable path: `HEADROOM_OUTPUT_SHAPER=0`, or
`HEADROOM_VERBOSITY_LEVEL=2` to restore the old level.
- Unsafe override required: no.
- Qualification impact: the steering block grows by about 60 tokens per
request; a conversation already running at the default level rewrites
its prompt cache once on the first request after the upgrade.
- Rollback path: revert the PR; the hooks have no persisted state.

## 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
- [ ] I have made corresponding changes to the documentation: no docs
page describes the default level
- [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
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

- Companion PR: #4878 books the modelled output saving per request.
- Open product question: `headroom learn --verbosity` still recommends
at most L3.

🤖 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>
This commit is contained in:
Tejas Chopra
2026-11-21 16:36:36 -08:00
committed by GitHub
co-authored by Claude Opus 5.5 JD Davis
parent e27f0d96cc
commit a3afd43e0c
7 changed files with 194 additions and 14 deletions
+9
View File
@@ -218,6 +218,11 @@ def install_all(
Raises:
RuntimeError: when a ``fail_closed`` extension's ``install()`` raised.
"""
from headroom.proxy.output_shaper import (
restore_steering_registry,
steering_registry_snapshot,
)
enabled_set = _resolve_enabled(enabled)
discovered = list(discover())
discovered_names = [n for n, _ in discovered]
@@ -246,9 +251,13 @@ def install_all(
if not wildcard and name not in enabled_set:
continue
before = len(middleware_list) if isinstance(middleware_list, list) else 0
registry_before = steering_registry_snapshot()
try:
install(app, config)
except Exception as exc: # noqa: BLE001 — one bad extension must not brick the proxy
# A skipped extension must not keep steering text, a default
# level or savings factors it registered before raising.
restore_steering_registry(registry_before)
if _is_fail_closed(install):
# The extension is the proxy's upstream auth (or equivalent):
# running without it would serve requests it was meant to
+64 -11
View File
@@ -30,10 +30,10 @@ from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Any
from headroom.proxy import runtime_env
from headroom.proxy import output_savings, output_verbosity_policy, runtime_env
from headroom.proxy.output_steering import (
apply_openai_chat_verbosity_steering,
apply_openai_responses_verbosity_steering,
@@ -52,6 +52,9 @@ logger = logging.getLogger(__name__)
__all__ = [
"DEFAULT_VERBOSITY_LEVEL",
"register_default_verbosity_level",
"restore_steering_registry",
"steering_registry_snapshot",
"OutputShaperSettings",
"ShapeResult",
"TurnKind",
@@ -71,14 +74,62 @@ _replace_or_append_steering_block = replace_or_append_steering_block
#: Level handed to an operator who turned the shaper on and said nothing else.
#: Two, not three: L3 instructs the model to drop content ("give conclusions
#: only; omit rationale"), which reads as the model getting worse to someone who
#: did not ask for it -- the same reasoning the feature's own rollout spec gives
#: for not defaulting the shaper on at all. L2 only forbids ceremony and
#: restatement. Measured on a long explain-with-code turn (3 paired runs,
#: non-overlapping ranges): 2375 -> 1663 output tokens, -30%, with no visible
#: loss of content.
DEFAULT_VERBOSITY_LEVEL = 2
#: Three. Paired SWE-bench Verified runs (Claude Code 2.1.325, Opus 5.5, 49
#: tasks x 2 attempts against unsteered Claude Code) put L3 at -11.7% output
#: tokens (95% CI 7.3-16.1%) and -9.5% cost, solving the same tasks. A blind
#: judge playing the reviewer who must merge the change wanted a follow-up on
#: 14% of L3's final replies against 11% unsteered. L4 saved more (-21%) but
#: the judge wanted a follow-up on 20% of its replies against 3%, mostly for
#: dropped caveats, which is why it is not the default.
DEFAULT_VERBOSITY_LEVEL = 3
def register_default_verbosity_level(level: int) -> None:
"""Set the level used when ``HEADROOM_VERBOSITY_LEVEL`` is not set.
Extension seam, alongside ``register_verbosity_text``: an extension that
installs its own benchmarked text for a level can make that level the
default. An operator's explicit ``HEADROOM_VERBOSITY_LEVEL`` still wins, and
a proxy without the extension keeps core's default. Call it at startup:
the level is read per request, and moving it mid-conversation rewrites
the system-prompt tail, busting the prefix cache once. The setting is
process-wide: every app in the process steers at it.
"""
global DEFAULT_VERBOSITY_LEVEL
if isinstance(level, bool) or not isinstance(level, int) or not 0 <= level <= 4:
raise ValueError(f"default verbosity level must be an int in 0-4; got {level!r}")
DEFAULT_VERBOSITY_LEVEL = level
#: What the three extension seams have registered: the default level
#: (:func:`register_default_verbosity_level`), each level's steering text
#: (``output_verbosity_policy.register_verbosity_text``) and the modelled savings
#: factors (``output_savings.register_modelled_factors``). A new seam belongs here.
SteeringRegistry = tuple[int, dict[int, str], dict[int, tuple[float, float]]]
def steering_registry_snapshot() -> SteeringRegistry:
"""Copy of everything the steering and savings seams can change."""
return (
DEFAULT_VERBOSITY_LEVEL,
dict(output_verbosity_policy.VERBOSITY_LEVELS),
dict(output_savings.MODELLED_REDUCTION),
)
def restore_steering_registry(snapshot: SteeringRegistry) -> None:
"""Put the seams back as :func:`steering_registry_snapshot` found them.
``install_all`` uses this so an extension that raises after registering
leaves nothing behind when it is skipped.
"""
global DEFAULT_VERBOSITY_LEVEL
level, texts, factors = snapshot
DEFAULT_VERBOSITY_LEVEL = level
output_verbosity_policy.VERBOSITY_LEVELS.clear()
output_verbosity_policy.VERBOSITY_LEVELS.update(texts)
output_savings.MODELLED_REDUCTION.clear()
output_savings.MODELLED_REDUCTION.update(factors)
@dataclass(frozen=True)
@@ -86,7 +137,9 @@ class OutputShaperSettings:
"""Output-shaping settings with rollout enablement injected by the proxy."""
enabled: bool = False
verbosity_level: int = DEFAULT_VERBOSITY_LEVEL
# Read at construction, not import, so a level registered by an extension
# applies to direct construction exactly as it does to from_env().
verbosity_level: int = field(default_factory=lambda: DEFAULT_VERBOSITY_LEVEL)
# False in ``mode="cache"``. Steering is the one lever that writes into the
# provider prefix-cache key (it appends to the system-prompt tail, and on a
# body with no system field it creates one). See
+30
View File
@@ -89,6 +89,36 @@ VERBOSITY_LEVELS = {
}
def register_verbosity_text(level: int, text: str) -> None:
"""Replace the steering text for one existing level.
Extension seam, the text-side twin of
:func:`headroom.proxy.output_savings.register_modelled_factors`: an
extension that has benchmarked its own wording installs it at startup,
together with the factors measured for that wording. Call it before the
proxy serves traffic. Changing a level's text mid-conversation rewrites the
system-prompt tail and so busts the provider prefix cache once. The text is
process-wide: every app in the process steers with it.
Only levels core already defines can be replaced, so the 0-4 range every
caller clamps to stays true. The text must be non-empty and must not
contain the sentinel or suffix, which would break the idempotent
replace-in-place in :func:`replace_or_append_steering_block`.
"""
if level not in VERBOSITY_LEVELS:
raise ValueError(
f"no verbosity level {level} to replace; levels are {sorted(VERBOSITY_LEVELS)}"
)
if not text.strip():
raise ValueError(f"steering text for level {level} must not be empty")
if STEERING_SENTINEL in text or STEERING_SUFFIX in text:
raise ValueError(
f"steering text for level {level} must not contain "
f"{STEERING_SENTINEL} or {STEERING_SUFFIX}; steering_text() adds them"
)
VERBOSITY_LEVELS[level] = text
def steering_text(level: int) -> str | None:
"""The full steering block for a verbosity level, or ``None`` for level 0."""
text = VERBOSITY_LEVELS.get(level)
+3 -1
View File
@@ -963,7 +963,9 @@ def test_verbosity_apply_reads_an_unparseable_pin_as_the_default_level(
proxy = _FakeProxy({"mode": "cache", "runtime_env": {"HEADROOM_VERBOSITY_LEVEL": "high"}})
output = _apply_learned_level(monkeypatch, runner, tmp_path, proxy, level=3)
# Any learned level other than the default, or there is nothing to report.
learned = 4 if DEFAULT_VERBOSITY_LEVEL != 4 else 3
output = _apply_learned_level(monkeypatch, runner, tmp_path, proxy, level=learned)
assert proxy.posted == [{"HEADROOM_OUTPUT_SHAPER": "1"}]
assert f"it stays at level {DEFAULT_VERBOSITY_LEVEL}: HEADROOM_VERBOSITY_LEVEL" in output
+40 -2
View File
@@ -9,6 +9,8 @@ from __future__ import annotations
import copy
from typing import Any
import pytest
from headroom.proxy.output_shaper import (
DEFAULT_VERBOSITY_LEVEL,
OutputShaperSettings,
@@ -421,7 +423,7 @@ class TestCacheModeSuppressesSteeringOnly:
settings = OutputShaperSettings(enabled=True, verbosity_level=4, steering_enabled=False)
assert resolve_verbosity_level(settings) == (4, "env_pinned")
def test_shaper_alone_steers_at_l2_in_cache_mode(self, monkeypatch):
def test_shaper_alone_steers_at_l3_in_cache_mode(self, monkeypatch):
"""``HEADROOM_OUTPUT_SHAPER=1`` must be sufficient on its own.
The shaper is opt-in, so an enabled shaper is already an explicit
@@ -439,7 +441,7 @@ class TestCacheModeSuppressesSteeringOnly:
settings = OutputShaperSettings.from_env(enabled=True, steering_enabled=False)
assert settings.enabled is True
assert resolve_verbosity_level(settings) == (DEFAULT_VERBOSITY_LEVEL, "cache_mode_default")
assert DEFAULT_VERBOSITY_LEVEL == 2
assert DEFAULT_VERBOSITY_LEVEL == 3
def test_cache_mode_ignores_a_learned_level(self, tmp_path, monkeypatch):
"""``verbosity.json`` appears the moment someone runs ``learn``, so it
@@ -552,3 +554,39 @@ class TestCacheModeSuppressesSteeringOnly:
result = shape_request(body, settings, level_override=0)
assert "system" not in body, "cache mode must not create a system block"
assert result is not None
def test_registered_default_level_applies_only_when_no_level_is_pinned(monkeypatch) -> None:
from headroom.proxy import output_shaper
monkeypatch.setattr(
output_shaper, "DEFAULT_VERBOSITY_LEVEL", output_shaper.DEFAULT_VERBOSITY_LEVEL
)
monkeypatch.delenv("HEADROOM_VERBOSITY_LEVEL", raising=False)
output_shaper.register_default_verbosity_level(4)
assert output_shaper.OutputShaperSettings.from_env(enabled=True).verbosity_level == 4
monkeypatch.setenv("HEADROOM_VERBOSITY_LEVEL", "2")
assert output_shaper.OutputShaperSettings.from_env(enabled=True).verbosity_level == 2
def test_direct_settings_use_the_registered_default_level(monkeypatch) -> None:
from headroom.proxy import output_shaper
monkeypatch.setattr(
output_shaper, "DEFAULT_VERBOSITY_LEVEL", output_shaper.DEFAULT_VERBOSITY_LEVEL
)
output_shaper.register_default_verbosity_level(4)
assert output_shaper.OutputShaperSettings(enabled=True).verbosity_level == 4
@pytest.mark.parametrize("bad", [5, -1, True, "4"])
def test_register_default_level_rejects_out_of_range(monkeypatch, bad) -> None:
from headroom.proxy import output_shaper
monkeypatch.setattr(
output_shaper, "DEFAULT_VERBOSITY_LEVEL", output_shaper.DEFAULT_VERBOSITY_LEVEL
)
with pytest.raises(ValueError):
output_shaper.register_default_verbosity_level(bad)
assert output_shaper.DEFAULT_VERBOSITY_LEVEL == 3
+27
View File
@@ -2,9 +2,13 @@
from __future__ import annotations
import pytest
from headroom.proxy import output_verbosity_policy
from headroom.proxy.output_verbosity_policy import (
STEERING_SENTINEL,
STEERING_SUFFIX,
register_verbosity_text,
replace_or_append_steering_block,
steering_text,
)
@@ -69,3 +73,26 @@ def test_replace_or_append_is_idempotent_when_block_matches() -> None:
updated, changed = replace_or_append_steering_block(f"System.\n\n{block}", block)
assert changed is False
assert updated == f"System.\n\n{block}"
def test_registered_text_replaces_a_level_wrapped_as_usual(monkeypatch) -> None:
monkeypatch.setattr(
output_verbosity_policy, "VERBOSITY_LEVELS", dict(output_verbosity_policy.VERBOSITY_LEVELS)
)
register_verbosity_text(4, "Extension wording.")
assert steering_text(4) == f"{STEERING_SENTINEL}\nExtension wording.\n{STEERING_SUFFIX}"
assert "Never restate code" in (steering_text(3) or "")
@pytest.mark.parametrize(
("level", "text"),
[(5, "x"), (0, "x"), (4, " "), (4, f"a {STEERING_SENTINEL} b"), (4, f"a {STEERING_SUFFIX}")],
)
def test_register_rejects_unknown_levels_and_unsafe_text(monkeypatch, level, text) -> None:
monkeypatch.setattr(
output_verbosity_policy, "VERBOSITY_LEVELS", dict(output_verbosity_policy.VERBOSITY_LEVELS)
)
before = dict(output_verbosity_policy.VERBOSITY_LEVELS)
with pytest.raises(ValueError):
register_verbosity_text(level, text)
assert output_verbosity_policy.VERBOSITY_LEVELS == before
+21
View File
@@ -134,3 +134,24 @@ def test_discover_warns_when_entry_point_enumeration_fails(monkeypatch) -> None:
def test_discover_is_quiet_when_nothing_is_installed(monkeypatch) -> None:
assert _discover_warnings(monkeypatch, lambda **_: []) == []
def test_a_skipped_extension_leaves_no_steering_registrations(monkeypatch) -> None:
from headroom.proxy import output_shaper
from headroom.proxy.output_savings import register_modelled_factors
from headroom.proxy.output_verbosity_policy import register_verbosity_text
core = output_shaper.steering_registry_snapshot()
def install(app: Any, config: Any) -> None:
output_shaper.register_default_verbosity_level(4)
register_verbosity_text(4, "extension text")
register_modelled_factors(4, 0.2, 0.5)
raise RuntimeError("licence check failed")
monkeypatch.setattr(extensions, "discover", lambda: iter([("steer", install)]))
try:
assert extensions.install_all(object(), object(), enabled=["steer"]) == []
assert output_shaper.steering_registry_snapshot() == core
finally:
output_shaper.restore_steering_registry(core)