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:
commit
342c69602d
54 files changed
+22279
-264
No files matched your search
@@ -12,6 +12,7 @@
|
||||
| Date | Section | Change |
|
||||
|---|---|---|
|
||||
| 2026-10-27 | §3 writes | **⚠ RETRACTS the write-frame model (#46, measured).** Every Blastware request on record re-encodes under the uniform rule (02/03/04/10 escaped, SUM8): 3,869/3,869 frames in the Feb–Apr 2026 captures, plus BE9441's 26 write frames of 2026-10-26. A write's [4:6] is its data LENGTH. Config blocks are their header N + 2 bytes: event index (68) and trigger (82) are written as read plus `02 00` / `00 00` (constant on 15 sends); waveform data (69) and the 2,092-byte compliance image (71) are written whole, the latter in addressed chunks (params[2:4] = address; 1,024 B in March, 512 B with Blastware 10.74). The trailing two bytes are not a CRC and went out stale, so the unit evidently ignores them. "Only BW_CMD doubled", the "DLE-aware checksum", "offset = data[1] + 2" and "chunks 1,027 / 1,055 at offset 0x1004" were these frames read with their escape bytes in. The trigger block is read first (SUB 0x2E, 26 bytes); its byte 5 has been 01 / 03 / 04 by unit and session (meaning unknown). |
|
||||
| 2026-10-26 (5) | §7.8.9 | ✅ **The embedded event record: the instrument's trigger time, inside the 5A stream.** Every Blastware waveform file carries `00 28 05 00 ?? ?? fe 80 [trigger 8 B][stop 8 B]`, times as `dd mm yyyy(BE) 00 hh mm ss`. The trigger equals Blastware's report 1,320/1,320, the filename 7,935/7,935 and the unit's 0C record 10/10. It occurs once in the unit's own A5 payloads (8/8 events) and in SFM-only downloads (2/2): instrument data, not Blastware's. The footer's `ts2 - record time` is only an estimate, a second off on ~19%. Decoder rule, validation and an open case (3 waveform-named files the codec does not recognise) in §7.8.9. 🔶 The §7.5 `0C` "sub_code" timestamp variants look like the same 8-byte form read with its escapes. |
|
||||
| 2026-10-26 (4) | §3, §10 | **Replies follow the request rule; a write-frame suspicion (inferred).** Measured on all 748 reply frames of the 10-26 recording: the unit escapes exactly 02/03/04/10 with a `10`, and the checksum is **SUM8 of the unescaped payload**, 748/748. The long-held "S3 response checksums frequently fail SUM8" (`protocol._validate_frame`) is `S3FrameParser`'s own doing: it keeps the `10` of `10 02/03/04` in its output (consumers rely on that) and sums it, so 502/540 A5 replies read invalid. 🔶 **Inferred only:** `build_bw_write_frame`'s model ("raw except BW_CMD", "DLE-aware checksum") shows the same fingerprints as the retracted 5A model -- SUB 71's "offset 0x1004" reads as length 0x0400 escaped, and Blastware escapes `03` in write data (§3 note, 2026-04-20). A write whose payload holds a bare 02/03/04/10 may be malformed; one Blastware config-write capture settles it. Not acted on. |
|
||||
| 2026-10-26 (3) | §3, §7.8, §10 | **⚠ RETRACTS the 5A "non-standard frame" model; the 64 KB page bug is FIXED (measured).** A bridge recorded Blastware downloading all 8 of BE9441's events, 4 crossing a 64 KB page (`tests/fixtures/minimate-bench-10-26-26-blastware/`). **Every request** is the standard 16-byte payload with a SUM8 checksum and **every 02, 03, 04 and 10 DLE-escaped**, payload and checksum alike: 748/748 re-encode byte-identically. §10's "only 0x10 is stuffed" is half the rule. **A 5A request is an ordinary request** `[10 00 5A 00][length BE 2][address BE 4][zeros 6]`, where length is 0x0200 per chunk and the remainder for TERM. The walk: the event's start address, +0x200 at a time as plain 32-bit addresses (carrying into the page byte), then TERM at the next boundary for exactly the remainder, ending at STRT's full 32-bit end key. **Misreadings retracted:** the fixed "offset 0x1002" is length 0x0200 escaped (`10 02 00`); the "metadata pages at 0x1002 / 0x1004, global, read once per session" are the first event's own chunks at 0x0200 and 0x0400; the "11-byte params" counted the length's low byte; the "partial DLE stuffing" carve-outs were the escape rule seen half; the 16-bit counter is why a walk could not leave its page. **Verified live on BE9441:** all 8 events downloaded whole, the 4 crossings included, each matching the unit's own 0C peaks. Code `887e75d`. |
|
||||
| 2026-10-26 (2) | §7.8 | **The 64 KB page bug, narrowed (measured, BE9441).** Blastware's own downloads of all 20 events (Brian, `example-events/10-25-26 - thumps`) give byte-exact ground truth. SFM's downloads of events 0, 1, 3, 4 and 10 are **byte-identical** to Blastware's. Importing Blastware's files first (the watcher route) makes SFM's downloads of the same events return `already_stored`: the unit's 0C and Blastware's file agree on (serial, timestamp). For an event that crosses a page (event 2, `0111c92c` → STRT end key `01122f06`, full 32 bits) a read-only test walk with the page byte carried (params `00 01 12 01 2c`) got a proper A5 reply for the first chunk in page 0x12, echoing `01 12 01 2c`. The second chunk, `00 01 12 03 2c`, got no reply frame: a raw 0x03 (ETX) inside the params. Page 0x11 never shows this, because event 1 skips 0x0000–0x05FF, so no counter there has a 02/03/04 byte. Every later page does. ⚠ How Blastware encodes a lone 02/03/04 inside params is unknown: §7.8 says `10 02/03/04` is kept as a literal pair, which would shift the address. A wire capture of Blastware downloading BE9441 event 2 or 19 settles it. Blastware's files are fixtures (`tests/fixtures/minimate-bench-10-25-26/blastware/`). |
|
||||
@@ -2248,6 +2249,82 @@ bulk stream protocol from §7.8.5. Use the `0x46` keys, not the `0x2C` keys, as
|
||||
|
||||
---
|
||||
|
||||
#### 7.8.9 The embedded event record — the instrument's trigger time, inside the 5A stream ✅ 2026-10-26
|
||||
|
||||
Every Blastware waveform file carries a copy of the instrument's **event record**, and it
|
||||
holds the event's **trigger time to the second**. It is the instrument's data, not
|
||||
Blastware's: it arrives in the unit's own 5A stream (provenance below). Found by reading a
|
||||
dump in `seismo_lab.py`'s Inspector, where it sits in the trailing region the Inspector
|
||||
labels "unknown", after the notes and channel blocks.
|
||||
|
||||
**Layout** — offsets relative to `M`, the position of the marker:
|
||||
|
||||
| bytes | content | measured on 7,935 waveforms (DL2 archive 6,541 + prod store 1,394) |
|
||||
|---|---|---|
|
||||
| `[M-6:M-2]` | `00 28 05 00` | constant, 7,935/7,935 ✅ (meaning ❓) |
|
||||
| `[M-2:M]` | 2 bytes | vary; not decoded ❓ |
|
||||
| `[M:M+2]` | `fe 80` — marker | 7,935/7,935 ✅. Histogram files carry `fe f5` here instead (#51) |
|
||||
| `[M+2:M+10]` | **trigger** — `dd mm yyyy(BE) 00 hh mm ss` | = Blastware's report Event Time 1,320/1,320; = the filename's time 7,935/7,935; = the unit's `0C` record 10/10 ✅ |
|
||||
| `[M+10:M+18]` | **stop**, same format | = the footer's `ts2` on 7,836; one second before it on 99 ✅ |
|
||||
| `[M+18:M+40]` | `[+18]` `00` (7,933/7,935), `[+22:24]` `00 00`, `[+26:34]` eight `00`, `[+36]` `00`, `[+37:39]` `16 32`, `[+39]` `00` | constant; meaning ❓ |
|
||||
|
||||
**Relations** (7,935/7,935): footer `ts1` (session start) ≤ trigger ≤ stop; and
|
||||
`(stop - trigger) - record time` lies in −3 … +6 s.
|
||||
|
||||
**Ambiguity:** 30 files hold a second `fe 80`; it never passes the checks below, and every
|
||||
file has exactly one candidate that does.
|
||||
|
||||
**Provenance** (where it comes from — measured):
|
||||
- **Blastware's download of 8 BE9441 events** (2026-10-26 recording,
|
||||
`tests/fixtures/minimate-bench-10-26-26-blastware/`). Each event's 18-byte record, with
|
||||
the 24 bytes before it and the 22 after, occurs **exactly once in the unit's own A5 reply
|
||||
payloads**. Its trigger equals the unit's separate `0C` (SUB F3) record 8/8: F3 data
|
||||
`[11:19]` is the same `dd mm yyyy 00 hh mm ss` form.
|
||||
- **SFM's own downloads of BE9441 events 0 and 1** (2026-10-25, no Blastware anywhere). The
|
||||
record is present, and its trigger = the `0C` record, 2/2.
|
||||
- So it is instrument-transmitted. An event SFM receives directly carries it, with no
|
||||
Blastware name involved.
|
||||
|
||||
**What it replaces.** The footer alone gives only an estimate. `ts2` is the stop to the
|
||||
second (its byte `[4]` is `00` in all 1,330 report-paired files, so it holds no fraction),
|
||||
and `ts2 - record time` is exact on 1,113/1,330 report-paired waveforms and a second late
|
||||
on 217. On prod's 1,394 it is a second off on 260: 199 late, 61 early.
|
||||
|
||||
**Decoder** (`event_file_io._embedded_event_record`).
|
||||
- **What qualifies.** A candidate counts only when it has the lead bytes, the marker, two
|
||||
well-formed times (zero byte zero), `ts1 ≤ trigger ≤ stop`, a stop equal to `ts2` or one
|
||||
second before it, and a length that agrees with the record time.
|
||||
- **One answer or none.** Exactly one candidate must qualify. With none, or more than one,
|
||||
the event keeps the footer estimate and carries a `decode_problems` entry; nothing is
|
||||
guessed.
|
||||
- **Names and reports are cross-checks only.** A Blastware filename is never a time source:
|
||||
a disagreement is logged and the record kept. A paired report's time fills in only when
|
||||
there is no validated record.
|
||||
- Decoded from raw bytes with no name: every waveform the codec recognises takes the
|
||||
record's time, 7,961/7,961 (DL2 6,538, prod 1,394, bench 29), with 0 disagreements
|
||||
against the filename or a report. The 3 it does not recognise are the open case below.
|
||||
|
||||
🔶 **For the decoder audit (#53), inferred only.** The `0C` timestamp layouts documented in §7.5
|
||||
look like this same 8-byte form, read without its escapes:
|
||||
- the "sub_code 0x10" 9-byte form;
|
||||
- the 10-byte "continuous mode" form, whose own example `10 03 10 04 07 ea 00 0f 14 11` reads
|
||||
as day 3, month 4, escaped, at 15:20:17.
|
||||
|
||||
The early captures were all in April (month `04`, sent as `10 04`). Not changed here.
|
||||
|
||||
⚠ **Open:** 3 DL2 files named as waveforms (`K440I4LG.JK0W`, `K888HW07.7K0W`,
|
||||
`R349KPNU.FK0W`) carry a valid record, but their body is not recognised by the waveform
|
||||
codec. They are decoded as histograms and stamped with the footer start, 4 s off; `dev`
|
||||
behaves the same. Prod's store has none. Tracked in #53.
|
||||
|
||||
⚠ **Corrected 2026-10-29 (measured against their Blastware `_XML.XML` reports):** they
|
||||
do **not** decode as histograms. All three decode as waveforms with Blastware's full
|
||||
sample count (4,352 / 4,352 / 13,280 rows), and their record time and sample rate are
|
||||
read. Only the time is wrong: no footer stop time (`ts2`) is read, so the decoder falls
|
||||
back to the footer start -- 11:14:12 / 11:14:12 / 16:14:11 against Blastware's
|
||||
11:14:08 / 11:14:08 / 16:14:08 -- and records no `decode_problems` entry. 🔶 Inferred,
|
||||
from the decode-checker design review: the decoder takes an earlier, false footer.
|
||||
|
||||
## 7.9 Compliance Config Field Inventory (Blastware UI, 2026-04-08) ✅
|
||||
|
||||
Fields visible in the Blastware "Compliance Setup" dialog. ✅ = byte offset confirmed in code. ❓ = not yet located in raw bytes.
|
||||
|
||||
@@ -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/<YYYYmmdd-HHMMSS>/`; 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 `<stem>_<ext>_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
|
||||
# <Tag><Value>v</Value><Units>u</Units></Tag> -> v
|
||||
units: dict[str, str] # tag -> the nested <Units> text
|
||||
event_units: Optional[str] # top-level <Units>, e.g. "in/s and dB(L)"
|
||||
channels: list[str] # <Channels>/<Channel> in order
|
||||
job_number: Optional[str]
|
||||
notes: list[tuple[str, str]] # (tag, value), non-empty, in order, between
|
||||
# top-level </Units> and <GeoRange>, 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 `<Value>` 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.<ch>", "intervals.<column title>"
|
||||
verdict: str
|
||||
bw: Optional[str] # printed text, or "<n> 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.<ch>`, 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.<column>`, 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=<id>`.
|
||||
- **`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 = <stem>_<ext>_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 `<out>/results.jsonl.gz` (one line per event) and
|
||||
`<out>/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 # <out>/summary.md, for Brian
|
||||
def write_details(agg: dict, path: Path) -> None # <out>/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 <bin_dir> <xml_dir> --file <name>"`.
|
||||
|
||||
- [ ] **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 # <out>/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`
|
||||
@@ -0,0 +1,268 @@
|
||||
# Series 3 decode checker — design
|
||||
|
||||
**Date:** 2026-10-29 · **Branch:** `feat/s3-decode-checker` · **Status:** design
|
||||
|
||||
## Why this exists
|
||||
|
||||
SFM is meant to replace Blastware. Today, when a Series 3 event arrives with
|
||||
Blastware's ASCII report, SFM takes many of its values from the report: ZC
|
||||
frequency, acceleration, the sensor check and so on. Two of the four ways
|
||||
events will reach SFM, its own serial/modem download and its future call-in
|
||||
server, never have a report. So SFM must produce **everything Blastware
|
||||
reports, from the event file alone**, and we need proof that it does.
|
||||
|
||||
The checker is that proof, and the to-do list for getting there. It decodes
|
||||
each event file the way SFM ingest does, with no report, and compares every
|
||||
field with Blastware's own report of the same event. Then it says what
|
||||
matches, what doesn't, and what SFM can't produce yet.
|
||||
|
||||
It is the first of four pieces, agreed with Brian on 2026-10-29:
|
||||
|
||||
1. **This checker.**
|
||||
2. Completing SFM's file-only decode, one field group at a time, each slice
|
||||
done when the checker shows it matching. Slice 1, the setup fields and
|
||||
notes (#44/#45), merged to dev as `42fe35f`.
|
||||
3. Flipping ingest to file-only. Reports are kept for checking only. This
|
||||
happens only when piece 2 leaves no blanks and the checker proves it.
|
||||
Prod keeps its current behaviour until then.
|
||||
4. The watcher: it forwards the XML report while we verify, then stops
|
||||
forwarding reports.
|
||||
|
||||
## The reference: Blastware's XML event reports
|
||||
|
||||
Every Blastware ACH machine keeps, in `Sent/`, a full XML event report for each
|
||||
event: `<stem>_<ext>_XML.XML` next to the binary `<stem>.<ext>`. DL2's backup
|
||||
holds **70,042 of them for Series 3 events, from 2016 to 2026**. Its ASCII
|
||||
reports, by contrast, cover only 2025–26.
|
||||
|
||||
Local copies on the dev box (`tmi-dev`, 10.0.0.44):
|
||||
|
||||
| what | where | count |
|
||||
|---|---|---|
|
||||
| event binaries (Series 3) | `~/dl2-archive/files/` (root + `Sent/` mirror, dedupe by basename) | 70,112 distinct |
|
||||
| XML reports | `~/dl2-archive/xml/` (flat) | 75,958 = 70,042 Series 3 + 5,916 Micromate (`UM…_IDF?_XML.XML`) |
|
||||
| ASCII reports | `~/dl2-archive/files/` | 14,338 (2025–26 only) |
|
||||
|
||||
What the Series 3 XML contains (surveyed across all 75,958 on 2026-10-29):
|
||||
|
||||
- **Identity:** `EventType` (`Full Waveform` 6,524, `Full Histogram`
|
||||
63,518), `SerialNumber`, `Version` (`V 10.72-8.17 MiniMate Plus` or
|
||||
`… BlastMate III`), `FileName`.
|
||||
- **Time:** waveform `EventDate`/`EventTime`; histogram
|
||||
`HistogramStart*`/`HistogramStop*`.
|
||||
- **Setup:** `Channels`, `Trigger`, `GeoTriggerLevel`, `MicTriggerLevel`,
|
||||
`Pre-triggerLength`, `RecordTime`, `RecordStopMode` (only `Fixed` occurs),
|
||||
`SampleRate`, `IntervalSize` (2 s / 5 s / 15 s / 1 min / 5 min),
|
||||
`NumberofIntervals`, `GeoRange` (10.000: 75,923; 1.250: 35), `Units` (`in/s
|
||||
and dB(L)` / `psi(L)` / `dB(A)` / `in/s`), `Microphone` (weighting).
|
||||
- **Unit:** `BatteryLevel`, `Calibration` (date + by whom), `MicCalibration`.
|
||||
- **Notes:** `JobNumber`, then up to four user notes. Each is tagged with its
|
||||
operator-editable label (`Project`, `Location`, `Seis.Loc`, `SeisLocation`,
|
||||
`SeismographLoc`, `Company`, `General`, …), and empty notes are omitted.
|
||||
They sit between the top-level `</Units>` and `<GeoRange>`.
|
||||
- **Results:** per channel `PPV`, `ZCFreq`, `TimeofPeak`, `PeakAcceleration`,
|
||||
`PeakDisplacement` (waveform) or `PeakDate`/`PeakTime` (histogram);
|
||||
`PeakVectorSum` with its time; mic `PSPL`, time, `ZCFreq` (dB(A)
|
||||
histograms carry `MicA*` fields instead).
|
||||
- **Sensor check:** per geophone `TestFreq`, `TestRatio`, `TestResults`; mic
|
||||
`TestFreq`, `TestAmplitude`, `TestResults`.
|
||||
- **`MonitorLog`:** the session's start, stop and status text.
|
||||
- **Data:** waveform `WaveformDataChannels/Data/Row/Cell` (4 cells per
|
||||
sample: Tran, Vert, Long in in/s, MicL in the event's mic units); histogram
|
||||
`HistogramDataIntervals` (a `Time` and a 10-cell `Row` per interval:
|
||||
Tran/Vert/Long peak + freq, geo PVS, MicL psi, dB and freq).
|
||||
|
||||
Value forms the parser must handle: numbers with units in the text (`6.7
|
||||
Volts`, `7.6 Hz.`, `3.0 sec.`, `-0.250 sec`); `>100` (ZC frequency above
|
||||
range; 71,823 files), `N/A` (37,293 files), `OORANGE` (59 files: the channel
|
||||
clipped), `Check` (2,193 files), and XML entities. Two `_XML.XML` details
|
||||
matter:
|
||||
|
||||
- Blastware prints each number to a fixed number of decimals and **rounds
|
||||
halves away from zero** (−0.0625 s prints as −0.063).
|
||||
- The small `<stem>_<ext>.XML` summary next to it uses **decimal commas**.
|
||||
It is not the reference; the `_XML.XML` is.
|
||||
|
||||
## Goals
|
||||
|
||||
- For every Series 3 event file with an XML report, compare **every field the
|
||||
XML carries**, plus every waveform sample and every histogram interval,
|
||||
against SFM's file-only decode.
|
||||
- Give each comparison one verdict: **match**, **mismatch**, **SFM blank**
|
||||
(SFM produced nothing), **accepted difference** (covered by a written
|
||||
carve-out), **no reference** (the XML lacks the field), or **error** (the
|
||||
decode or parse failed).
|
||||
- Produce two outputs:
|
||||
- **A short summary for Brian:** per field, the counts of each verdict and
|
||||
how far we are from done.
|
||||
- **A detailed report for Claude** that groups failures by what the failing
|
||||
events share, so 17,000 mismatches read as "one bug on 2048 sps
|
||||
histograms". It gives example files with Blastware's value and SFM's, and
|
||||
a one-line command to re-run a single event.
|
||||
- **Run again and again.** Each run is compared with the previous one, so a
|
||||
fix shows as numbers moving, and anything that used to match and stops is
|
||||
called out.
|
||||
- Keep the comparison as library code, so ingest can later run it on one
|
||||
event as it arrives (piece 3/4).
|
||||
|
||||
## What counts as "SFM's side"
|
||||
|
||||
The SFM side is **what SFM produces from the event's bytes alone**:
|
||||
|
||||
- **The `Event` that `decode_blastware_bytes` returns when given the bytes and
|
||||
no filename.**
|
||||
- SFM's own download and call-in paths never have a Blastware name.
|
||||
- Today the event type comes only from the filename's extension, so every
|
||||
histogram decodes as "Waveform". The checker reports that as it is: a
|
||||
mismatch until the decoder reads the type from the file (#41). It must
|
||||
not borrow the name to make it match.
|
||||
- **Anything else SFM reads from those bytes outside the decoder**, such as the
|
||||
serial.
|
||||
- Ingest's `sfm/waveform_store._serial_from_bw_bytes` uses the filename to
|
||||
validate what it finds.
|
||||
- Whatever SFM can't get from the bytes alone is "SFM blank".
|
||||
- **Values the codec computes but never puts on the `Event`** count as SFM
|
||||
blank until they are wired through (piece 2). For example, histogram
|
||||
half-periods in `histogram_codec.decode_histogram_body_full` give the
|
||||
per-interval frequency.
|
||||
- **SFM's assumptions included.**
|
||||
- SFM cannot yet read the geophone range from the file, and assumes Normal
|
||||
(10 in/s): `_peaks_from_samples` does, and ingest writes `.h5` with
|
||||
`geo_range="normal"`.
|
||||
- The checker compares what SFM actually produces under that assumption.
|
||||
The range field itself is SFM blank.
|
||||
- So the 35 events recorded on the 1.250 in/s range show as 8× mismatches,
|
||||
not blanks. Example: `T438L713.QP0W` gives PPV 0.015/0.02/0.015 against
|
||||
Blastware's 0.002.
|
||||
- The range is never taken from the reference.
|
||||
|
||||
So the comparison takes an SFM-side record plus the parsed reference. The
|
||||
runner assembles that record from the decoder and any SFM helpers. The
|
||||
comparison itself stays pure codec-library code; only the runner (a lab tool)
|
||||
may import from `sfm/`.
|
||||
|
||||
## The rule for disagreements (decided by Brian)
|
||||
|
||||
**Every mismatch is an SFM bug until shown otherwise.** A mismatch becomes an
|
||||
"accepted difference" only through a written carve-out that names the fields
|
||||
it covers and the rule it applies. Its evidence must not rest on SFM's own
|
||||
output: Blastware contradicting itself, the instrument's own data (counts
|
||||
in the file, the unit's embedded record), a third source (another instrument,
|
||||
a known signal), or Instantel documentation. Each run reports how many events
|
||||
each carve-out covers.
|
||||
|
||||
The carve-out list starts with one entry, already proven in
|
||||
`scratch/verify_against_ascii.py`: **saturation**. On a clipped channel,
|
||||
Blastware clamps its numbers to the range maximum and writes `OORANGE`, while
|
||||
the file holds counts past full scale. Rounding to Blastware's printed
|
||||
precision is a comparison rule, not a carve-out.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- **Series 4 / Micromate.** Thor's IDF decode has its own CSV-based check, and
|
||||
the 5,916 Micromate XMLs are noted for a later Series 4 checker.
|
||||
- **Changing what SFM decodes.** The checker reports gaps; filling them is
|
||||
piece 2.
|
||||
- **Wiring the check into ingest, the watcher or Terra-View.** That's pieces
|
||||
3/4. Nothing on prod changes.
|
||||
- **ASCII reports as a reference.** The XML covers every year, including the
|
||||
2025–26 events that have ASCII. The reference is parsed into a shape another
|
||||
report format could fill later, but no ASCII adapter is built now.
|
||||
|
||||
## Anti-goals (would make it a failure even if it runs)
|
||||
|
||||
- **Comparing SFM with Blastware's own numbers.** The SFM side must come only
|
||||
from the event file, through `decode_blastware_bytes` with no report
|
||||
overlay. Nothing from the XML or ASCII report may reach the SFM side.
|
||||
- **Hiding mismatches:** a carve-out without evidence, a tolerance looser
|
||||
than Blastware's printed precision, or blanks counted as matches.
|
||||
- **Wrong conversions:** counts converted to in/s with a range or scale that
|
||||
came from the reference rather than the file. If SFM can't read the range
|
||||
from the file yet, that is a gap to report, not something to borrow.
|
||||
- **A report that only says "N mismatches"** without grouping and examples.
|
||||
It must be usable to find the cause.
|
||||
- **A full run so slow it isn't run after every fix.**
|
||||
|
||||
## Constraints
|
||||
|
||||
- **Hardware:** runs on the dev box (4 cores, ~17 GB free disk after the
|
||||
22 GB XML copy; Brian can add space).
|
||||
- **Read-only:** it never writes to the corpus folders and needs no network.
|
||||
- **Speed:** a full run over all 70,042 events in **under an hour**. A
|
||||
partial run (by serial, year, event type or field group, or a random sample)
|
||||
in **a few minutes**. The setup/notes harness covering ~6 fields took ~4
|
||||
minutes with 4 processes. Samples and intervals add parsing 22 GB of XML.
|
||||
The standard library parses at ~45 MB/s per core (`lxml` is not
|
||||
installed), which fits the budget.
|
||||
- **Codec library purity (ADR 0003):** the codec library stays pure. Bench and
|
||||
lab tools stay out of the production image.
|
||||
- **Results contain customer project names**, so run output is kept outside
|
||||
the repo and never committed.
|
||||
|
||||
## What's decided, and by whom
|
||||
|
||||
**Brian:**
|
||||
- SFM's data comes only from the binary; reports are for checking.
|
||||
- The disagreement rule and carve-outs above.
|
||||
- The two outputs: a summary for him, a detailed report for Claude to diagnose.
|
||||
- Repeated runs with run-to-run comparison.
|
||||
- It lives in seismo-relay, and the comparison is library code.
|
||||
- Series 3 only. Nothing on prod or in Terra-View changes.
|
||||
|
||||
**Claude's calls (correct if wrong):**
|
||||
- The XML is the single reference.
|
||||
- **Placement:**
|
||||
- The XML report parser belongs in the codec library, a sibling of
|
||||
`minimateplus/bw_ascii_report.py`.
|
||||
- The comparison (one decoded `Event` + one parsed report → verdicts per
|
||||
field) is pure and belongs in the codec library too.
|
||||
- The batch runner is a lab tool (`scratch/`), per ADR 0003.
|
||||
- The carve-out list lives in the repo next to the comparison, as code or
|
||||
data the comparison reads, with each entry's evidence written beside it.
|
||||
- **Grouping attributes for the detailed report:**
|
||||
- device model (from `Version`), serial
|
||||
- event type, event year
|
||||
- sample rate, geophone range, mic units/weighting, interval size
|
||||
- whether the setup is named "Standard Recording Setup"
|
||||
- which decoder path produced the samples, where the decoder exposes it
|
||||
- `scratch/verify_bw_fields_against_xml.py` (committed `f46afaf`) is the
|
||||
starting point. It already handles the notes/job-number layout and the
|
||||
rounding rule. The checker replaces it.
|
||||
|
||||
**Left to the builder:**
|
||||
- module, function and file names; the output file formats
|
||||
- how runs are stored and compared
|
||||
- parallelism and any caching of decode or parse results
|
||||
- the CLI shape, as long as the partial-run filters and single-event re-run
|
||||
exist
|
||||
|
||||
## What success looks like
|
||||
|
||||
- **One command** produces the summary and the detailed report for all 70,042
|
||||
events within the time budget.
|
||||
- **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
|
||||
- `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)
|
||||
- event type mismatches on every histogram, because no filename is given
|
||||
(#41)
|
||||
- job number and the calculated values (ZC frequency, acceleration,
|
||||
displacement, time of peak, sensor check, battery, calibration, trigger
|
||||
levels, range, units, monitor log) show up as SFM blank
|
||||
- the three `#53` files fail loudly as waveform time mismatches, 4 s off.
|
||||
The decoder picks an earlier, false footer and records no
|
||||
`decode_problems`. The `#53` description in
|
||||
`docs/instantel_protocol_reference.md`, which says they decode as
|
||||
histograms, is out of date.
|
||||
- Every non-match group in the detailed report carries example files and a
|
||||
re-run command.
|
||||
- Tests cover the XML parser on real fixture reports with literal expected
|
||||
values, every comparison rule (rounding, `>100`, `N/A`, `OORANGE`,
|
||||
units), carve-out accounting, and a guard that the SFM side never sees the
|
||||
reference.
|
||||
Reference in new issue
Block a user