From 847900baeb591a403add6174700921b5bebc5227 Mon Sep 17 00:00:00 2001 From: serversdown Date: Mon, 26 Oct 2026 18:18:23 -0400 Subject: [PATCH 1/3] fix(sfm): a re-stored event at a corrected time moves its row instead of duplicating it The waveform event-time fix (a84a46e / 1e76d08, on dev since 2026-09-20) changed what time a Series-3 waveform decodes to: the trigger, where v0.31.0 stamped the monitoring-session start -- hours off. events is unique on (serial, timestamp), so re-storing an old event at its corrected time matched nothing and inserted it a second time. Measured 2026-10-26: files stored with v0.31.0 (prod's code), then dev's backfill_sidecars --force -- the release's own deploy step -- gave every waveform two rows, one at each time. N844LQHB.ZT0W (BE12844): 06:00:13 and 10:33:29, its false-trigger mark only on the wrong-time copy. A Blastware re-forward of an old event would do the same with no backfill at all. Prod has not run the new decoder, so it holds no duplicates yet. insert_events now matches a row by its stored file first (serial + blastware_filename; a Blastware name encodes the serial and the second): one under another time is moved to the new time in place -- same id, review kept -- and the usual refresh follows. When a different stored file already holds the corrected second, nothing moves and nothing is written; the old upsert wrote this event's file and peaks over that other event's row. Rows with no stored file are matched on time alone, as before. Tests: the move (id, review, refresh), a different file, no file, the collision, a duplicate already at the new time, and the release backfill end to end on a v0.31.0-shaped row. Re-checked across versions: v0.31.0 import, then this branch's backfill -- 5 real files, every row corrected in place, no duplicates. Suite: only the 16 known fixture failures. No schema change, no migration, no codec change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL --- sfm/database.py | 52 ++++++++++++++ tests/test_event_restamp.py | 132 ++++++++++++++++++++++++++++++++++++ 2 files changed, 184 insertions(+) create mode 100644 tests/test_event_restamp.py diff --git a/sfm/database.py b/sfm/database.py index b2ebf08..89b3141 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -397,6 +397,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 +431,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 +593,47 @@ 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. + + 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. + """ + mine = conn.execute( + "SELECT id, timestamp FROM events WHERE serial = ? AND blastware_filename = ? " + "AND (timestamp IS NULL OR timestamp != ?) ORDER BY 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: diff --git a/tests/test_event_restamp.py b/tests/test_event_restamp.py new file mode 100644 index 0000000..3e1b2ab --- /dev/null +++ b/tests/test_event_restamp.py @@ -0,0 +1,132 @@ +"""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) From abb671a44037243c2af29480122083c13ec94577 Mon Sep 17 00:00:00 2001 From: serversdown Date: Mon, 26 Oct 2026 18:26:26 -0400 Subject: [PATCH 2/3] fix(decode): a paired report's event time is read in ISO form and survives a backfill The event-time fix makes a Blastware report's Event Time + Event Date authoritative over the binary, which gives the trigger only to the second. On prod's own data it never applied (measured on the 2026-09-30 store snapshot, all 81 report-paired Series-3 waveforms): - every one of those reports writes Event Date as ISO ('2026-08-14'); _parse_event_date read only 'August 14, 2026', so event_datetime was None (Brian's own laptop writes the long form -- it follows the PC's settings); - the sidecar's bw_report block never stored the event time, and apply_bw_report_dict_to_event -- the backfill's overlay -- never set it. The binary's trigger matched Blastware's printed time on 66 of the 81 and was a second late on 15; 8 of those 15 hold the right time in prod today, so the release backfill would have made them a second worse. - _parse_event_date accepts ISO dates too (81/81 now parse to the time Blastware printed; 0/81 before). - _bw_report_to_dict stores event_datetime (additive key). - apply_bw_report_dict_to_event applies it, as apply_report_to_event does. Prod's sidecars were written by the old parser, so the deploy runs backfill_sidecars.py with --reparse-txt to re-read the saved .TXTs. Tests: both date forms, the round trip through the saved block, a block with no time, and the backfill (--force --reparse-txt) on a prod-shaped row. Suite: only the 16 known fixture failures. Codec-library change (report parser): TOOL_VERSION to be bumped at release. No schema or DB migration. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL --- minimateplus/bw_ascii_report.py | 13 +++-- minimateplus/event_file_io.py | 17 ++++++ tests/test_report_event_time.py | 93 +++++++++++++++++++++++++++++++++ 3 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 tests/test_report_event_time.py diff --git a/minimateplus/bw_ascii_report.py b/minimateplus/bw_ascii_report.py index 2f919c4..9a9d17e 100644 --- a/minimateplus/bw_ascii_report.py +++ b/minimateplus/bw_ascii_report.py @@ -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) diff --git a/minimateplus/event_file_io.py b/minimateplus/event_file_io.py index a00d02c..37d2b46 100644 --- a/minimateplus/event_file_io.py +++ b/minimateplus/event_file_io.py @@ -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: diff --git a/tests/test_report_event_time.py b/tests/test_report_event_time.py new file mode 100644 index 0000000..8de8004 --- /dev/null +++ b/tests/test_report_event_time.py @@ -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() From 3948dc1a3c08d8342dad9b4afb8dd654c7a22eb6 Mon Sep 17 00:00:00 2001 From: serversdown Date: Mon, 26 Oct 2026 19:15:59 -0400 Subject: [PATCH 3/3] fix(decode): a Series-3 waveform's time comes from its Blastware filename The review of this branch measured (and I re-measured) that the binary's trigger -- ts2 minus the record time, from 1e76d08 -- is a second off on 260 of prod's 1,394 waveforms (2026-09-30 snapshot): 199 late, 61 early. A Blastware filename encodes Blastware's own time to the second: it equals the report's Event Time on 81/81 prod and 1,249/1,249 DL2 report-paired waveforms. The cost of the second was real, not cosmetic: - events is unique on (serial, timestamp), and on BE9558 the 61 early waveforms land on their histogram twin's second -- a fresh import wrote each waveform over its histogram's row (888 files -> 827 rows on dev); - the release backfill would have moved 161 prod rows that v0.31.0 already had exactly right a second off. Same-second collisions across all 11,827 prod-snapshot files: 61 with the binary's times, 0 with waveform names. 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 with both on Blastware's times a waveform and its histogram share a second 209 times -- the key cannot hold that. Correcting histogram times needs the key changed; not here. - blastware_file.blastware_filename_time(): the inverse of blastware_filename(), V10.72 'AB0' names only, None for anything else. - read_blastware_file(path, *, name=None): a waveform takes the name's time; save_imported_bw passes the upload's real name (it reads a temp file). - insert_events' restamp matches only Blastware names (every unnamed upload is 'imported.bw', so two events could share it) and, of several copies, moves a reviewed one with a time first (review items M1, M2). Tests: the decoder (documented names, encoder round trip, other names), a waveform's name time, a temp-named read, histograms unchanged, the twin collision on BE9441's own ZI0 (binary 14:23:43, Blastware 14:23:42), and both review items. 5 mutants, each caught. Suite: only the 16 known failures. Codec-library change: TOOL_VERSION to be bumped at release. No schema change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL --- minimateplus/blastware_file.py | 26 +++++ minimateplus/event_file_io.py | 21 +++- sfm/database.py | 10 +- sfm/waveform_store.py | 2 +- .../blastware/K441LTOF.ZI0 | Bin 0 -> 35390 bytes tests/test_bw_filename_time.py | 105 ++++++++++++++++++ tests/test_event_restamp.py | 26 +++++ 7 files changed, 184 insertions(+), 6 deletions(-) create mode 100644 tests/fixtures/minimate-bench-10-26-26-blastware/blastware/K441LTOF.ZI0 create mode 100644 tests/test_bw_filename_time.py diff --git a/minimateplus/blastware_file.py b/minimateplus/blastware_file.py index 2784040..8ca5c9a 100644 --- a/minimateplus/blastware_file.py +++ b/minimateplus/blastware_file.py @@ -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`: `.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. diff --git a/minimateplus/event_file_io.py b/minimateplus/event_file_io.py index 37d2b46..0b0aa14 100644 --- a/minimateplus/event_file_io.py +++ b/minimateplus/event_file_io.py @@ -859,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 @@ -878,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") @@ -998,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") @@ -1016,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, diff --git a/sfm/database.py b/sfm/database.py index 89b3141..12c5aa3 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -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") @@ -603,7 +604,9 @@ class SeismoDb: 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. + 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 @@ -611,9 +614,12 @@ class SeismoDb: 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 rowid LIMIT 1", + "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: diff --git a/sfm/waveform_store.py b/sfm/waveform_store.py index 01f6d66..7b26682 100644 --- a/sfm/waveform_store.py +++ b/sfm/waveform_store.py @@ -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() diff --git a/tests/fixtures/minimate-bench-10-26-26-blastware/blastware/K441LTOF.ZI0 b/tests/fixtures/minimate-bench-10-26-26-blastware/blastware/K441LTOF.ZI0 new file mode 100644 index 0000000000000000000000000000000000000000..8630f0fc64afe3e5b33c7b2ebe8833796cc182e2 GIT binary patch literal 35390 zcma)_f3RKGRo~BfezvaVYu)qY7v~XFzbpAAyadHk904vkL?uom69b-D`B9o_aJT=e z?w*rxIk~*tul@Aley!_%_hi5R=ew?3>AIem)#0wquAlXbVQ10tw_9xX{tn$vw=>%u zJkQBthnAC_Szb4I<>KJw&2D4ZpzRD9kwClKIy&_`GX~(a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FMRQjpZf}*e0utZ`LV07-ZQy&?{(AZ_51ei<6k@CXYI-lZ)UR@SFWE< zue&bgIQzueC!g@=96wJzb@AfGOHVJC zGva8}ss4eK}Dz}vO`Ym7hJH@p7&>#v*cz3$p;uiZ1*bImY0g-wig`||R|b7!A? z{1cz}#ACns*eCq&?Bi$8o;~-(xeMnmE@?4cESC$?6B&20cJm>A_8(#>hI7M^45z`v ze%`Jf_p>qmKe?&<(wDJq^85S0>Fx7ln06h$;vbM7*7onmHhwT`f9%@NkPM7v`=*$NzxKvo z@BE=tcf8@y!G1Qobn)D|C!aWb_Hlk5dyGG4@!6A4ox6a?*o9s$y0ta&zO7%;Bs{i% n|G`5bw$>jcvv)!_KIihcZtPyRZ!)s`mE-GCtR)F<-uV9jrxTUM literal 0 HcmV?d00001 diff --git a/tests/test_bw_filename_time.py b/tests/test_bw_filename_time.py new file mode 100644 index 0000000..244b8ee --- /dev/null +++ b/tests/test_bw_filename_time.py @@ -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")] diff --git a/tests/test_event_restamp.py b/tests/test_event_restamp.py index 3e1b2ab..98b7013 100644 --- a/tests/test_event_restamp.py +++ b/tests/test_event_restamp.py @@ -130,3 +130,29 @@ def test_the_release_backfill_corrects_a_v031_row_in_place(tmp_path): (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