diff --git a/policybench/analysis.py b/policybench/analysis.py index 8154c38f..022469d0 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,127 @@ 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, 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 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 + 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. 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 + 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 (``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 + 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 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 + 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. 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 + # 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: + 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 + # 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 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(): + return None + + def recorded(column: str) -> pd.Series: + if column not in counts: + return pd.Series(0.0, index=priced.index) + 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) + cache_write = np.minimum(recorded("cache_write_prompt_tokens"), row_prompt - cached) + # 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 ( + 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 + + def model_cost_latency( predictions: pd.DataFrame, price_overrides: dict[str, dict[str, float]] | None = None, @@ -1466,12 +1588,16 @@ 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 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. + 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 + (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 {} @@ -1483,28 +1609,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..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 and output 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/scripts/effort_sensitivity.py b/scripts/effort_sensitivity.py index 8e85dfc9..7ab985ec 100644 --- a/scripts/effort_sensitivity.py +++ b/scripts/effort_sensitivity.py @@ -308,39 +308,87 @@ 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 _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) + + +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 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) + + 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] - 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() + # model_cost_latency leaves out a cost it cannot establish (and a latency + # 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 + # 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 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") parsed = rows["prediction"].notna() return { "households": int(rows["scenario_id"].nunique()), "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"]), - "output_tokens": int(round(float(rows["completion_tokens"].sum()))), - "answered_calls": int(live_calls.sum()) if recorded else None, + "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": ( + 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()), } @@ -353,15 +401,23 @@ def check_board(inputs: ScoringInputs, board: pd.DataFrame) -> dict: for model in BOARD_MODELS: row = stats[model] 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: 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["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"]), + "exact": (scores[model]["exact"], row.get("exact")), + "within1pct": (scores[model]["within1pct"], row.get("within1pct")), + "score": (scores[model]["score"], row.get("score")), + "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"], - row["latencySeconds"], + row.get("latencySeconds"), ), "n_parsed": ( int( @@ -372,7 +428,7 @@ def check_board(inputs: ScoringInputs, board: pd.DataFrame) -> dict: .notna() .sum() ), - row["nParsed"], + row.get("nParsed"), ), } return report @@ -559,8 +615,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, @@ -614,7 +674,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/scripts/freeze_snapshot.py b/scripts/freeze_snapshot.py index 977c5608..368563af 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,60 @@ 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 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 + 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" + ] + + def is_cost(value: object) -> bool: + return ( + isinstance(value, (int, float)) + and not isinstance(value, bool) + and math.isfinite(value) + and value >= 0 + ) + + 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"]) + ) + 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 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 and token counts 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} + + def regenerate_analysis(dest_dir: Path) -> None: """Run the analyze CLI into ``dest_dir`` and add the impact summary. @@ -994,12 +1049,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 +2111,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_cost_latency.py b/tests/test_cost_latency.py index 67a2d027..e173d49a 100644 --- a/tests/test_cost_latency.py +++ b/tests/test_cost_latency.py @@ -2,18 +2,36 @@ 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; -- 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; +- 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 + 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, + 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 + 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 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 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 reconstruction tests check that a filled cache-rate cost is what +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. """ import json @@ -26,8 +44,8 @@ from hypothesis import given, settings from hypothesis import strategies as st -from policybench.analysis import model_cost_latency -from policybench.config import PRICE_OVERRIDES_PER_1M +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 ROOT = Path(__file__).resolve().parents[1] @@ -195,7 +213,552 @@ 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, 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, + } + + +@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 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)], + ) + 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_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 + 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) + + +@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 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) + 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), + # 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: 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( + [ + _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 "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_counts_read_back_as_floats_are_priced(): + """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( + [ + _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 + + 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_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" + 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 + 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(): + """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 response has its usage on one row here, so + 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, + 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] + 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 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( + 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 +773,28 @@ 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)), + # -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) 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 +806,41 @@ 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 - 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 + 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 + 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"]) not in {(1.0, 0.0), (0.0, 1.0)} + for r in priced + ): + return None + + def written_count(row): + if "cache_write" not in override: + return 0.0 + return max(row["cache_write_prompt_tokens"], 0.0) + + cached = [ + min(max(r["cached_prompt_tokens"], 0.0), r["prompt_tokens"]) for r in priced + ] + written = [ + min(written_count(r), r["prompt_tokens"] - c) for r, c in zip(priced, cached) + ] + 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"]) + + math.fsum(written) * override.get("cache_write", override["input"]) + + completion * override["output"] + ) / 1e6 @settings(max_examples=300, deadline=None) @@ -247,13 +849,20 @@ def _reference_cost(rows: list[dict], override: dict | None) -> float | None: 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, @@ -263,6 +872,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 ] @@ -275,13 +896,14 @@ 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: 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 ) @@ -292,12 +914,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 +934,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 +969,38 @@ 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): + """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 + 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 diff --git a/tests/test_effort_sensitivity_run_stats.py b/tests/test_effort_sensitivity_run_stats.py new file mode 100644 index 00000000..49631cee --- /dev/null +++ b/tests/test_effort_sensitivity_run_stats.py @@ -0,0 +1,332 @@ +"""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 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 +import dataclasses +import importlib.util +import json +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_a_figure_one_side_lacks_as_a_mismatch(script): + """--check-board compares each recomputed figure with the frozen one; a + 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) + + +@pytest.mark.parametrize( + ("key", "field"), + [ + ("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): + """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] + 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, + 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) + + +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.""" + 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.""" + 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_a_failed_household_keeps_the_runs_tokens_and_time_window(run_stats): + """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 = [ + "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["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): + """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 diff --git a/tests/test_freeze_published_costs.py b/tests/test_freeze_published_costs.py new file mode 100644 index 00000000..6b475912 --- /dev/null +++ b/tests/test_freeze_published_costs.py @@ -0,0 +1,185 @@ +"""The freeze needs a published cost for every board model. + +analysis.model_cost_latency leaves costUsd out of a model's dashboard row when +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 + +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("infinite", costUsd=math.inf), + _stat("negative", costUsd=-1.0), + _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) + # 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(): + """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 + 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), + _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..b85ab017 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,30 @@ 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, +): + """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( + { + "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'