From 11850d02f8f44699f02b914f8fe1d94daa73845c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 20 Nov 2026 18:36:33 +0000 Subject: [PATCH 01/17] Price the analysis cost fallback only where row usage supports it When a model records no cost, model_cost_latency filled one from its price override with the base input and output rates on the summed token counts. That ignored cached and cache-write tokens for overrides that price them apart, and the Responses-API GPT models' long-context rate, which turns on one request's prompt length (above 272k prompt tokens OpenAI charges the whole request 2x input and cache and 1.5x output). A row records its share of its household's usage, summed over the household's requests, so no row holds one request's prompt length. The fallback now gives a GPT Responses model no cost, prices cached and cache-write tokens at an override's cache rates the way eval_no_tools._reconstruct_token_cost does, and gives no cost when the frame lacks the column of a cache rate the override lists. Overrides with only input and output rates keep the old arithmetic, so the two published fallback costs (Gemini 3.6 Flash, Grok Build 0.1) do not move by a bit. Co-Authored-By: Claude Opus 5.5 --- policybench/analysis.py | 100 ++++++++++--- policybench/config.py | 2 +- tests/test_cost_latency.py | 299 +++++++++++++++++++++++++++++++++---- 3 files changed, 351 insertions(+), 50 deletions(-) diff --git a/policybench/analysis.py b/policybench/analysis.py index 8154c38f..5f7faf4c 100644 --- a/policybench/analysis.py +++ b/policybench/analysis.py @@ -9,6 +9,7 @@ from policybench.config import ( BINARY_PROGRAMS, + GPT_RESPONSES_MODELS, PRICE_OVERRIDES_PER_1M, SEED, ) @@ -1456,6 +1457,74 @@ def household_latency_seconds(predictions: pd.DataFrame) -> pd.Series: ) +def _override_fallback_cost( + rows: pd.DataFrame, model: str, rates: dict[str, float] +) -> float | None: + """One model's cost from its price override, or None when it is unknown. + + The rows priced are those that recorded both prompt and completion token + counts. A row missing either count adds nothing, as + ``eval_no_tools._reconstruct_token_cost`` prices no such request, and a + model with no row to price (Claude Fable 5's frozen board rows record no + usage) gets no cost, not $0. + + A row's token counts are its share of its household's usage, summed over + the household's requests, so no row records one request's usage. An + override whose price depends on a request's own prompt length gives no + cost: the Responses-API GPT models (``GPT_RESPONSES_MODELS``) charge every + token of a request above 272k prompt tokens at a higher rate. Other + overrides price usage linearly, so the rows' sums price it exactly: + - an override with only input and output rates prices the prompt tokens, + cached ones included, at the input rate, as the reconstruction does; + - an override with a ``cache_read`` or ``cache_write`` rate prices the + rows' cached and cache-write tokens at those rates, bounded per row as + the reconstruction bounds them, and a missing rate is the input rate. + An empty count on a row is no such tokens, as the reconstruction reads + a count the provider did not report. A frame without the column of a + rate the override lists records none of that usage, so the model gets + no cost. + """ + if model in GPT_RESPONSES_MODELS: + return None + token_columns = ["prompt_tokens", "completion_tokens"] + if not set(token_columns) <= set(rows.columns): + return None + priced = rows.dropna(subset=token_columns) + if priced.empty: + return None + # The same grouped sum the published fallback costs were computed from, + # so an input-and-output override reproduces them to the bit. + sums = priced.groupby("model")[token_columns].sum().iloc[0] + prompt = float(sums["prompt_tokens"]) + completion = float(sums["completion_tokens"]) + if "cache_read" not in rates and "cache_write" not in rates: + return prompt * rates["input"] / 1e6 + completion * rates["output"] / 1e6 + for rate, column in ( + ("cache_read", "cached_prompt_tokens"), + ("cache_write", "cache_write_prompt_tokens"), + ): + if rate in rates and column not in priced.columns: + return None + + def recorded(column: str) -> pd.Series: + if column not in priced.columns: + return pd.Series(0.0, index=priced.index) + return priced[column].astype(float).fillna(0.0).clip(lower=0.0) + + row_prompt = priced["prompt_tokens"].astype(float) + cached = np.minimum(recorded("cached_prompt_tokens"), row_prompt) + cache_write = np.minimum(recorded("cache_write_prompt_tokens"), row_prompt - cached) + cached_total = float(cached.sum()) + cache_write_total = float(cache_write.sum()) + uncached = prompt - cached_total - cache_write_total + return ( + uncached * rates["input"] + + cached_total * rates.get("cache_read", rates["input"]) + + cache_write_total * rates.get("cache_write", rates["input"]) + + completion * rates["output"] + ) / 1e6 + + def model_cost_latency( predictions: pd.DataFrame, price_overrides: dict[str, dict[str, float]] | None = None, @@ -1467,11 +1536,9 @@ def model_cost_latency( each household's calls summed, then the median across households — which is robust to the occasional rate-limit retry that inflates the mean. When a model's reconstructed cost is missing (a provider preview model not yet in - litellm's price map), it is filled from ``price_overrides`` by pricing the - rows that recorded both prompt and completion token counts. A row missing - either count adds nothing, as ``eval_no_tools._reconstruct_token_cost`` - prices no such row, and a model with no row to price (Claude Fable 5's - frozen board rows record no usage) gets no cost, not $0. + litellm's price map), :func:`_override_fallback_cost` fills it from + ``price_overrides`` where the rows' recorded usage supports the override's + pricing, and otherwise the model gets no cost. """ if predictions.empty or "model" not in predictions.columns: return {} @@ -1483,28 +1550,15 @@ def model_cost_latency( household_latency_seconds(predictions).groupby("model").median() ) overrides = price_overrides or {} - token_columns = ["prompt_tokens", "completion_tokens"] - priceable = pd.DataFrame(columns=token_columns) - if set(token_columns) <= set(predictions.columns): - priceable = ( - predictions.dropna(subset=token_columns) - .groupby("model")[token_columns] - .sum() - ) out: dict[str, dict[str, float]] = {} for _, row in usage.iterrows(): model = str(row["model"]) cost = row.get("total_cost_usd") - if ( - (cost is None or pd.isna(cost)) - and model in overrides - and row["model"] in priceable.index - ): - price = overrides[model] - prompt, completion = priceable.loc[row["model"], token_columns] - cost = ( - float(prompt) * price["input"] / 1e6 - + float(completion) * price["output"] / 1e6 + if (cost is None or pd.isna(cost)) and model in overrides: + cost = _override_fallback_cost( + predictions.loc[predictions["model"] == row["model"]], + model, + overrides[model], ) entry: dict[str, float] = {} if cost is not None and not pd.isna(cost): diff --git a/policybench/config.py b/policybench/config.py index 06a7edeb..50922a96 100644 --- a/policybench/config.py +++ b/policybench/config.py @@ -306,7 +306,7 @@ # (eval_no_tools._extract_usage_metadata; eval-no-tools enables the # cache); and, for a model whose usage records no cost, # analysis.model_cost_latency computes one from the current entry's - # input and output rates. Once the entry changes, each would put the + # input, output and cache-read rates. Once the entry changes, each would put the # December rate on a request made in November. The pricing page # lists one rate at every prompt length, implicit caching only, and no # free tier for this model. litellm 1.95.0's bundled price map has no diff --git a/tests/test_cost_latency.py b/tests/test_cost_latency.py index 67a2d027..421aa6c2 100644 --- a/tests/test_cost_latency.py +++ b/tests/test_cost_latency.py @@ -3,17 +3,24 @@ Cost invariants, for every input (the property test executes them): - costUsd and costPerHousehold are both present or both absent; - a model has a cost exactly when one of its rows recorded total_cost_usd, or - it has a price override and one of its rows recorded both prompt and - completion token counts; a row missing either count is not priced, so no - cost rests on a count nobody recorded, and a model with no usage at all - gets no cost rather than $0; + it has a price override, is not a Responses-API GPT model, and one of its + rows recorded both prompt and completion token counts; a row missing either + count is not priced, so no cost rests on a count nobody recorded, and a + model with no usage at all gets no cost rather than $0; - a recorded cost is the sum of the recorded row costs and the override is not consulted; a filled cost is the override's prices applied to the token - sums of the rows that recorded both counts; + sums of the rows that recorded both counts, with cached and cache-write + tokens at the override's cache rates where it has them; +- a Responses-API GPT model's cost is never filled: its long-context rate + turns on one request's prompt length, and a row records a share of its + household's usage, not one request's; - costPerHousehold is costUsd over the distinct households in the input. -The frozen-snapshot tests check the published figures: every model's usage -fields but Claude Fable 5's reproduce from the frozen predictions, and Fable -5's, which those rows do not record, are not computed at all. +The parity tests check that a filled cost is what +eval_no_tools._reconstruct_token_cost records for the same usage. The +frozen-snapshot tests check the published figures: every model's usage +fields but Claude Fable 5's reproduce from the frozen predictions, including +the two models whose cost the override fills (Gemini 3.6 Flash and Grok Build +0.1), and Fable 5's, which those rows do not record, are not computed at all. """ import json @@ -27,7 +34,7 @@ from hypothesis import strategies as st from policybench.analysis import model_cost_latency -from policybench.config import PRICE_OVERRIDES_PER_1M +from policybench.config import GPT_RESPONSES_MODELS, MODELS, PRICE_OVERRIDES_PER_1M from policybench.snapshot_payload import read_run_payload ROOT = Path(__file__).resolve().parents[1] @@ -195,7 +202,185 @@ def test_recorded_zero_cost_and_recorded_zero_tokens_stay_zero(): assert out["zero-tokens"]["costUsd"] == 0.0 -MODEL_NAMES = ("a", "b", "c") +def _usage_row(model, scenario, prompt, completion, cached, cache_write): + return { + **_row(model, scenario, np.nan, 5.0, prompt=prompt, completion=completion), + "cached_prompt_tokens": cached, + "cache_write_prompt_tokens": cache_write, + } + + +@pytest.mark.parametrize("prompt", [100_000, 300_000]) +def test_gpt_responses_override_fills_no_cost(prompt): + """GPT-6.1 Sol charges a request above 272k prompt tokens 2x input and + cache and 1.5x output on every token. A row holds its household's usage + divided among its rows, so whether a request crossed 272k is not on the + row, and pricing the rows at the base rates could understate the cost.""" + model = "gpt-6.1-sol" + preds = pd.DataFrame( + [_usage_row(model, "s1", prompt, 20_000, 50_000, 0)], + ) + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert "costUsd" not in out[model] + assert "costPerHousehold" not in out[model] + assert out[model]["latencySeconds"] == pytest.approx(5.0) + + +def test_cache_rates_price_cached_and_cache_write_tokens(): + """Claude Fable 5.2's override lists $8 input, $0.20 cache reads, $10 + cache writes and $40 output per 1M tokens. The filled cost prices the + rows' cached and cache-write tokens at those rates, not at the input + rate.""" + model = "claude-fable-5.2" + rates = PRICE_OVERRIDES_PER_1M[model] + assert rates == { + "input": 8.0, + "output": 40.0, + "cache_read": 0.2, + "cache_write": 10.0, + } + preds = pd.DataFrame( + [_usage_row(model, "s1", 1_000_000, 10_000, 600_000, 100_000)], + ) + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + # 300k uncached at $8, 600k cached at $0.20, 100k written at $10, and + # 10k output at $40 per 1M: $2.40 + $0.12 + $1.00 + $0.40. + assert out[model]["costUsd"] == pytest.approx(3.92) + + +def test_cache_read_override_prices_cache_writes_at_input(): + """Grok 4.7's override lists a cache-read rate and no cache-write rate, + so cache-write tokens take the input rate, as the reconstruction prices + them, and a frame with no cache-write column still has a cost.""" + model = "grok-4.7" + preds = pd.DataFrame( + [_usage_row(model, "s1", 1_000_000, 100_000, 400_000, 200_000)], + ) + # $2 on 600k (uncached and written), $0.50 on 400k cached, $6 on 100k. + expected = (600_000 * 2.0 + 400_000 * 0.5 + 100_000 * 6.0) / 1e6 + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert out[model]["costUsd"] == pytest.approx(expected) + no_writes = preds.drop(columns=["cache_write_prompt_tokens"]) + out = model_cost_latency(no_writes, PRICE_OVERRIDES_PER_1M) + assert out[model]["costUsd"] == pytest.approx(expected) + + +@pytest.mark.parametrize( + "model, dropped", + [ + ("claude-fable-5.2", "cached_prompt_tokens"), + ("claude-fable-5.2", "cache_write_prompt_tokens"), + ("grok-4.7", "cached_prompt_tokens"), + ], +) +def test_cache_rate_without_its_column_fills_no_cost(model, dropped): + """A frame with no column for a usage the override prices apart records + none of that usage, so the cache distinction cannot be recovered.""" + preds = pd.DataFrame( + [_usage_row(model, "s1", 1_000_000, 10_000, 600_000, 100_000)], + ).drop(columns=[dropped]) + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert "costUsd" not in out[model] + + +def test_input_output_override_needs_no_cache_columns(): + """An override with only input and output rates prices every prompt token + at the input rate, so the cache columns do not matter.""" + preds = pd.DataFrame( + [_row("m", "s1", np.nan, 5.0, prompt=1_000_000, completion=2_000_000)] + ) + out = model_cost_latency(preds, {"m": {"input": 1.0, "output": 2.0}}) + assert out["m"]["costUsd"] == pytest.approx(5.0) + preds["cached_prompt_tokens"] = 500_000.0 + out = model_cost_latency(preds, {"m": {"input": 1.0, "output": 2.0}}) + assert out["m"]["costUsd"] == pytest.approx(5.0) + + +def test_unreported_cache_count_is_no_cached_tokens(): + """An empty count on a row is no such tokens, as the reconstruction reads + a count the provider did not report.""" + model = "claude-fable-5.2" + preds = pd.DataFrame( + [_usage_row(model, "s1", 1_000_000, 10_000, np.nan, np.nan)], + ) + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert out[model]["costUsd"] == pytest.approx((8_000_000 + 400_000) / 1e6) + + +def _reconstruction(): + """eval_no_tools imports litellm, so the parity tests import it lazily.""" + from policybench.eval_no_tools import _reconstruct_token_cost + + return _reconstruct_token_cost + + +USAGES = [ + (1_000, 500, None, None), + (120_000, 30_000, 70_000, None), + (150_000, 8_000, 40_000, 25_000), + (300_000, 12_000, 100_000, 50_000), + (80_000, 4_000, 90_000, 5_000), # a cached count above the prompt count +] + + +@pytest.mark.parametrize("model", sorted(PRICE_OVERRIDES_PER_1M)) +@pytest.mark.parametrize("prompt, completion, cached, cache_write", USAGES) +def test_filled_cost_matches_request_reconstruction( + model, prompt, completion, cached, cache_write +): + """A household answered by one request has its usage on one row here, so + the filled cost is what eval_no_tools._reconstruct_token_cost records for + that request, for every override; a GPT Responses model's is not filled.""" + reconstruct = _reconstruction() + recorded = reconstruct( + model_name=model, + model_id=MODELS.get(model, model), + prompt_tokens=prompt, + completion_tokens=completion, + cached_prompt_tokens=cached, + cache_write_prompt_tokens=cache_write, + ) + assert recorded.usd is not None and recorded.is_estimated is False + preds = pd.DataFrame( + [ + _usage_row( + model, + "s1", + prompt, + completion, + np.nan if cached is None else cached, + np.nan if cache_write is None else cache_write, + ) + ] + ) + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M)[model] + if model in GPT_RESPONSES_MODELS: + assert "costUsd" not in out + else: + assert out["costUsd"] == pytest.approx(recorded.usd, rel=1e-12) + + +def test_filled_cost_splits_like_the_request(): + """Rows that share a request's usage equally price to the request's cost: + the fill is linear in each token count.""" + reconstruct = _reconstruction() + model = "claude-fable-5.2" + request = reconstruct( + model_name=model, + model_id=MODELS[model], + prompt_tokens=210_000, + completion_tokens=21_000, + cached_prompt_tokens=140_000, + cache_write_prompt_tokens=35_000, + ) + preds = pd.DataFrame( + [_usage_row(model, "s1", 210_000 / 7, 3_000, 20_000, 5_000) for _ in range(7)] + ) + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert out[model]["costUsd"] == pytest.approx(request.usd, rel=1e-12) + + +MODEL_NAMES = ("a", "b", "c", "gpt-6.1-sol") SCENARIOS = ("s1", "s2", "s3", "s4") missing = st.just(float("nan")) @@ -210,18 +395,25 @@ def test_recorded_zero_cost_and_recorded_zero_tokens_stay_zero(): ), "prompt_tokens": st.one_of(missing, st.integers(0, 5_000_000).map(float)), "completion_tokens": st.one_of(missing, st.integers(0, 5_000_000).map(float)), + "cached_prompt_tokens": st.one_of( + missing, st.integers(0, 6_000_000).map(float) + ), + "cache_write_prompt_tokens": st.one_of( + missing, st.integers(0, 6_000_000).map(float) + ), "elapsed_seconds": st.one_of(missing, st.floats(min_value=0, max_value=600)), } ) +rate = st.floats(min_value=0, max_value=100, allow_subnormal=False) price = st.fixed_dictionaries( - { - "input": st.floats(min_value=0, max_value=100, allow_subnormal=False), - "output": st.floats(min_value=0, max_value=100, allow_subnormal=False), - } + {"input": rate, "output": rate}, + optional={"cache_read": rate, "cache_write": rate}, ) -def _reference_cost(rows: list[dict], override: dict | None) -> float | None: +def _reference_cost( + model: str, rows: list[dict], override: dict | None +) -> float | None: """The cost the invariants define, from the rows in plain Python.""" recorded = [ r["total_cost_usd"] for r in rows if not math.isnan(r["total_cost_usd"]) @@ -233,12 +425,28 @@ def _reference_cost(rows: list[dict], override: dict | None) -> float | None: for r in rows if not math.isnan(r["prompt_tokens"]) and not math.isnan(r["completion_tokens"]) ] - if override is None or not priced: + if override is None or not priced or model in GPT_RESPONSES_MODELS: return None + prompt = math.fsum(r["prompt_tokens"] for r in priced) + completion = math.fsum(r["completion_tokens"] for r in priced) + if "cache_read" not in override and "cache_write" not in override: + return prompt * override["input"] / 1e6 + completion * override["output"] / 1e6 + + def count(value): + return 0.0 if math.isnan(value) else value + + cached = [min(count(r["cached_prompt_tokens"]), r["prompt_tokens"]) for r in priced] + written = [ + min(count(r["cache_write_prompt_tokens"]), r["prompt_tokens"] - c) + for r, c in zip(priced, cached) + ] + uncached = prompt - math.fsum(cached) - math.fsum(written) return ( - math.fsum(r["prompt_tokens"] for r in priced) * override["input"] / 1e6 - + math.fsum(r["completion_tokens"] for r in priced) * override["output"] / 1e6 - ) + uncached * override["input"] + + math.fsum(cached) * override.get("cache_read", override["input"]) + + math.fsum(written) * override.get("cache_write", override["input"]) + + completion * override["output"] + ) / 1e6 @settings(max_examples=300, deadline=None) @@ -275,7 +483,7 @@ def test_cost_is_present_exactly_when_recorded_usage_supports_it( for model in sorted(set(frame["model"])): entry = out.get(model, {}) expected = _reference_cost( - [r for r in rows if r["model"] == model], overrides.get(model) + model, [r for r in rows if r["model"] == model], overrides.get(model) ) assert ("costUsd" in entry) == ("costPerHousehold" in entry) if expected is None: @@ -292,12 +500,15 @@ def test_cost_is_present_exactly_when_recorded_usage_supports_it( USAGE_FIELDS = ("costUsd", "costPerHousehold", "latencySeconds", "totalTokens") -@pytest.fixture(scope="module") -def frozen(): +def _frozen_run() -> Path: manifest = json.loads((SNAPSHOT_DIR / "manifest.json").read_text()) - run = SNAPSHOT_DIR / "runs" / manifest["source_run_labels"]["us"] - predictions = pd.read_csv( - run / "predictions.csv.gz", + return SNAPSHOT_DIR / "runs" / manifest["source_run_labels"]["us"] + + +@pytest.fixture(scope="module") +def frozen_predictions(): + return pd.read_csv( + _frozen_run() / "predictions.csv.gz", usecols=[ "model", "scenario_id", @@ -309,11 +520,18 @@ def frozen(): "prompt_tokens", "completion_tokens", "total_tokens", + "cached_prompt_tokens", + "cache_write_prompt_tokens", ], low_memory=False, ) + + +@pytest.fixture(scope="module") +def frozen(frozen_predictions): + run = _frozen_run() published = {row["model"]: row for row in read_run_payload(run)["modelStats"]} - return model_cost_latency(predictions, PRICE_OVERRIDES_PER_1M), published + return model_cost_latency(frozen_predictions, PRICE_OVERRIDES_PER_1M), published def test_frozen_usage_reproduces_every_published_model_but_fable_5(frozen): @@ -337,6 +555,35 @@ def test_frozen_fable_5_usage_is_carried_not_computed(frozen): assert all(fable[k] > 0 for k in USAGE_FIELDS) +# The published board's models whose cost the override fills, and the costs +# the board publishes for them (paper/snapshot/20260501, 2026-11-20). +FROZEN_FILLED_COSTS = { + "gemini-3.6-flash": 5.4831164999999995, + "grok-build-0.1": 4.487201, +} + + +def test_frozen_filled_costs_are_the_published_ones(frozen, frozen_predictions): + """Exactly two published models record no cost on any row and take the + override's: their overrides list only input and output rates, so the + fill prices every prompt token at the input rate, as it did when the + board was published, and the figures do not move by a bit.""" + computed, published = frozen + filled = sorted( + model + for model, rows in frozen_predictions.groupby("model") + if rows["total_cost_usd"].isna().all() + and model in PRICE_OVERRIDES_PER_1M + and rows[["prompt_tokens", "completion_tokens"]].notna().all(axis=1).any() + ) + assert filled == sorted(FROZEN_FILLED_COSTS) + for model, cost in FROZEN_FILLED_COSTS.items(): + assert set(PRICE_OVERRIDES_PER_1M[model]) == {"input", "output"} + assert model not in GPT_RESPONSES_MODELS + assert published[model]["costUsd"] == cost + assert computed[model]["costUsd"] == cost + + # ----- invariants of household latency (docs/latency_replay_audit.md) ------- from hypothesis import given, settings # noqa: E402 From 0779cbac8853c4b59538fbfc5c1a21858c719d6f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 20 Nov 2026 18:50:04 +0000 Subject: [PATCH 02/17] Say how batch rows share a request's usage in the fallback docstring A batch run splits one chunk's request among the chunk's outputs, not a household's summed requests. The rows still record neither a request's prompt length nor how many rows share it, so the conclusion stands. Co-Authored-By: Claude Opus 5.5 --- policybench/analysis.py | 8 +++++--- tests/test_cost_latency.py | 10 +++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/policybench/analysis.py b/policybench/analysis.py index 5f7faf4c..bb6cf37e 100644 --- a/policybench/analysis.py +++ b/policybench/analysis.py @@ -1468,9 +1468,11 @@ def _override_fallback_cost( model with no row to price (Claude Fable 5's frozen board rows record no usage) gets no cost, not $0. - A row's token counts are its share of its household's usage, summed over - the household's requests, so no row records one request's usage. An - override whose price depends on a request's own prompt length gives no + A row's token counts are an equal share of its request group's usage: a + synchronous run sums all of a household's requests, and a batch run + splits one chunk's request among the chunk's outputs. The rows record + neither a request's prompt length nor how many rows share it, so an + override whose price depends on one request's prompt length gives no cost: the Responses-API GPT models (``GPT_RESPONSES_MODELS``) charge every token of a request above 272k prompt tokens at a higher rate. Other overrides price usage linearly, so the rows' sums price it exactly: diff --git a/tests/test_cost_latency.py b/tests/test_cost_latency.py index 421aa6c2..216afc78 100644 --- a/tests/test_cost_latency.py +++ b/tests/test_cost_latency.py @@ -12,8 +12,8 @@ sums of the rows that recorded both counts, with cached and cache-write tokens at the override's cache rates where it has them; - a Responses-API GPT model's cost is never filled: its long-context rate - turns on one request's prompt length, and a row records a share of its - household's usage, not one request's; + turns on one request's prompt length, and a row records an equal share of + its request group's usage, not one request's prompt length; - costPerHousehold is costUsd over the distinct households in the input. The parity tests check that a filled cost is what eval_no_tools._reconstruct_token_cost records for the same usage. The @@ -213,9 +213,9 @@ def _usage_row(model, scenario, prompt, completion, cached, cache_write): @pytest.mark.parametrize("prompt", [100_000, 300_000]) def test_gpt_responses_override_fills_no_cost(prompt): """GPT-6.1 Sol charges a request above 272k prompt tokens 2x input and - cache and 1.5x output on every token. A row holds its household's usage - divided among its rows, so whether a request crossed 272k is not on the - row, and pricing the rows at the base rates could understate the cost.""" + cache and 1.5x output on every token. A row holds an equal share of its + request group's usage, so the row does not show whether a request crossed + 272k, and pricing the rows at the base rates could understate the cost.""" model = "gpt-6.1-sol" preds = pd.DataFrame( [_usage_row(model, "s1", prompt, 20_000, 50_000, 0)], From 200981b6d0a6d7dc1c05732dc941e503e4558d73 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 20 Nov 2026 20:43:19 +0000 Subject: [PATCH 03/17] Fill a cache-rate cost only from rows that each record one response (review r1) Review round 1 of #273 found three ways the fill gave a wrong cost: - A categorical model column: under pandas 2's groupby default the grouped sum has a row for every category, and .iloc[0] took the first one, so a model that was not the first category was priced from zeros. Select the model's own group, with observed=True. - Rows that sum several responses: bounding the summed cache counts by the summed prompt is not what the reconstruction does response by response. A cache-rate fill now needs every priced row to record one response (live_calls + cache_hit_calls == 1). - Empty cache counts read as zero: concatenating per-model frames pads a column one frame lacks, so a model whose rows never recorded cache usage got a cache-blind cost. An empty count for a rate the override lists now gives no cost. GPT Responses models still get no cost: a household's row sum bounds a request's prompt only on a frame known to hold every row, which the rows cannot show. The two published fallback costs (Gemini 3.6 Flash, Grok Build 0.1) use input-and-output overrides and are unchanged to the bit. Co-Authored-By: Claude Fable 5.2 --- policybench/analysis.py | 113 ++++++++---- policybench/config.py | 6 +- tests/test_cost_latency.py | 340 +++++++++++++++++++++++++++++++++---- 3 files changed, 384 insertions(+), 75 deletions(-) diff --git a/policybench/analysis.py b/policybench/analysis.py index bb6cf37e..aa230fe6 100644 --- a/policybench/analysis.py +++ b/policybench/analysis.py @@ -1457,34 +1457,61 @@ def household_latency_seconds(predictions: pd.DataFrame) -> pd.Series: ) +# The row columns that count the provider responses a row's usage sums: +# eval_no_tools.NO_TOOLS_CALL_PROVENANCE_COLUMNS without the time (analysis +# does not import eval_no_tools, which imports litellm). +RESPONSE_COUNT_COLUMNS = ("live_calls", "cache_hit_calls") + + def _override_fallback_cost( rows: pd.DataFrame, model: str, rates: dict[str, float] ) -> float | None: """One model's cost from its price override, or None when it is unknown. The rows priced are those that recorded both prompt and completion token - counts. A row missing either count adds nothing, as - ``eval_no_tools._reconstruct_token_cost`` prices no such request, and a - model with no row to price (Claude Fable 5's frozen board rows record no - usage) gets no cost, not $0. - - A row's token counts are an equal share of its request group's usage: a - synchronous run sums all of a household's requests, and a batch run - splits one chunk's request among the chunk's outputs. The rows record - neither a request's prompt length nor how many rows share it, so an - override whose price depends on one request's prompt length gives no - cost: the Responses-API GPT models (``GPT_RESPONSES_MODELS``) charge every - token of a request above 272k prompt tokens at a higher rate. Other - overrides price usage linearly, so the rows' sums price it exactly: - - an override with only input and output rates prices the prompt tokens, - cached ones included, at the input rate, as the reconstruction does; - - an override with a ``cache_read`` or ``cache_write`` rate prices the - rows' cached and cache-write tokens at those rates, bounded per row as - the reconstruction bounds them, and a missing rate is the input rate. - An empty count on a row is no such tokens, as the reconstruction reads - a count the provider did not report. A frame without the column of a - rate the override lists records none of that usage, so the model gets - no cost. + counts. A row missing either count adds nothing, and a model with no row + to price (Claude Fable 5's frozen board rows record no usage) gets no + cost, not $0. + + A row's counts can sum several provider responses. A synchronous run + adds up a household's responses (retries, repairs and chunks) and gives + each row an equal share; a batch run gives each cell's row a share of + the chunk request that answered it, summed over repair rounds; and a row + repair replaces a row's usage with the whole usage of its own responses. + ``live_calls`` plus ``cache_hit_calls`` counts the responses a row sums, + or more when a response reported no usage. + + - An override with only input and output rates prices the rows' summed + prompt tokens, cached ones included, at the input rate and their + completion tokens at the output rate. The sums take in every response + a row adds up, including one that reported a prompt count and no + completion count, or the reverse, which + ``eval_no_tools._reconstruct_token_cost`` would not price. + - The Responses-API GPT models (``GPT_RESPONSES_MODELS``) charge every + token of a request above 272k prompt tokens at a higher rate. No row + records a request's own prompt count or how many rows share it, and a + sum over a household's rows bounds a request's prompt only when the + frame holds every row the request was split among, unrepaired, which + the rows cannot show. These models get no cost. + - An override with a ``cache_read`` or ``cache_write`` rate prices cached + and cache-write tokens at those rates (a rate it does not list is the + input rate), bounding each row's counts by its prompt count as the + reconstruction bounds a response's. The bound of a sum is not the sum + of the bounds, so it needs rows that each hold one response's usage: + every priced row must record one response, a cached count, and, if + the override lists a cache-write rate, a cache-write count (with no + such rate, cache-write tokens price at the input rate like uncached + ones, so their count changes nothing). A row's counts are then that + response's counts divided among the rows sharing it, and each row + prices to its share of the response's cost. Otherwise the model gets + no cost: an empty count may be one the provider did not report or a + column another model's rows brought into the frame, and an empty + response count may be a row written before the column existed. + + The rates are the override's, as the reconstruction applies them: at any + prompt length, since the GPT long-context rate is the only length tier + the reconstruction models (the Claude Haiku 5.5 entry lists the rates + for prompts up to 100,000 tokens). """ if model in GPT_RESPONSES_MODELS: return None @@ -1495,23 +1522,35 @@ def _override_fallback_cost( if priced.empty: return None # The same grouped sum the published fallback costs were computed from, - # so an input-and-output override reproduces them to the bit. - sums = priced.groupby("model")[token_columns].sum().iloc[0] + # so an input-and-output override reproduces them to the bit. The model's + # own group: pandas 2 also gives a categorical column's other categories + # a group (all zero) unless observed is set. + sums = ( + priced.groupby("model", observed=True)[token_columns] + .sum() + .loc[priced["model"].iloc[0]] + ) prompt = float(sums["prompt_tokens"]) completion = float(sums["completion_tokens"]) if "cache_read" not in rates and "cache_write" not in rates: return prompt * rates["input"] / 1e6 + completion * rates["output"] / 1e6 - for rate, column in ( - ("cache_read", "cached_prompt_tokens"), - ("cache_write", "cache_write_prompt_tokens"), - ): - if rate in rates and column not in priced.columns: - return None + # The cached count prices at the cache-read rate and bounds the + # cache-write count; with no cache-write rate, cache-write tokens price + # at the input rate like uncached ones, so their count changes nothing. + counts = ["cached_prompt_tokens"] + if "cache_write" in rates: + counts.append("cache_write_prompt_tokens") + needed = [*counts, *RESPONSE_COUNT_COLUMNS] + if not set(needed) <= set(priced.columns) or priced[needed].isna().any().any(): + return None + responses = sum(priced[column].astype(float) for column in RESPONSE_COUNT_COLUMNS) + if not (responses == 1).all(): + return None def recorded(column: str) -> pd.Series: - if column not in priced.columns: + if column not in counts: return pd.Series(0.0, index=priced.index) - return priced[column].astype(float).fillna(0.0).clip(lower=0.0) + return priced[column].astype(float).clip(lower=0.0) row_prompt = priced["prompt_tokens"].astype(float) cached = np.minimum(recorded("cached_prompt_tokens"), row_prompt) @@ -1536,11 +1575,11 @@ def model_cost_latency( Cost is the run total in USD (matching :func:`usage_summary_by_model`) plus a per-household figure. Latency is the *median* per-household request-time — each household's calls summed, then the median across households — which is - robust to the occasional rate-limit retry that inflates the mean. When a - model's reconstructed cost is missing (a provider preview model not yet in - litellm's price map), :func:`_override_fallback_cost` fills it from - ``price_overrides`` where the rows' recorded usage supports the override's - pricing, and otherwise the model gets no cost. + robust to the occasional rate-limit retry that inflates the mean. When no + row of a model records a cost (rows from a run that had no price for the + model), :func:`_override_fallback_cost` fills it from ``price_overrides`` + where the rows' recorded usage supports the override's pricing, and + otherwise the model gets no cost and no ``costUsd`` key. """ if predictions.empty or "model" not in predictions.columns: return {} diff --git a/policybench/config.py b/policybench/config.py index 50922a96..d58a7a08 100644 --- a/policybench/config.py +++ b/policybench/config.py @@ -305,9 +305,9 @@ # response the LiteLLM disk cache replays at the replay # (eval_no_tools._extract_usage_metadata; eval-no-tools enables the # cache); and, for a model whose usage records no cost, - # analysis.model_cost_latency computes one from the current entry's - # input, output and cache-read rates. Once the entry changes, each would put the - # December rate on a request made in November. The pricing page + # analysis.model_cost_latency can compute one from the current entry's + # input, output and cache-read rates. Once the entry changes, each would + # put the December rate on a request made in November. The pricing page # lists one rate at every prompt length, implicit caching only, and no # free tier for this model. litellm 1.95.0's bundled price map has no # gemini-4 id, and its remote map priced the 2026-11-14 gauntlet's calls diff --git a/tests/test_cost_latency.py b/tests/test_cost_latency.py index 216afc78..2378b3c2 100644 --- a/tests/test_cost_latency.py +++ b/tests/test_cost_latency.py @@ -2,25 +2,31 @@ Cost invariants, for every input (the property test executes them): - costUsd and costPerHousehold are both present or both absent; -- a model has a cost exactly when one of its rows recorded total_cost_usd, or - it has a price override, is not a Responses-API GPT model, and one of its - rows recorded both prompt and completion token counts; a row missing either - count is not priced, so no cost rests on a count nobody recorded, and a - model with no usage at all gets no cost rather than $0; - a recorded cost is the sum of the recorded row costs and the override is - not consulted; a filled cost is the override's prices applied to the token - sums of the rows that recorded both counts, with cached and cache-write - tokens at the override's cache rates where it has them; + not consulted; +- otherwise a model has a cost exactly when it has a price override that is + not a Responses-API GPT model and one of its rows recorded both prompt and + completion token counts, and, for an override with a cache rate, every such + row records one provider response (live_calls + cache_hit_calls == 1), a + cached count and, if the override lists a cache-write rate, a cache-write + count; a row missing either token count is not priced, so no cost rests on + a count nobody recorded, and a model with no usage at all gets no cost + rather than $0; +- a filled cost is the override's input and output rates applied to the + token sums of the rows that recorded both counts, with each row's cached + and cache-write tokens, bounded by its prompt count, at the override's + cache rates where it has them; - a Responses-API GPT model's cost is never filled: its long-context rate - turns on one request's prompt length, and a row records an equal share of - its request group's usage, not one request's prompt length; + turns on one request's prompt length, which no row records; - costPerHousehold is costUsd over the distinct households in the input. -The parity tests check that a filled cost is what -eval_no_tools._reconstruct_token_cost records for the same usage. The -frozen-snapshot tests check the published figures: every model's usage -fields but Claude Fable 5's reproduce from the frozen predictions, including -the two models whose cost the override fills (Gemini 3.6 Flash and Grok Build -0.1), and Fable 5's, which those rows do not record, are not computed at all. +The reconstruction tests check that a filled cache-rate cost is what +eval_no_tools._reconstruct_token_cost records for the one response the rows +share, and that rows summing two responses, or with an unrecorded count, get +no cost. The frozen-snapshot tests check the published figures: every model's +usage fields but Claude Fable 5's reproduce from the frozen predictions, +including the two models whose cost the override fills (Gemini 3.6 Flash and +Grok Build 0.1), and Fable 5's, which those rows do not record, are not +computed at all. """ import json @@ -33,7 +39,7 @@ from hypothesis import given, settings from hypothesis import strategies as st -from policybench.analysis import model_cost_latency +from policybench.analysis import RESPONSE_COUNT_COLUMNS, model_cost_latency from policybench.config import GPT_RESPONSES_MODELS, MODELS, PRICE_OVERRIDES_PER_1M from policybench.snapshot_payload import read_run_payload @@ -202,11 +208,17 @@ def test_recorded_zero_cost_and_recorded_zero_tokens_stay_zero(): assert out["zero-tokens"]["costUsd"] == 0.0 -def _usage_row(model, scenario, prompt, completion, cached, cache_write): +def _usage_row( + model, scenario, prompt, completion, cached, cache_write, live=1, cache_hits=0 +): + """A row with no recorded cost; by default its usage is one live + response's.""" return { **_row(model, scenario, np.nan, 5.0, prompt=prompt, completion=completion), "cached_prompt_tokens": cached, "cache_write_prompt_tokens": cache_write, + "live_calls": live, + "cache_hit_calls": cache_hits, } @@ -226,6 +238,21 @@ def test_gpt_responses_override_fills_no_cost(prompt): assert out[model]["latencySeconds"] == pytest.approx(5.0) +def test_gpt_household_sum_does_not_bound_a_request_on_a_partial_frame(): + """One GPT-6.1 Sol request of 300,000 prompt tokens, above the 272k line, + split among a household's four rows. A frame holding three of them sums + to 225,000, which looks like a base-rate request. The rows do not show + whether a household is complete, so a household's sum is not used to + place its requests under 272k, and the model gets no cost.""" + model = "gpt-6.1-sol" + household = [_usage_row(model, "s1", 300_000 / 4, 5_000, 0, 0) for _ in range(4)] + partial = pd.DataFrame(household[:3]) + assert partial["prompt_tokens"].sum() < 272_000 < 300_000 + for frame in (partial, pd.DataFrame(household)): + out = model_cost_latency(frame, PRICE_OVERRIDES_PER_1M) + assert "costUsd" not in out[model] + + def test_cache_rates_price_cached_and_cache_write_tokens(): """Claude Fable 5.2's override lists $8 input, $0.20 cache reads, $10 cache writes and $40 output per 1M tokens. The filled cost prices the @@ -296,15 +323,221 @@ def test_input_output_override_needs_no_cache_columns(): assert out["m"]["costUsd"] == pytest.approx(5.0) -def test_unreported_cache_count_is_no_cached_tokens(): - """An empty count on a row is no such tokens, as the reconstruction reads - a count the provider did not report.""" +@pytest.mark.parametrize( + "model, emptied", + [ + ("claude-fable-5.2", "cached_prompt_tokens"), + ("claude-fable-5.2", "cache_write_prompt_tokens"), + ("grok-4.7", "cached_prompt_tokens"), + ], +) +def test_empty_cache_count_fills_no_cost(model, emptied): + """An empty count may be one the provider did not report or a column + another model's rows brought into the frame, so the cache distinction + cannot be recovered and the model gets no cost.""" + preds = pd.DataFrame( + [ + _usage_row(model, "s1", 1_000_000, 10_000, 600_000, 100_000), + _usage_row(model, "s2", 1_000_000, 10_000, 600_000, 100_000), + ] + ) + preds.loc[1, emptied] = np.nan + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert "costUsd" not in out[model] + + +def test_empty_cache_write_count_is_irrelevant_without_a_cache_write_rate(): + """Grok 4.7 lists no cache-write rate, so cache-write tokens price at the + input rate like uncached ones and an empty cache-write count changes + nothing.""" + model = "grok-4.7" + preds = pd.DataFrame( + [_usage_row(model, "s1", 1_000_000, 100_000, 400_000, np.nan)], + ) + expected = (600_000 * 2.0 + 400_000 * 0.5 + 100_000 * 6.0) / 1e6 + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert out[model]["costUsd"] == pytest.approx(expected) + + +def test_concatenated_frames_fill_no_cost_from_padded_cache_columns(): + """full_run_export and fold_board concatenate per-model frames, and + pandas pads a column one frame lacks with NaN. A cache-rate model whose + own rows have no cache columns gets no cost in the combined frame, as it + does alone.""" + model = "claude-fable-5.2" + older = pd.DataFrame( + [_row(model, s, np.nan, 5.0, prompt=1_000, completion=200) for s in "ab"] + ) + newer = pd.DataFrame( + [ + { + **_usage_row("claude-opus-5.5", s, 1_000, 200, 400, 0), + "total_cost_usd": 0.01, + } + for s in "ab" + ] + ) + combined = pd.concat([older, newer], ignore_index=True) + assert combined.loc[combined["model"] == model, "cached_prompt_tokens"].isna().all() + assert "costUsd" not in model_cost_latency(older, PRICE_OVERRIDES_PER_1M)[model] + assert "costUsd" not in model_cost_latency(combined, PRICE_OVERRIDES_PER_1M)[model] + + +def _two_response_rows(model, first, second, rows): + """One synchronous household answered by two responses: the runner sums + their counts (_aggregate_request_results), splits the sums equally among + the household's rows and repeats the response count on each.""" + summed = [a + b for a, b in zip(first, second)] + return [ + _usage_row(model, "s1", *(count / rows for count in summed), live=2) + for _ in range(rows) + ] + + +def test_rows_summing_two_responses_fill_no_cost(): + """Two Fable 5.2 responses of 100,000 prompt and 1,000 completion tokens, + with 150,000 and 0 cache reads reported: the reconstruction bounds the + first response's reads by its prompt and prices the two at $0.90, but + bounding the household's sums would give $0.51. Rows that sum responses + do not show each response's counts, so the model gets no cost.""" + reconstruct = _reconstruction() + model = "claude-fable-5.2" + first, second = (100_000, 1_000, 150_000, 0), (100_000, 1_000, 0, 0) + per_response = sum( + reconstruct( + model_name=model, + model_id=MODELS[model], + prompt_tokens=p, + completion_tokens=c, + cached_prompt_tokens=r, + cache_write_prompt_tokens=w, + ).usd + for p, c, r, w in (first, second) + ) + assert per_response == pytest.approx(0.90) + preds = pd.DataFrame(_two_response_rows(model, first, second, rows=4)) + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert "costUsd" not in out[model] + + +@pytest.mark.parametrize( + "live, cache_hits", [(2, 0), (1, 1), (0, 2), (0, 0), (np.nan, 0), (1, np.nan)] +) +def test_cache_rates_need_rows_recording_one_response(live, cache_hits): + """A cache-rate fill needs every priced row to record one response, live + or replayed; a row recording none, several, or no count gets no cost. + (One replayed response is priced: test_one_replayed_response_is_priced.)""" model = "claude-fable-5.2" preds = pd.DataFrame( - [_usage_row(model, "s1", 1_000_000, 10_000, np.nan, np.nan)], + [ + _usage_row(model, "s1", 1_000, 200, 400, 100), + _usage_row(model, "s2", 1_000, 200, 400, 100, live, cache_hits), + ] ) out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) - assert out[model]["costUsd"] == pytest.approx((8_000_000 + 400_000) / 1e6) + assert "costUsd" not in out[model] + + +def test_cache_rates_need_the_response_count_columns(): + model = "claude-fable-5.2" + preds = pd.DataFrame([_usage_row(model, "s1", 1_000, 200, 400, 100)]) + for column in RESPONSE_COUNT_COLUMNS: + out = model_cost_latency(preds.drop(columns=[column]), PRICE_OVERRIDES_PER_1M) + assert "costUsd" not in out[model] + + +def test_one_replayed_response_is_priced(): + """A response the disk cache replays records its usage like a live one.""" + model = "claude-fable-5.2" + preds = pd.DataFrame( + [_usage_row(model, "s1", 1_000_000, 10_000, 600_000, 100_000, 0, 1)] + ) + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert out[model]["costUsd"] == pytest.approx(3.92) + + +def test_response_count_columns_are_the_runner_provenance_counts(): + from policybench.eval_no_tools import NO_TOOLS_CALL_PROVENANCE_COLUMNS + + assert set(RESPONSE_COUNT_COLUMNS) == set(NO_TOOLS_CALL_PROVENANCE_COLUMNS) - { + "live_elapsed_seconds" + } + + +def test_input_output_override_ignores_response_counts(): + """An input-and-output override prices the rows' sums, which are linear + in the responses they add up, so rows recording several responses, or no + count, still price.""" + preds = pd.DataFrame( + [ + _usage_row("m", "s1", 1_000_000, 2_000_000, np.nan, np.nan, live=3), + _usage_row("m", "s2", 1_000_000, 2_000_000, np.nan, np.nan, live=np.nan), + ] + ) + out = model_cost_latency(preds, {"m": {"input": 1.0, "output": 2.0}}) + assert out["m"]["costUsd"] == pytest.approx(10.0) + + +def test_cache_write_rate_needs_the_cached_count(): + """The cached count bounds the cache-write count, so an override with a + cache-write rate and no cache-read rate still needs it: 300k cached and + 900k written on a 1M prompt leaves 700k to price at the write rate.""" + rates = {"input": 1.0, "output": 2.0, "cache_write": 3.0} + row = _usage_row("m", "s1", 1_000_000, 0, 300_000, 900_000) + out = model_cost_latency(pd.DataFrame([row]), {"m": rates}) + # 300k cached at the input rate, 700k written at the write rate. + assert out["m"]["costUsd"] == pytest.approx((300_000 * 1.0 + 700_000 * 3.0) / 1e6) + row["cached_prompt_tokens"] = np.nan + out = model_cost_latency(pd.DataFrame([row]), {"m": rates}) + assert "costUsd" not in out["m"] + + +@pytest.fixture +def pandas_2_groupby(monkeypatch): + """DataFrame.groupby with pandas 2's default: a categorical key gets a + group for every category (observed=False). uv.lock pins pandas 3, whose + default is observed=True, and pyproject allows pandas>=2.0.""" + groupby = pd.DataFrame.groupby + + def observed_false_by_default(self, *args, **kwargs): + kwargs.setdefault("observed", False) + return groupby(self, *args, **kwargs) + + monkeypatch.setattr(pd.DataFrame, "groupby", observed_false_by_default) + + +@pytest.mark.parametrize("groupby_default", ["pandas 3", "pandas 2"]) +@pytest.mark.parametrize("model", ["gemini-3.6-flash", "claude-fable-5.2"]) +def test_categorical_model_column_prices_the_model_itself( + request, groupby_default, model +): + """With the model column categorical and the filled model after another + category, the fill prices the model's own rows, under either pandas + default, not the first category's empty group.""" + if groupby_default == "pandas 2": + request.getfixturevalue("pandas_2_groupby") + rates = PRICE_OVERRIDES_PER_1M[model] + filled = [_usage_row(model, s, 1_000, 200, 400, 100) for s in ("s1", "s2")] + recorded = [ + {**_usage_row("claude-opus-5", s, 1_000, 200, 400, 100), "total_cost_usd": 0.01} + for s in ("s1", "s2") + ] + preds = pd.DataFrame(recorded + filled) + preds["model"] = pd.Categorical( + preds["model"], categories=["claude-opus-5", model, "unused"] + ) + if "cache_read" in rates: + expected = ( + 2 * 500 * rates["input"] + + 2 * 400 * rates["cache_read"] + + 2 * 100 * rates["cache_write"] + + 2 * 200 * rates["output"] + ) / 1e6 + else: + expected = (2 * 1_000 * rates["input"] + 2 * 200 * rates["output"]) / 1e6 + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert out[model]["costUsd"] == pytest.approx(expected, rel=1e-12) + assert out["claude-opus-5"]["costUsd"] == pytest.approx(0.02) def _reconstruction(): @@ -328,9 +561,10 @@ def _reconstruction(): def test_filled_cost_matches_request_reconstruction( model, prompt, completion, cached, cache_write ): - """A household answered by one request has its usage on one row here, so + """A household answered by one response has its usage on one row here, so the filled cost is what eval_no_tools._reconstruct_token_cost records for - that request, for every override; a GPT Responses model's is not filled.""" + that response, for every override, where the row records each count the + override's cache rates need; a GPT Responses model's is not filled.""" reconstruct = _reconstruction() recorded = reconstruct( model_name=model, @@ -354,15 +588,20 @@ def test_filled_cost_matches_request_reconstruction( ] ) out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M)[model] - if model in GPT_RESPONSES_MODELS: + rates = PRICE_OVERRIDES_PER_1M[model] + unrecorded = ("cache_read" in rates or "cache_write" in rates) and ( + cached is None or ("cache_write" in rates and cache_write is None) + ) + if model in GPT_RESPONSES_MODELS or unrecorded: assert "costUsd" not in out else: assert out["costUsd"] == pytest.approx(recorded.usd, rel=1e-12) def test_filled_cost_splits_like_the_request(): - """Rows that share a request's usage equally price to the request's cost: - the fill is linear in each token count.""" + """Rows that share one response's usage equally price to the response's + cost: dividing a response's counts among rows commutes with bounding them + by its prompt count.""" reconstruct = _reconstruction() model = "claude-fable-5.2" request = reconstruct( @@ -402,6 +641,8 @@ def test_filled_cost_splits_like_the_request(): missing, st.integers(0, 6_000_000).map(float) ), "elapsed_seconds": st.one_of(missing, st.floats(min_value=0, max_value=600)), + "live_calls": st.one_of(missing, st.sampled_from([0.0, 1.0, 2.0])), + "cache_hit_calls": st.one_of(missing, st.sampled_from([0.0, 1.0])), } ) rate = st.floats(min_value=0, max_value=100, allow_subnormal=False) @@ -431,14 +672,24 @@ def _reference_cost( completion = math.fsum(r["completion_tokens"] for r in priced) if "cache_read" not in override and "cache_write" not in override: return prompt * override["input"] / 1e6 + completion * override["output"] / 1e6 + counts = ["cached_prompt_tokens", "live_calls", "cache_hit_calls"] + if "cache_write" in override: + counts.append("cache_write_prompt_tokens") + if any(math.isnan(r[c]) for r in priced for c in counts) or any( + r["live_calls"] + r["cache_hit_calls"] != 1 for r in priced + ): + return None - def count(value): - return 0.0 if math.isnan(value) else value + def written_count(row): + if "cache_write" not in override: + return 0.0 + return max(row["cache_write_prompt_tokens"], 0.0) - cached = [min(count(r["cached_prompt_tokens"]), r["prompt_tokens"]) for r in priced] + cached = [ + min(max(r["cached_prompt_tokens"], 0.0), r["prompt_tokens"]) for r in priced + ] written = [ - min(count(r["cache_write_prompt_tokens"]), r["prompt_tokens"] - c) - for r, c in zip(priced, cached) + min(written_count(r), r["prompt_tokens"] - c) for r, c in zip(priced, cached) ] uncached = prompt - math.fsum(cached) - math.fsum(written) return ( @@ -455,13 +706,20 @@ def count(value): overrides=st.dictionaries(st.sampled_from(MODEL_NAMES), price, max_size=3), uncosted=st.sets(st.sampled_from(MODEL_NAMES)), untokened=st.sets(st.sampled_from(MODEL_NAMES)), + single=st.sets(st.sampled_from(MODEL_NAMES)), ) def test_cost_is_present_exactly_when_recorded_usage_supports_it( - drawn, overrides, uncosted, untokened + drawn, overrides, uncosted, untokened, single ): # Whole models with no recorded cost, or (like Fable 5) no token counts, - # so the fill and the no-usage cases are drawn often. + # so the fill and the no-usage cases are drawn often; and whole models + # whose rows each record one response and every cache count, so the + # cache-rate fill is drawn often too. nan = float("nan") + + def recorded(value): + return 0.0 if math.isnan(value) else value + rows = [ { **row, @@ -471,6 +729,18 @@ def test_cost_is_present_exactly_when_recorded_usage_supports_it( if row["model"] in untokened else {} ), + **( + { + "live_calls": 1.0, + "cache_hit_calls": 0.0, + "cached_prompt_tokens": recorded(row["cached_prompt_tokens"]), + "cache_write_prompt_tokens": recorded( + row["cache_write_prompt_tokens"] + ), + } + if row["model"] in single + else {} + ), } for row in drawn ] From 9985a8036cf5a1ba3eead6d600b8fc42eaec520e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 20 Nov 2026 20:43:19 +0000 Subject: [PATCH 04/17] Report a cost effort_sensitivity cannot establish as null (review r1) run_stats indexed costUsd, costPerHousehold and latencySeconds directly, so a model whose cost model_cost_latency leaves out raised a KeyError. It now reports null, and --check-board counts a null figure as a mismatch. Co-Authored-By: Claude Fable 5.2 --- scripts/effort_sensitivity.py | 25 ++++- tests/test_effort_sensitivity_run_stats.py | 109 +++++++++++++++++++++ 2 files changed, 129 insertions(+), 5 deletions(-) create mode 100644 tests/test_effort_sensitivity_run_stats.py diff --git a/scripts/effort_sensitivity.py b/scripts/effort_sensitivity.py index 8e85dfc9..e677d77e 100644 --- a/scripts/effort_sensitivity.py +++ b/scripts/effort_sensitivity.py @@ -312,10 +312,25 @@ def _utc(seconds: float) -> str: return pd.Timestamp(float(seconds), unit="s").strftime("%Y-%m-%dT%H:%M:%SZ") +def _float_or_none(value: float | None) -> float | None: + return None if value is None else float(value) + + +def _close(mine: float | None, frozen: float | None) -> bool: + """Whether a recomputed figure is within 1e-9 of the frozen one; a figure + either side lacks (a cost the rows cannot establish) does not match.""" + if mine is None or frozen is None: + return False + return math.isclose(mine, frozen, rel_tol=0, abs_tol=1e-9) + + def run_stats(predictions: pd.DataFrame, model: str) -> dict: """Cost, output tokens, median latency, calls and parse failures of one row.""" rows = predictions[predictions["model"] == model] - cost = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M)[model] + # model_cost_latency leaves out a cost it cannot establish (and a latency + # no row timed), and the model itself when it has neither; those are null + # here, as the dashboard shows them as not recorded. + cost = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M).get(model, {}) by_household = rows.groupby("scenario_id") # live_calls counts the answered provider calls behind a household's rows # (repeated on each row); rows written before the column existed leave it @@ -328,9 +343,9 @@ def run_stats(predictions: pd.DataFrame, model: str) -> dict: "outputs": int(len(rows)), "outputs_parsed": int(parsed.sum()), "parse_failures": int((~parsed).sum()), - "cost_usd": float(cost["costUsd"]), - "cost_per_household_usd": float(cost["costPerHousehold"]), - "median_household_seconds": float(cost["latencySeconds"]), + "cost_usd": _float_or_none(cost.get("costUsd")), + "cost_per_household_usd": _float_or_none(cost.get("costPerHousehold")), + "median_household_seconds": _float_or_none(cost.get("latencySeconds")), "output_tokens": int(round(float(rows["completion_tokens"].sum()))), "answered_calls": int(live_calls.sum()) if recorded else None, "households_with_a_second_answered_call": ( @@ -614,7 +629,7 @@ def main() -> None: if name in ("exact", "within1pct", "score", "n_parsed") ) close_match = all( - math.isclose(mine, frozen, rel_tol=0, abs_tol=1e-9) + _close(mine, frozen) for checks in report.values() for mine, frozen in checks.values() ) diff --git a/tests/test_effort_sensitivity_run_stats.py b/tests/test_effort_sensitivity_run_stats.py new file mode 100644 index 00000000..7540039f --- /dev/null +++ b/tests/test_effort_sensitivity_run_stats.py @@ -0,0 +1,109 @@ +"""scripts/effort_sensitivity.py run_stats on rows whose cost is not recorded. + +model_cost_latency leaves out a cost it cannot establish, and the model when +it has neither a cost nor a latency; run_stats then reports null for those +fields, as the dashboard reports a cost as not recorded, rather than failing, +and --check-board counts a null figure as a mismatch. +""" + +import importlib.util +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from policybench.analysis import model_cost_latency +from policybench.config import PRICE_OVERRIDES_PER_1M + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def script(): + # The script defines dataclasses, which look their module up in + # sys.modules while it loads. + name = "effort_sensitivity_under_test" + spec = importlib.util.spec_from_file_location( + name, ROOT / "scripts" / "effort_sensitivity.py" + ) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + try: + spec.loader.exec_module(module) + yield module + finally: + sys.modules.pop(name, None) + + +@pytest.fixture(scope="module") +def run_stats(script): + return script.run_stats + + +def _rows(model, *, cost, elapsed, live=1): + return pd.DataFrame( + [ + { + "model": model, + "scenario_id": scenario, + "variable": "v", + "prediction": 1.0, + "total_cost_usd": cost, + "elapsed_seconds": elapsed, + "prompt_tokens": 1_000.0, + "completion_tokens": 200.0, + "total_tokens": 1_200.0, + "cached_prompt_tokens": 400.0, + "cache_write_prompt_tokens": 0.0, + "live_calls": live, + "cache_hit_calls": 0, + "request_started_at": 1_763_600_000.0, + "request_completed_at": 1_763_600_010.0, + } + for scenario in ("s1", "s2") + ] + ) + + +def test_recorded_cost_and_latency_are_reported(run_stats): + rows = _rows("claude-fable-5.2", cost=0.01, elapsed=4.0) + stats = run_stats(rows, "claude-fable-5.2") + expected = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M)["claude-fable-5.2"] + assert stats["cost_usd"] == expected["costUsd"] == pytest.approx(0.02) + assert stats["cost_per_household_usd"] == expected["costPerHousehold"] + assert stats["median_household_seconds"] == expected["latencySeconds"] + + +def test_unestablished_cost_is_null(run_stats): + """Fable 5.2 rows with no recorded cost whose households each sum two + responses: the cache-rate fill cannot price them, so the cost is null and + the latency is still reported.""" + rows = _rows("claude-fable-5.2", cost=np.nan, elapsed=4.0, live=2) + stats = run_stats(rows, "claude-fable-5.2") + assert stats["cost_usd"] is None + assert stats["cost_per_household_usd"] is None + assert stats["median_household_seconds"] == pytest.approx(4.0) + + +def test_model_with_no_cost_or_latency_is_all_null(run_stats): + """With no cost, no latency and no total tokens, model_cost_latency leaves + the model out altogether.""" + rows = _rows("claude-fable-5.2", cost=np.nan, elapsed=np.nan, live=2).drop( + columns=["total_tokens"] + ) + assert "claude-fable-5.2" not in model_cost_latency(rows, PRICE_OVERRIDES_PER_1M) + stats = run_stats(rows, "claude-fable-5.2") + assert stats["cost_usd"] is None + assert stats["cost_per_household_usd"] is None + assert stats["median_household_seconds"] is None + + +def test_board_check_counts_an_unestablished_figure_as_a_mismatch(script): + """--check-board compares each recomputed figure with the frozen one; a + figure run_stats reports as null fails the check instead of raising.""" + assert script._close(1.0, 1.0 + 1e-12) + assert not script._close(1.0, 1.0 + 1e-6) + assert not script._close(None, 31.69) + assert not script._close(31.69, None) From 3a9abe3d76b96e0216103ac705c7c5d2a38aedf1 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 01:32:04 +0100 Subject: [PATCH 05/17] Read the frozen cost and latency with get in --check-board (review r2) The dashboard leaves out a cost or latency it cannot establish, so a frozen modelStats row can lack the key (the committed gpt-5.5 row has no latencySeconds). check_board indexed both and raised KeyError before comparing. It now reads them with get; a figure only one side records fails the check and a figure neither side records passes. The tests go through check_board on the committed snapshot. Co-Authored-By: Claude Opus 5.5 --- scripts/effort_sensitivity.py | 13 +++- tests/test_effort_sensitivity_run_stats.py | 85 ++++++++++++++++++++-- 2 files changed, 89 insertions(+), 9 deletions(-) diff --git a/scripts/effort_sensitivity.py b/scripts/effort_sensitivity.py index e677d77e..834a12f4 100644 --- a/scripts/effort_sensitivity.py +++ b/scripts/effort_sensitivity.py @@ -317,8 +317,11 @@ def _float_or_none(value: float | None) -> float | None: def _close(mine: float | None, frozen: float | None) -> bool: - """Whether a recomputed figure is within 1e-9 of the frozen one; a figure - either side lacks (a cost the rows cannot establish) does not match.""" + """Whether a recomputed figure is within 1e-9 of the frozen one. A figure + neither side records (the dashboard shows it as not recorded) matches; a + figure only one side records does not.""" + if mine is None and frozen is None: + return True if mine is None or frozen is None: return False return math.isclose(mine, frozen, rel_tol=0, abs_tol=1e-9) @@ -368,15 +371,17 @@ def check_board(inputs: ScoringInputs, board: pd.DataFrame) -> dict: for model in BOARD_MODELS: row = stats[model] mine = run_stats(board, model) + # The dashboard leaves out a cost or latency it cannot establish (the + # key is absent, not null), so read those two with get. report[model] = { "exact": (scores[model]["exact"], row["exact"]), "within1pct": (scores[model]["within1pct"], row["within1pct"]), "score": (scores[model]["score"], row["score"]), "household_mean_exact": (100 * float(wide[model].mean()), row["exact"]), - "cost_usd": (mine["cost_usd"], row["costUsd"]), + "cost_usd": (mine["cost_usd"], row.get("costUsd")), "median_household_seconds": ( mine["median_household_seconds"], - row["latencySeconds"], + row.get("latencySeconds"), ), "n_parsed": ( int( diff --git a/tests/test_effort_sensitivity_run_stats.py b/tests/test_effort_sensitivity_run_stats.py index 7540039f..f9919580 100644 --- a/tests/test_effort_sensitivity_run_stats.py +++ b/tests/test_effort_sensitivity_run_stats.py @@ -1,11 +1,17 @@ -"""scripts/effort_sensitivity.py run_stats on rows whose cost is not recorded. +"""scripts/effort_sensitivity.py run_stats and --check-board on figures the +rows cannot establish. model_cost_latency leaves out a cost it cannot establish, and the model when it has neither a cost nor a latency; run_stats then reports null for those -fields, as the dashboard reports a cost as not recorded, rather than failing, -and --check-board counts a null figure as a mismatch. +fields, as the dashboard reports a cost as not recorded, rather than failing. +The dashboard leaves such a key out of a frozen modelStats row (the committed +snapshot's gpt-5.5 row has no latencySeconds), so --check-board reads the +frozen figures without assuming the keys: a figure only one side records fails +the check, and a figure neither side records passes it. """ +import copy +import dataclasses import importlib.util import sys from pathlib import Path @@ -100,10 +106,79 @@ def test_model_with_no_cost_or_latency_is_all_null(run_stats): assert stats["median_household_seconds"] is None -def test_board_check_counts_an_unestablished_figure_as_a_mismatch(script): +def test_board_check_counts_a_figure_one_side_lacks_as_a_mismatch(script): """--check-board compares each recomputed figure with the frozen one; a - figure run_stats reports as null fails the check instead of raising.""" + figure only one side records fails the check instead of raising, and a + figure neither side records passes.""" assert script._close(1.0, 1.0 + 1e-12) assert not script._close(1.0, 1.0 + 1e-6) assert not script._close(None, 31.69) assert not script._close(31.69, None) + assert script._close(None, None) + + +FABLE = "claude-fable-5.2" +OPUS = "claude-opus-5.5" + + +@pytest.fixture(scope="module") +def frozen(script): + return script.scoring_inputs(), script.load_board_predictions() + + +def _without(inputs, model, key): + payload = copy.deepcopy(inputs.payload) + (row,) = [row for row in payload["modelStats"] if row["model"] == model] + del row[key] + return dataclasses.replace(inputs, payload=payload) + + +def _passes(script, report): + return all( + script._close(mine, frozen) + for checks in report.values() + for mine, frozen in checks.values() + ) + + +def test_committed_snapshot_passes_the_board_check(script, frozen): + inputs, board = frozen + assert _passes(script, script.check_board(inputs, board)) + + +@pytest.mark.parametrize( + ("model", "key", "field"), + [ + (FABLE, "costUsd", "cost_usd"), + (OPUS, "latencySeconds", "median_household_seconds"), + ], +) +def test_a_figure_only_the_recomputation_has_fails_the_board_check( + script, frozen, model, key, field +): + """A frozen row without the key reports the figure as missing.""" + inputs, board = frozen + report = script.check_board(_without(inputs, model, key), board) + mine, frozen_value = report[model][field] + assert mine is not None + assert frozen_value is None + assert not _passes(script, report) + + +def test_a_cost_neither_side_records_passes_the_board_check(script, frozen): + """Fable 5.2 rows with no recorded cost whose rows each sum two responses + get no cost from the cache-rate fill; a frozen row without costUsd agrees, + and a frozen row with one does not.""" + inputs, board = frozen + cleared = board.copy() + fable = cleared["model"] == FABLE + cleared.loc[fable, "total_cost_usd"] = np.nan + cleared.loc[fable, "live_calls"] = 2 + cleared.loc[fable, "cache_hit_calls"] = 0 + agree = script.check_board(_without(inputs, FABLE, "costUsd"), cleared) + assert agree[FABLE]["cost_usd"] == (None, None) + assert _passes(script, agree) + differ = script.check_board(inputs, cleared) + assert differ[FABLE]["cost_usd"][0] is None + assert differ[FABLE]["cost_usd"][1] is not None + assert not _passes(script, differ) From f68eff2739697b2517412addf2e73dc19e110aec Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:27:14 +0100 Subject: [PATCH 06/17] Refuse a freeze whose board lacks a model's cost, by name, before any write (review r2) model_cost_latency now leaves costUsd out for rows it cannot price (a cache-rate model whose rows sum several responses or lack a count, a Responses-API GPT model), where main priced them at the flat input and output rates. regenerate_analysis indexed costUsd on every board row, so such a board raised KeyError('costUsd') after main() had already deleted and rewritten the run directory. require_published_costs names the models without a finite cost and exits. main() calls it on the published dashboard before remove_stale_artifacts, and regenerate_analysis calls it where it built the dict. The committed board passes with the same costs in the same order. Co-Authored-By: Claude Fable 5.2 --- scripts/freeze_snapshot.py | 45 +++++++- tests/test_freeze_published_costs.py | 166 +++++++++++++++++++++++++++ tests/test_model_response_window.py | 44 ++++++- 3 files changed, 247 insertions(+), 8 deletions(-) create mode 100644 tests/test_freeze_published_costs.py diff --git a/scripts/freeze_snapshot.py b/scripts/freeze_snapshot.py index 977c5608..e9c8a1d9 100644 --- a/scripts/freeze_snapshot.py +++ b/scripts/freeze_snapshot.py @@ -45,6 +45,7 @@ import gzip import hashlib import json +import math import re import shutil import subprocess @@ -940,6 +941,38 @@ def household_impact_summary_by_model( ) +def require_published_costs(country_payload: dict) -> dict[str, float]: + """Each no-tools board model's published ``costUsd``; refuse a board + that lacks one. + + ``analysis.model_cost_latency`` leaves ``costUsd`` out when no row of a + model records a cost and the rows' usage cannot establish one from the + model's price override. The report's published total sums every board + model's cost, and the paper's caption explains a missing cost only as a + zero charge, so the freeze stops and names the models rather than + publish a board with a cost missing. + """ + rows = [ + row for row in country_payload["modelStats"] if row["condition"] == "no_tools" + ] + missing = sorted( + str(row["model"]) + for row in rows + if isinstance(row.get("costUsd"), bool) + or not isinstance(row.get("costUsd"), (int, float)) + or not math.isfinite(row["costUsd"]) + ) + if missing: + raise SystemExit( + f"The published payload has no costUsd for {', '.join(missing)}: no " + "row of those models records a cost, and analysis.model_cost_latency " + "could not establish one from the price override. Record the rows' " + "costs or carry a released cost (as the release drivers' " + "CARRIED_USAGE does), then export again." + ) + return {row["model"]: row["costUsd"] for row in rows} + + def regenerate_analysis(dest_dir: Path) -> None: """Run the analyze CLI into ``dest_dir`` and add the impact summary. @@ -994,12 +1027,7 @@ def regenerate_analysis(dest_dir: Path) -> None: report_tables["bounded_summary"] = report_tables["model_summary"][ ["model", "bounded_score", "amount_accuracy", "participation_accuracy"] ].sort_values("model") - country_payload = read_run_payload(RUN_DEST) - published_model_costs = { - row["model"]: row["costUsd"] - for row in country_payload["modelStats"] - if row["condition"] == "no_tools" - } + published_model_costs = require_published_costs(read_run_payload(RUN_DEST)) (dest_dir / "report.md").write_text( render_markdown_report( report_tables, published_model_costs=published_model_costs @@ -2061,6 +2089,11 @@ def main() -> None: response_window = model_response_window( SOURCE_US / "predictions.csv", MODEL_RESPONSE_START, MODEL_RESPONSE_DATE ) + # regenerate_analysis needs every board model's cost; check it before + # the steps below delete and rewrite the snapshot. + require_published_costs( + json.loads(PUBLISHED_DASHBOARD_SOURCE.read_bytes())["countries"]["us"] + ) remove_stale_artifacts() run_files = freeze_run() diff --git a/tests/test_freeze_published_costs.py b/tests/test_freeze_published_costs.py new file mode 100644 index 00000000..5ae52cce --- /dev/null +++ b/tests/test_freeze_published_costs.py @@ -0,0 +1,166 @@ +"""The freeze needs a published cost for every board model. + +analysis.model_cost_latency leaves costUsd out of a model's dashboard row when +no row of the model records a cost and the rows' usage cannot establish one +from its price override: a cache-rate model whose rows sum several responses +or lack a count, and a Responses-API GPT model. The freeze's report sums +every board model's cost, so freeze_snapshot.require_published_costs names +the models without one and stops, where the lookup used to raise +KeyError('costUsd'). +""" + +from __future__ import annotations + +import json +import math +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from policybench.analysis import model_cost_latency +from policybench.config import PRICE_OVERRIDES_PER_1M +from policybench.snapshot_payload import read_run_payload + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) + +import freeze_snapshot as freezer # noqa: E402 + + +def _payload(*rows: dict) -> dict: + return {"modelStats": list(rows)} + + +def _stat(model: str, condition: str = "no_tools", **fields) -> dict: + return {"model": model, "condition": condition, **fields} + + +def test_a_board_model_without_a_cost_is_named(): + payload = _payload( + _stat("costed", costUsd=1.0), + _stat("no-key"), + _stat("null", costUsd=None), + _stat("nan", costUsd=math.nan), + _stat("true", costUsd=True), + _stat("text", costUsd="1.0"), + _stat("tools-arm", condition="with_tools"), + ) + with pytest.raises(SystemExit) as refused: + freezer.require_published_costs(payload) + message = str(refused.value) + assert "no costUsd for nan, no-key, null, text, true:" in message + assert "tools-arm" not in message + assert "costed" not in message + + +def test_a_zero_cost_is_a_cost_and_the_payload_order_is_kept(): + payload = _payload( + _stat("zero-charge", costUsd=0), + _stat("costed", costUsd=1.5), + _stat("tools-arm", condition="with_tools", costUsd=9.0), + ) + costs = freezer.require_published_costs(payload) + assert costs == {"zero-charge": 0, "costed": 1.5} + assert list(costs) == ["zero-charge", "costed"] + + +def test_the_committed_snapshot_has_a_cost_for_every_board_model(): + """The check changes nothing for the frozen board: the costs the report + sums are the ones the payload carries, in its order.""" + payload = read_run_payload(freezer.RUN_DEST) + board = [row for row in payload["modelStats"] if row["condition"] == "no_tools"] + assert board + costs = freezer.require_published_costs(payload) + assert list(costs.items()) == [(row["model"], row["costUsd"]) for row in board] + + +def _costless_rows(model: str, live: int) -> pd.DataFrame: + return pd.DataFrame( + [ + { + "model": model, + "scenario_id": scenario, + "variable": "v", + "prediction": 1.0, + "total_cost_usd": np.nan, + "elapsed_seconds": 4.0, + "prompt_tokens": 1_000.0, + "completion_tokens": 200.0, + "total_tokens": 1_200.0, + "cached_prompt_tokens": 400.0, + "cache_write_prompt_tokens": 0.0, + "live_calls": live, + "cache_hit_calls": 0, + } + for scenario in ("s1", "s2") + ] + ) + + +@pytest.fixture +def staged_freeze(tmp_path, monkeypatch): + """regenerate_analysis with the analyze CLI and its CSVs stubbed, reading + its payload from a staged run directory. Returns a function that stages a + payload and regenerates the analysis.""" + staged = tmp_path / "run" + staged.mkdir() + (staged / "reference_outputs.csv").write_text("scenario_id,variable,value\n") + monkeypatch.setattr(freezer, "RUN_DEST", staged) + monkeypatch.setattr(freezer.subprocess, "run", lambda *args, **kwargs: None) + monkeypatch.setattr( + freezer.pd, + "read_csv", + lambda path, *args, **kwargs: pd.DataFrame( + { + "model": [], + "bounded_score": [], + "amount_accuracy": [], + "participation_accuracy": [], + } + ), + ) + monkeypatch.setattr( + freezer, + "render_markdown_report", + lambda tables, *, published_model_costs: json.dumps(published_model_costs), + ) + monkeypatch.setattr( + freezer, "scored_reference_for", lambda path: (pd.DataFrame(), None) + ) + monkeypatch.setattr( + freezer, + "household_impact_summary_by_model", + lambda references, predictions: pd.DataFrame({"model": []}), + ) + + def regenerate(payload: dict) -> Path: + (staged / "data.json").write_text(json.dumps(payload)) + freezer.regenerate_analysis(staged / "analysis") + return staged / "analysis" / "report.md" + + return regenerate + + +def test_rows_the_fill_cannot_price_stop_the_report_by_name(staged_freeze): + """Fable 5.2 rows with no recorded cost whose households each sum two + responses: the cache-rate fill gives no cost, the dashboard row has no + costUsd, and the freeze's report names the model instead of raising + KeyError. The same rows with one response each are priced and reported.""" + model = "claude-fable-5.2" + + def stat(live: int) -> dict: + entry = model_cost_latency(_costless_rows(model, live), PRICE_OVERRIDES_PER_1M) + return _stat(model, **entry.get(model, {})) + + unpriced = stat(live=2) + assert "costUsd" not in unpriced + with pytest.raises(SystemExit, match=rf"no costUsd for {model}:"): + staged_freeze(_payload(unpriced)) + + priced = stat(live=1) + report = staged_freeze(_payload(priced)) + assert json.loads(report.read_text()) == {model: priced["costUsd"]} + assert priced["costUsd"] > 0 diff --git a/tests/test_model_response_window.py b/tests/test_model_response_window.py index 3b6da59c..d767a500 100644 --- a/tests/test_model_response_window.py +++ b/tests/test_model_response_window.py @@ -189,8 +189,22 @@ def freeze_inputs(tmp_path, monkeypatch): source / "us" / "predictions.csv", [(None, None), (LAST_ANSWER_20260930 - 60, LAST_ANSWER_20260930)], ) - for name in ("dashboard.json", "reference_outputs.csv.meta.json"): - (tmp_path / name).write_text("{}\n") + # The freeze checks that every board model has a published cost before + # it writes, so the dashboard carries one costed model. + (tmp_path / "dashboard.json").write_text( + json.dumps( + { + "countries": { + "us": { + "modelStats": [ + {"model": "model", "condition": "no_tools", "costUsd": 1.5} + ] + } + } + } + ) + ) + (tmp_path / "reference_outputs.csv.meta.json").write_text("{}\n") monkeypatch.setattr(freezer, "SOURCE_RUN", source) monkeypatch.setattr(freezer, "SOURCE_US", source / "us") monkeypatch.setattr( @@ -239,6 +253,32 @@ def test_the_freeze_refuses_a_release_date_window_before_any_write( assert freeze_inputs == [] +def test_the_freeze_refuses_a_board_model_without_a_cost_before_any_write( + freeze_inputs, +): + """analysis.model_cost_latency leaves costUsd out of a model's row when + its rows record no cost and their usage cannot establish one. The freeze + names that model and stops before it deletes or rewrites anything; it + used to raise KeyError('costUsd') after rewriting the run directory.""" + freezer.PUBLISHED_DASHBOARD_SOURCE.write_text( + json.dumps( + { + "countries": { + "us": { + "modelStats": [ + {"model": "costed", "condition": "no_tools", "costUsd": 2}, + {"model": "costless", "condition": "no_tools"}, + ] + } + } + } + ) + ) + with pytest.raises(SystemExit, match=r"no costUsd for costless:"): + freezer.main() + assert freeze_inputs == [] + + def test_a_csv_time_just_before_utc_midnight_stays_on_its_day(tmp_path): """End to end through the CSV parser, not only ``_utc_date``: the last double before 2027-02-01 00:00 UTC is a January 31 answer. pandas' From c9451f2c815751fe79faee7b6a49ac7931c593a9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:28:14 +0100 Subject: [PATCH 07/17] Accept only one-response count pairs and sum uncached tokens per row (review r2) The cache-rate fill checked that live_calls + cache_hit_calls is 1, which also passed (-1, 2) and (0.5, 0.5). It now needs (1, 0) or (0, 1), compared as floats so counts read back as 1.0 and 0.0 still pass. It also subtracted the summed cache counts from the grouped prompt sum. The two sums round differently, so a fully cached prompt split into fractional shares could price below zero at a zero cache-read rate (-8.9e-22 for seven tokens over six rows). Each row's uncached count is now taken after the bounds and then summed. The input-and-output return, which prices the two published fallback costs, comes before both lines and is unchanged. Co-Authored-By: Claude Fable 5.2 --- policybench/analysis.py | 26 +++++++++----- tests/test_cost_latency.py | 74 +++++++++++++++++++++++++++++++------- 2 files changed, 79 insertions(+), 21 deletions(-) diff --git a/policybench/analysis.py b/policybench/analysis.py index aa230fe6..181f0eae 100644 --- a/policybench/analysis.py +++ b/policybench/analysis.py @@ -1498,7 +1498,8 @@ def _override_fallback_cost( input rate), bounding each row's counts by its prompt count as the reconstruction bounds a response's. The bound of a sum is not the sum of the bounds, so it needs rows that each hold one response's usage: - every priced row must record one response, a cached count, and, if + every priced row must record one response (``live_calls`` and + ``cache_hit_calls`` of 1 and 0, or 0 and 1), a cached count, and, if the override lists a cache-write rate, a cache-write count (with no such rate, cache-write tokens price at the input rate like uncached ones, so their count changes nothing). A row's counts are then that @@ -1543,8 +1544,13 @@ def _override_fallback_cost( needed = [*counts, *RESPONSE_COUNT_COLUMNS] if not set(needed) <= set(priced.columns) or priced[needed].isna().any().any(): return None - responses = sum(priced[column].astype(float) for column in RESPONSE_COUNT_COLUMNS) - if not (responses == 1).all(): + # One response, live or replayed: the counts are (1, 0) or (0, 1). A sum + # of 1 would also pass (-1, 2) or (0.5, 0.5), which no runner writes. The + # counts compare as floats, so one read back as 1.0 (a column with an + # empty cell elsewhere, a CSV round trip) still passes. + live, replayed = (priced[column].astype(float) for column in RESPONSE_COUNT_COLUMNS) + one_response = ((live == 1) & (replayed == 0)) | ((live == 0) & (replayed == 1)) + if not one_response.all(): return None def recorded(column: str) -> pd.Series: @@ -1555,13 +1561,15 @@ def recorded(column: str) -> pd.Series: row_prompt = priced["prompt_tokens"].astype(float) cached = np.minimum(recorded("cached_prompt_tokens"), row_prompt) cache_write = np.minimum(recorded("cache_write_prompt_tokens"), row_prompt - cached) - cached_total = float(cached.sum()) - cache_write_total = float(cache_write.sum()) - uncached = prompt - cached_total - cache_write_total + # Each row's uncached count is non-negative after the bounds. Summing the + # rows' counts, rather than subtracting the cache sums from the grouped + # prompt sum (the two sums round differently), keeps a fully cached + # prompt from pricing below zero. + uncached = row_prompt - cached - cache_write return ( - uncached * rates["input"] - + cached_total * rates.get("cache_read", rates["input"]) - + cache_write_total * rates.get("cache_write", rates["input"]) + float(uncached.sum()) * rates["input"] + + float(cached.sum()) * rates.get("cache_read", rates["input"]) + + float(cache_write.sum()) * rates.get("cache_write", rates["input"]) + completion * rates["output"] ) / 1e6 diff --git a/tests/test_cost_latency.py b/tests/test_cost_latency.py index 2378b3c2..056e0ed3 100644 --- a/tests/test_cost_latency.py +++ b/tests/test_cost_latency.py @@ -7,11 +7,12 @@ - otherwise a model has a cost exactly when it has a price override that is not a Responses-API GPT model and one of its rows recorded both prompt and completion token counts, and, for an override with a cache rate, every such - row records one provider response (live_calls + cache_hit_calls == 1), a - cached count and, if the override lists a cache-write rate, a cache-write - count; a row missing either token count is not priced, so no cost rests on - a count nobody recorded, and a model with no usage at all gets no cost - rather than $0; + row records one provider response (live_calls and cache_hit_calls are 1 + and 0, or 0 and 1), a cached count and, if the override lists a cache-write + rate, a cache-write count; a row missing either token count is not priced, + so no cost rests on a count nobody recorded, and a model with no usage at + all gets no cost rather than $0; +- a filled cost is never negative for non-negative counts and rates; - a filled cost is the override's input and output rates applied to the token sums of the rows that recorded both counts, with each row's cached and cache-write tokens, bounded by its prompt count, at the override's @@ -421,12 +422,26 @@ def test_rows_summing_two_responses_fill_no_cost(): @pytest.mark.parametrize( - "live, cache_hits", [(2, 0), (1, 1), (0, 2), (0, 0), (np.nan, 0), (1, np.nan)] + "live, cache_hits", + [ + (2, 0), + (1, 1), + (0, 2), + (0, 0), + (np.nan, 0), + (1, np.nan), + # Counts no runner writes, though they sum to one. + (-1, 2), + (2, -1), + (0.5, 0.5), + (1.5, -0.5), + ], ) def test_cache_rates_need_rows_recording_one_response(live, cache_hits): """A cache-rate fill needs every priced row to record one response, live - or replayed; a row recording none, several, or no count gets no cost. - (One replayed response is priced: test_one_replayed_response_is_priced.)""" + or replayed: counts of (1, 0) or (0, 1). A row recording none, several, + no count, or counts that only sum to one gets no cost. (One replayed + response is priced: test_one_replayed_response_is_priced.)""" model = "claude-fable-5.2" preds = pd.DataFrame( [ @@ -456,6 +471,37 @@ def test_one_replayed_response_is_priced(): assert out[model]["costUsd"] == pytest.approx(3.92) +def test_response_counts_read_back_as_floats_are_priced(): + """A count column with an empty cell elsewhere, or one read back from a + CSV beside such a column, holds 1.0 and 0.0: still one response.""" + model = "claude-fable-5.2" + preds = pd.DataFrame( + [ + _usage_row(model, "s1", 1_000_000, 10_000, 600_000, 100_000, 1.0, 0.0), + _usage_row(model, "s2", 1_000_000, 10_000, 600_000, 100_000, 0.0, 1.0), + ] + ) + assert preds["live_calls"].dtype == float + out = model_cost_latency(preds, PRICE_OVERRIDES_PER_1M) + assert out[model]["costUsd"] == pytest.approx(2 * 3.92) + + +@pytest.mark.parametrize("shares", range(2, 13)) +@pytest.mark.parametrize("prompt", [1, 7, 10, 1_000_003]) +def test_a_fully_cached_prompt_never_prices_below_zero(shares, prompt): + """A fully cached response split among rows whose shares are not exact + in floating point, at a zero cache-read rate: every token is cached, so + the cost is exactly zero. Subtracting the summed cache counts from the + summed prompt count gave -8.9e-22 for seven tokens over six rows.""" + rates = {"input": 1.0, "output": 1.0, "cache_read": 0.0} + share = prompt / shares + preds = pd.DataFrame( + [_usage_row("m", "s1", share, 0, share, 0) for _ in range(shares)] + ) + out = model_cost_latency(preds, {"m": rates}) + assert out["m"]["costUsd"] == 0.0 + + def test_response_count_columns_are_the_runner_provenance_counts(): from policybench.eval_no_tools import NO_TOOLS_CALL_PROVENANCE_COLUMNS @@ -641,8 +687,9 @@ def test_filled_cost_splits_like_the_request(): missing, st.integers(0, 6_000_000).map(float) ), "elapsed_seconds": st.one_of(missing, st.floats(min_value=0, max_value=600)), - "live_calls": st.one_of(missing, st.sampled_from([0.0, 1.0, 2.0])), - "cache_hit_calls": st.one_of(missing, st.sampled_from([0.0, 1.0])), + # -1, 2 and 0.5 let a draw pair counts that only sum to one. + "live_calls": st.one_of(missing, st.sampled_from([0.0, 1.0, 2.0, -1.0, 0.5])), + "cache_hit_calls": st.one_of(missing, st.sampled_from([0.0, 1.0, 2.0, 0.5])), } ) rate = st.floats(min_value=0, max_value=100, allow_subnormal=False) @@ -676,7 +723,8 @@ def _reference_cost( if "cache_write" in override: counts.append("cache_write_prompt_tokens") if any(math.isnan(r[c]) for r in priced for c in counts) or any( - r["live_calls"] + r["cache_hit_calls"] != 1 for r in priced + (r["live_calls"], r["cache_hit_calls"]) not in {(1.0, 0.0), (0.0, 1.0)} + for r in priced ): return None @@ -691,7 +739,9 @@ def written_count(row): written = [ min(written_count(r), r["prompt_tokens"] - c) for r, c in zip(priced, cached) ] - uncached = prompt - math.fsum(cached) - math.fsum(written) + uncached = math.fsum( + r["prompt_tokens"] - c - w for r, c, w in zip(priced, cached, written) + ) return ( uncached * override["input"] + math.fsum(cached) * override.get("cache_read", override["input"]) From 375b86fec69aae388d96385104abeaf7ff1d2ff4 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:29:07 +0100 Subject: [PATCH 08/17] Report null for run figures some row does not record (review r2) run_stats raised ValueError (NaT) on rows with no request timestamps and KeyError on rows written before the call-count columns, and reported zero output tokens or cache hits for rows that record none. Output tokens, each call count and each end of the request window are now null unless every row records them. lockfile_litellm(None) returns a null pin: git reads --before=None as now and would return today's lockfile. The frozen board rows still reproduce the committed summary's run figures. Co-Authored-By: Claude Fable 5.2 --- scripts/effort_sensitivity.py | 53 +++++++--- tests/test_effort_sensitivity_run_stats.py | 107 +++++++++++++++++++++ 2 files changed, 145 insertions(+), 15 deletions(-) diff --git a/scripts/effort_sensitivity.py b/scripts/effort_sensitivity.py index 834a12f4..87f9ebf7 100644 --- a/scripts/effort_sensitivity.py +++ b/scripts/effort_sensitivity.py @@ -308,10 +308,20 @@ def paired_difference( } -def _utc(seconds: float) -> str: +def _utc(seconds: float | None) -> str | None: + if seconds is None or pd.isna(seconds): + return None return pd.Timestamp(float(seconds), unit="s").strftime("%Y-%m-%dT%H:%M:%SZ") +def _every_row(rows: pd.DataFrame, column: str) -> pd.Series | None: + """The column when every row records it, else None: rows written before + the column existed lack it, and an empty value is not recorded, not zero.""" + if rows.empty or column not in rows.columns or rows[column].isna().any(): + return None + return rows[column] + + def _float_or_none(value: float | None) -> float | None: return None if value is None else float(value) @@ -334,12 +344,17 @@ def run_stats(predictions: pd.DataFrame, model: str) -> dict: # no row timed), and the model itself when it has neither; those are null # here, as the dashboard shows them as not recorded. cost = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M).get(model, {}) - by_household = rows.groupby("scenario_id") - # live_calls counts the answered provider calls behind a household's rows - # (repeated on each row); rows written before the column existed leave it - # empty, and then the count is not recorded rather than zero. - recorded = bool(rows["live_calls"].notna().all()) - live_calls = by_household["live_calls"].first() + # live_calls and cache_hit_calls count the answered and replayed provider + # calls behind a household's rows (repeated on each row). A figure some + # row does not record (rows written before its column existed, or calls + # nobody timed) is null here, not zero and not a bound from the rows that + # do record it. + live = _every_row(rows, "live_calls") + live_calls = None if live is None else live.groupby(rows["scenario_id"]).first() + hits = _every_row(rows, "cache_hit_calls") + completion = _every_row(rows, "completion_tokens") + started = _every_row(rows, "request_started_at") + completed = _every_row(rows, "request_completed_at") parsed = rows["prediction"].notna() return { "households": int(rows["scenario_id"].nunique()), @@ -349,16 +364,20 @@ def run_stats(predictions: pd.DataFrame, model: str) -> dict: "cost_usd": _float_or_none(cost.get("costUsd")), "cost_per_household_usd": _float_or_none(cost.get("costPerHousehold")), "median_household_seconds": _float_or_none(cost.get("latencySeconds")), - "output_tokens": int(round(float(rows["completion_tokens"].sum()))), - "answered_calls": int(live_calls.sum()) if recorded else None, + "output_tokens": ( + None if completion is None else int(round(float(completion.sum()))) + ), + "answered_calls": None if live_calls is None else int(live_calls.sum()), "households_with_a_second_answered_call": ( - int((live_calls > 1).sum()) if recorded else None + None if live_calls is None else int((live_calls > 1).sum()) ), "cache_hit_calls": ( - int(by_household["cache_hit_calls"].first().sum()) if recorded else None + None + if hits is None + else int(hits.groupby(rows["scenario_id"]).first().sum()) ), - "first_request_utc": _utc(rows["request_started_at"].min()), - "last_response_utc": _utc(rows["request_completed_at"].max()), + "first_request_utc": None if started is None else _utc(started.min()), + "last_response_utc": None if completed is None else _utc(completed.max()), } @@ -579,8 +598,12 @@ def probe_record(path: Path) -> dict: } -def lockfile_litellm(before_utc: str) -> dict: - """The repository lockfile's litellm pin as last changed before a time.""" +def lockfile_litellm(before_utc: str | None) -> dict: + """The repository lockfile's litellm pin as last changed before a time; + null when the rows record no first request (git would read + ``--before=None`` as now and return today's pin).""" + if before_utc is None: + return {"lockfile_commit": None, "litellm": None} commit = subprocess.run( ["git", "log", "-1", "--format=%H", f"--before={before_utc}", "--", "uv.lock"], cwd=ROOT, diff --git a/tests/test_effort_sensitivity_run_stats.py b/tests/test_effort_sensitivity_run_stats.py index f9919580..d694c8e9 100644 --- a/tests/test_effort_sensitivity_run_stats.py +++ b/tests/test_effort_sensitivity_run_stats.py @@ -4,6 +4,10 @@ model_cost_latency leaves out a cost it cannot establish, and the model when it has neither a cost nor a latency; run_stats then reports null for those fields, as the dashboard reports a cost as not recorded, rather than failing. +It reports null the same way for output tokens, call counts and the request +time window when some row does not record them (rows written before the +column existed, or calls nobody timed), where it used to raise or report +zero; with no first request, the lockfile pin is null too. The dashboard leaves such a key out of a frozen modelStats row (the committed snapshot's gpt-5.5 row has no latencySeconds), so --check-board reads the frozen figures without assuming the keys: a figure only one side records fails @@ -13,6 +17,7 @@ import copy import dataclasses import importlib.util +import json import sys from pathlib import Path @@ -182,3 +187,105 @@ def test_a_cost_neither_side_records_passes_the_board_check(script, frozen): assert differ[FABLE]["cost_usd"][0] is None assert differ[FABLE]["cost_usd"][1] is not None assert not _passes(script, differ) + + +UNTIMED = {"request_started_at": np.nan, "request_completed_at": np.nan} +PROVENANCE = [ + "live_calls", + "cache_hit_calls", + "request_started_at", + "request_completed_at", +] + + +def test_untimed_rows_report_no_latency_and_no_time_window(run_stats): + """Rows that record no elapsed time and no request timestamps: the cost is + still reported; the latency and the first and last times are null. This + raised ValueError (NaT) from the time window.""" + rows = _rows("claude-fable-5.2", cost=0.01, elapsed=np.nan).assign(**UNTIMED) + stats = run_stats(rows, "claude-fable-5.2") + assert stats["cost_usd"] == pytest.approx(0.02) + assert stats["median_household_seconds"] is None + assert stats["first_request_utc"] is None + assert stats["last_response_utc"] is None + + +def test_rows_without_timestamps_keep_their_latency(run_stats): + """Elapsed time recorded, request timestamps not (the frozen board's + older rows): the latency is reported and the time window is null.""" + rows = _rows("claude-fable-5.2", cost=0.01, elapsed=4.0).assign(**UNTIMED) + stats = run_stats(rows, "claude-fable-5.2") + assert stats["median_household_seconds"] == pytest.approx(4.0) + assert stats["first_request_utc"] is None + assert stats["last_response_utc"] is None + + +def test_rows_written_before_the_provenance_columns_report_null_counts(run_stats): + """Rows from a run that wrote no call counts or request times: those + figures are null, the rest is reported, and the result writes as JSON. + This raised KeyError('live_calls').""" + rows = _rows("claude-fable-5.2", cost=0.01, elapsed=4.0).drop(columns=PROVENANCE) + stats = run_stats(rows, "claude-fable-5.2") + for field in ( + "answered_calls", + "households_with_a_second_answered_call", + "cache_hit_calls", + "first_request_utc", + "last_response_utc", + ): + assert stats[field] is None, field + assert stats["cost_usd"] == pytest.approx(0.02) + assert stats["median_household_seconds"] == pytest.approx(4.0) + assert stats["households"] == 2 + assert stats["output_tokens"] == 400 + assert json.loads(json.dumps(stats)) == stats + + +def test_unrecorded_cache_hits_are_null_not_zero(run_stats): + rows = _rows("claude-fable-5.2", cost=0.01, elapsed=4.0).assign( + cache_hit_calls=np.nan + ) + stats = run_stats(rows, "claude-fable-5.2") + assert stats["answered_calls"] == 2 + assert stats["cache_hit_calls"] is None + + +def test_unrecorded_output_tokens_are_null_not_zero(run_stats): + rows = _rows("claude-fable-5.2", cost=0.01, elapsed=4.0) + unrecorded = rows.assign(completion_tokens=np.nan) + assert run_stats(unrecorded, "claude-fable-5.2")["output_tokens"] is None + absent = rows.drop(columns=["completion_tokens"]) + assert run_stats(absent, "claude-fable-5.2")["output_tokens"] is None + + +def test_partly_timed_rows_report_no_time_window(run_stats): + """One household untimed: the earliest recorded start bounds the first + request but need not be it, so the window is null, as a call count some + row lacks is.""" + rows = _rows("claude-fable-5.2", cost=0.01, elapsed=4.0) + rows.loc[rows["scenario_id"] == "s2", list(UNTIMED)] = np.nan + stats = run_stats(rows, "claude-fable-5.2") + assert stats["first_request_utc"] is None + assert stats["last_response_utc"] is None + + +def test_lockfile_pin_is_null_without_a_first_request(script): + """git log reads --before=None as now; with no first request the pin is + not established, so it is null rather than today's lockfile.""" + assert script.lockfile_litellm(None) == {"lockfile_commit": None, "litellm": None} + + +def test_board_rows_reproduce_the_committed_run_figures(script, frozen): + """The published summary's board figures, from the frozen board rows: + Opus 5.5's rows predate the call counts (null), Fable 5.2's record them.""" + _, board = frozen + committed = json.loads( + (ROOT / "sensitivity" / "data" / "claude-effort-2026-11.json").read_text() + )["runs"] + boards = {run["model"]: run["board"] for run in committed.values()} + assert set(boards) == {FABLE, OPUS} + for model, published in boards.items(): + stats = script.run_stats(board, model) + assert stats == {field: published[field] for field in stats}, model + assert boards[OPUS]["answered_calls"] is None + assert boards[FABLE]["answered_calls"] == 106 From 314c2738e6623ea3a325c5fffc5a26b044e967a2 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:31:50 +0100 Subject: [PATCH 09/17] Say when a model reaches the cost fallback and what a GPT row can prove (review r2) model_cost_latency's docstring said the fallback reaches rows from a run that had no price for the model. It also reaches a model none of whose responses recorded both token counts: a batch cell answered with a prompt count only, then repaired with a completion count only, merges to a row with both counts and no cost. A test builds that row with the batch runner and pins what the fill does with it (an input-and-output override prices the sums; a cache-rate override gives no cost). The GPT bullet said the rows cannot show whether a request crossed 272k. A one-response row above 272k does show it; the fill prices neither case. No computed result changes. Co-Authored-By: Claude Fable 5.2 --- policybench/analysis.py | 26 +++++++---- tests/test_cost_latency.py | 96 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 109 insertions(+), 13 deletions(-) diff --git a/policybench/analysis.py b/policybench/analysis.py index 181f0eae..51353afa 100644 --- a/policybench/analysis.py +++ b/policybench/analysis.py @@ -1488,11 +1488,16 @@ def _override_fallback_cost( completion count, or the reverse, which ``eval_no_tools._reconstruct_token_cost`` would not price. - The Responses-API GPT models (``GPT_RESPONSES_MODELS``) charge every - token of a request above 272k prompt tokens at a higher rate. No row - records a request's own prompt count or how many rows share it, and a - sum over a household's rows bounds a request's prompt only when the - frame holds every row the request was split among, unrepaired, which - the rows cannot show. These models get no cost. + token of a request above 272k prompt tokens at a higher rate. A row + holds a share of its responses' usage, and no row records how many + rows share a response, so a row at or below 272k does not show which + rate its request paid: a sum over a household's rows bounds a + request's prompt only when the frame holds every row the request was + split among, unrepaired, which the rows cannot show. A row that + records one response and a prompt share above 272k does prove the + higher rate for that response, and pricing the model that way would + need every priced row to prove it. The fill does not attempt it: + these models get no cost. - An override with a ``cache_read`` or ``cache_write`` rate prices cached and cache-write tokens at those rates (a rate it does not list is the input rate), bounding each row's counts by its prompt count as the @@ -1584,10 +1589,13 @@ def model_cost_latency( a per-household figure. Latency is the *median* per-household request-time — each household's calls summed, then the median across households — which is robust to the occasional rate-limit retry that inflates the mean. When no - row of a model records a cost (rows from a run that had no price for the - model), :func:`_override_fallback_cost` fills it from ``price_overrides`` - where the rows' recorded usage supports the override's pricing, and - otherwise the model gets no cost and no ``costUsd`` key. + row of a model records a cost, :func:`_override_fallback_cost` fills it + from ``price_overrides`` where the rows' recorded usage supports the + override's pricing, and otherwise the model gets no cost and no + ``costUsd`` key. No row records a cost at least when the run had no price + for the model, and when no response behind the rows recorded both a + prompt and a completion count (a row can still hold both counts, summed + from two such responses). """ if predictions.empty or "model" not in predictions.columns: return {} diff --git a/tests/test_cost_latency.py b/tests/test_cost_latency.py index 056e0ed3..9873ae0f 100644 --- a/tests/test_cost_latency.py +++ b/tests/test_cost_latency.py @@ -18,7 +18,9 @@ and cache-write tokens, bounded by its prompt count, at the override's cache rates where it has them; - a Responses-API GPT model's cost is never filled: its long-context rate - turns on one request's prompt length, which no row records; + turns on one request's prompt length, and a row holds a share of it (a + one-response row above 272k would prove the higher rate; the fill does not + price that case); - costPerHousehold is costUsd over the distinct households in the input. The reconstruction tests check that a filled cache-rate cost is what eval_no_tools._reconstruct_token_cost records for the one response the rows @@ -226,9 +228,11 @@ def _usage_row( @pytest.mark.parametrize("prompt", [100_000, 300_000]) def test_gpt_responses_override_fills_no_cost(prompt): """GPT-6.1 Sol charges a request above 272k prompt tokens 2x input and - cache and 1.5x output on every token. A row holds an equal share of its - request group's usage, so the row does not show whether a request crossed - 272k, and pricing the rows at the base rates could understate the cost.""" + cache and 1.5x output on every token. A row holds a share of its + responses' usage: a row at or below 272k does not show whether its + request crossed the line, and pricing it at the base rates could + understate the cost. A one-response row above 272k does show it; the fill + prices neither.""" model = "gpt-6.1-sol" preds = pd.DataFrame( [_usage_row(model, "s1", prompt, 20_000, 50_000, 0)], @@ -524,6 +528,90 @@ def test_input_output_override_ignores_response_counts(): assert out["m"]["costUsd"] == pytest.approx(10.0) +def test_a_batch_cell_merged_from_two_partial_count_responses_reaches_the_fill(): + """A row has no cost when no response behind it has one, and a response + that reports only one of the two token counts has none. A batch cell + answered with a prompt count and no completion count, then repaired with + a completion count and no prompt count, merges to a row with both counts + and no cost, so a model whose every row is like it reaches the fill + though the run had a price for it. The input-and-output fill prices the + row's sums, which the reconstruction prices for neither response; under + a cache-rate override the row sums two responses and gets no cost.""" + from policybench import batch_eval + + model = "gemini-3.6-flash" + answers = [ + ({"prompt_tokens": 100_000}, None, False), + ( + {"completion_tokens": 1_000}, + '{"eitc": {"value": 123, "explanation": "x = 123"}}', + True, + ), + ] + rows_by_key, attempts_by_key, disagreements, ledger = {}, {}, [], [] + for round_index, (usage, content, repair) in enumerate(answers): + unit = batch_eval.BatchUnit( + scenario_id="s1", variables=["eitc"], chunk_index=0, repair=repair + ) + result = batch_eval.NormalizedResult( + custom_id=unit.custom_id, content=content, **usage + ) + predictions, explanations, raw, error = batch_eval.parse_unit_result( + unit, result + ) + state = batch_eval.BatchRunState( + model=model, + round_index=round_index, + batch_id=f"b{round_index}", + provider="gemini", + submitted_at=0.0, + ) + ledger.append( + batch_eval._batch_spend_record( + state=state, + unit=unit, + model_name=model, + model_id=MODELS[model], + result=result, + predictions=predictions, + explanations=explanations, + error=error, + ) + ) + rows = batch_eval.rows_from_unit( + model_name=model, + model_id=MODELS[model], + unit=unit, + predictions=predictions, + explanations=explanations, + raw_response=raw, + error=error, + result=result, + ) + assert rows[0]["total_cost_usd"] is None + batch_eval.merge_attempt_rows(rows_by_key, attempts_by_key, rows, disagreements) + merged = pd.DataFrame(list(rows_by_key.values())) + batch_eval._apply_spend_ledger_costs(merged, ledger) + (row,) = merged.to_dict("records") + assert (row["prompt_tokens"], row["completion_tokens"]) == (100_000, 1_000) + assert pd.isna(row["total_cost_usd"]) + assert (row["live_calls"], row["cache_hit_calls"]) == (2, 0) + + out = model_cost_latency(merged, PRICE_OVERRIDES_PER_1M) + rates = PRICE_OVERRIDES_PER_1M[model] + assert set(rates) == {"input", "output"} + assert out[model]["costUsd"] == pytest.approx( + (100_000 * rates["input"] + 1_000 * rates["output"]) / 1e6 + ) + cache_rate_model = merged.assign( + model="claude-fable-5.2", + cached_prompt_tokens=0.0, + cache_write_prompt_tokens=0.0, + ) + out = model_cost_latency(cache_rate_model, PRICE_OVERRIDES_PER_1M) + assert "costUsd" not in out.get("claude-fable-5.2", {}) + + def test_cache_write_rate_needs_the_cached_count(): """The cached count bounds the cache-write count, so an override with a cache-write rate and no cache-read rate still needs it: 300k cached and From b3f9542242935dc7662d1ca0f3f3d52399f8483f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:32:44 +0100 Subject: [PATCH 10/17] Read the frozen exact, within-1% and parsed counts with get too (review r2) The dashboard also drops exact and within1pct when it cannot compute them, so check_board read them the way it read costUsd. A score the frozen row lacks now fails the check instead of raising KeyError. Co-Authored-By: Claude Fable 5.2 --- scripts/effort_sensitivity.py | 16 ++++++++++------ tests/test_effort_sensitivity_run_stats.py | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/scripts/effort_sensitivity.py b/scripts/effort_sensitivity.py index 87f9ebf7..b7cf33a8 100644 --- a/scripts/effort_sensitivity.py +++ b/scripts/effort_sensitivity.py @@ -390,13 +390,17 @@ def check_board(inputs: ScoringInputs, board: pd.DataFrame) -> dict: for model in BOARD_MODELS: row = stats[model] mine = run_stats(board, model) - # The dashboard leaves out a cost or latency it cannot establish (the - # key is absent, not null), so read those two with get. + # The dashboard leaves out a figure it cannot establish (the key is + # absent, not null), so read each one it may omit with get; score is + # always there. report[model] = { - "exact": (scores[model]["exact"], row["exact"]), - "within1pct": (scores[model]["within1pct"], row["within1pct"]), + "exact": (scores[model]["exact"], row.get("exact")), + "within1pct": (scores[model]["within1pct"], row.get("within1pct")), "score": (scores[model]["score"], row["score"]), - "household_mean_exact": (100 * float(wide[model].mean()), row["exact"]), + "household_mean_exact": ( + 100 * float(wide[model].mean()), + row.get("exact"), + ), "cost_usd": (mine["cost_usd"], row.get("costUsd")), "median_household_seconds": ( mine["median_household_seconds"], @@ -411,7 +415,7 @@ def check_board(inputs: ScoringInputs, board: pd.DataFrame) -> dict: .notna() .sum() ), - row["nParsed"], + row.get("nParsed"), ), } return report diff --git a/tests/test_effort_sensitivity_run_stats.py b/tests/test_effort_sensitivity_run_stats.py index d694c8e9..a633e010 100644 --- a/tests/test_effort_sensitivity_run_stats.py +++ b/tests/test_effort_sensitivity_run_stats.py @@ -170,6 +170,22 @@ def test_a_figure_only_the_recomputation_has_fails_the_board_check( assert not _passes(script, report) +@pytest.mark.parametrize( + ("key", "field"), + [("exact", "exact"), ("within1pct", "within1pct"), ("nParsed", "n_parsed")], +) +def test_a_score_the_frozen_row_lacks_fails_the_board_check(script, frozen, key, field): + """The dashboard also leaves out a score it could not compute; the check + reports it as missing and fails, for the exact comparison as well.""" + inputs, board = frozen + report = script.check_board(_without(inputs, FABLE, key), board) + mine, frozen_value = report[FABLE][field] + assert mine is not None + assert frozen_value is None + assert mine != frozen_value + assert not _passes(script, report) + + def test_a_cost_neither_side_records_passes_the_board_check(script, frozen): """Fable 5.2 rows with no recorded cost whose rows each sum two responses get no cost from the cache-rate fill; a frozen row without costUsd agrees, From aacced1a25cb5630bb6e0876641d95caedd02b10 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:33:41 +0100 Subject: [PATCH 11/17] Keep a run's tokens and time window when one household failed A failed household's rows record no usage and no request times (and call counts of zero). Requiring every row to record completion tokens and request times would have nulled the whole run's output tokens, request window and lockfile pin for one failed household, where they came from the households that answered. Those three figures now use the rows that record them and are null only when none does. The call counts keep the every-row rule. Co-Authored-By: Claude Fable 5.2 --- scripts/effort_sensitivity.py | 25 +++++++++---- tests/test_effort_sensitivity_run_stats.py | 43 ++++++++++++++++------ 2 files changed, 50 insertions(+), 18 deletions(-) diff --git a/scripts/effort_sensitivity.py b/scripts/effort_sensitivity.py index b7cf33a8..434ef50b 100644 --- a/scripts/effort_sensitivity.py +++ b/scripts/effort_sensitivity.py @@ -322,6 +322,15 @@ def _every_row(rows: pd.DataFrame, column: str) -> pd.Series | None: return rows[column] +def _recorded(rows: pd.DataFrame, column: str) -> pd.Series | None: + """The values the rows record in a column, or None when none does (or + the column is absent).""" + if column not in rows.columns: + return None + values = rows[column].dropna() + return None if values.empty else values + + def _float_or_none(value: float | None) -> float | None: return None if value is None else float(value) @@ -345,16 +354,18 @@ def run_stats(predictions: pd.DataFrame, model: str) -> dict: # here, as the dashboard shows them as not recorded. cost = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M).get(model, {}) # live_calls and cache_hit_calls count the answered and replayed provider - # calls behind a household's rows (repeated on each row). A figure some - # row does not record (rows written before its column existed, or calls - # nobody timed) is null here, not zero and not a bound from the rows that - # do record it. + # calls behind a household's rows (repeated on each row, zero for a + # household whose request failed). Rows written before a count's column + # existed leave it empty, and then the count is null, not zero. live = _every_row(rows, "live_calls") live_calls = None if live is None else live.groupby(rows["scenario_id"]).first() hits = _every_row(rows, "cache_hit_calls") - completion = _every_row(rows, "completion_tokens") - started = _every_row(rows, "request_started_at") - completed = _every_row(rows, "request_completed_at") + # A failed household's rows record no usage and no request times, so the + # output tokens and the request window come from the rows that record + # them, and are null only when none does. + completion = _recorded(rows, "completion_tokens") + started = _recorded(rows, "request_started_at") + completed = _recorded(rows, "request_completed_at") parsed = rows["prediction"].notna() return { "households": int(rows["scenario_id"].nunique()), diff --git a/tests/test_effort_sensitivity_run_stats.py b/tests/test_effort_sensitivity_run_stats.py index a633e010..7e74bc84 100644 --- a/tests/test_effort_sensitivity_run_stats.py +++ b/tests/test_effort_sensitivity_run_stats.py @@ -4,10 +4,12 @@ model_cost_latency leaves out a cost it cannot establish, and the model when it has neither a cost nor a latency; run_stats then reports null for those fields, as the dashboard reports a cost as not recorded, rather than failing. -It reports null the same way for output tokens, call counts and the request -time window when some row does not record them (rows written before the -column existed, or calls nobody timed), where it used to raise or report -zero; with no first request, the lockfile pin is null too. +It reports null the same way for a call count some row does not record (rows +written before the column existed), and for output tokens and the request +time window when no row records them, where it used to raise or report zero; +with no first request, the lockfile pin is null too. A household whose +request failed records no usage and no request times, and does not null the +run's figures. The dashboard leaves such a key out of a frozen modelStats row (the committed snapshot's gpt-5.5 row has no latencySeconds), so --check-board reads the frozen figures without assuming the keys: a figure only one side records fails @@ -274,15 +276,34 @@ def test_unrecorded_output_tokens_are_null_not_zero(run_stats): assert run_stats(absent, "claude-fable-5.2")["output_tokens"] is None -def test_partly_timed_rows_report_no_time_window(run_stats): - """One household untimed: the earliest recorded start bounds the first - request but need not be it, so the window is null, as a call count some - row lacks is.""" +def test_a_failed_household_keeps_the_runs_tokens_and_time_window(run_stats): + """The runner writes a failed household's rows with no prediction, usage + or request times and with call counts of zero. The run's output tokens, + request window and counts still come from the households that answered.""" rows = _rows("claude-fable-5.2", cost=0.01, elapsed=4.0) - rows.loc[rows["scenario_id"] == "s2", list(UNTIMED)] = np.nan + failed = rows["scenario_id"] == "s2" + unrecorded = [ + "prediction", + "total_cost_usd", + "elapsed_seconds", + "prompt_tokens", + "completion_tokens", + "total_tokens", + "cached_prompt_tokens", + "cache_write_prompt_tokens", + *UNTIMED, + ] + rows.loc[failed, unrecorded] = np.nan + rows.loc[failed, "live_calls"] = 0 stats = run_stats(rows, "claude-fable-5.2") - assert stats["first_request_utc"] is None - assert stats["last_response_utc"] is None + assert stats["households"] == 2 + assert stats["parse_failures"] == 1 + assert stats["output_tokens"] == 200 + assert stats["answered_calls"] == 1 + assert stats["cache_hit_calls"] == 0 + assert stats["first_request_utc"] == "2025-11-20T00:53:20Z" + assert stats["last_response_utc"] == "2025-11-20T00:53:30Z" + assert stats["cost_usd"] == pytest.approx(0.01) def test_lockfile_pin_is_null_without_a_first_request(script): From b7cb1c684065a457e061093bc80f8d39a0bf6419 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:39:09 +0100 Subject: [PATCH 12/17] Refuse a negative or infinite published cost; say how a new model gets one require_published_costs accepted -1.0 as a cost. A cost is now a finite number, zero or more. The refusal told the reader to carry a released cost, which a new model does not have; it now says to rerun or replay the model so its rows record their costs, or to carry a cost a release decision supplies. Co-Authored-By: Claude Fable 5.2 --- scripts/freeze_snapshot.py | 25 ++++++++++++++++--------- tests/test_freeze_published_costs.py | 6 +++++- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/scripts/freeze_snapshot.py b/scripts/freeze_snapshot.py index e9c8a1d9..46d89b79 100644 --- a/scripts/freeze_snapshot.py +++ b/scripts/freeze_snapshot.py @@ -950,25 +950,32 @@ def require_published_costs(country_payload: dict) -> dict[str, float]: model's price override. The report's published total sums every board model's cost, and the paper's caption explains a missing cost only as a zero charge, so the freeze stops and names the models rather than - publish a board with a cost missing. + publish a board with a cost missing. A cost is a finite number, zero or + more. """ rows = [ row for row in country_payload["modelStats"] if row["condition"] == "no_tools" ] + + def is_cost(value: object) -> bool: + return ( + isinstance(value, (int, float)) + and not isinstance(value, bool) + and math.isfinite(value) + and value >= 0 + ) + missing = sorted( - str(row["model"]) - for row in rows - if isinstance(row.get("costUsd"), bool) - or not isinstance(row.get("costUsd"), (int, float)) - or not math.isfinite(row["costUsd"]) + str(row["model"]) for row in rows if not is_cost(row.get("costUsd")) ) if missing: raise SystemExit( f"The published payload has no costUsd for {', '.join(missing)}: no " "row of those models records a cost, and analysis.model_cost_latency " - "could not establish one from the price override. Record the rows' " - "costs or carry a released cost (as the release drivers' " - "CARRIED_USAGE does), then export again." + "could not establish one from the price override. Rerun or replay " + "the model so its rows record their costs, or carry a cost a " + "release decision supplies (as the release drivers' CARRIED_USAGE " + "does), then export again." ) return {row["model"]: row["costUsd"] for row in rows} diff --git a/tests/test_freeze_published_costs.py b/tests/test_freeze_published_costs.py index 5ae52cce..491b324f 100644 --- a/tests/test_freeze_published_costs.py +++ b/tests/test_freeze_published_costs.py @@ -44,6 +44,8 @@ def test_a_board_model_without_a_cost_is_named(): _stat("no-key"), _stat("null", costUsd=None), _stat("nan", costUsd=math.nan), + _stat("infinite", costUsd=math.inf), + _stat("negative", costUsd=-1.0), _stat("true", costUsd=True), _stat("text", costUsd="1.0"), _stat("tools-arm", condition="with_tools"), @@ -51,7 +53,9 @@ def test_a_board_model_without_a_cost_is_named(): with pytest.raises(SystemExit) as refused: freezer.require_published_costs(payload) message = str(refused.value) - assert "no costUsd for nan, no-key, null, text, true:" in message + assert ( + "no costUsd for infinite, nan, negative, no-key, null, text, true:" in message + ) assert "tools-arm" not in message assert "costed" not in message From 9135560fc134119a40b5ba027194dabaef7c0782 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:58:51 +0100 Subject: [PATCH 13/17] Drop general claims about when the harness records a cost (review r3) The model_cost_latency docstring said no row records a cost when no response recorded both token counts. A synchronous response without both extracted counts still records the provider's reported charge when it carries one, and the extractor drops a count reported as 0. The docstring now says only that the fill can be invoked for a model whose run had a price, and names the test that builds such a row. The batch test's docstring is scoped to batch_eval.rows_from_unit, and the frozen-cost test's docstring names Claude Fable 5, for which the fill is invoked and returns nothing. The freeze's refusal reported a recorded cost of -1.0 as a cost no row records. It now reports a missing costUsd and an invalid one separately. Co-Authored-By: Claude Fable 5.2 --- policybench/analysis.py | 8 ++++---- scripts/freeze_snapshot.py | 30 ++++++++++++++++++++-------- tests/test_cost_latency.py | 30 ++++++++++++++++------------ tests/test_freeze_published_costs.py | 21 ++++++++++++++++--- 4 files changed, 61 insertions(+), 28 deletions(-) diff --git a/policybench/analysis.py b/policybench/analysis.py index 51353afa..6e20f530 100644 --- a/policybench/analysis.py +++ b/policybench/analysis.py @@ -1592,10 +1592,10 @@ def model_cost_latency( row of a model records a cost, :func:`_override_fallback_cost` fills it from ``price_overrides`` where the rows' recorded usage supports the override's pricing, and otherwise the model gets no cost and no - ``costUsd`` key. No row records a cost at least when the run had no price - for the model, and when no response behind the rows recorded both a - prompt and a completion count (a row can still hold both counts, summed - from two such responses). + ``costUsd`` key. The fill can be invoked for a model whose run had a + price for it: a batch cell merged from two responses that each reported + one token count holds both counts and no cost (tests/test_cost_latency.py, + ``test_a_batch_cell_merged_from_two_partial_count_responses_invokes_the_fill``). """ if predictions.empty or "model" not in predictions.columns: return {} diff --git a/scripts/freeze_snapshot.py b/scripts/freeze_snapshot.py index 46d89b79..a5b6910b 100644 --- a/scripts/freeze_snapshot.py +++ b/scripts/freeze_snapshot.py @@ -965,17 +965,31 @@ def is_cost(value: object) -> bool: and value >= 0 ) - missing = sorted( - str(row["model"]) for row in rows if not is_cost(row.get("costUsd")) + absent = sorted(str(row["model"]) for row in rows if row.get("costUsd") is None) + invalid = sorted( + str(row["model"]) + for row in rows + if row.get("costUsd") is not None and not is_cost(row["costUsd"]) ) - if missing: - raise SystemExit( - f"The published payload has no costUsd for {', '.join(missing)}: no " - "row of those models records a cost, and analysis.model_cost_latency " - "could not establish one from the price override. Rerun or replay " + problems = [] + if absent: + problems.append( + f"no costUsd for {', '.join(absent)}: analysis.model_cost_latency " + "leaves a cost out when no row of the model records one and it " + "cannot establish one from the price override. Rerun or replay " "the model so its rows record their costs, or carry a cost a " "release decision supplies (as the release drivers' CARRIED_USAGE " - "does), then export again." + "does), then export again" + ) + if invalid: + problems.append( + "a costUsd that is not a finite number, zero or more, for " + f"{', '.join(invalid)}: check the costs those models' rows " + "record, then export again" + ) + if problems: + raise SystemExit( + "The published payload has " + ". It also has ".join(problems) + "." ) return {row["model"]: row["costUsd"] for row in rows} diff --git a/tests/test_cost_latency.py b/tests/test_cost_latency.py index 9873ae0f..9ada7cf8 100644 --- a/tests/test_cost_latency.py +++ b/tests/test_cost_latency.py @@ -528,15 +528,16 @@ def test_input_output_override_ignores_response_counts(): assert out["m"]["costUsd"] == pytest.approx(10.0) -def test_a_batch_cell_merged_from_two_partial_count_responses_reaches_the_fill(): - """A row has no cost when no response behind it has one, and a response - that reports only one of the two token counts has none. A batch cell - answered with a prompt count and no completion count, then repaired with - a completion count and no prompt count, merges to a row with both counts - and no cost, so a model whose every row is like it reaches the fill - though the run had a price for it. The input-and-output fill prices the - row's sums, which the reconstruction prices for neither response; under - a cache-rate override the row sums two responses and gets no cost.""" +def test_a_batch_cell_merged_from_two_partial_count_responses_invokes_the_fill(): + """batch_eval.rows_from_unit takes a row's cost from the token + reconstruction, which gives none without both a prompt and a completion + count. A batch cell answered with a prompt count and no completion + count, then repaired with a completion count and no prompt count, merges + here to a row with both counts and no cost, though the model has a + price. On a frame of such rows the fill is invoked: an input-and-output + override prices the row's sums, which the reconstruction priced for + neither response, and under a cache-rate override the row sums two + responses and gets no cost.""" from policybench import batch_eval model = "gemini-3.6-flash" @@ -972,10 +973,13 @@ def test_frozen_fable_5_usage_is_carried_not_computed(frozen): def test_frozen_filled_costs_are_the_published_ones(frozen, frozen_predictions): - """Exactly two published models record no cost on any row and take the - override's: their overrides list only input and output rates, so the - fill prices every prompt token at the input rate, as it did when the - board was published, and the figures do not move by a bit.""" + """Two published models record no cost on any row, have an override and + record both token counts, so they get a filled cost: their overrides + list only input and output rates, so the fill prices every prompt token + at the input rate, as it did when the board was published, and the + figures do not move by a bit. (Claude Fable 5 records no cost either; + its rows record no token counts, so the fill gives it nothing: + test_frozen_fable_5_usage_is_carried_not_computed.)""" computed, published = frozen filled = sorted( model diff --git a/tests/test_freeze_published_costs.py b/tests/test_freeze_published_costs.py index 491b324f..eae367ad 100644 --- a/tests/test_freeze_published_costs.py +++ b/tests/test_freeze_published_costs.py @@ -53,13 +53,28 @@ def test_a_board_model_without_a_cost_is_named(): with pytest.raises(SystemExit) as refused: freezer.require_published_costs(payload) message = str(refused.value) - assert ( - "no costUsd for infinite, nan, negative, no-key, null, text, true:" in message - ) + # A cost the payload lacks and one it carries but cannot publish are + # reported separately: the second is not a model no row costed. + assert "no costUsd for no-key, null:" in message + assert "zero or more, for infinite, nan, negative, text, true:" in message assert "tools-arm" not in message assert "costed" not in message +def test_a_recorded_negative_cost_is_not_reported_as_unrecorded(): + """Rows that record a cost of -1.0 give a dashboard row a costUsd of + -1.0. The freeze refuses it as a cost it cannot publish, without saying + that no row records one.""" + rows = _costless_rows("gemini-3.6-flash", live=1).assign(total_cost_usd=-0.5) + entry = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M)["gemini-3.6-flash"] + assert entry["costUsd"] == -1.0 + with pytest.raises(SystemExit) as refused: + freezer.require_published_costs(_payload(_stat("gemini-3.6-flash", **entry))) + message = str(refused.value) + assert "zero or more, for gemini-3.6-flash:" in message + assert "no costUsd for" not in message + + def test_a_zero_cost_is_a_cost_and_the_payload_order_is_kept(): payload = _payload( _stat("zero-charge", costUsd=0), From 3797be1ddb0b5e74f24a421a6b4df0efb892a791 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 14:25:52 +0100 Subject: [PATCH 14/17] Limit comments and docstrings to what the code and tests show A claim-by-claim check of the comments this branch adds found several that were broader than their evidence. Narrowed here, with no change to what any function computes for a row the committed data holds: - _override_fallback_cost: how a household run, a batch run and a row repair put usage on a row, as each does it; the reconstruction's length tiers "for an override". - model_cost_latency: the fill runs "in the cases that function lists"; the batch example names which count each response reported. - effort_sensitivity: the model is left out only with no cost, no latency and no total tokens; a household "none of whose requests was answered" records no usage; no statement about what the dashboard displays. - freeze_snapshot: a cost is absent when no row records one and the model has no override or the override cannot price its rows; an invalid cost can come from the rows' token counts as well as their costs. - Test docstrings: "returns" for _reconstruct_token_cost, not "records"; no statement of what a case raised before. check_board now reads the frozen score with get as well, and the property test asserts a filled cost is not negative. Co-Authored-By: Claude Fable 5.2 --- policybench/analysis.py | 44 +++++++++++--------- scripts/effort_sensitivity.py | 30 +++++++------- scripts/freeze_snapshot.py | 26 ++++++------ tests/test_cost_latency.py | 30 ++++++++------ tests/test_effort_sensitivity_run_stats.py | 48 ++++++++++++---------- tests/test_freeze_published_costs.py | 17 ++++---- tests/test_model_response_window.py | 6 +-- 7 files changed, 105 insertions(+), 96 deletions(-) diff --git a/policybench/analysis.py b/policybench/analysis.py index 6e20f530..81312502 100644 --- a/policybench/analysis.py +++ b/policybench/analysis.py @@ -1473,13 +1473,15 @@ def _override_fallback_cost( to price (Claude Fable 5's frozen board rows record no usage) gets no cost, not $0. - A row's counts can sum several provider responses. A synchronous run - adds up a household's responses (retries, repairs and chunks) and gives - each row an equal share; a batch run gives each cell's row a share of - the chunk request that answered it, summed over repair rounds; and a row - repair replaces a row's usage with the whole usage of its own responses. - ``live_calls`` plus ``cache_hit_calls`` counts the responses a row sums, - or more when a response reported no usage. + A row's counts can sum several provider responses, and can be a share + of counts several rows divide. A household run + (``eval_no_tools.run_no_tools_eval``) adds up the answered responses of + a household's request group and gives each row an equal share; a batch + run gives each cell's row an equal share of every request that covered + the cell and came back without an error, summed over repair rounds; and + a row repair replaces a row's usage with that of the one repair attempt + it accepts. ``live_calls`` plus ``cache_hit_calls`` counts the responses + a row sums, or more when a response reported no usage. - An override with only input and output rates prices the rows' summed prompt tokens, cached ones included, at the input rate and their @@ -1514,10 +1516,10 @@ def _override_fallback_cost( column another model's rows brought into the frame, and an empty response count may be a row written before the column existed. - The rates are the override's, as the reconstruction applies them: at any - prompt length, since the GPT long-context rate is the only length tier - the reconstruction models (the Claude Haiku 5.5 entry lists the rates - for prompts up to 100,000 tokens). + The rates are the override's, as the reconstruction applies an + override: at any prompt length, since the GPT long-context rate is the + only length tier it applies to an override (the Claude Haiku 5.5 entry + lists the rates for prompts up to 100,000 tokens). """ if model in GPT_RESPONSES_MODELS: return None @@ -1540,8 +1542,9 @@ def _override_fallback_cost( completion = float(sums["completion_tokens"]) if "cache_read" not in rates and "cache_write" not in rates: return prompt * rates["input"] / 1e6 + completion * rates["output"] / 1e6 - # The cached count prices at the cache-read rate and bounds the - # cache-write count; with no cache-write rate, cache-write tokens price + # The cached count prices at the cache-read rate (the input rate when + # the override lists none) and bounds the cache-write count; with no + # cache-write rate, cache-write tokens price # at the input rate like uncached ones, so their count changes nothing. counts = ["cached_prompt_tokens"] if "cache_write" in rates: @@ -1551,8 +1554,8 @@ def _override_fallback_cost( return None # One response, live or replayed: the counts are (1, 0) or (0, 1). A sum # of 1 would also pass (-1, 2) or (0.5, 0.5), which no runner writes. The - # counts compare as floats, so one read back as 1.0 (a column with an - # empty cell elsewhere, a CSV round trip) still passes. + # counts compare as floats, so a 1.0 (a count column with an empty cell + # elsewhere is a float column) still passes. live, replayed = (priced[column].astype(float) for column in RESPONSE_COUNT_COLUMNS) one_response = ((live == 1) & (replayed == 0)) | ((live == 0) & (replayed == 1)) if not one_response.all(): @@ -1590,11 +1593,12 @@ def model_cost_latency( each household's calls summed, then the median across households — which is robust to the occasional rate-limit retry that inflates the mean. When no row of a model records a cost, :func:`_override_fallback_cost` fills it - from ``price_overrides`` where the rows' recorded usage supports the - override's pricing, and otherwise the model gets no cost and no - ``costUsd`` key. The fill can be invoked for a model whose run had a - price for it: a batch cell merged from two responses that each reported - one token count holds both counts and no cost (tests/test_cost_latency.py, + from ``price_overrides`` in the cases that function lists, and otherwise + the model gets no cost and no ``costUsd`` key. The fill can be invoked + for a model whose run had a price for it: a batch cell merged from a + response that reported only a prompt count and a repair that reported + only a completion count holds both counts and no cost + (tests/test_cost_latency.py, ``test_a_batch_cell_merged_from_two_partial_count_responses_invokes_the_fill``). """ if predictions.empty or "model" not in predictions.columns: diff --git a/scripts/effort_sensitivity.py b/scripts/effort_sensitivity.py index 434ef50b..22c833b4 100644 --- a/scripts/effort_sensitivity.py +++ b/scripts/effort_sensitivity.py @@ -337,8 +337,7 @@ def _float_or_none(value: float | None) -> float | None: def _close(mine: float | None, frozen: float | None) -> bool: """Whether a recomputed figure is within 1e-9 of the frozen one. A figure - neither side records (the dashboard shows it as not recorded) matches; a - figure only one side records does not.""" + neither side records matches; a figure only one side records does not.""" if mine is None and frozen is None: return True if mine is None or frozen is None: @@ -350,19 +349,20 @@ def run_stats(predictions: pd.DataFrame, model: str) -> dict: """Cost, output tokens, median latency, calls and parse failures of one row.""" rows = predictions[predictions["model"] == model] # model_cost_latency leaves out a cost it cannot establish (and a latency - # no row timed), and the model itself when it has neither; those are null - # here, as the dashboard shows them as not recorded. + # no row timed), and the model itself when it has no cost, no latency and + # no total tokens; those are null here. cost = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M).get(model, {}) - # live_calls and cache_hit_calls count the answered and replayed provider - # calls behind a household's rows (repeated on each row, zero for a - # household whose request failed). Rows written before a count's column - # existed leave it empty, and then the count is null, not zero. + # live_calls and cache_hit_calls count the answered and replayed + # responses behind a row. A household run repeats a household's counts + # on each of its rows, so this reads each household's first row. A count + # some row leaves empty (rows written before its column existed) is + # null, not zero. live = _every_row(rows, "live_calls") live_calls = None if live is None else live.groupby(rows["scenario_id"]).first() hits = _every_row(rows, "cache_hit_calls") - # A failed household's rows record no usage and no request times, so the - # output tokens and the request window come from the rows that record - # them, and are null only when none does. + # A household none of whose requests was answered records no usage and + # no request times, so the output tokens and the request window come + # from the rows that record them, and are null only when none does. completion = _recorded(rows, "completion_tokens") started = _recorded(rows, "request_started_at") completed = _recorded(rows, "request_completed_at") @@ -401,13 +401,13 @@ def check_board(inputs: ScoringInputs, board: pd.DataFrame) -> dict: for model in BOARD_MODELS: row = stats[model] mine = run_stats(board, model) - # The dashboard leaves out a figure it cannot establish (the key is - # absent, not null), so read each one it may omit with get; score is - # always there. + # A frozen row can lack a figure: the dashboard drops a cost, latency, + # exact or within-1% rate it cannot establish (the key is absent, not + # null). Read each with get, so a missing one fails the comparison. report[model] = { "exact": (scores[model]["exact"], row.get("exact")), "within1pct": (scores[model]["within1pct"], row.get("within1pct")), - "score": (scores[model]["score"], row["score"]), + "score": (scores[model]["score"], row.get("score")), "household_mean_exact": ( 100 * float(wide[model].mean()), row.get("exact"), diff --git a/scripts/freeze_snapshot.py b/scripts/freeze_snapshot.py index a5b6910b..c4697927 100644 --- a/scripts/freeze_snapshot.py +++ b/scripts/freeze_snapshot.py @@ -946,12 +946,12 @@ def require_published_costs(country_payload: dict) -> dict[str, float]: that lacks one. ``analysis.model_cost_latency`` leaves ``costUsd`` out when no row of a - model records a cost and the rows' usage cannot establish one from the - model's price override. The report's published total sums every board - model's cost, and the paper's caption explains a missing cost only as a - zero charge, so the freeze stops and names the models rather than - publish a board with a cost missing. A cost is a finite number, zero or - more. + model records a cost and either the model has no price override or + ``analysis._override_fallback_cost`` returns no cost for its rows. The + report's published total sums every board model's cost, and the paper's + render asserts that the models with a cost dash are its zero-cost + models, so the freeze stops and names the models rather than publish a + board with a cost missing. A cost is a finite number, zero or more. """ rows = [ row for row in country_payload["modelStats"] if row["condition"] == "no_tools" @@ -975,17 +975,17 @@ def is_cost(value: object) -> bool: if absent: problems.append( f"no costUsd for {', '.join(absent)}: analysis.model_cost_latency " - "leaves a cost out when no row of the model records one and it " - "cannot establish one from the price override. Rerun or replay " - "the model so its rows record their costs, or carry a cost a " - "release decision supplies (as the release drivers' CARRIED_USAGE " - "does), then export again" + "leaves a cost out when no row of the model records one and the " + "model has no price override or the override cannot price its " + "rows. Rerun or replay the model so its rows record their costs, " + "or carry a cost a release decision supplies (as the release " + "drivers' CARRIED_USAGE does), then export again" ) if invalid: problems.append( "a costUsd that is not a finite number, zero or more, for " - f"{', '.join(invalid)}: check the costs those models' rows " - "record, then export again" + f"{', '.join(invalid)}: check the costs and token counts those " + "models' rows record, then export again" ) if problems: raise SystemExit( diff --git a/tests/test_cost_latency.py b/tests/test_cost_latency.py index 9ada7cf8..0b14918e 100644 --- a/tests/test_cost_latency.py +++ b/tests/test_cost_latency.py @@ -4,9 +4,10 @@ - costUsd and costPerHousehold are both present or both absent; - a recorded cost is the sum of the recorded row costs and the override is not consulted; -- otherwise a model has a cost exactly when it has a price override that is - not a Responses-API GPT model and one of its rows recorded both prompt and - completion token counts, and, for an override with a cache rate, every such +- otherwise, for finite counts and rates, a model has a cost exactly when it + has a price override that is not a Responses-API GPT model and one of its + rows recorded both prompt and completion token counts, and, for an + override with a cache rate, every such row records one provider response (live_calls and cache_hit_calls are 1 and 0, or 0 and 1), a cached count and, if the override lists a cache-write rate, a cache-write count; a row missing either token count is not priced, @@ -23,11 +24,12 @@ price that case); - costPerHousehold is costUsd over the distinct households in the input. The reconstruction tests check that a filled cache-rate cost is what -eval_no_tools._reconstruct_token_cost records for the one response the rows -share, and that rows summing two responses, or with an unrecorded count, get -no cost. The frozen-snapshot tests check the published figures: every model's -usage fields but Claude Fable 5's reproduce from the frozen predictions, -including the two models whose cost the override fills (Gemini 3.6 Flash and +eval_no_tools._reconstruct_token_cost returns for the counts of the one +response the rows share, and that rows summing two responses, or with an +unrecorded count, get no cost. The frozen-snapshot tests check the published +figures: every model's usage fields but Claude Fable 5's reproduce from the +frozen predictions, including the two models whose cost the override fills +(Gemini 3.6 Flash and Grok Build 0.1), and Fable 5's, which those rows do not record, are not computed at all. """ @@ -476,8 +478,8 @@ def test_one_replayed_response_is_priced(): def test_response_counts_read_back_as_floats_are_priced(): - """A count column with an empty cell elsewhere, or one read back from a - CSV beside such a column, holds 1.0 and 0.0: still one response.""" + """A count column with an empty cell elsewhere is a float column, so + its counts are 1.0 and 0.0: still one response.""" model = "claude-fable-5.2" preds = pd.DataFrame( [ @@ -697,9 +699,10 @@ def test_filled_cost_matches_request_reconstruction( model, prompt, completion, cached, cache_write ): """A household answered by one response has its usage on one row here, so - the filled cost is what eval_no_tools._reconstruct_token_cost records for - that response, for every override, where the row records each count the - override's cache rates need; a GPT Responses model's is not filled.""" + the filled cost is what eval_no_tools._reconstruct_token_cost returns + for that response's counts, for every override, where the row records + each count the override's cache rates need; a GPT Responses model's is + not filled.""" reconstruct = _reconstruction() recorded = reconstruct( model_name=model, @@ -899,6 +902,7 @@ def recorded(value): assert "costUsd" not in entry continue assert entry["costUsd"] == pytest.approx(expected, rel=1e-12, abs=1e-12) + assert entry["costUsd"] >= 0 assert entry["costPerHousehold"] == pytest.approx( entry["costUsd"] / households, rel=1e-12, abs=1e-12 ) diff --git a/tests/test_effort_sensitivity_run_stats.py b/tests/test_effort_sensitivity_run_stats.py index 7e74bc84..49631cee 100644 --- a/tests/test_effort_sensitivity_run_stats.py +++ b/tests/test_effort_sensitivity_run_stats.py @@ -2,18 +2,17 @@ rows cannot establish. model_cost_latency leaves out a cost it cannot establish, and the model when -it has neither a cost nor a latency; run_stats then reports null for those -fields, as the dashboard reports a cost as not recorded, rather than failing. -It reports null the same way for a call count some row does not record (rows -written before the column existed), and for output tokens and the request -time window when no row records them, where it used to raise or report zero; -with no first request, the lockfile pin is null too. A household whose -request failed records no usage and no request times, and does not null the -run's figures. -The dashboard leaves such a key out of a frozen modelStats row (the committed -snapshot's gpt-5.5 row has no latencySeconds), so --check-board reads the -frozen figures without assuming the keys: a figure only one side records fails -the check, and a figure neither side records passes it. +it has no cost, no latency and no total tokens; run_stats then reports null +for those fields rather than failing. It reports null the same way for a call +count some row does not record (rows written before the column existed), and +for output tokens and the request time window when no row records them; with +no first request, the lockfile pin is null too. A household none of whose +requests was answered records no usage and no request times, and does not +null the run's figures. +A frozen modelStats row can lack a figure's key (the committed snapshot's +gpt-5.5 row has no latencySeconds), so --check-board reads the frozen figures +with get: a figure only one side records fails the check, and a figure +neither side records passes it. """ import copy @@ -174,11 +173,17 @@ def test_a_figure_only_the_recomputation_has_fails_the_board_check( @pytest.mark.parametrize( ("key", "field"), - [("exact", "exact"), ("within1pct", "within1pct"), ("nParsed", "n_parsed")], + [ + ("exact", "exact"), + ("within1pct", "within1pct"), + ("score", "score"), + ("nParsed", "n_parsed"), + ], ) def test_a_score_the_frozen_row_lacks_fails_the_board_check(script, frozen, key, field): - """The dashboard also leaves out a score it could not compute; the check - reports it as missing and fails, for the exact comparison as well.""" + """A frozen row without exact, within1pct, score or nParsed: the check + reports the figure as missing and fails, for the exact comparison as + well.""" inputs, board = frozen report = script.check_board(_without(inputs, FABLE, key), board) mine, frozen_value = report[FABLE][field] @@ -218,8 +223,7 @@ def test_a_cost_neither_side_records_passes_the_board_check(script, frozen): def test_untimed_rows_report_no_latency_and_no_time_window(run_stats): """Rows that record no elapsed time and no request timestamps: the cost is - still reported; the latency and the first and last times are null. This - raised ValueError (NaT) from the time window.""" + still reported; the latency and the first and last times are null.""" rows = _rows("claude-fable-5.2", cost=0.01, elapsed=np.nan).assign(**UNTIMED) stats = run_stats(rows, "claude-fable-5.2") assert stats["cost_usd"] == pytest.approx(0.02) @@ -240,8 +244,7 @@ def test_rows_without_timestamps_keep_their_latency(run_stats): def test_rows_written_before_the_provenance_columns_report_null_counts(run_stats): """Rows from a run that wrote no call counts or request times: those - figures are null, the rest is reported, and the result writes as JSON. - This raised KeyError('live_calls').""" + figures are null, the rest is reported, and the result writes as JSON.""" rows = _rows("claude-fable-5.2", cost=0.01, elapsed=4.0).drop(columns=PROVENANCE) stats = run_stats(rows, "claude-fable-5.2") for field in ( @@ -277,9 +280,10 @@ def test_unrecorded_output_tokens_are_null_not_zero(run_stats): def test_a_failed_household_keeps_the_runs_tokens_and_time_window(run_stats): - """The runner writes a failed household's rows with no prediction, usage - or request times and with call counts of zero. The run's output tokens, - request window and counts still come from the households that answered.""" + """Rows as eval_no_tools.run_no_tools_eval writes them for a household + whose run raised: no prediction, usage or request times, and call counts + of zero. The run's output tokens, request window and counts still come + from the household that answered.""" rows = _rows("claude-fable-5.2", cost=0.01, elapsed=4.0) failed = rows["scenario_id"] == "s2" unrecorded = [ diff --git a/tests/test_freeze_published_costs.py b/tests/test_freeze_published_costs.py index eae367ad..9ef32f09 100644 --- a/tests/test_freeze_published_costs.py +++ b/tests/test_freeze_published_costs.py @@ -1,12 +1,11 @@ """The freeze needs a published cost for every board model. analysis.model_cost_latency leaves costUsd out of a model's dashboard row when -no row of the model records a cost and the rows' usage cannot establish one -from its price override: a cache-rate model whose rows sum several responses -or lack a count, and a Responses-API GPT model. The freeze's report sums -every board model's cost, so freeze_snapshot.require_published_costs names -the models without one and stops, where the lookup used to raise -KeyError('costUsd'). +no row of the model records a cost and the fill from its price override +returns none (for example a cache-rate model whose rows sum several +responses, or a Responses-API GPT model). The freeze's report sums every +board model's cost, so freeze_snapshot.require_published_costs names the +models without one and stops. """ from __future__ import annotations @@ -62,9 +61,9 @@ def test_a_board_model_without_a_cost_is_named(): def test_a_recorded_negative_cost_is_not_reported_as_unrecorded(): - """Rows that record a cost of -1.0 give a dashboard row a costUsd of - -1.0. The freeze refuses it as a cost it cannot publish, without saying - that no row records one.""" + """Two rows that each record a cost of -0.5 give a dashboard row a + costUsd of -1.0. The freeze refuses it as a cost it cannot publish, + without saying that no row records one.""" rows = _costless_rows("gemini-3.6-flash", live=1).assign(total_cost_usd=-0.5) entry = model_cost_latency(rows, PRICE_OVERRIDES_PER_1M)["gemini-3.6-flash"] assert entry["costUsd"] == -1.0 diff --git a/tests/test_model_response_window.py b/tests/test_model_response_window.py index d767a500..b85ab017 100644 --- a/tests/test_model_response_window.py +++ b/tests/test_model_response_window.py @@ -256,10 +256,8 @@ def test_the_freeze_refuses_a_release_date_window_before_any_write( def test_the_freeze_refuses_a_board_model_without_a_cost_before_any_write( freeze_inputs, ): - """analysis.model_cost_latency leaves costUsd out of a model's row when - its rows record no cost and their usage cannot establish one. The freeze - names that model and stops before it deletes or rewrites anything; it - used to raise KeyError('costUsd') after rewriting the run directory.""" + """A board model whose dashboard row has no costUsd: the freeze names + it and stops before any of main's write steps runs.""" freezer.PUBLISHED_DASHBOARD_SOURCE.write_text( json.dumps( { From 7eb2422af55298246a64cc3ea117d53e8d4c30db Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 14:50:02 +0100 Subject: [PATCH 15/17] Narrow four more comments a second claims check flagged - _override_fallback_cost: say only that a row's counts can sum several responses and can be an equal share. The sentence about what a household run adds up had a counterexample (a household whose first round raises after a truncated response was answered). - check_board: a cost or latency neither side has passes; the comment said a missing figure fails. - Test header: the recorded-cost invariant is for finite recorded costs. - _two_response_rows: name the household runner. Comments only; no code changes. Co-Authored-By: Claude Fable 5.2 --- policybench/analysis.py | 14 +++++--------- scripts/effort_sensitivity.py | 4 +++- tests/test_cost_latency.py | 11 ++++++----- 3 files changed, 14 insertions(+), 15 deletions(-) diff --git a/policybench/analysis.py b/policybench/analysis.py index 81312502..555206aa 100644 --- a/policybench/analysis.py +++ b/policybench/analysis.py @@ -1473,15 +1473,11 @@ def _override_fallback_cost( to price (Claude Fable 5's frozen board rows record no usage) gets no cost, not $0. - A row's counts can sum several provider responses, and can be a share - of counts several rows divide. A household run - (``eval_no_tools.run_no_tools_eval``) adds up the answered responses of - a household's request group and gives each row an equal share; a batch - run gives each cell's row an equal share of every request that covered - the cell and came back without an error, summed over repair rounds; and - a row repair replaces a row's usage with that of the one repair attempt - it accepts. ``live_calls`` plus ``cache_hit_calls`` counts the responses - a row sums, or more when a response reported no usage. + A row's counts can sum several provider responses (a household's + re-requests and repair rounds in ``eval_no_tools.run_no_tools_eval``, a + batch cell's repair rounds), and can be an equal share of counts that + several rows divide. ``live_calls`` plus ``cache_hit_calls`` counts the + responses a row sums, or more when a response reported no usage. - An override with only input and output rates prices the rows' summed prompt tokens, cached ones included, at the input rate and their diff --git a/scripts/effort_sensitivity.py b/scripts/effort_sensitivity.py index 22c833b4..7ab985ec 100644 --- a/scripts/effort_sensitivity.py +++ b/scripts/effort_sensitivity.py @@ -403,7 +403,9 @@ def check_board(inputs: ScoringInputs, board: pd.DataFrame) -> dict: mine = run_stats(board, model) # A frozen row can lack a figure: the dashboard drops a cost, latency, # exact or within-1% rate it cannot establish (the key is absent, not - # null). Read each with get, so a missing one fails the comparison. + # null). Read each with get: a figure the frozen row lacks fails the + # comparison when the recomputation has it, and a cost or latency + # that neither side has passes. report[model] = { "exact": (scores[model]["exact"], row.get("exact")), "within1pct": (scores[model]["within1pct"], row.get("within1pct")), diff --git a/tests/test_cost_latency.py b/tests/test_cost_latency.py index 0b14918e..e173d49a 100644 --- a/tests/test_cost_latency.py +++ b/tests/test_cost_latency.py @@ -2,8 +2,8 @@ Cost invariants, for every input (the property test executes them): - costUsd and costPerHousehold are both present or both absent; -- a recorded cost is the sum of the recorded row costs and the override is - not consulted; +- for finite recorded costs, a recorded cost is the sum of the recorded row + costs and the override is not consulted; - otherwise, for finite counts and rates, a model has a cost exactly when it has a price override that is not a Responses-API GPT model and one of its rows recorded both prompt and completion token counts, and, for an @@ -391,9 +391,10 @@ def test_concatenated_frames_fill_no_cost_from_padded_cache_columns(): def _two_response_rows(model, first, second, rows): - """One synchronous household answered by two responses: the runner sums - their counts (_aggregate_request_results), splits the sums equally among - the household's rows and repeats the response count on each.""" + """One household of a household run (eval_no_tools.run_no_tools_eval) + answered by two responses: the runner sums their counts + (_aggregate_request_results), splits the sums equally among the + household's rows and repeats the response count on each.""" summed = [a + b for a, b in zip(first, second)] return [ _usage_row(model, "s1", *(count / rows for count in summed), live=2) From b33ec0ae38e71ced95cd9aa4996c28bc2471189f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 15:25:00 +0100 Subject: [PATCH 16/17] State the fill trigger as an empty cost sum (review r4) model_cost_latency invokes the fill when a model's summed total_cost_usd is empty. That covers recorded costs of +inf and -inf, whose sum is NaN, as well as a model with no recorded cost; the docstring named only the second. The response-count comment now says a count column with an empty cell can be a float column: a nullable Int64 column keeps its dtype. Docstring and comment only; the module's AST with docstrings removed is unchanged. Co-Authored-By: Claude Opus 5.5 --- policybench/analysis.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/policybench/analysis.py b/policybench/analysis.py index 555206aa..022469d0 100644 --- a/policybench/analysis.py +++ b/policybench/analysis.py @@ -1551,7 +1551,7 @@ def _override_fallback_cost( # One response, live or replayed: the counts are (1, 0) or (0, 1). A sum # of 1 would also pass (-1, 2) or (0.5, 0.5), which no runner writes. The # counts compare as floats, so a 1.0 (a count column with an empty cell - # elsewhere is a float column) still passes. + # elsewhere can be a float column) still passes. live, replayed = (priced[column].astype(float) for column in RESPONSE_COUNT_COLUMNS) one_response = ((live == 1) & (replayed == 0)) | ((live == 0) & (replayed == 1)) if not one_response.all(): @@ -1587,10 +1587,12 @@ def model_cost_latency( Cost is the run total in USD (matching :func:`usage_summary_by_model`) plus a per-household figure. Latency is the *median* per-household request-time — each household's calls summed, then the median across households — which is - robust to the occasional rate-limit retry that inflates the mean. When no - row of a model records a cost, :func:`_override_fallback_cost` fills it - from ``price_overrides`` in the cases that function lists, and otherwise - the model gets no cost and no ``costUsd`` key. The fill can be invoked + robust to the occasional rate-limit retry that inflates the mean. When a + model's summed ``total_cost_usd`` is empty, :func:`_override_fallback_cost` + fills it from ``price_overrides`` in the cases that function lists, and + otherwise the model gets no cost and no ``costUsd`` key. The sum is empty + when no row records a cost, and also when the recorded costs include both + +inf and -inf, whose sum is NaN. The fill can be invoked for a model whose run had a price for it: a batch cell merged from a response that reported only a prompt count and a repair that reported only a completion count holds both counts and no cost From 05135437c49159f03f660fd427c71e4846d50c16 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 15:29:15 +0100 Subject: [PATCH 17/17] State when costUsd is left out as an empty cost sum (review r4) The require_published_costs docstring and the freeze test's header said model_cost_latency leaves costUsd out when no row of a model records a cost. The trigger is the model's summed cost being empty, which recorded costs of +inf and -inf also produce. Same correction as b33ec0ae. Docstrings only; each file's AST with docstrings removed is unchanged. Co-Authored-By: Claude Opus 5.5 --- scripts/freeze_snapshot.py | 5 +++-- tests/test_freeze_published_costs.py | 11 ++++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/scripts/freeze_snapshot.py b/scripts/freeze_snapshot.py index c4697927..368563af 100644 --- a/scripts/freeze_snapshot.py +++ b/scripts/freeze_snapshot.py @@ -945,8 +945,9 @@ def require_published_costs(country_payload: dict) -> dict[str, float]: """Each no-tools board model's published ``costUsd``; refuse a board that lacks one. - ``analysis.model_cost_latency`` leaves ``costUsd`` out when no row of a - model records a cost and either the model has no price override or + ``analysis.model_cost_latency`` leaves ``costUsd`` out when a model's + summed cost is empty (no row records one, or recorded costs of +inf and + -inf sum to NaN) and either the model has no price override or ``analysis._override_fallback_cost`` returns no cost for its rows. The report's published total sums every board model's cost, and the paper's render asserts that the models with a cost dash are its zero-cost diff --git a/tests/test_freeze_published_costs.py b/tests/test_freeze_published_costs.py index 9ef32f09..6b475912 100644 --- a/tests/test_freeze_published_costs.py +++ b/tests/test_freeze_published_costs.py @@ -1,11 +1,12 @@ """The freeze needs a published cost for every board model. analysis.model_cost_latency leaves costUsd out of a model's dashboard row when -no row of the model records a cost and the fill from its price override -returns none (for example a cache-rate model whose rows sum several -responses, or a Responses-API GPT model). The freeze's report sums every -board model's cost, so freeze_snapshot.require_published_costs names the -models without one and stops. +the model's summed cost is empty (no row records one, or recorded costs of ++inf and -inf sum to NaN) and the fill from its price override returns none +(for example a cache-rate model whose rows sum several responses, or a +Responses-API GPT model). The freeze's report sums every board model's cost, +so freeze_snapshot.require_published_costs names the models without one and +stops. """ from __future__ import annotations