File size: 9,646 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""Trace annotation for the MAUX coverage study (Section 6.5 of the paper).

Two stages:

1. Sample: stratified sample of traces (balanced over topology, family, and
   regret quartile), exported to results/<run_id>/annotation/sample.jsonl and
   an editable CSV for the two human author annotators.

     python src/analysis/annotate.py sample --run-id RUN --n 600

2. Judge: LLM-judge pass with a locked rubric prompt against the configured
   judge model (annotation.judge_model in config/experiment.yaml), writing one
   MAUX + MAST label set per trace. Agreement (Cohen's kappa) between judge
   and each human, and between humans on the dual-annotated subset, is
   computed by the report subcommand.

     python src/analysis/annotate.py judge  --run-id RUN
     python src/analysis/annotate.py report --run-id RUN
"""
from __future__ import annotations

import argparse
import csv
import json
import os
import sys

import numpy as np
import pandas as pd
import yaml

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from client import LLMClient  # noqa: E402

MAUX_CODES = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "NONE"]
MAST_CODES = ["SPEC", "MISALIGN", "VERIFY", "NONE"]

RUBRIC = """You are annotating an execution trace of a multi-agent LLM pipeline
serving as the intelligence layer of a user interface. Assign zero or more MAUX
failure codes and zero or more MAST categories.

MAUX codes:
F1 adaptation suboptimality: final answer is far from the declared optimum.
F2 referential inconsistency: output would differ under a paraphrase of the
   same request (evident from unstable reasoning tied to surface wording).
F3 temporal inconsistency: reasoning is seed-dependent or arbitrary between
   equally described options.
F4 deliberative opacity: committee members disagreed and the disagreement was
   dropped or silently averaged rather than resolved or surfaced.
F5 intervention miscalibration: policy over/under-intervenes relative to the
   declared cost matrix.
F6 latency unpredictability: a role produced extreme response time relative to
   the others (visible in per-call latency fields).
F7 non-graceful degradation: a role failure, empty message, corrupted handoff,
   or schema failure propagated into a worse final answer.
F8 resource inefficiency: many tokens spent without improving the answer over
   the first proposal.
NONE no MAUX failure.

MAST categories (task-completion failures):
SPEC specification or system design failure; MISALIGN inter-agent
misalignment; VERIFY task verification failure; NONE.

Respond with ONLY JSON: {"maux": [codes], "mast": [codes],
"witness": "one sentence citing the decisive evidence in the trace"}."""


def load_run(results_dir: str, run_id: str):
    run_dir = os.path.join(results_dir, run_id)
    recs = []
    seen = set()
    with open(os.path.join(run_dir, "records.jsonl")) as f:
        for line in f:
            try:
                r = json.loads(line)
                if r.get("key") != "ERR" and r["key"] not in seen:
                    seen.add(r["key"])
                    recs.append(r)
            except Exception:
                pass
    return run_dir, pd.DataFrame(recs)


def cmd_sample(args) -> None:
    run_dir, df = load_run(args.results_dir, args.run_id)
    adir = os.path.join(run_dir, "annotation")
    os.makedirs(adir, exist_ok=True)
    df["quartile"] = pd.qcut(df["normalized_regret"].rank(method="first"), 4,
                             labels=False)
    strata = df.groupby(["topology", "family", "quartile"])
    per = max(1, args.n // max(len(strata), 1))
    rng = np.random.default_rng(7)
    keys = []
    for _, g in strata:
        take = min(per, len(g))
        keys += list(g.sample(take, random_state=int(rng.integers(1e9)))["key"])
    keys = keys[: args.n]
    with open(os.path.join(adir, "sample.jsonl"), "w") as f:
        for k in keys:
            f.write(json.dumps({"key": k}) + "\n")
    # human annotation sheets (dual subset first)
    dual = keys[: args.dual]
    for annotator in ("A", "B"):
        with open(os.path.join(adir, f"human_{annotator}.csv"), "w",
                  newline="") as f:
            w = csv.writer(f)
            w.writerow(["key", "maux_codes", "mast_codes", "notes"])
            rows = dual if annotator == "B" else keys
            for k in rows:
                w.writerow([k, "", "", ""])
    print(f"[info] sampled {len(keys)} traces ({len(dual)} dual) into {adir}")


def cmd_judge(args) -> None:
    with open(args.config) as f:
        cfg = yaml.safe_load(f)
    judge_model = cfg["annotation"].get("judge_model")
    if not judge_model:
        print("[error] set annotation.judge_model in config/experiment.yaml")
        return
    client = LLMClient(base_url=cfg["server"]["base_url"],
                       api_key=cfg["server"]["api_key"],
                       timeout_s=cfg["server"]["timeout_s"])
    run_dir, _ = load_run(args.results_dir, args.run_id)
    adir = os.path.join(run_dir, "annotation")
    out_path = os.path.join(adir, "judge.jsonl")
    done = set()
    if os.path.exists(out_path):
        with open(out_path) as f:
            done = {json.loads(l)["key"] for l in f if l.strip()}
    with open(os.path.join(adir, "sample.jsonl")) as f:
        keys = [json.loads(l)["key"] for l in f]
    for i, k in enumerate(keys):
        if k in done:
            continue
        tpath = os.path.join(run_dir, "traces", f"{k}.json")
        if not os.path.exists(tpath):
            continue
        with open(tpath) as f:
            trace = json.load(f)
        # compact the trace for the judge context window
        lines = []
        for c in trace["calls"]:
            lines.append(f"[{c['role']} ok={c['ok']} lat={c['latency_s']:.1f}s "
                         f"tok={c['completion_tokens']}]\n"
                         f"{c['completion'][:1500]}")
        res = client.chat(judge_model,
                          [{"role": "system", "content": RUBRIC},
                           {"role": "user",
                            "content": "TRACE:\n" + "\n\n".join(lines)[:24000]}],
                          temperature=0.0, max_tokens=8192)
        rec = {"key": k, "ok": res.ok, "raw": res.text, "error": res.error}
        with open(out_path, "a") as f:
            f.write(json.dumps(rec) + "\n")
        if (i + 1) % 25 == 0:
            print(f"[judge] {i+1}/{len(keys)}")
    print(f"[info] judge annotations at {out_path}")


def _parse_codes(raw: str, valid: list[str], field: str) -> frozenset:
    try:
        start = raw.find("{")
        obj = json.loads(raw[start:raw.rfind("}") + 1])
        return frozenset(c for c in obj.get(field, []) if c in valid)
    except Exception:
        return frozenset()


def cohen_kappa(a: list[frozenset], b: list[frozenset], code: str) -> float:
    xa = np.array([code in s for s in a])
    xb = np.array([code in s for s in b])
    po = float((xa == xb).mean())
    pe = float(xa.mean() * xb.mean() + (1 - xa.mean()) * (1 - xb.mean()))
    if pe >= 1.0:
        return float("nan")
    return (po - pe) / (1 - pe)


def cmd_report(args) -> None:
    run_dir, _ = load_run(args.results_dir, args.run_id)
    adir = os.path.join(run_dir, "annotation")
    judge = {}
    with open(os.path.join(adir, "judge.jsonl")) as f:
        for l in f:
            r = json.loads(l)
            judge[r["key"]] = (_parse_codes(r.get("raw", ""), MAUX_CODES, "maux"),
                               _parse_codes(r.get("raw", ""), MAST_CODES, "mast"))
    print(f"[info] {len(judge)} judged traces")
    counts = {c: sum(1 for m, _ in judge.values() if c in m) for c in MAUX_CODES}
    print("MAUX prevalence:", counts)
    mast_counts = {c: sum(1 for _, m in judge.values() if c in m)
                   for c in MAST_CODES}
    print("MAST prevalence:", mast_counts)
    # disjointness witnesses: MAUX failure with MAST == NONE or empty
    witnesses = [k for k, (mx, ms) in judge.items()
                 if mx and mx != {"NONE"} and (not ms or ms == {"NONE"})]
    print(f"MAST-disjoint MAUX failures (witness candidates): {len(witnesses)}")
    with open(os.path.join(adir, "witnesses.json"), "w") as f:
        json.dump(witnesses, f, indent=2)
    # human agreement if sheets are filled
    for annotator in ("A", "B"):
        p = os.path.join(adir, f"human_{annotator}.csv")
        if os.path.exists(p):
            h = pd.read_csv(p).fillna("")
            filled = h[h["maux_codes"].astype(str).str.strip() != ""]
            if len(filled) > 10:
                keys = [k for k in filled["key"] if k in judge]
                hs = [frozenset(str(r).replace(";", ",").split(","))
                      for r in filled.set_index("key").loc[keys, "maux_codes"]]
                js = [judge[k][0] for k in keys]
                for code in ["F1", "F4", "F7"]:
                    print(f"kappa(judge, {annotator}) {code}: "
                          f"{cohen_kappa(js, hs, code):.2f}")


def main() -> None:
    ap = argparse.ArgumentParser()
    sub = ap.add_subparsers(dest="cmd", required=True)
    for name in ("sample", "judge", "report"):
        p = sub.add_parser(name)
        p.add_argument("--run-id", required=True)
        p.add_argument("--results-dir", default="results")
        p.add_argument("--config", default="config/experiment.yaml")
        if name == "sample":
            p.add_argument("--n", type=int, default=600)
            p.add_argument("--dual", type=int, default=150)
    args = ap.parse_args()
    {"sample": cmd_sample, "judge": cmd_judge, "report": cmd_report}[args.cmd](args)


if __name__ == "__main__":
    main()