From d84204f5332bac81d392135b67a07b1ced1aa1cc Mon Sep 17 00:00:00 2001 From: serversdown Date: Wed, 21 Oct 2026 17:04:44 -0400 Subject: [PATCH] feat(sfm): store a downloaded event -- one ingest for both series Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- sfm/event_ingest.py | 80 +++++++++++++++++++++++++++++++ sfm/server.py | 24 +--------- tests/test_event_ingest.py | 96 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 178 insertions(+), 22 deletions(-) create mode 100644 sfm/event_ingest.py create mode 100644 tests/test_event_ingest.py diff --git a/sfm/event_ingest.py b/sfm/event_ingest.py new file mode 100644 index 0000000..d07cb8d --- /dev/null +++ b/sfm/event_ingest.py @@ -0,0 +1,80 @@ +"""Store an event SFM downloaded from a unit -- the SDM side of +POST /device/events/download. + +Both series end in the two writes every other ingest path makes: the waveform +store (file + sidecar + .h5) and SeismoDb.insert_events(). The database matches +rows on (serial, timestamp), so storing an event already there -- by an earlier +download, or by THOR's watcher -- refreshes the row instead of duplicating it. +""" +from __future__ import annotations + +import datetime +from pathlib import Path +from typing import Any, Optional + +from sfm.device_access.models import DownloadedEvent, EventDownload + + +class IngestError(Exception): + """Downloaded from the unit, but could not be stored.""" + + +def backfill_series3_event(ev: Any, cc: Any) -> None: + """Compliance-config values that supersede what the 5A stream decoded. + + Some STRT fields have ambiguous semantics (STRT[20] is rectime, but + STRT[8:10] / STRT[16:18] are device-specific scratch, not reliable sample or + pre-trigger counts). Shared with GET /device/event/{i}/blastware_file. + """ + if not cc: + return + if ev.sample_rate is None and cc.sample_rate: + ev.sample_rate = cc.sample_rate + if cc.record_time: + # Authoritative: the user-set value the unit followed when recording. + ev.rectime_seconds = cc.record_time + # Derive total_samples from sample_rate x rectime when we can; the + # STRT-derived value can land at a buffer offset rather than a count. + if ev.sample_rate and ev.rectime_seconds: + derived = int(round(ev.sample_rate * ev.rectime_seconds)) + if (ev.total_samples is None + or ev.total_samples > derived * 2 + or ev.total_samples < derived // 4): + ev.total_samples = derived + + +def _event_dt(ev: Any) -> Optional[datetime.datetime]: + ts = getattr(ev, "timestamp", None) + try: + return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second) + except Exception: # noqa: BLE001 + return None + + +def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownload: + if dl.series == 4: + ev, rec = store.save_imported_idf(dl.idf_bytes, source_path=Path(dl.filename), + serial_hint=dl.serial) + family = "series4" + else: + ev = dl.event + backfill_series3_event(ev, dl.compliance) + geo_range = getattr(dl.compliance, "geo_range", None) if dl.compliance else None + rec = store.save(ev, serial=dl.serial, a5_frames=dl.a5_frames, + geo_range=geo_range if geo_range is not None else "normal") + family = "series3" + if ev is None or ev._waveform_key is None: + raise IngestError(f"{dl.filename}: stored the file but could not build a database row") + inserted, _skipped = db.insert_events( + [ev], serial=dl.serial, + waveform_records={ev._waveform_key.hex(): rec}, device_family=family) + row_id = None + dt = _event_dt(ev) + if dt is not None: + rows = db.query_events(serial=dl.serial, from_dt=dt, to_dt=dt, limit=1) + row_id = rows[0]["id"] if rows else None + return EventDownload( + event_id=dl.event_id, serial=dl.serial, series=dl.series, db_event_id=row_id, + stored_filename=rec["filename"], filesize=rec["filesize"], sha256=rec.get("sha256"), + inserted=inserted > 0, verified=dl.verified, detail=dict(dl.detail), + ) diff --git a/sfm/server.py b/sfm/server.py index d2ebb01..33f01b5 100644 --- a/sfm/server.py +++ b/sfm/server.py @@ -82,6 +82,7 @@ from sfm.database import SeismoDb from sfm.live_cache import LiveCache as _LiveCache from sfm.waveform_store import WaveformStore from sfm import db_snapshot +from sfm.event_ingest import backfill_series3_event, persist_download import dataclasses from sfm.device_access import DeviceAccess, DeviceError, UnitAddress from sfm.device_access.errors import BadRequest @@ -1000,28 +1001,7 @@ def device_event_blastware_file( if serial != "UNKNOWN" and ev._waveform_key is not None: try: cc = info.compliance_config - # Backfill authoritative compliance-config values onto the - # Event before persisting. These supersede whatever - # _decode_a5_waveform read from the STRT bytes (some of which - # have ambiguous semantics — e.g. STRT[20] is rectime but - # STRT[8:10] / STRT[16:18] are device-specific scratch fields - # that aren't reliable sample/pretrig counts). - if cc: - if ev.sample_rate is None and cc.sample_rate: - ev.sample_rate = cc.sample_rate - if cc.record_time: - # record_time from compliance is authoritative — the - # user-set value the device followed when recording. - ev.rectime_seconds = cc.record_time - # Derive total_samples from sample_rate × rectime when - # we can; the STRT-derived value can land at a buffer- - # offset rather than a sample count. - if ev.sample_rate and ev.rectime_seconds: - derived = int(round(ev.sample_rate * ev.rectime_seconds)) - if (ev.total_samples is None - or ev.total_samples > derived * 2 - or ev.total_samples < derived // 4): - ev.total_samples = derived + backfill_series3_event(ev, cc) geo_range = getattr(cc, "geo_range", None) if cc else None rec = _get_store().save( ev, serial=serial, a5_frames=a5_frames, diff --git a/tests/test_event_ingest.py b/tests/test_event_ingest.py new file mode 100644 index 0000000..5563c3a --- /dev/null +++ b/tests/test_event_ingest.py @@ -0,0 +1,96 @@ +"""Storing a downloaded event: the same store + DB writes every ingest path makes.""" +from __future__ import annotations + +import datetime +import os +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from device_access_fakes import FakeMiniMateClient, s3_event # noqa: E402 +from sfm.database import SeismoDb # noqa: E402 +from sfm.device_access.models import DownloadedEvent # noqa: E402 +from sfm.event_ingest import backfill_series3_event, persist_download # noqa: E402 +from sfm.waveform_store import WaveformStore # noqa: E402 + +THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf" + + +@pytest.fixture +def sdm(tmp_path): + return WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo.db") + + +def s4_download(name, verified=True): + return DownloadedEvent(event_id=f"UM20147:055d4a81:{name[8:22]}", serial="UM20147", series=4, + filename=name, verified=verified, idf_bytes=(THOR_IDF / name).read_bytes()) + + +def test_a_series4_waveform_is_stored_and_findable(sdm): + store, db = sdm + out = persist_download(s4_download("UM20147_20250531135901.IDFW"), store=store, db=db) + assert out.stored_filename == "UM20147_20250531135901.IDFW" and out.inserted + assert (store.root / "UM20147" / out.stored_filename).exists() + row = db.get_event(out.db_event_id) + assert row["serial"] == "UM20147" and row["device_family"] == "series4" + assert out.verified is True and out.sha256 + + +def test_a_series4_histogram_is_stored(sdm): + store, db = sdm + out = persist_download(s4_download("UM20147_20250330070110.IDFH", verified=None), store=store, db=db) + assert out.inserted and out.db_event_id and out.verified is None + + +def test_storing_the_same_event_twice_refreshes_rather_than_duplicates(sdm): + store, db = sdm + first = persist_download(s4_download("UM20147_20250531135901.IDFW"), store=store, db=db) + again = persist_download(s4_download("UM20147_20250531135901.IDFW"), store=store, db=db) + assert (first.inserted, again.inserted) == (True, False) + assert again.db_event_id == first.db_event_id + assert len(db.query_events(serial="UM20147")) == 1 + + +class RecordingStore: + def __init__(self): + self.saved = [] + + def save(self, ev, serial, a5_frames, *, geo_range="normal", source_kind="sfm-live"): + self.saved.append((ev, serial, a5_frames, geo_range)) + return {"filename": "T193LQ9K.OE0", "filesize": 8708, "sha256": "ab" * 32} + + +def test_a_series3_event_is_backfilled_then_stored_as_series3(tmp_path): + db = SeismoDb(tmp_path / "seismo.db") + store = RecordingStore() + fake = FakeMiniMateClient() + ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)) + dl = DownloadedEvent(event_id="BE18193:01110000:20261001080000", serial="BE18193", series=3, + filename="T193LQ9K.OE0", verified=None, event=ev, a5_frames=["frame"], + compliance=fake.compliance) + out = persist_download(dl, store=store, db=db) + saved_ev, serial, frames, geo_range = store.saved[0] + assert (serial, frames, geo_range) == ("BE18193", ["frame"], 0) + assert saved_ev.sample_rate == 1024 and saved_ev.rectime_seconds == 3.0 + assert db.get_event(out.db_event_id)["device_family"] == "series3" + assert out.stored_filename == "T193LQ9K.OE0" + + +def test_backfill_derives_total_samples_only_when_the_decoded_one_is_implausible(): + cc = FakeMiniMateClient().compliance # 1024 sps, 3.0 s + ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1)) + ev.total_samples = 40_000 + backfill_series3_event(ev, cc) + assert ev.total_samples == 3072 + ev.total_samples = 3000 + backfill_series3_event(ev, cc) + assert ev.total_samples == 3000 + + +def test_backfill_without_settings_changes_nothing(): + ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1)) + backfill_series3_event(ev, None) + assert ev.sample_rate is None