diff --git a/README.md b/README.md index ae22f820..c0dad690 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,64 @@ 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 looks up another +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, 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, 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. +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, 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-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, +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 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 +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 commands reuse that manifest by default instead of regenerating households from diff --git a/policybench/cli.py b/policybench/cli.py index 6b3b7eb4..c6270674 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 + # 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 0e876bb1..ac6a18ea 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 @@ -4301,6 +4313,302 @@ 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}" + + +# 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 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 + 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 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), + 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, 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: + self._run_id = run_id + self._output_name = output_name + 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): + raise RuntimeError( + f"Cannot start repeat {self._run_id}: another repeat is running " + "in this process, and the two would share one cache 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: + 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: + 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.{output} Run nothing else in this process " + "while a repeat runs, and do not call enable_cache() or assign " + "litellm.cache." + ) + + +def _response_sources( + frame: pd.DataFrame, single_output: bool = False +) -> tuple[int, int, int]: + """Where the responses behind a run's rows came from. + + 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: + return 0, 0, 0 + 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()), + ) + + +# 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 _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. 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, 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] = {} + 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. + + 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 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 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 + 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 + 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 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], set[str]] = {} + for path in sorted(output_path.glob(_RUNS_DIR_FILES)): + try: + 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: + 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: + 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} 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." + ) + 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: + shared.setdefault((holder, path.name), set()).add(key[1]) + if shared: + pairs = "; ".join( + 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, 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." + ) + + +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( scenarios: list[Scenario], repeats: int, @@ -4310,28 +4618,61 @@ 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 runs under its own disk-cache namespace + (``_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 (``_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. + """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True) + _refuse_shared_responses(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" 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, + kept = _rows_kept_on_resume( + 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, run_output_path.name): + 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, 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 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"; of these, kept from {run_output_path.name}: provider " + 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 new file mode 100644 index 00000000..39d4560e --- /dev/null +++ b/tests/test_repeated_runs_sample_fresh.py @@ -0,0 +1,1594 @@ +"""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 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 +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. + +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). +""" + +from __future__ import annotations + +import json +import os +import re +import socket +from types import SimpleNamespace + +import httpx +import litellm +import pandas as pd +import pytest +from hypothesis import 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 ( + EXPLANATION_FUNCTION_NAME, + REASONING_EFFORT_OVERRIDE_ENV, + _answer_contract_for_model, + _OwnCacheNamespace, + _refuse_shared_responses, + _repeat_cache_namespace, + _response_sources, + _uses_responses_api, + run_repeated_no_tools_eval, +) +from policybench.model_cards import MODEL_CARDS, explanation_chunk_size_for +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, +) +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" + +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())] +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: + 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}") + + +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. + + 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: + 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, 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") + + 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, 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 []) + ) + monkeypatch.setattr(litellm, "cache", None) + yield + os.environ.clear() + os.environ.update(environment) + + +@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) + + +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) -> _Wire: + """The requests LiteLLM put on the wire, each answered from this file.""" + sent = _Wire() + + def send(self, request, **_kwargs): + body = json.loads(request.content) + sent.append({"path": request.url.path, "body": body}) + 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") + + 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: + run_id = kwargs.get("run_id") + counts[run_id] = counts.get(run_id, 0) + len(wire) - before + + return run + + for name, runner in runners.items(): + monkeypatch.setattr(eval_no_tools, name, counting(runner)) + 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], + 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() + + +def _assert_answered(frame: pd.DataFrame) -> None: + """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() + + +@pytest.mark.parametrize("model_id", REPRESENTATIVES) +def test_repeat_2_asks_again_when_repeat_1_is_cached( + 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"], ( + "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") + # 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, keys_per_repeat, tmp_path +): + base = disk_cache.namespace + + frame = _run(OPUS, tmp_path / "runs", single_output=True) + + _assert_answered(frame) + # 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 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 + + 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")) + assert set(keys_per_repeat) == {"run_000", "run_001"} + for run_id, used in keys_per_repeat.items(): + 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( + 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 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) + 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) + 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, 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, 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"] + 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() + + # 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 + assert sent_per_repeat == { + "run_000": rerun, + "run_001": rerun, + "run_002": one_repeat, + } + assert len(wire) - sent_before == 2 * rerun + one_repeat + assert set(_raw(again, "run_002")).isdisjoint( + _raw(again, "run_000") + _raw(again, "run_001") + ) + 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: + 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 + assert f"run_001: provider responses 0, cache replays {one_repeat}\n" 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: 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) + + 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(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: + 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}" + ) + + +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 = OPUS + 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"] + 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() + + +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; of these, " + f"kept from run_001.csv: provider responses {one_repeat}, cache replays 0\n" + ) in out + + +@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_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.""" + 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 +): + """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" + 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) + + 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 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( + when, disk_cache, wire, monkeypatch, tmp_path +): + """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: list[tuple[int, int]] = [] + + def kept(run_output_path, *args, **kwargs): + 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) + + with pytest.raises( + ValueError, match=r"run_001\.csv and run_002\.csv.*Use a new output directory" + ): + _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( + "left", + ["no id column", "a blank id", "a file it cannot read", "one response twice"], +) +def test_a_directory_the_command_cannot_check_is_refused_before_any_request( + left, monkeypatch, tmp_path +): + runs = tmp_path / "runs" + runs.mkdir() + 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) + ) + + with pytest.raises(ValueError, match="Use a new output directory"): + _run(OPUS, runs) + + assert not called + + +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; 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 + + "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") + # 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_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 +): + """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_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", + # 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, + }, + ] + 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) + + +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_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( + [ + { + "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 + + +@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_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 + + _run(OPUS, 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, keys_per_repeat, tmp_path, monkeypatch +): + """The override's own request namespace outranks the cache's, so it has + to carry the repeat: for the lookup, the store, and a rerun's replay.""" + monkeypatch.setenv(REASONING_EFFORT_OVERRIDE_ENV, f"{OPUS}=high") + base = disk_cache.namespace + + first = _run(OPUS, tmp_path / "runs") + + 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() + + enable_cache(str(tmp_path / "cache")) + again = _run(OPUS, 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(first, 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(OPUS, tmp_path / "runs") + + assert seen == [_repeat_cache_namespace(base, "run_000")] + assert litellm.cache.namespace == base + + +@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), + 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, + "model": "a", + "scenario_id": SCENARIO.id, + "variable": "snap", + "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}:")