diag: add stable source reasons and diagnostic incidence reporting

This commit is contained in:
dev committed 2026-10-07 18:52:36 +03:00
1 parent 911982dd1c
commit dbd9763713
21 files changed
+571 -156

No files matched your search

+101 -15
View File
@@ -10,14 +10,16 @@ import statistics
from . import util
def load(paths):
runs = []
def _run_files(paths):
for p in paths:
for f in [p] if p.endswith("run.json") else glob.glob(os.path.join(p, "**", "run.json"), recursive=True):
if "/superseded/" in f:
continue
runs.append(util.read_json(f))
return runs
yield f
def load(paths):
return [util.read_json(f) for f in _run_files(paths)]
def mean(xs):
@@ -134,6 +136,7 @@ def summary(paths):
unc = [((r["metrics"].get("context") or {}).get("provider_input_tokens") or {}).get("uncached") for r in rs]
out.append(f"| {k} | {len(rs)} | {acc} | {round(acc / len(rs), 3)} | {mean(cyc)} | {mean([r['metrics'].get('tool_calls') for r in rs])} | {mean([r['metrics'].get('elapsed_seconds') for r in rs])} | {mean(unc)} |")
out.append("")
out.append(_diagnostic_reason_summary(paths))
return "\n".join(out)
@@ -151,20 +154,24 @@ def _source_size(run_dir, exts):
return files, lines, nbytes
def _diagnostic_codes(r, run_dir):
def _command_outputs(r, run_dir):
from . import native
if r.get("track") == "B":
return [o for _, _, o in native.command_events(r["agent"]["name"], os.path.join(run_dir, "transcript.jsonl"))]
with open(os.path.join(run_dir, "events.jsonl")) as f:
return [json.loads(l).get("output") or "" for l in f if '"event": "command"' in l]
def _diagnostic_codes(r, run_dir, outputs=None):
"""Counts of verifier/compiler diagnostic codes seen in the run's command
outputs (codes only: no message text, no task content)."""
import collections
import re
from . import native
counts = collections.Counter()
if r.get("track") == "B":
cmds = native.command_events(r["agent"]["name"], os.path.join(run_dir, "transcript.jsonl"))
outputs = [o for _, _, o in cmds]
else:
outputs = [json.loads(l).get("output") or "" for l in open(os.path.join(run_dir, "events.jsonl")) if '"event": "command"' in l]
if outputs is None:
outputs = _command_outputs(r, run_dir)
lang = r["language"]["name"]
for o in outputs:
if lang in ("aji_air", "aji_source"):
@@ -177,6 +184,80 @@ def _diagnostic_codes(r, run_dir):
return dict(counts.most_common())
def _diagnostic_reasons(r, run_dir):
"""Split the existing Aji code counts using whole JSON diagnostic records.
Unparsed/historical records retain reason=None. Code totals and their
historical extraction are unchanged; no message text supplies a reason.
None means unavailable logs or a non-Aji language, not zero observations.
"""
import collections
if r["language"]["name"] not in ("aji_air", "aji_source"):
return None
logfile = "transcript.jsonl" if r.get("track") == "B" else "events.jsonl"
if not os.path.isfile(os.path.join(run_dir, logfile)):
return None
outputs = _command_outputs(r, run_dir)
counts = collections.Counter({(c, None): n for c, n in _diagnostic_codes(r, run_dir, outputs).items()})
for output in outputs:
for line in output.splitlines():
try:
record = json.loads(line)
except (ValueError, TypeError):
continue
if not isinstance(record, dict):
continue
code, reason = record.get("code"), record.get("reason")
if not isinstance(code, str) or not isinstance(reason, str) or not reason:
continue
# Only split a record the existing compact-code extractor counted.
# A spaced/unrelated record cannot consume another unknown record.
if f'"code":"{code}"' not in line or counts[(code, None)] <= 0:
continue
counts[(code, None)] -= 1
counts[(code, reason)] += 1
return [{"code": c, "reason": reason, "count": n}
for (c, reason), n in sorted(counts.items(), key=lambda x: (x[0][0], x[0][1] or "")) if n]
def _reason_label(reason):
return "unknown" if reason is None else reason.replace("|", "\\|").replace("\n", " ")
def _diagnostic_reason_summary(paths):
import collections
totals, available, occurrences, incidence = (collections.Counter() for _ in range(4))
for f in _run_files(paths):
r = util.read_json(f)
lang = r["language"]["name"]
if lang not in ("aji_air", "aji_source"):
continue
totals[lang] += 1
pairs = _diagnostic_reasons(r, os.path.dirname(f))
if pairs is None:
continue
available[lang] += 1
for pair in pairs:
key = lang, pair["code"], pair["reason"]
occurrences[key] += pair["count"]
incidence[key] += 1
if not totals:
return ""
out = ["### Observed diagnostic reasons\n",
"Counts describe observed command outputs. Historical or unparsed reasons are unknown; unavailable logs are excluded from observations.\n",
"| language | code | reason | occurrences | runs observed | logs available / runs |",
"|---|---|---|---|---|---|"]
for lang in sorted(totals):
keys = sorted((k for k in occurrences if k[0] == lang), key=lambda k: (k[1], k[2] or ""))
for key in keys:
out.append(f"| {lang} | {key[1]} | {_reason_label(key[2])} | {occurrences[key]} | {incidence[key]} | {available[lang]}/{totals[lang]} |")
if not keys:
out.append(f"| {lang} | - | - | - | - | {available[lang]}/{totals[lang]} |")
return "\n".join(out)
# Diagnostics about the textual form of AIR (syntax, names, module header,
# SSA, CFG): the classes the source frontend is meant to remove. Type
# mismatches (E1001 from AIR, E7005 from source) are semantic and counted
@@ -212,8 +293,8 @@ def profile(paths):
Shareable: numbers and diagnostic codes only."""
from . import languages
out = ["| task | language | agent | termination | output tokens | tool calls | source files / lines / bytes | lowered AIR bytes raw / normalized | docs files read | IR-form diagnostics | type mismatches | diagnostic codes (count) |",
"|---|---|---|---|---|---|---|---|---|---|---|---|"]
out = ["| task | language | agent | termination | output tokens | tool calls | source files / lines / bytes | lowered AIR bytes raw / normalized | docs files read | IR-form diagnostics | type mismatches | diagnostic codes (count) | code / reason (count) |",
"|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
for p in paths:
for f in sorted(glob.glob(os.path.join(p, "**", "run.json"), recursive=True)):
if "/superseded/" in f:
@@ -223,6 +304,9 @@ def profile(paths):
exts = set(languages.load(r["language"]["name"]).get("source_extensions", []))
files, lines, nbytes = _source_size(d, exts)
codes = _diagnostic_codes(r, d)
pairs = _diagnostic_reasons(r, d)
reasons = "n/a" if pairs is None else ", ".join(
f"{p['code']} / {_reason_label(p['reason'])} {p['count']}" for p in pairs) or "-"
m = r["metrics"]
lowered = _lowered_size(d) if r["language"]["name"] == "aji_source" else None
docs = (m.get("context") or {}).get("docs") or {}
@@ -230,7 +314,7 @@ def profile(paths):
ty = sum(v for k, v in codes.items() if k in TYPE_MISMATCH)
out.append(f"| {r['task']['id']} | {r['language']['name']} | {_agent_key(r)} | {m.get('termination')} | {m.get('output_tokens')} | {m.get('tool_calls')} | "
f"{files} / {lines} / {nbytes} | {f'{lowered[0]} / {lowered[1]}' if lowered else '-'} | "
f"{docs.get('unique_docs_read', '-')} | {ir} | {ty} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} |")
f"{docs.get('unique_docs_read', '-')} | {ir} | {ty} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} | {reasons} |")
return "\n".join(out)
@@ -489,6 +573,7 @@ def checkpoint_rows(paths):
"output_tokens": v(m.get("output_tokens")),
"docs": doc_fields,
"diagnostics": _diagnostic_buckets(codes),
"diagnostic_reasons": _diagnostic_reasons(r, d),
"program": program,
# B1 §5 (n/a in records without the data).
"pretest_static_safety_caught": statically_prevented(r, d, codes),
@@ -514,5 +599,6 @@ def checkpoint(paths, as_json=False):
out.append(f"- {group}:")
for k, x in r[group].items():
out.append(f" - {k}: {json.dumps(x) if isinstance(x, (dict, list)) else x}")
out.append(f"- diagnostic_reasons: {json.dumps(r['diagnostic_reasons'])}")
out.append("")
return "\n".join(out)
@@ -0,0 +1,87 @@
"""Structured reason counts: historical uncertainty and per-run incidence."""
import json
import os
import tempfile
import unittest
from unittest.mock import patch
from ajieval import report
class DiagnosticReasons(unittest.TestCase):
def events(self, directory, outputs):
with open(os.path.join(directory, 'events.jsonl'), 'w') as f:
for output in outputs:
f.write(json.dumps({'event': 'command', 'output': output}) + '\n')
def test_unknown_historical_records_and_code_totals(self):
r = {'language': {'name': 'aji_source'}}
with tempfile.TemporaryDirectory() as d:
self.events(d, [
'{"code":"E7006","reason":"move_copy","message":"any prose"}\n'
'{"reason":"zero_not_zeroable","code":"E7006"}\n'
'{"code":"E7006","message":"move applies to Copy"}\n'
'prefix {"code":"E7006","reason":"move_copy"} truncated\n'
'{"code":"E7006","reason":12}\n'
'{"code":"E0006","reason":"future_reason"}\n'
'{"code":"E3101"}\n'])
pairs = report._diagnostic_reasons(r, d)
self.assertEqual(pairs, [
{'code': 'E0006', 'reason': 'future_reason', 'count': 1},
{'code': 'E3101', 'reason': None, 'count': 1},
{'code': 'E7006', 'reason': None, 'count': 3},
{'code': 'E7006', 'reason': 'move_copy', 'count': 1},
{'code': 'E7006', 'reason': 'zero_not_zeroable', 'count': 1}])
totals = {}
for row in pairs:
totals[row['code']] = totals.get(row['code'], 0) + row['count']
self.assertEqual(totals, report._diagnostic_codes(r, d))
def test_native_outputs_and_unavailable_logs(self):
r = {'track': 'B', 'agent': {'name': 'claude'}, 'language': {'name': 'aji_source'}}
with tempfile.TemporaryDirectory() as d:
self.assertIsNone(report._diagnostic_reasons(r, d))
open(os.path.join(d, 'transcript.jsonl'), 'w').close()
outputs = [(None, None, '{"code":"E7006","reason":"move_borrow"}\n')]
with patch('ajieval.native.command_events', return_value=outputs):
self.assertEqual(report._diagnostic_reasons(r, d), [
{'code': 'E7006', 'reason': 'move_borrow', 'count': 1}])
self.assertIsNone(report._diagnostic_reasons({'language': {'name': 'rust'}}, d))
def test_spaced_records_do_not_change_legacy_code_counts(self):
r = {'language': {'name': 'aji_source'}}
with tempfile.TemporaryDirectory() as d:
self.events(d, ['{"code": "E7006", "reason": "move_copy"}\n'
'{"code":"E7006"}\n'])
# The historical code-count extractor deliberately remains intact.
# A spaced record it did not count cannot consume another record's
# unknown bucket and manufacture known Copy evidence.
self.assertEqual(report._diagnostic_reasons(r, d), [
{'code': 'E7006', 'reason': None, 'count': 1}])
def test_summary_counts_runs_once_and_reports_log_coverage(self):
with tempfile.TemporaryDirectory() as root:
runs = []
for i in range(3):
d = os.path.join(root, str(i)); os.makedirs(d)
r = {'task': {'id': 'synthetic'}, 'language': {'name': 'aji_source'},
'model': {'id': 'test', 'class': 'test'}, 'accepted': False,
'metrics': {'context': {}}, '_dir': d}
runs.append(r)
with open(os.path.join(d, 'run.json'), 'w') as f:
json.dump(r, f)
if i != 2:
output = ('{"code":"E7006","reason":"move_copy"}\n' * 2
if i == 0 else '{"code":"E7006"}\n')
self.events(d, [output])
text = report.summary([root])
self.assertIn('| aji_source | E7006 | move_copy | 2 | 1 | 2/3 |', text)
self.assertIn('| aji_source | E7006 | unknown | 1 | 1 | 2/3 |', text)
self.assertIn('observed command outputs', text)
rows = report.checkpoint_rows([os.path.join(root, '0'), os.path.join(root, '1')])
pairs = [p for row in rows for p in (row['diagnostic_reasons'] or [])]
self.assertIn({'code': 'E7006', 'reason': 'move_copy', 'count': 2}, pairs)
if __name__ == '__main__':
unittest.main()