Files
seismo-relay/tests/test_bw_filename_time.py
T
serversdownandClaude Opus 5.5 f91949be89 fix(decode): a Series-3 waveform's time comes from the instrument's embedded event record
Brian's requirements: the instrument's data is the only time source; a filename
is a cross-check, never a fallback (an event SFM receives itself has none).

The record (found by reading a seismo_lab Inspector dump; Series-III reference
§7.8.9): 00 28 05 00 ?? ?? | fe 80 | trigger | stop, times dd mm yyyy(BE) 00 hh
mm ss.  Measured on 7,935 waveforms (DL2 + prod store): exactly one candidate
validates in every file; trigger = Blastware's report 1,320/1,320, = filename
7,935/7,935, = the unit's 0C record 10/10.

Provenance (requirement 6, measured): in Blastware's download of 8 BE9441
events the record -- with 24 B before and 22 after -- occurs exactly once in the
unit's own A5 reply payloads; SFM-only downloads (no Blastware) carry it too.
It is instrument data, not Blastware's.

- _embedded_event_record(): every fe 80 before the footer is a candidate; it
  counts only with the lead bytes, two well-formed times (zero byte zero),
  footer ts1 <= trigger <= stop, stop = footer ts2 or a second before, and a
  length matching the record time.  Exactly one must count; none or several is
  a decode problem, never a guess.
- Without one: the footer estimate, timestamp_source 'estimate', a
  decode_problems entry, a WARNING.  No filename fallback.
- A filename that disagrees is logged; the decoded time is kept.  A paired
  report fills in only without a validated record (apply_report_to_event, the
  sidecar dict overlay, event_to_sidecar_dict) and is logged when it disagrees.
- decode_blastware_bytes(raw, name=None): no file or name needed;
  save_imported_bw uses it (no temp file).  Event gains timestamp_source and
  decode_problems; the sidecar records both.
