Datasets:
File size: 5,999 Bytes
a785ccd | 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 | """Classify screen episodes into the pilot's failure categories.
Each failed episode gets one primary category, decided in this order:
invalid_action the reply was not one valid JSON action (malformed JSON, escaping, schema), or an
over-long reply was cut while budget remained
budget the completion/context budget or the call cap ended the episode
missing_output the episode ended normally but the output file did not exist
bad_structure the file exists but does not parse or has the wrong keys/header/types
wrong_code repair tasks: the file is structurally fine but the code fails the checks
wrong_answer other tasks: structurally fine, wrong values
grader_defect the saved files pass a local regrade although the episode scored 0
The output's state at the end is reported for every episode as well, whatever ended it.
Usage: PYTHONPATH=. .venv/bin/python tools/classify.py runs/pilot-4x/records.jsonl
"""
import ast
import collections
import csv
import io
import json
import os
import random
import sys
import tempfile
sys.path.insert(0, ".")
os.environ.setdefault("TERMINAL_DESK_APP", tempfile.mkdtemp(prefix="td-cls-"))
from terminal_desk.families import ALL_FAMILIES, FAMILIES, instance_seed, parse_task_id # noqa: E402
BUDGET = 4096
MISSING = "@@MISSING@@"
JSON_KEYS = {
"ev_backorder": {"backordered"},
"tx_events": {"counts", "errors", "skipped"},
"plan_load": {"items", "total_value", "total_weight_kg"},
}
CSV_HEADERS = {
"ev_calibration": ["sample_id", "instrument_id", "run_date"],
"cmp_channels": ["channel", "total_hours", "weighted_minutes"],
"cmp_rainfall": ["station", "total_mm", "wet_days", "mean_mm_per_wet_day"],
"plan_shifts": ["shift_id", "staff"],
}
def structure_ok(family: str, text: str, path: str = "") -> bool:
if family not in CSV_HEADERS and family not in JSON_KEYS and family not in ("fix_toolkit", "tx_contacts", "fix_report"):
# Reserved and newer tasks: structure by file type only (values are judged by the regrade).
try:
if path.endswith(".csv"):
from terminal_desk.families.util import parse_csv_strict
return parse_csv_strict(text) is not None
if path.endswith(".json"):
json.loads(text)
return True
if path.endswith(".py"):
ast.parse(text)
return True
except (ValueError, SyntaxError):
return False
return bool(text.strip())
try:
if family in CSV_HEADERS:
header = next(csv.reader(io.StringIO(text)))
return [h.strip() for h in header] == CSV_HEADERS[family]
if family == "fix_toolkit":
ast.parse(text)
return True
value = json.loads(text)
if family in JSON_KEYS:
return isinstance(value, dict) and set(value) == JSON_KEYS[family]
if family == "tx_contacts":
keys = {"id", "name", "email", "tags", "active"}
return isinstance(value, list) and all(isinstance(v, dict) and set(v) == keys for v in value)
if family == "fix_report":
return isinstance(value, dict) and all(isinstance(v, dict) for v in value.values())
except (ValueError, StopIteration, SyntaxError):
return False
return True
def regrade(task_id: str, snapshot: dict) -> bool:
fid, level, _ = parse_task_id(task_id)
built = ALL_FAMILIES[fid].build(level, random.Random(instance_seed(task_id)))
app = tempfile.mkdtemp(prefix="td-regrade-")
for path, text in snapshot.items():
full = os.path.join(app, path)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, "w") as fh:
fh.write(text + ("" if text.endswith("\n") else "\n"))
try:
return bool(built.artifact.verify(app))
except Exception:
return False
def output_state(rec: dict) -> str:
family = rec["task_id"].split("-L")[0]
snap = rec.get("snapshot") or {}
fid, level, _ = parse_task_id(rec["task_id"])
path = ALL_FAMILIES[fid].build(level, random.Random(instance_seed(rec["task_id"]))).artifact.path
text = snap.get(path)
if text is None:
return "unknown"
if text.strip() == MISSING:
return "missing"
if not structure_ok(family, text, path):
return "bad_structure"
if rec["reward"] == 1.0:
return "correct"
return "passes_regrade" if regrade(rec["task_id"], {p: t for p, t in snap.items() if t.strip() != MISSING}) else "wrong"
def classify(rec: dict) -> tuple[str, str]:
state = output_state(rec)
if rec["reward"] == 1.0:
return "solved", state
ended = rec["ended"]
if ended in ("invalid_reply", "invalid_action"):
return "invalid_action", state
if ended == "truncated":
return ("budget" if rec["completion_spent"] >= BUDGET - 16 else "invalid_action"), state
if ended in ("budget", "context", "cap"):
return "budget", state
if state == "passes_regrade":
return "grader_defect", state
if state == "missing":
return "missing_output", state
if state == "bad_structure":
return "bad_structure", state
family = rec["task_id"].split("-L")[0]
return ("wrong_code" if family.startswith("fix_") else "wrong_answer"), state
def main() -> None:
recs = [json.loads(line) for line in open(sys.argv[1])]
per_task = collections.defaultdict(list)
totals = collections.Counter()
for r in recs:
cat, state = classify(r)
per_task[r["task_id"]].append((cat, state, r["ended"], r["steps"], r["completion_spent"]))
totals[cat] += 1
for task, eps in per_task.items():
solved = sum(c == "solved" for c, *_ in eps)
print(f"{task:18} {solved}/{len(eps)} " + " ".join(f"{c}[{s},{e},{n}st,{sp}t]" for c, s, e, n, sp in eps))
print("\ntotals:", dict(totals))
if __name__ == "__main__":
main()
|