#29 runner per-item guard (bozuk item run'ı düşürmez) + dürüst maliyet-etiketi + judge per-metrik-n (survivorship görünür) + is_fail_closed docstring
Browse files at this commit1941569cd8d6a3f9407572db767d14805cff6346Parent: 8a9d0e9- fix
- #29 runner per-item guard (bozuk item run'ı düşürmez) + dürüst maliyet-etiketi + judge per-metrik-n (survivorship görünür) + is_fail_closed docstring
- runner/judge testleri (0-test'ti). Closes #29
4 changed files +200 -14
- src/eval/metrics.py +12 -7
- src/eval/runner.py +49 -7
- tests/unit/test_eval_judge.py +51 -0
- tests/unit/test_eval_runner.py +88 -0
src/eval/metrics.pymodified+12 -7
| @@ -206,13 +206,18 @@ def guardrail_pass(expected_behavior: str, abstained: bool, reason: str) -> bool | ||
| 206 | 206 | |
| 207 | 207 | |
| 208 | 208 | def is_fail_closed(abstained: bool, cost_usd: float) -> bool | None: |
| 209 | - """"Kanıt/karar yetersizse LLM'e GERÇEKTEN gidilmedi mi?" (OPTIMIZATION.md | |
| 210 | - §A hedefi: fail-closed %100). Yalnız abstain edilen item'lar için anlamlı | |
| 211 | - -> cevaplanan (abstained=False) item'larda tanımsız (None). | |
| 212 | - abstained=True VE cost_usd==0.0 -> LLM'e hiç gidilmedi (gerçek fail-closed). | |
| 213 | - abstained=True AMA cost_usd>0.0 -> LLM ÇAĞRILDI (ör. guard_output ya da | |
| 214 | - model_abstained) — çekimser/red SONUCA ULAŞTI ama maliyet zaten oluştu; | |
| 215 | - bu durum "sonuç doğru ama fail-closed değil" olarak False döner.""" | |
| 209 | + """"Pahalı ÜRETİM LLM'ine gidilmeden mi çekimser kalındı?" (OPTIMIZATION.md | |
| 210 | + §A hedefi). Yalnız abstain edilen item'lar için anlamlı -> cevaplanan | |
| 211 | + (abstained=False) item'larda None. | |
| 212 | + abstained=True VE cevap cost_usd==0.0 -> ÜRETİM LLM'i çağrılmadı (fail-closed): | |
| 213 | + regex/LLM-sınıflandırıcı red'i ya da retrieval fail-closed abstain'i. | |
| 214 | + abstained=True AMA cost_usd>0.0 -> üretim LLM'i ÇAĞRILDI (guard_output ya da | |
| 215 | + model_abstained) -> False. | |
| 216 | + DÜRÜST NOT (AUDIT EXP-007 #29/eval#5): burada cost_usd, GroundedAnswer'ın ÜRETİM | |
| 217 | + maliyetidir. LLM-güvenlik-sınıflandırıcısı (2. katman) red ederse üretim | |
| 218 | + çağrılmaz (cost_usd=0 -> True) ama sınıflandırıcının KENDİ küçük DeepSeek | |
| 219 | + maliyeti costlog'a AYRI (module=guard) yazılır — yani "cost_usd==0" 'hiç LLM | |
| 220 | + yok' DEĞİL, 'üretim LLM'i yok' demektir.""" | |
| 216 | 221 | if not abstained: |
| 217 | 222 | return None |
| 218 | 223 | return cost_usd == 0.0 |
src/eval/runner.pymodified+49 -7
| @@ -257,6 +257,27 @@ def _eval_item(item: dict, pipeline: dict, judge: LlmJudge | None, | ||
| 257 | 257 | } |
| 258 | 258 | |
| 259 | 259 | |
| 260 | +def _failed_item(item: dict, exc: Exception) -> dict: | |
| 261 | + """AUDIT EXP-007 #29/eval#4: bir golden item değerlendirilirken hata olursa | |
| 262 | + (eksik alan, pipeline hatası) TÜM run'ı düşürme — hatayı bu item'a kaydet, | |
| 263 | + aggregate ile uyumlu boş-metrik iskeleti dön, döngü devam etsin.""" | |
| 264 | + return { | |
| 265 | + "id": item.get("id", "?"), "kategori": item.get("kategori", "?"), | |
| 266 | + "unite": item.get("unite"), "kazanim_kod": item.get("kazanim_kod"), | |
| 267 | + "critical": bool(item.get("critical")), | |
| 268 | + "beklenen_davranis": item.get("beklenen_davranis", "?"), | |
| 269 | + "zararli_kategori": item.get("zararli_kategori"), | |
| 270 | + "soru": item.get("soru", ""), | |
| 271 | + "retrieval": {}, "citation": {}, | |
| 272 | + "guardrail": {"passed": None, "fail_closed": None, "abstained": None, "reason": "eval_error"}, | |
| 273 | + "generation": {"text": "", "abstained": None, | |
| 274 | + "reason": f"eval_error: {type(exc).__name__}", "n_citations": 0, | |
| 275 | + "invalid_citations": [], "cost_usd": 0.0, "latency_s": 0.0}, | |
| 276 | + "judge": None, | |
| 277 | + "error": f"{type(exc).__name__}: {exc}", | |
| 278 | + } | |
| 279 | + | |
| 280 | + | |
| 260 | 281 | # -------------------------------------------------------------------------- |
| 261 | 282 | # Aggregate + rapor |
| 262 | 283 | # -------------------------------------------------------------------------- |
| @@ -280,9 +301,17 @@ def _aggregate(subset: list[dict]) -> dict: | ||
| 280 | 301 | judged = [it["judge"] for it in subset if it["judge"] and not it["judge"].get("skipped")] |
| 281 | 302 | judge_agg = {k: M.mean([j.get(k) for j in judged]) for k in _JUDGE_KEYS} |
| 282 | 303 | judge_agg["n_judged"] = len(judged) |
| 304 | + # AUDIT EXP-007 #29/eval#6: mean() None'ları düşürür → "faithfulness (n=N)" ama | |
| 305 | + # ortalama gerçekte < N item üzerinden olabilir (judge hatası → skor None ama | |
| 306 | + # skipped değil → judged'da kalır). Her metrik için KATKI VEREN (None-olmayan) | |
| 307 | + # sayıyı + hakem-hata sayısını AYRI raporla (survivorship pass-bias görünür olsun). | |
| 308 | + for k in _JUDGE_KEYS: | |
| 309 | + judge_agg[k + "_n"] = sum(1 for j in judged if j.get(k) is not None) | |
| 310 | + judge_agg["n_errors"] = sum(1 for j in judged if j.get("errors")) | |
| 283 | 311 | return {"n": n, "retrieval": retrieval, "citation": citation, |
| 284 | 312 | "guardrail_pass_rate": guardrail_pass_rate, "n_guardrail_applicable": len(guardrail_vals), |
| 285 | 313 | "fail_closed_rate": fail_closed_rate, "n_abstained": len(fc_vals), |
| 314 | + "n_errors": sum(1 for it in subset if it.get("error")), | |
| 286 | 315 | "judge": judge_agg} |
| 287 | 316 | |
| 288 | 317 | |
| @@ -292,6 +321,8 @@ def _weakness_score(it: dict) -> float: | ||
| 292 | 321 | hatasi her zaman en kritik zayifliktir. Aksi halde mevcut (None olmayan) |
| 293 | 322 | kalite sinyallerinin ortalamasi (retrieval recall@20, citation recall, |
| 294 | 323 | faithfulness, answer_correctness).""" |
| 324 | + if it.get("error"): # #29: değerlendirilemeyen item en zayıf (görünür kalsın) | |
| 325 | + return 0.0 | |
| 295 | 326 | g = it["guardrail"]["passed"] |
| 296 | 327 | if g is False: |
| 297 | 328 | return 0.0 |
| @@ -329,7 +360,9 @@ def _md_report(golden: dict, items_out: list[dict], overall: dict, by_category: | ||
| 329 | 360 | lines.append(f"- Item sayisi: {len(items_out)}") |
| 330 | 361 | lines.append(f"- LLM-hakem yontemi: **{judge_method}** (DeepEval kutuphanesi + DeepSeek custom judge model)") |
| 331 | 362 | lines.append(f"- LLM-hakem uygulanan item'lar ({len(judge_ids)}): {', '.join(sorted(judge_ids))}") |
| 332 | - lines.append(f"- Toplam GERCEK DeepSeek maliyeti (bu eval kosusu, uretim+hakem): ${total_cost_usd:.6f}") | |
| 363 | + lines.append(f"- DeepSeek maliyeti (bu eval kosusu, URETIM + HAKEM): ${total_cost_usd:.6f} " | |
| 364 | + f"— NOT: guard LLM-siniflandirici + history-rewrite cagrilarinin maliyeti " | |
| 365 | + f"costlog'da AYRI (module=guard/memory); bu toplam yalniz uretim+hakem'dir (#29).") | |
| 333 | 366 | lines.append("") |
| 334 | 367 | |
| 335 | 368 | lines.append("## Genel (tum item'lar)") |
| @@ -393,9 +426,14 @@ def _aggregate_table(agg: dict) -> str: | ||
| 393 | 426 | lines.append(f"| citation recall | {_fmt(c.get('recall'))} |") |
| 394 | 427 | lines.append(f"| guardrail pass-rate (n={agg['n_guardrail_applicable']}) | {_fmt(agg['guardrail_pass_rate'])} |") |
| 395 | 428 | lines.append(f"| fail-closed orani (n={agg['n_abstained']} abstain) | {_fmt(agg['fail_closed_rate'])} |") |
| 396 | - lines.append(f"| faithfulness (n={j['n_judged']}) | {_fmt(j.get('faithfulness'))} |") | |
| 397 | - lines.append(f"| answer_relevancy (n={j['n_judged']}) | {_fmt(j.get('answer_relevancy'))} |") | |
| 398 | - lines.append(f"| answer_correctness (n={j['n_judged']}) | {_fmt(j.get('answer_correctness'))} |") | |
| 429 | + # per-metrik n = ortalamaya KATKI VEREN item (hakem hatası olanlar hariç, #29) | |
| 430 | + lines.append(f"| faithfulness (n={j.get('faithfulness_n', j['n_judged'])}) | {_fmt(j.get('faithfulness'))} |") | |
| 431 | + lines.append(f"| answer_relevancy (n={j.get('answer_relevancy_n', j['n_judged'])}) | {_fmt(j.get('answer_relevancy'))} |") | |
| 432 | + lines.append(f"| answer_correctness (n={j.get('answer_correctness_n', j['n_judged'])}) | {_fmt(j.get('answer_correctness'))} |") | |
| 433 | + if j.get("n_errors"): | |
| 434 | + lines.append(f"| ⚠ hakem-hatası item | {j['n_errors']} (skor None → ortalamaya girmedi) |") | |
| 435 | + if agg.get("n_errors"): | |
| 436 | + lines.append(f"| ⚠ değerlendirilemeyen item (eval_error) | {agg['n_errors']} |") | |
| 399 | 437 | return "\n".join(lines) |
| 400 | 438 | |
| 401 | 439 | |
| @@ -419,8 +457,12 @@ def run(golden_path: str = GOLDEN_PATH, book_path: str = BOOK_PATH, | ||
| 419 | 457 | |
| 420 | 458 | items_out = [] |
| 421 | 459 | for i, item in enumerate(items, start=1): |
| 422 | - print(f"[eval] ({i}/{len(items)}) {item['id']}: {item['soru'][:70]!r}") | |
| 423 | - it_out = _eval_item(item, pipeline, judge, judge_ids) | |
| 460 | + print(f"[eval] ({i}/{len(items)}) {item.get('id','?')}: {str(item.get('soru',''))[:70]!r}") | |
| 461 | + try: | |
| 462 | + it_out = _eval_item(item, pipeline, judge, judge_ids) | |
| 463 | + except Exception as e: # #29: tek bozuk item run'ı düşürmesin | |
| 464 | + print(f" !! HATA ({type(e).__name__}: {e}) -- item atlandı, run devam") | |
| 465 | + it_out = _failed_item(item, e) | |
| 424 | 466 | items_out.append(it_out) |
| 425 | 467 | print(f" -> abstained={it_out['generation']['abstained']} " |
| 426 | 468 | f"reason={it_out['generation']['reason']!r} " |
| @@ -463,7 +505,7 @@ def run(golden_path: str = GOLDEN_PATH, book_path: str = BOOK_PATH, | ||
| 463 | 505 | |
| 464 | 506 | print(f"\n[eval] TAMAM ({elapsed_s:.1f}s). JSON: {json_path}") |
| 465 | 507 | print(f"[eval] MD: {md_path}") |
| 466 | - print(f"[eval] toplam gercek DeepSeek maliyeti (bu kosuda): ${total_cost_usd:.6f}") | |
| 508 | + print(f"[eval] DeepSeek maliyeti (uretim+hakem; guard/rewrite costlog'da ayri): ${total_cost_usd:.6f}") | |
| 467 | 509 | return payload |
| 468 | 510 | |
| 469 | 511 |
tests/unit/test_eval_judge.pyadded+51 -0
| @@ -0,0 +1,51 @@ | ||
| 1 | +"""eval/judge testleri (AUDIT EXP-007 #29 — judge 0-test'ti). Ağ yok: sahte DeepSeek. | |
| 2 | +DeepEval import'u gerektiğinden yoksa atla.""" | |
| 3 | +import unittest | |
| 4 | + | |
| 5 | +try: | |
| 6 | + from src.eval.judge import DeepSeekJudgeModel | |
| 7 | + _HAS_DEEPEVAL = True | |
| 8 | +except Exception: | |
| 9 | + _HAS_DEEPEVAL = False | |
| 10 | + | |
| 11 | +from src.pricing import Usage | |
| 12 | + | |
| 13 | + | |
| 14 | +class _Chat: | |
| 15 | + def __init__(self, txt): self.text = txt; self.usage = Usage(output=3); \ | |
| 16 | + self.model = "deepseek-chat"; self.latency_s = 0.0 | |
| 17 | +class _FakeDS: | |
| 18 | + def __init__(self): self.calls = [] | |
| 19 | + def chat(self, prompt, **k): self.calls.append(k); return _Chat('{"ok":1}') | |
| 20 | + | |
| 21 | + | |
| 22 | +@unittest.skipUnless(_HAS_DEEPEVAL, "deepeval yok") | |
| 23 | +class JudgeModelTests(unittest.TestCase): | |
| 24 | + def _model(self): | |
| 25 | + m = DeepSeekJudgeModel() | |
| 26 | + m._ds = _FakeDS() | |
| 27 | + return m | |
| 28 | + | |
| 29 | + def test_schema_forces_json_mode(self): | |
| 30 | + m = self._model() | |
| 31 | + out = m.generate("değerlendir", schema={"a": 1}) | |
| 32 | + self.assertEqual(out, '{"ok":1}') | |
| 33 | + self.assertEqual(m._ds.calls[-1].get("extra"), | |
| 34 | + {"response_format": {"type": "json_object"}}) | |
| 35 | + | |
| 36 | + def test_no_schema_no_extra(self): | |
| 37 | + m = self._model() | |
| 38 | + m.generate("düz istek") | |
| 39 | + self.assertIsNone(m._ds.calls[-1].get("extra")) | |
| 40 | + | |
| 41 | + def test_usage_since_sums(self): | |
| 42 | + m = self._model() | |
| 43 | + cp = len(m.usages) | |
| 44 | + m.generate("a", schema={"x": 1}) | |
| 45 | + m.generate("b") | |
| 46 | + u = m.usage_since(cp) | |
| 47 | + self.assertEqual(u.output, 6) # 3 + 3 | |
| 48 | + | |
| 49 | + | |
| 50 | +if __name__ == "__main__": | |
| 51 | + unittest.main() |
tests/unit/test_eval_runner.pyadded+88 -0
| @@ -0,0 +1,88 @@ | ||
| 1 | +"""eval/runner saf-fonksiyon testleri (AUDIT EXP-007 #29 — runner 0-test'ti). | |
| 2 | +Ağ/model gerektirmez; yalnız aggregate/seçim/skor mantığı.""" | |
| 3 | +import unittest | |
| 4 | + | |
| 5 | +from src.eval import runner as R | |
| 6 | + | |
| 7 | + | |
| 8 | +def _item(id, beh="cevapla", critical=False, unite=None, | |
| 9 | + recall20=None, citR=None, judge=None, guard_passed=None, fail_closed=None, | |
| 10 | + error=None): | |
| 11 | + d = { | |
| 12 | + "id": id, "kategori": "orta", "unite": unite, "beklenen_davranis": beh, | |
| 13 | + "critical": critical, | |
| 14 | + "retrieval": {"recall_at_20": recall20, "recall_at_10": recall20}, | |
| 15 | + "citation": {"recall": citR, "precision": None}, | |
| 16 | + "guardrail": {"passed": guard_passed, "fail_closed": fail_closed, | |
| 17 | + "abstained": False, "reason": ""}, | |
| 18 | + "judge": judge, | |
| 19 | + } | |
| 20 | + if error: | |
| 21 | + d["error"] = error | |
| 22 | + return d | |
| 23 | + | |
| 24 | + | |
| 25 | +class SelectJudgeIdsTests(unittest.TestCase): | |
| 26 | + def test_critical_and_unite_backfill(self): | |
| 27 | + items = [ | |
| 28 | + {"id": "a", "beklenen_davranis": "cevapla", "critical": True, "unite": "U1"}, | |
| 29 | + {"id": "b", "beklenen_davranis": "cevapla", "critical": False, "unite": "U1"}, | |
| 30 | + {"id": "c", "beklenen_davranis": "cevapla", "critical": False, "unite": "U2"}, | |
| 31 | + {"id": "d", "beklenen_davranis": "red", "critical": True, "unite": "U3"}, # cevapla değil → yok | |
| 32 | + ] | |
| 33 | + ids = R._select_judge_ids(items) | |
| 34 | + self.assertIn("a", ids) # critical cevapla | |
| 35 | + self.assertIn("c", ids) # U2 temsil edilmemişti → backfill | |
| 36 | + self.assertNotIn("b", ids) # U1 zaten 'a' ile temsil | |
| 37 | + self.assertNotIn("d", ids) # red → hakem yok | |
| 38 | + | |
| 39 | + def test_missing_unite_no_crash(self): | |
| 40 | + items = [{"id": "x", "beklenen_davranis": "cevapla", "critical": True}] # unite yok | |
| 41 | + self.assertEqual(R._select_judge_ids(items), {"x"}) | |
| 42 | + | |
| 43 | + | |
| 44 | +class AggregateTests(unittest.TestCase): | |
| 45 | + def test_none_drop_and_per_metric_n(self): | |
| 46 | + items = [ | |
| 47 | + _item("a", recall20=1.0, citR=0.8, | |
| 48 | + judge={"faithfulness": 0.9, "answer_relevancy": 1.0, "answer_correctness": 0.8}), | |
| 49 | + _item("b", recall20=0.5, citR=None, | |
| 50 | + judge={"faithfulness": None, "answer_relevancy": 1.0, # faith None (hakem hatası) | |
| 51 | + "answer_correctness": 0.6, "errors": ["timeout"]}), | |
| 52 | + ] | |
| 53 | + agg = R._aggregate(items) | |
| 54 | + self.assertAlmostEqual(agg["retrieval"]["recall_at_20"], 0.75) | |
| 55 | + self.assertEqual(agg["judge"]["n_judged"], 2) | |
| 56 | + self.assertEqual(agg["judge"]["faithfulness_n"], 1) # yalnız 'a' katkı verdi | |
| 57 | + self.assertEqual(agg["judge"]["answer_relevancy_n"], 2) | |
| 58 | + self.assertEqual(agg["judge"]["n_errors"], 1) | |
| 59 | + self.assertAlmostEqual(agg["judge"]["faithfulness"], 0.9) # None düştü → tek değer | |
| 60 | + | |
| 61 | + def test_empty_subset(self): | |
| 62 | + agg = R._aggregate([]) | |
| 63 | + self.assertEqual(agg["n"], 0) | |
| 64 | + self.assertIsNone(agg["guardrail_pass_rate"]) | |
| 65 | + | |
| 66 | + | |
| 67 | +class WeaknessScoreTests(unittest.TestCase): | |
| 68 | + def test_guardrail_fail_is_zero(self): | |
| 69 | + self.assertEqual(R._weakness_score(_item("a", guard_passed=False)), 0.0) | |
| 70 | + def test_error_item_is_zero(self): | |
| 71 | + self.assertEqual(R._weakness_score(R._failed_item({"id": "e"}, ValueError("x"))), 0.0) | |
| 72 | + def test_normal_average(self): | |
| 73 | + it = _item("a", recall20=1.0, citR=0.6) | |
| 74 | + self.assertAlmostEqual(R._weakness_score(it), 0.8) # (1.0+0.6)/2 | |
| 75 | + | |
| 76 | + | |
| 77 | +class FailedItemTests(unittest.TestCase): | |
| 78 | + def test_failed_item_aggregate_compatible(self): | |
| 79 | + fi = R._failed_item({"id": "z", "kategori": "orta", "soru": "s"}, KeyError("beklenen_davranis")) | |
| 80 | + # aggregate ile uyumlu (çökmeden işlenmeli) | |
| 81 | + agg = R._aggregate([fi]) | |
| 82 | + self.assertEqual(agg["n"], 1) | |
| 83 | + self.assertEqual(agg["n_errors"], 1) | |
| 84 | + self.assertIn("eval_error", fi["generation"]["reason"]) | |
| 85 | + | |
| 86 | + | |
| 87 | +if __name__ == "__main__": | |
| 88 | + unittest.main() |