| 1 | """Offline regression checks for the opt-in manual engine comparison.""" |
| 2 | |
| 3 | import importlib.util |
| 4 | import json |
| 5 | import subprocess |
| 6 | import sys |
| 7 | from pathlib import Path |
| 8 | from unittest import mock |
| 9 | |
| 10 | import pytest |
| 11 | |
| 12 | import last30days as cli |
| 13 | from lib import pipeline, schema |
| 14 | |
| 15 | |
| 16 | def build_report(topic, source_counts, *, errors=None): |
| 17 | items_by_source = { |
| 18 | source: [schema.SourceItem( |
| 19 | item_id=f"{topic}-{source}-{index}", source=source, title=topic, |
| 20 | body="fixture evidence", url=f"https://example.invalid/{source}/{index}", |
| 21 | ) for index in range(count)] |
| 22 | for source, count in source_counts.items() |
| 23 | } |
| 24 | candidates = [schema.Candidate( |
| 25 | candidate_id=item.item_id, item_id=item.item_id, source=source, |
| 26 | title=item.title, url=item.url, snippet=item.body, |
| 27 | subquery_labels=[topic], native_ranks={source: index + 1}, |
| 28 | local_relevance=0.8, freshness=1, engagement=1, source_quality=0.8, |
| 29 | rrf_score=0.1, |
| 30 | ) for source, items in items_by_source.items() for index, item in enumerate(items)] |
| 31 | return schema.Report( |
| 32 | topic=topic, range_from="2026-09-06", range_to="2026-10-06", |
| 33 | generated_at="2026-10-06T00:00:00Z", |
| 34 | provider_runtime=schema.ProviderRuntime("local", "fixture", "fixture"), |
| 35 | query_plan=schema.QueryPlan( |
| 36 | intent="concept", freshness_mode="balanced_recent", cluster_mode="topic", |
| 37 | raw_topic=topic, |
| 38 | subqueries=[schema.SubQuery(topic, topic, topic, list(source_counts))], |
| 39 | source_weights={source: 1.0 for source in source_counts}, |
| 40 | ), |
| 41 | clusters=[schema.Cluster( |
| 42 | cluster_id=topic, title=topic, |
| 43 | candidate_ids=[candidate.candidate_id for candidate in candidates], |
| 44 | representative_ids=[candidates[0].candidate_id] if candidates else [], |
| 45 | sources=list(source_counts), score=0.8, |
| 46 | )], |
| 47 | ranked_candidates=candidates, items_by_source=items_by_source, |
| 48 | errors_by_source=errors or {}, |
| 49 | source_status={source: schema.SourceOutcome( |
| 50 | source=source, state="ok" if items else "no-results", items_returned=len(items), |
| 51 | ) for source, items in items_by_source.items()}, |
| 52 | ) |
| 53 | |
| 54 | |
| 55 | def load_comparison_module(): |
| 56 | path = Path(__file__).with_name("e2e_comparison.py") |
| 57 | spec = importlib.util.spec_from_file_location("e2e_comparison_module", path) |
| 58 | module = importlib.util.module_from_spec(spec) |
| 59 | assert spec and spec.loader |
| 60 | spec.loader.exec_module(module) |
| 61 | return module |
| 62 | |
| 63 | |
| 64 | def test_current_engine_uses_canonical_path(): |
| 65 | module = load_comparison_module() |
| 66 | assert Path(module.V3_SCRIPT) == ( |
| 67 | Path(__file__).resolve().parents[1] |
| 68 | / "skills" / "last30days" / "scripts" / "last30days.py" |
| 69 | ) |
| 70 | assert Path(module.V3_SCRIPT).is_file() |
| 71 | |
| 72 | |
| 73 | @pytest.mark.parametrize("source_error", [False, True]) |
| 74 | def test_comparison_output_aggregates_nested_reports_and_errors(tmp_path, capsys, source_error): |
| 75 | module = load_comparison_module() |
| 76 | reports = [ |
| 77 | ("alpha", build_report("alpha", {"reddit": 2, "web": 1})), |
| 78 | ("beta", build_report("beta", {"reddit": 1, "x": 0}, |
| 79 | errors={"x": "fixture timeout"} if source_error else None)), |
| 80 | ] |
| 81 | if source_error: |
| 82 | reports[1][1].source_status["x"] = schema.SourceOutcome(source="x", state="timeout") |
| 83 | payload = cli.emit_comparison_output(reports, "json", json_profile="raw") |
| 84 | result = subprocess.CompletedProcess([], 0, payload, "") |
| 85 | reference = tmp_path / "reference.py" |
| 86 | reference.touch() |
| 87 | with mock.patch.object(module.subprocess, "run", return_value=result), mock.patch.object( |
| 88 | module, "QUERIES", [("alpha vs beta", "comparison")] |
| 89 | ), mock.patch.object(sys, "argv", ["e2e_comparison", "--v2-script", str(reference)]): |
| 90 | metrics = module.run_query("fixture.py", "alpha vs beta") |
| 91 | assert metrics["sources"] == 3 |
| 92 | assert metrics["total_items"] == 4 |
| 93 | assert metrics["candidates"] == 4 |
| 94 | assert metrics["clusters"] == 2 |
| 95 | assert metrics["intent"] == "comparison" |
| 96 | assert metrics["subqueries"] == 2 |
| 97 | assert metrics["errors"] == (["beta: x"] if source_error else []) |
| 98 | assert module.main() == int(source_error) |
| 99 | output = capsys.readouterr().out |
| 100 | assert "| Total items retrieved | 4 | 4 | +0 |" in output |
| 101 | assert "| Total sources with items | 3 | 3 | +0 |" in output |
| 102 | assert f"Outcome: {'partial' if source_error else 'passed'}" in output |
| 103 | if source_error: |
| 104 | assert "beta: x" in output |
| 105 | |
| 106 | |
| 107 | @pytest.mark.parametrize("comparison", [False, True]) |
| 108 | @pytest.mark.parametrize("state", [ |
| 109 | "partial", "rate-limited", "auth-failed", "payment-required", |
| 110 | "unreachable", "timeout", "schema-drift", "error", |
| 111 | ]) |
| 112 | def test_source_status_failures_are_partial_without_legacy_errors(tmp_path, capsys, comparison, state): |
| 113 | module = load_comparison_module() |
| 114 | report = build_report("alpha", {"reddit": 1 if state in {"partial", "auth-failed"} else 0, "web": 1}) |
| 115 | bundle = schema.RetrievalBundle() |
| 116 | for source, items in report.items_by_source.items(): |
| 117 | bundle.add_items("alpha", source, items) |
| 118 | bundle.record_failure("reddit", state, "fixture retrieval failure") |
| 119 | report.source_status = pipeline._finalize_source_status(bundle.source_status, report.items_by_source) |
| 120 | report.warnings = pipeline._warnings( |
| 121 | report.items_by_source, report.ranked_candidates, {}, {"reddit": "fixture retrieval failure"}, |
| 122 | ) |
| 123 | assert report.errors_by_source == {} |
| 124 | assert report.source_status["reddit"].state == state |
| 125 | payload = ( |
| 126 | cli.emit_comparison_output([("alpha", report)], "json", json_profile="raw") |
| 127 | if comparison else json.dumps(schema.to_dict(report)) |
| 128 | ) |
| 129 | result = subprocess.CompletedProcess([], 0, payload, "") |
| 130 | reference = tmp_path / "reference.py" |
| 131 | reference.touch() |
| 132 | with mock.patch.object(module.subprocess, "run", return_value=result), mock.patch.object( |
| 133 | module, "QUERIES", [("fixture topic", "concept")] |
| 134 | ), mock.patch.object(sys, "argv", ["e2e_comparison", "--v2-script", str(reference)]): |
| 135 | metrics = module.run_query("fixture.py", "fixture topic") |
| 136 | assert metrics["errors"] == (["alpha: reddit"] if comparison else ["reddit"]) |
| 137 | assert module.main() == 1 |
| 138 | output = capsys.readouterr().out |
| 139 | assert "| Source errors | 1 | 1 | +0 |" in output |
| 140 | assert "Outcome: partial" in output |
| 141 | |
| 142 | |
| 143 | @pytest.mark.parametrize("state", ["ok", "no-results", "skipped-unconfigured"]) |
| 144 | def test_benign_source_status_and_warnings_remain_successful(tmp_path, capsys, state): |
| 145 | module = load_comparison_module() |
| 146 | report = build_report("alpha", {"reddit": 1 if state == "ok" else 0, "web": 1}) |
| 147 | report.source_status["reddit"] = schema.SourceOutcome( |
| 148 | source="reddit", state=state, items_returned=len(report.items_by_source["reddit"]), |
| 149 | attempted=state != "skipped-unconfigured", detail="Informational coverage note", |
| 150 | lane_failure_state="timeout" if state == "ok" else None, |
| 151 | ) |
| 152 | report.warnings = ["Evidence is thin for this topic.", "Informational coverage note"] |
| 153 | result = subprocess.CompletedProcess([], 0, json.dumps(schema.to_dict(report)), "") |
| 154 | reference = tmp_path / "reference.py" |
| 155 | reference.touch() |
| 156 | with mock.patch.object(module.subprocess, "run", return_value=result), mock.patch.object( |
| 157 | module, "QUERIES", [("fixture topic", "concept")] |
| 158 | ), mock.patch.object(sys, "argv", ["e2e_comparison", "--v2-script", str(reference)]): |
| 159 | assert module.main() == 0 |
| 160 | output = capsys.readouterr().out |
| 161 | assert "| Source errors | 0 | 0 | +0 |" in output |
| 162 | assert "Outcome: passed" in output |
| 163 | |
| 164 | |
| 165 | def test_source_error_is_counted_once_when_both_channels_report_it(): |
| 166 | module = load_comparison_module() |
| 167 | report = build_report("alpha", {"reddit": 0, "web": 1}, errors={"reddit": "fixture timeout"}) |
| 168 | report.source_status["reddit"] = schema.SourceOutcome(source="reddit", state="timeout") |
| 169 | result = subprocess.CompletedProcess([], 0, json.dumps(schema.to_dict(report)), "") |
| 170 | with mock.patch.object(module.subprocess, "run", return_value=result): |
| 171 | assert module.run_query("fixture.py", "fixture topic")["errors"] == ["reddit"] |
| 172 | |
| 173 | |
| 174 | def test_legacy_v2_success_retains_source_and_item_counts(): |
| 175 | module = load_comparison_module() |
| 176 | payload = {"mode": "legacy", "reddit": [{"id": "one"}, {"id": "two"}], "web": [{"id": "three"}]} |
| 177 | result = subprocess.CompletedProcess([], 0, json.dumps(payload), "") |
| 178 | with mock.patch.object(module.subprocess, "run", return_value=result): |
| 179 | metrics = module.run_query("fixture.py", "fixture topic") |
| 180 | assert metrics["sources"] == 2 |
| 181 | assert metrics["total_items"] == 3 |
| 182 | assert metrics["candidates"] == 3 |
| 183 | assert metrics["intent"] == "legacy" |
| 184 | assert metrics["errors"] == [] |
| 185 | |
| 186 | |
| 187 | @pytest.mark.parametrize("comparison", [False, True]) |
| 188 | def test_process_exits_nonzero_for_partial_source_status(tmp_path, comparison): |
| 189 | report = build_report("alpha", {"reddit": 1}) |
| 190 | bundle = schema.RetrievalBundle() |
| 191 | bundle.add_items("alpha", "reddit", report.items_by_source["reddit"]) |
| 192 | bundle.record_failure("reddit", "rate-limited", "fixture retrieval failure") |
| 193 | report.source_status = pipeline._finalize_source_status(bundle.source_status, report.items_by_source) |
| 194 | payload = ( |
| 195 | cli.emit_comparison_output([("alpha", report)], "json", json_profile="raw") |
| 196 | if comparison else json.dumps(schema.to_dict(report)) |
| 197 | ) |
| 198 | runner = tmp_path / "comparison_runner.py" |
| 199 | tool = Path(__file__).with_name("e2e_comparison.py").resolve() |
| 200 | reference = tmp_path / "reference.py" |
| 201 | reference.touch() |
| 202 | runner.write_text( |
| 203 | "import runpy, subprocess\n" |
| 204 | "from unittest.mock import patch\n" |
| 205 | f"result = subprocess.CompletedProcess([], 0, {payload!r}, '')\n" |
| 206 | "with patch('subprocess.run', return_value=result):\n" |
| 207 | f" runpy.run_path({str(tool)!r}, run_name='__main__')\n" |
| 208 | ) |
| 209 | result = subprocess.run( |
| 210 | [sys.executable, str(runner), "--v2-script", str(reference)], |
| 211 | capture_output=True, text=True, timeout=10, |
| 212 | ) |
| 213 | assert result.returncode == 1, result.stderr |
| 214 | assert "Outcome: partial" in result.stdout |
| 215 | expected_source = "alpha: reddit" if comparison else "reddit" |
| 216 | assert expected_source in result.stdout |
| 217 | |
| 218 | |
| 219 | @pytest.mark.parametrize("source_errors,expected_exit,outcome", [ |
| 220 | ({}, 0, "passed"), ({"reddit": "rate-limited"}, 1, "partial"), |
| 221 | ]) |
| 222 | def test_reports_source_outcomes(tmp_path, capsys, source_errors, expected_exit, outcome): |
| 223 | module = load_comparison_module() |
| 224 | engine = tmp_path / "fixture_engine.py" |
| 225 | payload = { |
| 226 | "query_plan": {"intent": "concept", "subqueries": [{}]}, |
| 227 | "items_by_source": {"reddit": [{"id": "fixture"}]}, |
| 228 | "ranked_candidates": [{"id": "fixture"}], |
| 229 | "errors_by_source": source_errors, |
| 230 | } |
| 231 | engine.write_text("print(" + repr(json.dumps(payload)) + ")\n") |
| 232 | with mock.patch.object(module, "V3_SCRIPT", str(engine)), mock.patch.object( |
| 233 | module, "QUERIES", [("fixture topic", "concept")] |
| 234 | ), mock.patch.object(sys, "argv", ["e2e_comparison", "--v2-script", str(engine)]): |
| 235 | assert module.main() == expected_exit |
| 236 | output = capsys.readouterr().out |
| 237 | assert "| Total items retrieved | 1 | 1 | +0 |" in output |
| 238 | assert "| Command errors | 0 | 0 | +0 |" in output |
| 239 | assert f"| Source errors | {len(source_errors)} | {len(source_errors)} | +0 |" in output |
| 240 | assert f"Outcome: {outcome}" in output |
| 241 | |
| 242 | |
| 243 | @pytest.mark.parametrize("failed_engines,outcome", [(2, "failed"), (1, "partial")]) |
| 244 | def test_command_failures_are_visible_and_fail(tmp_path, capsys, failed_engines, outcome): |
| 245 | module = load_comparison_module() |
| 246 | reference = tmp_path / "reference.py" |
| 247 | reference.touch() |
| 248 | failure = subprocess.CompletedProcess([], 3, "", "engine-failure-sentinel") |
| 249 | success = subprocess.CompletedProcess([], 0, '{"reddit":[{"id":"fixture"}]}', "") |
| 250 | outcomes = [failure, failure if failed_engines == 2 else success] |
| 251 | with mock.patch.object(module.subprocess, "run", side_effect=outcomes) as run, mock.patch.object( |
| 252 | module, "QUERIES", [("fixture topic", "concept")] |
| 253 | ), mock.patch.object(sys, "argv", ["e2e_comparison", "--v2-script", str(reference)]): |
| 254 | assert module.main() == 1 |
| 255 | assert run.call_count == 2 |
| 256 | output = capsys.readouterr().out |
| 257 | other_errors = failed_engines - 1 |
| 258 | assert f"| Command errors | 1 | {other_errors} | {1 - other_errors:+d} |" in output |
| 259 | assert "engine-failure-sentinel" in output |
| 260 | assert f"Outcome: {outcome}" in output |
| 261 | |
| 262 | |
| 263 | @pytest.mark.parametrize("result,expected_error", [ |
| 264 | (subprocess.CompletedProcess([], 4, "", ""), "engine exited with status 4"), |
| 265 | (subprocess.CompletedProcess([], 0, "not-json", ""), "Expecting value"), |
| 266 | (subprocess.CompletedProcess([], 0, '{"comparison":true,"reports":[]}', ""), "comparison output contains no reports"), |
| 267 | (subprocess.TimeoutExpired("fixture", 7), "timeout"), |
| 268 | ]) |
| 269 | def test_invalid_output_and_timeout_are_command_errors(result, expected_error): |
| 270 | module = load_comparison_module() |
| 271 | behavior = {"side_effect": result} if isinstance(result, Exception) else {"return_value": result} |
| 272 | with mock.patch.object(module.subprocess, "run", **behavior) as run: |
| 273 | report = module.run_query("fixture.py", "fixture topic", timeout=7) |
| 274 | assert expected_error in report["error"] |
| 275 | assert report["sources"] == 0 |
| 276 | assert report["candidates"] == 0 |
| 277 | assert run.call_args.kwargs["timeout"] == 7 |
| 278 | |
| 279 | |
| 280 | def test_process_exits_nonzero_when_engines_fail(tmp_path): |
| 281 | runner = tmp_path / "comparison_runner.py" |
| 282 | tool = Path(__file__).with_name("e2e_comparison.py").resolve() |
| 283 | reference = tmp_path / "reference.py" |
| 284 | reference.touch() |
| 285 | runner.write_text( |
| 286 | "import runpy, subprocess\n" |
| 287 | "from unittest.mock import patch\n" |
| 288 | "failure = subprocess.CompletedProcess([], 3, '', 'fixture-failure')\n" |
| 289 | "with patch('subprocess.run', return_value=failure):\n" |
| 290 | f" runpy.run_path({str(tool)!r}, run_name='__main__')\n" |
| 291 | ) |
| 292 | result = subprocess.run( |
| 293 | [sys.executable, str(runner), "--v2-script", str(reference)], |
| 294 | capture_output=True, text=True, timeout=10, |
| 295 | ) |
| 296 | assert result.returncode == 1, result.stderr |
| 297 | assert "Outcome: failed" in result.stdout |
| 298 |