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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-03 21:29:46 -05:00
1 parent e8242aaadc
commit ea2dfc21b7
3 files changed
+193 -23

No files matched your search

+65 -19
View File
@@ -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