From c0d837c14fca9f97af995dc4596cf06b2fd0a6f9 Mon Sep 17 00:00:00 2001 From: serversdown Date: Thu, 29 Oct 2026 20:11:33 -0400 Subject: [PATCH] fix(checker): final-review fixes -- regressions, baselines, the PVS carve-out, the headline - A matching event that now fails outright is a regression: compare_runs walks the previous run's matching rows, so a check that collapses to one error row no longer hides every field it used to match. Counts moved are taken over the events both runs checked. - The default baseline is the newest completed run (run.json written) of the same scope; a 2,000-event sample is no baseline for a full run. changes.md names the previous run's scope. - The PVS saturation carve-out now needs Blastware's OORANGE, a channel Blastware clamped at SFM's ceiling, and SFM's sum within three channels at the ceiling -- an unclipped Sensitive-range channel read 8x can no longer let an 8x sum through. - 'Fields fully matching' needs a match: an always-empty element proves nothing. Events without a report are a line of their own. - CLAUDE.md: histogram PVS described correctly; 35 sub-minute histograms plus 2 one-minute no-mic ones, not '~37 sub-minute'. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9 --- CLAUDE.md | 8 ++- minimateplus/decode_check_carveouts.py | 16 ++++-- scratch/check_s3_decode.py | 27 +++++++-- scratch/decode_check_report.py | 80 ++++++++++++++++++++------ tests/test_check_s3_decode.py | 42 ++++++++++++++ tests/test_decode_check.py | 20 +++++++ 6 files changed, 162 insertions(+), 31 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index aaa7875..38347da 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,11 +30,13 @@ Read this first when picking the project back up. - ❌ Every histogram reads as a waveform without its filename (#41), and their start times are 1 s early (#51). - ❌ Open findings: - - histogram PVS: SFM sums interval peaks, Blastware takes the per-interval - vector sum + - histogram PVS: SFM takes the vector magnitude of each channel's interval + peak (peaks that may come from different moments); Blastware takes the + per-interval vector sum - mic psi conversion - mic dB off by 0.05–0.1 on ~1,000 events - - ~37 sub-minute histograms decode wrongly + - 35 sub-minute (5 s / 2 s) histograms decode wrongly, plus 2 one-minute + no-mic histograms (`R352HFZ7`-shaped, likely a separate cause) - 26 histogram start dates are a day off - ⬜ Not read yet: job number, ZC frequency, acceleration, displacement, time of peak, sensor check, battery, calibration, range, units, monitor log. diff --git a/minimateplus/decode_check_carveouts.py b/minimateplus/decode_check_carveouts.py index 9cb0c80..7122f57 100644 --- a/minimateplus/decode_check_carveouts.py +++ b/minimateplus/decode_check_carveouts.py @@ -54,11 +54,17 @@ def _saturation(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool: v = sfm.values.get(res.field) return v is not None and _clamped(res.bw or "", r) and _at_ceiling(float(v), r) if res.field == "PeakVectorSum": - # A vector sum can exceed the range (11.55 on T438HGTZ.B30W); it is the - # clipped channel under it that must sit at the ceiling. - return (_clamped(res.bw or "", r) and - any(sfm.values.get(f) is not None and _at_ceiling(float(sfm.values[f]), r) - for f in ("TranPPV", "VertPPV", "LongPPV"))) + # A vector sum can exceed the range without any clipping, so only + # Blastware's OORANGE counts. SFM's sum is bounded by three channels at + # the ceiling (11.55 on T438HGTZ.B30W), and a channel Blastware itself + # clamped must be the one SFM has at the ceiling -- an unclipped channel + # read 8x high on the Sensitive range does not qualify. + pvs = sfm.values.get("PeakVectorSum") + return ((res.bw or "").strip() == "OORANGE" and pvs is not None + and r - _TOL <= float(pvs) <= 3 ** 0.5 * r * 1.01 + and any(_clamped(ref.scalars.get(f, ""), r) and sfm.values.get(f) is not None + and _at_ceiling(float(sfm.values[f]), r) + for f in ("TranPPV", "VertPPV", "LongPPV"))) got = series_pairs(sfm, ref, res.field) if got is None or got[1]: return False diff --git a/scratch/check_s3_decode.py b/scratch/check_s3_decode.py index 51bbf3d..b9a6503 100644 --- a/scratch/check_s3_decode.py +++ b/scratch/check_s3_decode.py @@ -131,12 +131,29 @@ def _git_head() -> Optional[str]: return None -def _previous_run(out_dir: Path) -> Optional[Path]: - """The newest other run in the runs folder -- only for runs kept there.""" +_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 - runs = sorted(p for p in RUNS_DIR.iterdir() if p.is_dir() and p.resolve() != out_dir.resolve()) - return runs[-1] if runs else 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: @@ -211,7 +228,7 @@ def main(argv: Optional[list[str]] = None) -> int: "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) + 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") diff --git a/scratch/decode_check_report.py b/scratch/decode_check_report.py index fef7bc9..15d22c0 100644 --- a/scratch/decode_check_report.py +++ b/scratch/decode_check_report.py @@ -74,15 +74,29 @@ def aggregate(results_path: Path) -> dict: def _fully_matching(counts: Counter) -> bool: - return not any(counts[v] for v in _NOT_DONE) + """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: - fields = agg["fields"] + # 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 ""), ""] @@ -143,37 +157,67 @@ def _pick_examples(agg: dict, key: str, groups: dict) -> list[dict]: "rerun": rerun + e["file"]} for e in picked] -def _verdicts(results_path: Path) -> dict[tuple[str, str], str]: - out = {} +_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] - return out + 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: 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) + """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 (_, 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")) + 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, "prev": str(prev_results)} + "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 |", "|---|---|---|"] diff --git a/tests/test_check_s3_decode.py b/tests/test_check_s3_decode.py index 0d1b494..f9640f1 100644 --- a/tests/test_check_s3_decode.py +++ b/tests/test_check_s3_decode.py @@ -129,3 +129,45 @@ def test_file_prints_one_event(tmp_path, capsys): assert run.main([str(FIX), str(FIX), "--file", "M007HVWF.K30W"]) == 0 out = capsys.readouterr().out assert any("TranPPV" in line and "mismatch" in line for line in out.splitlines()) + + +# ── Final review fixes ────────────────────────────────────────────────────── + +def test_a_matching_event_that_now_errors_is_a_regression(tmp_path): + prev, cur = tmp_path / "prev.jsonl.gz", tmp_path / "cur.jsonl.gz" + _write_results(prev, [_one("A.W", "SampleRate", "match"), _one("B.W", "notes", "match")]) + _write_results(cur, [_one("A.W", "event", "error"), _one("B.W", "notes", "match")]) + chg = report.compare_runs(prev, cur) + assert chg["regressions"] == [{"file": "A.W", "field": "SampleRate", + "before": "match", "after": "error"}] + + +def test_counts_moved_cover_only_shared_events(tmp_path): + prev, cur = tmp_path / "prev.jsonl.gz", tmp_path / "cur.jsonl.gz" + _write_results(prev, [_one("A.W", "SampleRate", "match")]) + _write_results(cur, [_one("A.W", "SampleRate", "match"), _one("B.W", "SampleRate", "match")]) + assert report.compare_runs(prev, cur)["fields"]["SampleRate"]["match"] == [1, 1] + + +def test_default_comparison_is_the_newest_completed_run_of_the_same_scope(tmp_path, monkeypatch): + runs = tmp_path / "runs" + monkeypatch.setattr(run, "RUNS_DIR", runs) + base = [str(FIX), str(FIX), "--jobs", "1"] + assert run.main(base + ["--out", str(runs / "20990101-000001")]) == 0 # same scope + assert run.main(base + ["--out", str(runs / "20990101-000002"), "--type", "W"]) == 0 # narrower + (runs / "20990101-000003").mkdir() # never finished + assert run.main(base + ["--out", str(runs / "20990101-000004")]) == 0 + assert "20990101-000001" in (runs / "20990101-000004/changes.md").read_text().splitlines()[0] + + +def test_fields_fully_matching_need_a_match_and_skip_the_event_row(tmp_path): + res = tmp_path / "results.jsonl.gz" + _write_results(res, [ + {"file": "A.W", "attrs": {}, "results": [["SampleRate", "match", "1", "1", "", None], + ["UsbSummaryChannels", "no_reference", "", None, "", None]]}, + {"file": "B.W", "attrs": {}, "results": [["event", "no_reference", None, None, "no XML report", None]]}, + ]) + report.write_summary(report.aggregate(res), tmp_path / "summary.md") + text = (tmp_path / "summary.md").read_text() + assert "1 of 2 fields fully matching" in text + assert "1 event without a report" in text and "| event |" not in text diff --git a/tests/test_decode_check.py b/tests/test_decode_check.py index c33d823..1654819 100644 --- a/tests/test_decode_check.py +++ b/tests/test_decode_check.py @@ -123,3 +123,23 @@ def test_sensitive_range_8x_stays_a_mismatch(): def test_every_carveout_has_evidence(): assert all(c.id and c.fields and len(c.evidence) > 40 for c in CARVEOUTS) + + +def test_pvs_carveout_needs_oorange_from_blastware(): + raw = (FIX / "T438HGTZ.B30W").read_bytes() + ref = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML") + ref.scalars["PeakVectorSum"] = "10.392" # a vector sum may exceed the range unclipped + res = {r.field: r for r in compare(sfm_side(raw), ref, CARVEOUTS)} + assert res["PeakVectorSum"].verdict == "mismatch" + + +def test_pvs_carveout_needs_the_clipped_channel_at_the_ceiling(): + # 1.250 range, Blastware PVS OORANGE; an UNclipped channel's 8x value happens to land + # in the 1.250 band -- that must not let SFM's 8x vector sum through. + raw = (FIX / "M007HVWF.K30W").read_bytes() + ref = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML") + ref.scalars["TranPPV"] = "0.157" + side = sfm_side(raw) + side.values["TranPPV"] = 1.256 + res = {r.field: r for r in compare(side, ref, CARVEOUTS)} + assert res["PeakVectorSum"].verdict == "mismatch"