| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | import unittest |
| 12 | from dataclasses import dataclass, field |
| 13 | |
| 14 | from src.eval import runner as R |
| 15 | |
| 16 | |
| 17 | |
| 18 | @dataclass |
| 19 | class _Chunk: |
| 20 | chunk_id: str |
| 21 | level: str |
| 22 | text: str |
| 23 | span_ids: list |
| 24 | page_start: int |
| 25 | page_end: int |
| 26 | parent_id: str | None = None |
| 27 | doc_id: str = "doc" |
| 28 | sinif: str = "12" |
| 29 | ders: str = "biyoloji" |
| 30 | kaynak_turu: str = "ders_kitabi" |
| 31 | kinds: list = field(default_factory=list) |
| 32 | page_visual: str = "low_visual" |
| 33 | approx_tokens: int = 100 |
| 34 | |
| 35 | |
| 36 | class _StubRetriever: |
| 37 | |
| 38 | |
| 39 | def __init__(self, order): |
| 40 | self.order = order |
| 41 | |
| 42 | def retrieve(self, query, top_k=20, **kw): |
| 43 | return [(cid, 0.5) for cid in self.order[:top_k]] |
| 44 | |
| 45 | |
| 46 | class _StubReranker: |
| 47 | def rerank(self, query, pairs): |
| 48 | return [(cid, 0.9) for cid, _t in pairs] |
| 49 | |
| 50 | |
| 51 | class _StubLLMClient: |
| 52 | |
| 53 | |
| 54 | def __init__(self, text="Hucre zari secici gecirgendir [1]."): |
| 55 | self.text = text |
| 56 | self.calls = 0 |
| 57 | self._api_key = "test" |
| 58 | |
| 59 | def chat(self, prompt, system=None, **kw): |
| 60 | from src.pricing import Usage |
| 61 | from src.providers.llm import ChatResult |
| 62 | self.calls += 1 |
| 63 | return ChatResult(text=self.text, usage=Usage(input_cache_miss=10, output=5), |
| 64 | model="stub", latency_s=0.0, raw={}) |
| 65 | |
| 66 | |
| 67 | def _pipeline(llm=None): |
| 68 | |
| 69 | chunks = { |
| 70 | "c1": _Chunk("c1", "child", "gold metin bir", ["d#10.0"], 10, 10, parent_id="p1"), |
| 71 | "c2": _Chunk("c2", "child", "gold metin iki", ["d#11.0"], 11, 11, parent_id="p1"), |
| 72 | "c3": _Chunk("c3", "child", "alakasiz metin", ["d#90.0"], 90, 90, parent_id="p9"), |
| 73 | "p1": _Chunk("p1", "parent", "parent metni", ["d#10.0", "d#11.0"], 10, 11), |
| 74 | } |
| 75 | span_meta = {"d#10.0": {"page": 10, "bbox": (0, 0, 1, 1)}, |
| 76 | "d#11.0": {"page": 11, "bbox": (0, 0, 1, 1)}, |
| 77 | "d#90.0": {"page": 90, "bbox": (0, 0, 1, 1)}} |
| 78 | ds = llm or _StubLLMClient() |
| 79 | from src.generate import Generator |
| 80 | gen = Generator(_StubRetriever(["c3", "c3", "c1", "c2"]), _StubReranker(), |
| 81 | chunks, span_meta, ds, ders="biyoloji", abstain_score=0.30, |
| 82 | module="test", cost_recorder=lambda **kw: None) |
| 83 | return {"chunks_by_id": chunks, "span_meta": span_meta, |
| 84 | "retriever": _StubRetriever(["c3", "c3", "c1", "c2"]), |
| 85 | "reranker": _StubReranker(), "generator": gen, "doc": None}, ds |
| 86 | |
| 87 | |
| 88 | _ITEM = {"id": "t1", "soru": "Hucre zari nedir?", "kategori": "orta", |
| 89 | "unite": "U1", "kazanim_kod": "1.1", "critical": False, |
| 90 | "beklenen_davranis": "cevapla", |
| 91 | "gold_kaynak_spanlar": ["d#10.0", "d#11.0"], "gold_sayfalar": [10, 11], |
| 92 | "gold_cevap": "gold cevap", "zararli_kategori": None} |
| 93 | |
| 94 | |
| 95 | class ModeValidationTests(unittest.TestCase): |
| 96 | def test_modes_exported(self): |
| 97 | self.assertEqual(R.EVAL_MODES, |
| 98 | ("retrieval_only", "oracle_context", "end_to_end")) |
| 99 | |
| 100 | def test_unknown_mode_rejected(self): |
| 101 | pl, _ = _pipeline() |
| 102 | with self.assertRaises(ValueError): |
| 103 | R._eval_item(_ITEM, pl, None, set(), mode="uydurma") |
| 104 | |
| 105 | |
| 106 | class RetrievalOnlyTests(unittest.TestCase): |
| 107 | def test_no_llm_call_at_all(self): |
| 108 | |
| 109 | pl, ds = _pipeline() |
| 110 | out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") |
| 111 | self.assertEqual(ds.calls, 0) |
| 112 | self.assertEqual(out["mode"], "retrieval_only") |
| 113 | self.assertEqual(out["generation"]["cost_usd"], 0.0) |
| 114 | self.assertEqual(out["generation"]["reason"], "retrieval_only") |
| 115 | |
| 116 | def test_retrieval_metrics_still_computed(self): |
| 117 | pl, _ = _pipeline() |
| 118 | out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") |
| 119 | r = out["retrieval"] |
| 120 | self.assertAlmostEqual(r["recall_at_10"], 1.0) |
| 121 | self.assertEqual(r["n_gold_spans"], 2) |
| 122 | self.assertIsNotNone(r["ndcg_at_10"]) |
| 123 | |
| 124 | def test_citation_and_judge_are_empty_not_zero(self): |
| 125 | |
| 126 | pl, _ = _pipeline() |
| 127 | out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") |
| 128 | self.assertIsNone(out["citation"]["precision_page"]) |
| 129 | self.assertIsNone(out["judge"]) |
| 130 | self.assertIsNone(out["guardrail"]["abstained"]) |
| 131 | |
| 132 | |
| 133 | class RerankMeasuredAlwaysTests(unittest.TestCase): |
| 134 | def test_post_rerank_block_present_without_judge_ids(self): |
| 135 | |
| 136 | |
| 137 | pl, _ = _pipeline() |
| 138 | out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") |
| 139 | self.assertIn("retrieval_post_rerank", out) |
| 140 | self.assertIsNotNone(out["retrieval_post_rerank"]["recall_at_10"]) |
| 141 | |
| 142 | def test_fallback_rescues_second_gold_when_candidates_are_few(self): |
| 143 | |
| 144 | |
| 145 | |
| 146 | pl, _ = _pipeline() |
| 147 | out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") |
| 148 | self.assertEqual(out["retrieval"]["all_evidence_recall_at_10"], 1.0) |
| 149 | self.assertEqual(out["retrieval_post_rerank"]["all_evidence_recall_at_10"], 1.0) |
| 150 | |
| 151 | def test_diversity_constraint_no_longer_drops_second_gold(self): |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | chunks = { |
| 164 | "c1": _Chunk("c1", "child", "gold bir", ["d#10.0"], 10, 10, parent_id="p1"), |
| 165 | "c2": _Chunk("c2", "child", "gold iki", ["d#11.0"], 11, 11, parent_id="p1"), |
| 166 | } |
| 167 | order = ["c1", "c2"] |
| 168 | for k in range(2, 9): |
| 169 | cid = f"d{k}" |
| 170 | chunks[cid] = _Chunk(cid, "child", f"alakasiz {k}", [f"d#{90 + k}.0"], |
| 171 | 90 + k, 90 + k, parent_id=f"p{k}") |
| 172 | order.append(cid) |
| 173 | span_meta = {u: {"page": 1, "bbox": (0, 0, 1, 1)} |
| 174 | for ch in chunks.values() for u in ch.span_ids} |
| 175 | ds = _StubLLMClient() |
| 176 | from src.generate import Generator |
| 177 | gen = Generator(_StubRetriever(order), _StubReranker(), chunks, span_meta, ds, |
| 178 | ders="biyoloji", abstain_score=0.30, module="test", |
| 179 | cost_recorder=lambda **kw: None) |
| 180 | pl = {"chunks_by_id": chunks, "span_meta": span_meta, |
| 181 | "retriever": _StubRetriever(order), "reranker": _StubReranker(), |
| 182 | "generator": gen, "doc": None} |
| 183 | out = R._eval_item(_ITEM, pl, None, set(), mode="retrieval_only") |
| 184 | self.assertEqual(out["retrieval"]["all_evidence_recall_at_10"], 1.0) |
| 185 | self.assertEqual(out["retrieval_post_rerank"]["all_evidence_recall_at_10"], 1.0, |
| 186 | "ikinci gold kanıt rerank sonrası yine kayboldu") |
| 187 | self.assertAlmostEqual(out["retrieval_post_rerank"]["recall_at_10"], 1.0) |
| 188 | |
| 189 | |
| 190 | class OracleContextTests(unittest.TestCase): |
| 191 | def test_oracle_uses_gold_chunks_only(self): |
| 192 | pl, ds = _pipeline() |
| 193 | out = R._eval_item(_ITEM, pl, None, set(), mode="oracle_context") |
| 194 | self.assertEqual(out["mode"], "oracle_context") |
| 195 | self.assertEqual(out["n_oracle_chunks"], 2) |
| 196 | self.assertEqual(ds.calls, 1) |
| 197 | |
| 198 | def test_oracle_chunk_ids_are_page_ordered(self): |
| 199 | pl, _ = _pipeline() |
| 200 | ids = R._oracle_chunk_ids({"d#10.0", "d#11.0"}, pl["chunks_by_id"]) |
| 201 | self.assertEqual(ids, ["c1", "c2"]) |
| 202 | |
| 203 | def test_oracle_excludes_parent_chunks(self): |
| 204 | |
| 205 | pl, _ = _pipeline() |
| 206 | ids = R._oracle_chunk_ids({"d#10.0"}, pl["chunks_by_id"]) |
| 207 | self.assertEqual(ids, ["c1"]) |
| 208 | self.assertNotIn("p1", ids) |
| 209 | |
| 210 | def test_oracle_disables_parent_expansion(self): |
| 211 | |
| 212 | |
| 213 | pl, _ = _pipeline() |
| 214 | gen, ids = R._oracle_generator(pl, {"d#10.0", "d#11.0"}) |
| 215 | for cid in ids: |
| 216 | self.assertIsNone(gen.chunks_by_id[cid].parent_id) |
| 217 | |
| 218 | def test_oracle_inherits_production_settings(self): |
| 219 | |
| 220 | |
| 221 | pl, _ = _pipeline() |
| 222 | gen, _ = R._oracle_generator(pl, {"d#10.0"}) |
| 223 | base = pl["generator"] |
| 224 | self.assertEqual(gen.abstain_score, base.abstain_score) |
| 225 | self.assertEqual(gen.ders, base.ders) |
| 226 | self.assertEqual(gen.context_packing, base.context_packing) |
| 227 | self.assertIs(gen.llm, base.llm) |
| 228 | |
| 229 | def test_item_without_gold_is_skipped_not_scored(self): |
| 230 | |
| 231 | edge = dict(_ITEM, id="e1", beklenen_davranis="cekimser", |
| 232 | gold_kaynak_spanlar=[], gold_sayfalar=[], gold_cevap=None) |
| 233 | pl, ds = _pipeline() |
| 234 | out = R._eval_item(edge, pl, None, set(), mode="oracle_context") |
| 235 | self.assertIn("skipped", out) |
| 236 | self.assertEqual(ds.calls, 0) |
| 237 | self.assertIsNone(out["citation"]["precision_page"]) |
| 238 | |
| 239 | |
| 240 | class EndToEndTests(unittest.TestCase): |
| 241 | def test_default_mode_is_end_to_end(self): |
| 242 | pl, ds = _pipeline() |
| 243 | out = R._eval_item(_ITEM, pl, None, set()) |
| 244 | self.assertEqual(out["mode"], "end_to_end") |
| 245 | self.assertEqual(ds.calls, 1) |
| 246 | self.assertIsNone(out["n_oracle_chunks"]) |
| 247 | |
| 248 | def test_uses_real_retriever_not_oracle(self): |
| 249 | pl, _ = _pipeline() |
| 250 | e2e = R._eval_item(_ITEM, pl, None, set()) |
| 251 | oracle = R._eval_item(_ITEM, pl, None, set(), mode="oracle_context") |
| 252 | |
| 253 | self.assertIsNone(e2e["n_oracle_chunks"]) |
| 254 | self.assertEqual(oracle["n_oracle_chunks"], 2) |
| 255 | |
| 256 | def test_error_attribution_is_computable(self): |
| 257 | |
| 258 | pl, _ = _pipeline() |
| 259 | e2e = R._eval_item(_ITEM, pl, None, set()) |
| 260 | oracle = R._eval_item(_ITEM, pl, None, set(), mode="oracle_context") |
| 261 | for out in (e2e, oracle): |
| 262 | self.assertIsNotNone(out["citation"]["recall_page"]) |
| 263 | |
| 264 | fark = (oracle["citation"]["recall_page"] - e2e["citation"]["recall_page"]) |
| 265 | self.assertIsInstance(fark, float) |
| 266 | |
| 267 | |
| 268 | class RunSignatureTests(unittest.TestCase): |
| 269 | def test_run_rejects_bad_mode_before_any_work(self): |
| 270 | with self.assertRaises(ValueError): |
| 271 | R.run(mode="yok") |
| 272 | |
| 273 | def test_retrieval_only_does_not_require_api_key(self): |
| 274 | |
| 275 | import os |
| 276 | from unittest import mock |
| 277 | from src.providers.llm import LLM_API_KEY_ENV, RETIRED_ENV_NAMES |
| 278 | |
| 279 | |
| 280 | clean = {k: "" for k in (LLM_API_KEY_ENV,) + RETIRED_ENV_NAMES} |
| 281 | with mock.patch.dict(os.environ, clean): |
| 282 | |
| 283 | |
| 284 | with self.assertRaises(RuntimeError): |
| 285 | R.run(mode="end_to_end", book_path="/olmayan/kitap.pdf") |
| 286 | with self.assertRaises(FileNotFoundError): |
| 287 | R.run(mode="retrieval_only", book_path="/olmayan/kitap.pdf") |
| 288 | |
| 289 | |
| 290 | if __name__ == "__main__": |
| 291 | unittest.main() |