Skip to content

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.

fix(output-savings): count conversations, not requests, in the holdout gate (#3460)

gglucass53631adb1531
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.py
index 26ee43acb..0ed1324a5 100644
--- a/headroom/proxy/handlers/anthropic.py
+++ b/headroom/proxy/handlers/anthropic.py
@@ -3200,6 +3200,7 @@ class AnthropicHandlerMixin:
from headroom.proxy.output_savings import (
assign_arm,
conversation_key_from_body,
+ conversation_label,
stratum_key,
stratum_label,
)
@@ -3226,7 +3227,8 @@ class AnthropicHandlerMixin:
_holdout = float(runtime_env.getenv("HEADROOM_OUTPUT_HOLDOUT", "0") or "0")
except ValueError:
_holdout = 0.0
- _arm = assign_arm(conversation_key_from_body(body), _holdout)
+ _conversation = conversation_key_from_body(body)
+ _arm = assign_arm(_conversation, _holdout)
# Stratum from request features observable now (mirrors the
# offline baseline so live and learned strata line up).
@@ -3239,7 +3241,10 @@ class AnthropicHandlerMixin:
)
# Carry (arm, stratum) on the existing label channel so the
# outcome funnel can feed the savings ledger from any path.
+ # The conversation rides with it: it is the unit the arm was
+ # assigned to, so it is the unit the estimator has to count.
transforms_applied.append(stratum_label(_arm, _stratum))
+ transforms_applied.append(conversation_label(_conversation))
if _arm == "treatment":
_level, _src = resolve_verbosity_level(_shaper_settings)
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index e7eeba01e..36063e42f 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -718,6 +718,7 @@ def _shape_openai_responses_payload(
from headroom.proxy.output_savings import (
assign_arm,
conversation_key_from_responses_body,
+ conversation_label,
stratum_key,
stratum_label,
)
@@ -736,7 +737,8 @@ def _shape_openai_responses_payload(
holdout = float(runtime_env.getenv("HEADROOM_OUTPUT_HOLDOUT", "0") or "0")
except ValueError:
holdout = 0.0
- arm = assign_arm(conversation_key_from_responses_body(payload), holdout)
+ conversation = conversation_key_from_responses_body(payload)
+ arm = assign_arm(conversation, holdout)
turn_kind = classify_responses_turn(payload.get("input")).value
approx_input_tokens = len(json.dumps(payload)) // 4
@@ -746,7 +748,9 @@ def _shape_openai_responses_payload(
model=model or str(payload.get("model", "")),
has_tools=bool(payload.get("tools")),
)
- labels = [stratum_label(arm, stratum)]
+ # The conversation is the unit the arm was assigned to, so the ledger
+ # needs it to count distinct conversations rather than requests.
+ labels = [stratum_label(arm, stratum), conversation_label(conversation)]
if arm != "treatment":
return labels, False
@@ -4490,6 +4494,7 @@ class OpenAIHandlerMixin:
from headroom.proxy.output_savings import (
assign_arm,
conversation_key_from_body,
+ conversation_label,
stratum_key,
stratum_label,
)
@@ -4514,7 +4519,8 @@ class OpenAIHandlerMixin:
_holdout = float(runtime_env.getenv("HEADROOM_OUTPUT_HOLDOUT", "0") or "0")
except ValueError:
_holdout = 0.0
- _arm = assign_arm(conversation_key_from_body(body), _holdout)
+ _conversation = conversation_key_from_body(body)
+ _arm = assign_arm(_conversation, _holdout)
_turn_kind = classify_turn(body.get("messages", [])).value
_stratum = stratum_key(
turn_kind=_turn_kind,
@@ -4523,8 +4529,10 @@ class OpenAIHandlerMixin:
has_tools=bool(body.get("tools")),
)
# Carry (arm, stratum) on the transforms channel so the outcome
- # funnel feeds the output-savings ledger from the chat path too.
+ # funnel feeds the output-savings ledger from the chat path too,
+ # plus the conversation the arm was actually assigned to.
transforms_applied.append(stratum_label(_arm, _stratum))
+ transforms_applied.append(conversation_label(_conversation))
if _arm == "treatment":
_level, _src = resolve_verbosity_level(_shaper_settings)
_shape_result = shape_openai_chat_request(
diff --git a/headroom/proxy/output_savings.py b/headroom/proxy/output_savings.py
index 2caee6934..edb4fcc26 100644
--- a/headroom/proxy/output_savings.py
+++ b/headroom/proxy/output_savings.py
@@ -53,6 +53,9 @@ from .output_savings_policy import (
from .output_savings_policy import (
conversation_key_from_responses_body as conversation_key_from_responses_body,
)
+from .output_savings_policy import (
+ conversation_label as conversation_label,
+)
from .output_savings_policy import (
input_bucket as input_bucket,
)
@@ -60,6 +63,7 @@ from .output_savings_policy import (
model_family as model_family,
)
from .output_savings_policy import (
+ parse_conversation_label,
parse_stratum_label,
)
from .output_savings_policy import (
@@ -71,6 +75,21 @@ from .output_savings_policy import (
logger = logging.getLogger(__name__)
+# A stratum enters the measured (A/B) estimate only once BOTH arms hold this
+# many distinct conversations. Assignment is per conversation, so conversations
+# -- not requests -- are the independent draws: one agent session in the holdout
+# can leave 2,500 control requests in a single stratum, and every request-count
+# gate we have waves that through as a well-sampled arm. On a real ledger that
+# produced a -1.6% "measured" reduction whose two largest terms came from strata
+# with four control requests apiece.
+MEASURED_MIN_CLUSTERS = 5
+
+# Distinct conversations tracked per arm/stratum. The count is only ever
+# compared against the threshold above, so there is nothing to gain from an
+# exact tally of a busy stratum -- and this keeps a flushed-every-25-requests
+# ledger from growing a set per conversation forever.
+_CLUSTER_CAP = 32
+
@dataclass
class _Accum:
@@ -79,11 +98,43 @@ class _Accum:
n: int = 0
sum: float = 0.0
sumsq: float = 0.0
-
- def add(self, x: float) -> None:
+ #: Distinct conversation ids behind ``qn``, capped at ``_CLUSTER_CAP``.
+ clusters: set[str] = field(default_factory=set)
+ #: The conversation-QUALIFIED subset of n / sum / sumsq: observations that
+ #: arrived carrying a conversation label. Kept separate because the cluster
+ #: count alone cannot vouch for the totals. An accumulator upgraded from an
+ #: older ledger holds requests of unknown provenance -- possibly one
+ #: conversation, possibly thousands -- and five fresh labelled
+ #: conversations arriving afterwards would otherwise qualify all of that
+ #: legacy traffic for the measured estimate too, which is exactly the case
+ #: the cluster gate exists to exclude. Later unlabelled requests are
+ #: likewise kept out of an already-qualified stratum. The full totals stay
+ #: intact for the estimated / modelled tiers and historical reporting.
+ qn: int = 0
+ qsum: float = 0.0
+ qsumsq: float = 0.0
+
+ def add(self, x: float, cluster: str | None = None) -> None:
self.n += 1
self.sum += x
self.sumsq += x * x
+ if cluster is None:
+ return
+ self.qn += 1
+ self.qsum += x
+ self.qsumsq += x * x
+ if len(self.clusters) < _CLUSTER_CAP:
+ self.clusters.add(cluster)
+
+ @property
+ def n_clusters(self) -> int:
+ """Distinct conversations observed, saturating at ``_CLUSTER_CAP``.
+
+ 0 for an accumulator written before conversations were tracked, which
+ is why that data cannot clear :data:`MEASURED_MIN_CLUSTERS`: an
+ unverifiable arm is treated as an unqualified one.
+ """
+ return len(self.clusters)
@property
def mean(self) -> float:
@@ -96,6 +147,18 @@ class _Accum:
return 0.0
return max(0.0, (self.sumsq - self.sum * self.sum / self.n) / (self.n - 1))
+ @property
+ def qmean(self) -> float:
+ """Mean over the conversation-qualified observations only."""
+ return self.qsum / self.qn if self.qn else 0.0
+
+ @property
+ def qvar(self) -> float:
+ """Sample variance over the conversation-qualified observations only."""
+ if self.qn < 2:
+ return 0.0
+ return max(0.0, (self.qsumsq - self.qsum * self.qsum / self.qn) / (self.qn - 1))
+
def merge(self, other: _Accum) -> None:
"""Fold another accumulator's observations into this one.
@@ -105,16 +168,35 @@ class _Accum:
self.n += other.n
self.sum += other.sum
self.sumsq += other.sumsq
+ self.qn += other.qn
+ self.qsum += other.qsum
+ self.qsumsq += other.qsumsq
+ self.clusters |= set(list(other.clusters)[: _CLUSTER_CAP - len(self.clusters)])
- def to_dict(self) -> dict[str, float]:
- return {"n": self.n, "sum": self.sum, "sumsq": self.sumsq}
+ def to_dict(self) -> dict[str, Any]:
+ d: dict[str, Any] = {"n": self.n, "sum": self.sum, "sumsq": self.sumsq}
+ # Omitted when empty so a baseline model (which has no conversations to
+ # track) serializes exactly as it did before.
+ if self.clusters:
+ d["clusters"] = sorted(self.clusters)
+ if self.qn:
+ d["qn"] = self.qn
+ d["qsum"] = self.qsum
+ d["qsumsq"] = self.qsumsq
+ return d
@classmethod
- def from_dict(cls, d: dict[str, float]) -> _Accum:
+ def from_dict(cls, d: dict[str, Any]) -> _Accum:
a = cls()
a.n = int(d.get("n", 0))
a.sum = float(d.get("sum", 0.0))
a.sumsq = float(d.get("sumsq", 0.0))
+ a.clusters = {str(c) for c in (d.get("clusters") or ())}
+ # Absent in a pre-upgrade ledger, which is the point: those requests
+ # carry no conversation provenance and stay out of the measured arm.
+ a.qn = int(d.get("qn", 0))
+ a.qsum = float(d.get("qsum", 0.0))
+ a.qsumsq = float(d.get("qsumsq", 0.0))
return a
@@ -268,9 +350,11 @@ class SavingsLedger:
# ---- recording -------------------------------------------------------
- def record(self, arm: str, key: str, output_tokens: int) -> None:
+ def record(
+ self, arm: str, key: str, output_tokens: int, conversation: str | None = None
+ ) -> None:
target = self.treatment if arm == "treatment" else self.control
- target.setdefault(key, _Accum()).add(output_tokens)
+ target.setdefault(key, _Accum()).add(output_tokens, conversation)
# ---- estimation ------------------------------------------------------
@@ -305,9 +389,25 @@ class SavingsLedger:
def estimate_from_holdout(self) -> SavingsEstimate | None:
"""A/B measurement: per-stratum control mean minus treatment mean.
- Only strata with data in BOTH arms contribute. Returns ``None`` if no
- such stratum exists (no holdout traffic yet). Weighted by treatment
- volume; this is the unbiased causal number.
+ Only strata with conversation-labelled data in BOTH arms contribute,
+ and only once both arms hold :data:`MEASURED_MIN_CLUSTERS` distinct
+ conversations. Returns ``None`` if no such stratum exists (no holdout
+ traffic yet, or none of it spread across enough conversations).
+ Weighted by treatment volume; this is the unbiased causal number.
+
+ The number is built from the QUALIFIED subset of each arm, never the
+ arm totals: an upgraded ledger's legacy requests have no conversation
+ provenance, so five fresh conversations arriving afterwards must not
+ drag thousands of unattributable requests into the measurement with
+ them. The totals remain available to the estimated and modelled tiers.
+
+ The cluster gate is not a sample-size nicety. Assignment is
+ conversation-stable, so the requests inside one conversation are one
+ draw answering one question, and the variance below (which divides by
+ the REQUEST count) reads a single 2,500-request session as a precise
+ measurement. Strata that thin get excluded rather than down-weighted:
+ the arm they describe is one conversation's worth of work, and no
+ weighting recovers a comparison that was never made.
"""
total_saved = 0.0
total_baseline = 0.0
@@ -316,16 +416,20 @@ class SavingsLedger:
contributing = 0
for key, t in self.treatment.items():
c = self.control.get(key)
- if c is None or c.n == 0 or t.n == 0:
+ if c is None or c.qn == 0 or t.qn == 0:
+ continue
+ if c.n_clusters < MEASURED_MIN_CLUSTERS or t.n_clusters < MEASURED_MIN_CLUSTERS:
continue
contributing += 1
- n = t.n
+ # Everything below reads the qualified subset only. The clusters
+ # vouch for those observations and for nothing else.
+ n = t.qn
n_requests += n
- delta = c.mean - t.mean # tokens saved per request in this stratum
+ delta = c.qmean - t.qmean # tokens saved per request in this stratum
total_saved += n * delta
- total_baseline += n * c.mean
+ total_baseline += n * c.qmean
# Var of (c.mean - t.mean) = σ²_c/n_c + σ²_t/n_t, scaled by n².
- var += (n * n) * (c.var / c.n + t.var / t.n)
+ var += (n * n) * (c.qvar / c.qn + t.qvar / t.qn)
if contributing == 0:
return None
return self._finalize(total_saved, total_baseline, var, n_requests, "measured")
@@ -495,19 +599,33 @@ class SavingsRecorder:
def record_from_labels(self, labels: Any, output_tokens: int) -> bool:
"""Record one outcome given its transforms_applied labels. Returns True
- if a shaping label was found and recorded."""
+ if a shaping label was found and recorded.
+
+ The conversation label may sit either side of the stratum label, so the
+ labels are scanned once for both before recording. A request that
+ carries no conversation label (an older client, or a path that has not
+ adopted it) still records its output tokens; it just does not advance
+ the stratum's cluster count.
+ """
+ arm_key: tuple[str, str] | None = None
+ conversation: str | None = None
for label in labels or ():
- parsed = parse_stratum_label(str(label))
- if parsed is None:
- continue
- arm, key = parsed
- with self._lock:
- self._ledger.record(arm, key, output_tokens)
- self._since_flush += 1
- if self._since_flush >= self._flush_every:
- self._flush_locked()
- return True
- return False
+ text = str(label)
+ if arm_key is None:
+ arm_key = parse_stratum_label(text)
+ if arm_key is not None:
+ continue
+ if conversation is None:
+ conversation = parse_conversation_label(text)
+ if arm_key is None:
+ return False
+ arm, key = arm_key
+ with self._lock:
+ self._ledger.record(arm, key, output_tokens, conversation)
+ self._since_flush += 1
+ if self._since_flush >= self._flush_every:
+ self._flush_locked()
+ return True
def estimate_request_savings(self, labels: Any, output_tokens: int) -> int:
"""Per-request output tokens saved, for the savings rollup.
diff --git a/headroom/proxy/output_savings_policy.py b/headroom/proxy/output_savings_policy.py
index c81a8bbf8..eb30661be 100644
--- a/headroom/proxy/output_savings_policy.py
+++ b/headroom/proxy/output_savings_policy.py
@@ -11,6 +11,13 @@ _INPUT_BUCKETS = (2_000, 8_000, 32_000, 128_000)
_STRATUM_LABEL = "output_shaper:stratum:"
_CONTROL_LABEL = "output_shaper:control:"
+_CONVERSATION_LABEL = "output_shaper:conv:"
+
+# Enough of the conversation digest to separate conversations without
+# carrying a full key around: 48 bits, so a machine would need ~16M
+# conversations before two collided, and a collision only ever merges two
+# clusters (it cannot invent one).
+_CONVERSATION_LABEL_CHARS = 12
def input_bucket(input_tokens: int) -> str:
@@ -171,6 +178,28 @@ def stratum_label(arm: str, key: str) -> str:
return prefix + key
+def conversation_label(conversation_key: str) -> str:
+ """Encode the conversation a request belongs to as a label.
+
+ Rides the same ``transforms_applied`` channel as the stratum so the
+ ledger can count DISTINCT conversations per arm, not just requests.
+ Randomization is per conversation (see :func:`assign_arm`), so the
+ conversation is the independent unit; a single long agent session
+ otherwise enters the estimate as thousands of independent draws.
+
+ ``conversation_key`` is already a digest, so this only truncates it --
+ no request content reaches the label or the ledger.
+ """
+ return _CONVERSATION_LABEL + conversation_key[:_CONVERSATION_LABEL_CHARS]
+
+
+def parse_conversation_label(label: str) -> str | None:
+ """Decode a conversation label, or None if not one of ours."""
+ if label.startswith(_CONVERSATION_LABEL):
+ return label[len(_CONVERSATION_LABEL) :]
+ return None
+
+
def parse_stratum_label(label: str) -> tuple[str, str] | None:
"""Decode a label into ``(arm, stratum)``, or None if not one of ours."""
if label.startswith(_STRATUM_LABEL):
diff --git a/tests/test_output_savings.py b/tests/test_output_savings.py
index 5bd0a6c89..a78bf1ef0 100644
--- a/tests/test_output_savings.py
+++ b/tests/test_output_savings.py
@@ -2,14 +2,18 @@
from __future__ import annotations
+import json
+
import pytest
from headroom.proxy.output_savings import (
+ MEASURED_MIN_CLUSTERS,
BaselineModel,
SavingsLedger,
SavingsRecorder,
assign_arm,
conversation_key_from_body,
+ conversation_label,
echo_ratio,
input_bucket,
model_family,
@@ -287,9 +291,9 @@ class TestEstimateFromHoldout:
def test_measured_difference_of_means(self):
ledger = SavingsLedger()
- for _ in range(30):
- ledger.record("control", "opus|new_user_ask|s|tools", 1000)
- ledger.record("treatment", "opus|new_user_ask|s|tools", 750)
+ for i in range(30):
+ ledger.record("control", "opus|new_user_ask|s|tools", 1000, f"c{i}")
+ ledger.record("treatment", "opus|new_user_ask|s|tools", 750, f"t{i}")
est = ledger.estimate_from_holdout()
assert est is not None
assert est.kind == "measured"
@@ -299,21 +303,21 @@ class TestEstimateFromHoldout:
def test_only_strata_present_in_both_arms_contribute(self):
ledger = SavingsLedger()
- for _ in range(10):
- ledger.record("control", "opus|a|s|tools", 1000)
- ledger.record("treatment", "opus|a|s|tools", 800)
+ for i in range(10):
+ ledger.record("control", "opus|a|s|tools", 1000, f"c{i}")
+ ledger.record("treatment", "opus|a|s|tools", 800, f"t{i}")
# Treatment-only stratum must not contribute (no control to compare).
- ledger.record("treatment", "opus|b|m|notools", 50)
+ ledger.record("treatment", "opus|b|m|notools", 50, "t99")
est = ledger.estimate_from_holdout()
assert est is not None
assert est.n_requests == 10
def test_best_estimate_prefers_measured(self):
ledger = SavingsLedger()
- for _ in range(10):
+ for i in range(10):
ledger.baseline.observe("opus|a|s|tools", 1000)
- ledger.record("control", "opus|a|s|tools", 1000)
- ledger.record("treatment", "opus|a|s|tools", 900)
+ ledger.record("control", "opus|a|s|tools", 1000, f"c{i}")
+ ledger.record("treatment", "opus|a|s|tools", 900, f"t{i}")
assert ledger.best_estimate().kind == "measured"
def test_best_estimate_falls_back_to_estimated(self):
@@ -324,6 +328,191 @@ class TestEstimateFromHoldout:
assert ledger.best_estimate().kind == "estimated"
+class TestHoldoutClusterGate:
+ """A stratum needs distinct CONVERSATIONS in both arms, not requests.
+
+ Assignment is conversation-stable, so one long agent session is one draw.
+ Counting its requests as independent is what let four control requests
+ decide a fleet machine's headline reduction.
+ """
+
+ @staticmethod
+ def _fill(ledger, *, conversations, per_conversation, control_tokens=1000, treat_tokens=800):
+ for i in range(conversations):
+ for _ in range(per_conversation):
+ ledger.record("control", "opus|a|s|tools", control_tokens, f"c{i}")
+ ledger.record("treatment", "opus|a|s|tools", treat_tokens, f"t{i}")
+
+ def test_one_conversation_per_arm_does_not_qualify(self):
+ ledger = SavingsLedger()
+ # 2,500 requests an arm, all from one session each side: the shape that
+ # produced a -1.6% "measured" number on a real ledger.
+ self._fill(ledger, conversations=1, per_conversation=2_500)
+ assert ledger.estimate_from_holdout() is None
+
+ def test_enough_conversations_qualifies(self):
+ ledger = SavingsLedger()
+ self._fill(ledger, conversations=MEASURED_MIN_CLUSTERS, per_conversation=2)
+ est = ledger.estimate_from_holdout()
+ assert est is not None
+ assert est.kind == "measured"
+
+ def test_thin_control_arm_does_not_ride_on_a_thick_treatment_one(self):
+ ledger = SavingsLedger()
+ for i in range(50):
+ ledger.record("treatment", "opus|a|s|tools", 800, f"t{i}")
+ for _ in range(400):
+ ledger.record("control", "opus|a|s|tools", 1000, "one-session")
+ assert ledger.estimate_from_holdout() is None
+
+ def test_best_estimate_falls_back_when_the_holdout_is_one_conversation(self):
+ ledger = SavingsLedger()
+ for i in range(20):
+ ledger.baseline.observe("opus|a|s|tools", 1000)
+ ledger.record("treatment", "opus|a|s|tools", 900, f"t{i}")
+ ledger.record("control", "opus|a|s|tools", 1000, "one-session")
+ assert ledger.best_estimate().kind == "estimated"
+
+ def test_a_ledger_written_before_conversations_were_tracked_does_not_qualify(self):
+ # No cluster data at all: unverifiable, so it cannot clear the gate.
+ ledger = SavingsLedger()
+ for _ in range(100):
+ ledger.record("control", "opus|a|s|tools", 1000)
+ ledger.record("treatment", "opus|a|s|tools", 800)
+ assert ledger.estimate_from_holdout() is None
+
+ def test_cluster_tracking_saturates(self):
+ ledger = SavingsLedger()
+ for i in range(500):
+ ledger.record("treatment", "opus|a|s|tools", 800, f"t{i}")
+ # Bounded: the count is only ever compared against a threshold, so the
+ # ledger does not grow a set entry per conversation forever.
+ assert ledger.treatment["opus|a|s|tools"].n_clusters <= 32
+ assert ledger.treatment["opus|a|s|tools"].n_clusters >= MEASURED_MIN_CLUSTERS
+
+ def test_conversation_survives_a_save_load_cycle(self, tmp_path):
+ ledger = SavingsLedger()
+ for i in range(MEASURED_MIN_CLUSTERS):
+ ledger.record("control", "opus|a|s|tools", 1000, f"c{i}")
+ ledger.record("treatment", "opus|a|s|tools", 800, f"t{i}")
+ path = tmp_path / "savings.json"
+ ledger.save(path)
+ assert SavingsLedger.load(path).estimate_from_holdout() is not None
+
+ def test_recorder_reads_the_conversation_off_the_label_channel(self, tmp_path):
+ recorder = SavingsRecorder(tmp_path / "savings.json", flush_every=1)
+ for i in range(MEASURED_MIN_CLUSTERS):
+ key = conversation_key_from_body({"messages": [{"role": "user", "content": f"q{i}"}]})
+ assert recorder.record_from_labels(
+ [
+ "router:noop",
+ stratum_label("treatment", "opus|a|s|tools"),
+ conversation_label(key),
+ ],
+ 800,
+ )
+ assert recorder.record_from_labels(
+ [conversation_label(key + "control"), stratum_label("control", "opus|a|s|tools")],
+ 1000,
+ )
+ assert SavingsLedger.load(tmp_path / "savings.json").estimate_from_holdout() is not None
+
+ def test_a_request_without_a_conversation_label_still_records(self, tmp_path):
+ recorder = SavingsRecorder(tmp_path / "savings.json", flush_every=1)
+ assert recorder.record_from_labels([stratum_label("treatment", "opus|a|s|tools")], 800)
+ ledger = SavingsLedger.load(tmp_path / "savings.json")
+ assert ledger.treatment["opus|a|s|tools"].n == 1
+ assert ledger.treatment["opus|a|s|tools"].n_clusters == 0
+
+ # -- provenance: clusters vouch for labelled observations, nothing else ---
+
+ @staticmethod
+ def _legacy_ledger_dict(requests=2_500, control_tokens=1000, treat_tokens=2000):
+ """An arm as an upgraded ledger holds it: totals, no conversations.
+
+ Those requests could all be one conversation -- the exact case the
+ cluster gate exists to exclude -- and nothing on disk can say.
+ """
+ return {
+ "baseline": {"strata": {}},
+ "treatment": {
+ "opus|a|s|tools": {
+ "n": requests,
+ "sum": float(requests * treat_tokens),
+ "sumsq": float(requests * treat_tokens**2),
+ }
+ },
+ "control": {
+ "opus|a|s|tools": {
+ "n": requests,
+ "sum": float(requests * control_tokens),
+ "sumsq": float(requests * control_tokens**2),
+ }
+ },
+ }
+
+ def test_upgraded_legacy_traffic_never_joins_the_measured_arm(self, tmp_path):
+ """Five fresh conversations qualify the STRATUM, not the back catalogue.
+
+ Before this split the reload kept n/sum/sumsq and the new labelled
+ observations only added clusters to the same accumulator, so the moment
+ the gate opened all 2,500 unattributable requests an arm were measured
+ too -- reporting -99.8% over 2,505 requests while the conversations
+ actually observed showed no difference at all.
+ """
+ path = tmp_path / "savings.json"
+ path.write_text(json.dumps(self._legacy_ledger_dict()))
+ ledger = SavingsLedger.load(path)
+ assert ledger.estimate_from_holdout() is None, "legacy traffic alone cannot qualify"
+
+ for i in range(MEASURED_MIN_CLUSTERS):
+ ledger.record("control", "opus|a|s|tools", 1000, f"c{i}")
+ ledger.record("treatment", "opus|a|s|tools", 1000, f"t{i}")
+
+ est = ledger.estimate_from_holdout()
+ assert est is not None, "the labelled conversations are a real sample"
+ # Only the labelled requests are measured, and they show no difference.
+ assert est.n_requests == MEASURED_MIN_CLUSTERS
+ assert est.tokens_saved == pytest.approx(0.0)
+ assert est.pct == pytest.approx(0.0)
+ # The totals survive for the estimated / modelled tiers and reporting.
+ assert ledger.treatment["opus|a|s|tools"].n == 2_500 + MEASURED_MIN_CLUSTERS
+
+ def test_the_qualified_subset_survives_a_save_load_cycle(self, tmp_path):
+ """The split has to persist, or the next restart re-merges the arms."""
+ path = tmp_path / "savings.json"
+ path.write_text(json.dumps(self._legacy_ledger_dict()))
+ ledger = SavingsLedger.load(path)
+ for i in range(MEASURED_MIN_CLUSTERS):
+ ledger.record("control", "opus|a|s|tools", 1000, f"c{i}")
+ ledger.record("treatment", "opus|a|s|tools", 1000, f"t{i}")
+ ledger.save(path)
+
+ reloaded = SavingsLedger.load(path)
+ est = reloaded.estimate_from_holdout()
+ assert est is not None
+ assert est.n_requests == MEASURED_MIN_CLUSTERS
+ assert est.tokens_saved == pytest.approx(0.0)
+ assert reloaded.treatment["opus|a|s|tools"].n == 2_500 + MEASURED_MIN_CLUSTERS
+
+ def test_later_unlabelled_requests_stay_out_of_a_qualified_stratum(self):
+ """Qualifying a stratum does not open it to unattributable traffic."""
+ ledger = SavingsLedger()
+ for i in range(MEASURED_MIN_CLUSTERS):
+ ledger.record("control", "opus|a|s|tools", 1000, f"c{i}")
+ ledger.record("treatment", "opus|a|s|tools", 1000, f"t{i}")
+ before = ledger.estimate_from_holdout()
+ assert before is not None
+
+ for _ in range(2_000):
+ ledger.record("treatment", "opus|a|s|tools", 5)
+
+ after = ledger.estimate_from_holdout()
+ assert after is not None
+ assert after.n_requests == before.n_requests
+ assert after.tokens_saved == pytest.approx(before.tokens_saved)
+
+
# ---------------------------------------------------------------------------
# persistence
# ---------------------------------------------------------------------------
@@ -333,8 +522,9 @@ class TestLedgerPersistence:
def test_roundtrip(self, tmp_path):
ledger = SavingsLedger()
ledger.baseline.observe("opus|a|s|tools", 1000)
- ledger.record("treatment", "opus|a|s|tools", 800)
- ledger.record("control", "opus|a|s|tools", 1000)
+ for i in range(MEASURED_MIN_CLUSTERS):
+ ledger.record("treatment", "opus|a|s|tools", 800, f"t{i}")
+ ledger.record("control", "opus|a|s|tools", 1000, f"c{i}")
path = tmp_path / "savings.json"
ledger.save(path)
loaded = SavingsLedger.load(path)
diff --git a/tests/test_output_shaper_conversation_label.py b/tests/test_output_shaper_conversation_label.py
new file mode 100644
index 000000000..54f99455c
--- /dev/null
+++ b/tests/test_output_shaper_conversation_label.py
@@ -0,0 +1,116 @@
+"""The conversation label must ride with the stratum label on every shaped path.
+
+The ledger admits a stratum to the measured (A/B) estimate only once both arms
+hold ``MEASURED_MIN_CLUSTERS`` distinct conversations. A handler that emits the
+stratum without the conversation therefore feeds strata that can never qualify,
+and the measured number is withheld forever with nothing in the logs to say why.
+
+The /v1/responses path is pinned in ``test_output_shaper_responses.py``; these
+drive the two remaining shaped handlers end to end against a mocked upstream.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+fastapi = pytest.importorskip("fastapi")
+httpx = pytest.importorskip("httpx")
+
+from fastapi.testclient import TestClient # noqa: E402
+
+from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
+
+
[email protected](autouse=True)
+def _shaper_on(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("HEADROOM_OUTPUT_SHAPER", "1")
+ # Whole-holdout: the control arm labels itself but never shapes, so the
+ # assertions below pin the label pair rather than the steering text.
+ monkeypatch.setenv("HEADROOM_OUTPUT_HOLDOUT", "1.0")
+
+
+def _config() -> ProxyConfig:
+ return ProxyConfig(
+ optimize=True,
+ cache_enabled=False,
+ rate_limit_enabled=False,
+ cost_tracking_enabled=False,
+ log_requests=False,
+ )
+
+
+def _assert_paired(transforms: str) -> None:
+ labels = [t for t in transforms.split(",") if t.strip()]
+ assert any(
+ t.startswith(("output_shaper:stratum:", "output_shaper:control:")) for t in labels
+ ), transforms
+ assert any(t.startswith("output_shaper:conv:") for t in labels), transforms
+
+
+def test_anthropic_messages_pairs_the_conversation_with_the_stratum() -> None:
+ async def _fake_retry(method, url, headers, body, *args, **kwargs):
+ return httpx.Response(
+ 200,
+ json={
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-haiku-4-5",
+ "content": [{"type": "text", "text": "ok"}],
+ "stop_reason": "end_turn",
+ "usage": {"input_tokens": 10, "output_tokens": 2},
+ },
+ headers={"content-type": "application/json"},
+ )
+
+ with TestClient(create_app(_config())) as client:
+ client.app.state.proxy._retry_request = _fake_retry
+ resp = client.post(
+ "/v1/messages",
+ headers={"x-api-key": "test-key", "anthropic-version": "2023-06-01"},
+ json={
+ "model": "claude-haiku-4-5",
+ "max_tokens": 64,
+ "system": "You are helpful.",
+ "messages": [{"role": "user", "content": "hello"}],
+ },
+ )
+
+ assert resp.status_code == 200, resp.text
+ _assert_paired(resp.headers.get("x-headroom-transforms", ""))
+
+
+def test_openai_chat_pairs_the_conversation_with_the_stratum() -> None:
+ async def _fake_retry(method, url, headers, body, *args, **kwargs):
+ return httpx.Response(
+ 200,
+ json={
+ "id": "chatcmpl-1",
+ "object": "chat.completion",
+ "model": "gpt-4o",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "ok"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12},
+ },
+ headers={"content-type": "application/json"},
+ )
+
+ with TestClient(create_app(_config())) as client:
+ client.app.state.proxy._retry_request = _fake_retry
+ resp = client.post(
+ "/v1/chat/completions",
+ headers={"Authorization": "Bearer test-key"},
+ json={
+ "model": "gpt-4o",
+ "messages": [{"role": "user", "content": "hello"}],
+ "stream": False,
+ },
+ )
+
+ assert resp.status_code == 200, resp.text
+ _assert_paired(resp.headers.get("x-headroom-transforms", ""))
diff --git a/tests/test_output_shaper_responses.py b/tests/test_output_shaper_responses.py
index 9a57529a5..7ff881d3d 100644
--- a/tests/test_output_shaper_responses.py
+++ b/tests/test_output_shaper_responses.py
@@ -275,8 +275,11 @@ class TestShapeHandlerHelper:
labels, mutated = _shape_openai_responses_payload(body, model="gpt-5.5", request_id="t3")
assert mutated is False
assert json.dumps(body, sort_keys=True) == snapshot # control arm untouched
- assert len(labels) == 1
+ # Stratum + the conversation it was assigned to, and nothing else: the
+ # control arm labels itself but never shapes.
+ assert len(labels) == 2
assert labels[0].startswith("output_shaper:control:")
+ assert labels[1].startswith("output_shaper:conv:")
class TestHandlerPathControlLabels: