Files
seismo-relay/tests/test_report_event_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

101 lines
4.9 KiB
Python

"""A paired Blastware report's event time must win, in every date format and through a backfill.
The event-time fix makes a report's Event Time + Event Date authoritative (the
binary gives the trigger only to within a second). On prod's own data it never
applied (measured on the 2026-09-30 store snapshot, 81 report-paired waveforms):
* every one of those reports writes the date as ISO ("2026-08-14") -- the
parser read only "August 14, 2026", so event_datetime was always None;
* the sidecar's bw_report block never stored the event time, so a backfill had
nothing to re-apply -- and its overlay ignored the time anyway.
The binary's trigger matched Blastware's event time on 66 of the 81 and was one
second late on 15.
"""
from __future__ import annotations
import datetime
import json
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.bw_ascii_report import parse_report # noqa: E402
from minimateplus.event_file_io import (_bw_report_to_dict, # noqa: E402
apply_bw_report_dict_to_event, read_blastware_file)
from minimateplus.models import Event # noqa: E402
from sfm.database import SeismoDb # noqa: E402
from sfm.waveform_store import WaveformStore # noqa: E402
FIX = Path(__file__).parent / "fixtures"
WAVEFORM = FIX / "fft-oracle-2026-09-14" / "N844LQHB.ZT0W" # the binary's trigger: 10:33:29
REPORT_TIME = datetime.datetime(2026, 8, 25, 10, 33, 28) # a report a second earlier
def _report(date_line: str) -> str:
return ('"Event Type : Full Waveform"\n"Serial Number : BE12844"\n'
'"Event Time : 10:33:28"\n' + date_line + '\n"Record Time : 3.0 sec."\n')
def _tuple(ts):
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
def test_an_iso_dated_report_gives_its_event_time():
# The form all 81 of prod's saved waveform reports use.
assert parse_report(_report('"Event Date : 2026-08-25"')).event_datetime == REPORT_TIME
def test_a_long_form_dated_report_still_gives_its_event_time():
assert parse_report(_report('"Event Date : August 25, 2026"')).event_datetime == REPORT_TIME
def test_the_saved_report_block_carries_the_event_time_back_onto_the_event():
# It fills in when the instrument's event record gave no time ...
block = json.loads(json.dumps(_bw_report_to_dict(parse_report(_report('"Event Date : 2026-08-25"')))))
ev = Event(index=0)
apply_bw_report_dict_to_event(ev, block) # as a sidecar holds it
assert (_tuple(ev.timestamp), ev.timestamp_source) == (REPORT_TIME, "report")
# ... and is only a cross-check against a validated one
ev = read_blastware_file(WAVEFORM)
apply_bw_report_dict_to_event(ev, block)
assert (_tuple(ev.timestamp), ev.timestamp_source) == \
(datetime.datetime(2026, 8, 25, 10, 33, 29), "event_record")
def test_a_saved_report_block_without_an_event_time_leaves_the_time_alone():
ev = Event(index=0)
apply_bw_report_dict_to_event(ev, {"available": True, "peaks": {}})
assert ev.timestamp is None
def test_the_backfill_with_reparse_puts_a_v031_row_on_the_instruments_time(tmp_path):
"""prod's shape: a session-start row, a saved ISO-dated .TXT, a sidecar whose
report block has no event time (written by the old parser). The report here
disagrees by a second: the instrument's event record is kept."""
import scripts.backfill_sidecars as backfill
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
ev, rec = store.save_imported_bw(WAVEFORM.read_bytes(), source_path=Path(WAVEFORM.name),
bw_report_text=_report('"Event Date : 2026-08-25"'))
db.insert_events([ev], serial=rec["serial"], device_family="series3",
waveform_records={ev._waveform_key.hex(): rec})
with sqlite3.connect(str(db.db_path)) as c:
c.execute("UPDATE events SET timestamp = '2026-08-25T06:00:13'")
car = next((tmp_path / "waveforms").rglob("*.sfm.json"))
d = json.loads(car.read_text())
assert d["source"].get("txt_filename") # the report is on disk
d["bw_report"].pop("event_datetime", None) # as the old parser left it
car.write_text(json.dumps(d))
assert backfill.main(["--store-root", str(tmp_path / "waveforms"),
"--db-path", str(db.db_path), "--force", "--reparse-txt"]) == 0
with sqlite3.connect(str(db.db_path)) as c:
assert c.execute("SELECT timestamp FROM events").fetchall() == [("2026-08-25T10:33:29",)]
assert json.loads(car.read_text())["event"]["timestamp"] == "2026-08-25T10:33:29"
assert json.loads(car.read_text())["bw_report"]["event_datetime"] == REPORT_TIME.isoformat()