File size: 8,928 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
"""Open-vocabulary coverage study: breaks the circularity of rubric-based
taxonomy validation by separating failure identification from taxonomy
mapping, with the identification instrument blind to MAUX.

Stage 1 (open): an out-of-pool model (qwen3.6-35b-a3b, not part of the
  evaluated seven-model pool) reads each sampled trace and describes any
  failure in free text, with no taxonomy in its prompt.
Stage 2 (map): a second model maps each free-text description (without the
  trace) onto MAUX codes or OTHER, given only the code definitions.
Report: fraction of open-coded failures mappable to MAUX; OTHER cases with
  their descriptions (candidate taxonomy gaps).

  python3 src/analysis/annotate_open.py open   --run-id main
  python3 src/analysis/annotate_open.py map    --run-id main
  python3 src/analysis/annotate_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

OPEN_CODER = "qwen3.6-35b-a3b-fp8"
MAPPER = "gptoss-120b"

OPEN_PROMPT = """You are auditing one execution trace of an automated pipeline
that serves as the intelligence layer of an interactive user interface: it
receives an interface adaptation task and must produce a decision. Read the
trace below. In your own words, describe every way this execution failed or
behaved undesirably from the perspective of an interactive system and its
user (consider the final decision's quality, the process, timing, resources,
and reliability). Be concrete and cite evidence from the trace. If the
execution was acceptable, respond with exactly: NO FAILURE.
Respond with ONLY JSON: {"failures": ["<one sentence per distinct failure>"]}
or {"failures": []} if none."""

MAP_PROMPT = """Below are definitions of failure dimensions for interface
intelligence pipelines, followed by one failure description written by an
independent auditor. Assign the description to every dimension that fits.
If no dimension fits, assign OTHER and explain the gap in one sentence.

F1 adaptation suboptimality: the final decision is measurably far from the
   declared optimum.
F2 referential inconsistency: output changes under rewording of the same
   request.
F3 temporal inconsistency: output is unstable across repeated identical
   invocations.
F4 aggregation failure: combining committee members' proposals produced a
   worse answer than the members' own proposals, or discarded their
   disagreement.
F5 intervention miscalibration: acting, asking, or waiting at odds with the
   declared cost structure.
F6 latency unpredictability: extreme or highly variable response time.
F7 non-graceful degradation: a component failure, empty or corrupted message,
   or format failure propagated into a worse or missing final answer.
F8 resource inefficiency: excessive computation or tokens without
   corresponding quality gain.
F9 actuation grounding failure: inability to locate or act on the intended
   interface element.

FAILURE DESCRIPTION: {desc}

Respond with ONLY JSON: {{"codes": ["F1"|...|"OTHER"], "gap": "<only if OTHER>"}}"""


def compact_trace(trace: dict) -> str:
    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{c['completion'][:1500]}")
    return "TRACE:\n" + "\n\n".join(lines)[:24000]


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["open", "map", "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()
    cfg = yaml.safe_load(open(args.config))
    run_dir = os.path.join(args.results_dir, args.run_id)
    adir = os.path.join(run_dir, "annotation")
    keys = [json.loads(l)["key"] for l in open(os.path.join(adir,
                                                           "sample.jsonl"))]
    client = LLMClient(base_url=cfg["server"]["base_url"],
                       api_key=cfg["server"]["api_key"],
                       timeout_s=cfg["server"]["timeout_s"],
                       max_concurrency=8)

    if args.cmd == "open":
        out_path = os.path.join(adir, "open_coding.jsonl")
        done = set()
        if os.path.exists(out_path):
            done = {json.loads(l)["key"] for l in open(out_path)}
        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
            trace = json.load(open(tpath))
            res = client.chat(OPEN_CODER,
                              [{"role": "system", "content": OPEN_PROMPT},
                               {"role": "user",
                                "content": compact_trace(trace)}],
                              temperature=0.0, max_tokens=8192)
            with open(out_path, "a") as f:
                f.write(json.dumps({"key": k, "ok": res.ok,
                                    "raw": res.text}) + "\n")
            if (i + 1) % 25 == 0:
                print(f"[open] {i+1}/{len(keys)}", flush=True)
        print("[info] open coding complete")

    elif args.cmd == "map":
        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()})
        out_path = os.path.join(adir, "open_mapping.jsonl")
        done = set()
        if os.path.exists(out_path):
            done = {(json.loads(l)["key"], json.loads(l)["desc"])
                    for l in open(out_path)}
        print(f"[info] {len(descs)} failure descriptions to map")
        for i, d in enumerate(descs):
            if (d["key"], d["desc"]) in done:
                continue
            res = client.chat(MAPPER,
                              [{"role": "user",
                                "content": MAP_PROMPT.format(desc=d["desc"])}],
                              temperature=0.0, max_tokens=4096)
            with open(out_path, "a") as f:
                f.write(json.dumps({**d, "ok": res.ok,
                                    "raw": res.text}) + "\n")
            if (i + 1) % 50 == 0:
                print(f"[map] {i+1}/{len(descs)}", flush=True)
        print("[info] mapping complete")

    else:
        n_traces, n_fail_traces, n_descs = 0, 0, 0
        per_trace = {}
        for l in open(os.path.join(adir, "open_coding.jsonl")):
            r = json.loads(l)
            n_traces += 1
            m = re.search(r"\{.*\}", r.get("raw", ""), re.DOTALL)
            fails = []
            if m:
                try:
                    fails = [d for d in json.loads(m.group(0)).get(
                        "failures", []) if isinstance(d, str) and d.strip()]
                except Exception:
                    pass
            per_trace[r["key"]] = fails
            if fails:
                n_fail_traces += 1
                n_descs += len(fails)
        mapped, other, code_counts = 0, [], {}
        for l in open(os.path.join(adir, "open_mapping.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
            codes = [c for c in obj.get("codes", []) if isinstance(c, str)]
            f_codes = [c for c in codes if c.startswith("F")]
            for c in f_codes:
                code_counts[c] = code_counts.get(c, 0) + 1
            if f_codes:
                mapped += 1
            if "OTHER" in codes and not f_codes:
                other.append({"key": r["key"], "desc": r["desc"],
                              "gap": obj.get("gap", "")})
        print(f"traces open-coded: {n_traces}; with failures: "
              f"{n_fail_traces}; failure descriptions: {n_descs}")
        print(f"descriptions mapped to at least one MAUX code: {mapped}")
        print(f"descriptions mapped ONLY to OTHER: {len(other)}")
        print("code frequency:", dict(sorted(code_counts.items())))
        with open(os.path.join(adir, "open_other.json"), "w") as f:
            json.dump(other, f, indent=2)
        print("[info] OTHER cases written to open_other.json")


if __name__ == "__main__":
    main()