- Histograms unchanged (#51): their record (fe f5) is noted, not used.

Tests: raw bytes with no name (ZI0, 7 BE12844 oracles), a disagreeing name, each
validation rule alone, two valid candidates, no filename fallback, report
precedence, sidecar.  7 mutants, each caught.  Real data, decoded with no name:
7,961/7,961 waveforms on the record, 0 disagreements with filename or report;
10,433/10,433 prod histograms unchanged.  Suite: only the 16 known failures.

Open (reported, not changed): 3 DL2 files named as waveforms whose body the
waveform codec does not recognise keep the footer start, 4 s off, as on dev.
None in prod.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 23:59:22 -04:00

110 lines
5.7 KiB
Python

"""The Blastware filename's time: a cross-check on the decoded time, never its source.
A Blastware name encodes the event time to the second (stem + AB, see
`blastware_filename`) -- Blastware's own copy of the unit's trigger. The decoder
reads the time from the instrument's embedded event record instead (see
test_bw_event_record_time.py); an event SFM receives itself has no name.
Measured 2026-10-26:
* name == the report's Event Time on 81/81 prod-snapshot and 1,249/1,249 DL2
report-paired waveforms;
* the binary's trigger (ts2 - record time) is a second off on 260 of prod's
1,394 waveforms (199 late, 61 early). On BE9558 the 61 early ones land on
their histogram twin's second, and events is unique on (serial, timestamp):
a fresh import wrote each waveform over its histogram's row.
Histograms keep the binary's ts1. Their name is Blastware's start time too (13,089/13,089),
and ts1 runs a second early on 97% of them -- but in Blastware's timing a
waveform and its histogram share a second 209 times in prod's store, which a
(serial, timestamp) key cannot hold. That correction needs the key changed.
"""
from __future__ import annotations
import datetime
import os
import sqlite3
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.blastware_file import blastware_filename, blastware_filename_time # noqa: E402
from minimateplus.event_file_io import read_blastware_file # noqa: E402
from minimateplus.models import Event, PeakValues, Timestamp # noqa: E402
from sfm.database import SeismoDb # noqa: E402
from sfm.waveform_store import WaveformStore # noqa: E402
FIX = Path(__file__).parent / "fixtures"
ZI0 = FIX / "minimate-bench-10-26-26-blastware" / "blastware" / "K441LTOF.ZI0"
HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H"
def _dt(ts):
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
def test_names_decode_to_the_documented_times():
# the three S353L4H0 events the encoder was verified against, plus an H
assert blastware_filename_time("S353L4H0.3M0W") == datetime.datetime(2025, 6, 23, 13, 57, 22)
assert blastware_filename_time("S353L4H0.8S0H") == datetime.datetime(2025, 6, 23, 14, 0, 28)
assert blastware_filename_time("S353L4H0.9X0W") == datetime.datetime(2025, 6, 23, 14, 1, 9)
assert blastware_filename_time("P036L318.C80H") == datetime.datetime(2025, 5, 26, 15, 0, 8)
assert blastware_filename_time("K441LTOF.ZI0") == datetime.datetime(2026, 10, 26, 14, 23, 42)
assert blastware_filename_time("k441ltof.zi0") == datetime.datetime(2026, 10, 26, 14, 23, 42)
def test_the_decoder_inverts_the_encoder():
for t in (datetime.datetime(2018, 1, 2, 3, 4, 5), datetime.datetime(2026, 10, 26, 23, 59, 59),
datetime.datetime(2026, 2, 28, 0, 0, 0)):
ev = Event(index=0)
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=t.year, unknown_byte=0, month=t.month,
day=t.day, hour=t.hour, minute=t.minute, second=t.second)
assert blastware_filename_time(blastware_filename(ev, "BE9441")) == t
assert blastware_filename_time(blastware_filename(ev, "BE9441", ach=True)) == t
def test_other_names_give_nothing():
for name in ("imported.bw", "UM12947_20260406130113.IDFW", "K441LTOF.ZI1", "K441LTOF.ZI0X",
"K441LTO.ZI0", "K441LTOF.Z!0", "", "BE9441.MLG"):
assert blastware_filename_time(name) is None, name
def test_a_waveform_decodes_to_the_time_its_name_encodes():
# BE9441, 2026-10-26: the footer estimate says 14:23:43; the event record, the
# unit's 0C record and the name all say 14:23:42
assert _dt(read_blastware_file(ZI0).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 42)
def test_a_waveform_read_under_another_name_keeps_its_time(tmp_path):
tmp = tmp_path / "upload.bw"
tmp.write_bytes(ZI0.read_bytes())
assert _dt(read_blastware_file(tmp).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 42)
assert _dt(read_blastware_file(tmp, name=ZI0.name).timestamp) == \
datetime.datetime(2026, 10, 26, 14, 23, 42)
def test_a_histogram_keeps_the_binarys_window_start():
assert blastware_filename_time(HISTOGRAM.name) != datetime.datetime(2026, 5, 10, 19, 4, 50)
assert _dt(read_blastware_file(HISTOGRAM).timestamp) == datetime.datetime(2026, 5, 10, 19, 4, 50)
def test_an_import_no_longer_lands_a_waveform_on_its_histogram_twins_row(tmp_path):
"""BE9558's 61: the binary's second was the histogram twin's. Built here from
BE9441's ZI0: a histogram row at the binary's 14:23:43, then the waveform."""
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
hist = Event(index=0)
hist.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26,
hour=14, minute=23, second=43)
hist._waveform_key = bytes.fromhex("01110000")
hist.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None)
db.insert_events([hist], serial="BE9441", device_family="series3",
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}})
ev, rec = store.save_imported_bw(ZI0.read_bytes(), source_path=Path(ZI0.name))
db.insert_events([ev], serial="BE9441", device_family="series3",
waveform_records={ev._waveform_key.hex(): rec})
with sqlite3.connect(str(db.db_path)) as c:
rows = c.execute("SELECT blastware_filename, timestamp FROM events ORDER BY timestamp").fetchall()
assert rows == [("K441LTOF.ZI0", "2026-10-26T14:23:42"), ("K441LTOF.ZJ0H", "2026-10-26T14:23:43")]