"""Tests for src/askme/evaluation/compare.py.""" from __future__ import annotations import asyncio import json from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch from typer.testing import CliRunner from askme.backends import parse_spec from askme.evaluation.compare import ( _contexts, app, comparison_markdown, generate_samples, judge_samples, run_matrix, ) runner = CliRunner() def _raw(answer: str, chunks: list[str], hl=("hl",), ll=("ll",)) -> dict: """Shape of LightRAG's aquery_llm / aquery_data result.""" return { "data": {"chunks": [{"content": c} for c in chunks]}, "metadata": {"keywords": {"high_level": list(hl), "low_level": list(ll)}}, "llm_response": {"content": answer}, } def test_contexts_are_chunk_texts_capped(): """ Scenario: judge context is the retrieved source text, bounded Given retrieved chunks totalling more than the cap When _contexts runs with cap=10 Then whole chunks are kept until the cap, the last one truncated """ raw = _raw("a", ["aaaaaa", "bbbbbb", "cccccc"]) assert _contexts(raw, cap=10) == ["aaaaaa", "bbbb"] def test_generate_samples_records_answer_contexts_and_keywords(): """ Scenario: per-generator keywords (default) Given a generator and one question When generate_samples runs Then the query uses that generator's model_func with no preset keywords, and the sample holds answer, contexts and the extracted keywords """ rag = MagicMock() rag.aquery_llm = AsyncMock(return_value=_raw("ans", ["ctx"], hl=["h"], ll=["l"])) gen = parse_spec("gemma3:4b") with patch("askme.evaluation.compare.lightrag_model_func", return_value="FUNC"): samples = asyncio.run( generate_samples(rag, gen, [{"question": "q", "reference": "r"}], "hybrid") ) param = rag.aquery_llm.call_args.kwargs["param"] assert param.model_func == "FUNC" assert param.max_total_tokens == 12000 assert param.hl_keywords == [] and param.ll_keywords == [] assert samples == [ { "question": "q", "reference": "r", "answer": "ans", "contexts": ["ctx"], "hl_keywords": ["h"], "ll_keywords": ["l"], } ] def test_generate_samples_caps_context_for_every_generator(): """ Scenario: every generator sees the same, complete context Given LightRAG's default 30000-token prompt budget When generate_samples queries Then the prompt budget is capped at 12000 tokens (fits Ollama's 16k and the router's 32k windows, so no backend silently truncates or rejects the prompt) """ rag = MagicMock() rag.aquery_llm = AsyncMock(return_value=_raw("a", ["c"])) with patch("askme.evaluation.compare.lightrag_model_func"): asyncio.run( generate_samples(rag, parse_spec("x"), [{"question": "q", "reference": "r"}], "hybrid") ) param = rag.aquery_llm.call_args.kwargs["param"] assert param.max_total_tokens == 12000 def test_generate_samples_leaves_room_for_source_chunks(): """ Scenario: the capped prompt still carries notebook text Given LightRAG fills chunks only with what entities, relations and the ~2k-token system prompt leave of max_total_tokens When generate_samples queries Then entity + relation budgets leave at least 4000 tokens for chunks (with the 6000/8000 defaults a 12000 cap left none: 19/20 answers had no source text, so faithfulness was unmeasurable) """ rag = MagicMock() rag.aquery_llm = AsyncMock(return_value=_raw("a", ["c"])) with patch("askme.evaluation.compare.lightrag_model_func"): asyncio.run( generate_samples(rag, parse_spec("x"), [{"question": "q", "reference": "r"}], "hybrid") ) p = rag.aquery_llm.call_args.kwargs["param"] system_prompt = 2000 assert p.max_total_tokens - p.max_entity_tokens - p.max_relation_tokens - system_prompt >= 4000 def test_generate_samples_uses_pinned_keywords(): """ Scenario: pinned keywords isolate answer synthesis Given keywords already extracted for the question by the base model When generate_samples runs with them Then the query carries those keywords, so retrieval is identical across generators """ rag = MagicMock() rag.aquery_llm = AsyncMock(return_value=_raw("ans", ["ctx"], hl=["H"], ll=["L"])) pinned = {"q": (["H"], ["L"])} with patch("askme.evaluation.compare.lightrag_model_func"): asyncio.run( generate_samples( rag, parse_spec("gemma3:4b"), [{"question": "q", "reference": "r"}], "hybrid", pinned, ) ) param = rag.aquery_llm.call_args.kwargs["param"] assert (param.hl_keywords, param.ll_keywords) == (["H"], ["L"]) def _fake_matrix_deps(events: list): """Patch generation/judging/release, recording the order of GPU-relevant calls.""" rag = MagicMock() rag.initialize_storages = AsyncMock() rag.finalize_storages = AsyncMock() async def gen(_rag, spec, testset, mode, pinned=None): events.append(("gen", spec.label)) return [{"question": t["question"], "hl_keywords": [], "ll_keywords": []} for t in testset] async def judge(spec, samples): events.append(("judge", spec.label)) return [{"question": s["question"], "faithfulness": 1.0, "answer_relevancy": 0.5, "context_precision": 0.0} for s in samples] async def rel(spec): events.append(("release", spec.label)) return [ patch("askme.evaluation.compare.create_rag", return_value=rag), patch("askme.evaluation.compare.generate_samples", side_effect=gen), patch("askme.evaluation.compare.judge_samples", side_effect=judge), patch("askme.evaluation.compare.release", side_effect=rel), ] def _run(tmp_path: Path, events: list, **kw): patches = _fake_matrix_deps(events) for p in patches: p.start() try: return run_matrix( [parse_spec("g1"), parse_spec("g2")], [parse_spec("j1"), parse_spec("g1")], [{"question": "q", "reference": "r"}], "hybrid", "per-generator", tmp_path, **kw, ) finally: for p in patches: p.stop() def test_run_matrix_generates_all_before_judging_and_frees_gpu(tmp_path: Path): """ Scenario: one model on the 8GB GPU at a time Given 2 generators and 2 judges When run_matrix runs Then every generator answers before any judge runs, each model is released after its phase, and every judge scores every generator """ events: list = [] _run(tmp_path, events) assert events == [ ("gen", "g1"), ("release", "g1"), ("gen", "g2"), ("release", "g2"), ("judge", "j1"), ("judge", "j1"), ("release", "j1"), ("judge", "g1"), ("judge", "g1"), ("release", "g1"), ] assert len(list((tmp_path / "scores").glob("*.json"))) == 4 def test_run_matrix_resumes_from_existing_files(tmp_path: Path): """ Scenario: a long run crashed part-way Given samples and scores already written by a previous run When run_matrix runs again on the same directory Then nothing is regenerated or re-judged """ _run(tmp_path, []) events: list = [] _run(tmp_path, events) assert [e for e in events if e[0] != "release"] == [] def test_comparison_markdown_flags_self_judging(): """ Scenario: a model judging its own answers Given scores for g1 judged by j1 and by g1 When comparison_markdown renders the matrix Then each metric has a generator x judge table, and the g1/g1 cell is marked as self-judged with a note on the bias """ scores = { ("g1", "j1"): {"faithfulness": 0.5, "answer_relevancy": 0.6, "context_precision": 0.7}, ("g1", "g1"): {"faithfulness": 0.9, "answer_relevancy": 0.8, "context_precision": 0.7}, } md = comparison_markdown(["g1"], ["j1", "g1"], scores, keyword_overlap={"g1": 1.0}) assert "## faithfulness" in md assert "| g1 | 0.500 | 0.900* |" in md assert "self-judged" in md def test_cli_writes_comparison(tmp_path: Path): """ Scenario: one command runs the matrix and writes the report Given a testset file and generator/judge lists When askme-eval-compare runs Then it exits 0 and comparison.md exists in the output dir """ testset = tmp_path / "ts.json" testset.write_text(json.dumps([{"question": "q", "reference": "r"}] * 3)) out = tmp_path / "run" with patch("askme.evaluation.compare.run_matrix", return_value="# md\n") as rm: result = runner.invoke( app, ["--generators", "g1 g2", "--judges", "j1", "--n", "2", "--testset", str(testset), "--out", str(out)], ) assert result.exit_code == 0, result.output assert (out / "comparison.md").read_text() == "# md\n" generators, judges, ts = rm.call_args.args[:3] assert [g.label for g in generators] == ["g1", "g2"] assert [j.label for j in judges] == ["j1"] assert len(ts) == 2 def test_judge_samples_survives_a_failing_metric(): """ Scenario: a judge fails one metric on one question Given faithfulness raises (e.g. "output incomplete due to max_tokens") When judge_samples scores the sample Then faithfulness is None with the error recorded, and the other metrics are still scored — one bad call must not end a multi-hour run """ ok = MagicMock(value=0.5) faith = MagicMock(ascore=AsyncMock(side_effect=RuntimeError("max_tokens"))) relev = MagicMock(ascore=AsyncMock(return_value=ok)) prec = MagicMock(ascore=AsyncMock(return_value=ok)) with ( patch("askme.evaluation.compare.llm_factory"), patch("askme.evaluation.compare.OpenAIEmbeddings"), patch("askme.evaluation.compare.Faithfulness", return_value=faith), patch("askme.evaluation.compare.AnswerRelevancy", return_value=relev), patch("askme.evaluation.compare.ContextPrecisionWithReference", return_value=prec), ): [row] = asyncio.run( judge_samples( parse_spec("j"), [{"question": "q", "reference": "r", "answer": "a", "contexts": ["c"]}], ) ) assert row["faithfulness"] is None assert "max_tokens" in row["errors"]["faithfulness"] assert row["answer_relevancy"] == 0.5 and row["context_precision"] == 0.5 def test_comparison_markdown_shows_failed_counts(): """ Scenario: some judge calls failed in a cell Given a cell whose report counts 2 failed faithfulness calls When comparison_markdown renders it Then the cell reads "0.500 (2 failed)" so a mean over fewer questions is visible """ scores = {("g1", "j1"): {"faithfulness": 0.5, "answer_relevancy": 0.6, "context_precision": 0.7, "failed": {"faithfulness": 2}}} md = comparison_markdown(["g1"], ["j1"], scores, keyword_overlap={"g1": 1.0}) assert "| g1 | 0.500 (2 failed) |" in md