fix(sfm): a download never downgrades a stored event -- an existing row is returned, nothing written
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
This commit is contained in:
1 parent
ddb22d9624
commit
ef096e3082
9 files changed
+178
-22
No files matched your search
@@ -2,6 +2,7 @@
|
||||
series; anything only one series has goes under `detail`."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
@@ -102,9 +103,9 @@ class EventDownload:
|
||||
series: int
|
||||
db_event_id: Optional[str]
|
||||
stored_filename: str
|
||||
filesize: int
|
||||
sha256: Optional[str]
|
||||
inserted: bool # False: already stored; the row was refreshed
|
||||
filesize: Optional[int] # None only for a stored row with no file recorded
|
||||
sha256: Optional[str] # None when the event was already stored
|
||||
inserted: bool # False: already stored; nothing was written (detail.already_stored)
|
||||
verified: Optional[bool] # True: decode self-check passed; None: no check exists
|
||||
detail: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@@ -113,7 +114,12 @@ class EventDownload:
|
||||
class DownloadedEvent:
|
||||
"""The device side's result, before SFM stores it. Not an HTTP shape: it
|
||||
carries the payload -- a Series-3 Event + its 5A frames + the compliance
|
||||
config, or a Series-4 file's bytes -- to sfm.event_ingest."""
|
||||
config, or a Series-4 file's bytes -- to sfm.event_ingest.
|
||||
|
||||
`timestamp` is the event's time as the unit reported it: the store looks up
|
||||
an existing row by (serial, timestamp) before writing anything. `record` is
|
||||
what the unit's own event record said (Series 4's 0x0C), for the fields the
|
||||
file alone does not give."""
|
||||
event_id: str
|
||||
serial: str
|
||||
series: int
|
||||
@@ -123,4 +129,6 @@ class DownloadedEvent:
|
||||
event: Any = field(default=None, repr=False)
|
||||
a5_frames: Optional[list] = field(default=None, repr=False)
|
||||
compliance: Any = field(default=None, repr=False)
|
||||
timestamp: Optional[datetime.datetime] = None
|
||||
record: Dict[str, Any] = field(default_factory=dict)
|
||||
detail: Dict[str, Any] = field(default_factory=dict)
|
||||
@@ -204,6 +204,7 @@ class Series3Adapter:
|
||||
return DownloadedEvent(
|
||||
event_id=make_event_id(serial, key, found), serial=serial, series=3,
|
||||
filename=filename, verified=None, event=ev, a5_frames=ev._a5_frames,
|
||||
compliance=info.compliance_config, detail={"a5_frames": len(ev._a5_frames)},
|
||||
compliance=info.compliance_config, timestamp=_s3_dt(ev),
|
||||
detail={"a5_frames": len(ev._a5_frames)},
|
||||
)
|
||||
return self._run(address, op, timeout=S3_EVENT_TIMEOUT)
|
||||
@@ -287,6 +287,9 @@ def s4_download_event(client: Any, serial: str, key: bytes, stamp: Optional[str]
|
||||
return DownloadedEvent(
|
||||
event_id=make_event_id(serial, key, found), serial=serial, series=4,
|
||||
filename=ref.filename, verified=True if err is not None else None,
|
||||
idf_bytes=blob, detail={"size_bytes": ref.size, "pvs_error": err},
|
||||
idf_bytes=blob, timestamp=ref.timestamp,
|
||||
record={"peak_vector_sum_ips": ref.peak_vector_sum_ips,
|
||||
"sensor_location": ref.sensor_location, "setup": ref.setup},
|
||||
detail={"size_bytes": ref.size, "pvs_error": err},
|
||||
)
|
||||
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
|
||||
+26
-3
@@ -2,9 +2,13 @@
|
||||
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.
|
||||
store (file + sidecar + .h5) and SeismoDb.insert_events().
|
||||
|
||||
An event already stored -- by an earlier download, or by THOR's watcher or
|
||||
Blastware's ACH -- is returned as it is and NOTHING is written. The watcher's
|
||||
copy is the richer one (its paired report carries PVS, project strings and ZC
|
||||
frequencies a bare download does not), so a download never merges into it or
|
||||
replaces it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -51,13 +55,32 @@ def _event_dt(ev: Any) -> Optional[datetime.datetime]:
|
||||
return None
|
||||
|
||||
|
||||
def _already_stored(dl: DownloadedEvent, row: dict) -> EventDownload:
|
||||
return EventDownload(
|
||||
event_id=dl.event_id, serial=dl.serial, series=dl.series, db_event_id=row["id"],
|
||||
stored_filename=row.get("blastware_filename") or "",
|
||||
filesize=row.get("blastware_filesize"),
|
||||
sha256=None, # the events table does not keep one
|
||||
inserted=False, verified=dl.verified,
|
||||
detail={**dl.detail, "already_stored": True},
|
||||
)
|
||||
|
||||
|
||||
def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownload:
|
||||
# Never merge: a row for (serial, timestamp) means the event is stored, and
|
||||
# whoever stored it first keeps it. No store call, no insert, no sidecar.
|
||||
if dl.timestamp is not None:
|
||||
rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=1)
|
||||
if rows:
|
||||
return _already_stored(dl, rows[0])
|
||||
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
|
||||
if ev is None:
|
||||
raise IngestError(f"{dl.filename}: the download carried no event; nothing was stored")
|
||||
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,
|
||||
|
||||
+5
-3
@@ -1279,9 +1279,11 @@ def device_events_download(
|
||||
"""Download one event, check it, and store it in SFM's database.
|
||||
|
||||
Read-only on the unit. The stored file and waveform are then at
|
||||
/db/events/{db_event_id}/... . Storing an event that is already stored
|
||||
refreshes its row (`inserted: false`). The unit is busy for the whole
|
||||
download: other requests for it wait, then get 423.
|
||||
/db/events/{db_event_id}/... . An event already stored -- by an earlier
|
||||
download, or by THOR's watcher -- comes back as its existing row and
|
||||
nothing is written (`inserted: false`, `detail.already_stored: true`).
|
||||
The unit is busy for the whole download: other requests for it wait,
|
||||
then get 423.
|
||||
"""
|
||||
try:
|
||||
dl = _device_access().download_event(_unit_address(port, baud, host, tcp_port), serial, event_id)
|
||||
|
||||
@@ -64,6 +64,7 @@ def test_download_returns_the_event_its_frames_and_the_settings():
|
||||
assert (dl.series, dl.event_id, dl.verified) == (3, "BE18193:01110000:20261001080000", None)
|
||||
assert dl.event is fake.events[0] and dl.a5_frames == ["frame"]
|
||||
assert dl.compliance is fake.compliance and dl.filename.startswith("T193")
|
||||
assert dl.timestamp == datetime.datetime(2026, 10, 1, 8, 0, 0)
|
||||
|
||||
|
||||
def test_download_refuses_a_different_unit_before_downloading():
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Series-4 events: the chain walk mapped into the shared shape; download at the cursor."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -36,6 +37,17 @@ def test_download_walks_to_the_event_and_uses_thors_chunk_size():
|
||||
assert (dl.series, dl.filename, dl.verified) == (4, "UM20147_20250531135901.IDFW", True)
|
||||
|
||||
|
||||
def test_download_carries_the_units_timestamp_and_its_own_record():
|
||||
# What the unit's 0x0C said: the store looks up an existing row by the
|
||||
# timestamp, and fills what the file alone cannot give from the record.
|
||||
ref = FakeMicromateClient().event_refs[0]
|
||||
ref.sensor_location, ref.setup = "Loc A", "test2"
|
||||
fake = FakeMicromateClient(event_refs=[ref])
|
||||
dl = s4_download_event(fake, "UM20147", W_KEY, "20250531135901")
|
||||
assert dl.timestamp == datetime.datetime(2025, 5, 31, 13, 59, 1)
|
||||
assert dl.record == {"peak_vector_sum_ips": 0.2, "sensor_location": "Loc A", "setup": "test2"}
|
||||
|
||||
|
||||
def test_the_walk_stops_at_the_event_rather_than_reading_ahead():
|
||||
fake = FakeMicromateClient()
|
||||
s4_download_event(fake, "UM20147", W_KEY, None)
|
||||
|
||||
+114
-9
@@ -13,10 +13,11 @@ 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.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
|
||||
@@ -24,9 +25,24 @@ def sdm(tmp_path):
|
||||
return WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo.db")
|
||||
|
||||
|
||||
def s4_download(name, verified=True):
|
||||
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())
|
||||
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):
|
||||
@@ -45,13 +61,71 @@ def test_a_series4_histogram_is_stored(sdm):
|
||||
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):
|
||||
def test_storing_the_same_event_twice_stores_nothing_the_second_time(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)
|
||||
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
|
||||
assert len(db.query_events(serial="UM20147")) == 1
|
||||
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:
|
||||
@@ -70,7 +144,7 @@ def test_a_series3_event_is_backfilled_then_stored_as_series3(tmp_path):
|
||||
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)
|
||||
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)
|
||||
@@ -79,6 +153,37 @@ def test_a_series3_event_is_backfilled_then_stored_as_series3(tmp_path):
|
||||
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))
|
||||
|
||||
@@ -212,10 +212,11 @@ def test_download_stores_the_event_and_says_where(da, sdm):
|
||||
assert db.get_event(out["db_event_id"])["serial"] == "UM20147"
|
||||
|
||||
|
||||
def test_downloading_it_again_refreshes_the_same_row(da, sdm):
|
||||
def test_downloading_it_again_returns_the_stored_row_rather_than_rewriting_it(da, sdm):
|
||||
first = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
|
||||
again = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
|
||||
assert again["inserted"] is False and again["db_event_id"] == first["db_event_id"]
|
||||
assert again["detail"]["already_stored"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event_id,status", [
|
||||
|
||||
Reference in new issue
Block a user