fix(sfm): an estimated event time never overwrites, merges into or duplicates a row

Brian: keep an event whose time is only an estimate (no validated embedded
event record) -- never discard a measurement for want of an exact timestamp --
but it must not silently cause an overwrite, merge or dedup collision.

insert_events, for timestamp_source 'estimate' (_estimate_guard):
- never restamps (moves) a row;
- if its file (a Blastware name) is already stored under another time, writes
  nothing -- no second row, the stored time kept;
- if a different event already holds that second, writes nothing -- the old
  upsert would have written this event over that one;
- otherwise stores it, or refreshes its own row at the same second, as before.
Each refusal is a WARNING naming both sides; the file and sidecar (which says
'estimate' and carries the decode problem) are already in the store.  A generic
upload name ('imported.bw') is not taken as identity.

Tests: each rule, an estimate on a free second kept, generic names, and an
import end to end (a corrupted record next to a different event's second).
3 mutants, each caught.  Suite vs clean origin/dev: the same 16 failing tests,
failure reasons byte-identical; 582 passed vs 553.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-27 00:15:32 -04:00
1 parent f91949be89
commit 6cfcd04513
3 files changed
+114 -1

No files matched your search

+39 -1
View File
@@ -432,7 +432,17 @@ 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 \ if getattr(ev, "timestamp_source", None) == "estimate":
# No validated event record: the time may be a second off,
# so it is never allowed to move, merge into or duplicate
# a row (_estimate_guard). The file is already stored.
why = self._estimate_guard(conn, serial, rec.get("filename"), ts)
if why:
log.warning("insert_events: %s %s: %s", serial,
rec.get("filename") or key, why)
skipped += 1
continue
elif rec.get("filename") and ts and \
self._restamp_by_file(conn, serial, rec["filename"], ts) is False: self._restamp_by_file(conn, serial, rec["filename"], ts) is False:
skipped += 1 skipped += 1
continue continue
@@ -594,6 +604,34 @@ class SeismoDb:
serial, inserted, skipped) serial, inserted, skipped)
return inserted, skipped return inserted, skipped
@staticmethod
def _estimate_guard(conn: sqlite3.Connection, serial: str, filename: Optional[str],
ts: Optional[str]) -> Optional[str]:
"""Why an event whose time is only an estimate must not be written, or None.
An estimate (the decoder found no validated event record) may be a
second off, and (serial, timestamp) is the table's key. So it never
moves a row, never lands on another event's row, and never adds a second
row for an event already stored -- each refusal is logged by the caller,
and the event's file and sidecar are already in the store. Its own
row at the same second is refreshed as before; a free second is stored.
"""
named = filename if filename and blastware_filename_time(filename) is not None else None
if named:
own = [r[0] for r in conn.execute(
"SELECT timestamp FROM events WHERE serial = ? AND blastware_filename = ?",
(serial, named))]
if own and ts not in own:
return (f"already stored under {', '.join(str(t) for t in own)}; its estimated "
f"time {ts} does not move or duplicate it")
holder = conn.execute(
"SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
(serial, ts)).fetchone()
if holder is not None and (named is None or holder[0] != named):
return (f"its estimated time {ts} is held by {holder[0] or 'another event'}; "
"not merged into it")
return None
@staticmethod @staticmethod
def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str, def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str,
ts: str) -> Optional[bool]: ts: str) -> Optional[bool]:
+27
View File
@@ -165,3 +165,30 @@ def test_a_sidecar_carries_the_decode_problem():
blastware_filesize=0, blastware_sha256="", source_kind="bw-import") blastware_filesize=0, blastware_sha256="", source_kind="bw-import")
assert car["event"]["timestamp_source"] == "estimate" assert car["event"]["timestamp_source"] == "estimate"
assert "event record" in car["event"]["decode_problems"][0] assert "event record" in car["event"]["decode_problems"][0]
def test_an_imported_event_with_only_an_estimate_does_not_overwrite_its_neighbour(tmp_path, caplog):
import sqlite3
from minimateplus.models import Event, PeakValues, Timestamp
from sfm.database import SeismoDb
from sfm.waveform_store import WaveformStore
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
other = Event(index=0) # a different event at 14:23:43
other.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26,
hour=14, minute=23, second=43)
other._waveform_key = bytes.fromhex("01110000")
other.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None)
db.insert_events([other], serial="BE9441", device_family="series3",
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}})
broken = bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))) # no validated record
ev, rec = store.save_imported_bw(broken, source_path=Path(ZI0.name))
assert (_dt(ev.timestamp), ev.timestamp_source) == (ESTIMATE, "estimate")
with caplog.at_level(logging.WARNING):
assert db.insert_events([ev], serial="BE9441", device_family="series3",
waveform_records={ev._waveform_key.hex(): rec}) == (0, 1)
with sqlite3.connect(str(db.db_path)) as c:
assert c.execute("SELECT blastware_filename, peak_vector_sum FROM events").fetchall() == \
[("K441LTOF.ZJ0H", 0.04)]
assert (tmp_path / "waveforms" / "BE9441" / "K441LTOF.ZI0").exists() # the data is kept
assert any("not merged" in r.message for r in caplog.records)
+48
View File
@@ -15,6 +15,7 @@ second). insert_events now moves that row to the corrected time in place.
from __future__ import annotations from __future__ import annotations
import datetime import datetime
import logging
import os import os
import sqlite3 import sqlite3
import sys import sys
@@ -156,3 +157,50 @@ def test_of_two_copies_the_reviewed_one_with_a_time_is_the_one_moved(tmp_path):
moved = {r["id"]: r["timestamp"] for r in _rows(db)} moved = {r["id"]: r["timestamp"] for r in _rows(db)}
assert moved[reviewed] == NEW_TIME and moved["untimed"] is None assert moved[reviewed] == NEW_TIME and moved["untimed"] is None
# -- an estimated time (no validated event record) never overwrites, merges or
# duplicates; the event is still stored when its second is free --------------
def _estimated(when: str, key: str = "0111646a", pvs: float = 0.5) -> Event:
ev = _event(when, key, pvs)
ev.timestamp_source = "estimate"
return ev
def test_an_estimate_on_a_free_second_is_stored(tmp_path):
db = SeismoDb(tmp_path / "seismo_relay.db")
assert _store(db, _estimated(NEW_TIME)) == (1, 0)
assert [r["timestamp"] for r in _rows(db)] == [NEW_TIME]
def test_an_estimate_never_merges_into_another_events_row(tmp_path, caplog):
db = SeismoDb(tmp_path / "seismo_relay.db")
_store(db, _event(NEW_TIME, key="01118a2c", pvs=0.9), filename="N844LQHC.000W")
with caplog.at_level(logging.WARNING):
assert _store(db, _estimated(NEW_TIME)) == (0, 1)
assert [(r["blastware_filename"], r["peak_vector_sum"]) for r in _rows(db)] == [("N844LQHC.000W", 0.9)]
assert any("N844LQHC.000W" in r.message and "estimated" in r.message for r in caplog.records)
def test_an_estimate_never_moves_or_duplicates_its_own_stored_event(tmp_path, caplog):
db = SeismoDb(tmp_path / "seismo_relay.db")
_store(db, _event(NEW_TIME)) # stored at a validated time
with caplog.at_level(logging.WARNING):
assert _store(db, _estimated(OLD_TIME, pvs=0.7)) == (0, 1)
assert [(r["timestamp"], r["peak_vector_sum"]) for r in _rows(db)] == [(NEW_TIME, 0.5)]
assert any(NEW_TIME in r.message and "estimated" in r.message for r in caplog.records)
def test_an_estimate_on_its_own_rows_second_refreshes_it_as_before(tmp_path):
db = SeismoDb(tmp_path / "seismo_relay.db")
_store(db, _event(NEW_TIME))
assert _store(db, _estimated(NEW_TIME, pvs=0.7)) == (0, 1)
assert [(r["timestamp"], r["peak_vector_sum"]) for r in _rows(db)] == [(NEW_TIME, 0.7)]
def test_a_generic_upload_name_does_not_make_two_estimates_one_event(tmp_path):
db = SeismoDb(tmp_path / "seismo_relay.db")
_store(db, _estimated(OLD_TIME), filename="imported.bw")
assert _store(db, _estimated(NEW_TIME, key="01118a2c"), filename="imported.bw") == (1, 0)
assert len(_rows(db)) == 2