diff --git a/scratch/check_s3_decode.py b/scratch/check_s3_decode.py new file mode 100644 index 0000000..5580ad0 --- /dev/null +++ b/scratch/check_s3_decode.py @@ -0,0 +1,191 @@ +#!/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 [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// + 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 + +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 + + +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}/)") + 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.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)) + print(out_dir) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_check_s3_decode.py b/tests/test_check_s3_decode.py new file mode 100644 index 0000000..b39ebfb --- /dev/null +++ b/tests/test_check_s3_decode.py @@ -0,0 +1,57 @@ +""" +The decode checker's runner and reports (decode checker, Tasks 5-7). + +Runs on the fixture folder, which holds the binaries and their XML reports +side by side. +""" +from __future__ import annotations + +import gzip +import importlib +import json +from pathlib import Path + +run = importlib.import_module("scratch.check_s3_decode") + +FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26" + + +def test_find_pairs_dedupes_and_pairs(tmp_path): + (tmp_path / "Sent").mkdir() + for n in ("R352HIUI.F40W", "Sent/R352HIUI.F40W", "UM11719_20240404193109.IDFH"): + (tmp_path / n).write_bytes(b"x") + pairs = run.find_pairs(tmp_path, FIX) + assert [p[0] for p in pairs] == ["R352HIUI.F40W"] + assert pairs[0][2].name == "R352HIUI_F40W_XML.XML" + + +def test_check_event_rows_and_attrs(): + out = run.check_event("M007HVWF.K30W", str(FIX / "M007HVWF.K30W"), str(FIX / "M007HVWF_K30W_XML.XML")) + assert out["attrs"]["range"] == "1.250" and out["attrs"]["model"] == "MiniMate Plus" + assert any(r[0] == "TranPPV" and r[1] == "mismatch" for r in out["results"]) + + +def test_bad_input_is_one_error_row(tmp_path): + bad = tmp_path / "R352HIUI.F40W" + bad.write_bytes(b"not a blastware file") + out = run.check_event(bad.name, str(bad), str(FIX / "R352HIUI_F40W_XML.XML")) + assert out["results"] == [["event", "error", None, None, out["results"][0][4], None]] + + +def test_missing_reference_is_one_no_reference_row(): + out = run.check_event("R352HIUI.F40W", str(FIX / "R352HIUI.F40W"), None) + assert [r[:2] for r in out["results"]] == [["event", "no_reference"]] + + +def test_cli_writes_results(tmp_path): + assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1"]) == 0 + lines = gzip.open(tmp_path / "run/results.jsonl.gz", "rt").read().splitlines() + assert len(lines) == 7 + assert json.loads((tmp_path / "run/run.json").read_text())["events"] == 7 + + +def test_field_filter_keeps_only_matching_rows(tmp_path): + assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1", + "--field", "samples."]) == 0 + for line in gzip.open(tmp_path / "run/results.jsonl.gz", "rt"): + assert all(r[0].startswith("samples.") for r in json.loads(line)["results"])