"""Rater agreement audit: measure how well reward raters agree, per rule. This is the regression harness for reward iteration. It scores a labeled corpus with two raters (``static`` and ``decision`` by default) and reports, for every rule in the 13-rule set: * agreement rate between the two raters (same sign / both neutral), * cases where the static rule is *wrong in the dangerous direction* -- i.e. it returns a positive reward for code that violates the rule. Those silently reward bad code during training and are the highest-priority fixes. The corpus is plain Python files in a directory with a ``labels.json`` mapping ``filename -> expected rules dict``. Expected values are only used for informational "static vs expected" reporting; the audit's core output is rater-vs-rater, which needs no hand labels. Usage ----- guac-audit --corpus ./audit_corpus --rater-a static --rater-b decision """ import json import logging import os from typing import Any, Dict, List, Optional from guac_coder.config import RewardConfig from guac_coder.training import score_completion logger = logging.getLogger("guac_coder.rater_audit") # A rule's reward is positive when the code complies, negative when it violates. # This set marks rules where a *positive* score is only ever credit, so a # positive score on violating code means the detector missed the violation. VIOLATION_RULES = [ "no_seaborn_reward", "no_plot_grids_reward", "no_plot_titles_reward", "no_bargraphs_reward", "no_try_except_reward", "no_classes_reward", "resumable_checkpoint_reward", "not_bare_script_reward", "objective_comments_reward", "intermittent_writes_reward", "pandas_csv_preference_reward", "logging_over_print_reward", "chroptiks_preference_reward", ] def load_corpus(corpus_dir: str) -> List[Dict[str, Any]]: """Load ``*.py`` files (plus optional ``labels.json``) from a directory.""" if not os.path.isdir(corpus_dir): raise SystemExit(f"error: no such corpus directory: {corpus_dir}") labels: Dict[str, Dict[str, float]] = {} labels_path = os.path.join(corpus_dir, "labels.json") if os.path.isfile(labels_path): with open(labels_path, "r", encoding="utf-8") as fh: labels = json.load(fh) cases = [] for name in sorted(os.listdir(corpus_dir)): if not name.endswith(".py"): continue path = os.path.join(corpus_dir, name) with open(path, "r", encoding="utf-8") as fh: code = fh.read() cases.append({"name": name, "code": code, "expected": labels.get(name, {})}) if not cases: raise SystemExit(f"error: no .py files found in {corpus_dir}") return cases def _sign(value: float) -> int: if value > 1e-9: return 1 if value < -1e-9: return -1 return 0 def score_corpus( cases: List[Dict[str, Any]], rater: str, reward_cfg: Optional[RewardConfig] = None, rater_model: Optional[str] = None, ) -> List[Dict[str, Any]]: """Score every case with one rater, returning per-case rule breakdowns. A decision or LLM rater is scored **strictly**: any failure is recorded as a failed case rather than silently falling back to the static rules. An audit that let the decision rater fall back to static would report perfect agreement for a rater that never ran, which is worse than no audit. """ cfg = reward_cfg or RewardConfig() if rater_model: cfg.decision_model = rater_model cfg.rater = rater cfg.decision_on_error = "raise" scored = [] for case in cases: try: total, details = score_completion(case["code"], lambda **kwargs: {}, cfg, rater=rater) except Exception as exc: logger.error("%s rater=%s FAILED: %s", case["name"], rater, exc) scored.append( { "name": case["name"], "total": None, "rules": {}, "expected": case.get("expected", {}), "failed": str(exc), } ) continue scored.append( { "name": case["name"], "total": total, "rules": details.get("rules", {}), "expected": case.get("expected", {}), "failed": None, } ) logger.info("%s rater=%s total=%+.3f", case["name"], rater, total) return scored def label_accuracy(rows: List[Dict[str, Any]]) -> Dict[str, Any]: """Score one rater against the corpus labels, where labels exist. Rater-vs-rater comparison can only say the two disagree; it cannot say which is right. Labels supply that ground truth, so a weak second rater does not get to redefine correctness. """ per_rule: Dict[str, Dict[str, Any]] = {} misses: List[Dict[str, Any]] = [] for row in rows: if row.get("failed"): continue for rule, expected in (row.get("expected") or {}).items(): got = row["rules"].get(rule) if got is None: continue stats = per_rule.setdefault(rule, {"n": 0, "correct": 0}) stats["n"] += 1 # Compare position, not magnitude: the labels express the intended # direction, not an exact value. if _sign(got) == _sign(expected): stats["correct"] += 1 else: misses.append( { "case": row["name"], "rule": rule, "got": got, "expected": expected, } ) checked = sum(s["n"] for s in per_rule.values()) correct = sum(s["correct"] for s in per_rule.values()) return { "n_labeled": checked, "n_correct": correct, "accuracy": round(correct / checked, 3) if checked else None, "rules": { rule: { "n": s["n"], "correct": s["correct"], "accuracy": round(s["correct"] / s["n"], 3) if s["n"] else None, } for rule, s in per_rule.items() }, "misses": misses, } def compare_raters( a: List[Dict[str, Any]], b: List[Dict[str, Any]], name_a: str = "static", name_b: str = "decision", ) -> Dict[str, Any]: """Compare two scored corpora rule by rule.""" by_name_b = {row["name"]: row for row in b} rule_stats: Dict[str, Dict[str, Any]] = {} disagreements: List[Dict[str, Any]] = [] failed_a = [r["name"] for r in a if r.get("failed")] failed_b = [r["name"] for r in b if r.get("failed")] reason_a = next((r["failed"] for r in a if r.get("failed")), None) reason_b = next((r["failed"] for r in b if r.get("failed")), None) compared = 0 for row_a in a: row_b = by_name_b.get(row_a["name"]) if row_b is None: continue if row_a.get("failed") or row_b.get("failed"): continue compared += 1 for rule in VIOLATION_RULES: va = row_a["rules"].get(rule) vb = row_b["rules"].get(rule) if va is None or vb is None: continue stats = rule_stats.setdefault( rule, { "n": 0, "agree": 0, "disagree": 0, "abstain": 0, "a_positive_b_negative": 0, "a_negative_b_positive": 0, "gap_sum": 0.0, "worst": None, }, ) stats["n"] += 1 sa, sb = _sign(va), _sign(vb) # A neutral value is an *abstention* (the rule has no opinion), not # a contradiction. Counting it as disagreement makes rules that # return 0.0 for "not applicable" look broken. if sa == 0 or sb == 0: stats["abstain"] += 1 continue if sa == sb: stats["agree"] += 1 continue stats["disagree"] += 1 # a positive while b negative: `a` credited code `b` calls a violation. if va > 0 and vb < 0: stats["a_positive_b_negative"] += 1 elif va < 0 and vb > 0: stats["a_negative_b_positive"] += 1 gap = abs(va - vb) stats["gap_sum"] += gap if stats["worst"] is None or gap > stats["worst"]["gap"]: stats["worst"] = { "case": row_a["name"], f"{name_a}": va, f"{name_b}": vb, "gap": gap, } disagreements.append( { "case": row_a["name"], "rule": rule, name_a: va, name_b: vb, "gap": gap, } ) rules_out = {} for rule, stats in rule_stats.items(): n = stats["n"] decided = stats["agree"] + stats["disagree"] rules_out[rule] = { "n": n, "decided": decided, "abstentions": stats["abstain"], # Agreement over cases where both raters took a position. "agreement": round(stats["agree"] / decided, 3) if decided else None, # The dangerous direction: rater A rewarded code rater B calls a violation. "a_credited_violations": stats["a_positive_b_negative"], "a_penalized_clean": stats["a_negative_b_positive"], "mean_gap_on_disagreement": ( round(stats["gap_sum"] / stats["disagree"], 3) if stats["disagree"] else 0.0 ), "worst_disagreement": stats["worst"], } totals_a = [r["total"] for r in a if r["total"] is not None] totals_b = [r["total"] for r in b if r["total"] is not None] return { "rater_a": name_a, "rater_b": name_b, "n_cases": len(a), "n_compared": compared, "failed": {"a": failed_a, "b": failed_b}, "failure_reason": {name_a: reason_a, name_b: reason_b}, "mean_total": { name_a: round(sum(totals_a) / len(totals_a), 4) if totals_a else None, name_b: round(sum(totals_b) / len(totals_b), 4) if totals_b else None, }, "rules": rules_out, "disagreements": disagreements, # Ground truth, when the corpus carries labels. "accuracy": {name_a: label_accuracy(a), name_b: label_accuracy(b)}, "verdict": _verdict( rules_out, name_a, name_b, failed={"a": failed_a, "b": failed_b}, n_compared=compared, ), } def _verdict( rules_out: Dict[str, Dict[str, Any]], name_a: str, name_b: str, failed: Optional[Dict[str, List[str]]] = None, n_compared: Optional[int] = None, ) -> str: """One-line summary naming rules that need attention.""" failed = failed or {} if n_compared == 0: detail = "; ".join( "%s: %d case(s) failed" % (name_a if k == "a" else name_b, len(v)) for k, v in failed.items() if v ) return ( f"INCONCLUSIVE -- no case was scored by both raters ({detail}). " "The audit says nothing about agreement." ) suspects = [ rule for rule, stats in rules_out.items() if stats["agreement"] is not None and stats["agreement"] < 0.8 and stats["decided"] >= 1 ] msg = "" if not suspects: msg = f"{name_a} and {name_b} agree on every rule (>=0.8 agreement)." else: credited = [r for r in suspects if rules_out[r]["a_credited_violations"] > 0] msg = f"{len(suspects)} rule(s) below 0.8 agreement: {', '.join(sorted(suspects))}." if credited: msg += ( f" {name_a} rewarded violating code on: " f"{', '.join(sorted(credited))} -- fix these first." ) bad = [f"{k}: {len(v)}" for k, v in failed.items() if v] if bad: msg += f" WARNING: failed cases ({'; '.join(bad)}) were excluded." return msg def format_report(report: Dict[str, Any]) -> str: """Render a comparison report as text.""" lines = [] a, b = report["rater_a"], report["rater_b"] lines.append(f"Rater audit: {a} vs {b} over {report['n_cases']} cases") lines.append( " compared: %d mean total: %s=%s %s=%s" % ( report.get("n_compared", report["n_cases"]), a, report["mean_total"][a], b, report["mean_total"][b], ) ) for key, failed_names in (report.get("failed") or {}).items(): if failed_names: name = a if key == "a" else b lines.append( " FAILED (%s): %d case(s): %s" % (name, len(failed_names), ", ".join(failed_names)) ) reason = (report.get("failure_reason") or {}).get(name) if reason: lines.append(" reason: %s" % str(reason)[:200]) lines.append("") lines.append( " %-34s %5s %7s %8s %9s %9s" % ("rule", "n", "agree", "abstain", f"{a}>0,{b}<0", "mean gap") ) for rule, stats in sorted( report["rules"].items(), key=lambda kv: (kv[1]["agreement"] if kv[1]["agreement"] is not None else 9), ): lines.append( " %-34s %5d %7s %8d %9d %9.2f" % ( rule, stats["n"], "n/a" if stats["agreement"] is None else "%.2f" % stats["agreement"], stats["abstentions"], stats["a_credited_violations"], stats["mean_gap_on_disagreement"], ) ) acc = report.get("accuracy") or {} if any(v.get("n_labeled") for v in acc.values()): lines.append("") lines.append("Labeled accuracy (rater vs corpus labels):") for key, val in acc.items(): lines.append( " %-10s %s (%d/%d checked)" % ( key, "n/a" if val["accuracy"] is None else "%.2f" % val["accuracy"], val["n_correct"], val["n_labeled"], ) ) for miss in val["misses"][:5]: lines.append( " miss: %-28s %-30s got=%+.2f expected=%+.2f" % (miss["case"], miss["rule"], miss["got"], miss["expected"]) ) lines.append("") lines.append(f"Verdict: {report['verdict']}") if report["disagreements"]: lines.append("") lines.append("Worst disagreements:") worst = sorted(report["disagreements"], key=lambda d: -d["gap"])[:5] for d in worst: lines.append( " %-24s %-34s %s=%+.2f %s=%+.2f" % (d["case"], d["rule"], a, d[a], b, d[b]) ) return "\n".join(lines) def run_audit( corpus_dir: str, rater_a: str = "static", rater_b: str = "decision", rater_model: Optional[str] = None, ) -> Dict[str, Any]: """Score a corpus with two raters and return the comparison report.""" cases = load_corpus(corpus_dir) logger.info("Loaded %d cases from %s", len(cases), corpus_dir) scored_a = score_corpus(cases, rater_a) scored_b = score_corpus(cases, rater_b, rater_model=rater_model) return compare_raters(scored_a, scored_b, rater_a, rater_b)