mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
feat(savings): book modelled output savings per request, as a token and dollar range (#4878)
## Description
Benchmark factors registered with `register_modelled_factors` reached
`/stats` only as a percentage. They never reached the per-request
rollup, so modelled output savings had no tokens or dollars in the
lifetime totals that the local dashboard and the control-plane heartbeat
read. This PR books each shaped request's output saving as a low–high
range of tokens and dollars, from the same tier the dashboard reports.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue) — an unshaped
treatment request was booked a baseline saving
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- `SavingsRecorder.request_savings_range(labels, output_tokens) -> (low,
high)` replaces `estimate_request_savings` in the outcome funnel.
- It counts only requests that were actually shaped, marked by the
`output_shaper:verbosity:L<n>` label. The treatment stratum label is
attached before shaping is attempted, so it proves nothing.
- A holdout (control) request books nothing.
- A response with no reported output usage (output 0) books nothing.
- The tier comes from `SavingsLedger.select_tier(level)`, the function
`best_estimate` now delegates to. Lifetime dollars therefore always come
from the tier that the dashboard's percentage comes from:
- **measured:** the request's own stratum's control mean minus its
output, with low = high. It applies only if that stratum qualifies at
the cluster gate the measurement used. A stratum outside the measurement
books 0, because the measured headline excludes it too.
- **estimated:** the request's stratum baseline, with low = high.
- **modelled:** the factor band, `observed × r/(1−r)` at each end.
- `SavingsTracker`:
- Books the low end everywhere it booked before (history, rollups,
OTel).
- Adds `lifetime.output_tokens_saved_high` and
`output_savings_usd_high`, priced per model at output rates.
- Both state builders write the new keys, so a fresh tracker has them.
- Dashboard: the Output Tokens Saved tile adds "≈ $low–$high saved on
output · low–high tokens, all time", read through a component getter.
OSS is unchanged. It ships an empty factor table, so the modelled tier
never appears.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`): clean on the touched files
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
$ git log --oneline -1
1600ecae Merge branch 'main' into feat/output-savings-dashboard-range
$ pytest -q $(rg -l "output_savings|output_tokens_saved|best_estimate" tests) tests/test_request_outcome.py
421 passed in 23.29s
$ ruff check headroom
All checks passed!
```
Hosted CI:
`test_upstream_guard.py::test_openai_routes_refuse_a_private_override_instead_of_using_the_default`
and
`test_grok_shared_proxy_call_sites.py::test_the_base_url_override_is_resolved_once_per_request`
also fail on `main` at `d6df127d`.
New tests:
- the factor band;
- one control observation without a baseline keeps the modelled tier,
returning (200, 800);
- a measured holdout in stratum A credits A's requests from A's control
mean, while a request in stratum B (no control) books 0;
- a response without output usage books nothing;
- a baseline outranks the factors;
- an unshaped treatment request books nothing;
- no factors registered;
- the lifetime range survives a restart;
- a fresh tracker has the keys;
- end to end: outcome funnel → `PrometheusMetrics.record_request` →
tracker lifetime.
## Real Behavior Proof
- **Environment:**
- macOS (darwin), Python 3.12.
- The real `headroom proxy`, run from a scratch merge of this PR with
#4877 (version `0.45.0-dev`).
- An isolated `HEADROOM_WORKSPACE_DIR` per scenario.
- A local fake Anthropic upstream that returns `usage.output_tokens=800`
and records each request body.
- With an extension: a licensed extension that registers factors for its
levels (values not shown here).
- **Exact command / steps:**
- Start the proxy: `HEADROOM_OUTPUT_SHAPER=1 headroom proxy --port 18799
--anthropic-api-url http://127.0.0.1:18798`, with and without the
extension.
- Send 3 `POST /v1/messages` requests, each with a different user
prompt. Identical prompts are served from the proxy's response cache and
never reach the upstream.
- Read `GET /stats` → `tokens.output_reduction`, and the tracker's
persisted `proxy_savings.json` → `lifetime`.
- **Observed result** (3 requests × 800 output tokens each, all 3
reached the upstream):
| Scenario | `output_reduction` | lifetime saved tokens and USD |
|---|---|---|
| Core only (no extension) | `available: false` | 0–0 |
| Extension loaded | `modelled`, with a low–high band | a low–high
range, low < high; each end equals 3 × 800 × r/(1−r) for that end of the
registered band, and USD is tokens × the model's output price |
| Extension, `HEADROOM_VERBOSITY_LEVEL=3` pinned | `modelled`, the L3
band | a smaller low–high range, by the same arithmetic |
| Extension requested, no licence | `available: false` | 0–0 |
- **Not tested:**
- The dashboard tile rendered in a browser. Its Alpine expression was
evaluated in Node and renders "≈ $1.50–$4.20 saved on output · 1000–2600
tokens, all time" for a range, and a single figure for a point estimate.
- A real upstream provider.
- Streaming responses. The funnel is shared, but no streaming request
was sent.
- The measured and estimated tiers on live holdout or baseline traffic.
These are covered by unit tests, not a run.
## Runtime Rollout Safety
- **Rollout-managed feature(s):** `proxy_output_shaper`. Nothing is
booked unless steering is on and factors are registered.
- **Minimum rollout channel:** unchanged.
- **Stable/default behavior changed:** none in OSS, because no factors
are registered. With an extension, two lifetime keys are added, and the
per-request saving follows the dashboard's tier.
- **Kill switch / disable path:** `HEADROOM_OUTPUT_SHAPER=0`, or don't
load the extension.
- **Unsafe override required:** none.
- **Qualification impact:** each shaped request runs one `select_tier`
inside the recorder lock, off the event loop in the existing
`asyncio.to_thread` block.
- **Rollback path:** revert the PR. Older cores drop the two `_high`
keys when they load the savings file, and nothing else reads them.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation (no docs
describe these lifetime keys)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`
## Additional Notes
- Known gap: history checkpoints carry only the low end. If a reload
repairs lifetime from history, the band narrows for that window.
- Companion PR: #4877 adds the extension seams.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JD Davis
parent
1f4c66f50a
commit
00436a8b11
@@ -331,13 +331,28 @@
|
||||
'text-amber-500': stats.tokens?.output_reduction?.method === 'modelled'
|
||||
}"
|
||||
x-text="stats.tokens?.output_reduction?.method || ''"></span>
|
||||
<!-- A modelled band is the spread between the two benchmarked
|
||||
models, not a sampling CI. Calling it one would be a lie. -->
|
||||
<!-- A modelled band is a benchmark's range, not a CI over this
|
||||
deployment's traffic. 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>
|
||||
<!-- Lifetime dollars at each request's model output rate. The
|
||||
high end exists only when savings were modelled from a
|
||||
benchmark band; a point estimate shows one number. -->
|
||||
<template x-if="(lifetimeOutputSavings.output_savings_usd || 0) > 0">
|
||||
<div class="mt-1 text-xs text-gray-400 leading-relaxed"
|
||||
x-text="'≈ $' + formatCurrency(lifetimeOutputSavings.output_savings_usd || 0)
|
||||
+ ((lifetimeOutputSavings.output_savings_usd_high || 0) > (lifetimeOutputSavings.output_savings_usd || 0)
|
||||
? '–$' + formatCurrency(lifetimeOutputSavings.output_savings_usd_high) : '')
|
||||
+ ' saved on output · '
|
||||
+ formatNumber(lifetimeOutputSavings.output_tokens_saved || 0)
|
||||
+ ((lifetimeOutputSavings.output_tokens_saved_high || 0) > (lifetimeOutputSavings.output_tokens_saved || 0)
|
||||
? '–' + formatNumber(lifetimeOutputSavings.output_tokens_saved_high) : '')
|
||||
+ ' tokens, all time'">
|
||||
</div>
|
||||
</template>
|
||||
<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
|
||||
@@ -2800,6 +2815,10 @@
|
||||
return this.stats.persistent_savings?.lifetime?.cache_savings_usd || 0;
|
||||
},
|
||||
|
||||
get lifetimeOutputSavings() {
|
||||
return this.stats.persistent_savings?.lifetime || {};
|
||||
},
|
||||
|
||||
get cacheCardAvailable() {
|
||||
return this.cacheSessionActive || this.lifetimeCacheReadTokens > 0 || this.lifetimeCacheSavingsUsd > 0;
|
||||
},
|
||||
|
||||
@@ -588,22 +588,25 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:
|
||||
# observed output tokens to the recorder so it can produce an honest
|
||||
# reduction estimate. Best-effort: never let bookkeeping break a response.
|
||||
output_tokens_saved_est = 0
|
||||
# High end of the range when the saving is modelled from benchmark factors;
|
||||
# equal to the point estimate otherwise. Only the lifetime totals carry it.
|
||||
output_tokens_saved_high_est = 0
|
||||
if any(str(t).startswith("output_shaper:") for t in outcome.transforms_applied):
|
||||
try:
|
||||
from headroom.proxy.output_savings import get_recorder
|
||||
|
||||
_rec = get_recorder()
|
||||
|
||||
def _record_and_estimate() -> int:
|
||||
def _record_and_estimate() -> tuple[int, int]:
|
||||
_rec.record_from_labels(outcome.transforms_applied, outcome.output_tokens)
|
||||
return _rec.estimate_request_savings(
|
||||
outcome.transforms_applied, outcome.output_tokens
|
||||
)
|
||||
return _rec.request_savings_range(outcome.transforms_applied, outcome.output_tokens)
|
||||
|
||||
# Both calls take the recorder lock, and the every-Nth record also
|
||||
# does a full read-modify-write of the ledger file — run them
|
||||
# together off the event loop (#18) so a slow flush can't stall it.
|
||||
output_tokens_saved_est = await asyncio.to_thread(_record_and_estimate)
|
||||
output_tokens_saved_est, output_tokens_saved_high_est = await asyncio.to_thread(
|
||||
_record_and_estimate
|
||||
)
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
logger.debug(
|
||||
"Output savings record/estimate failed for request %s; booking 0: %s",
|
||||
@@ -731,6 +734,7 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:
|
||||
uncached_input_tokens=outcome.uncached_input_tokens,
|
||||
attempted_input_tokens=outcome.attempted_input_tokens,
|
||||
output_tokens_saved=output_tokens_saved_est,
|
||||
output_tokens_saved_high=output_tokens_saved_high_est,
|
||||
project=project,
|
||||
client=outcome.client,
|
||||
tool_search_saved=tool_search_saved,
|
||||
|
||||
@@ -333,6 +333,37 @@ def register_modelled_factors(level: int, conservative: float, optimistic: float
|
||||
MODELLED_REDUCTION[level] = (conservative, optimistic)
|
||||
|
||||
|
||||
def _shaped_level(labels: Any) -> int | None:
|
||||
"""The verbosity level a request was shaped at, or ``None`` if it was not."""
|
||||
for label in labels or ():
|
||||
text = str(label)
|
||||
if not text.startswith(_SHAPED_LABEL_PREFIX + "L"):
|
||||
continue
|
||||
try:
|
||||
return int(text[len(_SHAPED_LABEL_PREFIX) + 1 :])
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def modelled_request_savings(labels: Any, output_tokens: int) -> tuple[int, int]:
|
||||
"""Output tokens one shaped request saved, from its level's benchmark factors.
|
||||
|
||||
``(low, high)`` at the conservative and optimistic factor, using the same
|
||||
inversion as :meth:`SavingsLedger.estimate_from_model`: observed output is
|
||||
already shaped, so ``saved = observed * r / (1 - r)``. ``(0, 0)`` when the
|
||||
request was not shaped or its level has no registered factors.
|
||||
"""
|
||||
level = _shaped_level(labels)
|
||||
if output_tokens <= 0 or level is None:
|
||||
return 0, 0
|
||||
factors = MODELLED_REDUCTION.get(level)
|
||||
if factors is None:
|
||||
return 0, 0
|
||||
low, high = (int(round(output_tokens * r / (1.0 - r))) for r in factors)
|
||||
return low, high
|
||||
|
||||
|
||||
@dataclass
|
||||
class SavingsEstimate:
|
||||
"""Result of an estimation pass."""
|
||||
@@ -637,21 +668,48 @@ class SavingsLedger:
|
||||
reported, since it displaces nothing, but only while it covers the
|
||||
traffic: a corner of it is not a headline either way.
|
||||
"""
|
||||
return self.select_tier(level)[0]
|
||||
|
||||
def select_tier(self, level: int | None = None) -> tuple[SavingsEstimate, int | None]:
|
||||
""":meth:`best_estimate`, plus the cluster gate the measured tier used.
|
||||
|
||||
The second element is the ``min_clusters`` that qualified the measured
|
||||
estimate, or ``None`` for any other tier. A per-request booking needs
|
||||
it to tell whether the request's own stratum is part of the
|
||||
measurement; the headline excludes strata that are not.
|
||||
"""
|
||||
measured = self.estimate_from_holdout(min_clusters=MEASURED_SUPERSEDE_MIN_CLUSTERS)
|
||||
labelled = sum(t.qn for t in self.treatment.values())
|
||||
if measured is not None and _measured_supersedes(measured, labelled):
|
||||
return measured
|
||||
return measured, MEASURED_SUPERSEDE_MIN_CLUSTERS
|
||||
estimated = self.estimate_from_baseline()
|
||||
if estimated.n_requests > 0:
|
||||
return estimated
|
||||
return estimated, None
|
||||
measured = self.estimate_from_holdout()
|
||||
if measured is not None and _measured_covers(measured, labelled):
|
||||
return measured
|
||||
return measured, MEASURED_MIN_CLUSTERS
|
||||
if level is not None:
|
||||
modelled = self.estimate_from_model(level)
|
||||
if modelled is not None:
|
||||
return modelled
|
||||
return estimated
|
||||
return modelled, None
|
||||
return estimated, None
|
||||
|
||||
def measured_stratum_saving(
|
||||
self, key: str, output_tokens: int, min_clusters: int
|
||||
) -> int | None:
|
||||
"""Tokens one request in ``key`` saved, from that stratum's own A/B.
|
||||
|
||||
``None`` when the stratum is not part of the measurement at
|
||||
``min_clusters`` -- the same qualification :meth:`estimate_from_holdout`
|
||||
applies, so a stratum the headline excludes is never credited.
|
||||
"""
|
||||
t = self.treatment.get(key)
|
||||
c = self.control.get(key)
|
||||
if t is None or c is None or c.qn == 0 or t.qn == 0:
|
||||
return None
|
||||
if c.n_clusters < min_clusters or t.n_clusters < min_clusters:
|
||||
return None
|
||||
return max(0, int(round(c.qmean - output_tokens)))
|
||||
|
||||
# ---- persistence -----------------------------------------------------
|
||||
|
||||
@@ -828,6 +886,64 @@ class SavingsRecorder:
|
||||
return max(0, int(round(mean - output_tokens))) if n > 0 else 0
|
||||
return 0
|
||||
|
||||
def request_savings_range(self, labels: Any, output_tokens: int) -> tuple[int, int]:
|
||||
"""Per-request output tokens saved as ``(low, high)``, for the rollup.
|
||||
|
||||
Only a request that was actually shaped saves anything: the treatment
|
||||
stratum label is attached before shaping is attempted, so the
|
||||
``output_shaper:verbosity:L<n>`` label is the proof, as in
|
||||
:meth:`record_from_labels`. A holdout (control) request saved nothing.
|
||||
|
||||
The tier is whatever :meth:`SavingsLedger.best_estimate` picks for the
|
||||
request's level, so the lifetime dollars always come from the same
|
||||
tier the dashboard's percentage does:
|
||||
|
||||
* measured -> this stratum's own control mean minus the observed
|
||||
output, low = high, and only if the stratum is part of the
|
||||
measurement (0 otherwise: the headline excludes it too);
|
||||
* estimated -> the learned baseline for this request's stratum,
|
||||
low = high (0 where the stratum has no baseline);
|
||||
* modelled -> the level's benchmark factors, a low-high band.
|
||||
|
||||
With no factors registered (plain OSS) the modelled tier never
|
||||
appears, so nothing changes there.
|
||||
"""
|
||||
# Zero output means the provider reported no usage, not a silent
|
||||
# reply: every tier would otherwise book the whole baseline as saved.
|
||||
if output_tokens <= 0:
|
||||
return 0, 0
|
||||
label_strings = [str(label) for label in labels or ()]
|
||||
level = _shaped_level(label_strings)
|
||||
if level is None:
|
||||
return 0, 0
|
||||
key = None
|
||||
for text in label_strings:
|
||||
parsed = parse_stratum_label(text)
|
||||
if parsed is None:
|
||||
continue
|
||||
arm, key = parsed
|
||||
if arm != "treatment":
|
||||
return 0, 0
|
||||
break
|
||||
n = 0
|
||||
mean = 0.0
|
||||
measured_point: int | None = None
|
||||
with self._lock:
|
||||
tier, min_clusters = self._ledger.select_tier(level)
|
||||
if tier.kind == "estimated" and key is not None:
|
||||
mean, _var, n = self._ledger.baseline.lookup(key)
|
||||
if min_clusters is not None and key is not None:
|
||||
measured_point = self._ledger.measured_stratum_saving(
|
||||
key, output_tokens, min_clusters
|
||||
)
|
||||
if tier.kind == "modelled":
|
||||
return modelled_request_savings(label_strings, output_tokens)
|
||||
if tier.kind == "measured":
|
||||
point = measured_point or 0
|
||||
return point, point
|
||||
point = max(0, int(round(mean - output_tokens))) if n > 0 else 0
|
||||
return point, point
|
||||
|
||||
def _reload_baseline_locked(self) -> None:
|
||||
"""Adopt the on-disk baseline written by ``learn --verbosity --apply``.
|
||||
|
||||
|
||||
@@ -884,6 +884,8 @@ class PrometheusMetrics:
|
||||
uncached_input_tokens: int = 0,
|
||||
attempted_input_tokens: int = 0,
|
||||
output_tokens_saved: int = 0,
|
||||
# High end of a modelled output-savings range; None means "same as low".
|
||||
output_tokens_saved_high: int | None = None,
|
||||
project: str | None = None,
|
||||
client: str | None = None,
|
||||
tool_search_saved: int = 0,
|
||||
@@ -1143,6 +1145,7 @@ class PrometheusMetrics:
|
||||
total_input_tokens=total_input_tokens,
|
||||
total_input_cost_usd=total_input_cost_usd,
|
||||
output_tokens_saved=output_tokens_saved,
|
||||
output_tokens_saved_high=output_tokens_saved_high,
|
||||
output_tokens=output_tokens,
|
||||
estimated_savings_usd=savings_usd,
|
||||
)
|
||||
|
||||
@@ -1155,6 +1155,10 @@ class SavingsTracker:
|
||||
# message-only while per-model dollars did not.
|
||||
tool_search_saved: int = 0,
|
||||
output_tokens_saved: int = 0,
|
||||
# High end of a modelled output-savings range (benchmark factors give a
|
||||
# band, not a point); ``None`` means the saving is a point estimate and
|
||||
# the high end equals ``output_tokens_saved``. Lifetime-only.
|
||||
output_tokens_saved_high: int | None = None,
|
||||
# Tokens the model actually emitted, DISJOINT from
|
||||
# ``output_tokens_saved`` (which counts the ones it did not). Priced
|
||||
# into ``lifetime["total_output_cost_usd"]``; see the delta below.
|
||||
@@ -1188,6 +1192,11 @@ class SavingsTracker:
|
||||
delta_tool_tokens_saved = max(_coerce_int(tool_search_saved), 0)
|
||||
delta_input_tokens = _coerce_int(input_tokens)
|
||||
delta_output_tokens_saved = max(_coerce_int(output_tokens_saved), 0)
|
||||
delta_output_tokens_saved_high = (
|
||||
delta_output_tokens_saved
|
||||
if output_tokens_saved_high is None
|
||||
else max(_coerce_int(output_tokens_saved_high), delta_output_tokens_saved)
|
||||
)
|
||||
delta_output_tokens = max(_coerce_int(output_tokens), 0)
|
||||
delta_cache_read_tokens = _coerce_int(cache_read_tokens)
|
||||
priced = estimated_savings_usd
|
||||
@@ -1252,6 +1261,10 @@ class SavingsTracker:
|
||||
if priced is not None
|
||||
else _estimate_output_savings_usd(model, delta_output_tokens_saved)
|
||||
)
|
||||
# Same per-token rate table that priced the low end.
|
||||
delta_output_savings_usd_high = _estimate_output_savings_usd(
|
||||
model, delta_output_tokens_saved_high
|
||||
)
|
||||
# Completion spend. ``total_input_cost_usd`` has never had an output
|
||||
# counterpart, so anything answering "what share of my bill did
|
||||
# Headroom remove" had to divide savings that include output shaping by
|
||||
@@ -1343,6 +1356,13 @@ class SavingsTracker:
|
||||
lifetime.get("output_savings_usd", 0.0) + delta_output_savings_usd,
|
||||
6,
|
||||
)
|
||||
# High end of the output-savings range; equals the low end for
|
||||
# point estimates. Both state builders always write these keys.
|
||||
lifetime["output_tokens_saved_high"] += delta_output_tokens_saved_high
|
||||
lifetime["output_savings_usd_high"] = round(
|
||||
lifetime["output_savings_usd_high"] + delta_output_savings_usd_high,
|
||||
6,
|
||||
)
|
||||
lifetime["tool_tokens_saved"] += delta_tool_tokens_saved
|
||||
lifetime["tool_schema_savings_usd"] = round(
|
||||
lifetime["tool_schema_savings_usd"] + delta_tool_savings_usd,
|
||||
@@ -1851,6 +1871,8 @@ class SavingsTracker:
|
||||
"total_input_cost_usd": 0.0,
|
||||
"output_tokens_saved": 0,
|
||||
"output_savings_usd": 0.0,
|
||||
"output_tokens_saved_high": 0,
|
||||
"output_savings_usd_high": 0.0,
|
||||
"output_tokens": 0,
|
||||
"total_output_cost_usd": 0.0,
|
||||
},
|
||||
@@ -1923,6 +1945,8 @@ class SavingsTracker:
|
||||
is_v6_lifetime = False
|
||||
lifetime_output_tokens_saved = 0
|
||||
lifetime_output_savings_usd = 0.0
|
||||
lifetime_output_tokens_saved_high: int | None = None
|
||||
lifetime_output_savings_usd_high: float | None = None
|
||||
lifetime_output_tokens = 0
|
||||
lifetime_output_cost_usd = 0.0
|
||||
if isinstance(lifetime_raw, dict):
|
||||
@@ -1944,6 +1968,14 @@ class SavingsTracker:
|
||||
lifetime_basis = str(lifetime_raw.get("savings_basis") or BASIS_UNKNOWN)
|
||||
lifetime_output_tokens_saved = _coerce_int(lifetime_raw.get("output_tokens_saved"))
|
||||
lifetime_output_savings_usd = _coerce_float(lifetime_raw.get("output_savings_usd"))
|
||||
if "output_tokens_saved_high" in lifetime_raw:
|
||||
lifetime_output_tokens_saved_high = _coerce_int(
|
||||
lifetime_raw.get("output_tokens_saved_high")
|
||||
)
|
||||
if "output_savings_usd_high" in lifetime_raw:
|
||||
lifetime_output_savings_usd_high = _coerce_float(
|
||||
lifetime_raw.get("output_savings_usd_high")
|
||||
)
|
||||
lifetime_output_tokens = _coerce_int(lifetime_raw.get("output_tokens"))
|
||||
lifetime_output_cost_usd = _coerce_float(lifetime_raw.get("total_output_cost_usd"))
|
||||
|
||||
@@ -2044,6 +2076,14 @@ class SavingsTracker:
|
||||
"total_input_cost_usd": round(lifetime_input_cost_usd, 6),
|
||||
"output_tokens_saved": lifetime_output_tokens_saved,
|
||||
"output_savings_usd": round(lifetime_output_savings_usd, 6),
|
||||
# A high end below the low end can only come from the history
|
||||
# repair above raising the low end; never let the band invert.
|
||||
"output_tokens_saved_high": max(
|
||||
lifetime_output_tokens_saved_high or 0, lifetime_output_tokens_saved
|
||||
),
|
||||
"output_savings_usd_high": round(
|
||||
max(lifetime_output_savings_usd_high or 0.0, lifetime_output_savings_usd), 6
|
||||
),
|
||||
"output_tokens": lifetime_output_tokens,
|
||||
"total_output_cost_usd": round(lifetime_output_cost_usd, 6),
|
||||
},
|
||||
|
||||
@@ -9,6 +9,9 @@ SavingsRecorder.estimate_request_savings supplies that per-request number.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from headroom.proxy import output_savings
|
||||
from headroom.proxy.output_savings import (
|
||||
SavingsRecorder,
|
||||
stratum_key,
|
||||
@@ -86,3 +89,140 @@ def test_estimate_request_savings_zero_for_control_and_unknown(tmp_path):
|
||||
assert rec.estimate_request_savings(["something-else"], 600) == 0
|
||||
# Treatment but output exceeded the baseline -> clamped to 0, never negative.
|
||||
assert rec.estimate_request_savings([stratum_label("treatment", key)], 5000) == 0
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def l4_factors(monkeypatch):
|
||||
"""Benchmark factors as an enterprise extension would register them."""
|
||||
monkeypatch.setattr(output_savings, "MODELLED_REDUCTION", {4: (0.2, 0.5)})
|
||||
|
||||
|
||||
def test_shaped_request_without_a_baseline_is_priced_from_its_level_factors(tmp_path, l4_factors):
|
||||
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
|
||||
labels = [stratum_label("treatment", _key()), "output_shaper:verbosity:L4"]
|
||||
rec.record_from_labels(labels, 800) # the funnel records before it estimates
|
||||
|
||||
# Observed output is already shaped: saved = 800 * r / (1 - r).
|
||||
assert rec.request_savings_range(labels, 800) == (200, 800)
|
||||
|
||||
|
||||
def test_a_holdout_too_small_to_report_keeps_the_factor_tier(tmp_path, l4_factors):
|
||||
"""Same tier as the dashboard: one control observation does not make the
|
||||
holdout the headline, so the request stays on the modelled band."""
|
||||
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
|
||||
key = _key()
|
||||
shaped = [stratum_label("treatment", key), "output_shaper:verbosity:L4"]
|
||||
rec.record_from_labels(shaped, 800)
|
||||
rec.record_from_labels([stratum_label("control", key)], 1000)
|
||||
|
||||
assert rec._ledger.best_estimate(4).kind == "modelled"
|
||||
assert rec.request_savings_range(shaped, 800) == (200, 800)
|
||||
|
||||
|
||||
def test_measured_tier_credits_only_strata_inside_the_measurement(tmp_path, l4_factors):
|
||||
"""Devin's case: stratum A carries the holdout, stratum B has no control.
|
||||
A request in A books A's own control mean minus its output; a request in
|
||||
B books nothing, exactly as the measured headline leaves B out."""
|
||||
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
|
||||
a, b = "opus|a|s|tools", "opus|b|s|tools"
|
||||
for i in range(5):
|
||||
rec._ledger.record("control", a, 1000, f"c{i}")
|
||||
rec._ledger.record("treatment", a, 800, f"t{i}")
|
||||
rec._ledger.record("treatment", b, 1000, "tb")
|
||||
assert rec._ledger.best_estimate(4).kind == "measured"
|
||||
|
||||
shaped = "output_shaper:verbosity:L4"
|
||||
assert rec.request_savings_range([stratum_label("treatment", a), shaped], 800) == (200, 200)
|
||||
assert rec.request_savings_range([stratum_label("treatment", b), shaped], 1000) == (0, 0)
|
||||
|
||||
|
||||
def test_baseline_and_holdout_outrank_the_factors(tmp_path, l4_factors):
|
||||
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
|
||||
key = _key()
|
||||
for _ in range(5):
|
||||
rec._ledger.baseline.observe(key, 1000)
|
||||
|
||||
shaped = "output_shaper:verbosity:L4"
|
||||
assert rec.request_savings_range([stratum_label("treatment", key), shaped], 600) == (400, 400)
|
||||
assert rec.request_savings_range([stratum_label("control", key)], 600) == (0, 0)
|
||||
|
||||
|
||||
def test_no_registered_factors_means_no_modelled_saving(tmp_path):
|
||||
"""Plain OSS ships an empty factor table: nothing is booked."""
|
||||
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
|
||||
labels = [stratum_label("treatment", _key()), "output_shaper:verbosity:L4"]
|
||||
assert rec.request_savings_range(labels, 800) == (0, 0)
|
||||
|
||||
|
||||
def test_lifetime_carries_the_output_savings_range_across_a_restart(tmp_path):
|
||||
path = str(tmp_path / "s.json")
|
||||
tracker = SavingsTracker(path=path)
|
||||
tracker.record_request(
|
||||
model="claude-opus-4-8",
|
||||
input_tokens=1000,
|
||||
tokens_saved=0,
|
||||
output_tokens_saved=200,
|
||||
output_tokens_saved_high=800,
|
||||
timestamp="2026-03-27T09:00:00Z",
|
||||
)
|
||||
tracker.record_request( # a point estimate: high end equals low end
|
||||
model="claude-opus-4-8",
|
||||
input_tokens=1000,
|
||||
tokens_saved=0,
|
||||
output_tokens_saved=100,
|
||||
timestamp="2026-03-27T09:30:00Z",
|
||||
)
|
||||
|
||||
lifetime = SavingsTracker(path=path).snapshot()["lifetime"]
|
||||
assert lifetime["output_tokens_saved"] == 300
|
||||
assert lifetime["output_tokens_saved_high"] == 900
|
||||
low_usd, high_usd = lifetime["output_savings_usd"], lifetime["output_savings_usd_high"]
|
||||
assert low_usd > 0
|
||||
assert high_usd == pytest.approx(low_usd * 3, rel=1e-3)
|
||||
|
||||
|
||||
def test_treatment_request_that_was_not_shaped_saves_nothing(tmp_path, l4_factors):
|
||||
"""The stratum label is attached before shaping is attempted; only the
|
||||
verbosity label proves the request was shaped."""
|
||||
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
|
||||
key = _key()
|
||||
for _ in range(5):
|
||||
rec._ledger.baseline.observe(key, 1000)
|
||||
|
||||
assert rec.request_savings_range([stratum_label("treatment", key)], 600) == (0, 0)
|
||||
|
||||
|
||||
def test_factors_are_not_booked_once_the_deployment_has_a_baseline(tmp_path, l4_factors):
|
||||
"""A baseline learned for other traffic must not leave this request on
|
||||
benchmark factors while /stats reports the estimated tier."""
|
||||
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
|
||||
other = stratum_key(
|
||||
turn_kind="chat", input_tokens=500, model="claude-opus-4-8", has_tools=False
|
||||
)
|
||||
for _ in range(5):
|
||||
rec._ledger.baseline.observe(other, 1000)
|
||||
|
||||
labels = [stratum_label("treatment", _key()), "output_shaper:verbosity:L4"]
|
||||
rec.record_from_labels(labels, 800)
|
||||
low, high = rec.request_savings_range(labels, 800)
|
||||
assert low == high # a baseline point estimate, never the factor band
|
||||
|
||||
|
||||
def test_fresh_tracker_lifetime_carries_the_range_keys(tmp_path):
|
||||
lifetime = SavingsTracker(path=str(tmp_path / "s.json")).snapshot()["lifetime"]
|
||||
assert lifetime["output_tokens_saved_high"] == 0
|
||||
assert lifetime["output_savings_usd_high"] == 0.0
|
||||
|
||||
|
||||
def test_a_response_without_output_usage_books_nothing(tmp_path, l4_factors):
|
||||
"""A missing completion count arrives as 0; no tier may read that as
|
||||
the whole baseline saved."""
|
||||
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
|
||||
a = "opus|a|s|tools"
|
||||
for i in range(5):
|
||||
rec._ledger.record("control", a, 1000, f"c{i}")
|
||||
rec._ledger.record("treatment", a, 800, f"t{i}")
|
||||
rec._ledger.baseline.observe(a, 1000)
|
||||
shaped = [stratum_label("treatment", a), "output_shaper:verbosity:L4"]
|
||||
|
||||
assert rec.request_savings_range(shaped, 0) == (0, 0)
|
||||
|
||||
@@ -151,6 +151,8 @@ def test_savings_tracker_sanitizes_legacy_state_and_applies_retention(tmp_path):
|
||||
"total_input_cost_usd": 0.0,
|
||||
"output_tokens_saved": 0,
|
||||
"output_savings_usd": 0.0,
|
||||
"output_tokens_saved_high": 0,
|
||||
"output_savings_usd_high": 0.0,
|
||||
"output_tokens": 0,
|
||||
"total_output_cost_usd": 0.0,
|
||||
}
|
||||
@@ -205,6 +207,8 @@ def test_non_dict_savings_state_resets_to_default(tmp_path):
|
||||
"total_input_cost_usd": 0.0,
|
||||
"output_tokens_saved": 0,
|
||||
"output_savings_usd": 0.0,
|
||||
"output_tokens_saved_high": 0,
|
||||
"output_savings_usd_high": 0.0,
|
||||
"output_tokens": 0,
|
||||
"total_output_cost_usd": 0.0,
|
||||
}
|
||||
|
||||
@@ -723,3 +723,40 @@ def test_tokens_inflated_does_not_disturb_derived_sizes() -> None:
|
||||
assert o.attempted_input_tokens == 57845
|
||||
assert o.savings_pct == 0.0
|
||||
assert o.tokens_inflated == 2684
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_funnel_books_the_modelled_output_range_on_the_lifetime(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""Registered factors reach the tracker's lifetime totals end to end:
|
||||
outcome -> PrometheusMetrics.record_request -> SavingsTracker."""
|
||||
from headroom.proxy import output_savings
|
||||
from headroom.proxy.prometheus_metrics import PrometheusMetrics
|
||||
from headroom.proxy.savings_tracker import SavingsTracker
|
||||
|
||||
monkeypatch.setattr(output_savings, "MODELLED_REDUCTION", {4: (0.2, 0.5)})
|
||||
monkeypatch.setattr(
|
||||
output_savings, "_RECORDER", output_savings.SavingsRecorder(str(tmp_path / "o.json"))
|
||||
)
|
||||
tracker = SavingsTracker(path=str(tmp_path / "s.json"))
|
||||
h = _FunnelHarness()
|
||||
h.metrics = PrometheusMetrics(savings_tracker=tracker)
|
||||
key = output_savings.stratum_key(
|
||||
turn_kind="code", input_tokens=8000, model="claude-sonnet-4", has_tools=True
|
||||
)
|
||||
|
||||
await h._record_request_outcome(
|
||||
_outcome(
|
||||
output_tokens=800,
|
||||
transforms_applied=[
|
||||
output_savings.stratum_label("treatment", key),
|
||||
"output_shaper:verbosity:L4",
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
lifetime = tracker.snapshot()["lifetime"]
|
||||
assert lifetime["output_tokens_saved"] == 200
|
||||
assert lifetime["output_tokens_saved_high"] == 800
|
||||
assert lifetime["output_savings_usd_high"] > lifetime["output_savings_usd"] > 0
|
||||
|
||||
Reference in New Issue
Block a user