feat(mlg): store .MLG files and records, each record once

Two new tables, created on first start (no migration):
mlg_files (one row per file received, deduped by name + sha256) and
mlg_records (one row per log record, unique on serial, start, stop,
flag word and trigger source; COALESCE on the stop, since an open
record's NULL stop is distinct to a UNIQUE constraint).  The text is not
part of a record's identity: Blastware writes it, and two copies of the
same records differ there.  WaveformStore.save_mlg keeps the original
file byte for byte under <serial>/mlg/.

Operational consequence: two new tables on first start; no migration,
no backfill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-13 13:43:47 -05:00
1 parent a8adb03d23
commit 84d6cd05c3
3 files changed
+263 -3

No files matched your search

+152 -3
View File
@@ -1,11 +1,15 @@
"""
sfm/database.py — SQLite persistence layer for seismo-relay.
Three tables, all keyed by unit serial number:
Tables, all keyed by unit serial number:
ach_sessions — one row per inbound ACH call-home
events — one row per triggered waveform event (deduped by serial+timestamp)
monitor_log — one row per monitoring interval (deduped by serial+start_time)
monitor_log — one row per monitoring interval (deduped by serial+start_time);
live 0x0A reads by bridges/ach_server.py only
mlg_files — one row per Blastware .MLG received (deduped by file name+sha256)
mlg_records — one row per .MLG log record (deduped by serial, start, stop,
flag word, trigger source — never the text, which Blastware writes)
The DB file lives at:
<output_dir>/seismo_relay.db (default: bridges/captures/seismo_relay.db)
@@ -43,7 +47,7 @@ from pathlib import Path
from typing import Optional
from minimateplus.blastware_file import blastware_filename_time
from minimateplus.models import Event, MonitorLogEntry
from minimateplus.models import Event, MlgRecord, MonitorLogEntry
log = logging.getLogger("sfm.database")
@@ -150,6 +154,41 @@ CREATE TABLE IF NOT EXISTS device_commands (
states TEXT -- JSON: {"before": ..., "seen": [...], "after": ...}
);
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
-- Blastware monitor logs (.MLG): spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
-- Record times are the unit's own local clock (naive ISO); file_mtime is UTC (+00:00).
CREATE TABLE IF NOT EXISTS mlg_files (
id TEXT PRIMARY KEY,
serial TEXT, -- NULL: an empty file whose unit is not known yet
file_name TEXT NOT NULL,
sha256 TEXT NOT NULL,
size INTEGER NOT NULL,
record_count INTEGER NOT NULL, -- log records in the file (header excluded)
empty INTEGER NOT NULL, -- 1: the 18-byte prefix alone
call_in INTEGER NOT NULL DEFAULT 1, -- 0: a cable / direct download
file_mtime TEXT, -- the file's modified time, when the sender gave it
received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
stored_path TEXT, -- the original file, relative to the waveform store
UNIQUE(file_name, sha256)
);
CREATE INDEX IF NOT EXISTS idx_mlg_files_serial ON mlg_files(serial);
CREATE TABLE IF NOT EXISTS mlg_records (
id TEXT PRIMARY KEY,
serial TEXT NOT NULL,
start_time TEXT NOT NULL,
stop_time TEXT, -- NULL: "monitoring started", no stop yet
flags INTEGER NOT NULL, -- monitor-log flag word; 65535 = started
trigger_source INTEGER NOT NULL, -- 1-8 a channel, 1024 a histogram, 0 none
text TEXT,
trigger_level TEXT,
event_time TEXT,
file_id TEXT NOT NULL REFERENCES mlg_files(id), -- the file it first came in
seq INTEGER NOT NULL -- its position in that file (1 = first log record)
);
-- NULL stops are distinct to a UNIQUE constraint, so the identity uses COALESCE.
CREATE UNIQUE INDEX IF NOT EXISTS ux_mlg_records_identity
ON mlg_records(serial, start_time, COALESCE(stop_time, ''), flags, trigger_source);
"""
@@ -1259,6 +1298,116 @@ class SeismoDb:
).fetchall()
return [dict(r) for r in rows]
# ── Blastware monitor logs (.MLG) ─────────────────────────────────────────
def mlg_file_exists(self, file_name: str, sha256: str) -> bool:
with self._connect() as conn:
row = conn.execute(
"SELECT 1 FROM mlg_files WHERE file_name = ? AND sha256 = ?",
(file_name, sha256),
).fetchone()
return row is not None
def insert_mlg(
self,
*,
serial: Optional[str],
file_name: str,
sha256: str,
size: int,
empty: bool,
call_in: bool,
file_mtime: Optional[datetime.datetime],
stored_path: Optional[str],
records: list[MlgRecord],
) -> tuple[Optional[str], int, int]:
"""Store one .MLG file and its log records, in one transaction.
Returns (file_id, inserted, skipped); (None, 0, 0) when this file name
with these bytes is already stored. A record already stored (from an
earlier file) is skipped and keeps pointing at that file."""
file_id = self._new_id()
inserted = skipped = 0
with self._connect() as conn:
try:
conn.execute(
"""
INSERT INTO mlg_files
(id, serial, file_name, sha256, size, record_count, empty,
call_in, file_mtime, stored_path)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(file_id, serial, file_name, sha256, size, len(records), int(empty),
int(call_in), self._iso(file_mtime), stored_path),
)
except sqlite3.IntegrityError:
return None, 0, 0
for r in records:
cur = conn.execute(
"""
INSERT OR IGNORE INTO mlg_records
(id, serial, start_time, stop_time, flags, trigger_source,
text, trigger_level, event_time, file_id, seq)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(self._new_id(), serial, self._iso(r.start), self._iso(r.stop), r.flags,
r.trigger_source, r.text, r.trigger_level, self._iso(r.event_time),
file_id, r.index),
)
if cur.rowcount:
inserted += 1
else:
skipped += 1
log.debug("insert_mlg %s inserted=%d skipped=%d", file_name, inserted, skipped)
return file_id, inserted, skipped
def query_mlg_records(
self,
serial: str,
from_dt: Optional[datetime.datetime] = None,
to_dt: Optional[datetime.datetime] = None,
) -> list[dict]:
"""A unit's .MLG records, oldest first (start time, then position in file)."""
clauses, params = ["serial = ?"], [serial]
if from_dt:
clauses.append("start_time >= ?")
params.append(from_dt.isoformat())
if to_dt:
clauses.append("start_time <= ?")
params.append(to_dt.isoformat())
with self._connect() as conn:
rows = conn.execute(
f"SELECT * FROM mlg_records WHERE {' AND '.join(clauses)} "
f"ORDER BY start_time, seq",
params,
).fetchall()
return [dict(r) for r in rows]
def query_mlg_files(self, serial: str) -> list[dict]:
"""A unit's received .MLG files, oldest file time first."""
with self._connect() as conn:
rows = conn.execute(
"SELECT * FROM mlg_files WHERE serial = ? "
"ORDER BY COALESCE(file_mtime, received_at), file_name",
(serial,),
).fetchall()
return [dict(r) for r in rows]
def get_mlg_file(self, file_id: str) -> Optional[dict]:
with self._connect() as conn:
row = conn.execute("SELECT * FROM mlg_files WHERE id = ?", (file_id,)).fetchone()
return dict(row) if row else None
def known_serials(self) -> set[str]:
"""Every serial SFM holds data for: events, .MLG files and records."""
with self._connect() as conn:
rows = conn.execute(
"SELECT serial FROM events WHERE serial IS NOT NULL "
"UNION SELECT serial FROM mlg_files WHERE serial IS NOT NULL "
"UNION SELECT serial FROM mlg_records"
).fetchall()
return {r["serial"] for r in rows if r["serial"]}
# ── Fleet overview ────────────────────────────────────────────────────────
def query_units(self) -> list[dict]:
+17
View File
@@ -30,6 +30,7 @@ Roles:
from __future__ import annotations
import datetime
import hashlib
import logging
import pickle
import re
@@ -105,6 +106,22 @@ class WaveformStore:
d.mkdir(parents=True, exist_ok=True)
return d
def save_mlg(self, serial: Optional[str], file_name: str, data: bytes) -> str:
"""Keep an original .MLG byte for byte, at <serial or _unresolved>/mlg/<file_name>.
Blastware reuses some names (a cable download is always <serial>.MLG), so
a name already holding different bytes gets the hash in its name instead.
Returns the path relative to the store root."""
d = self.root / (serial or "_unresolved") / "mlg"
d.mkdir(parents=True, exist_ok=True)
path = d / Path(file_name).name
if path.exists() and path.read_bytes() != data:
digest = hashlib.sha256(data).hexdigest()[:8]
path = d / f"{path.stem}.{digest}{path.suffix}"
if not path.exists():
path.write_bytes(data)
return path.relative_to(self.root).as_posix()
def paths_for(self, serial: str, filename: str) -> tuple[Path, Path]:
"""Return (blastware_path, a5_pickle_path) for a given serial+filename.
+94
View File
@@ -0,0 +1,94 @@
"""
Tests for .MLG storage: SeismoDb's mlg_files / mlg_records tables and
WaveformStore.save_mlg (spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §3).
"""
from __future__ import annotations
import datetime
import hashlib
import os
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.mlg_file import read_mlg
from sfm.database import SeismoDb
from sfm.waveform_store import WaveformStore
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
UTC = datetime.timezone.utc
def _insert(db: SeismoDb, name: str, *, as_name: str | None = None, call_in: bool = True):
raw = (FIX / name).read_bytes()
mlg = read_mlg(FIX / name)
return db.insert_mlg(
serial=mlg.serial, file_name=as_name or name, sha256=hashlib.sha256(raw).hexdigest(),
size=len(raw), empty=mlg.empty, call_in=call_in,
file_mtime=datetime.datetime(2026, 9, 8, 17, 39, 52, tzinfo=UTC),
stored_path=f"{mlg.serial}/mlg/{as_name or name}", records=mlg.records,
)
def test_insert_and_query_round_trip(tmp_path):
db = SeismoDb(tmp_path / "t.db")
file_id, inserted, skipped = _insert(db, "BE128443067.MLG")
assert file_id and (inserted, skipped) == (3, 0)
rows = db.query_mlg_records("BE12844")
assert [r["start_time"] for r in rows] == [
"2026-09-07T18:47:27", "2026-09-08T06:00:13", "2026-09-08T13:38:22"]
assert rows[1]["stop_time"] is None and rows[1]["flags"] == 0xFFFF
assert (rows[2]["trigger_source"], rows[2]["event_time"], rows[2]["seq"]) == (
1, "2026-09-08T13:38:22", 3)
assert rows[2]["trigger_level"] == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert {r["file_id"] for r in rows} == {file_id}
f = db.get_mlg_file(file_id)
assert (f["file_name"], f["record_count"], f["empty"], f["call_in"]) == ("BE128443067.MLG", 3, 0, 1)
assert f["file_mtime"] == "2026-09-08T17:39:52+00:00"
assert [x["id"] for x in db.query_mlg_files("BE12844")] == [file_id]
def test_same_file_twice_is_a_duplicate(tmp_path):
db = SeismoDb(tmp_path / "t.db")
_insert(db, "BE128443067.MLG")
assert _insert(db, "BE128443067.MLG") == (None, 0, 0)
assert len(db.query_mlg_files("BE12844")) == 1
raw = (FIX / "BE128443067.MLG").read_bytes()
assert db.mlg_file_exists("BE128443067.MLG", hashlib.sha256(raw).hexdigest())
assert not db.mlg_file_exists("BE128443067.MLG", "0" * 64)
def test_open_record_is_stored_once(tmp_path):
db = SeismoDb(tmp_path / "t.db")
_insert(db, "BE128443067.MLG")
file_id, inserted, skipped = _insert(db, "BE128443067.MLG", as_name="BE12844.MLG", call_in=False)
assert file_id and (inserted, skipped) == (0, 3)
assert len(db.query_mlg_records("BE12844")) == 3
def test_records_differing_only_in_text_are_the_same_record(tmp_path):
db = SeismoDb(tmp_path / "t.db")
assert _insert(db, "BE11529.MLG")[1:] == (3, 0)
file_id, inserted, skipped = _insert(db, "BE115292.MLG")
assert file_id and (inserted, skipped) == (0, 3)
def test_known_serials(tmp_path):
db = SeismoDb(tmp_path / "t.db")
assert db.known_serials() == set()
_insert(db, "BE128443067.MLG")
_insert(db, "BE8081.MLG")
assert db.known_serials() == {"BE12844", "BE8081"}
def test_save_mlg_keeps_both_when_names_collide(tmp_path):
store = WaveformStore(tmp_path / "waveforms")
a = store.save_mlg("BE11529", "BE11529.MLG", b"one")
assert a == "BE11529/mlg/BE11529.MLG"
assert store.save_mlg("BE11529", "BE11529.MLG", b"one") == a # same bytes: reused
b = store.save_mlg("BE11529", "BE11529.MLG", b"two")
assert b != a and b.startswith("BE11529/mlg/BE11529.") and b.endswith(".MLG")
assert (store.root / a).read_bytes() == b"one" and (store.root / b).read_bytes() == b"two"
assert store.save_mlg(None, "BE6907751.MLG", b"x") == "_unresolved/mlg/BE6907751.MLG"