From ea2dfc21b71f037f9d97a631f249abe08e437bcc Mon Sep 17 00:00:00 2001 From: serversdown Date: Tue, 3 Nov 2026 21:29:46 -0500 Subject: [PATCH] feat(db): events are identified by unit + time + type (#51) The events table was UNIQUE(serial, timestamp): one event per unit per second. A unit records a waveform and a histogram in the same second legitimately -- 209 times in prod's 2026-09-30 store once histograms carry Blastware's start -- so the key is now (serial, timestamp, record_type). Agreed with Brian 2026-11-03. - Migration 3 rebuilds the table from its own current definition with only the key swapped, in one transaction: every column, row and id is kept (Terra-View reads rows by id) and the indexes are recreated. Migration 1's check no longer mistakes the new key for a missing one. - The upsert, the estimate guard and the restamp match on the type too. The restamp also re-types a file's own row in place: before v0.33.0 a row's type came from the filename, and a re-import under the file's own type must not add a second row. - An untyped event still refreshes the untyped row at its second (a UNIQUE key treats NULLs as distinct). - scripts/repair_unknown_serials.py checks the new key. No time changes yet: that is the next commit, and they ship together. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9 --- scripts/repair_unknown_serials.py | 9 ++- sfm/database.py | 84 +++++++++++++++----- tests/test_event_key.py | 123 ++++++++++++++++++++++++++++++ 3 files changed, 193 insertions(+), 23 deletions(-) create mode 100644 tests/test_event_key.py diff --git a/scripts/repair_unknown_serials.py b/scripts/repair_unknown_serials.py index 132bab9..5162573 100644 --- a/scripts/repair_unknown_serials.py +++ b/scripts/repair_unknown_serials.py @@ -73,7 +73,7 @@ def main(argv: list[str] | None = None) -> int: conn.row_factory = sqlite3.Row rows = list(conn.execute( - "SELECT id, serial, timestamp, blastware_filename " + "SELECT id, serial, timestamp, record_type, blastware_filename " " FROM events " " WHERE serial = 'UNKNOWN' " " ORDER BY timestamp", @@ -98,10 +98,11 @@ def main(argv: list[str] | None = None) -> int: unresolved += 1 continue - # Check for an existing row at the target (serial, timestamp). + # Check for an existing row at the target key (serial, timestamp, + # record_type -- #51). existing = conn.execute( - "SELECT id FROM events WHERE serial = ? AND timestamp = ?", - (new_serial, ts), + "SELECT id FROM events WHERE serial = ? AND timestamp = ? AND record_type IS ?", + (new_serial, ts, row["record_type"]), ).fetchone() action: str if existing is None: diff --git a/sfm/database.py b/sfm/database.py index 76ee65c..1ade723 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -35,6 +35,7 @@ from __future__ import annotations import datetime import logging +import re import sqlite3 import uuid from pathlib import Path @@ -106,7 +107,7 @@ CREATE TABLE IF NOT EXISTS events ( shape_offset_pre REAL, -- pre-trigger baseline median (in/s) shape_offset_spread REAL, -- max(pre,mid,end) - min(...) in in/s; small = constant/DC created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), - UNIQUE(serial, timestamp) + UNIQUE(serial, timestamp, record_type) -- unit + time + type (#51); see Migration 3 ); CREATE INDEX IF NOT EXISTS idx_events_serial ON events(serial); CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp); @@ -172,7 +173,7 @@ class SeismoDb: row = conn.execute( "SELECT sql FROM sqlite_master WHERE type='table' AND name='events'" ).fetchone() - if row and "UNIQUE(serial, timestamp)" not in row[0]: + if row and "UNIQUE(serial, timestamp" not in row[0]: # neither key form yet log.info("_migrate: rebuilding events table — UNIQUE(serial, timestamp)") conn.executescript(""" ALTER TABLE events RENAME TO events_old; @@ -315,6 +316,33 @@ class SeismoDb: """) log.info("_migrate: monitor_log table rebuilt OK") + # Migration 3 (#51, 2026-11-03): events UNIQUE (serial, timestamp) -> + # (serial, timestamp, record_type). A unit records a waveform and a + # histogram in the same second legitimately -- 209 times in prod's + # 2026-09-30 store once histograms carry Blastware's start -- and the old + # key could hold only one. The table is rebuilt from its own current + # definition with only the key swapped, so every column added by the + # migrations above, every row and every id is kept (Terra-View reads + # rows by id); its indexes are recreated. One transaction. + row = conn.execute( + "SELECT sql FROM sqlite_master WHERE type='table' AND name='events'" + ).fetchone() + if row and "UNIQUE(serial, timestamp)" in row[0]: + log.info("_migrate: rebuilding events table — UNIQUE(serial, timestamp, record_type)") + indexes = [r[0] for r in conn.execute( + "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name='events' " + "AND sql IS NOT NULL")] + table = re.sub(r'^CREATE TABLE\s+("?)events\1', "CREATE TABLE events_rekeyed", + row[0].replace("UNIQUE(serial, timestamp)", + "UNIQUE(serial, timestamp, record_type)", 1)) + conn.executescript("BEGIN;\n" + table + ";\n" + "INSERT INTO events_rekeyed SELECT * FROM events;\n" + "DROP TABLE events;\n" + "ALTER TABLE events_rekeyed RENAME TO events;\n" + + "".join(sql + ";\n" for sql in indexes) + + "COMMIT;") + log.info("_migrate: events table re-keyed OK (%d indexes recreated)", len(indexes)) + @staticmethod def _iso(dt: Optional[datetime.datetime]) -> Optional[str]: return dt.isoformat() if dt is not None else None @@ -385,7 +413,8 @@ class SeismoDb: device_family: Optional[str] = None, ) -> tuple[int, int]: """ - Insert triggered events. Silently skips duplicates (serial+timestamp). + Insert triggered events. Silently skips duplicates (serial + timestamp + + record_type: a waveform and a histogram may share a second, #51). Returns (inserted, skipped). ``waveform_records`` (optional): dict keyed by event waveform_key (hex) @@ -393,7 +422,7 @@ class SeismoDb: {"filename": str, "filesize": int, "a5_pickle_filename": str} For events whose key is in this dict, the matching columns are - populated. If a row with the same (serial, timestamp) already exists + populated. If a row with the same (serial, timestamp, record_type) already exists (dedup hit), the matching waveform record is upserted onto the existing row so a re-download via the live endpoint refreshes the file metadata. @@ -436,18 +465,27 @@ class SeismoDb: # 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) + why = self._estimate_guard(conn, serial, rec.get("filename"), ts, + ev.record_type) 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, + ev.record_type) is False: skipped += 1 continue try: + if ev.record_type is None and conn.execute( + "SELECT 1 FROM events WHERE serial = ? AND timestamp = ? " + "AND record_type IS NULL", (serial, ts)).fetchone(): + # A UNIQUE key treats NULLs as distinct, so an untyped + # event would never collide: it still refreshes the + # untyped row at its second, as under the old key. + raise sqlite3.IntegrityError("untyped event already stored") conn.execute( """ INSERT INTO events @@ -507,7 +545,7 @@ class SeismoDb: inserted += 1 except sqlite3.IntegrityError: skipped += 1 - # UPSERT path: a row for this (serial, timestamp) already + # UPSERT path: a row for this (serial, timestamp, record_type) already # exists. Refresh every device-authoritative field from # the new data so that a re-import with better data (e.g. # a watcher re-forward where the previous attempt missed @@ -560,7 +598,7 @@ class SeismoDb: shape_offset_axis = COALESCE(?, shape_offset_axis), shape_offset_pre = COALESCE(?, shape_offset_pre), shape_offset_spread = COALESCE(?, shape_offset_spread) - WHERE serial = ? AND timestamp = ? + WHERE serial = ? AND timestamp = ? AND record_type IS ? """, ( pv.tran if pv else None, @@ -597,6 +635,7 @@ class SeismoDb: rec.get("shape_offset_spread") if rec else None, serial, ts, + ev.record_type, ), ) @@ -606,11 +645,11 @@ class SeismoDb: @staticmethod def _estimate_guard(conn: sqlite3.Connection, serial: str, filename: Optional[str], - ts: Optional[str]) -> Optional[str]: + ts: Optional[str], record_type: Optional[str] = None) -> 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 + second off, and (serial, timestamp, record_type) 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 @@ -625,8 +664,8 @@ class SeismoDb: 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() + "SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ? " + "AND record_type IS ?", (serial, ts, record_type)).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") @@ -634,8 +673,9 @@ class SeismoDb: @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. + ts: str, record_type: Optional[str] = None) -> Optional[bool]: + """Move this file's row to `ts` (and `record_type`) when it sits under + another time or type. 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, @@ -646,6 +686,10 @@ class SeismoDb: 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. + The type moves the same way: before v0.33.0 a row's type came from the + filename, and with the type in the key (#51) a re-import under the file's + own type would otherwise add a second row. + 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 @@ -656,18 +700,20 @@ class SeismoDb: return None mine = conn.execute( "SELECT id, timestamp FROM events WHERE serial = ? AND blastware_filename = ? " - "AND (timestamp IS NULL OR timestamp != ?) " + "AND (timestamp IS NULL OR timestamp != ? OR record_type IS NOT ?) " "ORDER BY COALESCE(false_trigger, 0) DESC, timestamp IS NULL, rowid LIMIT 1", - (serial, filename, ts), + (serial, filename, ts, record_type), ).fetchone() if mine is None: return None holder = conn.execute( - "SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ?", - (serial, ts), + "SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ? " + "AND record_type IS ?", + (serial, ts, record_type), ).fetchone() if holder is None: - conn.execute("UPDATE events SET timestamp = ? WHERE id = ?", (ts, mine[0])) + conn.execute("UPDATE events SET timestamp = ?, record_type = ? WHERE id = ?", + (ts, record_type, mine[0])) log.info("insert_events: %s %s moved from %s to %s (corrected event time)", serial, filename, mine[1], ts) return True diff --git a/tests/test_event_key.py b/tests/test_event_key.py new file mode 100644 index 0000000..16ddda4 --- /dev/null +++ b/tests/test_event_key.py @@ -0,0 +1,123 @@ +"""An event is identified by unit + time + type (#51). + +The events table was unique on (serial, timestamp): one event per unit per +second. A unit records a waveform and a histogram in the same second +legitimately -- 209 times in prod's 2026-09-30 store once histograms carry +Blastware's start -- so the key is now (serial, timestamp, record_type). +Agreed with Brian 2026-11-03. +""" +from __future__ import annotations + +import datetime +import os +import sqlite3 +import sys + +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 + +T = "2026-08-25T10:33:29" +T_EARLY = "2026-08-25T10:33:28" + + +def _event(when: str, rtype: 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.record_type = rtype + 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) -> 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 timestamp, record_type")] + + +def _key_sql(db: SeismoDb) -> str: + with sqlite3.connect(str(db.db_path)) as c: + return c.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='events'" + ).fetchone()[0] + + +def test_a_waveform_and_a_histogram_can_share_a_second(tmp_path): + db = SeismoDb(tmp_path / "seismo_relay.db") + assert _store(db, _event(T, "Waveform"), "N844LQHB.ZT0W") == (1, 0) + assert _store(db, _event(T, "Histogram", key="0111700a"), "N844LQHB.ZT0H") == (1, 0) + assert [(r["timestamp"], r["record_type"]) for r in _rows(db)] == [ + (T, "Histogram"), (T, "Waveform")] + + +def test_the_same_event_twice_is_still_one_row(tmp_path): + db = SeismoDb(tmp_path / "seismo_relay.db") + _store(db, _event(T, "Histogram"), "N844LQHB.ZT0H") + assert _store(db, _event(T, "Histogram", pvs=0.8), "N844LQHB.ZT0H") == (0, 1) + (row,) = _rows(db) + assert row["peak_vector_sum"] == 0.8 # the upsert refreshed it + + +def test_a_histogram_moves_onto_its_waveforms_second(tmp_path): + # What the release backfill does: the histogram was stored a second early; + # its corrected start is the waveform's second. The row moves in place. + db = SeismoDb(tmp_path / "seismo_relay.db") + _store(db, _event(T, "Waveform"), "N844LQHB.ZT0W") + _store(db, _event(T_EARLY, "Histogram", key="0111700a"), "N844LQHB.ZS0H") + (before,) = [r for r in _rows(db) if r["record_type"] == "Histogram"] + assert _store(db, _event(T, "Histogram", key="0111700a"), "N844LQHB.ZS0H") == (0, 1) + rows = _rows(db) + assert [(r["timestamp"], r["record_type"]) for r in rows] == [(T, "Histogram"), (T, "Waveform")] + assert [r["id"] for r in rows if r["record_type"] == "Histogram"] == [before["id"]] + + +def test_a_re_typed_event_is_corrected_in_place(tmp_path): + # Before v0.33.0 the type came from the filename; a re-import with the + # file's own type must correct that row, not add a second one. + db = SeismoDb(tmp_path / "seismo_relay.db") + _store(db, _event(T, "Waveform"), "N844LQHB.ZT0H") + (before,) = _rows(db) + _store(db, _event(T, "Histogram"), "N844LQHB.ZT0H") + (row,) = _rows(db) + assert (row["id"], row["record_type"]) == (before["id"], "Histogram") + + +def test_an_old_database_is_migrated_keeping_every_row_and_id(tmp_path): + db = SeismoDb(tmp_path / "seismo_relay.db") + _store(db, _event(T, "Waveform"), "N844LQHB.ZT0W") + _store(db, _event(T_EARLY, "Histogram", key="0111700a"), "N844LQHB.ZS0H") + old_rows = _rows(db) + with sqlite3.connect(str(db.db_path)) as c: # put the old key back + sql = _key_sql(db).replace("UNIQUE(serial, timestamp, record_type)", + "UNIQUE(serial, timestamp)") + c.executescript(f""" + ALTER TABLE events RENAME TO events_new_key; + {sql}; + INSERT INTO events SELECT * FROM events_new_key; + DROP TABLE events_new_key; + """) + assert "UNIQUE(serial, timestamp)" in _key_sql(db) + + db = SeismoDb(tmp_path / "seismo_relay.db") # opening migrates + assert "UNIQUE(serial, timestamp, record_type)" in _key_sql(db) + assert _rows(db) == old_rows + assert _store(db, _event(T, "Histogram", key="0111700b"), "N844LQHC.ZT0H") == (1, 0) + with sqlite3.connect(str(db.db_path)) as c: + names = {r[0] for r in c.execute( + "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='events'")} + assert {"idx_events_serial", "idx_events_timestamp"} <= names + + +def test_reopening_keeps_the_new_key(tmp_path): + SeismoDb(tmp_path / "seismo_relay.db") + db = SeismoDb(tmp_path / "seismo_relay.db") + assert "UNIQUE(serial, timestamp, record_type)" in _key_sql(db)