Files
seismo-relay/scratch/decode_check_report.py
T
serversdownandClaude Opus 5.5 c8fc649568 tooling(scratch): decode-check run-to-run changes and a one-event view
Each run is diffed against the previous one (--compare-to, or the newest
other run in ~/dl2-archive/checker-runs): changes.md lists every
(event, field) that matched before and no longer does, how many now
match, and how each field's counts moved; summary.md leads with the
regression count.  --file NAME checks one event and prints its table,
writing no run folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:30:53 -04:00

192 lines
8.9 KiB
Python

"""
Reports for the Series 3 decode checker (scratch/check_s3_decode.py).
From a run's results.jsonl.gz:
summary.md for Brian: per field, how many events got each verdict; how many
fields fully match; non-matches by event year; carve-out counts
details.json for Claude: each non-matching (field, verdict) with the event
attributes its failures concentrate in, and example events, each
with a command that re-runs just that event
Streams the results file and holds only counters and a capped example list.
"""
from __future__ import annotations
import gzip
import json
from collections import Counter, defaultdict
from pathlib import Path
from typing import Optional
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
_NOT_DONE = ("mismatch", "sfm_blank", "error")
_GROUP_SHARE = 0.10 # an attribute value is shown when it holds >= 10% of a failure
_CONCENTRATED = 0.95 # ... and flagged when nearly every compared event with it fails
_EXAMPLES = 8
_KEEP = 60 # candidate examples kept per failure while streaming
def _run_dirs(results_path: Path) -> tuple[str, str]:
run = results_path.parent / "run.json"
try:
args = json.loads(run.read_text())["args"]
return args["bin_dir"], args["xml_dir"]
except (OSError, KeyError, ValueError):
return "<bin_dir>", "<xml_dir>"
def aggregate(results_path: Path) -> dict:
fields: dict[str, Counter] = defaultdict(Counter)
by_year: dict[str, Counter] = defaultdict(Counter)
compared: dict[str, dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))
failing: dict[str, dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))
examples: dict[str, list] = defaultdict(list)
carveouts: Counter = Counter()
events = 0
with gzip.open(results_path, "rt", encoding="utf-8") as fh:
for line in fh:
ev = json.loads(line)
events += 1
attrs = ev.get("attrs") or {}
covered = set()
for field, verdict, bw, sfm, detail, carveout in ev["results"]:
fields[field][verdict] += 1
if carveout:
covered.add(carveout)
if verdict != "no_reference":
for a, v in attrs.items():
compared[field][a][str(v)] += 1
if verdict in ("match", "accepted", "no_reference"):
continue
key = f"{field}|{verdict}"
by_year[field][attrs.get("year", "?")] += 1
for a, v in attrs.items():
failing[key][a][str(v)] += 1
if len(examples[key]) < _KEEP:
examples[key].append({"file": ev["file"], "attrs": attrs, "bw": bw,
"sfm": sfm, "detail": detail})
carveouts.update(covered)
bin_dir, xml_dir = _run_dirs(Path(results_path))
return {"events": events, "fields": fields, "by_year": by_year, "compared": compared,
"failing": failing, "examples": examples, "carveouts": carveouts,
"bin_dir": bin_dir, "xml_dir": xml_dir, "regressions": None}
def _fully_matching(counts: Counter) -> bool:
return not any(counts[v] for v in _NOT_DONE)
def write_summary(agg: dict, path: Path, title: Optional[str] = None) -> None:
fields = agg["fields"]
order = sorted(fields, key=lambda f: (-sum(fields[f][v] for v in _NOT_DONE), f))
done = sum(_fully_matching(fields[f]) for f in fields)
lines = [f"# Decode check — {title or Path(path).parent.name}", "",
f"{agg['events']} events · {done} of {len(fields)} fields fully matching", ""]
if agg.get("regressions") is not None:
n = agg["regressions"]
lines += [f"**{n} regressions** since the previous run" + (" — see changes.md" if n else ""), ""]
lines += ["| field | " + " | ".join(VERDICTS) + " |", "|---|" + "---:|" * len(VERDICTS)]
lines += [f"| {f} | " + " | ".join(str(fields[f][v]) for v in VERDICTS) + " |" for f in order]
years = sorted({y for c in agg["by_year"].values() for y in c})
bad = [f for f in order if not _fully_matching(fields[f])]
if bad:
lines += ["", "## Not matching, by event year", "",
"| field | " + " | ".join(years) + " |", "|---|" + "---:|" * len(years)]
lines += [f"| {f} | " + " | ".join(str(agg["by_year"][f][y] or "") for y in years) + " |"
for f in bad]
if agg["carveouts"]:
lines += ["", "## Carve-outs (events covered)", "", "| carve-out | events |", "|---|---:|"]
lines += [f"| {c} | {n} |" for c, n in agg["carveouts"].most_common()]
Path(path).write_text("\n".join(lines) + "\n")
def write_details(agg: dict, path: Path) -> None:
def total_of(key: str) -> int:
field, verdict = key.split("|", 1)
return agg["fields"][field][verdict]
out = {}
for key in sorted(agg["examples"], key=lambda k: (-total_of(k), k)):
field = key.split("|", 1)[0]
total = total_of(key)
groups = {}
for attr, values in agg["failing"].get(key, {}).items():
rows = []
for value, n in values.most_common():
if n < _GROUP_SHARE * total:
break
seen = agg["compared"][field][attr][value]
rate = round(n / seen, 3) if seen else 1.0
rows.append({"value": value, "failing": n, "compared": seen, "rate": rate,
"concentrated": rate >= _CONCENTRATED})
if rows:
groups[attr] = rows
out[key] = {"total": total, "groups": groups,
"examples": _pick_examples(agg, key, groups)}
Path(path).write_text(json.dumps(out, indent=1))
def _pick_examples(agg: dict, key: str, groups: dict) -> list[dict]:
"""One example per top group value first, then the rest in run order."""
pool, picked = agg["examples"][key], []
for attr, rows in groups.items():
for row in rows:
ex = next((e for e in pool if str(e["attrs"].get(attr)) == row["value"]
and e not in picked), None)
if ex is not None and len(picked) < _EXAMPLES:
picked.append(ex)
picked += [e for e in pool if e not in picked][: _EXAMPLES - len(picked)]
rerun = f"python scratch/check_s3_decode.py {agg['bin_dir']} {agg['xml_dir']} --file "
return [{"file": e["file"], "bw": e["bw"], "sfm": e["sfm"], "detail": e["detail"],
"rerun": rerun + e["file"]} for e in picked]
def _verdicts(results_path: Path) -> dict[tuple[str, str], str]:
out = {}
with gzip.open(results_path, "rt", encoding="utf-8") as fh:
for line in fh:
ev = json.loads(line)
for row in ev["results"]:
out[(ev["file"], row[0])] = row[1]
return out
def compare_runs(prev_results: Path, cur_results: Path) -> dict:
"""What changed between two runs: per-field verdict counts before and
after, every (event, field) that used to match and no longer does, and how
many non-matches now match."""
before, after = _verdicts(prev_results), _verdicts(cur_results)
fields: dict[str, dict[str, list[int]]] = defaultdict(lambda: defaultdict(lambda: [0, 0]))
for (_, field), v in before.items():
fields[field][v][0] += 1
for (_, field), v in after.items():
fields[field][v][1] += 1
regressions = [{"file": f, "field": fld, "before": "match", "after": v}
for (f, fld), v in sorted(after.items())
if v != "match" and before.get((f, fld)) == "match"]
fixed = sum(1 for k, v in after.items() if v == "match" and before.get(k) not in (None, "match"))
return {"fields": {f: dict(c) for f, c in fields.items()}, "regressions": regressions,
"fixed": fixed, "prev": str(prev_results)}
def write_changes(chg: dict, path: Path) -> None:
regs = chg["regressions"]
lines = [f"# Changes since {chg.get('prev', 'the previous run')}", "",
f"{len(regs)} regressions · {chg['fixed']} fixed", ""]
if regs:
lines += ["## Regressions (matched before, not now)", "", "| file | field | now |", "|---|---|---|"]
lines += [f"| {r['file']} | {r['field']} | {r['after']} |" for r in regs[:500]]
if len(regs) > 500:
lines.append(f"| … {len(regs) - 500} more | | |")
lines.append("")
moved = {f: c for f, c in chg["fields"].items() if any(b != a for b, a in c.values())}
if moved:
lines += ["## Fields whose counts moved (before → after)", "",
"| field | " + " | ".join(VERDICTS) + " |", "|---|" + "---|" * len(VERDICTS)]
for f in sorted(moved):
lines.append(f"| {f} | " + " | ".join(
f"{moved[f].get(v, [0, 0])[0]} → {moved[f].get(v, [0, 0])[1]}" for v in VERDICTS) + " |")
Path(path).write_text("\n".join(lines) + "\n")