THOR's watcher (and Blastware's ACH) store every event through
/db/import/idf_file and /db/import/blastware_file, with the paired report.
Storing a download of the same event afterwards overwrote that richer copy:
on Series 4 the file, .h5 and sidecar were rewritten (extensions dropped);
on Series 3 the row lost PVS, project strings and ZC frequencies and was
repointed at a second, review-less file set.
persist_download now looks up (serial, timestamp) first. A row there is
returned as it stands -- inserted false, detail.already_stored true -- with
no store call, no insert_events and no sidecar write. Never merge.
- DownloadedEvent gains `timestamp` (the unit's own event time) and
`record` (Series 4's 0x0C fields); both adapters set them.
- The Series-3 `event is None` guard now runs before backfill/save, with a
message that is true there ("nothing was stored").
- Tests build the watcher's state exactly as the import endpoints do and
prove the row dict, the sidecar bytes and the file mtimes are unchanged.
No schema change, no migration, no codec change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
202 lines
9.3 KiB
Python
202 lines
9.3 KiB
Python
"""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 IngestError, backfill_series3_event, persist_download # noqa: E402
|
|
from sfm.waveform_store import WaveformStore # noqa: E402
|
|
|
|
THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
|
|
BW_FIXTURES = Path(__file__).parent / "fixtures" / "5-11-26"
|
|
|
|
|
|
@pytest.fixture
|
|
def sdm(tmp_path):
|
|
return WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo.db")
|
|
|
|
|
|
def s4_download(name, verified=True, record=None):
|
|
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(),
|
|
timestamp=datetime.datetime.strptime(name[8:22], "%Y%m%d%H%M%S"),
|
|
record=dict(record or {}))
|
|
|
|
|
|
def _tree(root):
|
|
"""Every file under the store: (size, mtime_ns). Any write shows."""
|
|
return {str(p.relative_to(root)): (p.stat().st_size, p.stat().st_mtime_ns)
|
|
for p in sorted(root.rglob("*")) if p.is_file()}
|
|
|
|
|
|
def _age_files(directory):
|
|
"""Back-date every file, so a rewrite shows in its mtime whatever the clock's grain."""
|
|
for p in directory.iterdir():
|
|
if p.is_file():
|
|
os.utime(p, ns=(1_000_000_000_000_000_000, 1_000_000_000_000_000_000))
|
|
|
|
|
|
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_stores_nothing_the_second_time(sdm):
|
|
store, db = sdm
|
|
name = "UM20147_20250531135901.IDFW"
|
|
first = persist_download(s4_download(name), store=store, db=db)
|
|
_age_files(store.root / "UM20147")
|
|
row0 = db.get_event(first.db_event_id)
|
|
tree0 = _tree(store.root)
|
|
again = persist_download(s4_download(name), store=store, db=db)
|
|
assert (first.inserted, again.inserted) == (True, False)
|
|
assert again.db_event_id == first.db_event_id and again.detail["already_stored"] is True
|
|
assert db.query_events(serial="UM20147") == [row0]
|
|
assert (store.root / "UM20147" / name).stat().st_mtime_ns == tree0[f"UM20147/{name}"][1]
|
|
assert _tree(store.root) == tree0
|
|
|
|
|
|
# ── an event THOR's watcher (or Blastware's ACH) already stored ───────────────
|
|
# Built exactly as /db/import/idf_file and /db/import/blastware_file build it
|
|
# (sfm/server.py): the store's import call, then insert_events.
|
|
|
|
def watcher_import_idf(store, db, name):
|
|
ev, rec = store.save_imported_idf((THOR_IDF / name).read_bytes(), source_path=Path(name),
|
|
serial_hint=None, idf_report_text=None)
|
|
serial = rec.get("serial") or "UNKNOWN"
|
|
db.insert_events([ev], serial=serial,
|
|
waveform_records={ev._waveform_key.hex(): rec} if ev._waveform_key else None,
|
|
device_family="series4")
|
|
return serial, rec
|
|
|
|
|
|
def watcher_import_bw(store, db, name):
|
|
ev, rec = store.save_imported_bw((BW_FIXTURES / name).read_bytes(), source_path=Path(name),
|
|
serial_hint=None,
|
|
bw_report_text=(BW_FIXTURES / f"{name}.TXT").read_bytes())
|
|
serial = rec.get("serial") or "UNKNOWN"
|
|
db.insert_events([ev], serial=serial,
|
|
waveform_records={ev._waveform_key.hex(): rec if ev._waveform_key else None}
|
|
if ev._waveform_key else None,
|
|
device_family="series3")
|
|
return serial, rec
|
|
|
|
|
|
def test_downloading_an_event_the_watcher_stored_writes_nothing_series4(sdm):
|
|
store, db = sdm
|
|
name = "UM20147_20250531135901.IDFW"
|
|
serial, rec = watcher_import_idf(store, db, name)
|
|
assert serial == "UM20147"
|
|
# Something only the stored copy has; a rewrite of the sidecar would drop it.
|
|
assert store.patch_sidecar(serial, name, extensions={"operator_note": {"text": "checked on site"}})
|
|
_age_files(store.root / serial)
|
|
[row0] = db.query_events(serial=serial)
|
|
sidecar0 = store.sidecar_path_for(serial, name).read_bytes()
|
|
mtime0 = (store.root / serial / name).stat().st_mtime_ns
|
|
tree0 = _tree(store.root)
|
|
|
|
out = persist_download(s4_download(name, record={"peak_vector_sum_ips": 0.391,
|
|
"sensor_location": "Loc A"}),
|
|
store=store, db=db)
|
|
|
|
assert out.inserted is False and out.detail["already_stored"] is True
|
|
assert out.db_event_id == row0["id"]
|
|
assert (out.stored_filename, out.filesize) == (name, rec["filesize"])
|
|
assert db.query_events(serial=serial) == [row0]
|
|
assert store.sidecar_path_for(serial, name).read_bytes() == sidecar0
|
|
assert (store.root / serial / name).stat().st_mtime_ns == mtime0
|
|
assert _tree(store.root) == tree0
|
|
|
|
|
|
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, timestamp=datetime.datetime(2026, 10, 1, 8, 0, 0))
|
|
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_downloading_an_event_the_watcher_stored_writes_nothing_series3(tmp_path):
|
|
db = SeismoDb(tmp_path / "seismo.db")
|
|
serial, rec = watcher_import_bw(WaveformStore(tmp_path / "waveforms"), db, "M529LL1L.V70")
|
|
[row0] = db.query_events(serial=serial)
|
|
when = datetime.datetime.fromisoformat(row0["timestamp"])
|
|
# The download's own decode differs from the stored row (peaks, file name), so
|
|
# any write would show in the row.
|
|
ev = s3_event(0, row0["waveform_key"], when)
|
|
store = RecordingStore()
|
|
dl = DownloadedEvent(event_id=f"{serial}:{row0['waveform_key']}:{when:%Y%m%d%H%M%S}",
|
|
serial=serial, series=3, filename="M529LL1L.V70", verified=None, event=ev,
|
|
a5_frames=["frame"], compliance=FakeMiniMateClient().compliance,
|
|
timestamp=when)
|
|
out = persist_download(dl, store=store, db=db)
|
|
assert store.saved == []
|
|
assert db.query_events(serial=serial) == [row0]
|
|
assert out.inserted is False and out.detail["already_stored"] is True
|
|
assert (out.db_event_id, out.stored_filename, out.filesize) == (row0["id"], rec["filename"],
|
|
rec["filesize"])
|
|
assert ev.sample_rate is None # not even backfilled
|
|
|
|
|
|
def test_a_series3_download_with_no_event_stores_nothing_and_says_so(tmp_path):
|
|
store = RecordingStore()
|
|
dl = DownloadedEvent(event_id="BE18193:01110000:-", serial="BE18193", series=3,
|
|
filename="T193LQ9K.OE0", verified=None, event=None, a5_frames=["frame"])
|
|
with pytest.raises(IngestError, match="nothing was stored"):
|
|
persist_download(dl, store=store, db=SeismoDb(tmp_path / "seismo.db"))
|
|
assert store.saved == []
|
|
|
|
|
|
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
|