merge: dev into feat/series4-sfm-parity -- v0.32.0, #42, #47/#49, #44/#45, the S3 decode checker

Brings the branch up to dev (41 commits) before the 1c bench fixes, which
touch code dev changed: the histogram reader (#47/#49, bench finding #2), the
v0.32.0 event-time rules, the Blastware file's setup-block fields (#44/#45),
and the decode checker for verifying stored S3 downloads.

One conflict: the top of the Series-III reference's change table -- both sides
added rows; kept all, in date order, CRLF preserved.  CLAUDE.md, README,
blastware_file.py, models.py and database.py merged cleanly.  Suite: the known
16 failures only (15 test_bw_ascii_report, test_save_imported_bw_without_report_
works_unchanged, which also fails on dev); 1237 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-29 22:51:42 -04:00
commit 342c69602d
54 files changed
+22279 -264

No files matched your search

+243
View File
@@ -0,0 +1,243 @@
#!/usr/bin/env python3
"""
The Series 3 decode checker: SFM's file-only decode of every event, compared
with Blastware's `_XML.XML` report of the same event.
python scratch/check_s3_decode.py <binaries dir> <xml dir> [options]
Each event is decoded the way SFM ingest does, from its bytes alone -- no
filename, no report -- and every field, waveform sample and histogram interval
is compared (minimateplus/decode_check.py). Results go to a run folder outside
the repo, because they carry customer project names:
~/dl2-archive/checker-runs/<YYYYmmdd-HHMMSS>/
results.jsonl.gz one line per event: file, attrs, results rows
run.json args, commit, event count, wall time
Partial runs: --serial BE9441, --year 2024, --type W|H, --field samples.,
--sample 2000 [--seed K]. Spec:
docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md.
A lab tool (ADR 0003): it may import from sfm/; the comparison it runs may not.
"""
from __future__ import annotations
import argparse
import gzip
import json
import logging
import os
import random
import re
import subprocess
import sys
import time
from concurrent.futures import ProcessPoolExecutor
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
_REPO = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(_REPO))
from minimateplus.bw_xml_report import XmlReport, parse_xml_report_file # noqa: E402
from minimateplus.decode_check import compare, sfm_side # noqa: E402
from minimateplus.decode_check_carveouts import CARVEOUTS # noqa: E402
from scratch import decode_check_report as report # noqa: E402
RUNS_DIR = Path.home() / "dl2-archive" / "checker-runs"
_BIN = re.compile(r"^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$", re.I)
_MODEL = re.compile(r"^V\s+\S+\s+(.*)$")
_EPOCH = datetime(1985, 1, 1)
def find_pairs(bin_dir: Path, xml_dir: Path) -> list[tuple[str, Path, Optional[Path]]]:
"""(basename, binary, XML report or None) for every Series 3 event file
under `bin_dir`, deduped by basename -- an ACH folder's Sent/ mirrors its
root."""
xmls = {p.name.upper(): p for p in Path(xml_dir).iterdir() if p.is_file()}
seen: dict[str, tuple[str, Path]] = {}
for root, _, files in os.walk(bin_dir):
for f in files:
if _BIN.match(f) and f.upper() not in seen:
seen[f.upper()] = (f, Path(root) / f)
out = []
for key in sorted(seen):
name, path = seen[key]
stem, ext = name.split(".")
out.append((name, path, xmls.get(f"{stem}_{ext}_XML.XML".upper())))
return out
def event_attrs(name: str, ref: XmlReport, raw: bytes) -> dict[str, str]:
"""The keys failures are grouped by -- all from the reference or the file."""
s = ref.scalars
m = _MODEL.match(s.get("Version", ""))
date = s.get("EventDate") or s.get("HistogramStartDate") or ""
return {
"model": m.group(1) if m else s.get("Version", "?"),
"serial": s.get("SerialNumber", "?"),
"type": s.get("EventType", "?"),
"year": date[:4] or "?",
"sample_rate": s.get("SampleRate", "?").split(" ")[0],
"range": s.get("GeoRange", "?"),
"mic_units": ref.event_units or "?",
"interval": s.get("IntervalSize", "-"),
"setup_standard": "yes" if b"Standard Recording Setup" in raw else "no",
}
def check_event(name: str, bin_path: str, xml_path: Optional[str]) -> dict:
"""One event: its grouping attrs and one row per compared field. A missing
reference or any failure is a single row, so a run never stops on one file."""
if xml_path is None:
return {"file": name, "attrs": {},
"results": [["event", "no_reference", None, None, "no XML report", None]]}
try:
raw = Path(bin_path).read_bytes()
ref = parse_xml_report_file(xml_path)
rows = compare(sfm_side(raw), ref, CARVEOUTS)
return {"file": name, "attrs": event_attrs(name, ref, raw),
"results": [[r.field, r.verdict, r.bw, r.sfm, r.detail, r.carveout] for r in rows]}
except Exception as exc: # noqa: BLE001 -- one bad file must not stop a run
return {"file": name, "attrs": {},
"results": [["event", "error", None, None, repr(exc)[:300], None]]}
def _check_pair(pair: tuple[str, str, Optional[str]]) -> dict:
return check_event(*pair)
def _quiet() -> None:
logging.disable(logging.CRITICAL)
def _filename_prefix(serial: str) -> str:
"""BE9441 -> K441: the prefix Blastware's filenames encode a serial as."""
num = int(re.sub(r"\D", "", serial))
return f"{chr(ord('B') + num // 1000)}{num % 1000:03d}"
def _filename_year(name: str) -> int:
stem, ext = name.upper().split(".")
return (_EPOCH + timedelta(seconds=int(stem[4:8], 36) * 1296 + int(ext[:2], 36))).year
def _git_head() -> Optional[str]:
try:
return subprocess.run(["git", "rev-parse", "HEAD"], cwd=_REPO, capture_output=True,
text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
return None
_SCOPE = ("bin_dir", "xml_dir", "serial", "year", "type", "field", "sample", "seed")
def _scope(args: dict) -> dict:
return {k: args.get(k) for k in _SCOPE}
def _previous_run(out_dir: Path, args: dict) -> Optional[Path]:
"""The newest other completed run (run.json written) of the same scope in
the runs folder -- only for runs kept there. A sample or a one-serial run
is no baseline for a full run, nor the other way round."""
if out_dir.parent.resolve() != RUNS_DIR.resolve():
return None
want = _scope(args)
for p in sorted(RUNS_DIR.iterdir(), reverse=True):
if not p.is_dir() or p.resolve() == out_dir.resolve():
continue
try:
if _scope(json.loads((p / "run.json").read_text())["args"]) == want:
return p
except (OSError, KeyError, ValueError):
continue
return None
def _print_one(name: str, pairs: list[tuple[str, Path, Optional[Path]]]) -> int:
"""--file: check one event and print its table; no run folder."""
match = [p for p in pairs if p[0].upper() == name.upper()]
if not match:
print(f"{name}: no such event file under the binaries folder", file=sys.stderr)
return 1
n, b, x = match[0]
ev = check_event(n, str(b), str(x) if x else None)
print(f"{n} {ev['attrs']}")
print(f"{'field':30s} {'verdict':12s} {'Blastware':30s} {'SFM':30s} detail")
for field, verdict, bw, sfm, detail, carveout in ev["results"]:
note = f"{detail} {('[' + carveout + ']') if carveout else ''}".strip()
print(f"{field:30.30s} {verdict:12s} {str(bw):30.30s} {str(sfm):30.30s} {note}")
return 0
def main(argv: Optional[list[str]] = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("bin_dir", type=Path)
ap.add_argument("xml_dir", type=Path)
ap.add_argument("--out", type=Path, help=f"run folder (default {RUNS_DIR}/<timestamp>)")
ap.add_argument("--serial", action="append", default=[], help="e.g. BE9441; repeatable")
ap.add_argument("--year", action="append", type=int, default=[], help="event year; repeatable")
ap.add_argument("--type", choices=("W", "H"), help="waveforms or histograms only")
ap.add_argument("--field", action="append", default=[], help="keep result rows whose field starts with this")
ap.add_argument("--sample", type=int, help="check a random sample of N events")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--jobs", type=int, default=os.cpu_count() or 1)
ap.add_argument("--file", help="check one event and print its table")
ap.add_argument("--compare-to", type=Path, help="an earlier run folder to diff against")
args = ap.parse_args(argv)
started = time.monotonic()
pairs = find_pairs(args.bin_dir, args.xml_dir)
if args.file:
return _print_one(args.file, pairs)
if args.serial:
prefixes = tuple(_filename_prefix(s) for s in args.serial)
pairs = [p for p in pairs if p[0].upper().startswith(prefixes)]
if args.year:
pairs = [p for p in pairs if _filename_year(p[0]) in args.year]
if args.type:
pairs = [p for p in pairs if p[0].upper().endswith(args.type)]
if args.sample is not None and args.sample < len(pairs):
pairs = sorted(random.Random(args.seed).sample(pairs, args.sample))
out_dir = args.out or RUNS_DIR / datetime.now().strftime("%Y%m%d-%H%M%S")
out_dir.mkdir(parents=True, exist_ok=True)
work = [(n, str(b), str(x) if x else None) for n, b, x in pairs]
_quiet()
if args.jobs <= 1:
results = map(_check_pair, work)
pool = None
else:
pool = ProcessPoolExecutor(args.jobs, initializer=_quiet)
results = pool.map(_check_pair, work, chunksize=64)
try:
with gzip.open(out_dir / "results.jsonl.gz", "wt", encoding="utf-8") as fh:
for ev in results:
if args.field:
ev["results"] = [r for r in ev["results"] if r[0].startswith(tuple(args.field))]
fh.write(json.dumps(ev) + "\n")
finally:
if pool is not None:
pool.shutdown()
run = {"args": {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()},
"commit": _git_head(), "events": len(work),
"seconds": round(time.monotonic() - started, 1)}
(out_dir / "run.json").write_text(json.dumps(run, indent=2))
agg = report.aggregate(out_dir / "results.jsonl.gz")
prev = args.compare_to or _previous_run(out_dir, run["args"])
if prev is not None and (prev / "results.jsonl.gz").exists():
chg = report.compare_runs(prev / "results.jsonl.gz", out_dir / "results.jsonl.gz")
report.write_changes(chg, out_dir / "changes.md")
agg["regressions"] = len(chg["regressions"])
report.write_summary(agg, out_dir / "summary.md")
report.write_details(agg, out_dir / "details.json")
print(out_dir)
return 0
if __name__ == "__main__":
sys.exit(main())
+235
View File
@@ -0,0 +1,235 @@
"""
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:
"""Matched somewhere and failed nowhere. A field that only ever has no
reference (an always-empty element) has proven nothing."""
return (counts["match"] + counts["accepted"]) > 0 and not any(counts[v] for v in _NOT_DONE)
def _events_line(event: Counter) -> str:
def n(k: int, what: str) -> str:
return f"{k} event{'' if k == 1 else 's'} {what}"
return " · ".join(s for s in (n(event["no_reference"], "without a report") if event["no_reference"] else "",
n(event["error"], "that failed to check") if event["error"] else "") if s)
def write_summary(agg: dict, path: Path, title: Optional[str] = None) -> None:
# The "event" pseudo-field is a whole event with no report or a failure,
# not a field: it is reported on its own line.
fields = {f: c for f, c in agg["fields"].items() if f != "event"}
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", ""]
events = _events_line(agg["fields"].get("event", Counter()))
if events:
lines += [events, ""]
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]
_MATCHING = ("match", "accepted")
def _verdicts(results_path: Path) -> tuple[dict[tuple[str, str], str], set[str], set[str]]:
"""(file, field) -> verdict, every file in the run, and the files whose
check failed outright (their field rows collapse to one "event" error)."""
out, files, errored = {}, set(), set()
with gzip.open(results_path, "rt", encoding="utf-8") as fh:
for line in fh:
ev = json.loads(line)
files.add(ev["file"])
for row in ev["results"]:
out[(ev["file"], row[0])] = row[1]
if row[0] == "event" and row[1] == "error":
errored.add(ev["file"])
return out, files, errored
def compare_runs(prev_results: Path, cur_results: Path) -> dict:
"""What changed between two runs, over the events both checked: per-field
verdict counts before and after, every (event, field) that matched and no
longer does -- including events that now fail outright -- and how many
non-matches now match."""
before, files_before, _ = _verdicts(prev_results)
after, files_after, errored = _verdicts(cur_results)
shared = files_before & files_after
fields: dict[str, dict[str, list[int]]] = defaultdict(lambda: defaultdict(lambda: [0, 0]))
for (f, field), v in before.items():
if f in shared:
fields[field][v][0] += 1
for (f, field), v in after.items():
if f in shared:
fields[field][v][1] += 1
regressions = []
for (f, field), v in sorted(before.items()):
if v not in _MATCHING or f not in shared:
continue
now = after.get((f, field), "error" if f in errored else "missing")
if now not in _MATCHING:
regressions.append({"file": f, "field": field, "before": v, "after": now})
fixed = sum(1 for k, v in after.items()
if k[0] in shared and v in _MATCHING and before.get(k) not in (None,) + _MATCHING)
return {"fields": {f: dict(c) for f, c in fields.items()}, "regressions": regressions,
"fixed": fixed, "shared_events": len(shared), "prev": str(prev_results),
"prev_scope": _scope_of(Path(prev_results).parent)}
def _scope_of(run_dir: Path) -> Optional[dict]:
try:
args = json.loads((run_dir / "run.json").read_text())["args"]
except (OSError, KeyError, ValueError):
return None
return {k: args.get(k) for k in ("serial", "year", "type", "field", "sample", "seed") if args.get(k)}
def write_changes(chg: dict, path: Path) -> None:
regs = chg["regressions"]
scope = chg.get("prev_scope")
lines = [f"# Changes since {chg.get('prev', 'the previous run')}", "",
f"Previous run's scope: {scope or 'all events'} · compared over "
f"{chg.get('shared_events', '?')} events both runs checked", "",
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")