File size: 6,652 Bytes
7c188b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""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": "<one line citing the
decisive trace content, or why none exists>"}}"""


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()