"""Automated verification of open-vocabulary failure descriptions. A third instrument, independent of both the open coder and the mapper, re-reads each trace and judges whether a given failure description is supported by evidence in that trace. Combined with the programmatic checks in report_verified, this bounds the precision of the automated audit without any instrument seeing taxonomy labels. python3 src/analysis/verify_open.py run --run-id main python3 src/analysis/verify_open.py report --run-id main """ from __future__ import annotations import argparse import json import os import re import sys import yaml sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) from client import LLMClient # noqa: E402 from annotate_open import compact_trace # noqa: E402 VERIFIER = "gemma-4-31b" VERIFY_PROMPT = """You are verifying an audit claim about the execution trace below. Another auditor asserted the following failure description: CLAIM: {desc} Judge strictly whether the trace contains concrete evidence for this claim. Respond with ONLY JSON: {{"verdict": "SUPPORTED" or "UNSUPPORTED", "evidence": ""}}""" def load_descs(adir): descs = [] for l in open(os.path.join(adir, "open_coding.jsonl")): r = json.loads(l) m = re.search(r"\{.*\}", r.get("raw", ""), re.DOTALL) if not m: continue try: obj = json.loads(m.group(0)) except Exception: continue for d in obj.get("failures", []): if isinstance(d, str) and d.strip(): descs.append({"key": r["key"], "desc": d.strip()}) return descs def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("cmd", choices=["run", "report"]) ap.add_argument("--run-id", default="main") ap.add_argument("--results-dir", default="results") ap.add_argument("--config", default="config/experiment.yaml") args = ap.parse_args() run_dir = os.path.join(args.results_dir, args.run_id) adir = os.path.join(run_dir, "annotation") out_path = os.path.join(adir, "open_verify.jsonl") descs = load_descs(adir) if args.cmd == "run": cfg = yaml.safe_load(open(args.config)) client = LLMClient(base_url=cfg["server"]["base_url"], api_key=cfg["server"]["api_key"], timeout_s=cfg["server"]["timeout_s"], max_concurrency=8) done = set() if os.path.exists(out_path): done = {(json.loads(l)["key"], json.loads(l)["desc"]) for l in open(out_path)} import threading from concurrent.futures import ThreadPoolExecutor, as_completed lock = threading.Lock() todo = [d for d in descs if (d["key"], d["desc"]) not in done] print(f"[info] verifying {len(todo)} descriptions") def work(d): tpath = os.path.join(run_dir, "traces", f"{d['key']}.json") if not os.path.exists(tpath): return None trace = json.load(open(tpath)) res = client.chat(VERIFIER, [ {"role": "system", "content": VERIFY_PROMPT.format(desc=d["desc"])}, {"role": "user", "content": compact_trace(trace)}], temperature=0.0, max_tokens=512) return {**d, "ok": res.ok, "raw": res.text} n = 0 with ThreadPoolExecutor(max_workers=8) as ex: futs = {ex.submit(work, d): d for d in todo} for fut in as_completed(futs): r = fut.result() if r is None: continue with lock: with open(out_path, "a") as f: f.write(json.dumps(r) + "\n") n += 1 if n % 100 == 0: print(f"[verify {n}/{len(todo)}]", flush=True) print("[info] verification complete") return # ---------------- report: verifier verdicts + programmatic checks verd = {} for l in open(out_path): r = json.loads(l) m = re.search(r"SUPPORTED|UNSUPPORTED", (r.get("raw") or "").upper()) v = None mm = re.search(r"\{.*\}", r.get("raw", ""), re.DOTALL) if mm: try: v = json.loads(mm.group(0)).get("verdict", "").upper() except Exception: pass if not v and m: v = m.group(0) verd[(r["key"], r["desc"])] = v sup = sum(1 for v in verd.values() if v == "SUPPORTED") print(f"verifier: {sup}/{len(verd)} descriptions SUPPORTED " f"({100*sup/len(verd):.1f}%)") # programmatic checks on mechanically checkable claims recs = {} seen = set() for l in open(os.path.join(run_dir, "records.jsonl")): try: r = json.loads(l) except Exception: continue if r.get("key") != "ERR" and r["key"] not in seen: seen.add(r["key"]) recs[r["key"]] = r checked, correct = 0, 0 for d in descs: r = recs.get(d["key"]) if r is None: continue t = d["desc"].lower() claims = [] if any(w in t for w in ["budget", "token limit", "exhaust", "truncat", "cut off", "ran out"]): claims.append(r.get("completion_tokens", 0) >= 9000 or not r.get("parsed_ok", True)) if any(w in t for w in ["slow", "latency", "seconds", " long time", "response time"]): claims.append(r.get("wall_latency_s", 0) > 60) if any(w in t for w in ["far from optim", "suboptimal", "poor", "worse than random", "high regret", "low quality"]): claims.append(r.get("normalized_regret", 0) > 0.2) if any(w in t for w in ["no final answer", "empty", "failed to", "did not produce", "missing answer", "unparseable", "invalid json"]): claims.append(not r.get("parsed_ok", True) or r.get("penalty", 0) > 0) if claims: checked += 1 if any(claims): correct += 1 print(f"programmatic: {correct}/{checked} mechanically checkable " f"descriptions consistent with logged fields " f"({100*correct/max(checked,1):.1f}%)") if __name__ == "__main__": main()