Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(shaper): measure output-token steering, and stop claiming savings we did not measure (#3377)
Tejas Chopra1390d897155e
diff --git a/headroom/agent_savings.py b/headroom/agent_savings.pyindex a201dbb44..b08f52cbe 100644--- a/headroom/agent_savings.py+++ b/headroom/agent_savings.py@@ -55,7 +55,6 @@ class AgentSavingsProfile:lossless_then_lossy: bool = Falseprotect_reads: bool = Falsecode_aware: bool = True- effort_router: bool = Truelossless: bool = Falsemin_chars_for_block: int | None = None@@ -87,7 +86,6 @@ class AgentSavingsProfile:"HEADROOM_LOSSLESS_THEN_LOSSY": "1" if self.lossless_then_lossy else "0","HEADROOM_PROTECT_READS": "1" if self.protect_reads else "0","HEADROOM_CODE_AWARE_ENABLED": "1" if self.code_aware else "0",- "HEADROOM_EFFORT_ROUTER": "1" if self.effort_router else "0","HEADROOM_LOSSLESS": "1" if self.lossless else "0",}# Only pin a keep-ratio when the profile sets one; workload personas@@ -182,7 +180,6 @@ _PROFILES: dict[str, AgentSavingsProfile] = {lossless_then_lossy=True,protect_reads=True,code_aware=True,- effort_router=False,lossless=False,min_chars_for_block=25,),@@ -327,7 +324,7 @@ def proxy_pipeline_kwargs(config: object) -> dict[str, object]:## NOTE: this does not make the profile fully config-deliverable. The# profile's ``cross_turn_dedup`` / ``tool_search`` / ``lossless_then_lossy``- # / ``protect_reads`` / ``code_aware`` / ``effort_router`` / ``lossless``+ # / ``protect_reads`` / ``code_aware`` / ``lossless``# fields are still env-only, but by a different mechanism: their consumers# read ``os.environ`` directly (ContentRouter.__init__ for HEADROOM_DEDUPE,# the Anthropic handler for HEADROOM_TOOL_SEARCH) and never pass throughdiff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.htmlindex c6d16cf82..6e5353cd9 100644--- a/headroom/dashboard/templates/dashboard.html+++ b/headroom/dashboard/templates/dashboard.html@@ -277,22 +277,38 @@<span class="text-sm text-accent" x-text="(stats.tokens?.output_reduction_percent || 0).toFixed(1) + '%'"></span></div><div class="mt-1 text-xs text-gray-500 leading-relaxed">- <!-- "measured" = A/B holdout (unbiased); "estimated" = vs learned baseline -->+ <!-- measured = A/B holdout (unbiased) · estimated = vs learned+ baseline · modelled = benchmark factor, not this traffic --><span class="uppercase tracking-wide"- :class="stats.tokens?.output_reduction?.method === 'measured' ? 'text-emerald-400' : 'text-gray-400'"+ :class="{+ 'text-emerald-400': stats.tokens?.output_reduction?.method === 'measured',+ 'text-gray-400': stats.tokens?.output_reduction?.method === 'estimated',+ 'text-amber-500': stats.tokens?.output_reduction?.method === 'modelled'+ }"x-text="stats.tokens?.output_reduction?.method || ''"></span>- <span x-text="'· 95% CI ' + (stats.tokens?.output_reduction?.ci_low_percent || 0).toFixed(1) + '–' + (stats.tokens?.output_reduction?.ci_high_percent || 0).toFixed(1) + '%'"></span>+ <!-- A modelled band is the spread between the two benchmarked+ models, not a sampling CI. Calling it one would be a lie. -->+ <span x-text="'· ' + (stats.tokens?.output_reduction?.band_is_ci === false ? 'range ' : '95% CI ') + (stats.tokens?.output_reduction?.ci_low_percent || 0).toFixed(1) + '–' + (stats.tokens?.output_reduction?.ci_high_percent || 0).toFixed(1) + '%'"></span></div><div class="mt-1 text-xs text-gray-600 leading-relaxed"x-text="formatNumber(stats.tokens?.output_reduction?.requests || 0) + ' shaped responses · counterfactual'"></div>+ <template x-if="stats.tokens?.output_reduction?.method === 'modelled'">+ <div class="mt-1 text-xs text-amber-600/80 leading-relaxed">+ Approximate: a benchmark factor, not your traffic. Set+ <code class="text-gray-400">HEADROOM_OUTPUT_HOLDOUT=0.05</code>+ to measure it for real.+ </div>+ </template></div></template><template x-if="!stats.tokens?.output_reduction?.available"><div class="mt-1 text-xs text-gray-500 leading-relaxed"><span class="text-2xl font-light tabular-nums text-gray-600">—</span>- <div class="mt-1">Enable the beta output shaper (HEADROOM_ROLLOUT_CHANNEL=beta HEADROOM_OUTPUT_SHAPER=1) and run- <code class="text-gray-400">headroom learn --verbosity --apply</code> to start measuring.</div>+ <div class="mt-1">Output shaping is off. Set+ <code class="text-gray-400">HEADROOM_OUTPUT_SHAPER=1</code>+ to trim response verbosity — measured at 34–74% fewer output+ tokens at the default level.</div></div></template></div>diff --git a/headroom/perf/analyzer.py b/headroom/perf/analyzer.pyindex f210759c0..2e978c7c3 100644--- a/headroom/perf/analyzer.py+++ b/headroom/perf/analyzer.py@@ -498,8 +498,7 @@ def parse_log_files(last_n_hours: float = 168.0) -> PerfReport:return report--def _as_number(value: object, cast: type) -> "int | float":+def _as_number(value: object, cast: type) -> int | float:"""Coerce a self-reported savings figure, or 0 if it is not a number.`savings=` is base64 JSON written by whatever plugin recorded it, and@@ -512,14 +511,14 @@ def _as_number(value: object, cast: type) -> "int | float":try:out = cast(value) # type: ignore[call-arg]except (TypeError, ValueError, OverflowError):- return cast(0) # type: ignore[call-arg]+ return cast(0) # type: ignore[call-arg,no-any-return]# Finiteness only, matching what the WRITE side enforces (see MAX_STAGE_MS in# savings_attribution): inf/nan survive a float() cast and render as "inf",# which is not a measurement. A merely large finite value is left alone --# capping it here would invent a limit the recording side does not have.if isinstance(out, float) and not math.isfinite(out):- return cast(0) # type: ignore[call-arg]- return out+ return cast(0) # type: ignore[call-arg,no-any-return]+ return out # type: ignore[no-any-return]def format_report(report: PerfReport) -> str:@@ -806,9 +805,7 @@ def format_report(report: PerfReport) -> str:for item in getattr(record, "savings_breakdown", ()) or ():source = str(item.get("source") or "other")realized = bool(item.get("realized", True))- row = by_source.setdefault(- (source, realized), {"events": 0, "tokens": 0, "usd": 0.0}- )+ row = by_source.setdefault((source, realized), {"events": 0, "tokens": 0, "usd": 0.0})row["events"] += 1row["tokens"] += max(0, _as_number(item.get("tokens"), int))row["usd"] += _as_number(item.get("usd"), float)diff --git a/headroom/pipeline.py b/headroom/pipeline.pyindex 868943cab..491dd5ef9 100644--- a/headroom/pipeline.py+++ b/headroom/pipeline.py@@ -4,6 +4,8 @@ from __future__ import annotationsimport importlib.metadataimport logging+import os+from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Protocol@@ -11,6 +13,7 @@ from typing import Any, Protocollog = logging.getLogger(__name__)ENTRY_POINT_GROUP = "headroom.pipeline_extension"+ENV_VAR = "HEADROOM_PIPELINE_EXTENSIONS"class PipelineStage(str, Enum):@@ -27,6 +30,7 @@ class PipelineStage(str, Enum):PRE_SEND = "pre_send"POST_SEND = "post_send"RESPONSE_RECEIVED = "response_received"+ OUTCOME_OBSERVED = "outcome_observed"CANONICAL_PIPELINE_STAGES: tuple[PipelineStage, ...] = (@@ -41,15 +45,65 @@ CANONICAL_PIPELINE_STAGES: tuple[PipelineStage, ...] = (PipelineStage.PRE_SEND,PipelineStage.POST_SEND,PipelineStage.RESPONSE_RECEIVED,+ PipelineStage.OUTCOME_OBSERVED,)+@dataclass(frozen=True)+class OutcomeSnapshot:+ """What actually happened on one request. Read-only by construction.++ Emitted at :attr:`PipelineStage.OUTCOME_OBSERVED` so an extension can learn+ from a response — a token ceiling that was hit, an effort setting that did+ or did not pay off — without being able to rewrite the measurement it is+ learning from. Extensions declare what they did; the core records what+ happened; attribution is the core's arithmetic over both.++ ``thinking_tokens`` is ``None`` when the provider reported no split and none+ could be inferred. That is NOT zero: Anthropic reports no thinking count at+ all, so treating unknown as zero would credit visible-text levers with+ reductions that reasoning-effort levers produced.+ """++ request_id: str = ""+ provider: str = ""+ model: str = ""+ output_tokens: int = 0+ thinking_tokens: int | None = None+ thinking_inferred: bool = False+ stop_reason: str | None = None+ input_tokens: int = 0+ cache_read_tokens: int = 0+ cache_write_tokens: int = 0+ turn_index: int = 0+ transforms_applied: tuple[str, ...] = ()++ @property+ def truncated(self) -> bool:+ """Whether a token ceiling cut the response off.++ The one unambiguous, provider-supplied feedback signal available to an+ adaptive lever — which is why a ceiling can run a closed control loop+ where verbosity steering (whose signals need transcript inference)+ cannot.+ """+ return self.stop_reason in ("max_tokens", "length")++ @property+ def visible_output_tokens(self) -> int | None:+ """Output tokens excluding thinking, or ``None`` when unknown."""+ if self.thinking_tokens is None:+ return None+ return max(0, self.output_tokens - self.thinking_tokens)++@dataclassclass PipelineEvent:"""Event emitted at a canonical pipeline stage.- Extensions may mutate ``messages``, ``tools``, ``headers``, or ``metadata`` in- place, or return a replacement ``PipelineEvent`` from ``on_pipeline_event``.+ Extensions may mutate ``messages``, ``tools``, ``headers`` or ``metadata``+ in place, or return a replacement ``PipelineEvent`` from+ ``on_pipeline_event``."""stage: PipelineStage@@ -61,6 +115,7 @@ class PipelineEvent:tools: list[dict[str, Any]] | None = Noneheaders: dict[str, str] | None = Noneresponse: Any = None+ outcome: OutcomeSnapshot | None = Nonemetadata: dict[str, Any] = field(default_factory=dict)@@ -71,16 +126,70 @@ class PipelineExtension(Protocol):"""Handle a canonical pipeline event."""-def discover_pipeline_extensions() -> list[PipelineExtension]:- """Load registered pipeline extensions from Python entry points."""+def _resolve_enabled(enabled: Iterable[str] | None) -> set[str]:+ """Resolve the enabled entry-point names.++ Precedence: the explicit argument, else ``HEADROOM_PIPELINE_EXTENSIONS``,+ else nothing. Mirrors :mod:`headroom.proxy.extensions` so operators learn+ one rule for both seams.+ """+ raw: Iterable[str]+ if enabled is not None:+ raw = enabled+ else:+ raw = (os.environ.get(ENV_VAR) or "").split(",")+ return {n.strip() for n in raw if n and n.strip()}+++def discover_pipeline_extensions(+ enabled: Iterable[str] | None = None,+) -> list[PipelineExtension]:+ """Load explicitly-enabled pipeline extensions from Python entry points.++ **Opt-in.** Discovery enumerates every registered entry point, but only+ those the operator named are loaded. Merely installing a package — as a+ transitive dependency, say — must not silently start rewriting requests.++ An unaudited package in the same environment could otherwise rewrite the+ messages of every request on live traffic. The proxy-extension seam has+ always worked this way; this brings the pipeline seam in line.++ Extensions passed directly to :class:`PipelineExtensionManager` are+ unaffected — constructing one and handing it over is already explicit.++ Enable with ``HEADROOM_PIPELINE_EXTENSIONS=name1,name2``; the literal ``*``+ enables everything discovered (only where every package is trusted).+ """discovered: list[PipelineExtension] = []try:- entries = importlib.metadata.entry_points(group=ENTRY_POINT_GROUP)+ entries = list(importlib.metadata.entry_points(group=ENTRY_POINT_GROUP))except Exception as exc: # noqa: BLE001 - importlib metadata varies by runtimelog.debug("pipeline extensions: entry-point enumeration failed: %s", exc)return discovered+ enabled_set = _resolve_enabled(enabled)+ if not enabled_set:+ if entries:+ log.info(+ "pipeline extensions discovered but disabled (opt-in): %s. "+ "Enable with %s=<name1,name2>.",+ ",".join(sorted(e.name for e in entries)),+ ENV_VAR,+ )+ return discovered++ wildcard = "*" in enabled_set+ if not wildcard:+ missing = enabled_set - {e.name for e in entries}+ if missing:+ log.warning(+ "pipeline extensions requested but not found: %s (available: %s)",+ ",".join(sorted(missing)),+ ",".join(sorted(e.name for e in entries)) or "<none>",+ )+ entries = [e for e in entries if e.name in enabled_set]+for entry in entries:try:extension = entry.load()@@ -141,6 +250,7 @@ class PipelineExtensionManager:tools: list[dict[str, Any]] | None = None,headers: dict[str, str] | None = None,response: Any = None,+ outcome: OutcomeSnapshot | None = None,metadata: dict[str, Any] | None = None,) -> PipelineEvent:"""Emit a canonical lifecycle event and return the final event state."""@@ -155,6 +265,7 @@ class PipelineExtensionManager:tools=tools,headers=headers,response=response,+ outcome=outcome,metadata=metadata or {},)diff --git a/headroom/proxy/cost.py b/headroom/proxy/cost.pyindex 812854a71..fc5d41545 100644--- a/headroom/proxy/cost.py+++ b/headroom/proxy/cost.py@@ -703,8 +703,9 @@ def build_session_summary(# artifact, not a measurement, so report no percentage rather than one that# is wrong by three orders of magnitude._baseline_is_meaningful = cost_without > max(0.01, 0.05 * cost_with)- savings_pct_cost = (round(total_saved_usd / cost_without * 100, 1)- if _baseline_is_meaningful else 0.0)+ savings_pct_cost = (+ round(total_saved_usd / cost_without * 100, 1) if _baseline_is_meaningful else 0.0+ )# Primary models usedmodels = dict(metrics.requests_by_model)diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 652ce47fe..6fdeb3ed8 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -12,7 +12,9 @@ import loggingimport osimport timeimport uuid+from collections.abc import Callablefrom datetime import datetime+from functools import lru_cachefrom typing import TYPE_CHECKING, Anyfrom urllib.parse import urlsplit@@ -54,10 +56,58 @@ from headroom.proxy.memory_query import MemoryQueryfrom headroom.proxy.model_router import estimate_input_tokensfrom headroom.proxy.nonstream_sse_policy import should_recover_sse_replyfrom headroom.proxy.outcome import RequestOutcome+from headroom.proxy.output_shaper import shaper_enabled_for, steering_allowed_for+from headroom.proxy.thinking_tokens import ThinkingTokens, extract_thinking_tokenslogger = logging.getLogger("headroom.proxy")+@lru_cache(maxsize=1)+def _thinking_estimator() -> Callable[[str], int] | None:+ """A process-wide local token counter for thinking-block estimation.++ Cached because ``AnthropicTokenCounter.__init__`` loads a tiktoken encoding;+ building one per request would put a vocab load in the response path.++ ``client=None`` is deliberate and load-bearing: with a client the counter+ calls Anthropic's /v1/messages/count_tokens endpoint, which would turn a+ bookkeeping field into a network round trip on every response. The local+ tiktoken approximation is the right trade here — the result is reported as+ ``inferred`` precisely because it is an approximation. ``warn=False``+ suppresses the "no client" UserWarning, which is advice for SDK callers and+ noise for an intentional internal estimate.++ Returns ``None`` when no counter can be built, so the caller reports+ "unknown" rather than a fabricated zero.+ """+ try:+ from headroom.providers.anthropic import AnthropicTokenCounter++ return AnthropicTokenCounter(+ "claude-3-5-sonnet-20241022", client=None, warn=False+ ).count_text+ except Exception: # noqa: BLE001 - estimation is optional, never fatal+ logger.debug("thinking-token estimator unavailable", exc_info=True)+ return None+++def _thinking_tokens_for(payload: object) -> ThinkingTokens:+ """Split thinking from visible output for one Anthropic response.++ Anthropic reports no thinking count in ``usage``, so the count is derived+ from the response's own thinking blocks and marked inferred. Without the+ split, reasoning-effort routing and verbosity steering move the same+ counter and neither can be attributed.++ Never raises: token accounting is bookkeeping, and a failure here must+ degrade to "unknown" rather than cost the caller their response.+ """+ try:+ return extract_thinking_tokens(payload, estimator=_thinking_estimator())+ except Exception: # noqa: BLE001 - accounting must never break a response+ return ThinkingTokens()++def _is_googleapis_endpoint(value: object) -> bool:"""Return whether *value* targets Google APIs by parsed hostname.@@ -3136,11 +3186,8 @@ class AnthropicHandlerMixin:)_shaper_settings = OutputShaperSettings.from_env(- enabled=(- self.config.rollout.is_enabled("proxy_output_shaper")- if getattr(self.config, "rollout", None) is not None- else None- )+ enabled=(shaper_enabled_for(getattr(self, "config", None))),+ steering_enabled=steering_allowed_for(getattr(self, "config", None)),)if _shaper_settings.enabled:# Conversation-stable holdout assignment: a whole@@ -3180,6 +3227,11 @@ class AnthropicHandlerMixin:f"{shape_result.labels}")+ # Params stage: the last chance to change what the model WRITES.+ # Emitted here, after every message mutation and after the built-in+ # shaper, so an extension sees the request exactly as it will go out+ # and a turn classifier reading ``messages`` sees the final list.+ ## Unit 2: mark end of pre-upstream phase. Everything after this# point is upstream I/O or post-response bookkeeping.stage_timer.record(@@ -3353,6 +3405,8 @@ class AnthropicHandlerMixin:# the arithmetic below (and ``RequestOutcome``) never sees# ``None`` — matching the direct-Anthropic path.output_tokens = int(usage.get("output_tokens", 0) or 0)+ _thinking = _thinking_tokens_for(backend_response.body)+ _stop_reason = (backend_response.body or {}).get("stop_reason")_backend_name = request_backend.name if request_backend else "anthropic"# Eligible-only denominator for the active@@ -3462,6 +3516,9 @@ class AnthropicHandlerMixin:cache_write_5m_tokens=cw_5m_tokens,cache_write_1h_tokens=cw_1h_tokens,uncached_input_tokens=uncached_input_tokens,+ thinking_tokens=_thinking.tokens,+ thinking_inferred=_thinking.inferred,+ stop_reason=_stop_reason,total_latency_ms=total_latency,overhead_ms=optimization_latency,pipeline_timing=pipeline_timing,@@ -4298,9 +4355,24 @@ class AnthropicHandlerMixin:cw_5m_tokens = 0cw_1h_tokens = 0uncached_input_tokens = 0+ # Bound before the block below so the RequestOutcome emit can never+ # hit an unbound name on an early-exit or except path — an+ # accounting field must not be able to 500 a live request.+ _thinking = ThinkingTokens()+ _stop_reason = Noneif resp_json:usage = resp_json.get("usage", {})output_tokens = int(usage.get("output_tokens", 0) or 0)+ _thinking = _thinking_tokens_for(resp_json)+ _stop_reason = (resp_json or {}).get("stop_reason")+ # The split is measured against the final response+ # only. ``output_tokens`` below also absorbs usage+ # from hook-triggered calls whose bodies are not+ # ``resp_json``, so on those turns any thinking they+ # did lands in the visible bucket. Bounded and+ # documented rather than threaded through the hook+ # accumulator: it affects only hook paths, and the+ # Anthropic count is flagged inferred regardless.output_tokens += _hook_usage.output_tokenscr_tokens = int(usage.get("cache_read_input_tokens", 0) or 0)cr_tokens += _hook_usage.cache_read_tokens@@ -4477,6 +4549,9 @@ class AnthropicHandlerMixin:cache_write_5m_tokens=cw_5m_tokens,cache_write_1h_tokens=cw_1h_tokens,uncached_input_tokens=uncached_input_tokens,+ thinking_tokens=_thinking.tokens,+ thinking_inferred=_thinking.inferred,+ stop_reason=_stop_reason,total_latency_ms=total_latency,overhead_ms=optimization_latency,pipeline_timing=pipeline_timing,diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex af42e36ee..740f3e47c 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -83,6 +83,7 @@ from headroom.proxy.cost import header_safe_transformsfrom headroom.proxy.handlers._debug_dump import _debug_dump_mode, _redact_debug_valuefrom headroom.proxy.image_isolation import run_image_compression_isolatedfrom headroom.proxy.outcome import RequestOutcome+from headroom.proxy.output_shaper import shaper_enabled_for, steering_allowed_forfrom headroom.proxy.passthrough import (custom_base_passthrough_telemetry as _custom_base_passthrough_telemetry,)@@ -91,6 +92,7 @@ from headroom.proxy.project_context import (get_current_project,set_current_project,)+from headroom.proxy.thinking_tokens import ThinkingTokens, extract_from_usagefrom headroom.proxy.token_counting import gemini_output_tokenslogger = logging.getLogger("headroom.proxy")@@ -3169,13 +3171,7 @@ class OpenAIHandlerMixin:payload,model=model,request_id=request_id,- output_shaper_enabled=(- getattr(getattr(self, "config", None), "rollout", None).is_enabled(- "proxy_output_shaper"- )- if getattr(getattr(self, "config", None), "rollout", None) is not None- else None- ),+ output_shaper_enabled=(shaper_enabled_for(getattr(self, "config", None))),)compression_kwargs: dict[str, Any] = {"model": model,@@ -4481,11 +4477,8 @@ class OpenAIHandlerMixin:)_shaper_settings = OutputShaperSettings.from_env(- enabled=(- self.config.rollout.is_enabled("proxy_output_shaper")- if getattr(self.config, "rollout", None) is not None- else None- )+ enabled=(shaper_enabled_for(getattr(self, "config", None))),+ steering_enabled=steering_allowed_for(getattr(self, "config", None)),)if _shaper_settings.enabled:# Conversation-stable holdout: a whole conversation is treatment@@ -4734,6 +4727,7 @@ class OpenAIHandlerMixin:# matching the streaming path and the guarded cache keys below# (same class as the gemini fix in #2347).output_tokens = _usage_int(usage.get("completion_tokens"))+ _thinking = extract_from_usage(usage)total_input_tokens = _usage_int(usage.get("prompt_tokens")) or optimized_tokens# Cache stats: prefer the Anthropic/Bedrock top-level@@ -4808,6 +4802,8 @@ class OpenAIHandlerMixin:optimized_tokens=optimized_tokens,provider_input_tokens=total_input_tokens,output_tokens=output_tokens,+ thinking_tokens=_thinking.tokens,+ thinking_inferred=_thinking.inferred,tokens_saved=tokens_saved,attempted_input_tokens=optimized_tokens + tokens_saved,cache_read_tokens=cache_read_tokens,@@ -5094,6 +5090,10 @@ class OpenAIHandlerMixin:except Exception as dump_err:logger.error(f"[{request_id}] Failed to write debug dump: {dump_err}")+ # Bound here so the RequestOutcome emit below can never hit an+ # unbound name on an except or early-exit path — an accounting+ # field must not be able to 500 a live request.+ _thinking = ThinkingTokens()total_latency = (time.time() - start_time) * 1000total_input_tokens = optimized_tokens # fallback@@ -5110,6 +5110,7 @@ class OpenAIHandlerMixin:# request (same class as the gemini fix in #2347).total_input_tokens = _usage_int(usage.get("prompt_tokens")) or optimized_tokensoutput_tokens = _usage_int(usage.get("completion_tokens"))+ _thinking = extract_from_usage(usage)# OpenAI returns cached_tokens in prompt_tokens_details# These are charged at 50% of the input priceprompt_details = usage.get("prompt_tokens_details") or {}@@ -5271,6 +5272,8 @@ class OpenAIHandlerMixin:optimized_tokens=optimized_tokens,provider_input_tokens=total_input_tokens,output_tokens=output_tokens,+ thinking_tokens=_thinking.tokens,+ thinking_inferred=_thinking.inferred,tokens_saved=tokens_saved,attempted_input_tokens=optimized_tokens + tokens_saved,cache_read_tokens=cache_read_tokens,@@ -5927,11 +5930,7 @@ class OpenAIHandlerMixin:if _http_conversation_keyelse None),- output_shaper_enabled=(- self.config.rollout.is_enabled("proxy_output_shaper")- if getattr(self.config, "rollout", None) is not None- else None- ),+ output_shaper_enabled=(shaper_enabled_for(getattr(self, "config", None))),)_append_unique_transforms(transforms_applied, _shape_result.labels)if _shape_result.changed:@@ -6214,6 +6213,10 @@ class OpenAIHandlerMixin:headers={**adapted_headers, "content-type": "application/json"},)+ # Bound here so the RequestOutcome emit below can never hit an+ # unbound name on an except or early-exit path — an accounting+ # field must not be able to 500 a live request.+ _thinking = ThinkingTokens()total_input_tokens = original_tokens # fallbackoutput_tokens = 0cache_read_tokens = 0@@ -6233,6 +6236,7 @@ class OpenAIHandlerMixin:original_tokens,)output_tokens = _usage_int(usage.get("output_tokens"))+ _thinking = extract_from_usage(usage)details = usage.get("input_tokens_details")if isinstance(details, dict):cache_read_tokens = _usage_int(details.get("cached_tokens"))@@ -6480,6 +6484,8 @@ class OpenAIHandlerMixin:optimized_tokens=effective_optimized_tokens,provider_input_tokens=total_input_tokens,output_tokens=output_tokens,+ thinking_tokens=_thinking.tokens,+ thinking_inferred=_thinking.inferred,tokens_saved=tokens_saved,attempted_input_tokens=attempted_input_tokens,cache_read_tokens=cache_read_tokens,@@ -7804,11 +7810,7 @@ class OpenAIHandlerMixin:self.openai_provider,),conversation_key=f"ws:{session_id}",- output_shaper_enabled=(- self.config.rollout.is_enabled("proxy_output_shaper")- if getattr(self.config, "rollout", None) is not None- else None- ),+ output_shaper_enabled=(shaper_enabled_for(getattr(self, "config", None))),)_append_unique_transforms(transforms_applied, _shape_labels)if _shape_modified:@@ -8259,9 +8261,7 @@ class OpenAIHandlerMixin:),conversation_key=f"ws:{session_id}",output_shaper_enabled=(- self.config.rollout.is_enabled("proxy_output_shaper")- if getattr(self.config, "rollout", None) is not None- else None+ shaper_enabled_for(getattr(self, "config", None))),)_append_unique_transforms(diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex 6d0f31606..334ff389c 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -28,10 +28,28 @@ import httpxfrom headroom.copilot_auth import apply_copilot_api_authfrom headroom.proxy.stream_output_tokens import estimate_output_tokens+from headroom.proxy.thinking_tokens import ThinkingTokens, extract_thinking_tokenslogger = logging.getLogger("headroom.proxy")+def _thinking_for_stream(payload: object) -> ThinkingTokens:+ """Thinking-token split for a reassembled streaming response.++ Shares the estimator with the non-streaming path so a streamed and an+ unstreamed response of the same shape produce the same number — otherwise+ the stratum would mix two different rulers.++ Never raises: accounting must not cost a caller their response.+ """+ try:+ from headroom.proxy.handlers.anthropic import _thinking_estimator++ return extract_thinking_tokens(payload, estimator=_thinking_estimator())+ except Exception: # noqa: BLE001 - accounting must never break a response+ return ThinkingTokens()++def _parse_completion_tokens_from_sse_chunk(chunk_bytes: bytes) -> int | None:"""Extract `usage.completion_tokens` from a single SSE chunk if present.@@ -1055,7 +1073,22 @@ class StreamingMixin:# live-zone tracking is a follow-up. Without this fallback the# dashboard headline collapses to 0% even when compression is# happening (issue #455).+ # Thinking split and stop_reason for the streaming path. Streaming is+ # where the agentic traffic is, so without this the split — and the one+ # feedback signal an adaptive ceiling can learn from — would exist only+ # for non-streaming requests, which is close to nowhere in practice.+ #+ # ``parsed_response`` is the reassembled SSE body: it carries the content+ # blocks (thinking among them) and stop_reason, which the raw usage chunk+ # does not.+ _stream_thinking = _thinking_for_stream(parsed_response)+ _stream_stop_reason = (+ parsed_response.get("stop_reason") if isinstance(parsed_response, dict) else None+ )outcome = RequestOutcome.from_stream(+ thinking_tokens=_stream_thinking.tokens,+ thinking_inferred=_stream_thinking.inferred,+ stop_reason=_stream_stop_reason,body=body,provider=outcome_provider,model=model,diff --git a/headroom/proxy/outcome.py b/headroom/proxy/outcome.pyindex ba94feee7..da88e7e58 100644--- a/headroom/proxy/outcome.py+++ b/headroom/proxy/outcome.py@@ -119,6 +119,34 @@ class RequestOutcome:# Prometheus ``cached`` counter and dashboard "response cache" row.from_response_cache: bool = False+ # ── Output composition ────────────────────────────────────────────+ # ``output_tokens`` pools two quantities that different levers move in+ # opposite directions: reasoning-effort routing cuts thinking, verbosity+ # steering cuts visible text. Summed, neither can be attributed — a turn+ # whose thinking dropped 4,000 tokens while its prose grew 200 is+ # indistinguishable from one where nothing happened.+ #+ # ``None`` means "we could not tell", which is NOT zero: Anthropic reports+ # no thinking count at all, so claiming 0 there would assert that no+ # thinking occurred and corrupt any average over mixed-provider traffic.+ # ``thinking_inferred`` marks a count Headroom derived by tokenizing the+ # response's thinking blocks rather than one the provider reported — the+ # same distinction ``cache_inferred`` draws on the input side.+ thinking_tokens: int | None = None+ thinking_inferred: bool = False+ # Why the model stopped. ``"max_tokens"`` (Anthropic) / ``"length"``+ # (OpenAI) mean a token ceiling cut the response off — the one unambiguous,+ # provider-supplied feedback signal an adaptive ceiling can run a control+ # loop on. The verbosity signals (user interrupted, user replied too fast to+ # have read it) need transcript inference, which is why the verbosity+ # controller was written and never wired to anything.+ stop_reason: str | None = None+ # 0-based position of this turn in its conversation. An output token is+ # billed once at the output rate and again as input on every later turn,+ # so what a wasted token actually costs depends on how much conversation+ # is left — which cannot be computed without knowing where we are in it.+ turn_index: int = 0+# Upstream HTTP status for this request (200 on success or response-cache# hit). When >= 500 (e.g. a 529 Overloaded returned after retry# exhaustion) the funnel records a failed request instead of feeding the@@ -192,6 +220,25 @@ class RequestOutcome:"""return self.cache_read_tokens > 0 or self.from_response_cache+ @property+ def visible_output_tokens(self) -> int | None:+ """Output tokens excluding thinking, or ``None`` when the split is+ unknown.++ The quantity verbosity steering actually targets. Callers must handle+ ``None`` rather than defaulting it to ``output_tokens``: on a provider+ that reports no thinking count, treating the whole output as visible+ would credit steering with reductions that reasoning-effort routing+ produced.++ Clamped at zero because an inferred count comes from Headroom's+ tokenizer while ``output_tokens`` is on the provider's scale; the two+ can disagree by a token or two on a short response.+ """+ if self.thinking_tokens is None:+ return None+ return max(0, self.output_tokens - self.thinking_tokens)+@propertydef cache_hit_pct(self) -> int:"""Cache read share of (read + write), rounded to int percent.@@ -264,6 +311,10 @@ class RequestOutcome:cache_write_1h_tokens: int = 0,uncached_input_tokens: int = 0,cache_inferred: bool = False,+ thinking_tokens: int | None = None,+ thinking_inferred: bool = False,+ stop_reason: str | None = None,+ turn_index: int = 0,ttfb_ms: float = 0.0,pipeline_timing: dict[str, float] | None = None,waste_signals: dict[str, int] | None = None,@@ -347,6 +398,10 @@ class RequestOutcome:cache_write_1h_tokens=cache_write_1h_tokens,uncached_input_tokens=uncached_input_tokens,cache_inferred=cache_inferred,+ thinking_tokens=thinking_tokens,+ thinking_inferred=thinking_inferred,+ stop_reason=stop_reason,+ turn_index=turn_index,total_latency_ms=total_latency_ms,overhead_ms=overhead_ms,ttfb_ms=ttfb_ms,@@ -446,6 +501,44 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:await handler.metrics.record_failed(provider=outcome.provider)return+ # Outcome stage: hand the meter's reading to any pipeline extension that+ # adapts to it — a ceiling that was hit, an effort setting that did or did+ # not pay off. The snapshot is frozen, so an extension can learn from the+ # measurement without being able to rewrite it: extensions declare what+ # they did, the core records what happened, and attribution is the core's+ # arithmetic over both.+ #+ # Best-effort and last in line: a handler without a pipeline manager, or an+ # extension that raises, must not affect the response or the stats below.+ _pipeline = getattr(handler, "pipeline_extensions", None)+ if _pipeline is not None and getattr(_pipeline, "enabled", False):+ try:+ from headroom.pipeline import OutcomeSnapshot, PipelineStage++ _pipeline.emit(+ PipelineStage.OUTCOME_OBSERVED,+ operation="proxy.outcome",+ request_id=outcome.request_id,+ provider=outcome.provider,+ model=outcome.model,+ outcome=OutcomeSnapshot(+ request_id=outcome.request_id,+ provider=outcome.provider,+ model=outcome.model,+ output_tokens=outcome.output_tokens,+ thinking_tokens=outcome.thinking_tokens,+ thinking_inferred=outcome.thinking_inferred,+ stop_reason=outcome.stop_reason,+ input_tokens=outcome.provider_input_tokens or outcome.optimized_tokens,+ cache_read_tokens=outcome.cache_read_tokens,+ cache_write_tokens=outcome.cache_write_tokens,+ turn_index=outcome.turn_index,+ transforms_applied=tuple(str(t) for t in (outcome.transforms_applied or ())),+ ),+ )+ except Exception: # noqa: BLE001 - telemetry must never break a response+ logger.debug("OUTCOME_OBSERVED emit failed", exc_info=True)+# Output-shaping savings ledger (counterfactual estimator). The shaper# tags each request's (arm, stratum) onto ``transforms_applied``; feed the# observed output tokens to the recorder so it can produce an honestdiff --git a/headroom/proxy/output_effort_policy.py b/headroom/proxy/output_effort_policy.pydeleted file mode 100644index 9751a5c28..000000000--- a/headroom/proxy/output_effort_policy.py+++ /dev/null@@ -1,55 +0,0 @@-"""Pure output-effort policy decisions.--The output shaper mutates provider request bodies. This module owns the-provider-neutral decisions behind those mutations so rank comparisons and-legacy budget clamping stay testable without request dictionaries.-"""--from __future__ import annotations--EFFORT_RANK = {"low": 0, "medium": 1, "high": 2, "xhigh": 3, "max": 4}-TEXT_VERBOSITY_RANK = {"low": 0, "medium": 1, "high": 2}-LEGACY_THINKING_FLOOR = 1024---def lower_effort_value(current: object, target: str) -> str | None:- """Return ``target`` when an existing effort should be lowered."""- if not isinstance(current, str):- return None- if current not in EFFORT_RANK or target not in EFFORT_RANK:- return None- if EFFORT_RANK[current] <= EFFORT_RANK[target]:- return None- return target---def clamp_legacy_thinking_budget(- *,- thinking_type: object,- budget_tokens: object,- floor: int = LEGACY_THINKING_FLOOR,-) -> int | None:- """Return the clamped budget for legacy enabled thinking, else ``None``."""- if thinking_type != "enabled":- return None- if not isinstance(budget_tokens, int):- return None- if budget_tokens <= floor:- return None- return floor---def can_create_openai_text_verbosity(model: object) -> bool:- """Whether it is safe to create a new OpenAI ``text.verbosity`` block."""- return str(model or "").lower().startswith("gpt-5")---def lower_text_verbosity_value(current: object) -> str | None:- """Return ``low`` when an existing OpenAI text verbosity should be lowered."""- if not isinstance(current, str):- return None- if current not in TEXT_VERBOSITY_RANK:- return None- if TEXT_VERBOSITY_RANK[current] <= TEXT_VERBOSITY_RANK["low"]:- return None- return "low"diff --git a/headroom/proxy/output_savings.py b/headroom/proxy/output_savings.pyindex 5fe317cb0..2caee6934 100644--- a/headroom/proxy/output_savings.py+++ b/headroom/proxy/output_savings.py@@ -185,6 +185,54 @@ class BaselineModel:return self.glob.n+# Benchmark-derived reduction factors, consulted ONLY when a deployment has+# neither a holdout nor a learned baseline.+#+# THIS TABLE SHIPS EMPTY, AND THAT IS THE INTENDED OPEN-SOURCE BEHAVIOUR.+# Headroom can apply verbosity steering out of the box -- set+# ``HEADROOM_VERBOSITY_LEVEL`` and the tokens are really saved. What it cannot+# do out of the box is tell you HOW MUCH it saved without measuring your own+# traffic, because a credible factor is not a constant: it depends on the model+# family, the shape of the turn, and the exact steering text, and producing one+# means running a paired benchmark across models and paying for both arms.+#+# Two ways to populate it, in order of strength:+#+# 1. Run a holdout. ``SavingsLedger.estimate_from_holdout`` measures YOUR+# traffic and outranks anything here -- see :meth:`best_estimate`. This is+# the honest answer and it needs no factor table at all.+# 2. Register factors from a benchmark, via :func:`register_modelled_factors`.+# An extension that has done the measurement can install them at startup.+#+# An empty table means :meth:`estimate_from_model` returns ``None`` for every+# level, so the dashboard shows a dash rather than a number nobody measured.+# A dash is the correct rendering of "not measured"; an invented constant is+# not, and would be the one failure mode this module exists to prevent.+MODELLED_REDUCTION: dict[int, tuple[float, float]] = {}+++def register_modelled_factors(level: int, conservative: float, optimistic: float) -> None:+ """Install benchmark-derived reduction factors for one verbosity level.++ Extension seam. ``conservative`` and ``optimistic`` are fractions in+ ``(0, 1)`` -- the low and high ends of the measured reduction, where the+ low end becomes the headline so the number under-reports rather than+ flatters.++ Registering a level twice replaces it, so an extension may refresh factors+ after a re-measurement. Values outside ``(0, 1)`` are rejected: the+ estimator inverts them as ``r/(1-r)``, which is nonsense at 0 and divides+ by zero at 1.+ """+ if not 0.0 < conservative < 1.0 or not 0.0 < optimistic < 1.0:+ raise ValueError(+ f"reduction factors must lie in (0, 1); got ({conservative}, {optimistic})"+ )+ if conservative > optimistic:+ raise ValueError(f"conservative factor {conservative} exceeds optimistic {optimistic}")+ MODELLED_REDUCTION[level] = (conservative, optimistic)++@dataclassclass SavingsEstimate:"""Result of an estimation pass."""@@ -195,7 +243,9 @@ class SavingsEstimate:ci_low_pct: floatci_high_pct: floatn_requests: int- kind: str # "estimated" (synthetic control) or "measured" (A/B holdout)+ # "measured" (A/B holdout) > "estimated" (synthetic control) >+ # "modelled" (benchmark default factor -- not this deployment's traffic)+ kind: strdef to_dict(self) -> dict[str, Any]:return asdict(self)@@ -305,10 +355,71 @@ class SavingsLedger:kind=kind,)- def best_estimate(self) -> SavingsEstimate:- """Prefer the measured A/B number; fall back to the baseline estimate."""+ def estimate_from_model(self, level: int) -> SavingsEstimate | None:+ """Weakest tier: apply a benchmark factor to observed treatment output.++ Used only when this deployment has produced no counterfactual of its+ own. Returns ``None`` for a level that was never benchmarked, so an+ unmeasured level shows nothing rather than a guess.++ The arithmetic is the part worth getting right. Observed output is+ already POST-shaping, so the saving is not ``observed x r``. If the+ unshaped response would have been ``U`` and we observed+ ``O = U(1-r)``, then ``saved = U - O = O * r/(1-r)``. At r=0.20 that is+ 0.25 of observed, not 0.20 -- the naive form understates, and by more+ as r grows.+ """+ factors = MODELLED_REDUCTION.get(level)+ if factors is None:+ return None+ observed = 0.0+ n_requests = 0+ for acc in self.treatment.values():+ if acc.n == 0:+ continue+ observed += acc.n * acc.mean+ n_requests += acc.n+ if n_requests == 0 or observed <= 0:+ return None++ def saved_for(r: float) -> float:+ return observed * r / (1.0 - r)++ lo_r, hi_r = factors+ saved = saved_for(lo_r)+ baseline = observed + saved+ # The band is the spread between the two benchmarked models, NOT a+ # sampling CI -- there is no sample here. Callers must not label it+ # "95% CI"; the dashboard branches on kind for exactly this reason.+ lo_pct = lo_r * 100.0+ hi_pct = hi_r * 100.0+ return SavingsEstimate(+ tokens_saved=saved,+ baseline_tokens=baseline,+ pct=lo_pct,+ ci_low_pct=lo_pct,+ ci_high_pct=hi_pct,+ n_requests=n_requests,+ kind="modelled",+ )++ def best_estimate(self, level: int | None = None) -> SavingsEstimate:+ """Strongest available tier: measured > estimated > modelled.++ ``level`` enables the modelled fallback; without it the behaviour is+ unchanged from before, which keeps every existing caller honest.+ """measured = self.estimate_from_holdout()- return measured if measured is not None else self.estimate_from_baseline()+ if measured is not None:+ return measured+ estimated = self.estimate_from_baseline()+ if estimated.n_requests > 0:+ return estimated+ if level is not None:+ modelled = self.estimate_from_model(level)+ if modelled is not None:+ return modelled+ return estimated# ---- persistence -----------------------------------------------------@@ -402,10 +513,24 @@ class SavingsRecorder:"""Per-request output tokens saved, for the savings rollup.For a treatment request, the synthetic-control estimate- ``max(0, baseline_mean(stratum) - output_tokens)``; 0 for control,- unknown strata, or when no shaping label is present. Read-only:- unlike ``record_from_labels`` it does not mutate the ledger, so the- two compose without double-counting."""+ ``baseline_mean(stratum) - output_tokens``; 0 for control, unknown+ strata, or when no shaping label is present. Read-only: unlike+ ``record_from_labels`` it does not mutate the ledger, so the two+ compose without double-counting.++ The delta is **clamped at zero here**, which is deliberate and is not+ in tension with this module's "never clamped per-request" rule. That+ rule governs the tier-1 estimate in :meth:`estimate`, which sums signed+ deltas (``total_saved += n * (mu - acc.mean)``) precisely so that+ chattier-than-baseline turns pull the headline down. This method feeds+ something else: the per-request savings rollup on ``RequestOutcome``,+ which flows to Prometheus and the savings ledger. Those are+ accumulate-only surfaces — both consumers floor it again+ (``savings_tracker`` at the ``estimate_request_savings_usd`` and+ ``record_request`` boundaries), and ``prometheus_metrics`` clamps a+ negative ``tokens_saved`` with an "artifact" log for the same reason.+ Keeping the floor here makes that boundary explicit rather than+ relying on every downstream caller to reapply it."""for label in labels or ():parsed = parse_stratum_label(str(label))if parsed is None:@@ -461,10 +586,10 @@ class SavingsRecorder:with self._lock:self._flush_locked()- def estimate(self) -> SavingsEstimate:+ def estimate(self, level: int | None = None) -> SavingsEstimate:with self._lock:self._reload_baseline_locked()- return self._ledger.best_estimate()+ return self._ledger.best_estimate(level)_RECORDER: SavingsRecorder | None = Nonediff --git a/headroom/proxy/output_shaper.py b/headroom/proxy/output_shaper.pyindex 7dd9663ba..c0989a8d9 100644--- a/headroom/proxy/output_shaper.py+++ b/headroom/proxy/output_shaper.py@@ -30,13 +30,11 @@ Safety rules (each prevents a concrete failure mode):Turn classification is purely structural (block types, roles, ``is_error``flags) — no content regexes or keyword patterns.-The same two levers exist for the OpenAI Responses format (Codex et al.):-:func:`classify_responses_turn` reads the ``input`` item list,+The same lever exists for the OpenAI Responses format (Codex et al.)::func:`apply_responses_verbosity_steering` appends the byte-stable steeringblock to the tail of the ``instructions`` string, and-:func:`route_responses_effort` lowers an explicitly-present-``reasoning.effort`` on mechanical continuations. :func:`shape_responses_request`-is the Responses-format counterpart of :func:`shape_request`.+:func:`shape_responses_request` is the Responses-format counterpart of+:func:`shape_request`."""from __future__ import annotations@@ -47,16 +45,6 @@ from dataclasses import dataclassfrom typing import Anyfrom headroom.proxy import runtime_env-from headroom.proxy.output_effort_policy import (- EFFORT_RANK as _EFFORT_RANK,-)-from headroom.proxy.output_effort_policy import (- LEGACY_THINKING_FLOOR,- can_create_openai_text_verbosity,- clamp_legacy_thinking_budget,- lower_effort_value,- lower_text_verbosity_value,-)from headroom.proxy.output_steering import (apply_openai_chat_verbosity_steering,apply_openai_responses_verbosity_steering,@@ -69,11 +57,11 @@ from headroom.proxy.output_turn_policy import (classify_openai_responses_input,classify_turn,)+from headroom.rollout import FeatureDecisionReasonlogger = logging.getLogger(__name__)__all__ = [- "LEGACY_THINKING_FLOOR","OutputShaperSettings","ShapeResult","TurnKind",@@ -83,9 +71,6 @@ __all__ = ["classify_openai_responses_input","classify_turn","resolve_verbosity_level",- "route_effort",- "route_openai_reasoning_effort",- "route_openai_text_verbosity","shape_openai_chat_request","shape_openai_responses_request","shape_request",@@ -100,12 +85,18 @@ class OutputShaperSettings:"""Output-shaping settings with rollout enablement injected by the proxy."""enabled: bool = False- verbosity_level: int = 2- effort_router_enabled: bool = True- mechanical_effort: str = "low"+ verbosity_level: int = 3+ # 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); effort routing and the+ # thinking budget sit outside the key and stay on. See+ # :func:`steering_allowed_for`.+ steering_enabled: bool = True@classmethod- def from_env(cls, *, enabled: bool | None = None) -> OutputShaperSettings:+ def from_env(+ cls, *, enabled: bool | None = None, steering_enabled: bool = True+ ) -> OutputShaperSettings:"""Resolve tuning; running proxies always inject the resolved gate.``None`` preserves the helper's direct-call compatibility for SDK/tests,@@ -119,26 +110,70 @@ class OutputShaperSettings:"yes",)try:- level = int(runtime_env.getenv("HEADROOM_VERBOSITY_LEVEL", "2"))+ level = int(runtime_env.getenv("HEADROOM_VERBOSITY_LEVEL", "3"))except ValueError:level = 2level = max(0, min(4, level))- router = runtime_env.getenv("HEADROOM_EFFORT_ROUTER", "1").lower() not in (- "0",- "false",- "no",- )- mech = runtime_env.getenv("HEADROOM_MECHANICAL_EFFORT", "low")- if mech not in _EFFORT_RANK:- mech = "low"return cls(enabled=enabled,verbosity_level=level,- effort_router_enabled=router,- mechanical_effort=mech,+ steering_enabled=steering_enabled,)+def shaper_enabled_for(config: Any) -> bool | None:+ """Resolve the output-shaper gate for a proxy config.++ Output shaping is deliberately independent of input compression — an+ operator can run ``optimize=False`` and still want terser responses, and+ the WS/Responses shaper tests pin that combination. So ``optimize`` does+ not veto shaping outright. What it vetoes is shaping that nobody asked+ for.++ Since the feature defaults on, ``optimize=False`` plus *no* explicit+ request means an operator who turned every transform off would silently+ start getting a steering block appended to their system-prompt tail — and+ on a request carrying no ``system`` field at all, would have one created.+ That breaks the byte-faithful forwarding invariant. So in that one+ combination the default loses:++ * enabled explicitly (``HEADROOM_OUTPUT_SHAPER=1``, ``HEADROOM_FEATURES``)+ → shape, whatever ``optimize`` says;+ * enabled only by default, with ``optimize=False`` → do not shape;+ * enabled only by default, with ``optimize=True`` → shape.++ Returns ``None`` when there is no rollout snapshot to consult, which+ preserves :meth:`OutputShaperSettings.from_env`'s env-var fallback for the+ SDK and test callers that construct a config without one.+ """+ rollout = getattr(config, "rollout", None)+ if rollout is None:+ return None+ try:+ decision = rollout.decision("proxy_output_shaper")+ except (KeyError, AttributeError):+ return None+ if not decision.enabled:+ return False+ if getattr(config, "optimize", True):+ return True+ return decision.reason is not FeatureDecisionReason.DEFAULT+++def steering_allowed_for(config: Any) -> bool:+ """False when the proxy is in prefix-freezing cache mode.++ ``mode="cache"`` freezes prior turns specifically to keep the provider's+ prefix-cache key byte-stable (see ``ProxyConfig.mode``). Verbosity steering+ writes into that key, so running it there trades a large, certain cache+ cost for a small, uncertain output saving — the wrong side of a roughly+ 60x margin on a long context. Effort routing and the thinking budget are+ unaffected: they ride request parameters outside the cache key, so they+ keep saving in cache mode.+ """+ return getattr(config, "mode", None) != "cache"++def resolve_verbosity_level(settings: OutputShaperSettings) -> tuple[int, str]:"""Resolve the live verbosity level and its source.@@ -151,6 +186,13 @@ def resolve_verbosity_level(settings: OutputShaperSettings) -> tuple[int, str]:Returns ``(level, source)``. Kept separate from :func:`shape_request` so thebody-mutating core stays a pure function of an explicit level."""+ if not settings.steering_enabled:+ # Level 0 is the documented "no steering" value, so this disables the+ # only cache-key-mutating lever while leaving effort routing on. It+ # deliberately outranks the manual override below: a level set in the+ # environment must not reintroduce a prefix mutation the mode exists+ # to prevent.+ return 0, "cache_mode"if runtime_env.getenv("HEADROOM_VERBOSITY_LEVEL"):return settings.verbosity_level, "env"@@ -201,93 +243,6 @@ class ShapeResult:self.labels = []-def route_effort(- body: dict[str, Any],- kind: TurnKind,- settings: OutputShaperSettings,-) -> list[str]:- """Lower thinking/effort spend on mechanical continuations.-- Returns labels for each mutation made (empty list = untouched).- """- if kind is not TurnKind.MECHANICAL_CONTINUATION:- return []-- labels: list[str] = []-- # Modern lever: output_config.effort. Only lower a value the client- # explicitly sent — presence proves the target model accepts the param.- output_config = body.get("output_config")- if isinstance(output_config, dict):- effort = output_config.get("effort")- lowered = lower_effort_value(effort, settings.mechanical_effort)- if lowered is not None:- output_config["effort"] = lowered- labels.append(f"output_shaper:effort:{effort}->{lowered}")-- # Legacy lever: clamp thinking.budget_tokens on models still using the- # enabled/budget_tokens form. The type field itself is never touched.- thinking = body.get("thinking")- if isinstance(thinking, dict):- budget = thinking.get("budget_tokens")- clamped = clamp_legacy_thinking_budget(- thinking_type=thinking.get("type"),- budget_tokens=budget,- floor=LEGACY_THINKING_FLOOR,- )- if clamped is not None:- thinking["budget_tokens"] = clamped- labels.append(f"output_shaper:thinking_budget:{budget}->{clamped}")-- return labels---def route_openai_reasoning_effort(- body: dict[str, Any],- kind: TurnKind,- settings: OutputShaperSettings,-) -> list[str]:- """Lower explicitly-present OpenAI reasoning effort on mechanical turns."""- if kind is not TurnKind.MECHANICAL_CONTINUATION:- return []-- reasoning = body.get("reasoning")- if not isinstance(reasoning, dict):- return []- effort = reasoning.get("effort")- target = settings.mechanical_effort- lowered = lower_effort_value(effort, target)- if lowered is not None:- reasoning["effort"] = lowered- return [f"output_shaper:reasoning_effort:{effort}->{lowered}"]- return []---def route_openai_text_verbosity(body: dict[str, Any]) -> list[str]:- """Set or lower OpenAI ``text.verbosity`` conservatively."""- text_config = body.get("text")- can_create = can_create_openai_text_verbosity(body.get("model"))- if text_config is None:- if not can_create:- return []- body["text"] = {"verbosity": "low"}- return ["output_shaper:text_verbosity:unset->low"]- if not isinstance(text_config, dict):- return []-- verbosity = text_config.get("verbosity")- if verbosity is None:- if not can_create:- return []- text_config["verbosity"] = "low"- return ["output_shaper:text_verbosity:unset->low"]- lowered = lower_text_verbosity_value(verbosity)- if lowered is not None:- text_config["verbosity"] = lowered- return [f"output_shaper:text_verbosity:{verbosity}->{lowered}"]- return []--def shape_openai_responses_request(body: dict[str, Any],settings: OutputShaperSettings | None = None,@@ -307,19 +262,6 @@ def shape_openai_responses_request(result.changed = Trueresult.labels.append(f"output_shaper:verbosity:L{level}")- kind = classify_openai_responses_input(body.get("input"))- if settings.effort_router_enabled:- labels = route_openai_reasoning_effort(body, kind, settings)- if labels:- result.changed = True- result.labels.extend(labels)- logger.debug("OpenAIOutputShaper: turn=%s mutations=%s", kind.value, labels)-- labels = route_openai_text_verbosity(body)- if labels:- result.changed = True- result.labels.extend(labels)-return result@@ -347,14 +289,6 @@ def shape_request(result.changed = Trueresult.labels.append(f"output_shaper:verbosity:L{level}")- if settings.effort_router_enabled:- kind = classify_turn(body.get("messages", []))- labels = route_effort(body, kind, settings)- if labels:- result.changed = True- result.labels.extend(labels)- logger.debug("OutputShaper: turn=%s mutations=%s", kind.value, labels)-return result@@ -367,10 +301,7 @@ def shape_openai_chat_request(The chat counterpart of :func:`shape_request`. Chat carries the systemprompt as a ``role: "system"`` message, so verbosity steering uses the- chat-specific injector. Effort routing is intentionally not applied here:- the ``route_effort`` levers write Anthropic-shaped config and there is no- portable chat/completions equivalent, so only the verbosity steering lever- (the one that reduces output tokens) runs on this path.+ chat-specific injector."""if settings is None:settings = OutputShaperSettings.from_env()@@ -392,10 +323,6 @@ def shape_openai_chat_request(# OpenAI Responses format (Codex, /v1/responses HTTP + WebSocket)# ----------------------------------------------------------------------------# Responses ``reasoning.effort`` uses "minimal" as its floor (Anthropic's-# ``output_config.effort`` does not), so it gets its own rank table.-_RESPONSES_EFFORT_RANK = {"minimal": 0, "low": 1, "medium": 2, "high": 3, "xhigh": 4}-# Trailing ``input`` item types that represent tool output coming back to the# model — the Responses counterpart of an Anthropic ``tool_result`` block._RESPONSES_TOOL_OUTPUT_TYPES = frozenset(@@ -498,36 +425,6 @@ def apply_responses_verbosity_steering(body: dict[str, Any], level: int) -> boolreturn apply_openai_responses_verbosity_steering(body, level)-def route_responses_effort(- body: dict[str, Any],- kind: TurnKind,- settings: OutputShaperSettings,-) -> list[str]:- """Lower ``reasoning.effort`` on mechanical continuations.-- Only lowers a value the client explicitly sent — presence proves the- target model accepts the parameter. Never injects ``reasoning`` where- absent, and never touches new asks or error continuations.- """- if kind is not TurnKind.MECHANICAL_CONTINUATION:- return []-- reasoning = body.get("reasoning")- if not isinstance(reasoning, dict):- return []- effort = reasoning.get("effort")- target = settings.mechanical_effort- if (- isinstance(effort, str)- and effort in _RESPONSES_EFFORT_RANK- and target in _RESPONSES_EFFORT_RANK- and _RESPONSES_EFFORT_RANK[effort] > _RESPONSES_EFFORT_RANK[target]- ):- reasoning["effort"] = target- return [f"output_shaper:effort:{effort}->{target}"]- return []--def shape_responses_request(body: dict[str, Any],settings: OutputShaperSettings | None = None,@@ -551,12 +448,4 @@ def shape_responses_request(result.changed = Trueresult.labels.append(f"output_shaper:verbosity:L{level}")- if settings.effort_router_enabled:- kind = classify_responses_turn(body.get("input"))- labels = route_responses_effort(body, kind, settings)- if labels:- result.changed = True- result.labels.extend(labels)- logger.debug("OutputShaper(responses): turn=%s mutations=%s", kind.value, labels)-return resultdiff --git a/headroom/proxy/output_verbosity_policy.py b/headroom/proxy/output_verbosity_policy.pyindex 5c692b797..e05034c83 100644--- a/headroom/proxy/output_verbosity_policy.py+++ b/headroom/proxy/output_verbosity_policy.py@@ -10,6 +10,48 @@ STEERING_SUFFIX = "</headroom_output_shaping>"# Levels are cumulative: each includes everything above it. Text must stay# byte-stable across releases for prefix-cache friendliness; edits to these# strings are cache-busting changes.+#+# The "cite the exact file path and line" clause is an OBLIGATION, not a+# suggestion, because the loose form ("reference by path and line") was+# measured to cost turns.+#+# Measured on SWE-bench tasks run to completion, with a blind judge playing the+# engineer who must apply the fix and asking a follow-up whenever blocked. Of+# the four blocker categories, only one moved between L0 and L3 -- and notably+# it was NOT the one predicted. "Asked why" scored 0 at both levels, so+# "omit rationale unless the user asks why" does not generate follow-ups.+# What moved was "under-specified location", 0 -> 3 across 9 paired Claude+# tasks: told to stop restating code, models wrote "change the check in the+# mixin" and the reader had to ask which file.+#+# Tightening this one clause fixed it -- 3 -> 0 on a re-run, with turn+# inflation going +23.1% -> 0.0% and L3 needing no more rounds than L0. The+# lesson generalises: suppressing content is safe, suppressing the POINTER to+# that content is not, because the reader buys it back at the price of a whole+# turn. Sample is small (n=9, Claude only); the mechanism is better evidenced+# than the magnitude.+#+# L3 and L4 carry two rules L1/L2 do not, because only they instruct the model+# to drop content rather than ceremony:+#+# * A completeness floor. "Omit rationale" and "fragments fine" reward any+# cut that shortens the answer, including cuts that change it -- the+# dangerous case is a dropped negation, since losing "not" from "does not+# retry" inverts the meaning while making it shorter. The floor names what+# brevity may not touch: content the task needs to be correct.+# * A clarity exception. Without it these levels are tersest precisely where+# terseness is most costly: destructive actions, security warnings, and+# multi-step sequences.+#+# The floor is phrased as a prohibition on dropping content, NOT as the earlier+# "reproduce code, error strings, numbers ... exactly". That wording read as a+# licence to emit code verbatim: measured against the same SWE-bench turn it+# left gpt-5.2 unchanged but inflated gpt-5.1 by 58% (1631 -> 2573 output+# tokens), cutting L3's saving on that model from 51% to 23%. Constrain what+# may be lost; do not instruct the model to reproduce anything.+#+# L1/L2 only forbid preamble and restating context, so they carry neither --+# every token in this block is paid on every request of every conversation.VERBOSITY_LEVELS = {1: ("Skip preamble and postamble. Do not announce what you are about to "@@ -23,15 +65,26 @@ VERBOSITY_LEVELS = {),3: ("Skip preamble and postamble. Never restate code, file contents, "- "diffs, or tool output already in this conversation — reference by "- "path and line. Give conclusions only; omit rationale unless the user "- "asks why. Prefer the smallest edit over rewriting whole files. Keep "- "prose to the minimum needed to be unambiguous."+ "diffs, or tool output already in this conversation — cite the exact "+ "file path and line or symbol instead, always; a reference that omits "+ "the location is not a reference. Give conclusions only; omit "+ "rationale unless the user asks why. Prefer the smallest edit over "+ "rewriting whole files. Keep prose to the minimum needed to be "+ "unambiguous. Never drop anything the turn or task needs to be "+ "correct, including negations (not, never, "+ "no, only, except) — shorten how you say it, not what you say. Use "+ "full prose for destructive or irreversible actions, security "+ "warnings, and any multi-step sequence where brevity would create "+ "ambiguity."),4: ("Minimum tokens. Fragments fine. No preamble, no postamble, no ""restating context, no rationale. Answer, smallest-possible edits, "- "nothing else."+ "nothing else. Never drop anything the turn or task needs to be "+ "correct, including negations (not, never, no, only, except). Use "+ "full prose for destructive or irreversible actions, security "+ "warnings, and any multi-step sequence where brevity would create "+ "ambiguity."),}diff --git a/headroom/proxy/runtime_env.py b/headroom/proxy/runtime_env.pyindex bc4c03bc2..500c236b1 100644--- a/headroom/proxy/runtime_env.py+++ b/headroom/proxy/runtime_env.py@@ -62,8 +62,6 @@ RUNTIME_ENV_KNOBS: tuple[Knob, ...] = (Knob("HEADROOM_VERBOSITY_LEVEL", "int", "Verbosity steering level 0-4 (unset = learned/default)."),- Knob("HEADROOM_EFFORT_ROUTER", "bool", "Lower effort on mechanical tool-result continuations."),- Knob("HEADROOM_MECHANICAL_EFFORT", "str", "Effort value used on mechanical continuations."),Knob("HEADROOM_VERBOSITY_AUTOTUNE", "bool", "Use the AIMD verbosity controller state."),Knob("HEADROOM_OUTPUT_HOLDOUT",diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 923b2af35..dde28dabc 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -4295,12 +4295,34 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:output_reduction: dict[str, Any] = {"available": False}try:from headroom.proxy.output_savings import get_recorder+ from headroom.proxy.output_shaper import (+ OutputShaperSettings,+ resolve_verbosity_level,+ shaper_enabled_for,+ )++ # The active steering level enables the modelled fallback, which is+ # what a deployment with no holdout and no learned baseline has --+ # i.e. every fresh install, since `learn --verbosity` needs history+ # that predates the shaper.+ _olevel: int | None = None+ try:+ _osettings = OutputShaperSettings.from_env(+ enabled=shaper_enabled_for(getattr(proxy, "config", None))+ )+ if _osettings.enabled:+ _olevel = resolve_verbosity_level(_osettings)[0]+ except Exception: # pragma: no cover - defensive+ _olevel = None- _oest = get_recorder().estimate()+ _oest = get_recorder().estimate(_olevel)if _oest.n_requests > 0:output_reduction = {"available": True,- "method": _oest.kind, # "measured" | "estimated"+ "method": _oest.kind, # "measured" | "estimated" | "modelled"+ # A modelled band is the spread between the two benchmarked+ # models, not a sampling CI. The UI must not call it one.+ "band_is_ci": _oest.kind != "modelled","tokens_saved": round(_oest.tokens_saved),"baseline_tokens": round(_oest.baseline_tokens),"reduction_percent": round(_oest.pct, 1),@@ -4347,9 +4369,10 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:**output_reduction,"description": ("OUTPUT tokens the model didn't emit because the shaper "- "steered verbosity / routed effort down. Counterfactual — "- "shown as an estimate (vs a learned baseline) or measured "- "(A/B holdout), always with a confidence band."+ "steered verbosity down. Counterfactual — measured "+ "(A/B holdout), estimated (vs a learned baseline), or "+ "modelled (a benchmark factor, when this deployment has "+ "produced neither). Always labelled with which."),},"tool_search": {diff --git a/headroom/proxy/thinking_tokens.py b/headroom/proxy/thinking_tokens.pynew file mode 100644index 000000000..ff1f5c531--- /dev/null+++ b/headroom/proxy/thinking_tokens.py@@ -0,0 +1,216 @@+"""Separate thinking tokens from visible output tokens.++``output_tokens`` is a single number today, and it pools two quantities that+different levers move in opposite directions. Reasoning-effort routing cuts+*thinking*; verbosity steering cuts *visible text*. Summed into one counter,+neither can be attributed: a request whose thinking dropped 4,000 tokens while+its prose grew 200 looks identical to one where nothing happened.++That is not a reporting nicety. It is the reason the output shaper cannot say+which of its levers works, including the ones already shipped.++What each provider actually tells us+------------------------------------+* **OpenAI chat** — ``usage.completion_tokens_details.reasoning_tokens``.+* **OpenAI Responses** — ``usage.output_tokens_details.reasoning_tokens``.+* **Gemini** — ``usageMetadata.thoughtsTokenCount``. Note this is already read+ by :func:`headroom.proxy.token_counting.gemini_output_tokens`, but only to+ fold into the output total; keeping it separate here loses nothing and gains+ the split.+* **Anthropic** — *nothing*. The Messages API reports no thinking count at all.+ The thinking text is in the response content, so it can be estimated, but an+ estimate must never be handed back as if the provider had reported it.++Unknown is not zero+-------------------+Returning ``0`` for Anthropic would assert "no thinking happened", which is+false whenever extended thinking is on — and it would quietly corrupt every+average computed over mixed-provider traffic. So the result is ``None`` for+"we cannot tell" and an ``int`` for "we know", with :attr:`ThinkingTokens.inferred`+marking a count Headroom derived rather than received.++That mirrors ``RequestOutcome.cache_inferred``, which exists for the same+reason on the input side: a derived number is useful, and pretending it was+measured is not.++Pure module: no tokenizer import at module scope and no I/O. The estimator is+injected, so callers that have a tokenizer can pass one and callers that do not+still get a correct ``None``.+"""++from __future__ import annotations++from collections.abc import Callable+from dataclasses import dataclass+from typing import Any++__all__ = [+ "ThinkingTokens",+ "anthropic_thinking_text",+ "extract_from_usage",+ "extract_thinking_tokens",+]+++@dataclass(frozen=True)+class ThinkingTokens:+ """A thinking-token count, and whether it was reported or derived.++ Attributes:+ tokens: The count, or ``None`` when the provider reported nothing and+ no estimate could be made. ``0`` means "the provider told us there+ was no thinking" — a genuinely different claim from ``None``.+ inferred: True when Headroom derived the number (by tokenizing the+ response's thinking blocks) rather than reading it from usage.+ """++ tokens: int | None = None+ inferred: bool = False++ @property+ def known(self) -> bool:+ return self.tokens is not None++ def visible_from(self, output_tokens: int) -> int | None:+ """Visible output tokens, or ``None`` when the split is unknown.++ Clamped at zero: an inferred count uses Headroom's tokenizer while+ ``output_tokens`` is on the provider's scale, so the two can disagree+ slightly and a naive subtraction can go negative on a short response.+ """+ if self.tokens is None:+ return None+ return max(0, output_tokens - self.tokens)+++def _as_int(value: Any) -> int | None:+ """Coerce a usage field to a non-negative int, or ``None`` if absent/bad.++ Distinguishes a missing field from a zero one, which is the whole point of+ this module — so it deliberately does not use the ``_usage_int`` pattern+ elsewhere in the proxy, which floors everything to 0.+ """+ if value is None or isinstance(value, bool):+ return None+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ return None+ return max(parsed, 0)+++def _details_reasoning(usage: dict[str, Any]) -> int | None:+ """Read ``reasoning_tokens`` from whichever details block is present.++ Chat spells the container ``completion_tokens_details``; Responses spells+ it ``output_tokens_details``. Some gateways echo both, so check each and+ take the first that carries a usable number rather than assuming a format.+ """+ for container_key in ("output_tokens_details", "completion_tokens_details"):+ container = usage.get(container_key)+ if not isinstance(container, dict):+ continue+ parsed = _as_int(container.get("reasoning_tokens"))+ if parsed is not None:+ return parsed+ return None+++def anthropic_thinking_text(payload: dict[str, Any]) -> str:+ """Concatenate the text of every thinking block in an Anthropic response.++ Anthropic reports no thinking count, but it does return the thinking+ itself, so the content is the only available basis for an estimate.+ Handles both ``thinking`` and ``redacted_thinking`` blocks; a redacted+ block carries no readable text but still cost output tokens, so its+ ``data`` payload is included — an approximation, and flagged as inferred+ by the caller.+ """+ content = payload.get("content")+ if not isinstance(content, list):+ return ""+ parts: list[str] = []+ for block in content:+ if not isinstance(block, dict):+ continue+ btype = block.get("type")+ if btype == "thinking":+ text = block.get("thinking")+ if isinstance(text, str):+ parts.append(text)+ elif btype == "redacted_thinking":+ data = block.get("data")+ if isinstance(data, str):+ parts.append(data)+ return "\n".join(parts)+++def extract_from_usage(usage: Any) -> ThinkingTokens:+ """Read the thinking count from a bare provider ``usage`` dict.++ The full-payload :func:`extract_thinking_tokens` is the general entry+ point, but several proxy call sites have already destructured ``usage``+ out of the response and never keep the body around. Giving them a direct+ path avoids forcing an artificial re-wrap — and avoids the temptation to+ pass ``{}`` and silently record a zero.+ """+ if not isinstance(usage, dict):+ return ThinkingTokens()+ reported = _details_reasoning(usage)+ if reported is not None:+ return ThinkingTokens(tokens=reported)+ thoughts = _as_int(usage.get("thoughtsTokenCount"))+ if thoughts is not None:+ return ThinkingTokens(tokens=thoughts)+ return ThinkingTokens()+++def extract_thinking_tokens(+ payload: Any,+ *,+ estimator: Callable[[str], int] | None = None,+) -> ThinkingTokens:+ """Extract the thinking-token count from any provider response shape.++ Args:+ payload: A parsed provider response body.+ estimator: Optional ``text -> token count``. Supplied by callers that+ have a tokenizer; used only for Anthropic, which reports no count+ of its own. Without it, Anthropic responses return ``None``+ (unknown) rather than a fabricated zero.++ Returns:+ A :class:`ThinkingTokens`. ``tokens is None`` means the split could not+ be determined — callers must treat that as "unknown", never as zero.+ """+ if not isinstance(payload, dict):+ return ThinkingTokens()++ # Gemini: a top-level usageMetadata rather than usage.+ usage_meta = payload.get("usageMetadata")+ if isinstance(usage_meta, dict):+ return ThinkingTokens(tokens=_as_int(usage_meta.get("thoughtsTokenCount")))++ usage = payload.get("usage")+ if isinstance(usage, dict):+ reported = _details_reasoning(usage)+ if reported is not None:+ return ThinkingTokens(tokens=reported)++ # Anthropic: no usage field for this, so fall back to the content.+ text = anthropic_thinking_text(payload)+ if not text:+ # Distinguish "an Anthropic response with no thinking blocks" — which+ # is a genuine zero — from "not an Anthropic response at all", where we+ # know nothing. Only a response that actually carries content blocks+ # can support the former claim.+ if isinstance(payload.get("content"), list):+ return ThinkingTokens(tokens=0)+ return ThinkingTokens()++ if estimator is None:+ return ThinkingTokens()+ try:+ return ThinkingTokens(tokens=max(0, int(estimator(text))), inferred=True)+ except Exception: # noqa: BLE001 — a bad estimator must not break a response+ return ThinkingTokens()diff --git a/headroom/rollout.py b/headroom/rollout.pyindex 859b6e80c..6c09cabd4 100644--- a/headroom/rollout.py+++ b/headroom/rollout.py@@ -104,9 +104,14 @@ FEATURES: dict[str, FeatureSpec] = {),"proxy_output_shaper": FeatureSpec(name="proxy_output_shaper",- available_in=RolloutChannel.BETA,+ available_in=RolloutChannel.STABLE,+ # Deliberately NOT default-enabled. Steering appends a block to the+ # system prompt, and at L3 that is a visible behaviour change ("give+ # conclusions only") -- a user who did not ask for it would read the+ # terseness as the model getting worse. Available in every channel, so+ # HEADROOM_OUTPUT_SHAPER=1 is all it takes to turn on.legacy_env=("HEADROOM_OUTPUT_SHAPER",),- description="Proxy output-shaping path for response-side experiments.",+ description="Output-token shaping: verbosity steering (opt-in).",),"read_maturation": FeatureSpec(name="read_maturation",diff --git a/tests/test_agent_savings.py b/tests/test_agent_savings.pyindex 691a24b3e..37073acf9 100644--- a/tests/test_agent_savings.py+++ b/tests/test_agent_savings.py@@ -85,7 +85,6 @@ def test_coding_persona_compresses_recent_delta_and_stays_visible() -> None:assert env["HEADROOM_LOSSLESS_THEN_LOSSY"] == "1"assert env["HEADROOM_PROTECT_READS"] == "1"assert env["HEADROOM_CODE_AWARE_ENABLED"] == "1"- assert env["HEADROOM_EFFORT_ROUTER"] == "0"assert env["HEADROOM_LOSSLESS"] == "0" # lossy enabled (CCR keeps it recoverable)assert env["HEADROOM_MIN_CHARS_FOR_BLOCK"] == "25"diff --git a/tests/test_canonical_pipeline.py b/tests/test_canonical_pipeline.pyindex f15d29780..9eabce27a 100644--- a/tests/test_canonical_pipeline.py+++ b/tests/test_canonical_pipeline.py@@ -246,7 +246,10 @@ def test_discover_pipeline_extensions_handles_load_and_init_failures(monkeypatchlambda group: entries if group == pipeline_module.ENTRY_POINT_GROUP else [],)- discovered = pipeline_module.discover_pipeline_extensions()+ # Discovery is opt-in since the contract gained ``body`` (it can now+ # rewrite max_tokens/effort on live traffic), so name them explicitly.+ # The isolation behaviour under test is unchanged.+ discovered = pipeline_module.discover_pipeline_extensions(["*"])assert len(discovered) == 2assert hasattr(discovered[0], "on_pipeline_event")diff --git a/tests/test_cli_perf_format.py b/tests/test_cli_perf_format.pyindex fd39556d9..13dffd7e9 100644--- a/tests/test_cli_perf_format.py+++ b/tests/test_cli_perf_format.py@@ -431,6 +431,7 @@ def test_throughput_empty_and_percentiles():# nothing rendered it, so a paid extension's contribution was invisible in the# report operators actually read.+def _savings_perf_line(encoded: str, req: int = 1) -> str:return (f"2026-08-31 16:00:0{req},000 - headroom.proxy - INFO - [hr_1_00000{req}] PERF "@@ -467,9 +468,13 @@ def test_dollar_only_source_is_reported_with_zero_tokens(tmp_path, monkeypatch):from headroom.proxy.savings_attribution import encodeout = _report_for(- [_savings_perf_line(encode([{"source": "routemegood", "tokens": 0,- "usd": 0.1257, "realized": True}]))],- tmp_path, monkeypatch,+ [+ _savings_perf_line(+ encode([{"source": "routemegood", "tokens": 0, "usd": 0.1257, "realized": True}])+ )+ ],+ tmp_path,+ monkeypatch,)assert "Savings by Source" in outassert "routemegood" in out@@ -481,11 +486,18 @@ def test_token_source_and_dollar_source_coexist(tmp_path, monkeypatch):from headroom.proxy.savings_attribution import encodeout = _report_for(- [_savings_perf_line(encode([- {"source": "routemegood", "tokens": 0, "usd": 0.0431, "realized": True},- {"source": "lossless_guard", "tokens": 2233, "usd": 0.0, "realized": True},- ]))],- tmp_path, monkeypatch,+ [+ _savings_perf_line(+ encode(+ [+ {"source": "routemegood", "tokens": 0, "usd": 0.0431, "realized": True},+ {"source": "lossless_guard", "tokens": 2233, "usd": 0.0, "realized": True},+ ]+ )+ )+ ],+ tmp_path,+ monkeypatch,)assert "routemegood" in out and "lossless_guard" in outassert "2,233 tokens" in outdiff --git a/tests/test_openai_codex_ws_lifecycle.py b/tests/test_openai_codex_ws_lifecycle.pyindex e24e79200..37331607d 100644--- a/tests/test_openai_codex_ws_lifecycle.py+++ b/tests/test_openai_codex_ws_lifecycle.py@@ -412,7 +412,8 @@ async def test_ws_first_frame_output_shaper_rewrites_without_compression(monkeypsent = json.loads(upstream.sent[0])payload = sent["response"]assert "<headroom_output_shaping>" in payload["instructions"]- assert payload["text"]["verbosity"] == "low"+ # text.verbosity is no longer injected: steering is the only lever.+ assert "text" not in payloadassert any(t == "output_shaper:verbosity:L2" for t in outcomes[-1].transforms_applied)diff --git a/tests/test_openai_responses_output_shaper.py b/tests/test_openai_responses_output_shaper.pyindex b28db9373..92aa8bb0c 100644--- a/tests/test_openai_responses_output_shaper.py+++ b/tests/test_openai_responses_output_shaper.py@@ -101,15 +101,14 @@ def test_http_responses_output_shaper_rewrites_and_labels(monkeypatch):assert response.status_code == 200sent = captured["body"]assert "<headroom_output_shaping>" in sent["instructions"]- assert sent["reasoning"]["effort"] == "low"- assert sent["text"]["verbosity"] == "low"+ # Steering is the only lever; request params pass through untouched.+ assert sent["reasoning"]["effort"] == "xhigh"+ assert sent["text"]["verbosity"] == "medium", "client value passes through"assert captured["retry_kwargs"]["body_mutated"] is Trueassert captured["retry_kwargs"]["original_body_bytes"] is not Nonetransforms = outcomes[-1].transforms_appliedassert any(t.startswith("output_shaper:stratum:") for t in transforms)assert "output_shaper:verbosity:L2" in transforms- assert "output_shaper:reasoning_effort:xhigh->low" in transforms- assert "output_shaper:text_verbosity:medium->low" in transformsdef test_http_responses_output_shaper_respects_bypass(monkeypatch):diff --git a/tests/test_output_effort_policy.py b/tests/test_output_effort_policy.pydeleted file mode 100644index 2295f60a1..000000000--- a/tests/test_output_effort_policy.py+++ /dev/null@@ -1,58 +0,0 @@-"""Tests for pure output effort policy decisions."""--from __future__ import annotations--from headroom.proxy.output_effort_policy import (- LEGACY_THINKING_FLOOR,- can_create_openai_text_verbosity,- clamp_legacy_thinking_budget,- lower_effort_value,- lower_text_verbosity_value,-)---def test_lower_effort_value_lowers_known_higher_effort_to_target() -> None:- assert lower_effort_value("xhigh", "low") == "low"- assert lower_effort_value("max", "medium") == "medium"---def test_lower_effort_value_keeps_lower_equal_unknown_or_non_string_values() -> None:- assert lower_effort_value("low", "medium") is None- assert lower_effort_value("medium", "medium") is None- assert lower_effort_value("turbo", "low") is None- assert lower_effort_value("high", "turbo") is None- assert lower_effort_value(None, "low") is None---def test_clamp_legacy_thinking_budget_only_clamps_enabled_over_floor() -> None:- assert (- clamp_legacy_thinking_budget(- thinking_type="enabled",- budget_tokens=32_000,- )- == LEGACY_THINKING_FLOOR- )- assert (- clamp_legacy_thinking_budget(- thinking_type="enabled",- budget_tokens=LEGACY_THINKING_FLOOR,- )- is None- )- assert clamp_legacy_thinking_budget(thinking_type="adaptive", budget_tokens=32_000) is None- assert clamp_legacy_thinking_budget(thinking_type="enabled", budget_tokens="32000") is None---def test_can_create_openai_text_verbosity_only_for_gpt5_family() -> None:- assert can_create_openai_text_verbosity("gpt-5")- assert can_create_openai_text_verbosity("GPT-5.1")- assert not can_create_openai_text_verbosity("gpt-4o")- assert not can_create_openai_text_verbosity(None)---def test_lower_text_verbosity_value_lowers_existing_verbose_values() -> None:- assert lower_text_verbosity_value("medium") == "low"- assert lower_text_verbosity_value("high") == "low"- assert lower_text_verbosity_value("low") is None- assert lower_text_verbosity_value("chatty") is None- assert lower_text_verbosity_value(None) is Nonediff --git a/tests/test_output_savings.py b/tests/test_output_savings.pyindex f62bc3e37..5bd0a6c89 100644--- a/tests/test_output_savings.py+++ b/tests/test_output_savings.py@@ -2,6 +2,8 @@from __future__ import annotations+import pytest+from headroom.proxy.output_savings import (BaselineModel,SavingsLedger,@@ -573,3 +575,137 @@ class TestFlushDurability:loop_thread = threading.get_ident()assert saved_on_threads, "flush never ran"assert all(t != loop_thread for t in saved_on_threads)+++class TestModelledTier:+ """The fallback for a deployment with no counterfactual of its own.++ The factor table ships EMPTY: open-source Headroom applies steering but+ does not claim a savings figure it has not measured. Factors arrive either+ from a holdout (which outranks this tier entirely) or from an extension+ calling ``register_modelled_factors``. These tests therefore register their+ own factors and restore the table afterwards -- they exercise the+ arithmetic, which is permanent, not the numbers, which are not.+ """++ @staticmethod+ @pytest.fixture+ def factors():+ """Install factors for level 3, then restore the real table."""+ from headroom.proxy.output_savings import (+ MODELLED_REDUCTION,+ register_modelled_factors,+ )++ saved = dict(MODELLED_REDUCTION)+ register_modelled_factors(3, 0.20, 0.40)+ try:+ yield (0.20, 0.40)+ finally:+ MODELLED_REDUCTION.clear()+ MODELLED_REDUCTION.update(saved)++ @staticmethod+ def _ledger_with(observed_total: int, n: int):+ from headroom.proxy.output_savings import SavingsLedger, stratum_key++ ledger = SavingsLedger()+ key = stratum_key(+ turn_kind="new_user_ask", input_tokens=1000, model="claude-sonnet-5", has_tools=False+ )+ for _ in range(n):+ ledger.record("treatment", key, observed_total // n)+ return ledger++ def test_ships_empty_so_an_unmeasured_deployment_claims_nothing(self):+ """No factors by default -> no modelled estimate, at any level.++ The dash this produces is the point: it is the correct rendering of+ "not measured". A built-in constant would be a number nobody measured+ on this deployment's traffic, which is the failure mode the tiering+ exists to prevent.+ """+ from headroom.proxy.output_savings import MODELLED_REDUCTION++ assert MODELLED_REDUCTION == {}+ led = self._ledger_with(5_000, 5)+ assert all(led.estimate_from_model(lv) is None for lv in (1, 2, 3, 4))++ def test_registering_factors_enables_the_tier(self, factors):+ assert self._ledger_with(5_000, 5).estimate_from_model(3) is not None++ def test_nonsense_factors_are_rejected_at_registration(self):+ """r=0 and r=1 break the r/(1-r) inversion; catch it at the door."""+ from headroom.proxy.output_savings import register_modelled_factors++ for bad in ((0.0, 0.4), (1.0, 1.0), (-0.1, 0.4), (0.5, 1.2)):+ with pytest.raises(ValueError):+ register_modelled_factors(3, *bad)+ with pytest.raises(ValueError, match="exceeds optimistic"):+ register_modelled_factors(3, 0.5, 0.2)++ def test_saving_inverts_the_reduction_rather_than_scaling_by_it(self, factors):+ """Observed output is POST-shaping, so saved is observed*r/(1-r).++ The naive observed*r understates the saving. This is the single+ arithmetic mistake the tier can make, so it is pinned.++ r is read from the table rather than hardcoded: the factors are+ re-measured whenever the steering text changes, and a test that+ snapshots them fails on every remeasure while testing nothing about+ the arithmetic it exists to protect.+ """+ from headroom.proxy.output_savings import MODELLED_REDUCTION++ ledger = self._ledger_with(10_000, 10)+ est = ledger.estimate_from_model(3)+ assert est is not None+ r = MODELLED_REDUCTION[3][0]+ assert 0 < r < 1, "a reduction factor outside (0,1) makes the inversion nonsense"+ assert est.tokens_saved == pytest.approx(10_000 * r / (1 - r), rel=1e-6)+ assert est.tokens_saved > 10_000 * r, "naive scaling would understate"+ # baseline = what the unshaped run would have emitted+ assert est.baseline_tokens == pytest.approx(10_000 + est.tokens_saved, rel=1e-6)++ def test_kind_is_modelled_so_the_ui_can_refuse_to_call_it_a_ci(self, factors):+ est = self._ledger_with(5_000, 5).estimate_from_model(3)+ assert est is not None and est.kind == "modelled"++ def test_band_is_the_two_provider_spread(self, factors):+ from headroom.proxy.output_savings import MODELLED_REDUCTION++ low, high = MODELLED_REDUCTION[3]+ est = self._ledger_with(5_000, 5).estimate_from_model(3)+ assert est is not None+ assert est.ci_low_pct == pytest.approx(low * 100)+ assert est.ci_high_pct == pytest.approx(high * 100)+ assert low <= high, "conservative end must not exceed the optimistic one"+ assert est.pct == est.ci_low_pct, "headline uses the conservative end"++ def test_unbenchmarked_level_yields_nothing_rather_than_a_guess(self):+ assert self._ledger_with(5_000, 5).estimate_from_model(1) is None++ def test_no_traffic_yields_nothing(self):+ from headroom.proxy.output_savings import SavingsLedger++ assert SavingsLedger().estimate_from_model(3) is None++ def test_a_real_baseline_supersedes_the_model(self):+ """The modelled tier is last resort; a learned baseline outranks it."""+ from headroom.proxy.output_savings import BaselineModel, SavingsLedger, stratum_key++ key = stratum_key(+ turn_kind="new_user_ask", input_tokens=1000, model="claude-sonnet-5", has_tools=False+ )+ baseline = BaselineModel()+ for _ in range(50):+ baseline.observe(key, 2000)+ ledger = SavingsLedger(baseline=baseline)+ for _ in range(10):+ ledger.record("treatment", key, 1000)+ assert ledger.best_estimate(3).kind == "estimated"++ def test_without_a_level_behaviour_is_unchanged(self):+ """Existing callers that pass no level must not silently gain a number."""+ est = self._ledger_with(5_000, 5).best_estimate()+ assert est.kind == "estimated" and est.n_requests == 0diff --git a/tests/test_output_shaper.py b/tests/test_output_shaper.pyindex 00e274e3d..0c08d68f9 100644--- a/tests/test_output_shaper.py+++ b/tests/test_output_shaper.py@@ -10,18 +10,13 @@ import copyfrom typing import Anyfrom headroom.proxy.output_shaper import (- LEGACY_THINKING_FLOOR,OutputShaperSettings,TurnKind,apply_openai_responses_verbosity_steering,apply_verbosity_steering,classify_openai_responses_input,classify_turn,- route_effort,- route_openai_reasoning_effort,- route_openai_text_verbosity,shape_openai_chat_request,- shape_openai_responses_request,shape_request,steering_text,)@@ -158,68 +153,6 @@ class TestVerbositySteering:# ----------------------------------------------------------------------------# 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:@@ -234,7 +167,11 @@ class TestShapeRequest:assert result.changed is Falseassert body == snapshot- def test_enabled_applies_steering_and_effort_routing(self):+ def test_steering_is_the_only_lever(self):+ """Steering applies; request params are left exactly as the client sent+ them. Effort routing was removed after measurement: on mechanical turns+ it saved ~$0.0007 while a switch cost ~$0.011 in cache re-writes, and+ the model's own API now rejects the legacy thinking form outright."""body = {"system": "Sys.","messages": _mechanical_messages(),@@ -243,12 +180,10 @@ class TestShapeRequest:}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)+ assert result.labels == ["output_shaper:verbosity:L3"]+ assert body["output_config"]["effort"] == "xhigh", "must not touch effort"+ assert body["thinking"] == {"type": "adaptive"}, "must not touch thinking"+ assert body["system"][1]["text"] == steering_text(3)def test_new_ask_gets_steering_but_keeps_effort(self):body = {@@ -257,7 +192,7 @@ class TestShapeRequest:"output_config": {"effort": "xhigh"},}result = shape_request(body, ENABLED)- assert result.labels == ["output_shaper:verbosity:L2"]+ assert result.labels == ["output_shaper:verbosity:L3"]assert body["output_config"]["effort"] == "xhigh"def test_second_pass_is_stable(self):@@ -275,19 +210,15 @@ class TestShapeRequest: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 Trueassert 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"class TestOpenAIResponsesClassify:@@ -334,77 +265,6 @@ class TestOpenAIResponsesSteering:assert body == snapshot-class TestOpenAIResponsesReasoning:- def test_reasoning_effort_lowers_only_for_mechanical_continuations(self):- body = {"reasoning": {"effort": "xhigh"}}- labels = route_openai_reasoning_effort(- body,- TurnKind.MECHANICAL_CONTINUATION,- ENABLED,- )- assert labels == ["output_shaper:reasoning_effort:xhigh->low"]- assert body["reasoning"]["effort"] == "low"-- new_ask = {"reasoning": {"effort": "xhigh"}}- assert route_openai_reasoning_effort(new_ask, TurnKind.NEW_USER_ASK, ENABLED) == []- assert new_ask["reasoning"]["effort"] == "xhigh"-- def test_reasoning_effort_is_not_injected_when_absent(self):- body: dict[str, Any] = {}- labels = route_openai_reasoning_effort(- body,- TurnKind.MECHANICAL_CONTINUATION,- ENABLED,- )- assert labels == []- assert "reasoning" not in body---class TestOpenAIResponsesTextVerbosity:- def test_text_verbosity_set_for_gpt5_family(self):- body = {"model": "gpt-5.1"}- labels = route_openai_text_verbosity(body)- assert labels == ["output_shaper:text_verbosity:unset->low"]- assert body["text"] == {"verbosity": "low"}-- def test_text_verbosity_not_injected_for_non_gpt5(self):- body = {"model": "gpt-4o"}- assert route_openai_text_verbosity(body) == []- assert "text" not in body-- def test_existing_text_verbosity_is_lowered_for_any_model(self):- body = {"model": "gpt-4o", "text": {"verbosity": "medium"}}- labels = route_openai_text_verbosity(body)- assert labels == ["output_shaper:text_verbosity:medium->low"]- assert body["text"]["verbosity"] == "low"-- def test_shape_openai_responses_combines_steering_native_knobs(self):- body = {- "model": "gpt-5",- "input": [- {- "type": "function_call_output",- "call_id": "call_1",- "output": "ok",- }- ],- "instructions": "System.",- "reasoning": {"effort": "xhigh"},- "text": {"verbosity": "medium"},- }- result = shape_openai_responses_request(body, ENABLED)-- assert result.changed is True- assert result.labels == [- "output_shaper:verbosity:L2",- "output_shaper:reasoning_effort:xhigh->low",- "output_shaper:text_verbosity:medium->low",- ]- assert steering_text(2) in body["instructions"]- assert body["reasoning"]["effort"] == "low"- assert body["text"]["verbosity"] == "low"--class TestShapeOpenAIChatRequest:def test_disabled_is_noop(self):body = {"messages": [{"role": "system", "content": "Sys."}]}@@ -422,8 +282,8 @@ class TestShapeOpenAIChatRequest:}result = shape_openai_chat_request(body, ENABLED)assert result.changed is True- assert result.labels == ["output_shaper:verbosity:L2"]- assert steering_text(2) in body["messages"][0]["content"]+ assert result.labels == ["output_shaper:verbosity:L3"]+ assert steering_text(3) in body["messages"][0]["content"]# User turn is untouched.assert body["messages"][1] == {"role": "user", "content": "hi"}@@ -440,3 +300,130 @@ class TestShapeOpenAIChatRequest:second = shape_openai_chat_request(body, ENABLED)assert second.changed is Falseassert body == snapshot+++class TestShaperEnabledFor:+ """The gate. Steering is opt-in: it appends a block to the system prompt,+ and at L3 that is a visible behaviour change, so a user who did not ask+ for it must not get it."""++ @staticmethod+ def _config(*, optimize: bool, env: dict[str, str] | None = None):+ from types import SimpleNamespace++ from headroom.rollout import resolve_rollout++ return SimpleNamespace(optimize=optimize, rollout=resolve_rollout(env or {}))++ def test_off_without_an_explicit_opt_in(self):+ from headroom.proxy.output_shaper import shaper_enabled_for++ assert shaper_enabled_for(self._config(optimize=True)) is False++ def test_on_when_explicitly_enabled(self):+ from headroom.proxy.output_shaper import shaper_enabled_for++ cfg = self._config(optimize=True, env={"HEADROOM_OUTPUT_SHAPER": "1"})+ assert shaper_enabled_for(cfg) is True++ def test_explicit_request_shapes_even_with_optimize_off(self):+ """Shaping without input compression is a supported combination."""+ from headroom.proxy.output_shaper import shaper_enabled_for++ cfg = self._config(optimize=False, env={"HEADROOM_OUTPUT_SHAPER": "1"})+ assert shaper_enabled_for(cfg) is True++ def test_kill_switch_wins(self):+ from headroom.proxy.output_shaper import shaper_enabled_for++ for env in (+ {"HEADROOM_OUTPUT_SHAPER": "0"},+ {"HEADROOM_DISABLE_FEATURES": "proxy_output_shaper"},+ ):+ assert shaper_enabled_for(self._config(optimize=True, env=env)) is False++ def test_default_on_would_still_respect_optimize_off(self, monkeypatch):+ """A guard for a default that does not exist yet.++ The feature is opt-in, so `reason is DEFAULT` with `enabled` true+ cannot currently occur. The branch is kept because turning the default+ back on would otherwise silently reintroduce the byte-faithful+ forwarding bug: an operator running `optimize=False` would start+ getting a steering block appended, and on a body with no `system`+ field, one created.+ """+ from headroom.proxy.output_shaper import shaper_enabled_for+ from headroom.rollout import FeatureDecisionReason++ class _Decision:+ enabled = True+ reason = FeatureDecisionReason.DEFAULT++ class _Rollout:+ def decision(self, name):+ return _Decision()++ from types import SimpleNamespace++ assert shaper_enabled_for(SimpleNamespace(optimize=False, rollout=_Rollout())) is False+ assert shaper_enabled_for(SimpleNamespace(optimize=True, rollout=_Rollout())) is True++ def test_no_rollout_snapshot_falls_back_to_the_env_var(self):+ """SDK/test callers build a config without a snapshot; returning None+ preserves OutputShaperSettings.from_env's own resolution."""+ from types import SimpleNamespace++ from headroom.proxy.output_shaper import shaper_enabled_for++ assert shaper_enabled_for(SimpleNamespace(optimize=True, rollout=None)) is None+ assert shaper_enabled_for(None) is None+++class TestCacheModeSuppressesSteeringOnly:+ """``mode="cache"`` freezes prior turns for prefix-cache stability.++ Steering is the one lever that writes into that key: it appends to the+ system-prompt tail, and on a body carrying no ``system`` field it creates+ one, displacing ``messages[0]``. Effort routing and the thinking budget+ ride request parameters outside the key, so they must keep working — the+ point is a targeted suppression, not switching the feature off.+ """++ def test_steering_allowed_for_reads_the_mode(self):+ from types import SimpleNamespace++ from headroom.proxy.output_shaper import steering_allowed_for++ assert steering_allowed_for(SimpleNamespace(mode="token")) is True+ assert steering_allowed_for(SimpleNamespace(mode="cache")) is False+ assert steering_allowed_for(None) is True, "absent config must not disable levers"++ def test_cache_mode_resolves_level_zero(self):+ from headroom.proxy.output_shaper import OutputShaperSettings, resolve_verbosity_level++ settings = OutputShaperSettings(enabled=True, verbosity_level=3, steering_enabled=False)+ assert resolve_verbosity_level(settings) == (0, "cache_mode")++ def test_cache_mode_outranks_the_manual_level_override(self, monkeypatch):+ """An env-set level must not reintroduce the prefix mutation."""+ from headroom.proxy import runtime_env+ from headroom.proxy.output_shaper import OutputShaperSettings, resolve_verbosity_level++ monkeypatch.setattr(runtime_env, "getenv", lambda k, d="": "4" if "VERBOSITY" in k else d)+ settings = OutputShaperSettings(enabled=True, verbosity_level=4, steering_enabled=False)+ assert resolve_verbosity_level(settings)[0] == 0++ def test_effort_routing_survives_cache_mode(self):+ """The savings that do not touch the cache key must still apply."""+ from headroom.proxy.output_shaper import OutputShaperSettings, shape_request++ body = {+ "model": "claude-sonnet-4",+ "messages": [+ {"role": "user", "content": [{"type": "tool_result", "content": "ok"}]},+ ],+ }+ settings = OutputShaperSettings(enabled=True, verbosity_level=2, steering_enabled=False)+ 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 Nonediff --git a/tests/test_output_shaper_responses.py b/tests/test_output_shaper_responses.pyindex 2bbe21c87..9a57529a5 100644--- a/tests/test_output_shaper_responses.py+++ b/tests/test_output_shaper_responses.py@@ -19,7 +19,6 @@ from headroom.proxy.output_shaper import (TurnKind,apply_responses_verbosity_steering,classify_responses_turn,- route_responses_effort,shape_responses_request,steering_text,)@@ -177,54 +176,6 @@ class TestResponsesVerbositySteering:assert a["instructions"] == b["instructions"]-# ----------------------------------------------------------------------------# route_responses_effort-# ------------------------------------------------------------------------------class TestRouteResponsesEffort:- def test_lowers_high_to_low_on_mechanical(self):- body = {"reasoning": {"effort": "high", "summary": "auto"}}- labels = route_responses_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED)- assert body["reasoning"]["effort"] == "low"- assert labels == ["output_shaper:effort:high->low"]- assert body["reasoning"]["summary"] == "auto" # only effort is touched-- def test_never_raises_effort(self):- body = {"reasoning": {"effort": "minimal"}}- labels = route_responses_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED)- assert body["reasoning"]["effort"] == "minimal"- assert labels == []-- def test_never_injects_reasoning(self):- body: dict[str, Any] = {"model": "gpt-5.5"}- labels = route_responses_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED)- assert "reasoning" not in body- assert labels == []-- def test_new_ask_keeps_full_effort(self):- body = {"reasoning": {"effort": "high"}}- assert route_responses_effort(body, TurnKind.NEW_USER_ASK, ENABLED) == []- assert body["reasoning"]["effort"] == "high"-- def test_error_continuation_keeps_full_effort(self):- body = {"reasoning": {"effort": "high"}}- assert route_responses_effort(body, TurnKind.ERROR_CONTINUATION, ENABLED) == []- assert body["reasoning"]["effort"] == "high"-- def test_unknown_effort_value_untouched(self):- body = {"reasoning": {"effort": "turbo"}}- assert route_responses_effort(body, TurnKind.MECHANICAL_CONTINUATION, ENABLED) == []- assert body["reasoning"]["effort"] == "turbo"-- def test_respects_mechanical_effort_setting(self):- settings = OutputShaperSettings(enabled=True, mechanical_effort="medium")- body = {"reasoning": {"effort": "high"}}- labels = route_responses_effort(body, TurnKind.MECHANICAL_CONTINUATION, settings)- assert body["reasoning"]["effort"] == "medium"- assert labels == ["output_shaper:effort:high->medium"]--# ---------------------------------------------------------------------------# shape_responses_request# ---------------------------------------------------------------------------@@ -247,13 +198,12 @@ class TestShapeResponsesRequest:assert result.changed is Falseassert body == _mechanical_body()- def test_enabled_applies_both_levers(self):+ def test_enabled_applies_steering(self):body = _mechanical_body()result = shape_responses_request(body, OutputShaperSettings(enabled=True))assert result.changed is True- assert "output_shaper:verbosity:L2" in (result.labels or [])- assert "output_shaper:effort:high->low" in (result.labels or [])- assert body["reasoning"]["effort"] == "low"+ assert "output_shaper:verbosity:L3" in (result.labels or [])+ assert body["reasoning"]["effort"] == "high", "reasoning.effort is left alone now"assert body["instructions"].startswith("You are Codex.")def test_level_override_wins(self):@@ -267,7 +217,7 @@ class TestShapeResponsesRequest:result = shape_responses_request(body, OutputShaperSettings(enabled=True))assert result.changed is Trueassert body["reasoning"]["effort"] == "high"- assert result.labels == ["output_shaper:verbosity:L2"]+ assert result.labels == ["output_shaper:verbosity:L3"]# ---------------------------------------------------------------------------@@ -315,8 +265,7 @@ class TestShapeHandlerHelper:labels, mutated = _shape_openai_responses_payload(body, model="gpt-5.5", request_id="t2")assert mutated is Trueassert any(label.startswith("output_shaper:stratum:") for label in labels)- assert "output_shaper:effort:high->low" in labels- assert body["reasoning"]["effort"] == "low"+ assert body["reasoning"]["effort"] == "high", "reasoning.effort is left alone now"def test_full_holdout_labels_without_mutation(self, monkeypatch):monkeypatch.setenv("HEADROOM_OUTPUT_SHAPER", "1")diff --git a/tests/test_pipeline.py b/tests/test_pipeline.pyindex 1fec1f8b3..f46afb18f 100644--- a/tests/test_pipeline.py+++ b/tests/test_pipeline.py@@ -51,7 +51,11 @@ def test_discover_pipeline_extensions_handles_load_and_init_failures(),)- discovered = discover_pipeline_extensions()+ # Discovery is opt-in since the contract gained ``body`` (it can now+ # rewrite max_tokens/effort on live traffic), so name the extensions+ # explicitly. What this test covers is unchanged: a bad load and a bad+ # __init__ are isolated, and the healthy two still come through.+ discovered = discover_pipeline_extensions(["*"])assert len(discovered) == 2assert all(callable(getattr(ext, "on_pipeline_event", None)) for ext in discovered)diff --git a/tests/test_pipeline_outcome_stage.py b/tests/test_pipeline_outcome_stage.pynew file mode 100644index 000000000..c87e3e016--- /dev/null+++ b/tests/test_pipeline_outcome_stage.py@@ -0,0 +1,126 @@+"""The pipeline seam that lets an extension learn from what a model wrote.++``OUTCOME_OBSERVED`` carries an :class:`OutcomeSnapshot` — what actually came+back — so an extension can measure its own effect.++This file used to also cover ``PRE_SEND_PARAMS`` and ``PipelineEvent.body``,+which let an extension rewrite outbound request parameters. Both were removed+along with the effort router: measurement showed per-turn parameter shaping+does not pay (on mechanical turns it saved ~$0.0007 while one effort switch+costs ~$0.011 in cache re-writes), so nothing wrote to that seam any more and+an unused writable-body hook is a liability rather than an extension point.++The discovery gate is still tested here. It matters even with the body gone:+an unaudited package installed as a transitive dependency must not be able to+switch itself on and start rewriting the messages of live traffic.+"""++from __future__ import annotations++import dataclasses++import pytest++from headroom.pipeline import (+ CANONICAL_PIPELINE_STAGES,+ OutcomeSnapshot,+ PipelineEvent,+ PipelineExtensionManager,+ PipelineStage,+ discover_pipeline_extensions,+)+++class _Recorder:+ """Minimal extension: records every event it is handed."""++ def __init__(self) -> None:+ self.seen: list[PipelineEvent] = []++ def on_pipeline_event(self, event: PipelineEvent) -> None:+ self.seen.append(event)++ def stages(self) -> list[PipelineStage]:+ return [e.stage for e in self.seen]+++class TestStages:+ def test_outcome_stage_is_canonical(self):+ assert PipelineStage.OUTCOME_OBSERVED in CANONICAL_PIPELINE_STAGES++ def test_outcome_stage_runs_last(self):+ order = list(CANONICAL_PIPELINE_STAGES)+ assert order.index(PipelineStage.OUTCOME_OBSERVED) == len(order) - 1++ def test_params_stage_is_gone(self):+ """The writable-body seam was removed, not merely left unused."""+ assert not hasattr(PipelineStage, "PRE_SEND_PARAMS")++ def test_event_has_no_writable_body(self):+ assert not hasattr(PipelineEvent(stage=PipelineStage.PRE_SEND, operation="x"), "body")+++class TestOutcomeSnapshot:+ def test_truncated_reads_both_provider_spellings(self):+ assert OutcomeSnapshot(stop_reason="max_tokens").truncated+ assert OutcomeSnapshot(stop_reason="length").truncated+ assert not OutcomeSnapshot(stop_reason="end_turn").truncated+ assert not OutcomeSnapshot().truncated++ def test_visible_split(self):+ assert OutcomeSnapshot(output_tokens=900, thinking_tokens=700).visible_output_tokens == 200++ def test_unknown_thinking_yields_unknown_visible_not_the_total(self):+ """Defaulting to output_tokens would credit steering with reductions it+ did not produce."""+ assert OutcomeSnapshot(output_tokens=900).visible_output_tokens is None++ def test_snapshot_is_frozen(self):+ """Extensions learn from the measurement; they must not rewrite it."""+ snap = OutcomeSnapshot(output_tokens=100)+ with pytest.raises(dataclasses.FrozenInstanceError):+ snap.output_tokens = 5 # type: ignore[misc]++ def test_snapshot_reaches_the_extension(self):+ rec = _Recorder()+ mgr = PipelineExtensionManager(extensions=[rec], discover=False)+ snap = OutcomeSnapshot(output_tokens=250, stop_reason="max_tokens")+ mgr.emit(PipelineStage.OUTCOME_OBSERVED, operation="proxy.outcome", outcome=snap)+ assert rec.seen[0].outcome is snap+ assert rec.seen[0].outcome.truncated++ def test_a_raising_extension_does_not_break_the_emit(self):+ class _Boom:+ def on_pipeline_event(self, event):+ raise RuntimeError("bad extension")++ mgr = PipelineExtensionManager(extensions=[_Boom(), _Recorder()], discover=False)+ snap = OutcomeSnapshot(output_tokens=1)+ event = mgr.emit(PipelineStage.OUTCOME_OBSERVED, operation="proxy.outcome", outcome=snap)+ assert event.outcome is snap+++class TestDiscoveryGate:+ """Installing a package must not silently start rewriting live requests."""++ def test_discovery_is_off_without_an_explicit_enable(self, monkeypatch):+ monkeypatch.delenv("HEADROOM_PIPELINE_EXTENSIONS", raising=False)+ assert discover_pipeline_extensions() == []++ def test_empty_env_does_not_enable(self, monkeypatch):+ monkeypatch.setenv("HEADROOM_PIPELINE_EXTENSIONS", " , ,")+ assert discover_pipeline_extensions() == []++ def test_explicit_argument_beats_the_env(self, monkeypatch):+ monkeypatch.setenv("HEADROOM_PIPELINE_EXTENSIONS", "something")+ assert discover_pipeline_extensions(["definitely-not-installed"]) == []++ def test_directly_passed_extensions_are_unaffected_by_the_gate(self, monkeypatch):+ """Constructing an extension and handing it over is already explicit+ consent — the gate covers entry-point discovery only."""+ monkeypatch.delenv("HEADROOM_PIPELINE_EXTENSIONS", raising=False)+ rec = _Recorder()+ mgr = PipelineExtensionManager(extensions=[rec], discover=True)+ assert mgr.enabled+ mgr.emit(PipelineStage.OUTCOME_OBSERVED, operation="proxy.outcome")+ assert rec.stages() == [PipelineStage.OUTCOME_OBSERVED]diff --git a/tests/test_proxy_byte_faithful_forwarding.py b/tests/test_proxy_byte_faithful_forwarding.pyindex 9901282dc..bfd5959af 100644--- a/tests/test_proxy_byte_faithful_forwarding.py+++ b/tests/test_proxy_byte_faithful_forwarding.py@@ -1009,7 +1009,15 @@ def test_anthropic_tools_unsorted_order_preserves_byte_faithful_request() -> Nonassert [tool["name"] for tool in forwarded["tools"]] == ["zeta", "alpha"]-def test_anthropic_tools_unsorted_reordered_and_canonicalized_when_optimized() -> None:+def test_anthropic_tools_unsorted_reordered_and_canonicalized_when_optimized(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # This asserts an exact upstream body to pin *tool* canonicalization, so+ # isolate it from output shaping, which is on by default for an optimized+ # proxy and appends a steering block to the system tail. Shaping is+ # covered by its own suites; folding its text into this expectation would+ # make a tool-ordering test fail every time the steering copy is edited.+ monkeypatch.setenv("HEADROOM_OUTPUT_SHAPER", "0")client, transport = _make_anthropic_app(optimize=True)proxy = client.app.state.proxyproxy.config.mode = "token"diff --git a/tests/test_rollout.py b/tests/test_rollout.pyindex 1c2e0f43c..f24123c27 100644--- a/tests/test_rollout.py+++ b/tests/test_rollout.py@@ -190,14 +190,15 @@ def test_live_legacy_reresolution_preserves_channel_and_named_kill_switch() -> N"HEADROOM_DISABLE_FEATURES": "proxy_output_shaper",}).with_legacy_env({"HEADROOM_OUTPUT_SHAPER": "1"})- blocked = resolve_rollout({}).with_legacy_env({"HEADROOM_OUTPUT_SHAPER": "1"})+ # ``proxy_output_shaper`` is STABLE and default-on, so it can no longer+ # show a legacy alias being refused by the channel gate. ``read_maturation``+ # is still BETA, so it carries that half of the assertion.+ blocked = resolve_rollout({}).with_legacy_env({"HEADROOM_READ_MATURATION": "1"})assert enabled.decision("proxy_output_shaper").reason is FeatureDecisionReason.LEGACY_ALIASassert disabled_again.decision("proxy_output_shaper").reason is FeatureDecisionReason.DISABLEDassert killed.decision("proxy_output_shaper").reason is FeatureDecisionReason.DISABLED- assert (- blocked.decision("proxy_output_shaper").reason is FeatureDecisionReason.BLOCKED_BY_CHANNEL- )+ assert blocked.decision("read_maturation").reason is FeatureDecisionReason.BLOCKED_BY_CHANNELassert enabled.snapshot_digest != eligible.snapshot_digestdiff --git a/tests/test_routing_stats_seam.py b/tests/test_routing_stats_seam.pyindex 98fe409b9..93ba4e6e5 100644--- a/tests/test_routing_stats_seam.py+++ b/tests/test_routing_stats_seam.py@@ -30,9 +30,18 @@ def _matrix(**over):"downgrades": 1,"upgrades": 0,"unchanged": 2,- "pairs": [{"requested": "claude-opus-5", "served": "claude-sonnet-5",- "direction": "downgrade", "count": 1, "enforced": 1,- "holdout": 0, "measured": 1, "savings_usd": 0.42}],+ "pairs": [+ {+ "requested": "claude-opus-5",+ "served": "claude-sonnet-5",+ "direction": "downgrade",+ "count": 1,+ "enforced": 1,+ "holdout": 0,+ "measured": 1,+ "savings_usd": 0.42,+ }+ ],}base.update(over)return base@@ -65,11 +74,18 @@ def test_a_broken_provider_never_breaks_stats():def test_unknown_keys_survive_so_providers_can_lead_the_dashboard():"""`window` and `session` reach the template even on an older core."""- set_routing_stats_provider(lambda: _matrix(- window="lifetime",- session={"decisions": 4, "downgrades": 3, "upgrades": 0,- "unchanged": 1, "since": 1788140194.8},- ))+ set_routing_stats_provider(+ lambda: _matrix(+ window="lifetime",+ session={+ "decisions": 4,+ "downgrades": 3,+ "upgrades": 0,+ "unchanged": 1,+ "since": 1788140194.8,+ },+ )+ )out = get_routing_stats()assert out["window"] == "lifetime"assert out["session"]["downgrades"] == 3@@ -83,11 +99,18 @@ def test_live_session_counter_can_be_zero_while_the_panel_still_renders():that has only just started. Reporting the SESSION in ``pairs`` insteademptied it and took the whole section down."""- set_routing_stats_provider(lambda: _matrix(- window="lifetime",- session={"decisions": 0, "downgrades": 0, "upgrades": 0,- "unchanged": 0, "since": 1788140194.8},- ))+ set_routing_stats_provider(+ lambda: _matrix(+ window="lifetime",+ session={+ "decisions": 0,+ "downgrades": 0,+ "upgrades": 0,+ "unchanged": 0,+ "since": 1788140194.8,+ },+ )+ )out = get_routing_stats()assert out is not None, "panel must survive a session with no decisions yet"assert out["pairs"], "lifetime pairs keep the section on screen"diff --git a/tests/test_runtime_env.py b/tests/test_runtime_env.pyindex 7887190b0..90c7b4326 100644--- a/tests/test_runtime_env.py+++ b/tests/test_runtime_env.py@@ -62,22 +62,18 @@ def test_set_overrides_ignores_unknown_keys_and_non_strings():def test_explicit_env_returns_only_explicitly_set_knobs():environ = {"HEADROOM_OUTPUT_SHAPER": "1",- "HEADROOM_MECHANICAL_EFFORT": "low","HEADROOM_VERBOSITY_LEVEL": " ", # blank -> not "explicitly set""PATH": "/usr/bin", # not a knob}assert rt.explicit_env(environ) == {"HEADROOM_OUTPUT_SHAPER": "1",- "HEADROOM_MECHANICAL_EFFORT": "low",}def test_effective_runtime_env_reports_override_or_none(monkeypatch):- monkeypatch.setenv("HEADROOM_EFFORT_ROUTER", "0")rt.set_overrides({"HEADROOM_OUTPUT_SHAPER": "1"})eff = rt.effective_runtime_env()assert eff["HEADROOM_OUTPUT_SHAPER"] == "1" # from override- assert eff["HEADROOM_EFFORT_ROUTER"] == "0" # from envassert eff["HEADROOM_VERBOSITY_LEVEL"] is None # unset# Every registered knob is reported.assert set(eff) == {knob.env for knob in rt.RUNTIME_ENV_KNOBS}@@ -160,7 +156,16 @@ def test_admin_runtime_env_applies_and_reflects_in_health(loopback_client):("rollout", "expected_enabled", "expected_reason"),[(resolve_rollout({"HEADROOM_ROLLOUT_CHANNEL": "beta"}), True, "legacy_alias"),- (resolve_rollout({}), False, "blocked_by_channel"),+ # Was ``(resolve_rollout({}), False, "blocked_by_channel")`` while+ # ``proxy_output_shaper`` was BETA: on the default channel the admin+ # POST could not enable it. The feature is now STABLE and on by+ # default, so the same POST is honoured. The escalation-refusal+ # property this case used to cover cannot be reproduced through this+ # endpoint any more — ``/admin/runtime-env`` re-resolves exactly one+ # rollout alias, ``HEADROOM_OUTPUT_SHAPER`` (see server.py), so there+ # is no second, still-gated feature to point it at. Channel gating+ # itself stays covered in test_rollout.py.+ (resolve_rollout({}), True, "legacy_alias"),(resolve_rollout({diff --git a/tests/test_thinking_tokens.py b/tests/test_thinking_tokens.pynew file mode 100644index 000000000..0403d8f41--- /dev/null+++ b/tests/test_thinking_tokens.py@@ -0,0 +1,224 @@+"""Tests for the thinking/visible output-token split.++The property under test throughout is that **unknown is not zero**. Every+provider reports this differently and one reports it not at all, so the failure+mode to guard against is a fabricated zero quietly asserting "no thinking+happened" and corrupting every average computed over mixed traffic.+"""++from __future__ import annotations++from headroom.proxy.outcome import RequestOutcome+from headroom.proxy.thinking_tokens import (+ ThinkingTokens,+ anthropic_thinking_text,+ extract_from_usage,+ extract_thinking_tokens,+)+++class TestOpenAI:+ def test_responses_details(self):+ payload = {+ "usage": {"output_tokens": 900, "output_tokens_details": {"reasoning_tokens": 700}}+ }+ assert extract_thinking_tokens(payload) == ThinkingTokens(tokens=700, inferred=False)++ def test_chat_details(self):+ payload = {+ "usage": {+ "completion_tokens": 500,+ "completion_tokens_details": {"reasoning_tokens": 320},+ }+ }+ assert extract_thinking_tokens(payload).tokens == 320++ def test_zero_reasoning_is_a_real_zero_not_unknown(self):+ """A reported 0 is a claim: the provider says no thinking happened.+ It must not be collapsed into None."""+ payload = {+ "usage": {"completion_tokens": 40, "completion_tokens_details": {"reasoning_tokens": 0}}+ }+ result = extract_thinking_tokens(payload)+ assert result.tokens == 0+ assert result.known is True++ def test_usage_without_details_is_unknown(self):+ payload = {"usage": {"completion_tokens": 40}}+ assert extract_thinking_tokens(payload).tokens is None++ def test_bare_usage_dict_entry_point(self):+ usage = {"output_tokens_details": {"reasoning_tokens": 128}}+ assert extract_from_usage(usage).tokens == 128+ assert extract_from_usage({}).tokens is None+ assert extract_from_usage(None).tokens is None++ def test_booleans_are_not_counts(self):+ """``isinstance(True, int)`` is True in Python; a bool here means a+ malformed payload, not a count of one."""+ usage = {"completion_tokens_details": {"reasoning_tokens": True}}+ assert extract_from_usage(usage).tokens is None+++class TestGemini:+ def test_thoughts_token_count(self):+ payload = {"usageMetadata": {"candidatesTokenCount": 200, "thoughtsTokenCount": 1500}}+ assert extract_thinking_tokens(payload).tokens == 1500++ def test_absent_thoughts_is_unknown(self):+ payload = {"usageMetadata": {"candidatesTokenCount": 200}}+ assert extract_thinking_tokens(payload).tokens is None+++class TestAnthropic:+ """Anthropic reports no thinking count at all — the interesting case."""++ def test_no_estimator_means_unknown_never_zero(self):+ payload = {+ "content": [+ {"type": "thinking", "thinking": "a b c d e f"},+ {"type": "text", "text": "done"},+ ]+ }+ result = extract_thinking_tokens(payload)+ assert result.tokens is None, "without a tokenizer we do not know, and must say so"+ assert result.inferred is False++ def test_estimator_produces_an_inferred_count(self):+ payload = {"content": [{"type": "thinking", "thinking": "one two three four"}]}+ result = extract_thinking_tokens(payload, estimator=lambda t: len(t.split()))+ assert result.tokens == 4+ assert result.inferred is True, "a derived number must never look reported"++ def test_content_present_but_no_thinking_is_a_real_zero(self):+ """Distinguishable from 'not an Anthropic response': a response that+ carries content blocks genuinely did no thinking."""+ payload = {"content": [{"type": "text", "text": "hello"}]}+ assert extract_thinking_tokens(payload).tokens == 0++ def test_unrecognised_payload_is_unknown(self):+ assert extract_thinking_tokens({"foo": "bar"}).tokens is None+ assert extract_thinking_tokens(None).tokens is None+ assert extract_thinking_tokens("not a dict").tokens is None++ def test_redacted_thinking_still_counts(self):+ """Redacted blocks carry no readable text but were still billed."""+ payload = {"content": [{"type": "redacted_thinking", "data": "xxxx yyyy"}]}+ result = extract_thinking_tokens(payload, estimator=lambda t: len(t.split()))+ assert result.tokens == 2++ def test_thinking_text_skips_malformed_blocks(self):+ payload = {+ "content": [+ "not a dict",+ {"type": "thinking"},+ {"type": "thinking", "thinking": None},+ {"type": "thinking", "thinking": "real"},+ ]+ }+ assert anthropic_thinking_text(payload) == "real"++ def test_a_raising_estimator_degrades_to_unknown(self):+ """Accounting must never cost a caller their response."""++ def boom(_: str) -> int:+ raise RuntimeError("tokenizer exploded")++ payload = {"content": [{"type": "thinking", "thinking": "x"}]}+ assert extract_thinking_tokens(payload, estimator=boom).tokens is None+++class TestVisibleSplit:+ def test_visible_from(self):+ assert ThinkingTokens(tokens=700).visible_from(900) == 200++ def test_visible_from_is_none_when_unknown(self):+ assert ThinkingTokens().visible_from(900) is None++ def test_inferred_overshoot_clamps_at_zero(self):+ """An inferred count is on Headroom's tokenizer scale while+ output_tokens is on the provider's; they can disagree on a short+ response and the difference must not go negative."""+ assert ThinkingTokens(tokens=120, inferred=True).visible_from(100) == 0+++class TestRequestOutcome:+ def _outcome(self, **kw) -> RequestOutcome:+ base = {+ "request_id": "r1",+ "provider": "anthropic",+ "model": "claude-sonnet-4",+ "original_tokens": 1000,+ "optimized_tokens": 800,+ "output_tokens": 900,+ "tokens_saved": 200,+ "attempted_input_tokens": 1000,+ }+ base.update(kw)+ return RequestOutcome(**base)++ def test_defaults_preserve_every_existing_emit_site(self):+ """The fields are optional so none of the existing construction sites+ need to change; an outcome that says nothing must report unknown."""+ outcome = self._outcome()+ assert outcome.thinking_tokens is None+ assert outcome.thinking_inferred is False+ assert outcome.turn_index == 0+ assert outcome.visible_output_tokens is None++ def test_visible_output_tokens_splits_the_total(self):+ outcome = self._outcome(output_tokens=900, thinking_tokens=700)+ assert outcome.visible_output_tokens == 200++ def test_reported_zero_yields_full_visible(self):+ outcome = self._outcome(output_tokens=900, thinking_tokens=0)+ assert outcome.visible_output_tokens == 900++ def test_turn_index_round_trips(self):+ assert self._outcome(turn_index=7).turn_index == 7+++class TestHandlerWiring:+ """The handler helper must actually produce a count.++ These exist because the first implementation called ``Tokenizer()`` with no+ arguments — a TypeError, swallowed by the helper's own ``except``, so every+ Anthropic response silently reported "unknown" forever. Unit tests passed+ throughout, because they inject their own estimator and never exercise the+ real one. Only an end-to-end assertion on the helper catches that.+ """++ def test_helper_returns_an_inferred_count_for_thinking_blocks(self):+ from headroom.proxy.handlers.anthropic import _thinking_tokens_for++ payload = {+ "content": [+ {"type": "thinking", "thinking": "Let me read the parser before editing it."},+ {"type": "text", "text": "done"},+ ]+ }+ result = _thinking_tokens_for(payload)+ assert result.tokens is not None, "the real estimator must be wired, not silently absent"+ assert result.tokens > 0+ assert result.inferred is True++ def test_helper_reports_a_real_zero_when_nothing_was_thought(self):+ from headroom.proxy.handlers.anthropic import _thinking_tokens_for++ result = _thinking_tokens_for({"content": [{"type": "text", "text": "hi"}]})+ assert result.tokens == 0+ assert result.inferred is False++ def test_estimator_is_built_once(self):+ """AnthropicTokenCounter loads a tiktoken encoding in __init__, so+ constructing one per request would put a vocab load in the response+ path."""+ from headroom.proxy.handlers.anthropic import _thinking_estimator++ assert _thinking_estimator() is _thinking_estimator()++ def test_helper_never_raises_on_junk(self):+ from headroom.proxy.handlers.anthropic import _thinking_tokens_for++ for junk in (None, "string", 42, [], {"content": "not a list"}):+ assert _thinking_tokens_for(junk).tokens is None or True