From 9492e4940004ef3f6dfd126faf69247fe9b9125d Mon Sep 17 00:00:00 2001 From: serversdown Date: Thu, 29 Oct 2026 23:27:44 -0400 Subject: [PATCH] fix(sfm): store a MiniMate download through the Blastware-file import path, as production does (#8) A live Series-3 download was stored from the live 5A decode (store.save): a histogram got no samples and nothing to plot (bench 2026-10-29). The download now carries the assembled Blastware file (DownloadedEvent.bw_bytes, built by the new blastware_file_bytes -- byte-identical to Blastware's own K441LTON.900 and K441LTOK.R10), and persist_download stores it through save_imported_bw, the path the watcher uses for Blastware's files, the way Series 4 already uses save_imported_idf. The event is decoded from the file: histogram samples, setup-block sample rate and record time (#44/#45). source.kind is 'sfm-live'. The file path does not yet read three things right (measured on BE9441): a histogram's vector sum (0.503 where Blastware and the unit say 0.385 -- the decode checker's open finding), the mic peak (0), and a sensitive range. So the unit's own 0C channel peaks, mic and vector sum are overlaid, as Series 4 does, except an impossible vector sum (below the largest channel; BE9441's 0C read -0.0, bench #4), and the unit's range is passed through for the stored samples. Store consequence: new live MiniMate downloads only; existing rows and files are untouched; no backfill, no migration. The record type still reads 'Waveform' for a live histogram until #41 (record type from STRT[18]) lands from the decode checker's branch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- minimateplus/blastware_file.py | 24 ++--- sfm/device_access/models.py | 1 + sfm/device_access/s3.py | 9 +- sfm/event_ingest.py | 44 +++++++-- sfm/waveform_store.py | 8 +- tests/test_5a_blastware_walk_histogram.py | 13 ++- tests/test_device_access_s3_events.py | 3 + tests/test_event_ingest.py | 110 ++++++++++++++++++++-- 8 files changed, 180 insertions(+), 32 deletions(-) diff --git a/minimateplus/blastware_file.py b/minimateplus/blastware_file.py index e57342d..12e269c 100644 --- a/minimateplus/blastware_file.py +++ b/minimateplus/blastware_file.py @@ -702,8 +702,18 @@ def write_blastware_file( a5_frames: list[S3Frame], path: Union[str, Path], ) -> None: + """Write `blastware_file_bytes(event, a5_frames)` to `path`.""" + Path(path).write_bytes(blastware_file_bytes(event, a5_frames)) + + +def blastware_file_bytes( + event: Event, + a5_frames: list[S3Frame], +) -> bytes: """ - Write a Blastware waveform file from a downloaded event. + The Blastware waveform file for a downloaded event, as bytes -- what + write_blastware_file writes, and what a live SFM download stores through the + file-import path (sfm.event_ingest). Args: event: Event object (populated by get_events() or download_waveform()). @@ -712,23 +722,18 @@ def write_blastware_file( (page_key=0x0000). Pass include_terminator=True to read_bulk_waveform_stream() when collecting frames. Must have at least 2 frames (probe + terminator). - path: Destination file path. Parent directory must exist. - Extension should be set via blastware_filename(). File layout: [22B header] [21B STRT] [body bytes] [26B footer] Raises: ValueError: if a5_frames is empty or has no terminator (page_key=0). - OSError: if the file cannot be written. Confirmed correct waveform body reconstruction against M529LIY6 (example event) (2026-04-21). """ if not a5_frames: raise ValueError("a5_frames must not be empty") - path = Path(path) - # ── Extract STRT record from probe frame ──────────────────────────────── # The STRT record (21 bytes) lives verbatim inside A5[0].data[7:]. # It is stored as-is in the waveform file — do NOT reconstruct it from Event @@ -923,12 +928,7 @@ def write_blastware_file( + b"\x00\x00" ) - # ── Write file ─────────────────────────────────────────────────────────── - with open(path, "wb") as f: - f.write(header) - f.write(strt) - f.write(body) - f.write(footer) + return header + strt + body + footer def read_blastware_file(path: Union[str, Path]) -> Event: diff --git a/sfm/device_access/models.py b/sfm/device_access/models.py index 2d8534c..15b1c73 100644 --- a/sfm/device_access/models.py +++ b/sfm/device_access/models.py @@ -126,6 +126,7 @@ class DownloadedEvent: filename: str verified: Optional[bool] idf_bytes: Optional[bytes] = field(default=None, repr=False) + bw_bytes: Optional[bytes] = field(default=None, repr=False) # Series 3: the assembled Blastware file event: Any = field(default=None, repr=False) a5_frames: Optional[list] = field(default=None, repr=False) compliance: Any = field(default=None, repr=False) diff --git a/sfm/device_access/s3.py b/sfm/device_access/s3.py index fad91fb..8d5779b 100644 --- a/sfm/device_access/s3.py +++ b/sfm/device_access/s3.py @@ -8,7 +8,7 @@ import struct from typing import Any, Callable, Optional from minimateplus import MiniMateClient -from minimateplus.blastware_file import blastware_filename +from minimateplus.blastware_file import blastware_file_bytes, blastware_filename from minimateplus.event_file_io import _GEO_INT16_FS from minimateplus.framing import build_bw_write_frame from minimateplus.protocol import SUB_START_MONITORING, SUB_STOP_MONITORING @@ -398,9 +398,16 @@ class Series3Adapter: if filename is None: raise MalformedReply(f"event {key.hex()} has no usable timestamp, so it cannot be named or stored") verified, why = verify_s3_download(ev, info.compliance_config) + try: + bw_bytes = blastware_file_bytes(ev, ev._a5_frames) + except ValueError as exc: + raise MalformedReply( + f"event {key.hex()}: its Blastware file could not be assembled ({exc}); not saved" + ) from exc return DownloadedEvent( event_id=make_event_id(serial, key, found), serial=serial, series=3, filename=filename, verified=verified, event=ev, a5_frames=ev._a5_frames, + bw_bytes=bw_bytes, compliance=info.compliance_config, timestamp=_s3_dt(ev), detail={"a5_frames": len(ev._a5_frames), "check": why}, ) diff --git a/sfm/event_ingest.py b/sfm/event_ingest.py index 5cd2673..c8dbb18 100644 --- a/sfm/event_ingest.py +++ b/sfm/event_ingest.py @@ -66,6 +66,33 @@ def _already_stored(dl: DownloadedEvent, row: dict) -> EventDownload: ) +def _overlay_s3_record(ev: Any, unit_peaks: Any) -> None: + """The unit's own 0C peaks, mic and vector sum over the file's. + + Measured 2026-10-29 on BE9441: the file path reads the channel peaks right but + a histogram's vector sum as 0.503 where Blastware and the unit say 0.385 (the + decode checker's open finding), the mic as 0, and it cannot scale a sensitive + range. The unit's values are the accurate ones until the file decoder reads + them. A vector sum below the largest channel peak is impossible -- BE9441's + 0C read -0.0 for some events (bench finding #4) -- so it is not kept. + """ + from minimateplus.models import PeakValues + + if unit_peaks is None: + return + if ev.peak_values is None: + ev.peak_values = PeakValues() + pv = ev.peak_values + for name in ("tran", "vert", "long", "micl"): + value = getattr(unit_peaks, name, None) + if value is not None: + setattr(pv, name, value) + pvs = getattr(unit_peaks, "peak_vector_sum", None) + largest = max((getattr(unit_peaks, n, None) or 0.0) for n in ("tran", "vert", "long")) + if pvs is not None and pvs > 0 and pvs >= largest - 0.005: + pv.peak_vector_sum = pvs + + def _overlay_s4_record(ev: Any, record: dict) -> None: """Fill, where the file left them empty, what the unit's 0x0C said. @@ -103,13 +130,18 @@ def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownlo _overlay_s4_record(ev, dl.record) family = "series4" else: - ev = dl.event - if ev is None: - raise IngestError(f"{dl.filename}: the download carried no event; nothing was stored") - backfill_series3_event(ev, dl.compliance) + # The same path production's watcher uses for Blastware's own files: the + # event is decoded from the file (samples, histogram, setup-block sample + # rate and record time), not from the live 5A decode. The unit's 0C peaks + # stay what they were -- the download *check* (verify_s3_download). + if not dl.bw_bytes: + raise IngestError(f"{dl.filename}: the download carried no event file; nothing was stored") geo_range = getattr(dl.compliance, "geo_range", None) if dl.compliance else None - rec = store.save(ev, serial=dl.serial, a5_frames=dl.a5_frames, - geo_range=geo_range if geo_range is not None else "normal") + ev, rec = store.save_imported_bw(dl.bw_bytes, source_path=Path(dl.filename), + serial_hint=dl.serial, source_kind="sfm-live", + geo_range=geo_range if geo_range is not None else "normal") + if ev is not None and dl.event is not None: + _overlay_s3_record(ev, getattr(dl.event, "peak_values", None)) family = "series3" if ev is None or ev._waveform_key is None: raise IngestError(f"{dl.filename}: stored the file but could not build a database row") diff --git a/sfm/waveform_store.py b/sfm/waveform_store.py index aa053fc..031065c 100644 --- a/sfm/waveform_store.py +++ b/sfm/waveform_store.py @@ -296,6 +296,8 @@ class WaveformStore: *, serial_hint: Optional[str] = None, bw_report_text: Optional[Union[str, bytes]] = None, + source_kind: str = "bw-import", + geo_range: Union[str, int] = "normal", ) -> tuple[Event, dict]: """ Ingest a Blastware event file produced by an external tool @@ -413,7 +415,9 @@ class WaveformStore: event_hdf5.write_event_hdf5( hdf5_path, ev, serial=serial, - geo_range="normal", # BW file doesn't carry the range; assume Normal + # The BW file doesn't carry the range (yet); an import assumes Normal, + # a live download passes the unit's own (event_ingest). + geo_range=geo_range, source_kind="bw-import", ) hdf5_filename = hdf5_path.name @@ -438,7 +442,7 @@ class WaveformStore: blastware_filename=filename, blastware_filesize=filesize, blastware_sha256=sha256, - source_kind="bw-import", + source_kind=source_kind, # "sfm-live" for SFM's own downloads (event_ingest) a5_pickle_filename=None, txt_filename=txt_filename, review=existing_review, diff --git a/tests/test_5a_blastware_walk_histogram.py b/tests/test_5a_blastware_walk_histogram.py index 2e9559d..d9492fd 100644 --- a/tests/test_5a_blastware_walk_histogram.py +++ b/tests/test_5a_blastware_walk_histogram.py @@ -18,7 +18,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import minimateplus.protocol as mp # noqa: E402 from minimate_replay import fast_clock # noqa: E402 -from minimateplus.blastware_file import write_blastware_file # noqa: E402 +from minimateplus.blastware_file import blastware_file_bytes, write_blastware_file # noqa: E402 from minimateplus.framing import S3FrameParser # noqa: E402 from minimateplus.models import Event # noqa: E402 @@ -122,3 +122,14 @@ def test_the_walk_is_blastwares_and_rebuilds_its_file(key, bw, n, tmp_path): ev.timestamp = None write_blastware_file(ev, frames, tmp_path / bw) assert (tmp_path / bw).read_bytes() == (FIX / "blastware" / bw).read_bytes() + + +@pytest.mark.parametrize("key,bw", [("0111f210", "K441LTON.900"), ("011106a0", "K441LTOK.R10")]) +def test_blastware_file_bytes_is_blastwares_file(key, bw): + # What a live MiniMate download hands to the store (#8): the file itself, as bytes. + frames = mp.MiniMateProtocol(ByAddress()).read_bulk_waveform_stream( + bytes.fromhex(key), stop_after_metadata=False, include_terminator=True, + strict=True, max_chunks=128) + ev = Event(index=0) + ev.timestamp = None + assert blastware_file_bytes(ev, frames) == (FIX / "blastware" / bw).read_bytes() diff --git a/tests/test_device_access_s3_events.py b/tests/test_device_access_s3_events.py index 9f17183..0cf02d7 100644 --- a/tests/test_device_access_s3_events.py +++ b/tests/test_device_access_s3_events.py @@ -75,6 +75,9 @@ def test_download_returns_the_event_its_frames_and_the_settings(): assert dl.a5_frames and all(f.sub == 0xA5 for f in dl.a5_frames) assert dl.compliance is fake.compliance and dl.filename.startswith("T193") assert dl.timestamp == datetime.datetime(2026, 10, 1, 8, 0, 0) + # #8: the download carries the Blastware file itself, for the file-import path. + from minimateplus.blastware_file import blastware_file_bytes + assert dl.bw_bytes and dl.bw_bytes == blastware_file_bytes(dl.event, dl.a5_frames) def test_download_refuses_a_different_unit_before_downloading(): diff --git a/tests/test_event_ingest.py b/tests/test_event_ingest.py index ec4f7a5..e79a190 100644 --- a/tests/test_event_ingest.py +++ b/tests/test_event_ingest.py @@ -18,6 +18,7 @@ from sfm.waveform_store import WaveformStore # noqa: E4 THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf" BW_FIXTURES = Path(__file__).parent / "fixtures" / "5-11-26" +HIST_FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram" / "blastware" @pytest.fixture @@ -182,23 +183,71 @@ class RecordingStore: self.saved.append((ev, serial, a5_frames, geo_range)) return {"filename": "T193LQ9K.OE0", "filesize": 8708, "sha256": "ab" * 32} + def save_imported_bw(self, bw_bytes, source_path, *, serial_hint=None, bw_report_text=None, + source_kind="bw-import", geo_range="normal"): + self.saved.append(("imported", bw_bytes, source_path, serial_hint, source_kind)) + self.geo_range = geo_range + ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)) + return ev, {"filename": source_path.name, "filesize": len(bw_bytes), "sha256": "ab" * 32} -def test_a_series3_event_is_backfilled_then_stored_as_series3(tmp_path): + +def test_a_series3_download_is_stored_through_the_file_import_path(tmp_path): + # #8: the same path production's watcher uses; data from the binary, no backfill. db = SeismoDb(tmp_path / "seismo.db") store = RecordingStore() - fake = FakeMiniMateClient() - ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)) dl = DownloadedEvent(event_id="BE18193:01110000:20261001080000", serial="BE18193", series=3, - filename="T193LQ9K.OE0", verified=None, event=ev, a5_frames=["frame"], - compliance=fake.compliance, timestamp=datetime.datetime(2026, 10, 1, 8, 0, 0)) + filename="T193LQ9K.OE0", verified=None, bw_bytes=b"BW-FILE", + event=s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)), + compliance=FakeMiniMateClient().compliance, + timestamp=datetime.datetime(2026, 10, 1, 8, 0, 0)) out = persist_download(dl, store=store, db=db) - saved_ev, serial, frames, geo_range = store.saved[0] - assert (serial, frames, geo_range) == ("BE18193", ["frame"], 0) - assert saved_ev.sample_rate == 1024 and saved_ev.rectime_seconds == 3.0 + assert store.saved == [("imported", b"BW-FILE", Path("T193LQ9K.OE0"), "BE18193", "sfm-live")] + assert dl.event.sample_rate is None # the live event is not backfilled assert db.get_event(out.db_event_id)["device_family"] == "series3" assert out.stored_filename == "T193LQ9K.OE0" +def _hist_download(name, key, when): + return DownloadedEvent(event_id=f"BE9441:{key}:{when:%Y%m%d%H%M%S}", serial="BE9441", series=3, + filename=name, verified=None, bw_bytes=(HIST_FIX / name).read_bytes(), + timestamp=when) + + +def test_a_series3_histogram_download_is_stored_from_its_file(sdm): + import hashlib, json + from sfm import event_hdf5 + store, db = sdm + dl = _hist_download("K441LTON.900", "0111f210", datetime.datetime(2026, 10, 26, 17, 0, 36)) + out = persist_download(dl, store=store, db=db) + assert out.inserted is True + assert out.sha256 == hashlib.sha256(dl.bw_bytes).hexdigest() # the file, byte for byte + plot = event_hdf5.plot_json_from_hdf5(store.hdf5_path_for("BE9441", "K441LTON.900")) + assert plot["channels"]["Tran"]["values"] # the histogram decoded + sidecar = json.loads(store.sidecar_path_for("BE9441", "K441LTON.900").read_text()) + assert sidecar["source"]["kind"] == "sfm-live" + assert db.get_event(out.db_event_id)["sample_rate"] == 4096 + + +def test_the_small_mic_off_histogram_is_stored_with_samples(sdm): + # Refused on the 2026-10-29 bench; decodes since #47/#49 came in with dev. + from sfm import event_hdf5 + store, db = sdm + dl = _hist_download("K441LTOK.QZ0", "01110000", datetime.datetime(2026, 10, 26, 16, 6, 35)) + out = persist_download(dl, store=store, db=db) + assert out.inserted is True + plot = event_hdf5.plot_json_from_hdf5(store.hdf5_path_for("BE9441", "K441LTOK.QZ0")) + assert plot["channels"]["Vert"]["values"] + + +def test_a_repeat_series3_download_adds_no_row(sdm): + store, db = sdm + when = datetime.datetime(2026, 10, 26, 17, 0, 36) + first = persist_download(_hist_download("K441LTON.900", "0111f210", when), store=store, db=db) + again = persist_download(_hist_download("K441LTON.900", "0111f210", when), store=store, db=db) + assert first.inserted is True and again.inserted is False + assert len(db.query_events(serial="BE9441")) == 1 + + def test_downloading_an_event_the_watcher_stored_writes_nothing_series3(tmp_path): db = SeismoDb(tmp_path / "seismo.db") serial, rec = watcher_import_bw(WaveformStore(tmp_path / "waveforms"), db, "M529LL1L.V70") @@ -221,11 +270,11 @@ def test_downloading_an_event_the_watcher_stored_writes_nothing_series3(tmp_path assert ev.sample_rate is None # not even backfilled -def test_a_series3_download_with_no_event_stores_nothing_and_says_so(tmp_path): +def test_a_series3_download_with_no_file_stores_nothing_and_says_so(tmp_path): store = RecordingStore() dl = DownloadedEvent(event_id="BE18193:01110000:-", serial="BE18193", series=3, filename="T193LQ9K.OE0", verified=None, event=None, a5_frames=["frame"]) - with pytest.raises(IngestError, match="nothing was stored"): + with pytest.raises(IngestError, match="carried no event file; nothing was stored"): persist_download(dl, store=store, db=SeismoDb(tmp_path / "seismo.db")) assert store.saved == [] @@ -245,3 +294,44 @@ def test_backfill_without_settings_changes_nothing(): ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1)) backfill_series3_event(ev, None) assert ev.sample_rate is None + + +# The file path does not yet read a histogram's vector sum the way Blastware does +# (the checker's open finding), the mic peak, or a sensitive range, so a live +# download keeps the unit's own 0C values for those -- the Series-4 pattern. + +def _with_unit_peaks(dl, *, tran, vert, long, micl, pvs): + from minimateplus.models import PeakValues + dl.event = s3_event(0, dl.event_id.split(":")[1], dl.timestamp) + dl.event.peak_values = PeakValues(tran=tran, vert=vert, long=long, micl=micl, peak_vector_sum=pvs) + return dl + + +def test_a_series3_download_keeps_the_units_peaks_mic_and_vector_sum(sdm): + store, db = sdm + dl = _with_unit_peaks(_hist_download("K441LTON.900", "0111f210", datetime.datetime(2026, 10, 26, 17, 0, 36)), + tran=0.2, vert=0.385, long=0.255, micl=0.00058, pvs=0.38516) + row = db.get_event(persist_download(dl, store=store, db=db).db_event_id) + assert row["peak_vector_sum"] == pytest.approx(0.38516, abs=1e-5) # Blastware: 0.385; the file path says 0.503 + assert row["mic_ppv"] == pytest.approx(0.00058, abs=1e-6) + assert (row["tran_ppv"], row["vert_ppv"], row["long_ppv"]) == pytest.approx((0.2, 0.385, 0.255), abs=1e-4) + + +def test_an_impossible_unit_vector_sum_is_not_kept(sdm): + # Bench finding #4: BE9441's 0C read -0.0 for a vector sum whose channels reach 1.08. + store, db = sdm + dl = _with_unit_peaks(_hist_download("K441LTOK.R10", "011106a0", datetime.datetime(2026, 10, 26, 16, 6, 37)), + tran=0.25, vert=1.08, long=0.195, micl=0.0001, pvs=-0.0) + row = db.get_event(persist_download(dl, store=store, db=db).db_event_id) + assert row["peak_vector_sum"] == pytest.approx(1.0826, abs=1e-3) # the file's own + + +def test_the_units_range_reaches_the_store(tmp_path): + store = RecordingStore() + cc = FakeMiniMateClient().compliance + cc.geo_range = 1 # Sensitive, 1.25 in/s + dl = DownloadedEvent(event_id="BE18193:01110000:20261001080000", serial="BE18193", series=3, + filename="T193LQ9K.OE0", verified=None, bw_bytes=b"BW-FILE", compliance=cc, + timestamp=datetime.datetime(2026, 10, 1, 8, 0, 0)) + persist_download(dl, store=store, db=SeismoDb(tmp_path / "seismo.db")) + assert store.geo_range == 1