"""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": [""]} 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": ""}}""" 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()