From 462cc639a20ab60298ab44663ff1fb45ae5610e0 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 01:33:14 +0100 Subject: [PATCH 01/12] Give each repeat of eval-no-tools-repeated its own disk-cache namespace The command turns the LiteLLM disk cache on, and every repeat builds the same requests, so repeats 2..N got repeat 1's responses back from the cache and the run reported no run-to-run variation. Each repeat now runs under its own namespace (repeat=run_000, ...): it never replays another repeat's answers, and a rerun on the same cache replays its own. The command prints, after each repeat, how many responses came from the provider and how many from the cache. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 + policybench/eval_no_tools.py | 80 +++- tests/test_repeated_runs_sample_fresh.py | 510 +++++++++++++++++++++++ 3 files changed, 592 insertions(+), 9 deletions(-) create mode 100644 tests/test_repeated_runs_sample_fresh.py diff --git a/README.md b/README.md index ae22f820..8de5fcb3 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,17 @@ policybench eval-no-tools-repeated -n 100 --seed 42 --repeats 3 -o results/local policybench analyze --runs-dir results/local/no_tools/runs --output-dir results/local/analysis ``` +Each repeat asks the models again. The command keeps the LiteLLM disk cache on, +but each repeat looks up and stores its answers under its own cache namespace +(`repeat=run_000`, `repeat=run_001`, ...), so no repeat gets another repeat's +answers, or those of an `eval-no-tools` run. Run the command again with the +same cache directory and no repeat it already ran asks again: into the same +output directory it resumes from the CSVs, and into a new one each repeat +replays its own answers from the cache, while a higher `--repeats` asks only +for the new repeats. After each repeat the command prints how many responses +came from the provider and how many from the cache. To draw a new set of +repeats instead, point `POLICYBENCH_CACHE_DIR` at a new directory. + `policybench reference-outputs` writes PolicyEngine reference outputs, not administrative truth. It also writes `results/local/scenarios.csv`, and the eval commands reuse that manifest by default instead of regenerating households from diff --git a/policybench/eval_no_tools.py b/policybench/eval_no_tools.py index 0e876bb1..7657ce3e 100644 --- a/policybench/eval_no_tools.py +++ b/policybench/eval_no_tools.py @@ -1,5 +1,6 @@ """AI-alone evaluation using LiteLLM (no tools provided).""" +import contextlib import functools import hashlib import json @@ -4301,6 +4302,56 @@ def run_no_tools_single_output_eval( return df +def _repeat_cache_namespace(base: str | None, run_id: str) -> str: + """The disk-cache namespace of one repeat of a repeated run.""" + return f"{base}:repeat={run_id}" if base else f"repeat={run_id}" + + +@contextlib.contextmanager +def _own_cache_namespace(run_id: str): + """Give one repeat its own LiteLLM disk-cache namespace while it runs. + + Every repeat builds the same requests, and LiteLLM keys its disk cache on + the request, so without this the cache the CLI turns on answers repeats + 2..N with repeat 1's responses and the run reports no run-to-run + variation. LiteLLM prefixes every key it computes, for the lookup and for + the store, with the cache's ``namespace`` attribute, read on each call + (``Cache._add_namespace_to_cache_key`` in LiteLLM 1.95.0). So under its own + namespace a repeat never finds another repeat's answers, or those of an + ``eval-no-tools`` run, and a rerun of the same repeat on the same cache + replays that repeat's own answers. + + A request's own ``cache`` namespace outranks the attribute. The one the + harness sets, for an effort override (``_effort_cache_namespace``), is + built from the attribute when the request is built, so it keeps the + repeat. Without a cache this does nothing. + """ + cache = litellm.cache + if cache is None: + yield + return + base = cache.namespace + cache.namespace = _repeat_cache_namespace(base, run_id) + try: + yield + finally: + cache.namespace = base + + +def _response_sources(frame: pd.DataFrame) -> tuple[int, int]: + """Responses a run's rows got from the provider and from the disk cache.""" + if frame.empty or not {"call_id", "live_calls", "cache_hit_calls"} <= set( + frame.columns + ): + return 0, 0 + # Every row of one request group carries the group's counts. + calls = frame.drop_duplicates("call_id") + return tuple( + int(pd.to_numeric(calls[column], errors="coerce").fillna(0).sum()) + for column in ("live_calls", "cache_hit_calls") + ) + + def run_repeated_no_tools_eval( scenarios: list[Scenario], repeats: int, @@ -4310,7 +4361,12 @@ def run_repeated_no_tools_eval( include_explanations: bool = True, single_output: bool = False, ) -> pd.DataFrame: - """Run repeated AI-alone evaluations, saving one artifact per run.""" + """Run repeated AI-alone evaluations, saving one artifact per run. + + Each repeat asks the models again: it runs under its own disk-cache + namespace (``_own_cache_namespace``), so it never replays another + repeat's responses, and a rerun on the same cache replays its own. + """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True) @@ -4320,18 +4376,24 @@ def run_repeated_no_tools_eval( run_output_path = output_path / f"{run_id}.csv" print(f"=== Starting {run_id} ===") runner = run_no_tools_single_output_eval if single_output else run_no_tools_eval - frame = runner( - scenarios, - models=models, - programs=programs, - output_path=str(run_output_path), - run_id=run_id, - include_explanations=include_explanations, - ) + with _own_cache_namespace(run_id): + frame = runner( + scenarios, + models=models, + programs=programs, + output_path=str(run_output_path), + run_id=run_id, + include_explanations=include_explanations, + ) if "run_id" not in frame.columns: frame = frame.copy() frame["run_id"] = run_id frame.to_csv(run_output_path, index=False) + live, replayed = _response_sources(frame) + print( + f"{run_id}: {live} responses from the provider, " + f"{replayed} replayed from the disk cache" + ) frames.append(frame) if not frames: diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py new file mode 100644 index 00000000..a39eceb0 --- /dev/null +++ b/tests/test_repeated_runs_sample_fresh.py @@ -0,0 +1,510 @@ +"""Each repeat of a repeated run asks the models again. + +``policybench eval-no-tools-repeated`` turns the LiteLLM disk cache on, and +every repeat builds the same requests. LiteLLM keys the cache on the request, +so repeats 2..N used to get repeat 1's responses back from the cache and the +run reported no run-to-run variation. Each repeat now runs under its own +cache namespace (``_own_cache_namespace``). + +These tests run the harness's repeated path through LiteLLM's real request +path and the harness's real disk cache (``enable_cache`` in a temporary +directory). Only the wire is replaced: ``httpx.Client.send`` answers from this +file with a value that names the call, and a socket connection fails the test. +""" + +from __future__ import annotations + +import json +import socket +from types import SimpleNamespace + +import httpx +import litellm +import pandas as pd +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +import policybench.eval_no_tools as eval_no_tools +from policybench.cache import enable_cache +from policybench.config import MODELS +from policybench.eval_no_tools import ( + REASONING_EFFORT_OVERRIDE_ENV, + _answer_contract_for_model, + _repeat_cache_namespace, + _uses_responses_api, + run_repeated_no_tools_eval, +) +from policybench.model_cards import MODEL_CARDS +from policybench.scenarios import Person, Scenario + +SCENARIO = Scenario( + id="repeat_household", + state="CA", + filing_status="single", + adults=[Person(name="adult1", age=35, employment_income=18_000.0)], + year=2026, +) +VARIABLES = ["snap", "ssi"] +OPUS = "claude-opus-5-5" + +PROVIDER_KEY_VARIABLES = ( + "ANTHROPIC_API_KEY", + "DEEPSEEK_API_KEY", + "GEMINI_API_KEY", + "GOOGLE_API_KEY", + "OPENAI_API_KEY", + "OPENROUTER_API_KEY", + "XAI_API_KEY", +) +SENSITIVITY_VARIABLES = ( + REASONING_EFFORT_OVERRIDE_ENV, + "LITELLM_DROP_PARAMS", + "POLICYBENCH_CHUNK_OVERRIDE", + "POLICYBENCH_CONTRACT_OVERRIDE", + "POLICYBENCH_TOOL_CHOICE", +) + + +def _group(model_id: str) -> str: + """The provider path and answer contract a model's requests take.""" + if _uses_responses_api(model_id): + provider = "openai responses" + elif model_id.startswith("claude-"): + provider = "anthropic" + else: + provider = model_id.split("/", 1)[0] + return f"{provider} / {_answer_contract_for_model(model_id, env={})}" + + +def _name_of(model_id: str) -> str: + names = {card.litellm_id: name for name, card in MODEL_CARDS.items()} + names.update({litellm_id: name for name, litellm_id in MODELS.items()}) + return names[model_id] + + +GROUPS: dict[str, list[str]] = {} +for _model_id in sorted(card.litellm_id for card in MODEL_CARDS.values()): + GROUPS.setdefault(_group(_model_id), []).append(_model_id) +# One card per provider path and answer contract; a new one joins without an +# edit here. +REPRESENTATIVES = [ids[0] for _, ids in sorted(GROUPS.items())] +# LiteLLM rewrites a gemini/ tool request's schema between its cache lookup +# and its store, so on main a rebuilt gemini/ tool request never replays from +# the cache, repeat or not (the cache fix on branch +# fix/cache-replay-mutated-request). The replay tests leave that group out. +REPLAYING = [ + model_id for model_id in REPRESENTATIVES if _group(model_id) != "gemini / tool" +] + + +def _answer(call: int) -> dict: + value = 1000 + call + return { + "outputs": { + variable: {"value": value, "explanation": f"Call {call}. value = {value}"} + for variable in VARIABLES + } + } + + +def _tool_name(body: dict) -> str | None: + for tool in body.get("tools") or []: + declarations = tool.get("functionDeclarations") or tool.get( + "function_declarations" + ) + if declarations: + return declarations[0]["name"] + if "function" in tool: + return tool["function"]["name"] + if "name" in tool: + return tool["name"] + return None + + +def _canned_answer(path: str, body: dict, call: int) -> dict: + """A provider-shaped answer whose values name the call that made it.""" + tool = _tool_name(body) + arguments = _answer(call) + text = json.dumps(arguments) + if ":generateContent" in path: + part = ( + {"functionCall": {"name": tool, "args": arguments}} + if tool + else {"text": text} + ) + return { + "candidates": [ + { + "content": {"role": "model", "parts": [part]}, + "finishReason": "STOP", + "index": 0, + } + ], + "usageMetadata": { + "promptTokenCount": 10, + "candidatesTokenCount": 5, + "totalTokenCount": 15, + }, + "modelVersion": "stub", + "responseId": f"stub-{call}", + } + if path.endswith("/messages"): + content = ( + [ + { + "type": "tool_use", + "id": f"toolu_{call}", + "name": tool, + "input": arguments, + } + ] + if tool + else [{"type": "text", "text": text}] + ) + return { + "id": f"stub-{call}", + "type": "message", + "role": "assistant", + "model": body.get("model", "stub"), + "content": content, + "stop_reason": "tool_use" if tool else "end_turn", + "stop_sequence": None, + "usage": {"input_tokens": 10, "output_tokens": 5}, + } + if path.endswith("/responses"): + return { + "id": f"stub-{call}", + "object": "response", + "created_at": 1_795_000_000, + "status": "completed", + "model": body.get("model", "stub"), + "output": [ + { + "type": "function_call", + "id": f"fc_{call}", + "call_id": f"call_{call}", + "name": tool, + "arguments": text, + "status": "completed", + } + ], + "parallel_tool_calls": True, + "tool_choice": "auto", + "tools": [], + "error": None, + "incomplete_details": None, + "instructions": None, + "metadata": {}, + "temperature": 1.0, + "top_p": 1.0, + "truncation": "disabled", + "text": {"format": {"type": "text"}}, + "usage": { + "input_tokens": 10, + "output_tokens": 5, + "total_tokens": 15, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens_details": {"reasoning_tokens": 0}, + }, + } + if path.endswith("/chat/completions"): + message = ( + { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": f"call_{call}", + "type": "function", + "function": {"name": tool, "arguments": text}, + } + ], + } + if tool + else {"role": "assistant", "content": text} + ) + return { + "id": f"stub-{call}", + "object": "chat.completion", + "created": 1_795_000_000, + "model": body.get("model", "stub"), + "choices": [ + { + "index": 0, + "message": message, + "finish_reason": "tool_calls" if tool else "stop", + } + ], + "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, + } + raise AssertionError(f"the stub has no answer for the path {path}") + + +@pytest.fixture(autouse=True) +def offline(monkeypatch): + """No key, no socket, no sensitivity knob, one attempt per request.""" + + def refuse(*_args, **_kwargs): + raise AssertionError("a test tried to open a socket") + + monkeypatch.setattr(socket.socket, "connect", refuse) + monkeypatch.setattr(socket, "create_connection", refuse) + for name in PROVIDER_KEY_VARIABLES: + monkeypatch.setenv(name, "test-value-not-a-key") + for name in SENSITIVITY_VARIABLES: + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(eval_no_tools, "_PROCESS_REASONING_EFFORT_OVERRIDE", []) + monkeypatch.setattr(eval_no_tools, "MAX_ATTEMPTS", 1) + monkeypatch.setattr(litellm, "drop_params", False) + # Turning the cache on registers LiteLLM callbacks; give them back too. + for name in ("input_callback", "success_callback", "_async_success_callback"): + monkeypatch.setattr(litellm, name, list(getattr(litellm, name))) + monkeypatch.setattr(litellm, "cache", None) + + +@pytest.fixture +def wire(monkeypatch) -> list[dict]: + """The requests LiteLLM put on the wire, each answered from this file.""" + sent: list[dict] = [] + + def send(self, request, **_kwargs): + body = json.loads(request.content) + sent.append({"path": request.url.path, "body": body}) + return httpx.Response( + 200, + json=_canned_answer(request.url.path, body, len(sent)), + request=request, + ) + + def no_async_send(self, request, **_kwargs): + raise AssertionError("the harness sends no asynchronous request") + + monkeypatch.setattr(httpx.Client, "send", send) + monkeypatch.setattr(httpx.AsyncClient, "send", no_async_send) + return sent + + +@pytest.fixture +def disk_cache(tmp_path): + """The harness's disk cache, on in a temporary directory.""" + enable_cache(str(tmp_path / "cache")) + return litellm.cache + + +@pytest.fixture +def sent_per_repeat(monkeypatch, wire) -> dict[str, int]: + """How many requests each repeat put on the wire, by run id.""" + counts: dict[str, int] = {} + runners = { + name: getattr(eval_no_tools, name) + for name in ("run_no_tools_eval", "run_no_tools_single_output_eval") + } + + def counting(runner): + def run(*args, **kwargs): + before = len(wire) + try: + return runner(*args, **kwargs) + finally: + counts[kwargs["run_id"]] = ( + counts.get(kwargs["run_id"], 0) + len(wire) - before + ) + + return run + + for name, runner in runners.items(): + monkeypatch.setattr(eval_no_tools, name, counting(runner)) + return counts + + +def _run(model_id: str, output_dir, repeats: int = 2, **kwargs) -> pd.DataFrame: + return run_repeated_no_tools_eval( + [SCENARIO], + repeats=repeats, + output_dir=str(output_dir), + models={_name_of(model_id): model_id}, + programs=VARIABLES, + **kwargs, + ) + + +def _calls(frame: pd.DataFrame, run_id: str) -> pd.DataFrame: + return frame[frame["run_id"] == run_id].drop_duplicates("call_id") + + +def _raw(frame: pd.DataFrame, run_id: str) -> list[str]: + return frame[frame["run_id"] == run_id]["raw_response"].tolist() + + +@pytest.mark.parametrize("model_id", REPRESENTATIVES) +def test_repeat_2_asks_again_when_repeat_1_is_cached( + model_id, disk_cache, sent_per_repeat, tmp_path +): + frame = _run(model_id, tmp_path / "runs") + + sent = sent_per_repeat + assert sent["run_000"] > 0 + assert sent["run_001"] == sent["run_000"], ( + "repeat 2 got repeat 1's responses from the disk cache" + ) + second = _calls(frame, "run_001") + assert second["cache_hit_calls"].sum() == 0 + assert second["live_calls"].sum() == sent["run_001"] + assert _raw(frame, "run_001") != _raw(frame, "run_000") + + +def test_a_single_output_repeat_asks_again(disk_cache, sent_per_repeat, tmp_path): + model_id = REPLAYING[0] + + _run(model_id, tmp_path / "runs", single_output=True) + + assert sent_per_repeat["run_000"] > 0 + assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] + + +@pytest.mark.parametrize("model_id", REPLAYING) +def test_a_rerun_replays_each_repeats_own_responses( + model_id, disk_cache, sent_per_repeat, wire, tmp_path, capsys +): + first = _run(model_id, tmp_path / "first") + one_repeat = sent_per_repeat["run_000"] + sent_before = len(wire) + sent_per_repeat.clear() + capsys.readouterr() + + # A new output directory, so no CSV resume answers for the cache; one + # more repeat than before. + again = _run(model_id, tmp_path / "again", repeats=3) + + assert sent_per_repeat == {"run_000": 0, "run_001": 0, "run_002": one_repeat} + assert len(wire) - sent_before == one_repeat + for run_id in ("run_000", "run_001"): + assert _raw(again, run_id) == _raw(first, run_id) + replayed = _calls(again, run_id) + assert replayed["live_calls"].sum() == 0 + assert replayed["cache_hit_calls"].sum() == one_repeat + assert _raw(again, "run_001") != _raw(again, "run_000") + assert _raw(again, "run_002") not in ( + _raw(again, "run_000"), + _raw(again, "run_001"), + ) + out = capsys.readouterr().out + assert ( + f"run_001: 0 responses from the provider, {one_repeat} replayed from " + "the disk cache" + ) in out + assert f"run_002: {one_repeat} responses from the provider, 0 replayed" in out + + +def test_without_a_cache_every_repeat_asks(sent_per_repeat, tmp_path): + assert litellm.cache is None + + _run(REPLAYING[0], tmp_path / "runs") + + assert sent_per_repeat["run_000"] > 0 + assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] + + +def test_an_effort_override_keeps_the_repeat_namespace( + disk_cache, sent_per_repeat, tmp_path, monkeypatch +): + """The override's own request namespace outranks the cache's, so it has + to carry the repeat.""" + monkeypatch.setenv(REASONING_EFFORT_OVERRIDE_ENV, f"{OPUS}=high") + stored: list[str] = [] + put = disk_cache.cache.set_cache + + def set_cache(key, value, **kwargs): + stored.append(key) + return put(key, value, **kwargs) + + monkeypatch.setattr(disk_cache.cache, "set_cache", set_cache) + base = disk_cache.namespace + + _run(OPUS, tmp_path / "runs") + + assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] > 0 + for run_id in ("run_000", "run_001"): + prefix = f"{_repeat_cache_namespace(base, run_id)}:{OPUS}:effort=high:" + assert any(key.startswith(prefix) for key in stored), run_id + + +def test_the_cache_namespace_comes_back_when_a_repeat_fails( + disk_cache, monkeypatch, tmp_path +): + base = disk_cache.namespace + seen: list[str] = [] + + def failing(*_args, run_id, **_kwargs): + seen.append(litellm.cache.namespace) + raise RuntimeError("provider down") + + monkeypatch.setattr(eval_no_tools, "run_no_tools_eval", failing) + + with pytest.raises(RuntimeError, match="provider down"): + _run(REPLAYING[0], tmp_path / "runs") + + assert seen == [_repeat_cache_namespace(base, "run_000")] + assert litellm.cache.namespace == base + + +@settings( + max_examples=60, + deadline=None, + # The autouse offline fixture holds for every example. + suppress_health_check=[HealthCheck.function_scoped_fixture], +) +@given( + base=st.one_of(st.none(), st.text(min_size=1, max_size=40)), + repeats=st.integers(min_value=1, max_value=6), + fail_at=st.one_of(st.none(), st.integers(min_value=0, max_value=5)), +) +def test_repeats_get_distinct_namespaces_and_the_base_comes_back( + base, repeats, fail_at, tmp_path_factory +): + """For any base namespace, repeat count and failing repeat: each repeat + that runs sees its own namespace, built on the base, and the cache's + namespace is the base again afterwards.""" + output_dir = tmp_path_factory.mktemp("runs") + cache = SimpleNamespace(namespace=base) + seen: dict[str, str] = {} + + def runner(*_args, run_id, **_kwargs): + seen[run_id] = litellm.cache.namespace + if fail_at is not None and int(run_id.split("_")[1]) == fail_at: + raise RuntimeError("provider down") + return pd.DataFrame( + [ + { + "run_id": run_id, + "call_id": run_id, + "live_calls": 1, + "cache_hit_calls": 0, + } + ] + ) + + saved = (litellm.cache, eval_no_tools.run_no_tools_eval) + litellm.cache, eval_no_tools.run_no_tools_eval = cache, runner + try: + try: + run_repeated_no_tools_eval( + [SCENARIO], repeats=repeats, output_dir=str(output_dir) + ) + except RuntimeError: + assert fail_at is not None and fail_at < repeats + else: + assert fail_at is None or fail_at >= repeats + assert cache.namespace == base + finally: + litellm.cache, eval_no_tools.run_no_tools_eval = saved + + ran = min(repeats, repeats if fail_at is None else fail_at + 1) + assert list(seen) == [f"run_{index:03d}" for index in range(ran)] + assert len(set(seen.values())) == ran + for run_id, namespace in seen.items(): + assert namespace == _repeat_cache_namespace(base, run_id) + assert namespace.endswith(f"repeat={run_id}") + if base: + assert namespace.startswith(f"{base}:") From b08103a1888289fc430c4685d3c4e0b00f5d94f7 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:34:44 +0100 Subject: [PATCH 02/12] Pin the CLI path and the no-cross-replay invariant; drop the new import - Write the namespace switch as a small class, so this change adds no import line where the open cache fix (#275) adds one. - Test the command as the CLI runs it (cache on, two repeats), and that across a run and a rerun no repeat returns another repeat's responses, for every provider path and contract. - README and docstrings: a rerun replays the answers the cache finds under the repeat's namespace. Co-Authored-By: Claude Fable 5.2 --- README.md | 11 ++-- policybench/cli.py | 4 +- policybench/eval_no_tools.py | 37 ++++++------ tests/test_repeated_runs_sample_fresh.py | 72 ++++++++++++++++++++++-- 4 files changed, 97 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 8de5fcb3..2fbfdd12 100644 --- a/README.md +++ b/README.md @@ -157,12 +157,13 @@ Each repeat asks the models again. The command keeps the LiteLLM disk cache on, but each repeat looks up and stores its answers under its own cache namespace (`repeat=run_000`, `repeat=run_001`, ...), so no repeat gets another repeat's answers, or those of an `eval-no-tools` run. Run the command again with the -same cache directory and no repeat it already ran asks again: into the same +same cache directory and it reuses what each repeat already has: into the same output directory it resumes from the CSVs, and into a new one each repeat -replays its own answers from the cache, while a higher `--repeats` asks only -for the new repeats. After each repeat the command prints how many responses -came from the provider and how many from the cache. To draw a new set of -repeats instead, point `POLICYBENCH_CACHE_DIR` at a new directory. +replays the answers the cache finds under its own namespace, so a higher +`--repeats` asks only for the new repeats. After each repeat the command prints +how many of its responses came from the provider and how many from the cache. +To draw a new set of repeats instead, point `POLICYBENCH_CACHE_DIR` at a new +directory. `policybench reference-outputs` writes PolicyEngine reference outputs, not administrative truth. It also writes `results/local/scenarios.csv`, and the eval diff --git a/policybench/cli.py b/policybench/cli.py index 6b3b7eb4..0c1a380e 100644 --- a/policybench/cli.py +++ b/policybench/cli.py @@ -1122,7 +1122,9 @@ def main(): # Enable disk cache for ordinary eval calls. Contract-failure retry/repair # commands bypass cache by default, otherwise they can replay the same bad - # provider response indefinitely. + # provider response indefinitely. eval-no-tools-repeated gives each repeat + # its own cache namespace (run_repeated_no_tools_eval), so a repeat never + # gets another repeat's responses. if args.command in { "eval-no-tools", "eval-no-tools-repeated", diff --git a/policybench/eval_no_tools.py b/policybench/eval_no_tools.py index 7657ce3e..b5bafa2d 100644 --- a/policybench/eval_no_tools.py +++ b/policybench/eval_no_tools.py @@ -1,6 +1,5 @@ """AI-alone evaluation using LiteLLM (no tools provided).""" -import contextlib import functools import hashlib import json @@ -4307,8 +4306,7 @@ def _repeat_cache_namespace(base: str | None, run_id: str) -> str: return f"{base}:repeat={run_id}" if base else f"repeat={run_id}" -@contextlib.contextmanager -def _own_cache_namespace(run_id: str): +class _OwnCacheNamespace: """Give one repeat its own LiteLLM disk-cache namespace while it runs. Every repeat builds the same requests, and LiteLLM keys its disk cache on @@ -4319,23 +4317,28 @@ def _own_cache_namespace(run_id: str): (``Cache._add_namespace_to_cache_key`` in LiteLLM 1.95.0). So under its own namespace a repeat never finds another repeat's answers, or those of an ``eval-no-tools`` run, and a rerun of the same repeat on the same cache - replays that repeat's own answers. + looks up the answers that repeat stored. A request's own ``cache`` namespace outranks the attribute. The one the harness sets, for an effort override (``_effort_cache_namespace``), is built from the attribute when the request is built, so it keeps the repeat. Without a cache this does nothing. """ - cache = litellm.cache - if cache is None: - yield - return - base = cache.namespace - cache.namespace = _repeat_cache_namespace(base, run_id) - try: - yield - finally: - cache.namespace = base + + def __init__(self, run_id: str) -> None: + self._run_id = run_id + self._cache = None + self._base: str | None = None + + def __enter__(self) -> None: + self._cache = litellm.cache + if self._cache is not None: + self._base = self._cache.namespace + self._cache.namespace = _repeat_cache_namespace(self._base, self._run_id) + + def __exit__(self, *_exc) -> None: + if self._cache is not None: + self._cache.namespace = self._base def _response_sources(frame: pd.DataFrame) -> tuple[int, int]: @@ -4364,8 +4367,8 @@ def run_repeated_no_tools_eval( """Run repeated AI-alone evaluations, saving one artifact per run. Each repeat asks the models again: it runs under its own disk-cache - namespace (``_own_cache_namespace``), so it never replays another - repeat's responses, and a rerun on the same cache replays its own. + namespace (``_OwnCacheNamespace``), so it never replays another + repeat's responses, and a rerun on the same cache finds only its own. """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True) @@ -4376,7 +4379,7 @@ def run_repeated_no_tools_eval( run_output_path = output_path / f"{run_id}.csv" print(f"=== Starting {run_id} ===") runner = run_no_tools_single_output_eval if single_output else run_no_tools_eval - with _own_cache_namespace(run_id): + with _OwnCacheNamespace(run_id): frame = runner( scenarios, models=models, diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index a39eceb0..076b05fb 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -4,7 +4,7 @@ every repeat builds the same requests. LiteLLM keys the cache on the request, so repeats 2..N used to get repeat 1's responses back from the cache and the run reported no run-to-run variation. Each repeat now runs under its own -cache namespace (``_own_cache_namespace``). +cache namespace (``_OwnCacheNamespace``). These tests run the harness's repeated path through LiteLLM's real request path and the harness's real disk cache (``enable_cache`` in a temporary @@ -90,9 +90,9 @@ def _name_of(model_id: str) -> str: # edit here. REPRESENTATIVES = [ids[0] for _, ids in sorted(GROUPS.items())] # LiteLLM rewrites a gemini/ tool request's schema between its cache lookup -# and its store, so on main a rebuilt gemini/ tool request never replays from -# the cache, repeat or not (the cache fix on branch -# fix/cache-replay-mutated-request). The replay tests leave that group out. +# and its store, so a rebuilt gemini/ tool request never finds its stored +# answer, repeat or not, until the harness pins the cache key. The tests that +# need a replay leave that group out; the others cover it. REPLAYING = [ model_id for model_id in REPRESENTATIVES if _group(model_id) != "gemini / tool" ] @@ -397,6 +397,70 @@ def test_a_rerun_replays_each_repeats_own_responses( assert f"run_002: {one_repeat} responses from the provider, 0 replayed" in out +@pytest.mark.parametrize("model_id", REPRESENTATIVES) +def test_no_repeat_ever_returns_another_repeats_responses( + model_id, disk_cache, wire, tmp_path +): + """Across a run and a rerun on the same cache, an answer only ever comes + back under the run id that first got it.""" + first = _run(model_id, tmp_path / "first") + again = _run(model_id, tmp_path / "again", repeats=3) + + answers = { + (label, run_id): _raw(frame, run_id) + for label, frame in (("first", first), ("again", again)) + for run_id in sorted(set(frame["run_id"])) + } + assert len(answers) == 5 + assert all("value" in text for raw in answers.values() for text in raw) + for (label, run_id), raw in answers.items(): + for (other_label, other_id), other in answers.items(): + if other_id != run_id: + assert raw != other, ( + f"{label} {run_id} returned {other_label} {other_id}'s responses" + ) + + +def test_the_cli_command_asks_again_on_repeat_2(monkeypatch, sent_per_repeat, tmp_path): + """The command as the CLI runs it: the cache on, then two repeats.""" + from policybench.cli import main + + model_id = REPLAYING[0] + assert MODELS[_name_of(model_id)] == model_id + monkeypatch.setattr("policybench.cache.CACHE_DIR", str(tmp_path / "cache")) + monkeypatch.setattr( + "policybench.cli._load_eval_scenarios", lambda _args: [SCENARIO] + ) + monkeypatch.setattr( + "sys.argv", + [ + "policybench", + "eval-no-tools-repeated", + "--num-scenarios", + "1", + "--repeats", + "2", + "--model", + _name_of(model_id), + "--program", + "snap", + "--program", + "ssi", + "--output-dir", + str(tmp_path / "runs"), + ], + ) + + main() + + assert litellm.cache is not None, "the command no longer turns the cache on" + assert (tmp_path / "cache" / "cache.db").exists() + assert sent_per_repeat["run_000"] > 0 + assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] + second = pd.read_csv(tmp_path / "runs" / "run_001.csv") + assert second["cache_hit_calls"].sum() == 0 + + def test_without_a_cache_every_repeat_asks(sent_per_repeat, tmp_path): assert litellm.cache is None From 4fd9b6c93b164cca597d4876417e6c9b3ac5a381 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 13:43:18 +0100 Subject: [PATCH 03/12] Let the rerun test measure whether a rebuilt request replays The test kept a hand-written list that left the gemini/ tool group out, because on main a rebuilt gemini/ tool request never finds its stored answer. It now measures that per card with two plain runs and asserts that a rerun's repeats replay exactly when a plain rebuilt request does. So the gemini/ tool group joins the strict replay check by itself once the harness pins the cache key (#275), in either merge order. The same test now pins that a repeat never replays an eval-no-tools run's answers. Co-Authored-By: Claude Fable 5.2 --- tests/test_repeated_runs_sample_fresh.py | 86 ++++++++++++++++-------- 1 file changed, 57 insertions(+), 29 deletions(-) diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index 076b05fb..b9fac5aa 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -89,13 +89,6 @@ def _name_of(model_id: str) -> str: # One card per provider path and answer contract; a new one joins without an # edit here. REPRESENTATIVES = [ids[0] for _, ids in sorted(GROUPS.items())] -# LiteLLM rewrites a gemini/ tool request's schema between its cache lookup -# and its store, so a rebuilt gemini/ tool request never finds its stored -# answer, repeat or not, until the harness pins the cache key. The tests that -# need a replay leave that group out; the others cover it. -REPLAYING = [ - model_id for model_id in REPRESENTATIVES if _group(model_id) != "gemini / tool" -] def _answer(call: int) -> dict: @@ -307,9 +300,8 @@ def run(*args, **kwargs): try: return runner(*args, **kwargs) finally: - counts[kwargs["run_id"]] = ( - counts.get(kwargs["run_id"], 0) + len(wire) - before - ) + run_id = kwargs.get("run_id") + counts[run_id] = counts.get(run_id, 0) + len(wire) - before return run @@ -355,20 +347,50 @@ def test_repeat_2_asks_again_when_repeat_1_is_cached( def test_a_single_output_repeat_asks_again(disk_cache, sent_per_repeat, tmp_path): - model_id = REPLAYING[0] - - _run(model_id, tmp_path / "runs", single_output=True) + _run(OPUS, tmp_path / "runs", single_output=True) assert sent_per_repeat["run_000"] > 0 assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] -@pytest.mark.parametrize("model_id", REPLAYING) +def _a_rebuilt_request_replays(model_id: str, output_dir, wire: list) -> bool: + """Whether a plain run's rebuilt requests find their stored answers. + + Two ``eval-no-tools`` runs of the same household on the cache, outside any + repeat. LiteLLM rewrites a ``gemini/`` tool request's schema between its + cache lookup and its store, so until the harness pins the cache key that + one group's rebuilt request never finds its answer, repeat or not. + """ + + def plain(name: str) -> int: + before = len(wire) + eval_no_tools.run_no_tools_eval( + [SCENARIO], + models={_name_of(model_id): model_id}, + programs=VARIABLES, + output_path=str(output_dir / f"{name}.csv"), + ) + return len(wire) - before + + first, second = plain("plain_1"), plain("plain_2") + assert first > 0 and second in (0, first) + return second == 0 + + +@pytest.mark.parametrize("model_id", REPRESENTATIVES) def test_a_rerun_replays_each_repeats_own_responses( model_id, disk_cache, sent_per_repeat, wire, tmp_path, capsys ): + """A rerun's repeats replay exactly when a plain rebuilt request does, and + then each replays its own answers. The namespace scopes the cache; it + does not decide whether the cache can find an answer.""" + replays = _a_rebuilt_request_replays(model_id, tmp_path, wire) + assert replays or _group(model_id) == "gemini / tool" first = _run(model_id, tmp_path / "first") one_repeat = sent_per_repeat["run_000"] + assert sent_per_repeat["run_001"] == one_repeat > 0, ( + "a repeat replayed the plain run's answers, or another repeat's" + ) sent_before = len(wire) sent_per_repeat.clear() capsys.readouterr() @@ -377,24 +399,30 @@ def test_a_rerun_replays_each_repeats_own_responses( # more repeat than before. again = _run(model_id, tmp_path / "again", repeats=3) - assert sent_per_repeat == {"run_000": 0, "run_001": 0, "run_002": one_repeat} - assert len(wire) - sent_before == one_repeat - for run_id in ("run_000", "run_001"): - assert _raw(again, run_id) == _raw(first, run_id) - replayed = _calls(again, run_id) - assert replayed["live_calls"].sum() == 0 - assert replayed["cache_hit_calls"].sum() == one_repeat - assert _raw(again, "run_001") != _raw(again, "run_000") + rerun = 0 if replays else one_repeat + assert sent_per_repeat == { + "run_000": rerun, + "run_001": rerun, + "run_002": one_repeat, + } + assert len(wire) - sent_before == 2 * rerun + one_repeat assert _raw(again, "run_002") not in ( _raw(again, "run_000"), _raw(again, "run_001"), ) + assert _raw(again, "run_001") != _raw(again, "run_000") out = capsys.readouterr().out - assert ( - f"run_001: 0 responses from the provider, {one_repeat} replayed from " - "the disk cache" - ) in out assert f"run_002: {one_repeat} responses from the provider, 0 replayed" in out + if replays: + for run_id in ("run_000", "run_001"): + assert _raw(again, run_id) == _raw(first, run_id) + replayed = _calls(again, run_id) + assert replayed["live_calls"].sum() == 0 + assert replayed["cache_hit_calls"].sum() == one_repeat + assert ( + f"run_001: 0 responses from the provider, {one_repeat} replayed from " + "the disk cache" + ) in out @pytest.mark.parametrize("model_id", REPRESENTATIVES) @@ -425,7 +453,7 @@ def test_the_cli_command_asks_again_on_repeat_2(monkeypatch, sent_per_repeat, tm """The command as the CLI runs it: the cache on, then two repeats.""" from policybench.cli import main - model_id = REPLAYING[0] + model_id = OPUS assert MODELS[_name_of(model_id)] == model_id monkeypatch.setattr("policybench.cache.CACHE_DIR", str(tmp_path / "cache")) monkeypatch.setattr( @@ -464,7 +492,7 @@ def test_the_cli_command_asks_again_on_repeat_2(monkeypatch, sent_per_repeat, tm def test_without_a_cache_every_repeat_asks(sent_per_repeat, tmp_path): assert litellm.cache is None - _run(REPLAYING[0], tmp_path / "runs") + _run(OPUS, tmp_path / "runs") assert sent_per_repeat["run_000"] > 0 assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] @@ -507,7 +535,7 @@ def failing(*_args, run_id, **_kwargs): monkeypatch.setattr(eval_no_tools, "run_no_tools_eval", failing) with pytest.raises(RuntimeError, match="provider down"): - _run(REPLAYING[0], tmp_path / "runs") + _run(OPUS, tmp_path / "runs") assert seen == [_repeat_cache_namespace(base, "run_000")] assert litellm.cache.namespace == base From 5fb50e3242aa48b37863aadb549c6c5c10fdb2df Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 14:16:09 +0100 Subject: [PATCH 04/12] Refuse repeat files that predate the namespaces; make the repeat line and README exact From an in-session review of this pull request: - A directory of run_*.csv files written before this change resumed as if its repeats were independent. The command now writes repeated_run.json beside the run files and refuses a directory that holds repeat files without it. - The per-repeat line says when a repeat resumed from an existing file, whose stored rows its counts include, and counts request groups with no record apart from zero. - README: a rerun asks the model only for answers the cache does not find (a rebuilt gemini/ tool request finds none until #275), and a new independent set needs a new output directory as well as a new cache directory. - Tests: every key a repeat looks up or stores sits under its own namespace, for every provider path and contract, which fails for the gemini/ tool group too when the switch is removed; the namespace's spelling; a rerun on a new cache object; the resume line; the guard. Co-Authored-By: Claude Fable 5.2 --- README.md | 24 ++- policybench/eval_no_tools.py | 74 ++++++++-- tests/test_repeated_runs_sample_fresh.py | 179 ++++++++++++++++++++--- 3 files changed, 234 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 2fbfdd12..489c959b 100644 --- a/README.md +++ b/README.md @@ -156,14 +156,22 @@ policybench analyze --runs-dir results/local/no_tools/runs --output-dir results/ Each repeat asks the models again. The command keeps the LiteLLM disk cache on, but each repeat looks up and stores its answers under its own cache namespace (`repeat=run_000`, `repeat=run_001`, ...), so no repeat gets another repeat's -answers, or those of an `eval-no-tools` run. Run the command again with the -same cache directory and it reuses what each repeat already has: into the same -output directory it resumes from the CSVs, and into a new one each repeat -replays the answers the cache finds under its own namespace, so a higher -`--repeats` asks only for the new repeats. After each repeat the command prints -how many of its responses came from the provider and how many from the cache. -To draw a new set of repeats instead, point `POLICYBENCH_CACHE_DIR` at a new -directory. +answers, or those of an `eval-no-tools` run. + +Running the command again reuses what each repeat already has. Into the same +output directory, a repeat resumes from its CSV: it keeps the households the +file already answers in full and sends requests for the rest. Into a new +output directory with the same cache directory, a repeat looks for its answers +under its own namespace and asks the model only for those the cache does not +find. To draw a new, independent set of repeats, use a new output directory +and point `POLICYBENCH_CACHE_DIR` at a new directory. + +After each repeat the command prints how many provider responses and cache +replays the repeat's rows record, and says when the repeat resumed from an +existing file, whose stored rows those counts include. It writes +`repeated_run.json` beside the run files and refuses an output directory that +holds `run_*.csv` files without it: those repeats shared one cache namespace, +so the repeats after the first may be replays of it. `policybench reference-outputs` writes PolicyEngine reference outputs, not administrative truth. It also writes `results/local/scenarios.csv`, and the eval diff --git a/policybench/eval_no_tools.py b/policybench/eval_no_tools.py index b5bafa2d..f3b7a22a 100644 --- a/policybench/eval_no_tools.py +++ b/policybench/eval_no_tools.py @@ -4317,7 +4317,7 @@ class _OwnCacheNamespace: (``Cache._add_namespace_to_cache_key`` in LiteLLM 1.95.0). So under its own namespace a repeat never finds another repeat's answers, or those of an ``eval-no-tools`` run, and a rerun of the same repeat on the same cache - looks up the answers that repeat stored. + looks under the namespace that repeat stored its answers in. A request's own ``cache`` namespace outranks the attribute. The one the harness sets, for an effort override (``_effort_cache_namespace``), is @@ -4341,17 +4341,50 @@ def __exit__(self, *_exc) -> None: self._cache.namespace = self._base -def _response_sources(frame: pd.DataFrame) -> tuple[int, int]: - """Responses a run's rows got from the provider and from the disk cache.""" - if frame.empty or not {"call_id", "live_calls", "cache_hit_calls"} <= set( - frame.columns - ): - return 0, 0 +def _response_sources(frame: pd.DataFrame) -> tuple[int, int, int]: + """Where the responses behind a run's rows came from. + + Returns the responses the provider answered, the responses the disk cache + replayed, and the request groups whose rows record neither. + """ + if frame.empty or "call_id" not in frame.columns: + return 0, 0, 0 # Every row of one request group carries the group's counts. calls = frame.drop_duplicates("call_id") - return tuple( - int(pd.to_numeric(calls[column], errors="coerce").fillna(0).sum()) - for column in ("live_calls", "cache_hit_calls") + if not {"live_calls", "cache_hit_calls"} <= set(calls.columns): + return 0, 0, len(calls) + live = pd.to_numeric(calls["live_calls"], errors="coerce") + replayed = pd.to_numeric(calls["cache_hit_calls"], errors="coerce") + unrecorded = int((live.isna() | replayed.isna()).sum()) + return int(live.fillna(0).sum()), int(replayed.fillna(0).sum()), unrecorded + + +# Written beside a repeated run's CSVs. Its absence marks a directory whose +# repeat files predate per-repeat cache namespaces. +REPEATED_RUN_MARKER = "repeated_run.json" + + +def _claim_repeat_directory(output_path: Path) -> None: + """Mark ``output_path`` as a repeated run whose repeats sample fresh. + + Refuses a directory that already holds repeat files and no marker: every + repeat in it shared one cache namespace, so its repeats after the first + may be replays of the first, and resuming from them would report no + run-to-run variation. + """ + marker = output_path / REPEATED_RUN_MARKER + if marker.exists(): + return + earlier = sorted(path.name for path in output_path.glob("run_*.csv")) + if earlier: + raise ValueError( + f"{output_path} holds repeat files (first: {earlier[0]}) and no " + f"{REPEATED_RUN_MARKER}, so they were written before each repeat " + "had its own cache namespace and repeats after the first may be " + "replays of it. Use a new output directory." + ) + marker.write_text( + json.dumps({"each_repeat_has_its_own_cache_namespace": True}) + "\n" ) @@ -4369,14 +4402,19 @@ def run_repeated_no_tools_eval( Each repeat asks the models again: it runs under its own disk-cache namespace (``_OwnCacheNamespace``), so it never replays another repeat's responses, and a rerun on the same cache finds only its own. + After each repeat, one line says where its rows' responses came from. + Raises ValueError for a directory of repeat files written before repeats + had their own namespaces (``_claim_repeat_directory``). """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True) + _claim_repeat_directory(output_path) frames = [] for run_index in range(repeats): run_id = f"run_{run_index:03d}" run_output_path = output_path / f"{run_id}.csv" + resumed = run_output_path.exists() print(f"=== Starting {run_id} ===") runner = run_no_tools_single_output_eval if single_output else run_no_tools_eval with _OwnCacheNamespace(run_id): @@ -4392,11 +4430,17 @@ def run_repeated_no_tools_eval( frame = frame.copy() frame["run_id"] = run_id frame.to_csv(run_output_path, index=False) - live, replayed = _response_sources(frame) - print( - f"{run_id}: {live} responses from the provider, " - f"{replayed} replayed from the disk cache" - ) + live, replayed, unrecorded = _response_sources(frame) + sources = f"{run_id}: provider responses {live}, cache replays {replayed}" + if unrecorded: + sources += f", request groups with no record {unrecorded}" + if resumed: + # The runner keeps the file's complete rows and sends nothing for + # them, so the counts are what those rows recorded when written. + sources += ( + f" (resumed from {run_output_path.name}: counts include its rows)" + ) + print(sources) frames.append(frame) if not frames: diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index b9fac5aa..93899da7 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -6,15 +6,21 @@ run reported no run-to-run variation. Each repeat now runs under its own cache namespace (``_OwnCacheNamespace``). -These tests run the harness's repeated path through LiteLLM's real request -path and the harness's real disk cache (``enable_cache`` in a temporary -directory). Only the wire is replaced: ``httpx.Client.send`` answers from this -file with a value that names the call, and a socket connection fails the test. +The tests that send requests run the harness's repeated path through LiteLLM's +real request path and the harness's real disk cache (``enable_cache`` in a +temporary directory). They replace only the wire: ``httpx.Client.send`` +answers from this file with a value that names the call, and a socket +connection fails the test. Those tests also count requests per repeat and +record cache keys by wrapping the runner and the disk cache. Three tests send +nothing: the two that check the namespace comes back replace the runner (the +property test replaces the cache object too), and one checks the directory +guard. """ from __future__ import annotations import json +import os import socket from types import SimpleNamespace @@ -22,7 +28,7 @@ import litellm import pandas as pd import pytest -from hypothesis import HealthCheck, given, settings +from hypothesis import given, settings from hypothesis import strategies as st import policybench.eval_no_tools as eval_no_tools @@ -30,8 +36,10 @@ from policybench.config import MODELS from policybench.eval_no_tools import ( REASONING_EFFORT_OVERRIDE_ENV, + REPEATED_RUN_MARKER, _answer_contract_for_model, _repeat_cache_namespace, + _response_sources, _uses_responses_api, run_repeated_no_tools_eval, ) @@ -89,6 +97,7 @@ def _name_of(model_id: str) -> str: # One card per provider path and answer contract; a new one joins without an # edit here. REPRESENTATIVES = [ids[0] for _, ids in sorted(GROUPS.items())] +assert REPRESENTATIVES, "no model card to run the repeat tests on" def _answer(call: int) -> dict: @@ -253,9 +262,21 @@ def refuse(*_args, **_kwargs): # Turning the cache on registers LiteLLM callbacks; give them back too. for name in ("input_callback", "success_callback", "_async_success_callback"): monkeypatch.setattr(litellm, name, list(getattr(litellm, name))) + # LiteLLM remembers which callbacks it has set up in this module global. + monkeypatch.setattr( + litellm.utils, "callback_list", list(litellm.utils.callback_list or []) + ) monkeypatch.setattr(litellm, "cache", None) +@pytest.fixture(autouse=True) +def safe_umask(): + """The cache guard refuses a umask that lets others write the cache.""" + previous = os.umask(0o022) + yield + os.umask(previous) + + @pytest.fixture def wire(monkeypatch) -> list[dict]: """The requests LiteLLM put on the wire, each answered from this file.""" @@ -310,6 +331,39 @@ def run(*args, **kwargs): return counts +@pytest.fixture +def keys_per_repeat(monkeypatch, disk_cache) -> dict[str | None, list[tuple[str, str]]]: + """The keys LiteLLM looked up and stored in the disk cache, by run id.""" + keys: dict[str | None, list[tuple[str, str]]] = {} + running: list[str | None] = [None] + get, put = disk_cache.cache.get_cache, disk_cache.cache.set_cache + + def get_cache(key, **kwargs): + keys.setdefault(running[-1], []).append(("lookup", key)) + return get(key, **kwargs) + + def set_cache(key, value, **kwargs): + keys.setdefault(running[-1], []).append(("store", key)) + return put(key, value, **kwargs) + + monkeypatch.setattr(disk_cache.cache, "get_cache", get_cache) + monkeypatch.setattr(disk_cache.cache, "set_cache", set_cache) + + def tracking(runner): + def run(*args, **kwargs): + running.append(kwargs.get("run_id")) + try: + return runner(*args, **kwargs) + finally: + running.pop() + + return run + + for name in ("run_no_tools_eval", "run_no_tools_single_output_eval"): + monkeypatch.setattr(eval_no_tools, name, tracking(getattr(eval_no_tools, name))) + return keys + + def _run(model_id: str, output_dir, repeats: int = 2, **kwargs) -> pd.DataFrame: return run_repeated_no_tools_eval( [SCENARIO], @@ -329,12 +383,21 @@ def _raw(frame: pd.DataFrame, run_id: str) -> list[str]: return frame[frame["run_id"] == run_id]["raw_response"].tolist() +def _assert_answered(frame: pd.DataFrame) -> None: + """The stub's answers parsed, so no repair round ran.""" + assert frame["error"].isna().all(), frame["error"].dropna().iloc[0] + assert frame["prediction"].notna().all() + + @pytest.mark.parametrize("model_id", REPRESENTATIVES) def test_repeat_2_asks_again_when_repeat_1_is_cached( - model_id, disk_cache, sent_per_repeat, tmp_path + model_id, disk_cache, sent_per_repeat, keys_per_repeat, tmp_path ): + base = disk_cache.namespace + frame = _run(model_id, tmp_path / "runs") + _assert_answered(frame) sent = sent_per_repeat assert sent["run_000"] > 0 assert sent["run_001"] == sent["run_000"], ( @@ -344,13 +407,33 @@ def test_repeat_2_asks_again_when_repeat_1_is_cached( assert second["cache_hit_calls"].sum() == 0 assert second["live_calls"].sum() == sent["run_001"] assert _raw(frame, "run_001") != _raw(frame, "run_000") + # Every key a repeat looks up or stores sits under its own namespace, + # whether or not the cache can find the answer again later. + assert set(keys_per_repeat) == {"run_000", "run_001"} + for run_id, used in keys_per_repeat.items(): + assert {kind for kind, _ in used} == {"lookup", "store"} + prefix = f"{_repeat_cache_namespace(base, run_id)}:" + assert all(key.startswith(prefix) for _, key in used), run_id + + +def test_the_repeat_namespace_is_spelled_out(): + """A rerun finds a repeat's answers only while this spelling holds.""" + assert ( + _repeat_cache_namespace("policybench:x", "run_000") + == "policybench:x:repeat=run_000" + ) + assert _repeat_cache_namespace(None, "run_007") == "repeat=run_007" + assert _repeat_cache_namespace("", "run_007") == "repeat=run_007" def test_a_single_output_repeat_asks_again(disk_cache, sent_per_repeat, tmp_path): - _run(OPUS, tmp_path / "runs", single_output=True) + frame = _run(OPUS, tmp_path / "runs", single_output=True) + _assert_answered(frame) assert sent_per_repeat["run_000"] > 0 assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] + assert _calls(frame, "run_001")["cache_hit_calls"].sum() == 0 + assert _raw(frame, "run_001") != _raw(frame, "run_000") def _a_rebuilt_request_replays(model_id: str, output_dir, wire: list) -> bool: @@ -387,6 +470,7 @@ def test_a_rerun_replays_each_repeats_own_responses( replays = _a_rebuilt_request_replays(model_id, tmp_path, wire) assert replays or _group(model_id) == "gemini / tool" first = _run(model_id, tmp_path / "first") + _assert_answered(first) one_repeat = sent_per_repeat["run_000"] assert sent_per_repeat["run_001"] == one_repeat > 0, ( "a repeat replayed the plain run's answers, or another repeat's" @@ -395,8 +479,11 @@ def test_a_rerun_replays_each_repeats_own_responses( sent_per_repeat.clear() capsys.readouterr() - # A new output directory, so no CSV resume answers for the cache; one - # more repeat than before. + # As a new process would: a new cache object on the same directory. And a + # new output directory, so no CSV resume answers for the cache; one more + # repeat than before. + enable_cache(str(tmp_path / "cache")) + assert litellm.cache is not disk_cache again = _run(model_id, tmp_path / "again", repeats=3) rerun = 0 if replays else one_repeat @@ -412,17 +499,14 @@ def test_a_rerun_replays_each_repeats_own_responses( ) assert _raw(again, "run_001") != _raw(again, "run_000") out = capsys.readouterr().out - assert f"run_002: {one_repeat} responses from the provider, 0 replayed" in out + assert f"run_002: provider responses {one_repeat}, cache replays 0\n" in out if replays: for run_id in ("run_000", "run_001"): assert _raw(again, run_id) == _raw(first, run_id) replayed = _calls(again, run_id) assert replayed["live_calls"].sum() == 0 assert replayed["cache_hit_calls"].sum() == one_repeat - assert ( - f"run_001: 0 responses from the provider, {one_repeat} replayed from " - "the disk cache" - ) in out + assert f"run_001: provider responses 0, cache replays {one_repeat}\n" in out @pytest.mark.parametrize("model_id", REPRESENTATIVES) @@ -485,8 +569,68 @@ def test_the_cli_command_asks_again_on_repeat_2(monkeypatch, sent_per_repeat, tm assert (tmp_path / "cache" / "cache.db").exists() assert sent_per_repeat["run_000"] > 0 assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] + first = pd.read_csv(tmp_path / "runs" / "run_000.csv") second = pd.read_csv(tmp_path / "runs" / "run_001.csv") assert second["cache_hit_calls"].sum() == 0 + assert second["raw_response"].tolist() != first["raw_response"].tolist() + assert (tmp_path / "runs" / REPEATED_RUN_MARKER).exists() + + +def test_a_rerun_into_the_same_directory_resumes_and_says_so( + disk_cache, sent_per_repeat, tmp_path, capsys +): + first = _run(OPUS, tmp_path / "runs") + one_repeat = sent_per_repeat["run_000"] + out = capsys.readouterr().out + assert f"run_000: provider responses {one_repeat}, cache replays 0\n" in out + assert "resumed" not in out + sent_per_repeat.clear() + + again = _run(OPUS, tmp_path / "runs") + + assert sent_per_repeat == {"run_000": 0, "run_001": 0} + for run_id in ("run_000", "run_001"): + assert _raw(again, run_id) == _raw(first, run_id) + out = capsys.readouterr().out + assert ( + f"run_001: provider responses {one_repeat}, cache replays 0 " + "(resumed from run_001.csv: counts include its rows)\n" + ) in out + + +def test_repeat_files_written_before_the_namespaces_are_refused(monkeypatch, tmp_path): + """Repeats written under one shared namespace may be replays of repeat 1, + so the command does not resume from them.""" + runs = tmp_path / "runs" + runs.mkdir() + (runs / "run_000.csv").write_text("model,scenario_id,variable,prediction\n") + called = [] + monkeypatch.setattr( + eval_no_tools, "run_no_tools_eval", lambda *a, **k: called.append(k) + ) + + with pytest.raises(ValueError, match="Use a new output directory"): + _run(OPUS, runs) + + assert not called + assert not (runs / REPEATED_RUN_MARKER).exists() + + +def test_response_sources_counts_request_groups_without_a_record(): + rows = [ + {"call_id": "a", "live_calls": 2, "cache_hit_calls": 0}, + {"call_id": "a", "live_calls": 2, "cache_hit_calls": 0}, + {"call_id": "b", "live_calls": 0, "cache_hit_calls": 1}, + {"call_id": "c", "live_calls": None, "cache_hit_calls": None}, + ] + assert _response_sources(pd.DataFrame(rows)) == (2, 1, 1) + assert _response_sources(pd.DataFrame([{"call_id": "a"}, {"call_id": "b"}])) == ( + 0, + 0, + 2, + ) + assert _response_sources(pd.DataFrame()) == (0, 0, 0) + assert _response_sources(pd.DataFrame([{"prediction": 1.0}])) == (0, 0, 0) def test_without_a_cache_every_repeat_asks(sent_per_repeat, tmp_path): @@ -541,12 +685,7 @@ def failing(*_args, run_id, **_kwargs): assert litellm.cache.namespace == base -@settings( - max_examples=60, - deadline=None, - # The autouse offline fixture holds for every example. - suppress_health_check=[HealthCheck.function_scoped_fixture], -) +@settings(max_examples=60, deadline=None) @given( base=st.one_of(st.none(), st.text(min_size=1, max_size=40)), repeats=st.integers(min_value=1, max_value=6), From 8da0ea9950d93ad0cbc006184123da945f6f062e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 15:38:58 +0100 Subject: [PATCH 05/12] Record each repeat before it writes and count what a resume keeps (review r1) - repeated_run.json now lists the repeats this command started, each added before its runner writes. A run_*.csv the list does not name is refused before any request: a marker for the directory could not vouch for a file an older checkout added beside a recorded one. - The per-repeat line counts request groups by the runner's own unit (model and household, plus output for --single-output), so colons in model names or household ids no longer merge groups, and a group missing either count is reported, not summed. - The line names kept rows only when the runner's loader keeps some, and then gives their counts separately. - Repeats refuse to overlap in one process (the namespace is process-wide). - Docstrings and README say what the namespace guarantees and what it does not (requests with their own namespace or key; requests LiteLLM rewrites). - Tests: repair, chunk, escalation and explanation-only requests ask again under the repeat's namespace; single-output path proven; effort override checked on lookup, store and replay; answers compared pairwise; resume line after a fatal error and after infrastructure rows; marker cases. Co-Authored-By: Claude Opus 5.5 --- README.md | 31 +- policybench/cli.py | 2 +- policybench/eval_no_tools.py | 212 +++++++--- tests/test_repeated_runs_sample_fresh.py | 504 +++++++++++++++++++---- 4 files changed, 596 insertions(+), 153 deletions(-) diff --git a/README.md b/README.md index 489c959b..4ea09ff3 100644 --- a/README.md +++ b/README.md @@ -155,23 +155,28 @@ policybench analyze --runs-dir results/local/no_tools/runs --output-dir results/ Each repeat asks the models again. The command keeps the LiteLLM disk cache on, but each repeat looks up and stores its answers under its own cache namespace -(`repeat=run_000`, `repeat=run_001`, ...), so no repeat gets another repeat's -answers, or those of an `eval-no-tools` run. +(`repeat=run_000`, `repeat=run_001`, ...), so no repeat looks up another +repeat's answers, or those of an `eval-no-tools` run. Running the command again reuses what each repeat already has. Into the same -output directory, a repeat resumes from its CSV: it keeps the households the -file already answers in full and sends requests for the rest. Into a new -output directory with the same cache directory, a repeat looks for its answers -under its own namespace and asks the model only for those the cache does not -find. To draw a new, independent set of repeats, use a new output directory -and point `POLICYBENCH_CACHE_DIR` at a new directory. +output directory, a repeat resumes from its CSV before it consults the cache. +The batch runner keeps each household for which the file has a row for every +requested output, with no infrastructure error (and an explanation column when +explanations are on), even if some of those rows hold no parsed answer; it +asks again for the other households. With `--single-output` it keeps every row +without an infrastructure error. Into a new output directory with the same +cache directory, a repeat looks for its answers under its own namespace and +asks the model for those the cache does not find. To draw a new, independent +set of repeats, use a new output directory and point `POLICYBENCH_CACHE_DIR` +at a new directory. After each repeat the command prints how many provider responses and cache -replays the repeat's rows record, and says when the repeat resumed from an -existing file, whose stored rows those counts include. It writes -`repeated_run.json` beside the run files and refuses an output directory that -holds `run_*.csv` files without it: those repeats shared one cache namespace, -so the repeats after the first may be replays of it. +replays the repeat's rows record and, when it kept rows from an existing file, +how many of those the kept rows recorded when they were written. It records +each repeat in `repeated_run.json` beside the run files before the repeat +writes anything, and refuses an output directory holding a `run_*.csv` file +that the record does not list: nothing shows such a file was written under its +own cache namespace, so its rows may be replays of another repeat's. `policybench reference-outputs` writes PolicyEngine reference outputs, not administrative truth. It also writes `results/local/scenarios.csv`, and the eval diff --git a/policybench/cli.py b/policybench/cli.py index 0c1a380e..c6270674 100644 --- a/policybench/cli.py +++ b/policybench/cli.py @@ -1124,7 +1124,7 @@ def main(): # commands bypass cache by default, otherwise they can replay the same bad # provider response indefinitely. eval-no-tools-repeated gives each repeat # its own cache namespace (run_repeated_no_tools_eval), so a repeat never - # gets another repeat's responses. + # looks up another repeat's responses. if args.command in { "eval-no-tools", "eval-no-tools-repeated", diff --git a/policybench/eval_no_tools.py b/policybench/eval_no_tools.py index f3b7a22a..18476241 100644 --- a/policybench/eval_no_tools.py +++ b/policybench/eval_no_tools.py @@ -4306,23 +4306,33 @@ def _repeat_cache_namespace(base: str | None, run_id: str) -> str: return f"{base}:repeat={run_id}" if base else f"repeat={run_id}" +# Held while a repeat runs. The cache's namespace is process-wide, so two +# repeats running at once in one process would share it. +_REPEAT_NAMESPACE_LOCK = threading.Lock() + + class _OwnCacheNamespace: """Give one repeat its own LiteLLM disk-cache namespace while it runs. Every repeat builds the same requests, and LiteLLM keys its disk cache on - the request, so without this the cache the CLI turns on answers repeats - 2..N with repeat 1's responses and the run reports no run-to-run - variation. LiteLLM prefixes every key it computes, for the lookup and for - the store, with the cache's ``namespace`` attribute, read on each call - (``Cache._add_namespace_to_cache_key`` in LiteLLM 1.95.0). So under its own - namespace a repeat never finds another repeat's answers, or those of an - ``eval-no-tools`` run, and a rerun of the same repeat on the same cache - looks under the namespace that repeat stored its answers in. - - A request's own ``cache`` namespace outranks the attribute. The one the - harness sets, for an effort override (``_effort_cache_namespace``), is - built from the attribute when the request is built, so it keeps the - repeat. Without a cache this does nothing. + the request, so without this the cache the CLI turns on can answer + repeats 2..N with repeat 1's responses. LiteLLM prefixes each key it + computes, for the lookup and for the store, with the cache's + ``namespace`` attribute, read on each call (``Cache._add_namespace_to_cache_key`` + in LiteLLM 1.95.0), unless the request names its own namespace (in + ``cache`` or ``metadata["redis_namespace"]``) or brings its own + ``cache_key``. The one namespace the harness puts on a request, for an + effort override (``_effort_cache_namespace``), is built from the attribute + while the repeat runs, so it keeps the repeat. + + So a repeat looks up and stores its answers under keys no other repeat + uses, and a rerun of the same repeat on the same cache looks under the + keys that repeat stored. Whether the rerun finds an answer there is the + cache's business: a request LiteLLM rewrites between its lookup and its + store never finds its answer, in a repeat or out of one. + + Repeats cannot overlap in one process: entering one while another runs + raises RuntimeError. Without a cache the namespace is left alone. """ def __init__(self, run_id: str) -> None: @@ -4331,61 +4341,134 @@ def __init__(self, run_id: str) -> None: self._base: str | None = None def __enter__(self) -> None: + if not _REPEAT_NAMESPACE_LOCK.acquire(blocking=False): + raise RuntimeError( + f"Cannot start repeat {self._run_id}: another repeat is running " + "in this process, and the two would share one cache namespace." + ) self._cache = litellm.cache if self._cache is not None: self._base = self._cache.namespace self._cache.namespace = _repeat_cache_namespace(self._base, self._run_id) def __exit__(self, *_exc) -> None: - if self._cache is not None: - self._cache.namespace = self._base + try: + if self._cache is not None: + self._cache.namespace = self._base + finally: + _REPEAT_NAMESPACE_LOCK.release() -def _response_sources(frame: pd.DataFrame) -> tuple[int, int, int]: +def _response_sources( + frame: pd.DataFrame, single_output: bool = False +) -> tuple[int, int, int]: """Where the responses behind a run's rows came from. - Returns the responses the provider answered, the responses the disk cache - replayed, and the request groups whose rows record neither. + A request group is what one logical request answers: a model and a + household in the batch runner, and also an output in the single-output + runner. Every row of a group carries the group's counts. Returns the + responses the provider answered and the responses the disk cache + replayed, summed over the groups that record both counts, and the number + of groups that lack either count. """ - if frame.empty or "call_id" not in frame.columns: + if frame.empty: return 0, 0, 0 - # Every row of one request group carries the group's counts. - calls = frame.drop_duplicates("call_id") - if not {"live_calls", "cache_hit_calls"} <= set(calls.columns): - return 0, 0, len(calls) - live = pd.to_numeric(calls["live_calls"], errors="coerce") - replayed = pd.to_numeric(calls["cache_hit_calls"], errors="coerce") - unrecorded = int((live.isna() | replayed.isna()).sum()) - return int(live.fillna(0).sum()), int(replayed.fillna(0).sum()), unrecorded - - -# Written beside a repeated run's CSVs. Its absence marks a directory whose -# repeat files predate per-repeat cache namespaces. + unit = ( + ["model", "scenario_id", "variable"] + if single_output + else ["model", "scenario_id"] + ) + groups = frame.drop_duplicates(unit) + if not {"live_calls", "cache_hit_calls"} <= set(groups.columns): + return 0, 0, len(groups) + live = pd.to_numeric(groups["live_calls"], errors="coerce") + replayed = pd.to_numeric(groups["cache_hit_calls"], errors="coerce") + unrecorded = live.isna() | replayed.isna() + return ( + int(live[~unrecorded].sum()), + int(replayed[~unrecorded].sum()), + int(unrecorded.sum()), + ) + + +# Written beside a repeated run's CSVs: the repeats this command started, +# each under its own cache namespace. REPEATED_RUN_MARKER = "repeated_run.json" +_RECORDED_REPEATS_KEY = "repeats_with_own_cache_namespace" -def _claim_repeat_directory(output_path: Path) -> None: - """Mark ``output_path`` as a repeated run whose repeats sample fresh. +def _recorded_repeats(output_path: Path) -> set[str]: + """The repeats ``repeated_run.json`` in ``output_path`` records.""" + marker = output_path / REPEATED_RUN_MARKER + if not marker.exists(): + return set() + try: + recorded = json.loads(marker.read_text(encoding="utf-8"))[_RECORDED_REPEATS_KEY] + if not isinstance(recorded, list): + raise TypeError(f"{_RECORDED_REPEATS_KEY} is not a list") + return {str(run_id) for run_id in recorded} + except (ValueError, KeyError, TypeError) as error: + raise ValueError( + f"{marker} cannot be read ({error}). Use a new output directory." + ) from error + - Refuses a directory that already holds repeat files and no marker: every - repeat in it shared one cache namespace, so its repeats after the first - may be replays of the first, and resuming from them would report no - run-to-run variation. +def _refuse_unrecorded_repeat_files(output_path: Path, recorded: set[str]) -> None: + """Refuse a directory holding repeat files the marker does not record. + + Nothing shows such a file was written with its own cache namespace: an + earlier version of this command, under which every repeat shared one + namespace, or anything else may have written it, so its rows may be + replays of another repeat's. Resuming it, or analysing the directory, + would count it as an independent repeat. """ - marker = output_path / REPEATED_RUN_MARKER - if marker.exists(): - return - earlier = sorted(path.name for path in output_path.glob("run_*.csv")) - if earlier: + unrecorded = sorted( + path.name for path in output_path.glob("run_*.csv") if path.stem not in recorded + ) + if unrecorded: raise ValueError( - f"{output_path} holds repeat files (first: {earlier[0]}) and no " - f"{REPEATED_RUN_MARKER}, so they were written before each repeat " - "had its own cache namespace and repeats after the first may be " - "replays of it. Use a new output directory." + f"{output_path} holds repeat files that {REPEATED_RUN_MARKER} does " + f"not record as written under their own cache namespace " + f"({', '.join(unrecorded)}), so their rows may be replays of " + "another repeat's. Use a new output directory." ) - marker.write_text( - json.dumps({"each_repeat_has_its_own_cache_namespace": True}) + "\n" + + +def _record_repeat(output_path: Path, recorded: set[str], run_id: str) -> None: + """Add ``run_id`` to ``recorded`` and to the marker, before it writes.""" + if run_id in recorded: + return + recorded.add(run_id) + marker = output_path / REPEATED_RUN_MARKER + staging = marker.with_name(f"{marker.name}.tmp") + staging.write_text( + json.dumps({_RECORDED_REPEATS_KEY: sorted(recorded)}) + "\n", + encoding="utf-8", ) + os.replace(staging, marker) + + +def _rows_kept_on_resume( + run_output_path: Path, + scenarios: list[Scenario], + programs: list[str] | None, + include_explanations: bool, + single_output: bool, +) -> pd.DataFrame: + """The rows of an existing repeat file that its runner keeps, asking + nothing for them: the runner's own loader, given what the runner gives it.""" + if single_output: + rows, _ = _load_existing_single_output_rows( + str(run_output_path), include_explanations=include_explanations + ) + else: + rows, _ = _load_existing_rows( + str(run_output_path), + scenarios, + PROGRAMS if programs is None else programs, + include_explanations=include_explanations, + ) + return pd.DataFrame(rows) def run_repeated_no_tools_eval( @@ -4399,23 +4482,28 @@ def run_repeated_no_tools_eval( ) -> pd.DataFrame: """Run repeated AI-alone evaluations, saving one artifact per run. - Each repeat asks the models again: it runs under its own disk-cache - namespace (``_OwnCacheNamespace``), so it never replays another - repeat's responses, and a rerun on the same cache finds only its own. - After each repeat, one line says where its rows' responses came from. - Raises ValueError for a directory of repeat files written before repeats - had their own namespaces (``_claim_repeat_directory``). + Each repeat runs under its own disk-cache namespace + (``_OwnCacheNamespace``), so it never looks up another repeat's answers, + and a rerun on the same cache looks only under its own. Each repeat is + recorded in ``repeated_run.json`` before it writes, and a directory + holding a repeat file the record does not list raises ValueError before + any request. After each repeat, one line says where its rows' responses + came from, and how many of them it kept from an existing file. """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True) - _claim_repeat_directory(output_path) + recorded = _recorded_repeats(output_path) + _refuse_unrecorded_repeat_files(output_path, recorded) frames = [] for run_index in range(repeats): run_id = f"run_{run_index:03d}" run_output_path = output_path / f"{run_id}.csv" - resumed = run_output_path.exists() print(f"=== Starting {run_id} ===") + kept = _rows_kept_on_resume( + run_output_path, scenarios, programs, include_explanations, single_output + ) + _record_repeat(output_path, recorded, run_id) runner = run_no_tools_single_output_eval if single_output else run_no_tools_eval with _OwnCacheNamespace(run_id): frame = runner( @@ -4430,15 +4518,17 @@ def run_repeated_no_tools_eval( frame = frame.copy() frame["run_id"] = run_id frame.to_csv(run_output_path, index=False) - live, replayed, unrecorded = _response_sources(frame) + live, replayed, unrecorded = _response_sources(frame, single_output) sources = f"{run_id}: provider responses {live}, cache replays {replayed}" if unrecorded: sources += f", request groups with no record {unrecorded}" - if resumed: - # The runner keeps the file's complete rows and sends nothing for - # them, so the counts are what those rows recorded when written. + if not kept.empty: + # The runner sent nothing for these rows; their counts are what + # they recorded when the file was written. + kept_live, kept_replayed, _ = _response_sources(kept, single_output) sources += ( - f" (resumed from {run_output_path.name}: counts include its rows)" + f"; of these, kept from {run_output_path.name}: provider " + f"responses {kept_live}, cache replays {kept_replayed}" ) print(sources) frames.append(frame) diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index 93899da7..1c2be4dd 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -2,19 +2,26 @@ ``policybench eval-no-tools-repeated`` turns the LiteLLM disk cache on, and every repeat builds the same requests. LiteLLM keys the cache on the request, -so repeats 2..N used to get repeat 1's responses back from the cache and the -run reported no run-to-run variation. Each repeat now runs under its own -cache namespace (``_OwnCacheNamespace``). - -The tests that send requests run the harness's repeated path through LiteLLM's -real request path and the harness's real disk cache (``enable_cache`` in a -temporary directory). They replace only the wire: ``httpx.Client.send`` -answers from this file with a value that names the call, and a socket -connection fails the test. Those tests also count requests per repeat and -record cache keys by wrapping the runner and the disk cache. Three tests send -nothing: the two that check the namespace comes back replace the runner (the -property test replaces the cache object too), and one checks the directory -guard. +so repeats 2..N used to get repeat 1's responses back from the cache for +every request whose stored answer a rebuilt request finds, and the run +reported no run-to-run variation. Each repeat now runs under its own cache +namespace (``_OwnCacheNamespace``). + +Most tests run the harness's repeated path through LiteLLM's real request +path and replace only the wire: ``httpx.Client.send`` answers from this file +with a value that names the call. All but the no-cache control use the +harness's real disk cache (``enable_cache`` in a temporary directory). The +autouse fixture blocks sockets while each test runs and gives every request +one attempt (``MAX_ATTEMPTS``). It cannot reach LiteLLM's model-cost map, +which LiteLLM loads when it is first imported, before any fixture; set +``LITELLM_LOCAL_MODEL_COST_MAP=True`` to keep that load off the network. +Fixtures count requests per repeat and, where a test asks for them, record +the cache keys each repeat looks up and stores. + +Seven tests send no request: the namespace's spelling, the two directory +guards, the response counter, the overlap guard, and the two that check the +namespace comes back (they replace the runner; the property test replaces +the cache object too). """ from __future__ import annotations @@ -35,15 +42,17 @@ from policybench.cache import enable_cache from policybench.config import MODELS from policybench.eval_no_tools import ( + EXPLANATION_FUNCTION_NAME, REASONING_EFFORT_OVERRIDE_ENV, REPEATED_RUN_MARKER, _answer_contract_for_model, + _OwnCacheNamespace, _repeat_cache_namespace, _response_sources, _uses_responses_api, run_repeated_no_tools_eval, ) -from policybench.model_cards import MODEL_CARDS +from policybench.model_cards import MODEL_CARDS, explanation_chunk_size_for from policybench.scenarios import Person, Scenario SCENARIO = Scenario( @@ -98,6 +107,13 @@ def _name_of(model_id: str) -> str: # edit here. REPRESENTATIVES = [ids[0] for _, ids in sorted(GROUPS.items())] assert REPRESENTATIVES, "no model card to run the repeat tests on" +# The follow-up-path tests read the requested outputs from the request's +# Anthropic tool schema, and need a card that asks for every output at once. +ANTHROPIC_TOOL = next( + model_id + for model_id in GROUPS["anthropic / tool"] + if explanation_chunk_size_for(model_id) is None +) def _answer(call: int) -> dict: @@ -243,6 +259,93 @@ def _canned_answer(path: str, body: dict, call: int) -> dict: raise AssertionError(f"the stub has no answer for the path {path}") +def _anthropic_message(call: int, body: dict, content: list, stop_reason: str): + return { + "id": f"stub-{call}", + "type": "message", + "role": "assistant", + "model": body.get("model", "stub"), + "content": content, + "stop_reason": stop_reason, + "stop_sequence": None, + "usage": {"input_tokens": 10, "output_tokens": 5}, + } + + +class _FollowUpAnswers: + """Anthropic tool answers that send each household down one follow-up path. + + - ``repair``: a request for several outputs gets the first one only, so + the harness asks again for the rest (a repair round). + - ``chunk``: plain answers; the test sets a chunk size of one output. + - ``escalation``: a request at the first completion budget it sees stops + on the length limit with nothing in it, so the harness asks again with + a larger budget. + - ``explanation``: values with blank explanations; with no repair round + left, the harness asks for the explanations alone. + + Each household's answer depends only on the request, not on the order + requests arrive in, so a repeat that asks again takes the same path. + """ + + def __init__(self, path: str) -> None: + self.path = path + self.first_budget: int | None = None + self.values: dict[str, float] = {} + + def __call__(self, url_path: str, body: dict, call: int) -> dict: + assert url_path.endswith("/messages"), url_path + (tool,) = body["tools"] + schema = tool["input_schema"]["properties"] + value = 1000 + call + if tool["name"] == EXPLANATION_FUNCTION_NAME: + explanations = { + variable: f"Call {call}. value = {self.values[variable]:g}" + for variable in schema + } + return _anthropic_message( + call, + body, + [ + { + "type": "tool_use", + "id": f"toolu_{call}", + "name": tool["name"], + "input": explanations, + } + ], + "tool_use", + ) + asked = list(schema["outputs"]["properties"]) + if self.path == "escalation": + if self.first_budget is None: + self.first_budget = body["max_tokens"] + if body["max_tokens"] == self.first_budget: + return _anthropic_message(call, body, [], "max_tokens") + if self.path == "repair": + asked = asked[:1] + self.values.update(dict.fromkeys(asked, value)) + explanation = ( + "" if self.path == "explanation" else f"Call {call}. value = {value}" + ) + outputs = { + variable: {"value": value, "explanation": explanation} for variable in asked + } + return _anthropic_message( + call, + body, + [ + { + "type": "tool_use", + "id": f"toolu_{call}", + "name": tool["name"], + "input": {"outputs": outputs}, + } + ], + "tool_use", + ) + + @pytest.fixture(autouse=True) def offline(monkeypatch): """No key, no socket, no sensitivity knob, one attempt per request.""" @@ -259,9 +362,11 @@ def refuse(*_args, **_kwargs): monkeypatch.setattr(eval_no_tools, "_PROCESS_REASONING_EFFORT_OVERRIDE", []) monkeypatch.setattr(eval_no_tools, "MAX_ATTEMPTS", 1) monkeypatch.setattr(litellm, "drop_params", False) - # Turning the cache on registers LiteLLM callbacks; give them back too. - for name in ("input_callback", "success_callback", "_async_success_callback"): - monkeypatch.setattr(litellm, name, list(getattr(litellm, name))) + # Turning the cache on registers LiteLLM callbacks, and LiteLLM moves + # callbacks between its lists; give every list back. + for name, value in list(vars(litellm).items()): + if "callback" in name and isinstance(value, list): + monkeypatch.setattr(litellm, name, list(value)) # LiteLLM remembers which callbacks it has set up in this module global. monkeypatch.setattr( litellm.utils, "callback_list", list(litellm.utils.callback_list or []) @@ -277,19 +382,27 @@ def safe_umask(): os.umask(previous) +class _Wire(list): + """The requests LiteLLM put on the wire. + + ``answer(path, body, call)`` builds each response: a provider-shaped body, + or a ``(status, body)`` pair for an error. + """ + + answer = staticmethod(_canned_answer) + + @pytest.fixture -def wire(monkeypatch) -> list[dict]: +def wire(monkeypatch) -> _Wire: """The requests LiteLLM put on the wire, each answered from this file.""" - sent: list[dict] = [] + sent = _Wire() def send(self, request, **_kwargs): body = json.loads(request.content) sent.append({"path": request.url.path, "body": body}) - return httpx.Response( - 200, - json=_canned_answer(request.url.path, body, len(sent)), - request=request, - ) + answer = sent.answer(request.url.path, body, len(sent)) + status, payload = answer if isinstance(answer, tuple) else (200, answer) + return httpx.Response(status, json=payload, request=request) def no_async_send(self, request, **_kwargs): raise AssertionError("the harness sends no asynchronous request") @@ -426,24 +539,104 @@ def test_the_repeat_namespace_is_spelled_out(): assert _repeat_cache_namespace("", "run_007") == "repeat=run_007" -def test_a_single_output_repeat_asks_again(disk_cache, sent_per_repeat, tmp_path): +def test_a_single_output_repeat_asks_again( + disk_cache, sent_per_repeat, keys_per_repeat, tmp_path +): + base = disk_cache.namespace + frame = _run(OPUS, tmp_path / "runs", single_output=True) _assert_answered(frame) - assert sent_per_repeat["run_000"] > 0 - assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] + # One request per output, so the single-output runner ran, not the batch + # runner (one request for the household). + assert sent_per_repeat == {"run_000": len(VARIABLES), "run_001": len(VARIABLES)} assert _calls(frame, "run_001")["cache_hit_calls"].sum() == 0 - assert _raw(frame, "run_001") != _raw(frame, "run_000") + assert set(_raw(frame, "run_001")).isdisjoint(_raw(frame, "run_000")) + # Both repeats used the disk cache, each under its own namespace. + assert set(keys_per_repeat) == {"run_000", "run_001"} + for run_id, used in keys_per_repeat.items(): + assert {kind for kind, _ in used} == {"lookup", "store"} + prefix = f"{_repeat_cache_namespace(base, run_id)}:" + assert all(key.startswith(prefix) for _, key in used), run_id + + +def _request_shape(body: dict) -> tuple[str, tuple[str, ...], int]: + """An Anthropic tool request's tool, the outputs it asks for, and its + completion budget.""" + (tool,) = body["tools"] + schema = tool["input_schema"]["properties"] + if tool["name"] == EXPLANATION_FUNCTION_NAME: + return "explanation", tuple(schema), body["max_tokens"] + return "answer", tuple(schema["outputs"]["properties"]), body["max_tokens"] + +@pytest.mark.parametrize("path", ["repair", "chunk", "escalation", "explanation"]) +def test_a_follow_up_request_asks_again_under_its_repeats_namespace( + path, monkeypatch, disk_cache, wire, sent_per_repeat, keys_per_repeat, tmp_path +): + """A repair round, explanation chunks, a larger completion budget and + the explanation-only request each go out again in repeat 2, under its + namespace.""" + if path == "chunk": + monkeypatch.setattr( + eval_no_tools, "_required_explanation_chunk_size", lambda *_a, **_k: 1 + ) + if path == "explanation": + monkeypatch.setattr(eval_no_tools, "MAX_REPAIR_ROUNDS", 0) + wire.answer = _FollowUpAnswers(path) + base = disk_cache.namespace -def _a_rebuilt_request_replays(model_id: str, output_dir, wire: list) -> bool: - """Whether a plain run's rebuilt requests find their stored answers. + frame = _run(ANTHROPIC_TOOL, tmp_path / "runs") + + _assert_answered(frame) + assert frame["explanation"].fillna("").str.strip().ne("").all() + # Two requests a repeat: the household's first and the follow-up the + # path names. A plain answer would take one. + assert sent_per_repeat == {"run_000": 2, "run_001": 2} + shapes = [_request_shape(request["body"]) for request in wire] + first, follow_up = { + "repair": (("answer", ("snap", "ssi")), ("answer", ("ssi",))), + "chunk": (("answer", ("snap",)), ("answer", ("ssi",))), + "escalation": (("answer", ("snap", "ssi")), ("answer", ("snap", "ssi"))), + "explanation": (("answer", ("snap", "ssi")), ("explanation", ("snap", "ssi"))), + }[path] + assert [shape[:2] for shape in shapes] == [first, follow_up] * 2 + budgets = [shape[2] for shape in shapes] + if path == "escalation": + assert budgets[1] > budgets[0] and budgets[2:] == budgets[:2] + second = _calls(frame, "run_001") + assert second["live_calls"].sum() == 2 + assert second["cache_hit_calls"].sum() == 0 + assert set(_raw(frame, "run_001")).isdisjoint(_raw(frame, "run_000")) + for run_id, used in keys_per_repeat.items(): + assert sum(kind == "lookup" for kind, _ in used) == 2, run_id + prefix = f"{_repeat_cache_namespace(base, run_id)}:" + assert all(key.startswith(prefix) for _, key in used), run_id + + +def _a_rebuilt_request_replays( + model_id: str, output_dir, wire: list, monkeypatch +) -> tuple[bool, bool]: + """Whether a plain run's rebuilt requests find their stored answers, and + whether the harness handed LiteLLM a cache key for every request. Two ``eval-no-tools`` runs of the same household on the cache, outside any repeat. LiteLLM rewrites a ``gemini/`` tool request's schema between its - cache lookup and its store, so until the harness pins the cache key that - one group's rebuilt request never finds its answer, repeat or not. + cache lookup and its store, so unless the harness pins each request's + cache key, that group's rebuilt request never finds its answer, repeat or + not. """ + keyed: list[bool] = [] + + def spying(request_fn): + def request(*args, **kwargs): + keyed.append("cache_key" in kwargs) + return request_fn(*args, **kwargs) + + return request + + for name in ("completion", "responses"): + monkeypatch.setattr(eval_no_tools, name, spying(getattr(eval_no_tools, name))) def plain(name: str) -> int: before = len(wire) @@ -457,18 +650,23 @@ def plain(name: str) -> int: first, second = plain("plain_1"), plain("plain_2") assert first > 0 and second in (0, first) - return second == 0 + assert keyed + return second == 0, all(keyed) @pytest.mark.parametrize("model_id", REPRESENTATIVES) def test_a_rerun_replays_each_repeats_own_responses( - model_id, disk_cache, sent_per_repeat, wire, tmp_path, capsys + model_id, disk_cache, sent_per_repeat, wire, tmp_path, capsys, monkeypatch ): """A rerun's repeats replay exactly when a plain rebuilt request does, and then each replays its own answers. The namespace scopes the cache; it does not decide whether the cache can find an answer.""" - replays = _a_rebuilt_request_replays(model_id, tmp_path, wire) - assert replays or _group(model_id) == "gemini / tool" + replays, keys_pinned = _a_rebuilt_request_replays( + model_id, tmp_path, wire, monkeypatch + ) + # Only a gemini/ tool request may fail to replay, and only while the + # harness leaves the cache key to LiteLLM. + assert replays or (_group(model_id) == "gemini / tool" and not keys_pinned) first = _run(model_id, tmp_path / "first") _assert_answered(first) one_repeat = sent_per_repeat["run_000"] @@ -493,11 +691,10 @@ def test_a_rerun_replays_each_repeats_own_responses( "run_002": one_repeat, } assert len(wire) - sent_before == 2 * rerun + one_repeat - assert _raw(again, "run_002") not in ( - _raw(again, "run_000"), - _raw(again, "run_001"), + assert set(_raw(again, "run_002")).isdisjoint( + _raw(again, "run_000") + _raw(again, "run_001") ) - assert _raw(again, "run_001") != _raw(again, "run_000") + assert set(_raw(again, "run_001")).isdisjoint(_raw(again, "run_000")) out = capsys.readouterr().out assert f"run_002: provider responses {one_repeat}, cache replays 0\n" in out if replays: @@ -519,7 +716,7 @@ def test_no_repeat_ever_returns_another_repeats_responses( again = _run(model_id, tmp_path / "again", repeats=3) answers = { - (label, run_id): _raw(frame, run_id) + (label, run_id): set(_raw(frame, run_id)) for label, frame in (("first", first), ("again", again)) for run_id in sorted(set(frame["run_id"])) } @@ -528,8 +725,10 @@ def test_no_repeat_ever_returns_another_repeats_responses( for (label, run_id), raw in answers.items(): for (other_label, other_id), other in answers.items(): if other_id != run_id: - assert raw != other, ( - f"{label} {run_id} returned {other_label} {other_id}'s responses" + shared = raw & other + assert not shared, ( + f"{label} {run_id} returned {len(shared)} of " + f"{other_label} {other_id}'s responses" ) @@ -593,17 +792,103 @@ def test_a_rerun_into_the_same_directory_resumes_and_says_so( assert _raw(again, run_id) == _raw(first, run_id) out = capsys.readouterr().out assert ( - f"run_001: provider responses {one_repeat}, cache replays 0 " - "(resumed from run_001.csv: counts include its rows)\n" + f"run_001: provider responses {one_repeat}, cache replays 0; of these, " + f"kept from run_001.csv: provider responses {one_repeat}, cache replays 0\n" ) in out + record = json.loads((tmp_path / "runs" / REPEATED_RUN_MARKER).read_text()) + assert record == {"repeats_with_own_cache_namespace": ["run_000", "run_001"]} -def test_repeat_files_written_before_the_namespaces_are_refused(monkeypatch, tmp_path): - """Repeats written under one shared namespace may be replays of repeat 1, - so the command does not resume from them.""" +@pytest.mark.parametrize("left_by", ["fatal error", "infrastructure error"]) +def test_a_resume_that_keeps_no_row_does_not_say_it_kept_any( + left_by, disk_cache, wire, sent_per_repeat, tmp_path, capsys +): + """The repeat's file exists, but the runner keeps none of its rows, so the + line names no kept rows.""" + runs = tmp_path / "runs" + if left_by == "fatal error": + # A rejected key stops the model with no row; the command then writes + # a CSV holding a header only. Nothing was cached. + wire.answer = lambda *_args: ( + 401, + { + "type": "error", + "error": {"type": "authentication_error", "message": "bad key"}, + }, + ) + _run(ANTHROPIC_TOOL, runs, repeats=1) + assert (runs / "run_000.csv").read_text().strip() == "run_id" + expected = ({"run_000": 1}, "provider responses 1, cache replays 0") + else: + # Rows whose error the loader counts as infrastructure, as an + # interrupted or older run can leave. The answer is in the cache. + _run(ANTHROPIC_TOOL, runs, repeats=1) + rows = pd.read_csv(runs / "run_000.csv") + rows["error"] = "litellm.Timeout: request timed out" + rows.to_csv(runs / "run_000.csv", index=False) + expected = ({"run_000": 0}, "provider responses 0, cache replays 1") + assert sent_per_repeat["run_000"] > 0 + sent_per_repeat.clear() + capsys.readouterr() + wire.answer = staticmethod(_canned_answer) + + again = _run(ANTHROPIC_TOOL, runs, repeats=1) + + _assert_answered(again) + sent, counts = expected + assert sent_per_repeat == sent + out = capsys.readouterr().out + assert f"run_000: {counts}\n" in out + assert "kept from" not in out + + +def test_a_repeat_file_the_marker_does_not_record_is_refused( + disk_cache, wire, sent_per_repeat, tmp_path +): + """The marker does not vouch for a directory, only for the repeats it + lists: here a run without per-repeat namespaces, as an earlier version of + the command ran, adds a repeat file beside a recorded one.""" + runs = tmp_path / "runs" + _run(OPUS, runs, repeats=1) + eval_no_tools.run_no_tools_eval( + [SCENARIO], + models={_name_of(OPUS): OPUS}, + programs=VARIABLES, + output_path=str(runs / "run_001.csv"), + run_id="run_001", + ) + sent = len(wire) + record = (runs / REPEATED_RUN_MARKER).read_text() + + with pytest.raises(ValueError, match=r"run_001\.csv.*Use a new output directory"): + _run(OPUS, runs, repeats=3) + + assert len(wire) == sent + assert (runs / REPEATED_RUN_MARKER).read_text() == record + assert not (runs / "run_002.csv").exists() + + +@pytest.mark.parametrize( + "marker", + [ + None, + '{"repeats_with_own_cache_namespace": ["run_000"]}', + '{"each_repeat_has_its_own_cache_namespace": true}', + '{"repeats_with_own_cache_namespace": "run_000"}', + "not json", + ], +) +def test_repeat_files_without_a_record_are_refused_before_any_request( + marker, monkeypatch, tmp_path +): + """A file the marker does not list, here one past the repeats asked for, + or a marker that cannot be read: the command sends nothing.""" runs = tmp_path / "runs" runs.mkdir() (runs / "run_000.csv").write_text("model,scenario_id,variable,prediction\n") + (runs / "run_005.csv").write_text("model,scenario_id,variable,prediction\n") + if marker is not None: + (runs / REPEATED_RUN_MARKER).write_text(marker) called = [] monkeypatch.setattr( eval_no_tools, "run_no_tools_eval", lambda *a, **k: called.append(k) @@ -613,24 +898,82 @@ def test_repeat_files_written_before_the_namespaces_are_refused(monkeypatch, tmp _run(OPUS, runs) assert not called - assert not (runs / REPEATED_RUN_MARKER).exists() - - -def test_response_sources_counts_request_groups_without_a_record(): - rows = [ - {"call_id": "a", "live_calls": 2, "cache_hit_calls": 0}, - {"call_id": "a", "live_calls": 2, "cache_hit_calls": 0}, - {"call_id": "b", "live_calls": 0, "cache_hit_calls": 1}, - {"call_id": "c", "live_calls": None, "cache_hit_calls": None}, + if marker is None: + assert not (runs / REPEATED_RUN_MARKER).exists() + else: + assert (runs / REPEATED_RUN_MARKER).read_text() == marker + + +def test_response_sources_counts_each_request_group_once(): + batch = [ + # Model "a" and household "b:c", and model "a:b" and household "c", + # share the call id "run_000:a:b:c"; they are two request groups. + { + "model": "a", + "scenario_id": "b:c", + "variable": "snap", + "live_calls": 2, + "cache_hit_calls": 0, + }, + { + "model": "a", + "scenario_id": "b:c", + "variable": "ssi", + "live_calls": 2, + "cache_hit_calls": 0, + }, + { + "model": "a:b", + "scenario_id": "c", + "variable": "snap", + "live_calls": 1, + "cache_hit_calls": 0, + }, + { + "model": "a:b", + "scenario_id": "d", + "variable": "snap", + "live_calls": 0, + "cache_hit_calls": 1, + }, + { + "model": "a:b", + "scenario_id": "e", + "variable": "snap", + "live_calls": 1, + "cache_hit_calls": None, + }, + { + "model": "a:b", + "scenario_id": "f", + "variable": "snap", + "live_calls": None, + "cache_hit_calls": None, + }, ] - assert _response_sources(pd.DataFrame(rows)) == (2, 1, 1) - assert _response_sources(pd.DataFrame([{"call_id": "a"}, {"call_id": "b"}])) == ( - 0, - 0, - 2, - ) + frame = pd.DataFrame(batch) + for row in batch: + row["call_id"] = ":".join(["run_000", row["model"], row["scenario_id"]]) + assert _response_sources(pd.DataFrame(batch)) == (3, 1, 2) + assert _response_sources(frame) == (3, 1, 2) + # One output a request in the single-output runner. + assert _response_sources(frame, single_output=True) == (5, 1, 2) + no_counts = pd.DataFrame([{"model": "a", "scenario_id": "b", "variable": "snap"}]) + assert _response_sources(no_counts) == (0, 0, 1) assert _response_sources(pd.DataFrame()) == (0, 0, 0) - assert _response_sources(pd.DataFrame([{"prediction": 1.0}])) == (0, 0, 0) + + +def test_repeats_cannot_overlap_in_one_process(disk_cache): + base = disk_cache.namespace + with _OwnCacheNamespace("run_000"): + with pytest.raises(RuntimeError, match="another repeat is running"): + with _OwnCacheNamespace("run_001"): + pass + assert disk_cache.namespace == _repeat_cache_namespace(base, "run_000") + assert disk_cache.namespace == base + with _OwnCacheNamespace("run_001"): + assert disk_cache.namespace == _repeat_cache_namespace(base, "run_001") + assert disk_cache.namespace == base def test_without_a_cache_every_repeat_asks(sent_per_repeat, tmp_path): @@ -643,27 +986,30 @@ def test_without_a_cache_every_repeat_asks(sent_per_repeat, tmp_path): def test_an_effort_override_keeps_the_repeat_namespace( - disk_cache, sent_per_repeat, tmp_path, monkeypatch + disk_cache, sent_per_repeat, keys_per_repeat, tmp_path, monkeypatch ): """The override's own request namespace outranks the cache's, so it has - to carry the repeat.""" + to carry the repeat: for the lookup, the store, and a rerun's replay.""" monkeypatch.setenv(REASONING_EFFORT_OVERRIDE_ENV, f"{OPUS}=high") - stored: list[str] = [] - put = disk_cache.cache.set_cache + base = disk_cache.namespace - def set_cache(key, value, **kwargs): - stored.append(key) - return put(key, value, **kwargs) + first = _run(OPUS, tmp_path / "runs") - monkeypatch.setattr(disk_cache.cache, "set_cache", set_cache) - base = disk_cache.namespace + one_repeat = sent_per_repeat["run_000"] + assert sent_per_repeat["run_001"] == one_repeat > 0 + assert set(keys_per_repeat) == {"run_000", "run_001"} + for run_id, used in keys_per_repeat.items(): + assert {kind for kind, _ in used} == {"lookup", "store"} + prefix = f"{_repeat_cache_namespace(base, run_id)}:{OPUS}:effort=high:" + assert all(key.startswith(prefix) for _, key in used), run_id + sent_per_repeat.clear() - _run(OPUS, tmp_path / "runs") + enable_cache(str(tmp_path / "cache")) + again = _run(OPUS, tmp_path / "again") - assert sent_per_repeat["run_001"] == sent_per_repeat["run_000"] > 0 + assert sent_per_repeat == {"run_000": 0, "run_001": 0} for run_id in ("run_000", "run_001"): - prefix = f"{_repeat_cache_namespace(base, run_id)}:{OPUS}:effort=high:" - assert any(key.startswith(prefix) for key in stored), run_id + assert _raw(again, run_id) == _raw(first, run_id) def test_the_cache_namespace_comes_back_when_a_repeat_fails( @@ -709,7 +1055,9 @@ def runner(*_args, run_id, **_kwargs): [ { "run_id": run_id, - "call_id": run_id, + "model": "a", + "scenario_id": SCENARIO.id, + "variable": "snap", "live_calls": 1, "cache_hit_calls": 0, } From e16ebc2f2f2b22d4e690e482e691216ebb0f9057 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 15:41:36 +0100 Subject: [PATCH 06/12] Say which tests send no request Co-Authored-By: Claude Opus 5.5 --- tests/test_repeated_runs_sample_fresh.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index 1c2be4dd..8c214e36 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -18,10 +18,10 @@ Fixtures count requests per repeat and, where a test asks for them, record the cache keys each repeat looks up and stores. -Seven tests send no request: the namespace's spelling, the two directory -guards, the response counter, the overlap guard, and the two that check the -namespace comes back (they replace the runner; the property test replaces -the cache object too). +Six test functions send no request: the namespace's spelling, the guard +against unrecorded files (each case), the response counter, the overlap +guard, and the two that check the namespace comes back (they replace the +runner; the property test replaces the cache object too). """ from __future__ import annotations From b4c461eec1cc5eb33bb4003a0c8640ace8196332 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 16:04:47 +0100 Subject: [PATCH 07/12] Refuse a runs directory where two files hold one provider response (review r2) Replace repeated_run.json, which recorded which repeats this command started, with a check of what the files hold. Every answered row records the id of the provider response behind it, and a cache replay returns the stored response with its id, so two CSV files in the directory holding the same model and response id hold one answer twice, whatever wrote them. The command runs the check over every CSV in the output directory (what analyze --runs-dir reads) before its first request and again after each repeat. A file with answered rows but no response id, or one it cannot read, is refused too. The record could be defeated by an older checkout replacing a listed file's rows, by files written while the command paused after its one-time scan, and by a stale write from a concurrent process; the check reads the directory as it is each time. Offline, with the namespace switch off on a merge with #275, all 48 cards replay repeat 1 into repeat 2 and every replay carries repeat 1's response id; with it on, no two repeats share an id. Co-Authored-By: Claude Opus 5.5 --- README.md | 17 ++- policybench/eval_no_tools.py | 130 +++++++++++--------- tests/test_eval_no_tools.py | 1 + tests/test_repeated_runs_sample_fresh.py | 147 ++++++++++++++++------- 4 files changed, 186 insertions(+), 109 deletions(-) diff --git a/README.md b/README.md index 4ea09ff3..6d506406 100644 --- a/README.md +++ b/README.md @@ -172,11 +172,18 @@ at a new directory. After each repeat the command prints how many provider responses and cache replays the repeat's rows record and, when it kept rows from an existing file, -how many of those the kept rows recorded when they were written. It records -each repeat in `repeated_run.json` beside the run files before the repeat -writes anything, and refuses an output directory holding a `run_*.csv` file -that the record does not list: nothing shows such a file was written under its -own cache namespace, so its rows may be replays of another repeat's. +how many of those the kept rows recorded when they were written. + +Before its first request and after each repeat, the command checks every CSV +file in the output directory, whoever wrote it (`analyze --runs-dir` reads +them all). Each answered row +records the id of the provider response behind it (`provider_response_id`, the +first one when its household took several requests), and a cache replay +returns the stored response with its id, so two files holding the same model +and response id hold one answer twice. The command then stops with +an error naming the files. It also stops at a file with answered rows but no +response id (files written before the column existed), which it cannot check, +and at a file it cannot read. Use a new output directory then. `policybench reference-outputs` writes PolicyEngine reference outputs, not administrative truth. It also writes `results/local/scenarios.csv`, and the eval diff --git a/policybench/eval_no_tools.py b/policybench/eval_no_tools.py index 18476241..24e1f340 100644 --- a/policybench/eval_no_tools.py +++ b/policybench/eval_no_tools.py @@ -4391,63 +4391,73 @@ def _response_sources( ) -# Written beside a repeated run's CSVs: the repeats this command started, -# each under its own cache namespace. -REPEATED_RUN_MARKER = "repeated_run.json" -_RECORDED_REPEATS_KEY = "repeats_with_own_cache_namespace" - - -def _recorded_repeats(output_path: Path) -> set[str]: - """The repeats ``repeated_run.json`` in ``output_path`` records.""" - marker = output_path / REPEATED_RUN_MARKER - if not marker.exists(): - return set() - try: - recorded = json.loads(marker.read_text(encoding="utf-8"))[_RECORDED_REPEATS_KEY] - if not isinstance(recorded, list): - raise TypeError(f"{_RECORDED_REPEATS_KEY} is not a list") - return {str(run_id) for run_id in recorded} - except (ValueError, KeyError, TypeError) as error: - raise ValueError( - f"{marker} cannot be read ({error}). Use a new output directory." - ) from error - - -def _refuse_unrecorded_repeat_files(output_path: Path, recorded: set[str]) -> None: - """Refuse a directory holding repeat files the marker does not record. - - Nothing shows such a file was written with its own cache namespace: an - earlier version of this command, under which every repeat shared one - namespace, or anything else may have written it, so its rows may be - replays of another repeat's. Resuming it, or analysing the directory, - would count it as an independent repeat. +# The files the check below reads: every CSV in the output directory, as +# ``load_repeated_predictions`` (``analyze --runs-dir``) does. +_RUNS_DIR_FILES = "*.csv" + + +def _refuse_shared_responses(output_path: Path) -> None: + """Refuse a directory where two CSV files hold the same provider response. + + Every row records the id of the first provider response its request + group got (``provider_response_id``), and a cache replay returns the + stored response with its id. A household's first request is built from + the same inputs in every repeat, so a repeat that could reach another + repeat's cache entries would replay that request, and its rows would carry + the other repeat's id. Two files holding the same model and response id + therefore hold one answer twice, and one of them is not an independent + repeat, whatever wrote it. An answered row without an id cannot be + checked (files written before the column existed), so a file holding one + is refused, as is a file that cannot be read. """ - unrecorded = sorted( - path.name for path in output_path.glob("run_*.csv") if path.stem not in recorded - ) - if unrecorded: + columns = {"model", "prediction", "provider_response_id"} + holders: dict[tuple[str, str], str] = {} + shared: dict[tuple[str, str], int] = {} + for path in sorted(output_path.glob(_RUNS_DIR_FILES)): + try: + frame = pd.read_csv(path, dtype=str, usecols=lambda name: name in columns) + except pd.errors.EmptyDataError: + continue + except (OSError, UnicodeDecodeError, pd.errors.ParserError) as error: + raise ValueError( + f"{path} cannot be read ({error}), so this command cannot check " + "that its rows are not another repeat's answers. Use a new " + "output directory." + ) from error + if frame.empty: + continue + ids = frame.get("provider_response_id", pd.Series(pd.NA, index=frame.index)) + answered = ( + frame["prediction"].notna() + if "prediction" in frame.columns + else pd.Series(True, index=frame.index) + ) + unchecked = int((answered & ids.isna()).sum()) + if unchecked: + raise ValueError( + f"{path} has {unchecked} answered rows without a provider " + "response id, so this command cannot check that they are not " + "another repeat's answers. Use a new output directory." + ) + models = frame.get("model", pd.Series("", index=frame.index)).fillna("") + for key in set(zip(models[ids.notna()], ids[ids.notna()])): + holder = holders.setdefault(key, path.name) + if holder != path.name: + pair = (holder, path.name) + shared[pair] = shared.get(pair, 0) + 1 + if shared: + pairs = "; ".join( + f"{first} and {second}: {count}" + for (first, second), count in sorted(shared.items()) + ) raise ValueError( - f"{output_path} holds repeat files that {REPEATED_RUN_MARKER} does " - f"not record as written under their own cache namespace " - f"({', '.join(unrecorded)}), so their rows may be replays of " - "another repeat's. Use a new output directory." + f"Repeat files in {output_path} hold the same provider responses " + f"(same model and provider_response_id; {pairs}), so one file of " + "each pair repeats the other's answers instead of asking again. Use " + "a new output directory." ) -def _record_repeat(output_path: Path, recorded: set[str], run_id: str) -> None: - """Add ``run_id`` to ``recorded`` and to the marker, before it writes.""" - if run_id in recorded: - return - recorded.add(run_id) - marker = output_path / REPEATED_RUN_MARKER - staging = marker.with_name(f"{marker.name}.tmp") - staging.write_text( - json.dumps({_RECORDED_REPEATS_KEY: sorted(recorded)}) + "\n", - encoding="utf-8", - ) - os.replace(staging, marker) - - def _rows_kept_on_resume( run_output_path: Path, scenarios: list[Scenario], @@ -4484,16 +4494,15 @@ def run_repeated_no_tools_eval( Each repeat runs under its own disk-cache namespace (``_OwnCacheNamespace``), so it never looks up another repeat's answers, - and a rerun on the same cache looks only under its own. Each repeat is - recorded in ``repeated_run.json`` before it writes, and a directory - holding a repeat file the record does not list raises ValueError before - any request. After each repeat, one line says where its rows' responses - came from, and how many of them it kept from an existing file. + and a rerun on the same cache looks only under its own. Before the first + request and after each repeat, a directory where two repeat files hold the + same provider response raises ValueError (``_refuse_shared_responses``). + After each repeat, one line says where its rows' responses came from, and + how many of them it kept from an existing file. """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True) - recorded = _recorded_repeats(output_path) - _refuse_unrecorded_repeat_files(output_path, recorded) + _refuse_shared_responses(output_path) frames = [] for run_index in range(repeats): @@ -4503,7 +4512,6 @@ def run_repeated_no_tools_eval( kept = _rows_kept_on_resume( run_output_path, scenarios, programs, include_explanations, single_output ) - _record_repeat(output_path, recorded, run_id) runner = run_no_tools_single_output_eval if single_output else run_no_tools_eval with _OwnCacheNamespace(run_id): frame = runner( @@ -4531,6 +4539,8 @@ def run_repeated_no_tools_eval( f"responses {kept_live}, cache replays {kept_replayed}" ) print(sources) + # Another writer may have changed the directory while this repeat ran. + _refuse_shared_responses(output_path) frames.append(frame) if not frames: diff --git a/tests/test_eval_no_tools.py b/tests/test_eval_no_tools.py index fe2b522f..e9b64f71 100644 --- a/tests/test_eval_no_tools.py +++ b/tests/test_eval_no_tools.py @@ -4612,6 +4612,7 @@ def fake_run(*args, **kwargs): "prediction": 123.0, "raw_response": "123", "error": None, + "provider_response_id": f"resp-{kwargs['run_id']}", } ] ) diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index 8c214e36..92a00153 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -18,10 +18,11 @@ Fixtures count requests per repeat and, where a test asks for them, record the cache keys each repeat looks up and stores. -Six test functions send no request: the namespace's spelling, the guard -against unrecorded files (each case), the response counter, the overlap -guard, and the two that check the namespace comes back (they replace the -runner; the property test replaces the cache object too). +Seven test functions send no request: the namespace's spelling, the check +of directories the command cannot vouch for (each case), the check's +accepted rows, the response counter, the overlap guard, and the two that +check the namespace comes back (they replace the runner; the property test +replaces the cache object too). """ from __future__ import annotations @@ -44,9 +45,9 @@ from policybench.eval_no_tools import ( EXPLANATION_FUNCTION_NAME, REASONING_EFFORT_OVERRIDE_ENV, - REPEATED_RUN_MARKER, _answer_contract_for_model, _OwnCacheNamespace, + _refuse_shared_responses, _repeat_cache_namespace, _response_sources, _uses_responses_api, @@ -772,7 +773,6 @@ def test_the_cli_command_asks_again_on_repeat_2(monkeypatch, sent_per_repeat, tm second = pd.read_csv(tmp_path / "runs" / "run_001.csv") assert second["cache_hit_calls"].sum() == 0 assert second["raw_response"].tolist() != first["raw_response"].tolist() - assert (tmp_path / "runs" / REPEATED_RUN_MARKER).exists() def test_a_rerun_into_the_same_directory_resumes_and_says_so( @@ -795,8 +795,6 @@ def test_a_rerun_into_the_same_directory_resumes_and_says_so( f"run_001: provider responses {one_repeat}, cache replays 0; of these, " f"kept from run_001.csv: provider responses {one_repeat}, cache replays 0\n" ) in out - record = json.loads((tmp_path / "runs" / REPEATED_RUN_MARKER).read_text()) - assert record == {"repeats_with_own_cache_namespace": ["run_000", "run_001"]} @pytest.mark.parametrize("left_by", ["fatal error", "infrastructure error"]) @@ -842,53 +840,98 @@ def test_a_resume_that_keeps_no_row_does_not_say_it_kept_any( assert "kept from" not in out -def test_a_repeat_file_the_marker_does_not_record_is_refused( - disk_cache, wire, sent_per_repeat, tmp_path +def _write_without_namespaces(runs, run_ids) -> None: + """Write repeat files as the command did before each repeat had its own + namespace: every repeat under the cache's one namespace.""" + for run_id in run_ids: + eval_no_tools.run_no_tools_eval( + [SCENARIO], + models={_name_of(OPUS): OPUS}, + programs=VARIABLES, + output_path=str(runs / f"{run_id}.csv"), + run_id=run_id, + ) + + +def test_a_directory_holding_one_response_twice_is_refused_before_any_request( + disk_cache, wire, tmp_path ): - """The marker does not vouch for a directory, only for the repeats it - lists: here a run without per-repeat namespaces, as an earlier version of - the command ran, adds a repeat file beside a recorded one.""" + """Two repeat files written under one namespace, as an earlier version of + the command wrote them: the second replayed the first.""" runs = tmp_path / "runs" - _run(OPUS, runs, repeats=1) - eval_no_tools.run_no_tools_eval( - [SCENARIO], - models={_name_of(OPUS): OPUS}, - programs=VARIABLES, - output_path=str(runs / "run_001.csv"), - run_id="run_001", - ) + runs.mkdir() + _write_without_namespaces(runs, ["run_000", "run_001"]) + first = pd.read_csv(runs / "run_000.csv") + second = pd.read_csv(runs / "run_001.csv") + assert second["cache_hit_calls"].sum() > 0 + assert set(second["provider_response_id"]) == set(first["provider_response_id"]) sent = len(wire) - record = (runs / REPEATED_RUN_MARKER).read_text() - with pytest.raises(ValueError, match=r"run_001\.csv.*Use a new output directory"): + with pytest.raises( + ValueError, match=r"run_000\.csv and run_001\.csv.*Use a new output directory" + ): _run(OPUS, runs, repeats=3) assert len(wire) == sent - assert (runs / REPEATED_RUN_MARKER).read_text() == record assert not (runs / "run_002.csv").exists() +def test_a_file_another_writer_adds_during_the_run_is_caught_after_the_repeat( + disk_cache, wire, monkeypatch, tmp_path +): + """Between two repeats, a run without per-repeat namespaces writes the + next two repeat files, the second replaying the first. The command keeps + the next file's rows, as a resume does, and refuses the directory once + that repeat ends, before the repeat after it sends anything.""" + runs = tmp_path / "runs" + real_kept = eval_no_tools._rows_kept_on_resume + sent_before_other_writer: list[int] = [] + + def kept(run_output_path, *args, **kwargs): + if run_output_path.name == "run_001.csv" and not sent_before_other_writer: + sent_before_other_writer.append(len(wire)) + _write_without_namespaces(runs, ["run_001", "run_002"]) + return real_kept(run_output_path, *args, **kwargs) + + monkeypatch.setattr(eval_no_tools, "_rows_kept_on_resume", kept) + + with pytest.raises( + ValueError, match=r"run_001\.csv and run_002\.csv.*Use a new output directory" + ): + _run(OPUS, runs, repeats=3) + + (before,) = sent_before_other_writer + assert before > 0 + # The other writer asked once, for run_001; run_002 replayed it. The + # command sent nothing for run_001, whose rows it kept, or for run_002. + assert len(wire) == 2 * before + + @pytest.mark.parametrize( - "marker", - [ - None, - '{"repeats_with_own_cache_namespace": ["run_000"]}', - '{"each_repeat_has_its_own_cache_namespace": true}', - '{"repeats_with_own_cache_namespace": "run_000"}', - "not json", - ], + "left", + ["no id column", "a blank id", "a file it cannot read", "one response twice"], ) -def test_repeat_files_without_a_record_are_refused_before_any_request( - marker, monkeypatch, tmp_path +def test_a_directory_the_command_cannot_check_is_refused_before_any_request( + left, monkeypatch, tmp_path ): - """A file the marker does not list, here one past the repeats asked for, - or a marker that cannot be read: the command sends nothing.""" runs = tmp_path / "runs" runs.mkdir() - (runs / "run_000.csv").write_text("model,scenario_id,variable,prediction\n") - (runs / "run_005.csv").write_text("model,scenario_id,variable,prediction\n") - if marker is not None: - (runs / REPEATED_RUN_MARKER).write_text(marker) + header = "model,scenario_id,variable,prediction,provider_response_id\n" + if left == "no id column": + (runs / "run_000.csv").write_text( + "model,scenario_id,variable,prediction\nm,h,snap,1.0\n" + ) + elif left == "a blank id": + (runs / "run_000.csv").write_text( + header + "m,h,snap,1.0,resp-1\nm,i,snap,2.0,\n" + ) + elif left == "a file it cannot read": + (runs / "run_003.csv").mkdir() + else: + # A file past the repeats asked for, or not named as a repeat, still + # counts: analyze --runs-dir reads every CSV in the directory. + (runs / "run_000.csv").write_text(header + "m,h,snap,1.0,resp-1\n") + (runs / "copy.csv").write_text(header + "m,h,snap,1.0,resp-1\n") called = [] monkeypatch.setattr( eval_no_tools, "run_no_tools_eval", lambda *a, **k: called.append(k) @@ -898,10 +941,26 @@ def test_repeat_files_without_a_record_are_refused_before_any_request( _run(OPUS, runs) assert not called - if marker is None: - assert not (runs / REPEATED_RUN_MARKER).exists() - else: - assert (runs / REPEATED_RUN_MARKER).read_text() == marker + + +def test_the_check_accepts_rows_that_share_no_response(tmp_path): + """Error rows carry no response id; the same id under two models is two + responses; rows of one request group share their id within one file; an + empty file and a header-only file hold nothing to check; a file that is + not a CSV is not read.""" + header = "model,scenario_id,variable,prediction,error,provider_response_id\n" + (tmp_path / "run_000.csv").write_text( + header + + "a,h,snap,1.0,,resp-1\n" + + "a,h,ssi,2.0,,resp-1\n" + + "a,i,snap,,litellm.Timeout: request timed out,\n" + ) + (tmp_path / "run_001.csv").write_text(header + "b,h,snap,1.0,,resp-1\n") + (tmp_path / "run_002.csv").write_text("") + (tmp_path / "run_003.csv").write_text("run_id\n") + (tmp_path / "run_000.csv.spend.jsonl").write_text('{"id": "resp-1"}\n') + + _refuse_shared_responses(tmp_path) def test_response_sources_counts_each_request_group_once(): From a6220c615074302406e73ddbffc49646d0abd6ee Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 16:06:02 +0100 Subject: [PATCH 08/12] Raise when the cache changes under a repeat; claim only what the namespace gives (review r2) The namespace is an attribute of the process-wide cache, so another evaluation in the same process while a repeat runs shares it, and an enable_cache() call during the repeat swaps in a cache with the base namespace. A repeat now raises RuntimeError when it ends to find litellm.cache replaced or its namespace changed (unless it is already raising), after putting the namespace back. The docstrings and README state the one-evaluation-per-process precondition the CLI meets. The docstring said a rerun "looks under the keys that repeat stored". It looks up under the namespace that repeat stored under; it replays only where LiteLLM computes the same key for the lookup as for the store, which a gemini/ tool request misses until its key is pinned (#275). A follow-up request is built from the answers before it, so a rerun rebuilds it only where those answers lead to the same request. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +++- policybench/eval_no_tools.py | 50 ++++++++++++---- tests/test_repeated_runs_sample_fresh.py | 72 +++++++++++++++++++++++- 3 files changed, 116 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 6d506406..4dbaa918 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,10 @@ policybench analyze --runs-dir results/local/no_tools/runs --output-dir results/ Each repeat asks the models again. The command keeps the LiteLLM disk cache on, but each repeat looks up and stores its answers under its own cache namespace (`repeat=run_000`, `repeat=run_001`, ...), so no repeat looks up another -repeat's answers, or those of an `eval-no-tools` run. +repeat's answers, or those of an `eval-no-tools` run. The namespace is set on +the cache of the whole Python process, which the command has to itself; code +that calls `run_repeated_no_tools_eval` must run no other evaluation in the +same process meanwhile. Running the command again reuses what each repeat already has. Into the same output directory, a repeat resumes from its CSV before it consults the cache. @@ -166,7 +169,11 @@ explanations are on), even if some of those rows hold no parsed answer; it asks again for the other households. With `--single-output` it keeps every row without an infrastructure error. Into a new output directory with the same cache directory, a repeat looks for its answers under its own namespace and -asks the model for those the cache does not find. To draw a new, independent +asks the model for those the cache does not find. A household's first request +is the same every time, so the cache finds its answer whenever LiteLLM +computes the same key for it again. A repair or explanation-only request is +built from the answers before it, so the cache finds its answer only when the +rebuilt request comes out the same. To draw a new, independent set of repeats, use a new output directory and point `POLICYBENCH_CACHE_DIR` at a new directory. diff --git a/policybench/eval_no_tools.py b/policybench/eval_no_tools.py index 24e1f340..b1ff37b6 100644 --- a/policybench/eval_no_tools.py +++ b/policybench/eval_no_tools.py @@ -4325,20 +4325,34 @@ class _OwnCacheNamespace: effort override (``_effort_cache_namespace``), is built from the attribute while the repeat runs, so it keeps the repeat. - So a repeat looks up and stores its answers under keys no other repeat - uses, and a rerun of the same repeat on the same cache looks under the - keys that repeat stored. Whether the rerun finds an answer there is the - cache's business: a request LiteLLM rewrites between its lookup and its - store never finds its answer, in a repeat or out of one. - - Repeats cannot overlap in one process: entering one while another runs - raises RuntimeError. Without a cache the namespace is left alone. + So a repeat looks up and stores its answers under its own namespace, + which no other repeat uses, and a rerun of the same repeat on the same + cache looks up under the namespace that repeat stored under. The rerun + replays an answer only if LiteLLM computes the same key for the rebuilt + request's lookup as it did for the original's store: a request LiteLLM + rewrites between its lookup and its store (a ``gemini/`` tool request + whose key the harness leaves to LiteLLM) never finds its answer, in a + repeat or out of one. A household's first request is rebuilt from the + same inputs every time. A follow-up request is built from the answers + before it (a repair round from the outputs they left out, an + explanation-only request from their values), so a rerun rebuilds the same + follow-up only where those answers lead to it again. + + The namespace is an attribute of the cache, which is process-wide, so a + repeat must be the only evaluation in its process (the CLI runs one): + any other request sent while a repeat runs uses the repeat's namespace. + Entering a repeat while another runs raises RuntimeError, and so does a + repeat that ends to find ``litellm.cache`` replaced or its namespace + changed, since its requests may then have used another namespace (unless + the repeat is already raising). Without a cache the namespace is left + alone. """ def __init__(self, run_id: str) -> None: self._run_id = run_id self._cache = None self._base: str | None = None + self._namespace: str | None = None def __enter__(self) -> None: if not _REPEAT_NAMESPACE_LOCK.acquire(blocking=False): @@ -4349,14 +4363,25 @@ def __enter__(self) -> None: self._cache = litellm.cache if self._cache is not None: self._base = self._cache.namespace - self._cache.namespace = _repeat_cache_namespace(self._base, self._run_id) + self._namespace = _repeat_cache_namespace(self._base, self._run_id) + self._cache.namespace = self._namespace - def __exit__(self, *_exc) -> None: + def __exit__(self, exc_type, *_exc) -> None: try: + changed = litellm.cache is not self._cache or ( + self._cache is not None and self._cache.namespace != self._namespace + ) if self._cache is not None: self._cache.namespace = self._base finally: _REPEAT_NAMESPACE_LOCK.release() + if changed and exc_type is None: + raise RuntimeError( + f"The disk cache was replaced, or its namespace changed, while " + f"repeat {self._run_id} ran, so its requests may not have used " + "its own namespace. Run nothing else in this process while a " + "repeat runs." + ) def _response_sources( @@ -4493,8 +4518,9 @@ def run_repeated_no_tools_eval( """Run repeated AI-alone evaluations, saving one artifact per run. Each repeat runs under its own disk-cache namespace - (``_OwnCacheNamespace``), so it never looks up another repeat's answers, - and a rerun on the same cache looks only under its own. Before the first + (``_OwnCacheNamespace``), so, with nothing else running in the process, + it never looks up another repeat's answers, and a rerun on the same cache + looks up only under its own namespace. Before the first request and after each repeat, a directory where two repeat files hold the same provider response raises ValueError (``_refuse_shared_responses``). After each repeat, one line says where its rows' responses came from, and diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index 92a00153..f4bf10cf 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -18,10 +18,11 @@ Fixtures count requests per repeat and, where a test asks for them, record the cache keys each repeat looks up and stores. -Seven test functions send no request: the namespace's spelling, the check +Nine test functions send no request: the namespace's spelling, the check of directories the command cannot vouch for (each case), the check's -accepted rows, the response counter, the overlap guard, and the two that -check the namespace comes back (they replace the runner; the property test +accepted rows, the response counter, the overlap guard, the two that check +a repeat raises when the cache changes under it, and the two that check the +namespace comes back (these four replace the runner; the property test replaces the cache object too). """ @@ -1035,6 +1036,71 @@ def test_repeats_cannot_overlap_in_one_process(disk_cache): assert disk_cache.namespace == base +def _one_row(run_id: str) -> pd.DataFrame: + return pd.DataFrame( + [ + { + "run_id": run_id, + "model": "a", + "scenario_id": SCENARIO.id, + "variable": "snap", + "live_calls": 0, + "cache_hit_calls": 0, + } + ] + ) + + +@pytest.mark.parametrize( + "change", ["cache replaced", "namespace changed", "cache turned on"] +) +def test_a_repeat_that_finds_the_cache_changed_raises(change, monkeypatch, tmp_path): + """Something else in the process replaced the cache, changed its + namespace, or turned a cache on while a repeat ran: the repeat raises when + it ends, puts back the namespace it changed, and lets a later repeat + start.""" + if change != "cache turned on": + enable_cache(str(tmp_path / "cache")) + original = litellm.cache + base = None if original is None else original.namespace + + def runner(*_args, run_id, **_kwargs): + if change == "namespace changed": + litellm.cache.namespace = "policybench:elsewhere" + else: + enable_cache(str(tmp_path / "cache")) + return _one_row(run_id) + + monkeypatch.setattr(eval_no_tools, "run_no_tools_eval", runner) + + with pytest.raises( + RuntimeError, match="replaced, or its namespace changed, while repeat run_000" + ): + _run(OPUS, tmp_path / "runs") + + if original is not None: + assert original.namespace == base + with _OwnCacheNamespace("run_001"): + pass + + +def test_a_failing_repeat_keeps_its_own_error_when_the_cache_changed( + disk_cache, monkeypatch, tmp_path +): + base = disk_cache.namespace + + def runner(*_args, run_id, **_kwargs): + enable_cache(str(tmp_path / "cache")) + raise RuntimeError("provider down") + + monkeypatch.setattr(eval_no_tools, "run_no_tools_eval", runner) + + with pytest.raises(RuntimeError, match="provider down"): + _run(OPUS, tmp_path / "runs") + + assert disk_cache.namespace == base + + def test_without_a_cache_every_repeat_asks(sent_per_repeat, tmp_path): assert litellm.cache is None From 72b38c23bed183522d5503567b4e70e9fa6c80c4 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 16:18:05 +0100 Subject: [PATCH 09/12] Tighten the repeat tests and the single-output resume wording (review r2 P2/P3) - The follow-up-path tests require two lookups and two stores in each repeat, and a rerun on a new cache object that sends nothing and returns the same answers, so dropping the store on any follow-up request fails. - The no-shared-answer test compares stub call numbers and provider response ids per repeat, so a chunked household sharing one call of several is caught. - A partial resume (one household kept, one asked again) checks the line's overall and kept counts apart. - The offline fixture restores the whole process environment, which LiteLLM can extend (TIKTOKEN_CACHE_DIR). - README: with --single-output the loader keeps rows only from a file with model, scenario_id, variable and prediction columns, and an explanation column when explanations are on. - Two helper docstrings now say what they check. Co-Authored-By: Claude Opus 5.5 --- README.md | 42 +++++---- tests/test_repeated_runs_sample_fresh.py | 115 +++++++++++++++++++---- 2 files changed, 121 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 4dbaa918..de78c49f 100644 --- a/README.md +++ b/README.md @@ -165,32 +165,34 @@ Running the command again reuses what each repeat already has. Into the same output directory, a repeat resumes from its CSV before it consults the cache. The batch runner keeps each household for which the file has a row for every requested output, with no infrastructure error (and an explanation column when -explanations are on), even if some of those rows hold no parsed answer; it -asks again for the other households. With `--single-output` it keeps every row -without an infrastructure error. Into a new output directory with the same -cache directory, a repeat looks for its answers under its own namespace and -asks the model for those the cache does not find. A household's first request -is the same every time, so the cache finds its answer whenever LiteLLM -computes the same key for it again. A repair or explanation-only request is -built from the answers before it, so the cache finds its answer only when the -rebuilt request comes out the same. To draw a new, independent -set of repeats, use a new output directory and point `POLICYBENCH_CACHE_DIR` -at a new directory. +explanations are on), even if some of those rows hold no parsed answer; it asks +again for the other households. With `--single-output` it keeps every row +without an infrastructure error, provided the file has `model`, `scenario_id`, +`variable` and `prediction` columns, and an explanation column when +explanations are on; otherwise it keeps none. Into a new output directory with +the same cache directory, a repeat looks for its answers under its own +namespace and asks the model for those the cache does not find. A household's +first request is the same every time, so the cache finds its answer whenever +LiteLLM computes the same key for it again. A repair or explanation-only +request is built from the answers before it, so the cache finds its answer only +when the rebuilt request comes out the same. To draw a new, independent set of +repeats, use a new output directory and point `POLICYBENCH_CACHE_DIR` at a new +directory. After each repeat the command prints how many provider responses and cache replays the repeat's rows record and, when it kept rows from an existing file, how many of those the kept rows recorded when they were written. Before its first request and after each repeat, the command checks every CSV -file in the output directory, whoever wrote it (`analyze --runs-dir` reads -them all). Each answered row -records the id of the provider response behind it (`provider_response_id`, the -first one when its household took several requests), and a cache replay -returns the stored response with its id, so two files holding the same model -and response id hold one answer twice. The command then stops with -an error naming the files. It also stops at a file with answered rows but no -response id (files written before the column existed), which it cannot check, -and at a file it cannot read. Use a new output directory then. +file in the output directory, whoever wrote it (`analyze --runs-dir` reads them +all). Each answered row records the id of the provider response behind it +(`provider_response_id`, the first one when its household took several +requests), and a cache replay returns the stored response with its id, so two +files holding the same model and response id hold one answer twice. The command +then stops with an error naming the files. It also stops at a file with +answered rows but no response id (files written before the column existed), +which it cannot check, and at a file it cannot read. Use a new output directory +then. `policybench reference-outputs` writes PolicyEngine reference outputs, not administrative truth. It also writes `results/local/scenarios.csv`, and the eval diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index f4bf10cf..56ffaa11 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -30,6 +30,7 @@ import json import os +import re import socket from types import SimpleNamespace @@ -64,6 +65,13 @@ adults=[Person(name="adult1", age=35, employment_income=18_000.0)], year=2026, ) +SECOND_SCENARIO = Scenario( + id="repeat_household_2", + state="CA", + filing_status="single", + adults=[Person(name="adult1", age=40, employment_income=30_000.0)], + year=2026, +) VARIABLES = ["snap", "ssi"] OPUS = "claude-opus-5-5" @@ -286,8 +294,11 @@ class _FollowUpAnswers: - ``explanation``: values with blank explanations; with no repair round left, the harness asks for the explanations alone. - Each household's answer depends only on the request, not on the order - requests arrive in, so a repeat that asks again takes the same path. + The path a request takes depends only on the request (its tool and the + outputs it asks for, and for ``escalation`` its budget), so a repeat that + asks again takes the same path. The values name the call that answered, + and the explanation-only answer restates the values the answer before it + gave. """ def __init__(self, path: str) -> None: @@ -350,7 +361,11 @@ def __call__(self, url_path: str, body: dict, call: int) -> dict: @pytest.fixture(autouse=True) def offline(monkeypatch): - """No key, no socket, no sensitivity knob, one attempt per request.""" + """No key, no socket, no sensitivity knob, one attempt per request, and + the process environment as it was afterwards (LiteLLM can set variables + of its own, such as ``TIKTOKEN_CACHE_DIR`` on its first Anthropic + request).""" + environment = dict(os.environ) def refuse(*_args, **_kwargs): raise AssertionError("a test tried to open a socket") @@ -374,6 +389,9 @@ def refuse(*_args, **_kwargs): litellm.utils, "callback_list", list(litellm.utils.callback_list or []) ) monkeypatch.setattr(litellm, "cache", None) + yield + os.environ.clear() + os.environ.update(environment) @pytest.fixture(autouse=True) @@ -499,7 +517,7 @@ def _raw(frame: pd.DataFrame, run_id: str) -> list[str]: def _assert_answered(frame: pd.DataFrame) -> None: - """The stub's answers parsed, so no repair round ran.""" + """Every row ended with a parsed answer and no error.""" assert frame["error"].isna().all(), frame["error"].dropna().iloc[0] assert frame["prediction"].notna().all() @@ -610,10 +628,21 @@ def test_a_follow_up_request_asks_again_under_its_repeats_namespace( assert second["live_calls"].sum() == 2 assert second["cache_hit_calls"].sum() == 0 assert set(_raw(frame, "run_001")).isdisjoint(_raw(frame, "run_000")) + assert set(keys_per_repeat) == {"run_000", "run_001"} for run_id, used in keys_per_repeat.items(): - assert sum(kind == "lookup" for kind, _ in used) == 2, run_id + kinds = [kind for kind, _ in used] + assert kinds.count("lookup") == 2 and kinds.count("store") == 2, run_id prefix = f"{_repeat_cache_namespace(base, run_id)}:" assert all(key.startswith(prefix) for _, key in used), run_id + # A rerun on a new cache object, into a new output directory, finds both + # requests of each repeat: the first is rebuilt from the same inputs, and + # the follow-up from the replayed answer. + sent_per_repeat.clear() + enable_cache(str(tmp_path / "cache")) + again = _run(ANTHROPIC_TOOL, tmp_path / "again") + assert sent_per_repeat == {"run_000": 0, "run_001": 0} + for run_id in ("run_000", "run_001"): + assert _raw(again, run_id) == _raw(frame, run_id) def _a_rebuilt_request_replays( @@ -713,24 +742,36 @@ def test_no_repeat_ever_returns_another_repeats_responses( model_id, disk_cache, wire, tmp_path ): """Across a run and a rerun on the same cache, an answer only ever comes - back under the run id that first got it.""" + back under the run id that first got it: no stub call, and no provider + response id, appears under two run ids (a household whose answer + combines several calls is checked call by call).""" first = _run(model_id, tmp_path / "first") again = _run(model_id, tmp_path / "again", repeats=3) - answers = { - (label, run_id): set(_raw(frame, run_id)) + held = { + (label, run_id): ( + { + number + for text in _raw(frame, run_id) + for number in re.findall(r"Call (\d+)\.", str(text)) + }, + set(frame[frame["run_id"] == run_id]["provider_response_id"].dropna()), + ) for label, frame in (("first", first), ("again", again)) for run_id in sorted(set(frame["run_id"])) } - assert len(answers) == 5 - assert all("value" in text for raw in answers.values() for text in raw) - for (label, run_id), raw in answers.items(): - for (other_label, other_id), other in answers.items(): + assert len(held) == 5 + assert all(calls and ids for calls, ids in held.values()) + for (label, run_id), (calls, ids) in held.items(): + for (other_label, other_id), (other_calls, other_ids) in held.items(): if other_id != run_id: - shared = raw & other - assert not shared, ( - f"{label} {run_id} returned {len(shared)} of " - f"{other_label} {other_id}'s responses" + assert not calls & other_calls, ( + f"{label} {run_id} holds stub calls {sorted(calls & other_calls)} " + f"of {other_label} {other_id}" + ) + assert not ids & other_ids, ( + f"{label} {run_id} holds responses {sorted(ids & other_ids)} " + f"of {other_label} {other_id}" ) @@ -841,6 +882,48 @@ def test_a_resume_that_keeps_no_row_does_not_say_it_kept_any( assert "kept from" not in out +def test_a_partial_resume_counts_kept_and_new_rows_apart( + disk_cache, sent_per_repeat, tmp_path, capsys +): + """One household kept from the file, the other asked again: the line's + totals cover both households, and its kept counts the kept one only.""" + runs = tmp_path / "runs" + + def run() -> pd.DataFrame: + return run_repeated_no_tools_eval( + [SCENARIO, SECOND_SCENARIO], + repeats=1, + output_dir=str(runs), + models={_name_of(OPUS): OPUS}, + programs=VARIABLES, + ) + + run() + both = sent_per_repeat["run_000"] + one = both // 2 + assert one > 0 and both == 2 * one + rows = pd.read_csv(runs / "run_000.csv") + rows["error"] = rows["error"].astype(object) + rows.loc[rows["scenario_id"] == SECOND_SCENARIO.id, "error"] = ( + "litellm.Timeout: request timed out" + ) + rows.to_csv(runs / "run_000.csv", index=False) + sent_per_repeat.clear() + capsys.readouterr() + # A new cache directory, so the second household is asked again rather + # than replayed. + enable_cache(str(tmp_path / "other-cache")) + + again = run() + + _assert_answered(again) + assert sent_per_repeat == {"run_000": one} + assert ( + f"run_000: provider responses {both}, cache replays 0; of these, kept " + f"from run_000.csv: provider responses {one}, cache replays 0\n" + ) in capsys.readouterr().out + + def _write_without_namespaces(runs, run_ids) -> None: """Write repeat files as the command did before each repeat had its own namespace: every repeat under the cache's one namespace.""" From d8c00621a85bb46b0792d5fe6b46e813d48e2e78 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 16:39:06 +0100 Subject: [PATCH 10/12] Pin the last-repeat check and replayed ids; narrow the docs' claims The other-writer test now also covers a file written while the last repeat runs, and pins exact request counts. The rerun test checks that a replay keeps the original response id on every provider path. The accept test leaves a CSV that would be refused under a name the check does not read. README and docstrings say what the check sees (each request group's first id) and when the cache finds a rebuilt first-round request. Co-Authored-By: Claude Opus 5.5 --- README.md | 34 +++++++----- policybench/eval_no_tools.py | 68 +++++++++++++++--------- tests/test_repeated_runs_sample_fresh.py | 59 ++++++++++++++------ 3 files changed, 104 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index de78c49f..84d0d625 100644 --- a/README.md +++ b/README.md @@ -172,12 +172,15 @@ without an infrastructure error, provided the file has `model`, `scenario_id`, explanations are on; otherwise it keeps none. Into a new output directory with the same cache directory, a repeat looks for its answers under its own namespace and asks the model for those the cache does not find. A household's -first request is the same every time, so the cache finds its answer whenever -LiteLLM computes the same key for it again. A repair or explanation-only -request is built from the answers before it, so the cache finds its answer only -when the rebuilt request comes out the same. To draw a new, independent set of -repeats, use a new output directory and point `POLICYBENCH_CACHE_DIR` at a new -directory. +first-round requests (its first request, or each explanation chunk) are the +same every time, so the cache finds their answers when LiteLLM computes the +same key for the rebuilt request's lookup as for the original's store (not so +for a `gemini/` tool request unless the harness pins its key) and the entry is +still there (LiteLLM's disk cache drops the oldest entries past 1 GiB). A +repair or explanation-only request is built from the answers before it, so the +cache finds its answer only when the rebuilt request comes out the same. To +draw a new, independent set of repeats, use a new output directory and point +`POLICYBENCH_CACHE_DIR` at a new directory. After each repeat the command prints how many provider responses and cache replays the repeat's rows record and, when it kept rows from an existing file, @@ -185,14 +188,17 @@ how many of those the kept rows recorded when they were written. Before its first request and after each repeat, the command checks every CSV file in the output directory, whoever wrote it (`analyze --runs-dir` reads them -all). Each answered row records the id of the provider response behind it -(`provider_response_id`, the first one when its household took several -requests), and a cache replay returns the stored response with its id, so two -files holding the same model and response id hold one answer twice. The command -then stops with an error naming the files. It also stops at a file with -answered rows but no response id (files written before the column existed), -which it cannot check, and at a file it cannot read. Use a new output directory -then. +all). Each answered row records a response id (`provider_response_id`: the +first of its request group, which is a household, or one of its outputs with +`--single-output`; the provider's id, or one LiteLLM generated when the +provider gave none), and a cache replay returns the stored response with its +id, so two files holding the same model and response id hold one answer twice. +The command then stops with an error naming the files. It also stops at a file +with answered rows but no response id (written before the column was added, or +cut short by an interrupted write), which it cannot check, and at a file it +cannot read. Use a new output directory then. The check sees only each group's +first id, so a household whose first explanation chunk got no response in one +file could share later chunks with another file unseen. `policybench reference-outputs` writes PolicyEngine reference outputs, not administrative truth. It also writes `results/local/scenarios.csv`, and the eval diff --git a/policybench/eval_no_tools.py b/policybench/eval_no_tools.py index b1ff37b6..8f0d45e1 100644 --- a/policybench/eval_no_tools.py +++ b/policybench/eval_no_tools.py @@ -4326,17 +4326,20 @@ class _OwnCacheNamespace: while the repeat runs, so it keeps the repeat. So a repeat looks up and stores its answers under its own namespace, - which no other repeat uses, and a rerun of the same repeat on the same - cache looks up under the namespace that repeat stored under. The rerun + which no other repeat of its set uses, and a rerun of the same repeat on + the same cache looks up under the namespace that repeat stored under. (A + second set run on the same cache directory shares the first set's + namespaces repeat by repeat; that is what lets a rerun replay.) The rerun replays an answer only if LiteLLM computes the same key for the rebuilt - request's lookup as it did for the original's store: a request LiteLLM - rewrites between its lookup and its store (a ``gemini/`` tool request - whose key the harness leaves to LiteLLM) never finds its answer, in a - repeat or out of one. A household's first request is rebuilt from the - same inputs every time. A follow-up request is built from the answers - before it (a repair round from the outputs they left out, an - explanation-only request from their values), so a rerun rebuilds the same - follow-up only where those answers lead to it again. + request's lookup as it did for the original's store: a freshly built + request that LiteLLM rewrites between its lookup and its store (a + ``gemini/`` tool request whose key the harness leaves to LiteLLM) does + not find its answer, in a repeat or out of one. A household's + first-round requests (its first request, or each explanation chunk) are + rebuilt from the same inputs every time. A follow-up request is built + from the answers before it (a repair round from the outputs they left + out, an explanation-only request from their values), so a rerun rebuilds + the same follow-up only where those answers lead to it again. The namespace is an attribute of the cache, which is process-wide, so a repeat must be the only evaluation in its process (the CLI runs one): @@ -4424,16 +4427,23 @@ def _response_sources( def _refuse_shared_responses(output_path: Path) -> None: """Refuse a directory where two CSV files hold the same provider response. - Every row records the id of the first provider response its request - group got (``provider_response_id``), and a cache replay returns the - stored response with its id. A household's first request is built from - the same inputs in every repeat, so a repeat that could reach another - repeat's cache entries would replay that request, and its rows would carry - the other repeat's id. Two files holding the same model and response id - therefore hold one answer twice, and one of them is not an independent - repeat, whatever wrote it. An answered row without an id cannot be - checked (files written before the column existed), so a file holding one - is refused, as is a file that cannot be read. + Each answered row records ``provider_response_id``: the first id among + the responses its request group got (a household, or one of its outputs + with ``single_output``), as LiteLLM recorded it (the provider's id, or + one LiteLLM generated when the provider gave none). A cache replay + returns the stored response with its id. A group's first-round requests + are built from the same inputs in every repeat, so a repeat that could + reach another repeat's cache entries would replay them, and its rows + would carry the other repeat's id. Two files holding the same model and + response id therefore hold one answer twice, whatever wrote them. The + check sees only that first id: a household whose first explanation chunk + got no response in one file can share later chunks with another file + unseen. + + A row that holds an answer (or may: the file has no prediction column) + but no id cannot be checked, so a file holding one is refused; code from + before the column was added (c7bf2db0), or a write cut short, leaves such + rows. So is a file that cannot be read. """ columns = {"model", "prediction", "provider_response_id"} holders: dict[tuple[str, str], str] = {} @@ -4459,8 +4469,13 @@ def _refuse_shared_responses(output_path: Path) -> None: ) unchecked = int((answered & ids.isna()).sum()) if unchecked: + hold = ( + "hold an answer" + if "prediction" in frame.columns + else "may hold an answer (the file has no prediction column)" + ) raise ValueError( - f"{path} has {unchecked} answered rows without a provider " + f"{path} has {unchecked} rows that {hold} but no provider " "response id, so this command cannot check that they are not " "another repeat's answers. Use a new output directory." ) @@ -4476,9 +4491,9 @@ def _refuse_shared_responses(output_path: Path) -> None: for (first, second), count in sorted(shared.items()) ) raise ValueError( - f"Repeat files in {output_path} hold the same provider responses " - f"(same model and provider_response_id; {pairs}), so one file of " - "each pair repeats the other's answers instead of asking again. Use " + f"CSV files in {output_path} hold the same provider responses " + f"(same model and provider_response_id; {pairs}), so each pair " + "holds one answer twice and cannot be two independent repeats. Use " "a new output directory." ) @@ -4521,8 +4536,9 @@ def run_repeated_no_tools_eval( (``_OwnCacheNamespace``), so, with nothing else running in the process, it never looks up another repeat's answers, and a rerun on the same cache looks up only under its own namespace. Before the first - request and after each repeat, a directory where two repeat files hold the - same provider response raises ValueError (``_refuse_shared_responses``). + request and after each repeat, a directory where two CSV files hold the + same provider response, or a file holds an answer without an id or cannot + be read, raises ValueError (``_refuse_shared_responses``). After each repeat, one line says where its rows' responses came from, and how many of them it kept from an existing file. """ diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index 56ffaa11..26096f53 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -731,6 +731,12 @@ def test_a_rerun_replays_each_repeats_own_responses( if replays: for run_id in ("run_000", "run_001"): assert _raw(again, run_id) == _raw(first, run_id) + # The directory check relies on a replay keeping the original + # response's id. + assert ( + again[again["run_id"] == run_id]["provider_response_id"].tolist() + == first[first["run_id"] == run_id]["provider_response_id"].tolist() + ) replayed = _calls(again, run_id) assert replayed["live_calls"].sum() == 0 assert replayed["cache_hit_calls"].sum() == one_repeat @@ -960,21 +966,29 @@ def test_a_directory_holding_one_response_twice_is_refused_before_any_request( assert not (runs / "run_002.csv").exists() +@pytest.mark.parametrize("when", ["between repeats", "during the last repeat"]) def test_a_file_another_writer_adds_during_the_run_is_caught_after_the_repeat( - disk_cache, wire, monkeypatch, tmp_path + when, disk_cache, wire, monkeypatch, tmp_path ): - """Between two repeats, a run without per-repeat namespaces writes the - next two repeat files, the second replaying the first. The command keeps - the next file's rows, as a resume does, and refuses the directory once - that repeat ends, before the repeat after it sends anything.""" + """While the command runs, a run without per-repeat namespaces writes two + repeat files, the second replaying the first: between repeats (the + command then keeps the next file's rows, as a resume does), or just before + the command's last repeat sends its request. The command refuses the + directory once that repeat ends, before any later repeat sends + anything.""" runs = tmp_path / "runs" + repeats, written, hook = { + "between repeats": (3, ["run_001", "run_002"], "run_001.csv"), + "during the last repeat": (1, ["run_001", "run_002"], "run_000.csv"), + }[when] real_kept = eval_no_tools._rows_kept_on_resume - sent_before_other_writer: list[int] = [] + sent: list[tuple[int, int]] = [] def kept(run_output_path, *args, **kwargs): - if run_output_path.name == "run_001.csv" and not sent_before_other_writer: - sent_before_other_writer.append(len(wire)) - _write_without_namespaces(runs, ["run_001", "run_002"]) + if run_output_path.name == hook and not sent: + before = len(wire) + _write_without_namespaces(runs, written) + sent.append((before, len(wire))) return real_kept(run_output_path, *args, **kwargs) monkeypatch.setattr(eval_no_tools, "_rows_kept_on_resume", kept) @@ -982,13 +996,22 @@ def kept(run_output_path, *args, **kwargs): with pytest.raises( ValueError, match=r"run_001\.csv and run_002\.csv.*Use a new output directory" ): - _run(OPUS, runs, repeats=3) - - (before,) = sent_before_other_writer - assert before > 0 - # The other writer asked once, for run_001; run_002 replayed it. The - # command sent nothing for run_001, whose rows it kept, or for run_002. - assert len(wire) == 2 * before + _run(OPUS, runs, repeats=repeats) + + ((before, after),) = sent + # The other writer asked once, for run_001, and run_002 replayed it. + other_writer = after - before + assert other_writer > 0 + if when == "between repeats": + # run_000 asked as often as the other writer did. The command sent + # nothing for run_001, whose rows it kept, or for run_002. + assert before == other_writer + assert len(wire) == after + else: + # The command's only repeat asked under its own namespace, as often + # as the other writer did. + assert before == 0 + assert len(wire) == 2 * other_writer @pytest.mark.parametrize( @@ -1042,7 +1065,9 @@ def test_the_check_accepts_rows_that_share_no_response(tmp_path): (tmp_path / "run_001.csv").write_text(header + "b,h,snap,1.0,,resp-1\n") (tmp_path / "run_002.csv").write_text("") (tmp_path / "run_003.csv").write_text("run_id\n") - (tmp_path / "run_000.csv.spend.jsonl").write_text('{"id": "resp-1"}\n') + # CSV text in a file not named *.csv, sharing run_000's response: read, + # it would be refused. + (tmp_path / "run_000.csv.bak").write_text(header + "a,h,snap,1.0,,resp-1\n") _refuse_shared_responses(tmp_path) From ecfb1118a0de395fe3a6756e36b67cc8de124f6a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 17:34:20 +0100 Subject: [PATCH 11/12] Read the spend ledgers in the directory check; harden the repeat's exit (review r3) - The directory check adds every response each CSV file's spend ledger records, replays included, under the model id the ledger records, to the rows' first response ids, which it now counts under the row's model name and its model id. It finds a file that replayed another's explanation chunks in another order, and one model under two names. A missing or unreadable ledger adds nothing (review r3: both-chunks and display-name regressions, P1 2). - The check and the resume reader read a response id as written, so an id such as "NA" is not taken for a missing value (review r3, false refusal). - A repeat whose cache lost its namespace attribute puts it back and keeps a failing runner's error; the cache-changed error names the repeat's file to delete before a rerun (review r3: exit masking, P1 5). - Docstrings, README: repeats build the same first-round requests (P1 1); enable_cache() and assigning litellm.cache join the process precondition (P1 5); the check reads the directory as it is when it runs, and a file written while it reads or after the last check is not checked (P1 3). Co-Authored-By: Claude Opus 5.5 --- README.md | 34 +++-- policybench/eval_no_tools.py | 187 ++++++++++++++++------- tests/test_repeated_runs_sample_fresh.py | 156 ++++++++++++++++++- 3 files changed, 303 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index 84d0d625..674abee8 100644 --- a/README.md +++ b/README.md @@ -159,7 +159,10 @@ but each repeat looks up and stores its answers under its own cache namespace repeat's answers, or those of an `eval-no-tools` run. The namespace is set on the cache of the whole Python process, which the command has to itself; code that calls `run_repeated_no_tools_eval` must run no other evaluation in the -same process meanwhile. +same process meanwhile, and must not call `enable_cache()` or assign +`litellm.cache` while a repeat runs. A repeat that ends to find the cache +replaced or its namespace changed raises an error naming its file, which a +rerun into the same directory would otherwise keep. Running the command again reuses what each repeat already has. Into the same output directory, a repeat resumes from its CSV before it consults the cache. @@ -187,18 +190,23 @@ replays the repeat's rows record and, when it kept rows from an existing file, how many of those the kept rows recorded when they were written. Before its first request and after each repeat, the command checks every CSV -file in the output directory, whoever wrote it (`analyze --runs-dir` reads them -all). Each answered row records a response id (`provider_response_id`: the -first of its request group, which is a household, or one of its outputs with -`--single-output`; the provider's id, or one LiteLLM generated when the -provider gave none), and a cache replay returns the stored response with its -id, so two files holding the same model and response id hold one answer twice. -The command then stops with an error naming the files. It also stops at a file -with answered rows but no response id (written before the column was added, or -cut short by an interrupted write), which it cannot check, and at a file it -cannot read. Use a new output directory then. The check sees only each group's -first id, so a household whose first explanation chunk got no response in one -file could share later chunks with another file unseen. +file then in the output directory, whoever wrote it (`analyze --runs-dir` reads +them all). A cache replay returns the stored response with its id (the +provider's, or one LiteLLM generated when the provider gave none), so two files +holding the same model and response id hold one answer twice, and the command +then stops with an error naming the files. A file's responses are the +`provider_response_id` of its answered rows (the first response of each request +group: a household, or one of its outputs with `--single-output`) and every +response its spend ledger (`run_000.csv.spend.jsonl`, ...) records, replays +included; the model is the model's name in the file, or the model id the ledger +records. It also stops at a file with answered rows but no response id (written +before the column was added, or cut short by an interrupted write), which it +cannot check, and at a CSV file it cannot read. Use a new output directory +then. Without a readable ledger the check sees only each request group's first +response under the file's model name, so a replayed later response, or one +model under two names, can go unseen. The check reads the directory as it is +when it runs: a file written while it reads, or after the last check, is not +checked, so run nothing else into the output directory while the command runs. `policybench reference-outputs` writes PolicyEngine reference outputs, not administrative truth. It also writes `results/local/scenarios.csv`, and the eval diff --git a/policybench/eval_no_tools.py b/policybench/eval_no_tools.py index 8f0d45e1..1741be5b 100644 --- a/policybench/eval_no_tools.py +++ b/policybench/eval_no_tools.py @@ -3476,11 +3476,23 @@ def _output_metadata_path(output_path: str | None) -> Path | None: return Path(f"{output_path}.meta.json") +def _response_id_or_none(value: str) -> str | None: + """A response id read from a CSV cell, kept as written. + + An id such as ``NA`` or ``null`` is an id; only an empty cell is none. + """ + return value or None + + +# Read a CSV's response ids as written rather than as pandas' missing values. +_RESPONSE_ID_CONVERTERS = {"provider_response_id": _response_id_or_none} + + def _read_existing_output(path: Path) -> pd.DataFrame | None: if not path.exists() or path.stat().st_size == 0: return None try: - return pd.read_csv(path) + return pd.read_csv(path, converters=_RESPONSE_ID_CONVERTERS) except pd.errors.EmptyDataError: return None @@ -4309,21 +4321,24 @@ def _repeat_cache_namespace(base: str | None, run_id: str) -> str: # Held while a repeat runs. The cache's namespace is process-wide, so two # repeats running at once in one process would share it. _REPEAT_NAMESPACE_LOCK = threading.Lock() +# What a repeat finds when something removed the cache's namespace attribute. +_NO_NAMESPACE = object() class _OwnCacheNamespace: """Give one repeat its own LiteLLM disk-cache namespace while it runs. - Every repeat builds the same requests, and LiteLLM keys its disk cache on - the request, so without this the cache the CLI turns on can answer - repeats 2..N with repeat 1's responses. LiteLLM prefixes each key it - computes, for the lookup and for the store, with the cache's - ``namespace`` attribute, read on each call (``Cache._add_namespace_to_cache_key`` - in LiteLLM 1.95.0), unless the request names its own namespace (in - ``cache`` or ``metadata["redis_namespace"]``) or brings its own - ``cache_key``. The one namespace the harness puts on a request, for an - effort override (``_effort_cache_namespace``), is built from the attribute - while the repeat runs, so it keeps the repeat. + Every repeat builds the same first-round requests from the same inputs, + and LiteLLM keys its disk cache on the request, so without this the cache + the CLI turns on can answer repeats 2..N with repeat 1's responses. + LiteLLM prefixes each key it computes, for the lookup and for the store, + with the cache's ``namespace`` attribute, read on each call + (``Cache._add_namespace_to_cache_key`` in LiteLLM 1.95.0), unless the + request names its own namespace (in ``cache`` or + ``metadata["redis_namespace"]``) or brings its own ``cache_key``. The one + namespace the harness puts on a request, for an effort override + (``_effort_cache_namespace``), is built from the attribute while the + repeat runs, so it keeps the repeat. So a repeat looks up and stores its answers under its own namespace, which no other repeat of its set uses, and a rerun of the same repeat on @@ -4342,17 +4357,22 @@ class _OwnCacheNamespace: the same follow-up only where those answers lead to it again. The namespace is an attribute of the cache, which is process-wide, so a - repeat must be the only evaluation in its process (the CLI runs one): - any other request sent while a repeat runs uses the repeat's namespace. - Entering a repeat while another runs raises RuntimeError, and so does a - repeat that ends to find ``litellm.cache`` replaced or its namespace - changed, since its requests may then have used another namespace (unless - the repeat is already raising). Without a cache the namespace is left - alone. + repeat must be the only evaluation in its process (the CLI runs one), + and nothing may call ``enable_cache()`` or assign ``litellm.cache`` while + it runs: any other request sent while a repeat runs uses the repeat's + namespace, and a replaced cache gives the repeat's later requests + another namespace. Entering a repeat while another runs raises + RuntimeError. A repeat that ends to find ``litellm.cache`` replaced, or + its namespace changed or removed, puts the namespace back and raises + RuntimeError naming ``output_name``, whose rows may hold answers looked + up under another namespace and which a rerun into the same directory + would keep (unless the repeat is already raising). The check runs only + when the repeat ends. Without a cache the namespace is left alone. """ - def __init__(self, run_id: str) -> None: + def __init__(self, run_id: str, output_name: str | None = None) -> None: self._run_id = run_id + self._output_name = output_name self._cache = None self._base: str | None = None self._namespace: str | None = None @@ -4371,19 +4391,27 @@ def __enter__(self) -> None: def __exit__(self, exc_type, *_exc) -> None: try: - changed = litellm.cache is not self._cache or ( - self._cache is not None and self._cache.namespace != self._namespace - ) + changed = litellm.cache is not self._cache if self._cache is not None: + found = getattr(self._cache, "namespace", _NO_NAMESPACE) self._cache.namespace = self._base + changed = changed or found != self._namespace finally: _REPEAT_NAMESPACE_LOCK.release() if changed and exc_type is None: + delete = ( + f" Delete {self._output_name} before running the command into " + "this directory again: a rerun would keep its rows, which may " + "hold answers looked up under another namespace." + if self._output_name + else "" + ) raise RuntimeError( - f"The disk cache was replaced, or its namespace changed, while " + "The disk cache was replaced, or its namespace changed, while " f"repeat {self._run_id} ran, so its requests may not have used " - "its own namespace. Run nothing else in this process while a " - "repeat runs." + f"its own namespace.{delete} Run nothing else in this process " + "while a repeat runs, and do not call enable_cache() or assign " + "litellm.cache." ) @@ -4424,33 +4452,76 @@ def _response_sources( _RUNS_DIR_FILES = "*.csv" +def _ledger_responses(csv_path: Path) -> tuple[set[tuple[str, str]], dict[str, str]]: + """The responses a CSV file's spend ledger records, and its model ids. + + Returns the (model id, response id) pairs of every request the ledger + records a response for, replays included, and the model id it records + for each model name the file's rows use. A ledger that is absent, cannot + be read, or lost a record records less; it never adds a pair the file's + requests did not get. + """ + try: + records = read_spend_ledger(spend_ledger_path(csv_path)) + except (OSError, UnicodeDecodeError): + return set(), {} + responses: set[tuple[str, str]] = set() + model_ids: dict[str, str] = {} + for record in records: + name = record.get("model") + model_id = record.get("model_id") or name + if not isinstance(model_id, str) or not model_id: + continue + if isinstance(name, str) and name: + model_ids.setdefault(name, model_id) + response_id = record.get("provider_response_id") + if isinstance(response_id, str) and response_id: + responses.add((model_id, response_id)) + return responses, model_ids + + def _refuse_shared_responses(output_path: Path) -> None: """Refuse a directory where two CSV files hold the same provider response. - Each answered row records ``provider_response_id``: the first id among - the responses its request group got (a household, or one of its outputs - with ``single_output``), as LiteLLM recorded it (the provider's id, or - one LiteLLM generated when the provider gave none). A cache replay - returns the stored response with its id. A group's first-round requests - are built from the same inputs in every repeat, so a repeat that could - reach another repeat's cache entries would replay them, and its rows - would carry the other repeat's id. Two files holding the same model and - response id therefore hold one answer twice, whatever wrote them. The - check sees only that first id: a household whose first explanation chunk - got no response in one file can share later chunks with another file + A response is a model and a response id (the provider's id, or one + LiteLLM generated when the provider gave none), and a cache replay + returns the stored response with its id. So two files that hold the same + model and response id hold one answer twice, whatever wrote them. Each + file's responses are: + + - the ``provider_response_id`` of its answered rows: the first id among + the responses a row's request group got (a household, or one of its + outputs with ``single_output``); + - every response its spend ledger (``.spend.jsonl``) records, for + each request of the file, replays included, written by this code and + by the code since ea67093d. + + A row's response counts under its model name and under its model id: + the one the ledger records for the name, else the one ``MODELS`` gives + it, else the name. A ledger's response counts under the model id it + records. So the check finds every pair the CSV rows alone would show, + and more. Without a readable ledger it sees only each request group's + first id, so a replayed later response (a later explanation chunk, or a + follow-up), or one model under two names ``MODELS`` does not know, goes unseen. A row that holds an answer (or may: the file has no prediction column) but no id cannot be checked, so a file holding one is refused; code from before the column was added (c7bf2db0), or a write cut short, leaves such - rows. So is a file that cannot be read. + rows. So is a CSV file that cannot be read. The check reads the + directory as it is when it runs. """ columns = {"model", "prediction", "provider_response_id"} holders: dict[tuple[str, str], str] = {} - shared: dict[tuple[str, str], int] = {} + shared: dict[tuple[str, str], set[str]] = {} for path in sorted(output_path.glob(_RUNS_DIR_FILES)): try: - frame = pd.read_csv(path, dtype=str, usecols=lambda name: name in columns) + frame = pd.read_csv( + path, + dtype={"model": str, "prediction": str}, + usecols=lambda name: name in columns, + converters=_RESPONSE_ID_CONVERTERS, + ) except pd.errors.EmptyDataError: continue except (OSError, UnicodeDecodeError, pd.errors.ParserError) as error: @@ -4479,22 +4550,28 @@ def _refuse_shared_responses(output_path: Path) -> None: "response id, so this command cannot check that they are not " "another repeat's answers. Use a new output directory." ) - models = frame.get("model", pd.Series("", index=frame.index)).fillna("") - for key in set(zip(models[ids.notna()], ids[ids.notna()])): + responses, model_ids = _ledger_responses(path) + names = frame.get("model", pd.Series("", index=frame.index)).fillna("") + for name, response_id in zip(names[ids.notna()], ids[ids.notna()]): + # Under the name too, so files that agree on a name match whatever + # their ledgers record. + responses.add((name, response_id)) + model = model_ids.get(name) or MODELS.get(name) or name + responses.add((model, response_id)) + for key in responses: holder = holders.setdefault(key, path.name) if holder != path.name: - pair = (holder, path.name) - shared[pair] = shared.get(pair, 0) + 1 + shared.setdefault((holder, path.name), set()).add(key[1]) if shared: pairs = "; ".join( - f"{first} and {second}: {count}" - for (first, second), count in sorted(shared.items()) + f"{first} and {second}: {len(response_ids)}" + for (first, second), response_ids in sorted(shared.items()) ) raise ValueError( f"CSV files in {output_path} hold the same provider responses " - f"(same model and provider_response_id; {pairs}), so each pair " - "holds one answer twice and cannot be two independent repeats. Use " - "a new output directory." + f"(same model and response id; {pairs}), so each pair holds one " + "answer twice and cannot be two independent repeats. Use a new " + "output directory." ) @@ -4533,12 +4610,14 @@ def run_repeated_no_tools_eval( """Run repeated AI-alone evaluations, saving one artifact per run. Each repeat runs under its own disk-cache namespace - (``_OwnCacheNamespace``), so, with nothing else running in the process, - it never looks up another repeat's answers, and a rerun on the same cache - looks up only under its own namespace. Before the first - request and after each repeat, a directory where two CSV files hold the + (``_OwnCacheNamespace``), so, with nothing else running in the process + and nothing replacing the cache, it never looks up another repeat's + answers, and a rerun on the same cache looks up only under its own + namespace. Before the first request and after each repeat, it checks the + CSV files then in the directory and raises ValueError where two hold the same provider response, or a file holds an answer without an id or cannot - be read, raises ValueError (``_refuse_shared_responses``). + be read (``_refuse_shared_responses``). A file written while a check + reads the directory, or after the last one, is not checked. After each repeat, one line says where its rows' responses came from, and how many of them it kept from an existing file. """ @@ -4555,7 +4634,7 @@ def run_repeated_no_tools_eval( run_output_path, scenarios, programs, include_explanations, single_output ) runner = run_no_tools_single_output_eval if single_output else run_no_tools_eval - with _OwnCacheNamespace(run_id): + with _OwnCacheNamespace(run_id, run_output_path.name): frame = runner( scenarios, models=models, diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index 26096f53..56d8a9ff 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -1,7 +1,8 @@ """Each repeat of a repeated run asks the models again. ``policybench eval-no-tools-repeated`` turns the LiteLLM disk cache on, and -every repeat builds the same requests. LiteLLM keys the cache on the request, +every repeat builds the same first-round requests from the same inputs. +LiteLLM keys the cache on the request, so repeats 2..N used to get repeat 1's responses back from the cache for every request whose stored answer a rebuilt request finds, and the run reported no run-to-run variation. Each repeat now runs under its own cache @@ -18,11 +19,11 @@ Fixtures count requests per repeat and, where a test asks for them, record the cache keys each repeat looks up and stores. -Nine test functions send no request: the namespace's spelling, the check -of directories the command cannot vouch for (each case), the check's -accepted rows, the response counter, the overlap guard, the two that check -a repeat raises when the cache changes under it, and the two that check the -namespace comes back (these four replace the runner; the property test +Ten test functions send no request: the namespace's spelling, the check of +directories the command cannot vouch for (each case), the check's accepted +rows, the response counter, the overlap guard, the three that check a +repeat raises when the cache changes under it, and the two that check the +namespace comes back (these five replace the runner; the property test replaces the cache object too). """ @@ -1054,7 +1055,8 @@ def test_the_check_accepts_rows_that_share_no_response(tmp_path): """Error rows carry no response id; the same id under two models is two responses; rows of one request group share their id within one file; an empty file and a header-only file hold nothing to check; a file that is - not a CSV is not read.""" + not a CSV is not read; a spend ledger that cannot be read adds nothing, + and one that can adds its responses under the model ids it records.""" header = "model,scenario_id,variable,prediction,error,provider_response_id\n" (tmp_path / "run_000.csv").write_text( header @@ -1068,10 +1070,124 @@ def test_the_check_accepts_rows_that_share_no_response(tmp_path): # CSV text in a file not named *.csv, sharing run_000's response: read, # it would be refused. (tmp_path / "run_000.csv.bak").write_text(header + "a,h,snap,1.0,,resp-1\n") + # run_000's ledger records a second response, and model "a"'s id; run_001's + # cannot be read. + ledger = [ + {"call_key": "sync:1", "model": "a", "model_id": "id-a"}, + { + "call_key": "sync:2", + "model": "a", + "model_id": "id-a", + "provider_response_id": "resp-2", + }, + ] + (tmp_path / "run_000.csv.spend.jsonl").write_text( + "".join(json.dumps(record) + "\n" for record in ledger) + "{not json\n" + ) + (tmp_path / "run_001.csv.spend.jsonl").mkdir() + (tmp_path / "run_004.csv").write_text(header + "id-b,h,snap,1.0,,resp-2\n") _refuse_shared_responses(tmp_path) +def test_a_file_that_replayed_another_files_chunks_in_another_order_is_refused( + monkeypatch, disk_cache, wire, tmp_path +): + """One output per explanation chunk, and the second file asked for the + outputs in the other order, under one namespace: it replayed both of the + first file's chunks, and its rows' first id is the first file's second. + The spend ledgers record every response, so the check sees the replay.""" + monkeypatch.setattr( + eval_no_tools, "_required_explanation_chunk_size", lambda *_a, **_k: 1 + ) + wire.answer = _FollowUpAnswers("chunk") + runs = tmp_path / "runs" + runs.mkdir() + for run_id, programs in (("run_000", VARIABLES), ("run_001", VARIABLES[::-1])): + eval_no_tools.run_no_tools_eval( + [SCENARIO], + models={_name_of(ANTHROPIC_TOOL): ANTHROPIC_TOOL}, + programs=programs, + output_path=str(runs / f"{run_id}.csv"), + run_id=run_id, + ) + first = pd.read_csv(runs / "run_000.csv") + second = pd.read_csv(runs / "run_001.csv") + _assert_answered(second) + assert len(wire) == 2 + assert second["cache_hit_calls"].drop_duplicates().tolist() == [2] + assert set(first["provider_response_id"]).isdisjoint(second["provider_response_id"]) + + with pytest.raises(ValueError, match=r"run_000\.csv and run_001\.csv"): + _refuse_shared_responses(runs) + + +def test_one_model_under_two_names_is_one_model_to_the_check( + disk_cache, wire, tmp_path +): + """Two files name the same model differently, and the second replayed the + first: the spend ledgers record the model each request went to.""" + runs = tmp_path / "runs" + runs.mkdir() + for run_id, name in (("run_001", "first name"), ("run_002", "second name")): + eval_no_tools.run_no_tools_eval( + [SCENARIO], + models={name: OPUS}, + programs=VARIABLES, + output_path=str(runs / f"{run_id}.csv"), + run_id=run_id, + ) + second = pd.read_csv(runs / "run_002.csv") + assert second["cache_hit_calls"].sum() > 0 + + with pytest.raises(ValueError, match=r"run_001\.csv and run_002\.csv"): + _refuse_shared_responses(runs) + + +# A card whose provider response id reaches the row as the provider sent it. +PROVIDER_ID_CARD = next( + ids[0] + for group, ids in sorted(GROUPS.items()) + if group.startswith(("deepseek", "openrouter", "xai")) +) +# Ids that pandas reads as missing values unless told otherwise. +MISSING_LOOKING_IDS = ["NA", "null", "None", "N/A"] + + +def test_a_response_id_that_reads_as_missing_is_still_an_id(disk_cache, wire, tmp_path): + """A provider id spelled like a missing value is an id: the command + neither refuses its own files nor loses the ids when it resumes them.""" + + def answer(path, body, call): + response = _canned_answer(path, body, call) + response["id"] = MISSING_LOOKING_IDS[call - 1] + return response + + wire.answer = answer + runs = tmp_path / "runs" + + frame = _run(PROVIDER_ID_CARD, runs) + + _assert_answered(frame) + assert len(wire) == 2 + + def ids() -> dict[str, list[str]]: + return { + run_id: pd.read_csv( + runs / f"{run_id}.csv", dtype=str, keep_default_na=False + )["provider_response_id"].tolist() + for run_id in ("run_000", "run_001") + } + + written = ids() + assert written == {"run_000": ["NA", "NA"], "run_001": ["null", "null"]} + + _run(PROVIDER_ID_CARD, runs) + + assert len(wire) == 2 + assert ids() == written + + def test_response_sources_counts_each_request_group_once(): batch = [ # Model "a" and household "b:c", and model "a:b" and household "c", @@ -1209,6 +1325,32 @@ def runner(*_args, run_id, **_kwargs): assert disk_cache.namespace == base +@pytest.mark.parametrize("runner_fails", [True, False]) +def test_a_repeat_whose_cache_lost_its_namespace_restores_it( + runner_fails, disk_cache, monkeypatch, tmp_path +): + """Something removed the cache's namespace attribute while a repeat ran: + the repeat puts the namespace back, a failing runner keeps its own error, + and a runner that returned gets the cache-changed error.""" + base = disk_cache.namespace + + def runner(*_args, run_id, **_kwargs): + del litellm.cache.namespace + if runner_fails: + raise RuntimeError("provider down") + return _one_row(run_id) + + monkeypatch.setattr(eval_no_tools, "run_no_tools_eval", runner) + + match = "provider down" if runner_fails else "namespace changed, while repeat" + with pytest.raises(RuntimeError, match=match): + _run(OPUS, tmp_path / "runs") + + assert disk_cache.namespace == base + with _OwnCacheNamespace("run_001"): + pass + + def test_without_a_cache_every_repeat_asks(sent_per_repeat, tmp_path): assert litellm.cache is None From 9e7b11b27fcf256dde662cb79fd1f408182e19f9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 21 Nov 2026 17:53:04 +0100 Subject: [PATCH 12/12] Send a rerun after a cache change to a new directory; free the lock on a failed entry From an in-session adversarial check of the round-3 answers (no P0/P1): - The cache-changed error says to use a new output directory: deleting the named file left its spend ledger, so a rerun paid again and was refused. - A repeat that cannot set its namespace releases the overlap lock. - A ledger line json rejects with a plain ValueError (or a RecursionError) makes that ledger add nothing, as an unreadable one does. - Docs: a file's responses are its rows' ids (not only answered rows') and its ledger's, for a file that holds rows; the ledger includes requests of rows a resume replaced or a deleted file held; the refusal says the files' requests got one answer twice; the README notes a failing repeat keeps its own error. - Tests: a replayed repair round is refused through the ledger; the advice is followed to a clean run; the lock on a failed entry; a bad ledger line. Co-Authored-By: Claude Opus 5.5 --- README.md | 35 +++--- policybench/eval_no_tools.py | 75 ++++++------ tests/test_repeated_runs_sample_fresh.py | 138 ++++++++++++++++++++++- 3 files changed, 196 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 674abee8..c0dad690 100644 --- a/README.md +++ b/README.md @@ -161,8 +161,9 @@ the cache of the whole Python process, which the command has to itself; code that calls `run_repeated_no_tools_eval` must run no other evaluation in the same process meanwhile, and must not call `enable_cache()` or assign `litellm.cache` while a repeat runs. A repeat that ends to find the cache -replaced or its namespace changed raises an error naming its file, which a -rerun into the same directory would otherwise keep. +replaced or its namespace changed raises an error naming its file, unless it is +already raising with its own error; use a new output directory then, since a +rerun into the same one would keep that file's rows. Running the command again reuses what each repeat already has. Into the same output directory, a repeat resumes from its CSV before it consults the cache. @@ -193,20 +194,22 @@ Before its first request and after each repeat, the command checks every CSV file then in the output directory, whoever wrote it (`analyze --runs-dir` reads them all). A cache replay returns the stored response with its id (the provider's, or one LiteLLM generated when the provider gave none), so two files -holding the same model and response id hold one answer twice, and the command -then stops with an error naming the files. A file's responses are the -`provider_response_id` of its answered rows (the first response of each request -group: a household, or one of its outputs with `--single-output`) and every -response its spend ledger (`run_000.csv.spend.jsonl`, ...) records, replays -included; the model is the model's name in the file, or the model id the ledger -records. It also stops at a file with answered rows but no response id (written -before the column was added, or cut short by an interrupted write), which it -cannot check, and at a CSV file it cannot read. Use a new output directory -then. Without a readable ledger the check sees only each request group's first -response under the file's model name, so a replayed later response, or one -model under two names, can go unseen. The check reads the directory as it is -when it runs: a file written while it reads, or after the last check, is not -checked, so run nothing else into the output directory while the command runs. +whose requests got the same model and response id got one answer twice, and the +command then stops with an error naming the files. The responses of a file that +holds rows are the `provider_response_id` of its rows (the first response of +each request group: a household, or one of its outputs with `--single-output`) +and every response its spend ledger (`run_000.csv.spend.jsonl`, ...) records +for that path, replays included, even for rows a resume replaced or a deleted +file held; the model is the model's name in the file, or the model id the +ledger records. It also stops at a file with answered rows but no response id +(written before the column was added, or cut short by an interrupted write), +which it cannot check, and at a CSV file it cannot read. Use a new output +directory then. Without a readable ledger the check sees only each request +group's first response under the file's model name, so a replayed later +response, or one model under two names, can go unseen. The check reads the +directory as it is when it runs: a file written while it reads, or after the +last check, is not checked, so run nothing else into the output directory while +the command runs. `policybench reference-outputs` writes PolicyEngine reference outputs, not administrative truth. It also writes `results/local/scenarios.csv`, and the eval diff --git a/policybench/eval_no_tools.py b/policybench/eval_no_tools.py index 1741be5b..ac6a18ea 100644 --- a/policybench/eval_no_tools.py +++ b/policybench/eval_no_tools.py @@ -4362,12 +4362,14 @@ class _OwnCacheNamespace: it runs: any other request sent while a repeat runs uses the repeat's namespace, and a replaced cache gives the repeat's later requests another namespace. Entering a repeat while another runs raises - RuntimeError. A repeat that ends to find ``litellm.cache`` replaced, or - its namespace changed or removed, puts the namespace back and raises - RuntimeError naming ``output_name``, whose rows may hold answers looked - up under another namespace and which a rerun into the same directory - would keep (unless the repeat is already raising). The check runs only - when the repeat ends. Without a cache the namespace is left alone. + RuntimeError, and a repeat that cannot set its namespace releases the + lock before it raises. A repeat that ends to find ``litellm.cache`` + replaced, or its namespace changed or removed, puts the namespace back + and raises RuntimeError naming ``output_name``, whose rows may hold + answers looked up under another namespace and which a rerun into the + same directory would keep, unless the repeat is already raising, when + its own error goes on. The check runs only when the repeat ends. Without + a cache the namespace is left alone. """ def __init__(self, run_id: str, output_name: str | None = None) -> None: @@ -4383,11 +4385,16 @@ def __enter__(self) -> None: f"Cannot start repeat {self._run_id}: another repeat is running " "in this process, and the two would share one cache namespace." ) - self._cache = litellm.cache - if self._cache is not None: - self._base = self._cache.namespace - self._namespace = _repeat_cache_namespace(self._base, self._run_id) - self._cache.namespace = self._namespace + try: + self._cache = litellm.cache + if self._cache is not None: + self._base = self._cache.namespace + self._namespace = _repeat_cache_namespace(self._base, self._run_id) + self._cache.namespace = self._namespace + except BaseException: + # Python calls no __exit__ after a failed __enter__. + _REPEAT_NAMESPACE_LOCK.release() + raise def __exit__(self, exc_type, *_exc) -> None: try: @@ -4399,17 +4406,17 @@ def __exit__(self, exc_type, *_exc) -> None: finally: _REPEAT_NAMESPACE_LOCK.release() if changed and exc_type is None: - delete = ( - f" Delete {self._output_name} before running the command into " - "this directory again: a rerun would keep its rows, which may " - "hold answers looked up under another namespace." + output = ( + f" Use a new output directory: a rerun into this one would keep " + f"{self._output_name}'s rows, which may hold answers looked up " + "under another namespace." if self._output_name else "" ) raise RuntimeError( "The disk cache was replaced, or its namespace changed, while " f"repeat {self._run_id} ran, so its requests may not have used " - f"its own namespace.{delete} Run nothing else in this process " + f"its own namespace.{output} Run nothing else in this process " "while a repeat runs, and do not call enable_cache() or assign " "litellm.cache." ) @@ -4457,13 +4464,16 @@ def _ledger_responses(csv_path: Path) -> tuple[set[tuple[str, str]], dict[str, s Returns the (model id, response id) pairs of every request the ledger records a response for, replays included, and the model id it records - for each model name the file's rows use. A ledger that is absent, cannot - be read, or lost a record records less; it never adds a pair the file's - requests did not get. + for each model name the file's rows use. The ledger records the requests + made for the file's path, including those of rows a resume replaced or a + deleted file held. A ledger that is absent, cannot be read, or lost a + record records less. """ try: records = read_spend_ledger(spend_ledger_path(csv_path)) - except (OSError, UnicodeDecodeError): + except (OSError, UnicodeDecodeError, ValueError, RecursionError): + # ValueError covers json's limits (an over-long integer) as well as + # JSONDecodeError on a line read_spend_ledger does not skip. return set(), {} responses: set[tuple[str, str]] = set() model_ids: dict[str, str] = {} @@ -4485,16 +4495,17 @@ def _refuse_shared_responses(output_path: Path) -> None: A response is a model and a response id (the provider's id, or one LiteLLM generated when the provider gave none), and a cache replay - returns the stored response with its id. So two files that hold the same - model and response id hold one answer twice, whatever wrote them. Each - file's responses are: + returns the stored response with its id. So two files whose requests got + the same model and response id got one answer twice, whatever wrote + them. The responses of each CSV file that holds rows are: - - the ``provider_response_id`` of its answered rows: the first id among - the responses a row's request group got (a household, or one of its + - the ``provider_response_id`` of its rows: the first id among the + responses a row's request group got (a household, or one of its outputs with ``single_output``); - - every response its spend ledger (``.spend.jsonl``) records, for - each request of the file, replays included, written by this code and - by the code since ea67093d. + - every response its spend ledger (``.spend.jsonl``) records for + the requests made for that path, replays included, written by this + code and by the code since ea67093d. That includes requests of rows a + resume replaced or a deleted file held. A row's response counts under its model name and under its model id: the one the ledger records for the name, else the one ``MODELS`` gives @@ -4568,10 +4579,10 @@ def _refuse_shared_responses(output_path: Path) -> None: for (first, second), response_ids in sorted(shared.items()) ) raise ValueError( - f"CSV files in {output_path} hold the same provider responses " - f"(same model and response id; {pairs}), so each pair holds one " - "answer twice and cannot be two independent repeats. Use a new " - "output directory." + f"CSV files in {output_path} hold the same provider responses, in " + f"their rows or their spend ledgers (same model and response id; " + f"{pairs}), so each pair got one answer twice and cannot be two " + "independent repeats. Use a new output directory." ) diff --git a/tests/test_repeated_runs_sample_fresh.py b/tests/test_repeated_runs_sample_fresh.py index 56d8a9ff..39d4560e 100644 --- a/tests/test_repeated_runs_sample_fresh.py +++ b/tests/test_repeated_runs_sample_fresh.py @@ -19,10 +19,11 @@ Fixtures count requests per repeat and, where a test asks for them, record the cache keys each repeat looks up and stores. -Ten test functions send no request: the namespace's spelling, the check of -directories the command cannot vouch for (each case), the check's accepted -rows, the response counter, the overlap guard, the three that check a -repeat raises when the cache changes under it, and the two that check the +Twelve test functions send no request: the namespace's spelling, the check +of directories the command cannot vouch for (each case), the check's +accepted rows, a ledger json cannot parse, the response counter, the +overlap guard, a repeat that cannot enter, the three that check a repeat +raises when the cache changes under it, and the two that check the namespace comes back (these five replace the runner; the property test replaces the cache object too). """ @@ -1122,6 +1123,62 @@ def test_a_file_that_replayed_another_files_chunks_in_another_order_is_refused( _refuse_shared_responses(runs) +def test_a_file_that_replayed_another_files_repair_round_is_refused( + disk_cache, wire, tmp_path +): + """Two files under one namespace ask for the outputs in different orders, + so their first requests and first ids differ. Each first answer leaves out + ssi, so both send the same repair request, and the second file replays the + first file's repair. Only the spend ledgers record that response.""" + + def answer(path, body, call): + (tool,) = body["tools"] + asked = list(tool["input_schema"]["properties"]["outputs"]["properties"]) + if len(asked) > 1: + asked = ["snap"] + value = 1000 + call + outputs = { + variable: {"value": value, "explanation": f"Call {call}. value = {value}"} + for variable in asked + } + return _anthropic_message( + call, + body, + [ + { + "type": "tool_use", + "id": f"toolu_{call}", + "name": tool["name"], + "input": {"outputs": outputs}, + } + ], + "tool_use", + ) + + wire.answer = answer + runs = tmp_path / "runs" + runs.mkdir() + for run_id, programs in (("run_000", VARIABLES), ("run_001", VARIABLES[::-1])): + eval_no_tools.run_no_tools_eval( + [SCENARIO], + models={_name_of(ANTHROPIC_TOOL): ANTHROPIC_TOOL}, + programs=programs, + output_path=str(runs / f"{run_id}.csv"), + run_id=run_id, + ) + first = pd.read_csv(runs / "run_000.csv") + second = pd.read_csv(runs / "run_001.csv") + _assert_answered(second) + # run_000: first request and repair live; run_001: first request live, + # repair replayed from run_000. + assert len(wire) == 3 + assert second["cache_hit_calls"].drop_duplicates().tolist() == [1] + assert set(first["provider_response_id"]).isdisjoint(second["provider_response_id"]) + + with pytest.raises(ValueError, match=r"run_000\.csv and run_001\.csv"): + _refuse_shared_responses(runs) + + def test_one_model_under_two_names_is_one_model_to_the_check( disk_cache, wire, tmp_path ): @@ -1188,6 +1245,17 @@ def ids() -> dict[str, list[str]]: assert ids() == written +def test_a_ledger_json_cannot_parse_adds_nothing(tmp_path): + """A ledger line json rejects with a plain ValueError (an over-long + integer) makes the ledger add nothing, as an unreadable ledger does.""" + header = "model,scenario_id,variable,prediction,error,provider_response_id\n" + (tmp_path / "run_000.csv").write_text(header + "a,h,snap,1.0,,resp-1\n") + (tmp_path / "run_000.csv.spend.jsonl").write_text('{"n": ' + "1" * 5000 + "}\n") + (tmp_path / "run_001.csv").write_text(header + "a,h,snap,1.0,,resp-2\n") + + _refuse_shared_responses(tmp_path) + + def test_response_sources_counts_each_request_group_once(): batch = [ # Model "a" and household "b:c", and model "a:b" and household "c", @@ -1260,6 +1328,25 @@ def test_repeats_cannot_overlap_in_one_process(disk_cache): assert disk_cache.namespace == base +def test_a_repeat_that_cannot_enter_leaves_the_next_one_free(disk_cache): + """The cache lost its namespace attribute before a repeat began: entering + fails, and a later repeat, once the namespace is back, can start.""" + base = disk_cache.namespace + del disk_cache.namespace + try: + with pytest.raises(AttributeError): + with _OwnCacheNamespace("run_000"): + pass + assert not eval_no_tools._REPEAT_NAMESPACE_LOCK.locked() + finally: + disk_cache.namespace = base + if eval_no_tools._REPEAT_NAMESPACE_LOCK.locked(): + eval_no_tools._REPEAT_NAMESPACE_LOCK.release() + with _OwnCacheNamespace("run_001"): + assert disk_cache.namespace == _repeat_cache_namespace(base, "run_001") + assert disk_cache.namespace == base + + def _one_row(run_id: str) -> pd.DataFrame: return pd.DataFrame( [ @@ -1351,6 +1438,49 @@ def runner(*_args, run_id, **_kwargs): pass +def test_after_the_cache_changed_error_a_new_directory_runs_clean( + disk_cache, wire, monkeypatch, tmp_path +): + """Something turned the cache on again while repeat 2 ran, so it replayed + repeat 1 under the base namespace. The error names its file and says to + use a new output directory; a rerun into the same one is refused before + any request, and one into a new directory asks again.""" + runs = tmp_path / "runs" + runs.mkdir() + # run_000 under the base namespace; the command keeps it on resume. + _write_without_namespaces(runs, ["run_000"]) + real_runner = eval_no_tools.run_no_tools_eval + + def runner(*args, run_id, **kwargs): + if run_id == "run_001": + enable_cache(str(tmp_path / "cache")) + return real_runner(*args, run_id=run_id, **kwargs) + + monkeypatch.setattr(eval_no_tools, "run_no_tools_eval", runner) + with pytest.raises( + RuntimeError, + match=r"Use a new output directory: a rerun into this one would keep " + r"run_001\.csv's rows", + ): + _run(OPUS, runs) + assert pd.read_csv(runs / "run_001.csv")["cache_hit_calls"].sum() > 0 + + monkeypatch.setattr(eval_no_tools, "run_no_tools_eval", real_runner) + enable_cache(str(tmp_path / "cache")) + sent = len(wire) + with pytest.raises(ValueError, match=r"run_000\.csv and run_001\.csv"): + _run(OPUS, runs) + assert len(wire) == sent + + frame = _run(OPUS, tmp_path / "again") + + _assert_answered(frame) + assert len(wire) > sent + first = frame[frame["run_id"] == "run_000"] + second = frame[frame["run_id"] == "run_001"] + assert set(first["provider_response_id"]).isdisjoint(second["provider_response_id"]) + + def test_without_a_cache_every_repeat_asks(sent_per_repeat, tmp_path): assert litellm.cache is None