"""A Series-3 waveform's time comes from the instrument's own event record, not a filename. A Blastware waveform file carries a copy of the unit's event record: `00 28 05 00 ?? ?? | fe 80 | trigger | stop`, each time `dd mm yyyy(BE) 00 hh mm ss`. Measured 2026-10-26: * it is the instrument's data: in all 8 of BE9441's events Blastware downloaded, the record occurs exactly once in the unit's own 5A replies, and the trigger equals the unit's separate 0C record; SFM-only downloads carry it too; * on 7,935 waveforms (DL2 + prod store) exactly one candidate validates, its trigger equals Blastware's report (1,320/1,320) and filename (7,935/7,935); * the footer-only estimate (stop minus record time) is a second off on ~19%. A filename is never a time source -- an event SFM receives itself has none -- only a cross-check, logged when it disagrees. """ from __future__ import annotations import datetime import logging import os import sys from pathlib import Path import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from minimateplus.blastware_file import blastware_filename_time # noqa: E402 from minimateplus.bw_ascii_report import BwAsciiReport # noqa: E402 from minimateplus.event_file_io import (apply_report_to_event, # noqa: E402 decode_blastware_bytes, read_blastware_file) FIX = Path(__file__).parent / "fixtures" ZI0 = FIX / "minimate-bench-10-26-26-blastware" / "blastware" / "K441LTOF.ZI0" ORACLE = sorted((FIX / "fft-oracle-2026-09-14").glob("N844*W")) HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H" TRIGGER = datetime.datetime(2026, 10, 26, 14, 23, 42) # the unit's 0C record; the record ESTIMATE = datetime.datetime(2026, 10, 26, 14, 23, 43) # footer stop minus record time def _dt(ts): return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second) def _record_at(raw: bytes) -> int: return raw.rfind(b"\xfe\x80") def _decode(raw: bytes, **kw): ev = decode_blastware_bytes(bytes(raw), **kw) return _dt(ev.timestamp), ev.timestamp_source, ev.decode_problems # -- no filename at all -------------------------------------------------------- def test_raw_bytes_with_no_name_give_the_instruments_trigger(): assert _decode(ZI0.read_bytes()) == (TRIGGER, "event_record", []) def test_the_name_changes_nothing(): assert _dt(read_blastware_file(ZI0).timestamp) == TRIGGER assert _decode(ZI0.read_bytes(), name="upload.bw")[:2] == (TRIGGER, "event_record") @pytest.mark.parametrize("path", ORACLE, ids=lambda p: p.name) def test_every_oracle_waveform_decodes_from_bytes_alone_to_blastwares_time(path): # BE12844's seven, Blastware's exact times (the fft-oracle reports) t, source, problems = _decode(path.read_bytes()) assert (t, source, problems) == (blastware_filename_time(path.name), "event_record", []) # -- the filename is a cross-check --------------------------------------------- def test_a_disagreeing_filename_is_logged_and_the_record_wins(caplog): # K441LTOF.ZJ0 is a valid Blastware name one second later with caplog.at_level(logging.WARNING): t, source, _ = _decode(ZI0.read_bytes(), name="K441LTOF.ZJ0") assert (t, source) == (TRIGGER, "event_record") assert any("14:23:42" in r.message and "14:23:43" in r.message for r in caplog.records) def test_an_agreeing_filename_logs_nothing(caplog): with caplog.at_level(logging.WARNING): _decode(ZI0.read_bytes(), name=ZI0.name) assert not [r for r in caplog.records if "filename" in r.message] # -- validation: anything less than one clean candidate is a decode problem --- def _session_starts_after_trigger(raw: bytearray, i: int) -> None: # only this rule breaks: the footer's ts1 becomes the record's trigger + 1 s f = len(raw) - 26 raw[f + 2:f + 10] = raw[i + 2:i + 10] raw[f + 9] += 1 def _broken(edit) -> bytearray: raw = bytearray(ZI0.read_bytes()) edit(raw, _record_at(raw)) return raw @pytest.mark.parametrize("why,edit", [ ("lead bytes", lambda r, i: r.__setitem__(i - 5, 0x29)), # 00 28 05 00 -> 00 29 .. ("marker", lambda r, i: r.__setitem__(i + 1, 0x81)), ("trigger zero byte", lambda r, i: r.__setitem__(i + 6, 0x01)), ("impossible date", lambda r, i: r.__setitem__(i + 3, 13)), # month 13 ("stop far from the footer's", lambda r, i: r.__setitem__(i + 17, r[i + 17] - 5)), ("trigger before the session start", lambda r, i: _session_starts_after_trigger(r, i)), ], ids=lambda x: x if isinstance(x, str) else "") def test_a_record_that_fails_validation_is_a_decode_problem_not_a_filename(why, edit, caplog): with caplog.at_level(logging.WARNING): t, source, problems = _decode(_broken(edit), name=ZI0.name) # a valid name is right there assert (t, source) == (ESTIMATE, "estimate") # never the name's time assert problems and "event record" in problems[0] assert any("event record" in r.message for r in caplog.records) def test_two_records_that_both_validate_are_not_guessed_between(): def dup(raw, i): footer = len(raw) - 26 raw[footer - 24:footer] = raw[i - 6:i + 18] # a second, identical candidate t, source, problems = _decode(_broken(dup)) assert source == "estimate" and "2 candidates" in problems[0] # -- reports and histograms ---------------------------------------------------- def test_a_report_does_not_override_the_instruments_record(caplog): ev = decode_blastware_bytes(ZI0.read_bytes()) with caplog.at_level(logging.WARNING): apply_report_to_event(ev, BwAsciiReport(event_datetime=datetime.datetime(2026, 10, 26, 14, 23, 40))) assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "event_record") assert any("14:23:40" in r.message for r in caplog.records) def test_a_report_fills_in_when_the_record_is_missing(): ev = decode_blastware_bytes(bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81)))) apply_report_to_event(ev, BwAsciiReport(event_datetime=TRIGGER)) assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "report") def test_a_histogram_keeps_its_footer_start_for_now(): # Its record (marker fe f5) also holds Blastware's start -- that change is #51. ev = read_blastware_file(HISTOGRAM) assert (_dt(ev.timestamp), ev.timestamp_source) == (datetime.datetime(2026, 5, 10, 19, 4, 50), "footer") def test_the_sidecar_keeps_the_instruments_time_and_says_where_it_came_from(): from minimateplus.event_file_io import event_to_sidecar_dict ev = decode_blastware_bytes(ZI0.read_bytes()) car = event_to_sidecar_dict(ev, serial="BE9441", blastware_filename="K441LTOF.ZI0", blastware_filesize=0, blastware_sha256="", source_kind="bw-import", bw_report=BwAsciiReport(event_datetime=datetime.datetime(2026, 10, 26, 14, 23, 40))) assert (car["event"]["timestamp"], car["event"]["timestamp_source"]) == \ ("2026-10-26T14:23:42", "event_record") assert "decode_problems" not in car["event"] def test_a_sidecar_carries_the_decode_problem(): from minimateplus.event_file_io import event_to_sidecar_dict ev = decode_blastware_bytes(bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81)))) car = event_to_sidecar_dict(ev, serial="BE9441", blastware_filename="K441LTOF.ZI0", blastware_filesize=0, blastware_sha256="", source_kind="bw-import") assert car["event"]["timestamp_source"] == "estimate" assert "event record" in car["event"]["decode_problems"][0] def test_an_imported_event_with_only_an_estimate_does_not_overwrite_its_neighbour(tmp_path, caplog): import sqlite3 from minimateplus.models import Event, PeakValues, Timestamp from sfm.database import SeismoDb from sfm.waveform_store import WaveformStore store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db") other = Event(index=0) # a different event at 14:23:43 other.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26, hour=14, minute=23, second=43) other._waveform_key = bytes.fromhex("01110000") other.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None) db.insert_events([other], serial="BE9441", device_family="series3", waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}}) broken = bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))) # no validated record ev, rec = store.save_imported_bw(broken, source_path=Path(ZI0.name)) assert (_dt(ev.timestamp), ev.timestamp_source) == (ESTIMATE, "estimate") with caplog.at_level(logging.WARNING): assert db.insert_events([ev], serial="BE9441", device_family="series3", waveform_records={ev._waveform_key.hex(): rec}) == (0, 1) with sqlite3.connect(str(db.db_path)) as c: assert c.execute("SELECT blastware_filename, peak_vector_sum FROM events").fetchall() == \ [("K441LTOF.ZJ0H", 0.04)] assert (tmp_path / "waveforms" / "BE9441" / "K441LTOF.ZI0").exists() # the data is kept assert any("not merged" in r.message for r in caplog.records)