diff --git a/sfm/database.py b/sfm/database.py index 05880b6..d3c0a98 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -854,7 +854,8 @@ class SeismoDb: ).fetchone() return dict(row) if row else None - def find_event_by_blastware_name(self, serial: str, filename: str) -> Optional[dict]: + def find_event_by_blastware_name(self, serial: str, filename: str, + record_type: Optional[str] = None) -> Optional[dict]: """The row stored under `filename`'s Blastware name, or None. A Blastware name encodes the serial and the event's second @@ -865,6 +866,10 @@ class SeismoDb: itself and the letterless form -- not the other letter, since in Histogram+Continuous a waveform can trigger in the second a histogram starts. Any other name ("imported.bw") matches nothing. + + `record_type`: only a row of that type -- or an untyped one, which may be + this event -- matches (#51: a same-second waveform / histogram twin shares + the letterless name). Compared ignoring case. """ if blastware_filename_time(filename) is None: return None @@ -874,10 +879,14 @@ class SeismoDb: else: forms = (name, name + "W", name + "H") with self._connect() as conn: + typed, args = "", (serial, *forms) + if record_type is not None: + typed = " AND (record_type IS NULL OR UPPER(record_type) = UPPER(?))" + args = (*args, record_type) row = conn.execute( f"SELECT * FROM events WHERE serial = ? AND UPPER(blastware_filename) IN " - f"({', '.join('?' * len(forms))}) ORDER BY rowid LIMIT 1", - (serial, *forms), + f"({', '.join('?' * len(forms))}){typed} ORDER BY rowid LIMIT 1", + args, ).fetchone() return dict(row) if row else None diff --git a/sfm/event_ingest.py b/sfm/event_ingest.py index 128ebce..14ddaff 100644 --- a/sfm/event_ingest.py +++ b/sfm/event_ingest.py @@ -134,16 +134,43 @@ def _overlay_s4_record(ev: Any, record: dict) -> None: ev.project_info.sensor_location = location +def _download_record_type(dl: DownloadedEvent) -> Optional[str]: + """The download's own record type -- "Waveform" / "Histogram", as every stored + row has it -- from its file: a Series-3 file's STRT[18], a Series-4 name's + IDFW / IDFH. None when it does not read (then any row at its second counts).""" + if dl.series == 4: + ext = dl.filename.rsplit(".", 1)[-1].upper() + return {"IDFW": "Waveform", "IDFH": "Histogram"}.get(ext) + if not dl.bw_bytes: + return None + try: + from minimateplus.event_file_io import decode_blastware_bytes + return decode_blastware_bytes(dl.bw_bytes).record_type + except Exception: # noqa: BLE001 -- a check, not a decode + return None + + +def _same_type(row_type: Optional[str], mine: Optional[str]) -> bool: + """An untyped row, or a download whose type does not read, matches + conservatively: it may be this event.""" + return row_type is None or mine is None or row_type.casefold() == mine.casefold() + + 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. + # Never merge: a row for (serial, timestamp, record type) means the event is + # stored, and whoever stored it first keeps it. No store call, no insert, no + # sidecar. The type matters since #51: a waveform and a histogram recorded in + # the same second (Histogram + Continuous) are two events. + kind = _download_record_type(dl) if dl.timestamp is not None: - rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=1) + rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=10) + rows = [r for r in rows if _same_type(r.get("record_type"), kind)] if rows: return _already_stored(dl, rows[0]) - # A histogram's row is stored at its file's time, a second before the unit's - # on most (#51), so the time above misses it; its Blastware name does not. - row = db.find_event_by_blastware_name(dl.serial, dl.filename) + # The Blastware name encodes the event's second (a second guard; before #51 a + # histogram's row sat a second off the unit's time). Both twins share the + # letterless name, so it too is held to the type. + row = db.find_event_by_blastware_name(dl.serial, dl.filename, record_type=kind) if row is not None: return _already_stored(dl, row) if dl.series == 4: diff --git a/tests/test_event_ingest.py b/tests/test_event_ingest.py index e87f474..3b32b4c 100644 --- a/tests/test_event_ingest.py +++ b/tests/test_event_ingest.py @@ -499,3 +499,45 @@ def test_a_letterless_stored_name_still_matches_a_lettered_download(sdm): store, db = sdm _stored_as(store, db, "K441LTOK.QZ0") assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0H")["blastware_filename"] == "K441LTOK.QZ0" + + +# #51 (dev, 2026-11-03): a waveform and a histogram recorded in the same second +# are two events (UNIQUE(serial, timestamp, record_type)). A live download of one +# must not be skipped because its twin is stored -- not by the time, and not by a +# letterless Blastware name both twins share. An untyped row at that second still +# counts as stored (conservatively: it may be this event). + +def _stored_twin(store, db, name, record_type): + ev, rec = store.save_imported_bw((HIST_FIX / "K441LTOK.QZ0").read_bytes(), + source_path=Path(name), serial_hint=None, + bw_report_text=(HIST_FIX / "K441LTOK_QZ0_ASCII.TXT").read_bytes()) + ev.record_type = record_type + db.insert_events([ev], serial="BE9441", waveform_records={ev._waveform_key.hex(): rec}, + device_family="series3") + + +@pytest.mark.parametrize("twin_name", ["K441LTOK.QZ0W", "K441LTOK.QZ0"]) # call-in / direct name +def test_a_live_histogram_is_stored_beside_its_same_second_waveform_twin(sdm, twin_name): + store, db = sdm + _stored_twin(store, db, twin_name, "Waveform") + dl = _hist_download("K441LTOK.QZ0", "01110000", datetime.datetime(2026, 10, 26, 16, 6, 35)) + dl.filename = "K441LTOK.QZ0H" # a live download carries the letter (s3.py: with_type_letter) + out = persist_download(dl, store=store, db=db) + assert out.inserted is True + assert sorted(r["record_type"] for r in db.query_events(serial="BE9441")) == ["Histogram", "Waveform"] + + +def test_an_untyped_row_at_that_second_still_counts_as_stored(sdm): + store, db = sdm + _stored_twin(store, db, "K441LTOK.QZ0", None) + out = persist_download(_hist_download("K441LTOK.QZ0", "01110000", + datetime.datetime(2026, 10, 26, 16, 6, 35)), store=store, db=db) + assert out.inserted is False and out.detail["already_stored"] is True + + +def test_the_name_lookup_can_be_held_to_a_record_type(sdm): + store, db = sdm + _stored_twin(store, db, "K441LTOK.QZ0", "Waveform") + assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0H", record_type="Histogram") is None + assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0", record_type="waveform") is not None + assert db.find_event_by_blastware_name("BE9441", "K441LTOK.QZ0") is not None