diff --git a/src/evaluation/mutation.py b/src/evaluation/mutation.py new file mode 100644 index 0000000..73e292c --- /dev/null +++ b/src/evaluation/mutation.py @@ -0,0 +1,184 @@ +"""Mutasyon testi — kritik invariant'ların test/probe gücünü ölçer. + +Fikir (CheckList/mutation testing): kuralları KASITLI boz, kritik invariant +probe'larının bunu YAKALADIĞINI doğrula. Yakalanan mutasyon = "öldürülen". + mutation_score = öldürülen / toplam +Kritik invariant'lar için hedef %100'dür: yani gizlilik/collision/rol koruması +sağlayan hiçbir kural, testler fark etmeden bozulamamalı. + +Bu harness kural KATALOĞUNU (`rules._RAW_RULES`) bellek içinde mutasyona uğratır, +yeniden derler, `get_role_space` önbelleğini temizler, probe'ları koşar ve GERİ ALIR. +Kaynak dosyaya DOKUNMAZ. Çalıştırma: ``python -m src.evaluation.mutation``. +""" + +from __future__ import annotations + +import copy +from typing import Any, Callable + +from .. import rules as rules_mod +from ..engine import Engine +from ..role_spaces import get_role_space + + +# --- Kritik invariant probe'ları ------------------------------------------- +# (ad, sorgu, rol, invariant(resp)->bool). invariant, DOĞRU davranışta True döner; +# mutasyon onu bozarsa False (yakalandı). +Probe = tuple[str, str, str, Callable[[dict[str, Any]], bool]] + +def _intent_is(name: str) -> Callable[[dict[str, Any]], bool]: + return lambda r: r.get("intent") == name + +def _intent_not(name: str) -> Callable[[dict[str, Any]], bool]: + return lambda r: r.get("intent") != name + +def _safety_cat(cat: str) -> Callable[[dict[str, Any]], bool]: + return lambda r: (r.get("safety") or {}).get("category") == cat + + +PROBES: list[Probe] = [ + ("privacy_arkadas", "Sınıf arkadaşımın devamsızlığını söyle", "ogrenci", + _intent_is("privacy_security")), + ("privacy_baska_not", "Başka bir öğrencinin notunu görebilir miyim", "ogrenci", + _intent_is("privacy_security")), + ("exam_rejoin", "Sınava ikinci kez girme hakkım var mı?", "ogrenci", + _intent_not("exam_enter_room")), + ("attendance_policy", "Geç kalma devamsızlığa mı yazılır?", "ogrenci", + _intent_not("attendance_view")), + ("marks_own", "Ders notlarım listeleniyor", "ogrenci", + _intent_is("report_card_view")), # 'ders notlarım' -> karne (course_view none[not]) +] + + +# --- Mutasyonlar (kural kataloğunu bozar) ----------------------------------- +# Her mutasyon deepcopy edilmiş _RAW_RULES'u alır, bozar, döndürür. +Mutation = tuple[str, Callable[[list[dict[str, Any]]], list[dict[str, Any]]]] + + +def _drop_groups(raw, intent, token): + """intent'in 'all' listesi token içeren gruplarını siler.""" + for rule in raw: + if rule["intent"] == intent: + rule["groups"] = [g for g in rule["groups"] if token not in g.get("all", [])] + return raw + + +def _strip_none(raw, intent, token, all_kw=None): + """intent gruplarından bir 'none' token'ını kaldırır (all_kw verilirse yalnız o grup).""" + for rule in raw: + if rule["intent"] == intent: + for g in rule["groups"]: + if all_kw is not None and g.get("all") != all_kw: + continue + if token in g.get("none", []): + g["none"] = [t for t in g["none"] if t != token] + return raw + + +def _strip_all_none(raw, intent, all_kw=None): + """intent gruplarının TÜM none-guard'ını boşaltır (yük taşıyan korumayı kaldırır). + + all_kw verilirse yalnız o 'all' imzasına sahip grup; aksi halde tüm gruplar.""" + for rule in raw: + if rule["intent"] == intent: + for g in rule["groups"]: + if all_kw is not None and g.get("all") != all_kw: + continue + g["none"] = [] + return raw + + +MUTATIONS: list[Mutation] = [ + ("privacy: 'arkadaş' tetikleyicisini sil", + lambda raw: _drop_groups(raw, "privacy_security", "arkadaş")), + ("privacy: 'arkadaş+devamsız' kombosunu sil", + lambda raw: [r for r in raw if not (r["intent"] == "privacy_security" + and any(g.get("all") == ["arkadaş", "devamsız"] for g in r["groups"])) + ] or raw), + ("student_marks: {öğrenci,not,gör} none-guard'ını boşalt", + lambda raw: _strip_all_none(raw, "student_marks_lookup", ["öğrenci", "not", "gör"])), + ("exam_enter: {sınav,gir} none-guard'ını boşalt", + lambda raw: _strip_all_none(raw, "exam_enter_room", ["sınav", "gir"])), + ("attendance_view: {devamsız} none-guard'ını boşalt", + lambda raw: _strip_all_none(raw, "attendance_view", ["devamsız"])), + ("course_view: 'not' none-guard'ını kaldır (karne çakışması)", + lambda raw: _strip_none(raw, "course_view", "not")), +] + + +def _run_probes() -> dict[str, bool]: + """Her probe için invariant tutuyor mu? (True=doğru davranış).""" + engine = Engine() + results: dict[str, bool] = {} + for name, query, role, invariant in PROBES: + resp = engine.handle({ + "query": query, + "session": {"role": role, "authenticated": role != "ziyaretci"}, + }) + results[name] = invariant(resp) + return results + + +def _apply(mutate: Callable) -> None: + raw = copy.deepcopy(rules_mod._RAW_RULES) + mutated = mutate(raw) + rules_mod._RULES = rules_mod._compile_rules(mutated) + get_role_space.cache_clear() + + +def _restore(original_rules) -> None: + rules_mod._RULES = original_rules + get_role_space.cache_clear() + + +def compute() -> dict[str, Any]: + original = rules_mod._RULES + + # 0) Temel: mutasyonsuz tüm probe'lar tutmalı (aksi halde harness geçersiz). + baseline = _run_probes() + + rows: list[dict[str, Any]] = [] + try: + for name, mutate in MUTATIONS: + _apply(mutate) + after = _run_probes() + _restore(original) + # Öldürüldü mü? En az bir probe temelde True iken şimdi False olmalı. + killed = any(baseline[k] and not after[k] for k in after) + broke = [k for k in after if baseline[k] and not after[k]] + rows.append({"mutation": name, "killed": killed, "caught_by": broke}) + finally: + _restore(original) + + killed = sum(1 for r in rows if r["killed"]) + return { + "baseline_all_hold": all(baseline.values()), + "baseline": baseline, + "rows": rows, + "killed": killed, + "total": len(rows), + "score": killed / len(rows) if rows else 0.0, + } + + +def format_report(report: dict[str, Any]) -> str: + lines = [ + "============== MUTASYON TESTİ (kritik invariant) ==============", + f"Temel probe'lar hepsi tutuyor : {'EVET' if report['baseline_all_hold'] else 'HAYIR (!!)'}", + f"Mutation score (öldürülen) : {report['killed']}/{report['total']} " + f"= {report['score']:.0%} (kritik hedef %100)", + "--- Mutasyonlar ---", + ] + for r in report["rows"]: + mark = "KILLED " if r["killed"] else "SURVIVED" # survived = test açığı! + by = (", ".join(r["caught_by"])) if r["caught_by"] else "—" + lines.append(f" [{mark}] {r['mutation']} (yakalayan: {by})") + if report["score"] < 1.0: + lines.append("") + lines.append("UYARI: SURVIVED mutasyonlar = testlerin/probe'ların yakalayamadığı " + "kritik kural bozulmaları. Probe seti veya kural sağlamlaştırılmalı.") + return "\n".join(lines) + + +if __name__ == "__main__": + print(format_report(compute())) diff --git a/src/evaluation/selective.py b/src/evaluation/selective.py new file mode 100644 index 0000000..00ea8c3 --- /dev/null +++ b/src/evaluation/selective.py @@ -0,0 +1,188 @@ +"""Seçici sınıflandırma (selective classification / abstention) metrikleri. + +Ana ilke: "her soruyu cevaplamak" değil, "cevap verdiğinde çok yüksek olasılıkla +doğru olmak" (Geifman & El-Yaniv). Bu modül tek-eşik yerine RİSK–KAPSAMA eğrisi +çıkarır ve şu ürünleri üretir: + +- Risk–coverage eğrisi + AURC (düşük = daha iyi): kapsananlar arasında hata oranı. +- İşletim noktası (DEFAULT_THRESHOLD=0.18) için seçici risk + kapsama. +- OOS false-accept (kapsam-dışı ama cevaplanan) + near/far-OOS ayrımı. +- "Rule of three": sıfır-hatalı n test için gerçek hata oranının ~%95 üst sınırı 3/n. + +Çalıştırma: ``python -m src.evaluation.selective`` (markdown rapor stdout'a). +Kesinlikle deterministik: motoru (process) her örnek için bir kez çağırır. +""" + +from __future__ import annotations + +from typing import Any + +from ..decision import DEFAULT_THRESHOLD +from ..observability import process +from ..similarity import SimilarityMatcher +from .benchmark import OOS_LABEL, load_benchmark +from .evaluate import get_default_matcher + + +# near-OOS eşiği: benzerlik top-1 skoru bu değerin ÜSTÜNDEyse OOS örneği "desteklenen +# konuya benziyor" (near-OOS) sayılır; altındaysa far-OOS (tamamen ilgisiz). Alan +# kapısı eşiğiyle hizalı (domain-gate DEFAULT_THRESHOLD). +_NEAR_OOS_SCORE: float = DEFAULT_THRESHOLD + + +def _top1(trace: dict[str, Any]) -> tuple[str | None, float]: + """(top-1 intent, güven). Kural yolu -> güven 1.0; aksi halde benzerlik top-1.""" + + if trace["rule_layer"]["hit"]: + return trace["rule_layer"]["intent"], 1.0 + top_k = trace["similarity"].get("top_k") or [] + if not top_k: + return None, 0.0 + return top_k[0]["intent"], float(top_k[0]["score"]) + + +def collect_samples( + matcher: SimilarityMatcher | None = None, + records: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + """Her örnek için (güven, top-1, doğru mu, in_domain) toplar.""" + + matcher = matcher or get_default_matcher() + records = records if records is not None else load_benchmark() + + in_scope: list[dict[str, Any]] = [] # {conf, correct} + oos: list[dict[str, Any]] = [] # {conf, in_domain, accepted} + + for r in records: + role = r.get("role", "ziyaretci") + authenticated = role != "ziyaretci" + _, trace = process( + r["question"], role=role, authenticated=authenticated, matcher=matcher + ) + top1, conf = _top1(trace) + rule_hit = trace["rule_layer"]["hit"] + in_domain = trace["similarity"].get("in_domain", True) + expected = r["expected_intent"] + + if expected == OOS_LABEL: + # Kabul (accept) = kural çarptı VEYA (alan-içi ve güven >= eşik). + accepted = rule_hit or (in_domain and conf >= DEFAULT_THRESHOLD) + oos.append({"conf": conf, "in_domain": in_domain, "accepted": accepted}) + else: + in_scope.append({"conf": conf, "correct": top1 == expected}) + + return {"in_scope": in_scope, "oos": oos} + + +def risk_coverage_curve(in_scope: list[dict[str, Any]]) -> list[tuple[float, float]]: + """(coverage, selective_risk) noktaları: güvene göre azalan sırayla kümülatif. + + coverage = cevaplanan / toplam; risk = cevaplananlar arasında hata oranı. + """ + + ranked = sorted(in_scope, key=lambda s: s["conf"], reverse=True) + n = len(ranked) + points: list[tuple[float, float]] = [] + errors = 0 + for k, sample in enumerate(ranked, start=1): + if not sample["correct"]: + errors += 1 + points.append((k / n, errors / k)) + return points + + +def aurc(points: list[tuple[float, float]]) -> float: + """Risk–coverage eğrisi altındaki alan (kapsamaya göre ortalama risk).""" + + if not points: + return 0.0 + return sum(risk for _cov, risk in points) / len(points) + + +def compute( + matcher: SimilarityMatcher | None = None, + records: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + samples = collect_samples(matcher, records) + in_scope = samples["in_scope"] + oos = samples["oos"] + + curve = risk_coverage_curve(in_scope) + + # İşletim noktası: güven >= DEFAULT_THRESHOLD olanları cevapla (kural=1.0 hep dahil). + answered = [s for s in in_scope if s["conf"] >= DEFAULT_THRESHOLD] + answered_wrong = sum(1 for s in answered if not s["correct"]) + op_coverage = len(answered) / len(in_scope) if in_scope else 0.0 + op_risk = answered_wrong / len(answered) if answered else 0.0 + + # OOS false-accept (genel + near/far). + def _fa(bucket: list[dict[str, Any]]) -> tuple[int, int]: + accepted = sum(1 for s in bucket if s["accepted"]) + return accepted, len(bucket) + + near = [s for s in oos if s["conf"] >= _NEAR_OOS_SCORE] + far = [s for s in oos if s["conf"] < _NEAR_OOS_SCORE] + fa_all, n_all = _fa(oos) + fa_near, n_near = _fa(near) + fa_far, n_far = _fa(far) + + return { + "n_in_scope": len(in_scope), + "n_oos": len(oos), + "aurc": aurc(curve), + "op_threshold": DEFAULT_THRESHOLD, + "op_coverage": op_coverage, + "op_selective_risk": op_risk, + "op_answered": len(answered), + "op_answered_wrong": answered_wrong, + "oos_false_accept": fa_all / n_all if n_all else 0.0, + "oos_fa_count": (fa_all, n_all), + "oos_fa_near": (fa_near, n_near), + "oos_fa_far": (fa_far, n_far), + "curve": curve, + } + + +def _rule_of_three(errors: int, n: int) -> str: + """Sıfır-hatalı n için ~%95 üst sınır 3/n; hata varsa gözlenen oranı ver.""" + + if n == 0: + return "n=0" + if errors == 0: + if n < 30: + return f"0 gözlendi (n={n} — güven aralığı için örnek küçük)" + return f"≤ {3.0 / n:.2%} (rule-of-three, n={n})" + return f"{errors / n:.2%} gözlendi ({errors}/{n})" + + +def format_report(report: dict[str, Any]) -> str: + fa_near_c, fa_near_n = report["oos_fa_near"] + fa_far_c, fa_far_n = report["oos_fa_far"] + aw, an = report["op_answered_wrong"], report["op_answered"] + lines = [ + "========= SEÇİCİ SINIFLANDIRMA (SELECTIVE RISK) =========", + f"In-scope / OOS örnek : {report['n_in_scope']} / {report['n_oos']}", + "--- Risk–Coverage ---", + f"AURC (düşük=iyi) : {report['aurc']:.4f}", + f"İşletim eşiği : {report['op_threshold']:.3f}", + f" Kapsama (coverage) : {report['op_coverage']:.1%}", + f" Seçici risk : {report['op_selective_risk']:.2%} ({aw}/{an} yanlış)", + f" Kabul-doğruluk üst sın.: {_rule_of_three(aw, an)}", + "--- OOS false-accept (kapsam-dışı ama cevaplanan) ---", + f" Genel : {report['oos_false_accept']:.2%} " + f"({report['oos_fa_count'][0]}/{report['oos_fa_count'][1]})", + f" near-OOS (benzeyen) : {_rule_of_three(fa_near_c, fa_near_n)}", + f" far-OOS (ilgisiz) : {_rule_of_three(fa_far_c, fa_far_n)}", + "--- Risk–coverage eğrisi (örnek noktalar) ---", + ] + curve = report["curve"] + for frac in (0.5, 0.7, 0.8, 0.9, 0.95, 1.0): + idx = min(len(curve) - 1, int(frac * len(curve)) - 1) + if idx >= 0: + cov, risk = curve[idx] + lines.append(f" coverage≈{cov:>5.0%} -> risk={risk:.2%}") + return "\n".join(lines) + + +if __name__ == "__main__": + print(format_report(compute())) diff --git a/src/main.py b/src/main.py index 4adc61f..3cc55fe 100644 --- a/src/main.py +++ b/src/main.py @@ -30,6 +30,16 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="Benchmark üzerinde tam değerlendirme raporu üretir.", ) + parser.add_argument( + "--selective", + action="store_true", + help="Seçici sınıflandırma raporu (risk-coverage, AURC, OOS false-accept).", + ) + parser.add_argument( + "--mutation", + action="store_true", + help="Mutasyon testi: kritik invariant'ların yakalanma gücü (mutation score).", + ) parser.add_argument( "--chat", action="store_true", @@ -51,6 +61,18 @@ def main() -> int: print(format_report(run_evaluation())) return 0 + if args.selective: + from .evaluation.selective import compute, format_report as fmt_sel + + print(fmt_sel(compute())) + return 0 + + if args.mutation: + from .evaluation.mutation import compute, format_report as fmt_mut + + print(fmt_mut(compute())) + return 0 + if args.validate: print_validation_result(validate_catalog()) return 0 diff --git a/tests/integration/test_selective_mutation.py b/tests/integration/test_selective_mutation.py new file mode 100644 index 0000000..c58e116 --- /dev/null +++ b/tests/integration/test_selective_mutation.py @@ -0,0 +1,52 @@ +"""Seçici sınıflandırma + mutasyon testi regresyonu. + +Kalite kapıları (kriterler.md ile hizalı): +- Mutasyon score = %100 (kritik invariant'lar bozulunca probe'lar YAKALAR). +- İşletim noktasında seçici risk düşük (kabul edilen cevaplarda az hata). +- OOS false-accept ölçülür ve raporlanır (regresyonda artışı fark edelim). + +Bu testler ölçüm altyapısının kendisini de korur (harness bozulursa fark edilir). +""" + +import unittest + +from src.evaluation import mutation, selective + + +class MutationScoreTests(unittest.TestCase): + def test_baseline_probes_all_hold(self) -> None: + report = mutation.compute() + self.assertTrue( + report["baseline_all_hold"], + f"Temel invariant probe'ları tutmuyor: {report['baseline']}", + ) + + def test_mutation_score_is_perfect(self) -> None: + # Kritik invariant'lar için mutasyon score = %100 (hepsi öldürülmeli). + report = mutation.compute() + survived = [r["mutation"] for r in report["rows"] if not r["killed"]] + self.assertEqual(report["score"], 1.0, f"Hayatta kalan mutasyonlar: {survived}") + + +class SelectiveRiskTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.report = selective.compute() + + def test_operating_selective_risk_low(self) -> None: + # İşletim eşiğinde kabul edilen cevaplarda hata oranı <= %1 (şu an ~%0.5). + self.assertLessEqual(self.report["op_selective_risk"], 0.01) + + def test_aurc_low(self) -> None: + # Risk-coverage eğrisi altındaki alan küçük (iyi ayrışma). + self.assertLessEqual(self.report["aurc"], 0.02) + + def test_oos_false_accept_reported(self) -> None: + # Ölçülüyor ve mantıklı aralıkta (regresyonda artışı yakalamak için üst sınır). + fa = self.report["oos_false_accept"] + self.assertGreaterEqual(fa, 0.0) + self.assertLessEqual(fa, 0.20, "OOS false-accept beklenenden yüksek — gerileme?") + + +if __name__ == "__main__": + unittest.main()