merge: Series-3 waveform times from the Blastware filename; a corrected time moves its row instead of duplicating it
Brings fix/waveform-time-restamp (847900b,abb671a,3948dc1): insert_events restamps a re-stored event's row by its Blastware filename; a paired report's ISO-dated event time is read and survives a backfill; a waveform's time comes from its filename. Deploy rehearsal on prod's 2026-09-30 snapshot (11,827 files): waveforms 1,016 -> 1,394 of 1,394 on Blastware's exact time, every id kept, no row lost or merged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
This commit is contained in:
commit
5737168173
9 files changed
+486
-7
No files matched your search
@@ -152,6 +152,7 @@ from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import re
|
||||
import struct
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
@@ -416,6 +417,31 @@ def _make_stem(ts_local: datetime.datetime) -> str:
|
||||
return s
|
||||
|
||||
|
||||
_BW_NAME = re.compile(r"^[B-Z]\d{3}([0-9A-Z]{4})\.([0-9A-Z]{2})0[WH]?$")
|
||||
|
||||
|
||||
def blastware_filename_time(name: str) -> Optional[datetime.datetime]:
|
||||
"""The event time a Blastware filename encodes, or None for any other name.
|
||||
|
||||
The inverse of `blastware_filename`: `<prefix><serial3><stem 4>.<AB>0[W|H]`,
|
||||
time = 1985-01-01 + stem*1296 + AB seconds. This is Blastware's own time
|
||||
to the second -- it equals the report's Event Time on 1,330/1,330
|
||||
report-paired waveforms (81 prod-store, 1,249 DL2) and the report's
|
||||
Histogram Start Time on 13,089/13,089 histograms (measured 2026-10-26).
|
||||
Only the V10.72 `AB0` form is decoded; anything else gives None.
|
||||
"""
|
||||
m = _BW_NAME.match((name or "").upper())
|
||||
if not m:
|
||||
return None
|
||||
stem = 0
|
||||
for c in m.group(1):
|
||||
stem = stem * 36 + _STEM_CHARS.index(c)
|
||||
ab = _STEM_CHARS.index(m.group(2)[0]) * 36 + _STEM_CHARS.index(m.group(2)[1])
|
||||
if ab >= _STEM_UNIT_SEC:
|
||||
return None
|
||||
return _INSTANTEL_EPOCH + datetime.timedelta(seconds=stem * _STEM_UNIT_SEC + ab)
|
||||
|
||||
|
||||
def blastware_filename(event: Event, serial: str, ach: bool = False) -> str:
|
||||
"""
|
||||
Return the correct Blastware filename for an event.
|
||||
|
||||
@@ -280,8 +280,15 @@ _MONTHS = {
|
||||
|
||||
|
||||
def _parse_event_date(s: str) -> Optional[datetime.date]:
|
||||
"""Parse "April 23, 2026" or "May 8, 2026" → date."""
|
||||
"""Parse "April 23, 2026", "May 8, 2026" or "2026-08-14" → date.
|
||||
|
||||
Blastware writes whichever the PC's settings say: every one of the 81
|
||||
report-paired waveforms in prod's store (2026-09-30 snapshot) is ISO, and
|
||||
reading only the long form left their event time unread."""
|
||||
s = s.strip()
|
||||
iso = _parse_iso_date(s)
|
||||
if iso is not None:
|
||||
return iso
|
||||
parts = s.replace(",", " ").split()
|
||||
if len(parts) < 3:
|
||||
return None
|
||||
@@ -297,8 +304,8 @@ def _parse_event_date(s: str) -> Optional[datetime.date]:
|
||||
|
||||
def _parse_iso_date(s: str) -> Optional[datetime.date]:
|
||||
"""Parse "2026-05-16" → date. Histograms use ISO format for their
|
||||
Start Date / Stop Date / Peak Date fields; waveforms use the
|
||||
"May 8, 2026" long form which `_parse_event_date` handles."""
|
||||
Start Date / Stop Date / Peak Date fields; a waveform's Event Date may be
|
||||
either form (see `_parse_event_date`)."""
|
||||
s = s.strip()
|
||||
try:
|
||||
return datetime.date.fromisoformat(s)
|
||||
|
||||
@@ -157,6 +157,9 @@ def _bw_report_to_dict(report: BwAsciiReport) -> dict:
|
||||
"available": True,
|
||||
"event_type": report.event_type,
|
||||
"version": report.version,
|
||||
# Blastware's exact trigger, so a backfill can re-apply it
|
||||
# (apply_bw_report_dict_to_event); absent from sidecars before 0.32.0.
|
||||
"event_datetime": report.event_datetime.isoformat() if report.event_datetime else None,
|
||||
"trigger": {
|
||||
"channel": report.trigger_channel,
|
||||
"geo_level_ips": report.geo_trigger_level_ips,
|
||||
@@ -371,6 +374,20 @@ def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None:
|
||||
rt = rec.get("record_time_s")
|
||||
if rt is not None:
|
||||
event.rectime_seconds = rt
|
||||
# As apply_report_to_event: Blastware's exact trigger beats the binary's,
|
||||
# which is a second late on 15 of prod's 81 report-paired waveforms.
|
||||
edt = bw_report.get("event_datetime")
|
||||
if edt:
|
||||
try:
|
||||
t = datetime.datetime.fromisoformat(edt)
|
||||
except (TypeError, ValueError):
|
||||
t = None
|
||||
if t is not None:
|
||||
event.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,
|
||||
)
|
||||
|
||||
|
||||
def _project_info_to_dict(pi: Optional[ProjectInfo]) -> dict:
|
||||
@@ -842,14 +859,18 @@ def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
|
||||
return rt if 0.05 <= rt <= 600.0 else None
|
||||
|
||||
|
||||
def read_blastware_file(path: Union[str, Path]) -> Event:
|
||||
def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event:
|
||||
"""
|
||||
Parse a Blastware waveform file into an Event.
|
||||
|
||||
`name` is the file's real Blastware name when `path` is not (an upload
|
||||
stashed under a temp name); it defaults to `path.name`. A waveform's time
|
||||
comes from it when it is one (see the timestamp block below).
|
||||
|
||||
Recovers:
|
||||
- waveform_key, rectime_seconds, total_samples, pretrig_samples
|
||||
(from the STRT record)
|
||||
- timestamp (from the footer's start-time field)
|
||||
- timestamp (a waveform's from its Blastware filename, else the footer)
|
||||
- project_info (from ASCII labels embedded in the body)
|
||||
- raw_samples (Tran/Vert/Long/MicL int16 lists)
|
||||
- peak_values (computed from raw_samples; approximate — see notes
|
||||
@@ -861,6 +882,7 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
|
||||
not possible — the on-disk BW file IS the byte-for-byte source.
|
||||
"""
|
||||
path = Path(path)
|
||||
name = name or path.name
|
||||
raw = path.read_bytes()
|
||||
if len(raw) < _bw._WAVEFORM_HEADER_SIZE + 21 + 26:
|
||||
raise ValueError(f"{path}: file too short ({len(raw)} bytes) to be a BW event")
|
||||
@@ -981,7 +1003,7 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
|
||||
# ".bw" suffix, so the derivation falls back to "Waveform" and the
|
||||
# caller overrides ev.record_type using the original filename — see
|
||||
# waveform_store.save_imported_bw.
|
||||
ev.record_type = derive_record_type_from_filename(path.name)
|
||||
ev.record_type = derive_record_type_from_filename(name)
|
||||
ev.rectime_seconds = strt_fields.get("rectime_seconds")
|
||||
ev.total_samples = strt_fields.get("total_samples")
|
||||
ev.pretrig_samples = strt_fields.get("pretrig_samples")
|
||||
@@ -999,11 +1021,21 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
|
||||
# * Histogram / undecodable: ts1 = the window start, which IS the event
|
||||
# time — keep it.
|
||||
# Discriminate by ``is_waveform_body`` (the codec), not the filename.
|
||||
#
|
||||
# ⚠ 2026-10-26 (measured): ts2 - record time is a second off on 260 of
|
||||
# prod's 1,394 waveforms (199 late, 61 early). A Blastware filename
|
||||
# carries Blastware's own time -- equal to the report's Event Time on
|
||||
# 1,330/1,330 -- so a waveform takes it when `name` is one, and ts2 -
|
||||
# record time only otherwise. Histograms stay on ts1 although it runs a
|
||||
# second early on 97%: in Blastware's timing a waveform and its histogram
|
||||
# share a second 209 times in prod's store, and events is unique on
|
||||
# (serial, timestamp).
|
||||
if is_waveform_body and ts2 is not None:
|
||||
_stop = datetime.datetime(ts2.year, ts2.month, ts2.day,
|
||||
ts2.hour, ts2.minute, ts2.second)
|
||||
_rt = _parse_record_time_seconds(raw)
|
||||
_trig = _stop - datetime.timedelta(seconds=_rt) if _rt is not None else _stop
|
||||
_trig = _bw.blastware_filename_time(name) or _trig
|
||||
ev.timestamp = Timestamp(
|
||||
raw=footer[10:18],
|
||||
flag=0x10,
|
||||
|
||||
@@ -40,6 +40,7 @@ import uuid
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from minimateplus.blastware_file import blastware_filename_time
|
||||
from minimateplus.models import Event, MonitorLogEntry
|
||||
|
||||
log = logging.getLogger("sfm.database")
|
||||
@@ -397,6 +398,12 @@ class SeismoDb:
|
||||
existing row so a re-download via the live endpoint refreshes the
|
||||
file metadata.
|
||||
|
||||
An event whose stored file already has a row under a different time is
|
||||
the same event re-stored with a corrected time (the waveform event-time
|
||||
fix moved Series-3 waveforms from the session start to the trigger):
|
||||
that row is moved to the new time in place, keeping its id and review,
|
||||
rather than duplicated. See ``_restamp_by_file``.
|
||||
|
||||
``device_family`` (optional): "series3" (MiniMate Plus / Blastware) or
|
||||
"series4" (Micromate / Thor). Drives per-family UI rendering — most
|
||||
importantly the mic-unit convention (psi vs dB(L)). Set on every
|
||||
@@ -425,6 +432,11 @@ class SeismoDb:
|
||||
pi = ev.project_info
|
||||
rec = wave_recs.get(key) or {}
|
||||
|
||||
if rec.get("filename") and ts and \
|
||||
self._restamp_by_file(conn, serial, rec["filename"], ts) is False:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -582,6 +594,52 @@ class SeismoDb:
|
||||
serial, inserted, skipped)
|
||||
return inserted, skipped
|
||||
|
||||
@staticmethod
|
||||
def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str,
|
||||
ts: str) -> Optional[bool]:
|
||||
"""Move this file's row to `ts` when it sits under another time.
|
||||
|
||||
The events table is unique on (serial, timestamp), so an event re-stored
|
||||
with a corrected time -- every Series-3 waveform after the event-time fix,
|
||||
through the release backfill or a watcher re-forward -- matched nothing
|
||||
and was inserted a second time (measured 2026-10-26). The same stored
|
||||
file is the same event: a Blastware name encodes the serial and the time
|
||||
to the second. Any other name says nothing -- every unnamed upload is
|
||||
stored as "imported.bw" -- so only a Blastware name is matched. Of
|
||||
several rows for one file, a reviewed one with a time moves first.
|
||||
|
||||
Returns True when the row was moved; None when there was nothing to move
|
||||
(no row for this file elsewhere, or this file's own row already holds
|
||||
`ts`), so the caller goes on as before; False when a different stored
|
||||
file holds `ts` -- moving would collide, and the old upsert would write
|
||||
this event over that one -- so the caller must store nothing.
|
||||
"""
|
||||
if blastware_filename_time(filename) is None:
|
||||
return None
|
||||
mine = conn.execute(
|
||||
"SELECT id, timestamp FROM events WHERE serial = ? AND blastware_filename = ? "
|
||||
"AND (timestamp IS NULL OR timestamp != ?) "
|
||||
"ORDER BY COALESCE(false_trigger, 0) DESC, timestamp IS NULL, rowid LIMIT 1",
|
||||
(serial, filename, ts),
|
||||
).fetchone()
|
||||
if mine is None:
|
||||
return None
|
||||
holder = conn.execute(
|
||||
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
|
||||
(serial, ts),
|
||||
).fetchone()
|
||||
if holder is None:
|
||||
conn.execute("UPDATE events SET timestamp = ? WHERE id = ?", (ts, mine[0]))
|
||||
log.info("insert_events: %s %s moved from %s to %s (corrected event time)",
|
||||
serial, filename, mine[1], ts)
|
||||
return True
|
||||
if holder[1] in (None, filename):
|
||||
return None
|
||||
log.warning("insert_events: %s %s decodes to %s, which %s already holds -- "
|
||||
"row %s left at %s, nothing stored", serial, filename, ts, holder[1],
|
||||
mine[0], mine[1])
|
||||
return False
|
||||
|
||||
def get_event(self, event_id: str) -> Optional[dict]:
|
||||
"""Return one event row by id, or None."""
|
||||
with self._connect() as conn:
|
||||
|
||||
@@ -330,7 +330,7 @@ class WaveformStore:
|
||||
tmp.write(bw_bytes)
|
||||
tmp_path = Path(tmp.name)
|
||||
try:
|
||||
ev = event_file_io.read_blastware_file(tmp_path)
|
||||
ev = event_file_io.read_blastware_file(tmp_path, name=source_path.name)
|
||||
finally:
|
||||
try:
|
||||
tmp_path.unlink()
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,105 @@
|
||||
"""A Series-3 waveform's time comes from its Blastware filename, which is Blastware's own.
|
||||
|
||||
A Blastware name encodes the event time to the second (stem + AB, see
|
||||
`blastware_filename`). 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_takes_its_names_time_not_the_binarys():
|
||||
# BE9441, 2026-10-26: the binary says 14:23:43, Blastware (and the name) 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_is_told_its_real_one(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, 43)
|
||||
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")]
|
||||
@@ -0,0 +1,158 @@
|
||||
"""A re-stored event whose decoded time changed must correct its row, not duplicate it.
|
||||
|
||||
The waveform event-time fix (a84a46e / 1e76d08) changed what time a Series-3
|
||||
waveform decodes to: the trigger, where v0.31.0 stamped the monitoring-session
|
||||
start -- hours off. The events table is unique on (serial, timestamp), so every
|
||||
store path that re-saves an old event (the release backfill, a watcher
|
||||
re-forward) found no row at the corrected time and inserted a second one: the
|
||||
event twice, once at each time, its review state on the old copy only.
|
||||
Measured 2026-10-26 by storing real files with v0.31.0 and backfilling with dev.
|
||||
|
||||
A row is the same event when it holds the same stored file (serial +
|
||||
blastware_filename -- a Blastware name encodes the serial and the time to the
|
||||
second). insert_events now moves that row to the corrected time in place.
|
||||
"""
|
||||
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.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"
|
||||
WAVEFORM = FIX / "fft-oracle-2026-09-14" / "N844LQHB.ZT0W"
|
||||
OLD_TIME = "2026-08-25T06:00:13" # what v0.31.0 stored: the session start
|
||||
NEW_TIME = "2026-08-25T10:33:29" # the trigger, which the decoder now gives
|
||||
|
||||
|
||||
def _event(when: str, key: str = "0111646a", pvs: float = 0.5) -> Event:
|
||||
t = datetime.datetime.fromisoformat(when)
|
||||
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)
|
||||
ev._waveform_key = bytes.fromhex(key)
|
||||
ev.peak_values = PeakValues(tran=0.1, vert=0.2, long=0.3, peak_vector_sum=pvs, micl=None)
|
||||
return ev
|
||||
|
||||
|
||||
def _store(db: SeismoDb, ev: Event, filename: str = "N844LQHB.ZT0W") -> tuple:
|
||||
return db.insert_events([ev], serial="BE12844", device_family="series3",
|
||||
waveform_records={ev._waveform_key.hex(): {"filename": filename}})
|
||||
|
||||
|
||||
def _rows(db: SeismoDb) -> list:
|
||||
with sqlite3.connect(str(db.db_path)) as c:
|
||||
c.row_factory = sqlite3.Row
|
||||
return [dict(r) for r in c.execute(
|
||||
"SELECT * FROM events ORDER BY blastware_filename, timestamp")]
|
||||
|
||||
|
||||
def test_a_restored_event_at_a_corrected_time_moves_its_row(tmp_path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
_store(db, _event(OLD_TIME))
|
||||
(old,) = _rows(db)
|
||||
db.set_false_trigger(old["id"], True) # an operator's review
|
||||
|
||||
assert _store(db, _event(NEW_TIME, pvs=0.7)) == (0, 1) # nothing new inserted
|
||||
|
||||
(row,) = _rows(db)
|
||||
assert row["timestamp"] == NEW_TIME
|
||||
assert row["id"] == old["id"] # the same row ...
|
||||
assert row["false_trigger"] == 1 # ... its review kept
|
||||
assert row["peak_vector_sum"] == 0.7 # and refreshed as before
|
||||
|
||||
|
||||
def test_a_different_file_is_still_a_different_event(tmp_path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
_store(db, _event(OLD_TIME))
|
||||
_store(db, _event(NEW_TIME, key="01118a2c"), filename="N844LQHC.000W")
|
||||
assert [(r["blastware_filename"], r["timestamp"]) for r in _rows(db)] == [
|
||||
("N844LQHB.ZT0W", OLD_TIME), ("N844LQHC.000W", NEW_TIME)]
|
||||
|
||||
|
||||
def test_an_event_without_a_stored_file_is_matched_on_time_alone_as_before(tmp_path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
ev = _event(OLD_TIME)
|
||||
db.insert_events([ev], serial="BE12844", device_family="series3")
|
||||
db.insert_events([_event(NEW_TIME)], serial="BE12844", device_family="series3")
|
||||
assert [r["timestamp"] for r in _rows(db)] == [OLD_TIME, NEW_TIME]
|
||||
|
||||
|
||||
def test_a_corrected_time_held_by_another_file_moves_nothing_and_overwrites_nothing(tmp_path):
|
||||
# Another stored file already holds the corrected second. Moving onto it
|
||||
# would break the unique key, and the old upsert wrote this event's file and
|
||||
# peaks over THAT row. Now neither row changes.
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
_store(db, _event(OLD_TIME))
|
||||
_store(db, _event(NEW_TIME, key="01118a2c", pvs=0.9), filename="N844LQHC.000W")
|
||||
assert _store(db, _event(NEW_TIME)) == (0, 1)
|
||||
assert [(r["blastware_filename"], r["timestamp"], r["peak_vector_sum"]) for r in _rows(db)] == [
|
||||
("N844LQHB.ZT0W", OLD_TIME, 0.5), ("N844LQHC.000W", NEW_TIME, 0.9)]
|
||||
|
||||
|
||||
def test_a_duplicate_already_at_the_corrected_time_is_refreshed_as_before(tmp_path):
|
||||
# A box that already ran the new decoder holds the event twice; the row at
|
||||
# the corrected time is this file's own, so the usual refresh lands on it.
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
_store(db, _event(OLD_TIME))
|
||||
with sqlite3.connect(str(db.db_path)) as c:
|
||||
c.execute("UPDATE events SET blastware_filename = 'x'")
|
||||
_store(db, _event(NEW_TIME))
|
||||
with sqlite3.connect(str(db.db_path)) as c:
|
||||
c.execute("UPDATE events SET blastware_filename = 'N844LQHB.ZT0W'")
|
||||
assert _store(db, _event(NEW_TIME, pvs=0.8)) == (0, 1)
|
||||
assert [(r["timestamp"], r["peak_vector_sum"]) for r in _rows(db)] == [
|
||||
(OLD_TIME, 0.5), (NEW_TIME, 0.8)]
|
||||
|
||||
|
||||
def test_the_release_backfill_corrects_a_v031_row_in_place(tmp_path):
|
||||
"""The deploy step itself: a row as v0.31.0 stored it, then backfill_sidecars."""
|
||||
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))
|
||||
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: # as prod holds it today
|
||||
c.execute("UPDATE events SET timestamp = ?", (OLD_TIME,))
|
||||
(old,) = _rows(db)
|
||||
db.set_false_trigger(old["id"], True)
|
||||
|
||||
assert backfill.main(["--store-root", str(tmp_path / "waveforms"),
|
||||
"--db-path", str(db.db_path), "--force"]) == 0
|
||||
|
||||
(row,) = _rows(db)
|
||||
assert (row["id"], row["timestamp"], row["false_trigger"]) == (old["id"], NEW_TIME, 1)
|
||||
|
||||
|
||||
def test_a_generic_upload_name_is_not_one_event(tmp_path):
|
||||
# Unnamed uploads are all stored as "imported.bw": two different events can
|
||||
# share it. Only a Blastware name says which event a row is.
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
_store(db, _event(OLD_TIME), filename="imported.bw")
|
||||
_store(db, _event(NEW_TIME, key="01118a2c"), filename="imported.bw")
|
||||
assert [r["timestamp"] for r in _rows(db)] == [OLD_TIME, NEW_TIME]
|
||||
|
||||
|
||||
def test_of_two_copies_the_reviewed_one_with_a_time_is_the_one_moved(tmp_path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
db.insert_events([_event(OLD_TIME)], serial="BE12844", device_family="series3",
|
||||
waveform_records={"0111646a": {"filename": "N844LQHB.ZT0W"}})
|
||||
with sqlite3.connect(str(db.db_path)) as c: # an older copy with no time
|
||||
c.execute("INSERT INTO events (id, serial, waveform_key, timestamp, blastware_filename) "
|
||||
"VALUES ('untimed', 'BE12844', '0111646a', NULL, 'N844LQHB.ZT0W')")
|
||||
c.execute("UPDATE events SET rowid = 0 WHERE id = 'untimed'")
|
||||
reviewed = next(r["id"] for r in _rows(db) if r["timestamp"] == OLD_TIME)
|
||||
db.set_false_trigger(reviewed, True)
|
||||
|
||||
_store(db, _event(NEW_TIME))
|
||||
|
||||
moved = {r["id"]: r["timestamp"] for r in _rows(db)}
|
||||
assert moved[reviewed] == NEW_TIME and moved["untimed"] is None
|
||||
@@ -0,0 +1,93 @@
|
||||
"""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():
|
||||
block = _bw_report_to_dict(parse_report(_report('"Event Date : 2026-08-25"')))
|
||||
ev = read_blastware_file(WAVEFORM)
|
||||
assert _tuple(ev.timestamp) == datetime.datetime(2026, 8, 25, 10, 33, 29) # the binary's
|
||||
apply_bw_report_dict_to_event(ev, json.loads(json.dumps(block))) # as a sidecar holds it
|
||||
assert _tuple(ev.timestamp) == REPORT_TIME
|
||||
|
||||
|
||||
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_its_reports_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)."""
|
||||
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() == [(REPORT_TIME.isoformat(),)]
|
||||
assert json.loads(car.read_text())["event"]["timestamp"] == REPORT_TIME.isoformat()
|
||||
Reference in new issue
Block a user