#!/usr/bin/env python3 """Analyze benchmark ground truth for hard-rule deviations. For each benchmark case with a reference case.yaml, checks whether the expected product codes actually pass the pipeline's hard filtering rules (H1-H7). Records deviations into the benchmark_deviations DB table. Deviation types: - corpus_gap: Product exists but is missing a field hard rules need - corpus_missing: Product code not found in corpus at all - rule_conflict: Product field EXISTS but violates a hard rule vs schedule specs Usage: python scripts/analyze_deviations.py [--case-id example-3] [--dry-run] """ from __future__ import annotations import argparse import json import re import sqlite3 import sys from datetime import datetime, timezone from pathlib import Path import yaml REPO_ROOT = Path(__file__).resolve().parent.parent CORPUS_PATH = REPO_ROOT / "data" / "corpus_products.json" CASES_DIR = REPO_ROOT / "benchmark" / "cases" sys.path.insert(0, str(REPO_ROOT / "scripts")) from corpus_query import ( CCT_APPROVED_PAIRS, normalize_dimming, normalize_mounting, parse_ip_number, ) def load_corpus_map() -> dict[str, dict]: with open(CORPUS_PATH) as f: products = json.load(f) result = {} for p in products: code = p.get("product_code", "") result[code] = p norm = code.upper().replace("-", "").replace("_", "").replace(" ", "") result[norm] = p return result def find_product(corpus_map: dict, code: str) -> dict | None: if not code: return None if code in corpus_map: return corpus_map[code] norm = code.upper().replace("-", "").replace("_", "").replace(" ", "") return corpus_map.get(norm) def check_product(item: dict, product: dict, case_id: str, source_file: str) -> list[dict]: """Check a ground truth product against hard rules. Returns deviations.""" deviations = [] code = item["corpus_link"].get("expected_product_code") or "" item_id = item["benchmark_item_id"] def add(rule: str, detail: str, direction: str, expected: str, actual: str): deviations.append({ "case_id": case_id, "item_id": item_id, "source_file": source_file, "expected_product_code": code, "rule_violated": rule, "rule_detail": detail, "direction": direction, "expected_value": expected, "actual_value": actual, }) # --- Corpus gaps: fields the hard rules need but the product doesn't have --- p_cct = product.get("cct") if p_cct is None: add("H2", "Corpus gap: product missing CCT", "corpus_gap", "CCT present", "null") p_cri = product.get("cri") if p_cri is None: add("H3", "Corpus gap: product missing CRI", "corpus_gap", "CRI present", "null") p_lumens = product.get("lumens") if p_lumens is None: add("H4", "Corpus gap: product missing lumens", "corpus_gap", "lumens present", "null") p_dim = normalize_dimming(product.get("dimming_method")) if p_dim is None or p_dim == "unknown": add("H5", "Corpus gap: product missing dimming method", "corpus_gap", "dimming present", str(product.get("dimming_method"))) p_ip = parse_ip_number(product.get("ip_rating")) if p_ip is None: add("H6", "Corpus gap: product missing IP rating", "corpus_gap", "IP present", "null") p_mount = normalize_mounting(product.get("mounting_method")) if p_mount is None or p_mount == "unknown": add("H7", "Corpus gap: product missing mounting method", "corpus_gap", "mounting present", str(product.get("mounting_method"))) # --- Rule conflicts: product field EXISTS but may violate schedule specs --- # We infer schedule specs from the item description and rationale where possible. rationale = (item.get("corpus_link", {}).get("match_rationale") or "").lower() desc = (item.get("expected_normalized_description") or "").lower() evidence_notes = " ".join( (ref.get("note") or "") for ref in item.get("source_evidence_refs", []) ).lower() combined = f"{desc} {rationale} {evidence_notes}" # Try to infer schedule CCT from evidence/description cct_match = re.search(r'(\d{4})\s*k\b', combined) or re.search(r'\b(2700|3000|3500|4000|5000|5700|6500)\b', combined) if cct_match and p_cct is not None: sched_cct = int(cct_match.group(1)) if p_cct != sched_cct and (sched_cct, p_cct) not in CCT_APPROVED_PAIRS: add("H2", f"Rule conflict: schedule wants {sched_cct}K, product has {p_cct}K", "more_relaxed", str(sched_cct), str(p_cct)) # Try to infer schedule IP from evidence ip_match = re.search(r'ip\s*(\d{2,})', combined) if ip_match and p_ip is not None: sched_ip = int(ip_match.group(1)) if p_ip < sched_ip: add("H6", f"Rule conflict: schedule wants IP{sched_ip}, product has IP{p_ip}", "more_relaxed", f"IP{sched_ip}", f"IP{p_ip}") # Try to infer schedule mounting for mount_word, mount_val in [("recessed", "recessed"), ("surface", "surface"), ("suspended", "suspended"), ("pendant", "suspended"), ("wall mount", "wall"), ("wall-mount", "wall")]: if mount_word in combined and p_mount is not None and p_mount != "unknown": sched_mount = mount_val if p_mount != sched_mount: add("H7", f"Rule conflict: schedule wants {sched_mount}, product has {p_mount}", "more_relaxed", sched_mount, p_mount) break # Try to infer schedule lumens lumen_match = re.search(r'(\d{3,5})\s*l[um]', combined) if lumen_match and p_lumens is not None: sched_lumens = int(lumen_match.group(1)) if p_lumens < sched_lumens * 0.9: shortfall = round((1 - p_lumens / sched_lumens) * 100, 1) add("H4", f"Rule conflict: schedule wants {sched_lumens}lm, product has {p_lumens}lm ({shortfall}% shortfall)", "more_relaxed", str(sched_lumens), str(p_lumens)) return deviations def analyze_case(case_dir: Path, corpus_map: dict) -> list[dict]: case_yaml = case_dir / "case.yaml" if not case_yaml.exists(): return [] with open(case_yaml) as f: case = yaml.safe_load(f) case_id = case["metadata"]["case_id"] source_file = case_yaml.name all_deviations = [] for item in case.get("items", []): outcome = item.get("expected_outcome", "") code = (item.get("corpus_link", {}).get("expected_product_code") or "").strip() if outcome != "matched_to_output" or not code: continue product = find_product(corpus_map, code) if product is None: all_deviations.append({ "case_id": case_id, "item_id": item["benchmark_item_id"], "source_file": source_file, "expected_product_code": code, "rule_violated": "CORPUS", "rule_detail": f"Product code '{code}' not found in corpus", "direction": "corpus_missing", "expected_value": "code exists", "actual_value": "not found", }) continue # Check alternative codes too alts = item.get("corpus_link", {}).get("acceptable_alternative_product_codes") or [] for alt in alts: if alt and not find_product(corpus_map, alt): all_deviations.append({ "case_id": case_id, "item_id": item["benchmark_item_id"], "source_file": source_file, "expected_product_code": alt, "rule_violated": "CORPUS", "rule_detail": f"Alternative code '{alt}' not found in corpus", "direction": "corpus_missing", "expected_value": "code exists", "actual_value": "not found", }) devs = check_product(item, product, case_id, source_file) all_deviations.extend(devs) return all_deviations def get_db_path() -> Path: for candidate in [ REPO_ROOT / "storage" / "lighting_mvp.db", REPO_ROOT / "lighting_mvp.db", ]: if candidate.exists(): return candidate return REPO_ROOT / "storage" / "lighting_mvp.db" def save_to_db(deviations: list[dict], db_path: Path) -> None: conn = sqlite3.connect(str(db_path)) cur = conn.cursor() cur.execute(""" CREATE TABLE IF NOT EXISTS benchmark_deviations ( id INTEGER PRIMARY KEY AUTOINCREMENT, case_id TEXT NOT NULL, item_id TEXT NOT NULL, source_file TEXT NOT NULL, expected_product_code TEXT, rule_violated TEXT NOT NULL, rule_detail TEXT NOT NULL, direction TEXT NOT NULL, expected_value TEXT, actual_value TEXT, created_at TEXT NOT NULL ) """) case_ids = set(d["case_id"] for d in deviations) for cid in case_ids: cur.execute("DELETE FROM benchmark_deviations WHERE case_id = ?", (cid,)) now = datetime.now(timezone.utc).isoformat() for d in deviations: cur.execute( """INSERT INTO benchmark_deviations (case_id, item_id, source_file, expected_product_code, rule_violated, rule_detail, direction, expected_value, actual_value, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (d["case_id"], d["item_id"], d["source_file"], d["expected_product_code"], d["rule_violated"], d["rule_detail"], d["direction"], d["expected_value"], d["actual_value"], now), ) conn.commit() conn.close() def main(): parser = argparse.ArgumentParser(description="Analyze benchmark ground truth for hard-rule deviations") parser.add_argument("--case-id", help="Analyze only this case (default: all)") parser.add_argument("--dry-run", action="store_true", help="Print deviations without writing to DB") args = parser.parse_args() corpus_map = load_corpus_map() all_deviations = [] if args.case_id: case_dir = CASES_DIR / args.case_id if not case_dir.exists(): print(f"Case directory not found: {case_dir}") sys.exit(1) all_deviations = analyze_case(case_dir, corpus_map) else: for case_dir in sorted(CASES_DIR.iterdir()): if case_dir.is_dir() and not case_dir.name.endswith("-agent-test"): devs = analyze_case(case_dir, corpus_map) all_deviations.extend(devs) # Group by direction (type) by_type = {} for d in all_deviations: by_type.setdefault(d["direction"], []).append(d) print(f"Total deviations: {len(all_deviations)}\n") for dtype in ["corpus_missing", "corpus_gap", "more_relaxed", "stricter"]: devs = by_type.get(dtype, []) if not devs: continue print(f" [{dtype}] — {len(devs)}") # Sub-group by rule by_rule = {} for d in devs: by_rule.setdefault(d["rule_violated"], []).append(d) for rule, rdevs in sorted(by_rule.items()): print(f" {rule}: {len(rdevs)}") for d in rdevs[:2]: print(f" {d['case_id']}/{d['item_id']}: {d['rule_detail']}") if len(rdevs) > 2: print(f" ... +{len(rdevs) - 2} more") print() if not args.dry_run and all_deviations: db_path = get_db_path() print(f"Writing to DB: {db_path}") save_to_db(all_deviations, db_path) print(f"Saved {len(all_deviations)} deviations.") elif args.dry_run: print("(dry run — nothing written)") if __name__ == "__main__": main()