diff --git a/.ci/verify_viewer.py b/.ci/verify_viewer.py index 4d023472..1debf7d9 100644 --- a/.ci/verify_viewer.py +++ b/.ci/verify_viewer.py @@ -202,6 +202,26 @@ def fire_on_load(label): # markers no longer apply and the run's own name is what proves it drew. check_drawn(label, [FIXTURE_JOB_ID]) + def fire_on_load_compare(label): + # A compare link opens the tab. It must not start the AI comparison. + calls = [] + original = viewer_app.compare_evals + viewer_app.compare_evals = lambda *ids: calls.append(ids) or "unexpected" + try: + rt.context().set_query_param("tab", "compare") + rt.context().set_query_param("eval1", FIXTURE_RUN_IDS[0]) + rt.context().set_query_param("eval2", FIXTURE_RUN_IDS[1]) + viewer_app.on_load(me.LoadEvent(path=ROOT_PAGE)) + finally: + viewer_app.compare_evals = original + if calls: + failures.append(f"{label} started the AI comparison for {calls}") + tab = me.state(viewer_app.State).selected_main_tab + if tab != "Compare": + failures.append(f"{label} selected the tab {tab!r}, not 'Compare'") + rt.run_path(ROOT_PAGE) + check_drawn(label, ["Run AI comparison"]) + def report(): print(f"\n{len(failures)} check(s) failed:") for failure in failures: @@ -236,6 +256,7 @@ def report(): attempt(f"rendering {path}", partial(render_page, path)) attempt("on_load", fire_on_load) + attempt("on_load with a compare link", fire_on_load_compare) for tab in EXPECTED_TABS: attempt(f"rendering tab {tab!r}", partial(render_tab, tab)) diff --git a/evalbench/test/viewer_ai_comparer_test.py b/evalbench/test/viewer_ai_comparer_test.py index 77d4837a..1f05ac6a 100644 --- a/evalbench/test/viewer_ai_comparer_test.py +++ b/evalbench/test/viewer_ai_comparer_test.py @@ -1,4 +1,4 @@ -"""Tests for the prompt size of the viewer AI comparison.""" +"""Tests for the viewer AI comparison: prompt size, result cache, file size.""" import os import sys @@ -19,6 +19,7 @@ class ComparePromptBoundsTest(unittest.TestCase): """The comparison prompt must stay small when run files hold huge cells.""" def setUp(self): + ai_comparer._cache.clear() temp_dir = tempfile.TemporaryDirectory() self.addCleanup(temp_dir.cleanup) self.results = temp_dir.name @@ -59,5 +60,69 @@ def test_prompt_is_bounded(self): self.assertIn("Scores:", prompt) +class CompareCacheAndSizeTest(unittest.TestCase): + """The same request must not call the model again.""" + + def setUp(self): + ai_comparer._cache.clear() + temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(temp_dir.cleanup) + self.results = temp_dir.name + for run in ("run-1", "run-2"): + run_dir = os.path.join(self.results, run) + os.makedirs(run_dir) + pd.DataFrame({"id": [1, 2]}).to_csv( + os.path.join(run_dir, "evals.csv"), index=False) + pd.DataFrame({"comparator": ["goal_completion"]}).to_csv( + os.path.join(run_dir, "scores.csv"), index=False) + self.generator = MagicMock() + self.generator.vertex_model = "gemini-2.5-flash" + self.model = self.generator.client.models.generate_content + self.model.return_value.text = "Same." + + def _compare(self): + env = {k: v for k, v in os.environ.items() if k != "GOOGLE_API_KEY"} + env["RESULTS_DIR"] = self.results + with patch.dict(os.environ, env, clear=True): + with patch.object( + ai_comparer, "get_summarizer", return_value=self.generator + ): + return ai_comparer.compare_evals("run-1", "run-2") + + def test_second_request_uses_the_stored_result(self): + self.assertEqual(self._compare(), "Same.") + self.assertEqual(self._compare(), "Same.") + + self.assertEqual(self.model.call_count, 1) + + def test_changed_run_file_gets_a_new_comparison(self): + self._compare() + scores = os.path.join(self.results, "run-2", "scores.csv") + with open(scores, "a") as f: + f.write("trajectory_matcher\n") + + self._compare() + + self.assertEqual(self.model.call_count, 2) + + def test_error_is_not_stored(self): + self.model.side_effect = RuntimeError("model is down") + self.assertIn("Error during comparison", self._compare()) + self.model.side_effect = None + + self.assertEqual(self._compare(), "Same.") + self.assertEqual(self.model.call_count, 2) + + def test_oversized_run_file_is_not_read(self): + with patch.object(ai_comparer, "_MAX_CSV_BYTES", 10): + with patch.object(ai_comparer.pd, "read_csv") as read_csv: + result = self._compare() + + self.assertTrue(result.startswith("Error: ")) + self.assertIn("larger than", result) + read_csv.assert_not_called() + self.model.assert_not_called() + + if __name__ == "__main__": unittest.main() diff --git a/viewer/ai_comparer.py b/viewer/ai_comparer.py index 7f8dac59..88de7de8 100644 --- a/viewer/ai_comparer.py +++ b/viewer/ai_comparer.py @@ -1,3 +1,4 @@ +import collections import sys import os import logging @@ -22,6 +23,36 @@ # Global models dict for get_generator global_models = {"lock": threading.Lock(), "registered_models": {}} +# compare_evals does not read a run file that is larger than this. +_MAX_CSV_BYTES = 100 * 1024 * 1024 + +# Results of earlier comparisons, so the same request does not call the model +# again. The key holds the state of the run files, so a changed run gets a new +# comparison. +_CACHE_MAX_ENTRIES = 64 +_cache = collections.OrderedDict() +_cache_lock = threading.Lock() + + +def _file_state(path): + """Returns the modification time and size of path, or None.""" + try: + stat = os.stat(path) + except OSError: + return None + return (stat.st_mtime_ns, stat.st_size) + + +def _remember(key, text): + """Stores a comparison result. Does not store an empty result.""" + if not isinstance(text, str) or not text: + return + with _cache_lock: + _cache[key] = text + _cache.move_to_end(key) + while len(_cache) > _CACHE_MAX_ENTRIES: + _cache.popitem(last=False) + def get_results_dir(): # Try to read from environment variable @@ -62,6 +93,26 @@ def compare_evals(id1, id2): if not os.path.exists(path2): return f"Error: Directory for {id2} not found at {path2}" + run_files = [ + os.path.join(path, name) + for path in (path1, path2) + for name in ("evals.csv", "scores.csv") + ] + file_states = [_file_state(run_file) for run_file in run_files] + for run_file, state in zip(run_files, file_states): + if state and state[1] > _MAX_CSV_BYTES: + return ( + f"Error: {os.path.basename(run_file)} of run " + f"{os.path.basename(os.path.dirname(run_file))} is larger than " + f"{_MAX_CSV_BYTES // (1024 * 1024)} MB. The AI comparison does not read it." + ) + + cache_key = (id1, id2, tuple(file_states)) + with _cache_lock: + if cache_key in _cache: + _cache.move_to_end(cache_key) + return _cache[cache_key] + try: evals1 = pd.read_csv(os.path.join(path1, "evals.csv")) scores1 = pd.read_csv(os.path.join(path1, "scores.csv")) if os.path.exists(os.path.join(path1, "scores.csv")) else None @@ -117,6 +168,7 @@ def compare_evals(id1, id2): model=model_name, contents=prompt, ) + _remember(cache_key, response.text) return response.text except ClientError as e: if "429" in str(e) and attempt < max_retries - 1: diff --git a/viewer/main.py b/viewer/main.py index 6d047bf5..6060f17f 100644 --- a/viewer/main.py +++ b/viewer/main.py @@ -245,8 +245,8 @@ def on_load(e: me.LoadEvent): state.selected_main_tab = "Compare" state.compare_tab_visible = True state.compare_evals = json.dumps([eval1, eval2]) - # Trigger the AI comparison - state.ai_comparison = compare_evals(eval1, eval2) + # A page load must not start a model call. The user starts the AI + # comparison with the button on the Compare tab. def status_component(): @@ -2462,7 +2462,13 @@ def on_main_tab_change(e: me.ButtonToggleChangeEvent): with me.box(style=me.Style(margin=me.Margin(bottom="16px"))): me.markdown(f'Comparing: {comp_evals[0]} vs {comp_evals[1]}') - if not state.ai_comparison or state.ai_comparison == "Comparing...": + if not state.ai_comparison: + me.button( + "Run AI comparison", + on_click=on_compare_tab_click, + type="flat", + ) + elif state.ai_comparison == "Comparing...": me.text("Comparing...", style=me.Style(font_weight="bold", color="#0284c7", margin=me.Margin(bottom="16px"))) else: with me.box(style=me.Style(