Spaces:
Running

File size: 4,815 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Error-analysis loop (Phase 14; process in ``evals/error_analysis.md``).



    python -m evals.harness.runner --suite evals/suites/full.yaml --k 4 --by-language \\

        --results-jsonl evals/out/full.jsonl

    python -m evals.harness.errors evals/out/full.jsonl --out evals/out/failures.jsonl

    # annotate failures.jsonl (fill "annotation"), then group by your categories:

    python -m evals.harness.errors evals/out/failures.jsonl --annotated



Every failing trial becomes one JSONL row with its transcript (inbound event, agent replies),

tool calls (from the audit log), the database diff, the grader's problems, and automatic

failure-category tags. The ``annotation`` object is for the human pass (open coding: a

free-text note; axial coding: a ``category``; and the ``new_scenario`` added for it).

"""

from __future__ import annotations

import argparse
import json
import sys
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any

# (substring of a grader problem, category tag), first match per problem wins.
RULES: list[tuple[str, str]] = [
    ("harness error", "harness_or_runtime_error"),
    ("executed without an approval", "approval_violation"),
    ("executed with approval", "approval_violation"),
    ("used for", "approval_violation"),
    ("forbidden call", "forbidden_call"),
    ("unexpected change", "unexpected_side_effect"),
    ("missing change", "missing_effect"),
    ("approvals requested", "approval_count"),
    ("status ", "wrong_status"),
    ("not made", "wrong_tool"),
    ("made with other arguments", "wrong_arguments"),
    ("containing", "reply_language_or_content"),
    ("compile errors", "workflow_check"),
    ("dry run", "workflow_check"),
]


def categorize(problems: list[str]) -> list[str]:
    tags: list[str] = []
    for p in problems:
        tag = next((t for s, t in RULES if s in p), "other")
        if tag not in tags:
            tags.append(tag)
    return tags


def export(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    out = []
    for r in rows:
        if r.get("ok"):
            continue
        out.append(
            {
                "scenario": r["scenario"],
                "slice": r.get("slice"),
                "language": r.get("language"),
                "trial": r.get("trial"),
                "path": r.get("path"),
                "description": r.get("description"),
                "categories": categorize(r.get("problems") or []),
                "problems": r.get("problems") or [],
                "status": r.get("status"),
                "event": r.get("event"),
                "transcript": r.get("transcript") or [],
                "calls": r.get("calls") or [],
                "diff": r.get("changes") or [],
                "annotation": {"category": "", "note": "", "new_scenario": ""},
            }
        )
    return out


def summary(failures: list[dict[str, Any]], annotated: bool = False) -> str:
    counts: Counter[str] = Counter()
    where: dict[str, set[str]] = defaultdict(set)
    for f in failures:
        cats = [f["annotation"]["category"]] if annotated else f["categories"]
        for c in [c for c in cats if c] or ["unannotated"]:
            counts[c] += 1
            where[c].add(f"{f['scenario']}[{f.get('language')}]")
    if not counts:
        return "No failing trials."
    lines = ["| category | failing trials | scenario runs |", "|---|---|---|"]
    for c, n in counts.most_common():
        runs = sorted(where[c])
        lines.append(f"| {c} | {n} | {', '.join(runs[:8])}{' ...' if len(runs) > 8 else ''} |")
    return "\n".join(lines)


def _read(path: Path) -> list[dict[str, Any]]:
    return [json.loads(x) for x in path.read_text(encoding="utf-8").splitlines() if x.strip()]


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("results", type=Path, help="--results-jsonl output (or an annotated export)")
    p.add_argument("--out", type=Path, help="write failing trials here for annotation")
    p.add_argument(
        "--annotated", action="store_true", help="input is an annotated export: group by it"
    )
    a = p.parse_args()
    rows = _read(a.results)
    failures = rows if a.annotated else export(rows)
    if a.out:
        a.out.parent.mkdir(parents=True, exist_ok=True)
        a.out.write_text(
            "".join(json.dumps(f, ensure_ascii=False, default=str) + "\n" for f in failures),
            encoding="utf-8",
        )
    sys.stdout.reconfigure(encoding="utf-8")  # type: ignore[union-attr]
    print(f"{len(failures)} failing trial(s) of {len(rows)}")
    print(summary(failures, annotated=a.annotated))


if __name__ == "__main__":
    main()