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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
This commit is contained in:
1 parent
6690434ecf
commit
847900baeb
2 files changed
+184
No files matched your search
@@ -397,6 +397,12 @@ class SeismoDb:
|
|||||||
existing row so a re-download via the live endpoint refreshes the
|
existing row so a re-download via the live endpoint refreshes the
|
||||||
file metadata.
|
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
|
``device_family`` (optional): "series3" (MiniMate Plus / Blastware) or
|
||||||
"series4" (Micromate / Thor). Drives per-family UI rendering — most
|
"series4" (Micromate / Thor). Drives per-family UI rendering — most
|
||||||
importantly the mic-unit convention (psi vs dB(L)). Set on every
|
importantly the mic-unit convention (psi vs dB(L)). Set on every
|
||||||
@@ -425,6 +431,11 @@ class SeismoDb:
|
|||||||
pi = ev.project_info
|
pi = ev.project_info
|
||||||
rec = wave_recs.get(key) or {}
|
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:
|
try:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
@@ -582,6 +593,47 @@ class SeismoDb:
|
|||||||
serial, inserted, skipped)
|
serial, inserted, skipped)
|
||||||
return 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]:
|
def get_event(self, event_id: str) -> Optional[dict]:
|
||||||
"""Return one event row by id, or None."""
|
"""Return one event row by id, or None."""
|
||||||
with self._connect() as conn:
|
with self._connect() as conn:
|
||||||
|
|||||||
@@ -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)
|
||||||
Reference in new issue
Block a user