diff --git a/docs/superpowers/plans/2026-10-29-s3-decode-checker.md b/docs/superpowers/plans/2026-10-29-s3-decode-checker.md new file mode 100644 index 0000000..c046e64 --- /dev/null +++ b/docs/superpowers/plans/2026-10-29-s3-decode-checker.md @@ -0,0 +1,648 @@ +# Series 3 Decode Checker Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** A repeatable check that decodes every DL2 Series 3 event file the way SFM ingest does, with no report and no filename, and compares every field, sample and histogram interval with Blastware's `_XML.XML` report. It reports matches, mismatches and gaps, grouped for diagnosis, run after run. + +**Architecture:** There are four pieces. Two are pure codec-library modules: +- `bw_xml_report.py` parses the reference. +- `decode_check.py` builds SFM's side from the bytes and compares the two. + +A carve-out list sits beside the comparison. Two lab-tool scripts in +`scratch/` do the rest: one runs the corpus in parallel and writes a +results file, the other turns results into the summary, the detailed +report and the run-to-run changes. + +**Tech Stack:** Python 3.10, standard library only (`xml.etree.ElementTree`, `concurrent.futures`, `gzip`, `json`), pytest. + +**Spec:** `docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md` + +## Global Constraints + +- Work on branch `feat/s3-decode-checker`, worktree `~/seismo-relay-checker`. + Never commit to `main` or `dev`. **Do not touch `CHANGELOG.md`**: it is + written on dev at merge. +- **Standard library only.** `lxml` is not installed; do not add dependencies. +- **Codec-library modules never import `sfm/`.** These are + `minimateplus/bw_xml_report.py`, `minimateplus/decode_check.py` and + `minimateplus/decode_check_carveouts.py`. Only `scratch/` may import `sfm/`. +- **SFM's side comes only from the event bytes:** + `decode_blastware_bytes(raw, name=None)`. No filename, no report overlay, + and nothing from the XML ever reaches it. +- **SFM's own assumptions are kept:** + - geophone counts become in/s at the Normal range, `10.0 / 32000` per count + (`event_file_io._GEO_NORMAL_FS_INS / _GEO_INT16_FS`) + - mic counts become dB with `waveform_codec.mic_count_to_db`, or psi with + `event_file_io._MIC_FS_PSI` + - the range is never taken from the reference +- **Precision rule:** a number matches when + `|sfm − printed| ≤ 0.5·10^(−decimals in the printed text) + 1e-9`. + Blastware rounds halves away from zero. +- **Verdicts are exactly** `match`, `mismatch`, `sfm_blank`, `accepted`, + `no_reference`, `error`. +- **Series 3 only:** skip `UM…` XMLs. Dedupe binaries by upper-cased basename + (`Sent/` mirrors the root). +- **Run output goes outside the repo.** Default + `~/dl2-archive/checker-runs//`; it contains customer + names, so never commit it. +- **Speed:** a full run (70,042 events, `--jobs 4`) in under 1 h; `--sample + 2000` in a few minutes. +- **Tests:** run with `/home/serversdown/seismo-relay/.venv/bin/python -m + pytest`. + - The full suite has 18 known failures in this worktree, and they also fail + on unchanged dev: 15 in `tests/test_bw_ascii_report.py`, + `tests/test_event_file_io.py::test_save_imported_bw_without_report_works_unchanged`, + and 2 in `tests/test_idf_binary_codec.py` (three-channel). + - A task may add **no new** failures. +- **Fixtures:** `tests/fixtures/` is gitignored. Add new fixtures with + `git add -f`. + +## Review Focus + +1. **Ragged sample rows.** Channels can end at different lengths: in + `T438HGTZ.B30W`, Tran/Vert/MicL stop 3 samples before Long. Blastware's + own table then prints rows with fewer cells, holding the channels still + running, in order. Cells must be attributed by SFM's per-channel lengths, + not by position. That file must come out `match`. A row whose cell count + disagrees with SFM's running channels is a `mismatch` with + `row_length_disagreements` in `detail`; never a silent zip. Tests in Task 3. +2. **The Sensitive range: a clipped 1.250 in/s event** (`M007HVWF.K30W`, + `OORANGE`). SFM's Normal-range values (8× high) must stay `mismatch`; the + saturation carve-out must not swallow them. Test in Task 4. +3. **An event that fails to decode, or an XML that is truncated or + malformed.** That event gets one `error` row and the run continues. Test in + Task 5. +4. **Non-numeric reference text where numbers are expected:** `>100`, `N/A`, + `Check`, `OORANGE`, and units inside the text (`6.7 Volts`, `3.0 sec.`). + These parse without exceptions and map to the rules in Task 3. Tests in + Tasks 1 and 3. +5. **Mic units: `dB(L)` vs `psi(L)` vs none** (`in/s` only, 3 channels, 7 + interval columns). The comparison picks SFM's conversion by the reference's + units, and a no-mic event has no MicL rows at all. Tests in Tasks 1 and 3. + +--- + +### Task 1: Fixtures and the XML report parser + +**Files:** +- Create: `tests/fixtures/decode-checker-10-29-26/` holding these binaries + plus each one's `__XML.XML`, copied from `~/dl2-archive/files/` + and `~/dl2-archive/xml/`: + - `R352HIUI.F40W`: waveform, setup `BE16352.set` + - `M529L4XQ.R30H`: histogram, relabelled notes + - `T1905KDW.5F0W`: waveform, job number, `>100`, `N/A`, `Check` + - `M007HVWF.K30W`: waveform, range 1.250, `OORANGE` + - `T004JTRF.ME0H`: histogram, `psi(L)` + - `R352HFZ7.530H`: histogram, no mic + - `T438HGTZ.B30W`: waveform, ragged rows, `OORANGE` at range 10.000 +- Create: `minimateplus/bw_xml_report.py` +- Test: `tests/test_bw_xml_report.py` + +**Interfaces:** +- Produces: + ```python + @dataclass + class XmlReport: + scalars: dict[str, str] # tag -> text: top-level simple elements, and + # vu -> v + units: dict[str, str] # tag -> the nested text + event_units: Optional[str] # top-level , e.g. "in/s and dB(L)" + channels: list[str] # / in order + job_number: Optional[str] + notes: list[tuple[str, str]] # (tag, value), non-empty, in order, between + # top-level and , JobNumber excluded + sample_rows: Optional[list[list[str]]] # waveform: printed cells per row, as-is; + # a row holds only the channels still running + interval_columns: Optional[list[str]] # histogram: ColumnTitle, whitespace collapsed + intervals: Optional[list[tuple[str, list[str]]]] # histogram: (Time, cells) + def parse_xml_report(data: bytes) -> XmlReport + def parse_xml_report_file(path: Union[str, Path]) -> XmlReport + ``` + +- [ ] **Step 1: Copy the seven pairs into the fixture folder** (`cp` from the two dl2 folders; XML names keep the `_XML.XML` form). + +- [ ] **Step 2: Write the failing tests** (literal values read from the XMLs): + +```python +FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26" + +def test_scalars_units_and_special_text(): + r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML") + assert r.scalars["SampleRate"] == "1024 sps" + assert r.scalars["RecordTime"] == "1.0 sec." + assert r.scalars["TranPPV"] == "0.005" and r.units["TranPPV"] == "in/s" + assert r.scalars["VertZCFreq"] == ">100" # entity unescaped + assert r.scalars["TranZCFreq"] == "N/A" + assert r.scalars["TranTestResults"] == "Check" + assert r.scalars["BatteryLevel"] == "6.7 Volts" + assert r.job_number == "1" and r.notes == [] + assert r.channels == ["Tran", "Vert", "Long", "MicL"] + +def test_waveform_sample_rows(): + r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML") + assert len(r.sample_rows) == 1024 + assert r.sample_rows[0] == ["-0.005", "0.000", "0.000", "81.94"] + assert r.intervals is None + +def test_ragged_rows_are_kept_as_printed(): + r = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML") + assert len(r.sample_rows) == 2304 + assert r.sample_rows[-4] == ["-0.185", "0.235", "-0.255", "-87.96"] + assert r.sample_rows[-1] == ["-0.245"] # only Long still running + +def test_relabelled_notes_keep_their_tags_in_order(): + r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML") + assert r.notes == [("Location", "Test Loc")] + r = parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML") + assert r.notes[1] == ("Client", "Mele & Mele & Sons, Inc.") + assert r.event_units == "in/s and psi(L)" + +def test_histogram_intervals_and_columns(): + r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML") + assert r.interval_columns[0] == "Tran Peak in/s" and len(r.interval_columns) == 10 + assert r.intervals == [("2025-07-02 14:55:08", + ["2.430", "13", "0.940", ">100", "1.900", "5.8", "3.095", "0.001", "106.0", "51"])] + assert r.samples is None + +def test_no_mic_histogram_has_seven_columns(): + r = parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML") + assert r.event_units == "in/s" + assert r.channels == ["Tran", "Vert", "Long"] + assert len(r.interval_columns) == 7 and len(r.intervals[0][1]) == 7 + +def test_oorange_and_range_values(): + r = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML") + assert r.scalars["TranPPV"] == "OORANGE" + assert r.scalars["GeoRange"] == "1.250" and r.units["GeoRange"] == "in/s" + +def test_truncated_xml_raises_valueerror(): + data = (FIX / "M529L4XQ_R30H_XML.XML").read_bytes() + with pytest.raises(ValueError): + parse_xml_report(data[: len(data) // 2]) +``` + +- [ ] **Step 3: Run them to watch them fail.** + Run: `…/python -m pytest tests/test_bw_xml_report.py -v`. Expected: FAIL on import. + +- [ ] **Step 4: Implement `bw_xml_report.py`.** + - Parse with `xml.etree.ElementTree.fromstring`; wrap `ParseError` in `ValueError`. + - Walk the root's children in order. + - A child with a `` child goes in `scalars` and `units`. + - The notes are the simple children after the top-level `Units` and before + `GeoRange`. + - Waveform cells: `WaveformDataChannels/Data/Row/Cell`, one list per row, + unaltered. + - Histogram: `HistogramData/HistogramDataColumnTitle/ColumnTitle` and + `HistogramDataIntervals`, which interleaves `Time` and `Row`. + +- [ ] **Step 5: Run the tests.** Expected: PASS. + +- [ ] **Step 6: Commit** (fixtures with `git add -f`): + `feat(codec): parse Blastware's _XML.XML event report` + +--- + +### Task 2: SFM's side, from the bytes alone + +**Files:** +- Create: `minimateplus/decode_check.py` +- Test: `tests/test_decode_check.py` + +**Interfaces:** +- Consumes: `minimateplus.event_file_io.decode_blastware_bytes`, `_GEO_NORMAL_FS_INS`, `_GEO_INT16_FS`, `_MIC_FS_PSI`; `minimateplus.waveform_codec.mic_count_to_db`. +- Produces: + ```python + GEO_IPS_PER_COUNT: float = 10.0 / 32000 # from the event_file_io constants + @dataclass + class SfmSide: + event: Event + values: dict[str, object] # reference tag -> SFM's value, or absent/None = blank + notes: list[str] # non-empty project_info slots, in order + job_number: Optional[str] # None until the decoder reads it + channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order + counts: dict[str, list[int]] # waveform samples or histogram interval peaks, per channel + def sfm_side(raw: bytes) -> SfmSide + ``` + The `values` keys, and the only ones SFM fills today: + - `EventType`: `"Full Waveform"` / `"Full Histogram"` from `record_type` + - `SampleRate` (int), `RecordTime` (float) + - `Pre-triggerLength`: `-pretrig_samples / sample_rate` + - `EventDate` and `EventTime` for a waveform, or `HistogramStartDate` and + `HistogramStartTime` for a histogram: `YYYY-MM-DD` and `HH:MM:SS` from + `event.timestamp` + - `TranPPV`, `VertPPV`, `LongPPV`, `PeakVectorSum` from `peak_values` + - `MicLPSPL dB(L)`: `mic_count_to_db` of the largest |MicL count| + - `MicLPSPL psi(L)`: `peak_values.micl` + - `NumberofIntervals` for a histogram: the interval count + +- [ ] **Step 1: Write the failing tests:** + +```python +def test_waveform_side_from_bytes(): + s = sfm_side((FIX / "R352HIUI.F40W").read_bytes()) + assert s.values["SampleRate"] == 1024 and s.values["RecordTime"] == pytest.approx(1.0) + assert s.values["Pre-triggerLength"] == pytest.approx(-253 / 1024) + assert (s.values["EventDate"], s.values["EventTime"]) == ("2018-07-30", "16:13:52") + assert s.notes == ["JV 241 - 1425 Spanlers Mill Rad", "Walsh Granite JV", + "Terra-Mechanics Inc- D. Harrison", "Loc #1 - 1425 Spanlers Mill Rd"] + assert len(s.counts["Tran"]) == 1277 and s.job_number is None + +def test_histogram_interval_peak_in_counts(): + s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes()) + # Blastware: Tran interval peak 2.430 in/s = 7776 counts at 10/32000 in/s per count + assert s.counts["Tran"] == [7776] and s.values["NumberofIntervals"] == 1 + +def test_no_filename_reaches_the_decoder(): + # the type must come from bytes; today they can't tell (#41), so a histogram reads Waveform + s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes()) + assert s.values["EventType"] == "Full Waveform" + +def test_report_fields_stay_blank(): + s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes()) + for tag in ("TranZCFreq", "TranPeakAcceleration", "BatteryLevel", "Calibration", "TranTestResults"): + assert s.values.get(tag) is None +``` + + When #41 is fixed, `test_no_filename_reaches_the_decoder` is updated to + `"Full Histogram"`. Until then it pins that no name is passed. + +- [ ] **Step 2: Run them; expect a FAIL on import.** +- [ ] **Step 3: Implement `sfm_side`** in `minimateplus/decode_check.py`, per the Interfaces block. +- [ ] **Step 4: Run them; expect PASS.** +- [ ] **Step 5: Commit:** `feat(codec): SFM's side of the decode check, from the event bytes alone` + +--- + +### Task 3: The comparison + +**Files:** +- Modify: `minimateplus/decode_check.py` +- Test: `tests/test_decode_check.py` + +**Interfaces:** +- Consumes: `XmlReport` (Task 1), `SfmSide` (Task 2), `Carveout` (Task 4, + passed in; default `()` so this task stands alone). +- Produces: + ```python + VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error") + @dataclass + class FieldResult: + field: str # reference tag, or "notes", "JobNumber", "Channels", + # "samples.", "intervals." + verdict: str + bw: Optional[str] # printed text, or " cells" for a series + sfm: Optional[str] # SFM's value rendered at the printed precision + detail: str = "" # series: "rows=… differing=… row_length_disagreements=… first_diff=… max_abs=…" + carveout: Optional[str] = None + def matches_printed(value: float, printed: str) -> bool + def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult] + ``` + +**Rules** (exact; the tests pin each): + +- **Which fields:** every tag in `ref.scalars` is compared except + `FileVersion` and `FileName`. So a field the XML carries and SFM doesn't is + automatically `sfm_blank`. +- **The reference says `N/A`:** the verdict is `no_reference`. +- **SFM has nothing (`None`):** `sfm_blank`. +- **Numbers:** for a value whose printed text begins with a number + (`-?\d+(\.\d+)?`, units after it ignored), the verdict is `match` when + `matches_printed` holds, else `mismatch`. +- **`>100`:** matches only when SFM's matching `*_zc_above_range` flag is True. +- **`OORANGE`:** a `mismatch` unless a carve-out applies. +- **Text:** anything else is compared exactly after whitespace collapse. +- **`MicLPSPL`:** compared against SFM's `MicLPSPL dB(L)` when `event_units` + contains `dB(L)`, `MicLPSPL psi(L)` when it contains `psi(L)`, otherwise + `sfm_blank`. +- **`notes`:** the list of note values vs `sfm.notes`. **`JobNumber`:** + `ref.job_number` vs `sfm.job_number` (skipped when the reference has none). + **`Channels`:** `ref.channels` vs `sfm.channels`. +- **`samples.`, one result per reference channel:** + - SFM's cells are geophone `count × GEO_IPS_PER_COUNT`; MicL uses + `mic_count_to_db(count)` for `dB(L)` or `count × _MIC_FS_PSI` for + `psi(L)`. + - For row *j*, SFM's running channels are the reference channels (in + order) with `len(sfm.counts[ch]) > j`. Their cells pair up, in order, + with the reference row's cells. + - A row whose cell count differs from SFM's running count is a row-length + disagreement for every channel in it. So are reference rows past SFM's + longest channel. + - A channel is `match` only with no row-length disagreements and every + paired cell `matches_printed`. + - `detail` always carries `rows=`, `differing=`, + `row_length_disagreements=`, `first_diff=` and `max_abs=`. +- **`intervals.`, one row per column title:** + - The peak columns compare like samples: geophone `Peak in/s`, MicL + `Peak psi(L)` and `Peak dB(L)`. + - The `Freq` and `Geo PVS` columns are `sfm_blank` (SFM drops them). + - `intervals.Time` is `sfm_blank`. + +- [ ] **Step 1: Write the failing tests:** + +```python +def test_matches_printed_rounds_half_away(): + assert matches_printed(-0.0625, "-0.063") and matches_printed(0.0015, "0.002") + assert not matches_printed(0.0026, "0.002") + +def test_full_waveform_row_verdicts(): + raw = (FIX / "R352HIUI.F40W").read_bytes() + res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "R352HIUI_F40W_XML.XML"))} + for f in ("SampleRate", "RecordTime", "Pre-triggerLength", "EventDate", "EventTime", + "notes", "samples.Tran", "samples.Vert", "samples.Long"): + assert res[f].verdict == "match", (f, res[f]) + assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference") + assert res["BatteryLevel"].verdict == "sfm_blank" + assert "FileName" not in res + +def test_ragged_rows_match_by_running_channels(): + # Tran/Vert/MicL end 3 samples before Long, in SFM and in Blastware's table alike + raw = (FIX / "T438HGTZ.B30W").read_bytes() + res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML"))} + for ch in ("Tran", "Vert", "Long"): + assert res[f"samples.{ch}"].verdict == "match", res[f"samples.{ch}"] + +def test_an_extra_reference_row_is_a_mismatch_with_detail(): + raw = (FIX / "T1905KDW.5F0W").read_bytes() + ref = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML") + ref.sample_rows.append(["0.000", "0.000", "0.000", "0.000"]) + res = {r.field: r for r in compare(sfm_side(raw), ref)} + assert res["samples.Tran"].verdict == "mismatch" + assert "row_length_disagreements=1" in res["samples.Tran"].detail + +def test_job_number_na_and_above_range(): + raw = (FIX / "T1905KDW.5F0W").read_bytes() + res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML"))} + assert res["JobNumber"].verdict == "sfm_blank" + assert res["TranZCFreq"].verdict == "no_reference" # N/A + assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet + +def test_mic_units_pick_the_conversion(): + raw = (FIX / "T004JTRF.ME0H").read_bytes() # psi(L) + res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML"))} + assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch") + assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank" + raw = (FIX / "R352HFZ7.530H").read_bytes() # no mic + fields = {r.field for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML"))} + assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields) +``` + +- [ ] **Step 2: Run them; expect a FAIL** (no `compare`). +- [ ] **Step 3: Implement `matches_printed` and `compare`**, per the rules. +- [ ] **Step 4: Run them; expect PASS.** If a `match` assertion fails, report + the `FieldResult` and stop. Do not loosen a rule to make it pass. +- [ ] **Step 5: Commit:** `feat(codec): compare SFM's file-only decode with Blastware's XML, field by field` + +--- + +### Task 4: Carve-outs + +**Files:** +- Create: `minimateplus/decode_check_carveouts.py` +- Modify: `minimateplus/decode_check.py` (apply carve-outs in `compare`) +- Test: `tests/test_decode_check.py` + +**Interfaces:** +- Produces: + ```python + @dataclass(frozen=True) + class Carveout: + id: str + fields: tuple[str, ...] # exact names, or prefixes ending in "." ("samples.") + evidence: str # why Blastware is the one that differs, and the source + applies: Callable[[SfmSide, XmlReport, FieldResult], bool] + SATURATION: Carveout + CARVEOUTS: tuple[Carveout, ...] = (SATURATION,) + ``` +- **How `compare` uses them:** a `mismatch` whose field a carve-out covers and + whose `applies` returns True becomes `accepted`, with `carveout=`. +- **`SATURATION`:** + - Covers `TranPPV`, `VertPPV`, `LongPPV`, `PeakVectorSum`, + `samples.Tran/Vert/Long` and the `intervals.* Peak in/s` columns. + - `r = float(ref.scalars["GeoRange"])`. A cell or value Blastware printed as + `OORANGE`, or with `|bw| ≥ r − 0.0006`, is "clamped". + - It applies when every differing cell/value is clamped and SFM's is the + same sign with `r − 0.0006 ≤ |sfm| ≤ r × 1.01`. + - The upper bound keeps an 8× Sensitive-range value a mismatch. + - **`PeakVectorSum`** is a vector sum, so it can exceed the range (11.55 + on `T438HGTZ`). It is accepted when Blastware printed `OORANGE` and at + least one of SFM's three PPVs sits in that ceiling band. + - Evidence text: *"Blastware clamps a clipped channel to the range maximum + and prints OORANGE; the file holds counts past full scale (32016 counts = + 10.005 in/s observed). scratch/verify_against_ascii.py, 2026-08-28."* + +- [ ] **Step 1: Write the failing tests:** + +```python +def test_clipped_normal_range_is_accepted(): + # Blastware: Tran 5.445, Vert 6.310, Long OORANGE, PVS OORANGE; SFM Long 10.005, PVS 11.55 + raw = (FIX / "T438HGTZ.B30W").read_bytes() + res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML"), CARVEOUTS)} + assert res["TranPPV"].verdict == "match" and res["VertPPV"].verdict == "match" + for f in ("LongPPV", "PeakVectorSum"): + assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation") + +def test_sensitive_range_8x_stays_a_mismatch(): + raw = (FIX / "M007HVWF.K30W").read_bytes() + res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML"), CARVEOUTS)} + assert res["TranPPV"].verdict == "mismatch" and res["samples.Tran"].verdict == "mismatch" + +def test_every_carveout_has_evidence(): + assert all(c.id and c.fields and len(c.evidence) > 40 for c in CARVEOUTS) +``` + +- [ ] **Step 2: Run them; expect a FAIL.** +- [ ] **Step 3: Implement the module and the hook in `compare`.** +- [ ] **Step 4: Run all `tests/test_decode_check.py`; expect PASS.** +- [ ] **Step 5: Commit:** `feat(codec): carve-outs for proven Blastware differences -- saturation first` + +--- + +### Task 5: The runner + +**Files:** +- Create: `scratch/check_s3_decode.py` +- Test: `tests/test_check_s3_decode.py` + +**Interfaces:** +- Consumes: `parse_xml_report_file`, `sfm_side`, `compare`, `CARVEOUTS`. +- Produces: + ```python + def find_pairs(bin_dir: Path, xml_dir: Path) -> list[tuple[str, Path, Optional[Path]]] + # (basename, binary, xml or None); Series 3 binaries only (^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$), + # deduped by upper-case basename; xml = __XML.XML in xml_dir + def event_attrs(name: str, ref: XmlReport, raw: bytes) -> dict[str, str] + # grouping keys, all from the reference or the file: + # model ("MiniMate Plus" / "BlastMate III" from Version), serial (SerialNumber), + # type (EventType), year (EventDate or HistogramStartDate), sample_rate, range (GeoRange), + # mic_units (event_units), interval (IntervalSize or "-"), + # 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 + # {"file", "attrs", "results": [[field, verdict, bw, sfm, detail, carveout], ...]} + # no xml -> one ["event","no_reference",…] row; any exception -> one ["event","error",None,None,repr(exc),None] row + def main(argv: Optional[list[str]] = None) -> int + ``` +- **CLI:** `bin_dir xml_dir [--out DIR] [--serial S]... [--year Y]... + [--type W|H] [--field PREFIX]... [--sample N] [--seed K] [--jobs N] + [--file NAME] [--compare-to DIR]`. + - `--field` keeps only result rows whose field starts with a given prefix + (the spec's "field group" partial run). + - `--file` and `--compare-to` are wired in Task 7; here they are only + accepted. + - The spec's "decoder path" grouping key is omitted: the decoder does not + expose it today. +- **Output:** writes `/results.jsonl.gz` (one line per event) and + `/run.json`. + - `run.json` holds the args, the `git rev-parse HEAD`, the event count and + the wall time. + - It prints the run folder. + - Parallelism: `ProcessPoolExecutor(jobs).map(…, chunksize=64)`. + +- [ ] **Step 1: Write the failing tests** (on the fixture folder, which holds + binaries and XMLs together): + +```python +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 = find_pairs(tmp_path, FIX) + assert [p[0] for p in pairs] == ["R352HIUI.F40W"] and pairs[0][2].name == "R352HIUI_F40W_XML.XML" + +def test_check_event_rows_and_attrs(): + out = 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 = 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_cli_writes_results(tmp_path): + assert 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 and json.loads((tmp_path / "run/run.json").read_text())["events"] == 7 +``` + +- [ ] **Step 2: Run them; expect a FAIL.** +- [ ] **Step 3: Implement**, per the Interfaces block. +- [ ] **Step 4: Run them; expect PASS.** +- [ ] **Step 5: Time a sample.** Run `scratch/check_s3_decode.py + ~/dl2-archive/files ~/dl2-archive/xml --sample 2000 --jobs 4`. Expected: a + few minutes. Note the time in the commit body. +- [ ] **Step 6: Commit:** `tooling(scratch): run the decode check over the archive in parallel` + +--- + +### Task 6: The summary and the detailed report + +**Files:** +- Create: `scratch/decode_check_report.py` +- Modify: `scratch/check_s3_decode.py` (write both reports at the end of a run) +- Test: `tests/test_check_s3_decode.py` + +**Interfaces:** +- Produces: + ```python + def aggregate(results_path: Path) -> dict + def write_summary(agg: dict, path: Path) -> None # /summary.md, for Brian + def write_details(agg: dict, path: Path) -> None # /details.json, for Claude + ``` +- **`summary.md`** has four parts: + - a per-field table with one column per verdict (in `VERDICTS` order), + sorted by non-match count + - a line `N of M fields fully matching` + - the non-match counts per event year + - the carve-out counts +- **`details.json`** has one entry per `(field, verdict)` with verdict ≠ + `match`. Each entry holds: + - `total` + - `groups`: for each attribute, the values whose failing count is ≥ 10% of + `total`. Each value carries `{value, failing, compared, rate}`, where + `compared` counts events where the field's verdict was not + `no_reference`. Sorted by `failing` descending; `concentrated: true` when + `rate ≥ 0.95`. + - `examples`: up to 8, taking one per top group value first. Each gives + `{file, bw, sfm, detail, rerun}` with `rerun = "python + scratch/check_s3_decode.py --file "`. + +- [ ] **Step 1: Write the failing tests:** build a small `results.jsonl.gz` by + hand with literal rows: 3 events, one field `SampleRate`, two `mismatch` on + `sample_rate=2048`, one `match` on `1024`. Assert: + - `details.json["SampleRate|mismatch"]["groups"]["sample_rate"]` is + `[{"value": "2048", "failing": 2, "compared": 2, "rate": 1.0, + "concentrated": True}]` + - `summary.md` contains `0 of 1 fields fully matching` + - every example carries a `rerun` with `--file` +- [ ] **Step 2: Run them; expect a FAIL.** +- [ ] **Step 3: Implement**, streaming the results file line by line and + holding only counters plus a capped example list. +- [ ] **Step 4: Run them; expect PASS.** +- [ ] **Step 5: Commit:** `tooling(scratch): decode-check summary and grouped detail report` + +--- + +### Task 7: Run-to-run changes and the single-event view + +**Files:** +- Modify: `scratch/decode_check_report.py`, `scratch/check_s3_decode.py` +- Test: `tests/test_check_s3_decode.py` + +**Interfaces:** +- Produces: + ```python + def compare_runs(prev_results: Path, cur_results: Path) -> dict + # {"fields": {field: {verdict: [before, after]}}, + # "regressions": [{"file", "field", "before", "after"}], # before == "match", after != "match" + # "fixed": int} # before != "match", after == "match" + def write_changes(chg: dict, path: Path) -> None # /changes.md, regressions first + ``` +- **`--compare-to DIR`:** defaults to the newest other folder in the runs + folder. `summary.md` starts with a regressions line (`0 regressions` or the + count plus a pointer to `changes.md`). +- **`--file NAME`:** finds that one event, runs `check_event` and prints a + table `field | verdict | Blastware | SFM | detail` to stdout. No run folder + is written. + +- [ ] **Step 1: Write the failing tests:** + - Two hand-built results files where one `(file, field)` goes from `match` + to `mismatch` and another from `sfm_blank` to `match`: assert one + regression and `fixed == 1`. + - `main([FIX, FIX, "--file", "M007HVWF.K30W"])` prints a line containing + `TranPPV` and `mismatch`, and returns 0. +- [ ] **Step 2: Run them; expect a FAIL.** +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run them; expect PASS.** +- [ ] **Step 5: Commit:** `tooling(scratch): decode-check run-to-run changes and a one-event view` + +--- + +### Task 8: The first full run, checked against what we know + +**Files:** +- Delete: `scratch/verify_bw_fields_against_xml.py` (the checker replaces it) +- Modify: `CLAUDE.md` ("Where things stand": one short bullet with the first + run's headline numbers and the command) +- Modify: `docs/instantel_protocol_reference.md`. Correct the `#53` note in + place, per the retraction convention: the three files pick an earlier, + false footer, get the right sample count and a time 4 s off, and log no + `decode_problems`. ⚠ The file is CRLF, so edit it with the Edit tool, not a + Python text-mode rewrite. + +- [ ] **Step 1: Full run.** `scratch/check_s3_decode.py ~/dl2-archive/files + ~/dl2-archive/xml --jobs 4`. Expected: it finishes in under an hour and + writes `summary.md`, `details.json` and `results.jsonl.gz`. +- [ ] **Step 2: Check the first-run expectations from the spec's "What success + looks like"**, one by one, against `summary.md` and `details.json`: + - `SampleRate`, `RecordTime`, `Pre-triggerLength` and `notes` all `match` + - `samples.*` mismatch only on the range-1.250 events (8×) among 2025–26 + events; `T438HGTZ.B30W` matches + - `EventType` mismatches exactly on the histograms + - `JobNumber` and the calculated fields are `sfm_blank` + - the three `#53` files show as time mismatches + Any other non-match is a finding. Write it into the report's notes for + Brian; **do not change a rule to hide it.** If an expectation fails because + the checker is wrong, fix the checker with a test first. +- [ ] **Step 3: Full suite.** Expected: no new failures beyond the 18 known. +- [ ] **Step 4: Docs, per Files above.** +- [ ] **Step 5: Commit:** `docs: the decode checker's first full run; correct the #53 note` diff --git a/docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md b/docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md index f27d240..a4105a5 100644 --- a/docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md +++ b/docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md @@ -243,8 +243,10 @@ precision is a comparison rule, not a carve-out. - **The first run reproduces what is known**, which is how we tell the checker is honest: - sample rate, record time, pre-trigger and notes match everywhere - - one waveform (`T438HGTZ.B30W`) is 3 samples short on Tran, Vert and - MicL; Long is full length + - `T438HGTZ.B30W` matches. Its Tran, Vert and MicL end 3 samples before + Long, and Blastware's own table does the same: its last rows carry only + the Long cell. An earlier harness that compared one channel's length with + the table's row count called this a decoder truncation; it was not. - samples and histogram intervals match on the 2025–26 events, as `verify_against_ascii.py` showed, **except the events on the 1.250 in/s range**, which are 8× high (5 of them in 2025–26, 35 in all)