From f41e4be382d2e1d37f8baa8444fd333c7f475d06 Mon Sep 17 00:00:00 2001 From: serversdown Date: Fri, 13 Nov 2026 13:45:21 -0500 Subject: [PATCH] feat(mlg): ingest one .MLG: verify, resolve the serial, keep the original sfm/mlg_ingest.ingest_mlg() is shared by the import route and the bulk script. A file that is not whole, or with any record failing its checksum, stores nothing. The serial comes from the file; for an empty file (no serial inside) from the caller's hint, else the longest known serial its name starts with, else unresolved. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1 --- sfm/mlg_ingest.py | 102 +++++++++++++++++++++++++++++++++++++++ tests/test_mlg_ingest.py | 101 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 203 insertions(+) create mode 100644 sfm/mlg_ingest.py create mode 100644 tests/test_mlg_ingest.py diff --git a/sfm/mlg_ingest.py b/sfm/mlg_ingest.py new file mode 100644 index 0000000..8dd3d2e --- /dev/null +++ b/sfm/mlg_ingest.py @@ -0,0 +1,102 @@ +""" +sfm/mlg_ingest.py — take in one Blastware .MLG: verify it, work out its unit, +keep the original, store its records once. + +Shared by POST /db/import/mlg_file and scripts/import_mlg_dir.py. Spec: +docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §3, §5, §6. +""" + +from __future__ import annotations + +import datetime +import hashlib +import logging +from pathlib import Path +from typing import Optional + +from minimateplus.mlg_file import MlgFormatError, parse_mlg + +log = logging.getLogger("sfm.mlg_ingest") + + +def resolve_serial( + file_name: str, + header_serial: Optional[str], + hint: Optional[str], + known: set[str], +) -> Optional[str]: + """The unit a .MLG belongs to. + + The serial inside the file wins; then the caller's hint. An empty file + carries none, and its name is with nothing between, so + take the longest serial SFM already knows that the name starts with, + followed only by digits (or nothing: DL2's first file was BE8081.MLG). + None when nothing fits.""" + if header_serial: + return header_serial + if hint: + return hint + stem = Path(file_name).name + if stem.upper().endswith(".MLG"): + stem = stem[:-4] + def fits(serial: str) -> bool: + counter = stem[len(serial):] + return stem.upper().startswith(serial.upper()) and (counter == "" or counter.isdigit()) + + candidates = [s for s in known if fits(s)] + return max(candidates, key=len) if candidates else None + + +def ingest_mlg( + db, + store, + file_name: str, + data: bytes, + *, + serial_hint: Optional[str] = None, + file_mtime: Optional[datetime.datetime] = None, + call_in: bool = True, +) -> dict: + """Ingest one .MLG. Never raises for a bad file: the result says what happened. + + status "error": not a whole .MLG, or any record fails its checksum — nothing + of it is stored. status "duplicate": this name with these bytes is already + stored. status "ok": the original is kept and its new records stored.""" + result = { + "filename": file_name, "status": "error", "detail": None, "serial": None, + "serial_unresolved": False, "empty": False, "records": 0, + "inserted": 0, "skipped": 0, "file_id": None, + } + try: + mlg = parse_mlg(data) + except MlgFormatError as exc: + result["detail"] = str(exc) + return result + result["records"] = len(mlg.records) + result["empty"] = mlg.empty + if mlg.crc_failures: + result["detail"] = ", ".join(f"record {i}" for i in mlg.crc_failures) + " fails its checksum" + return result + + serial = resolve_serial(file_name, mlg.serial, serial_hint, db.known_serials()) + result["serial"] = serial + result["serial_unresolved"] = serial is None + + sha256 = hashlib.sha256(data).hexdigest() + if db.mlg_file_exists(file_name, sha256): + result["status"] = "duplicate" + result["detail"] = "this file is already stored" + return result + + stored_path = store.save_mlg(serial, file_name, data) + file_id, inserted, skipped = db.insert_mlg( + serial=serial, file_name=file_name, sha256=sha256, size=len(data), empty=mlg.empty, + call_in=call_in, file_mtime=file_mtime, stored_path=stored_path, records=mlg.records, + ) + if file_id is None: # stored between the check and the insert + result["status"] = "duplicate" + result["detail"] = "this file is already stored" + return result + result.update(status="ok", file_id=file_id, inserted=inserted, skipped=skipped) + log.info("mlg %s serial=%s inserted=%d skipped=%d", file_name, serial, inserted, skipped) + return result diff --git a/tests/test_mlg_ingest.py b/tests/test_mlg_ingest.py new file mode 100644 index 0000000..80b46c9 --- /dev/null +++ b/tests/test_mlg_ingest.py @@ -0,0 +1,101 @@ +""" +Tests for sfm/mlg_ingest.py — one .MLG in: verified, its serial resolved, the +original kept, its records stored once (spec §3, §5, §6). +""" + +from __future__ import annotations + +import datetime +import os +import sys +from pathlib import Path + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from sfm.database import SeismoDb +from sfm.mlg_ingest import ingest_mlg, resolve_serial +from sfm.waveform_store import WaveformStore + +FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26" +UTC = datetime.timezone.utc + + +def _env(tmp_path): + return SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "waveforms") + + +def _ingest(db, store, name, data=None, **kw): + return ingest_mlg(db, store, name, data if data is not None else (FIX / name).read_bytes(), **kw) + + +def test_ingest_ok(tmp_path): + db, store = _env(tmp_path) + res = _ingest(db, store, "BE128443067.MLG") + assert (res["status"], res["serial"], res["records"], res["inserted"], res["skipped"]) == ( + "ok", "BE12844", 3, 3, 0) + assert res["empty"] is False and res["serial_unresolved"] is False and res["file_id"] + assert (store.root / "BE12844" / "mlg" / "BE128443067.MLG").read_bytes() == ( + FIX / "BE128443067.MLG").read_bytes() + + +def test_ingest_twice_is_duplicate(tmp_path): + db, store = _env(tmp_path) + _ingest(db, store, "BE128443067.MLG") + res = _ingest(db, store, "BE128443067.MLG") + assert res["status"] == "duplicate" and res["inserted"] == 0 + assert len(db.query_mlg_files("BE12844")) == 1 + + +def test_corrupted_file_stores_nothing(tmp_path): + db, store = _env(tmp_path) + data = bytearray((FIX / "BE128443065.MLG").read_bytes()) + data[18 + 292 + 40] ^= 0xFF + res = _ingest(db, store, "BE128443065.MLG", bytes(data)) + assert res["status"] == "error" and "record 1" in res["detail"] + assert db.query_mlg_files("BE12844") == [] and db.query_mlg_records("BE12844") == [] + assert not list(store.root.rglob("mlg")) + + +def test_truncated_file_is_an_error(tmp_path): + db, store = _env(tmp_path) + res = _ingest(db, store, "BE128443065.MLG", (FIX / "BE128443065.MLG").read_bytes()[:-5]) + assert res["status"] == "error" and "not an MLG" in res["detail"] + assert not list(store.root.rglob("mlg")) + + +def test_empty_file_takes_known_serial(tmp_path): + db, store = _env(tmp_path) + _ingest(db, store, "BE6907750.MLG") + res = _ingest(db, store, "BE6907751.MLG") + assert (res["status"], res["serial"], res["empty"], res["serial_unresolved"]) == ( + "ok", "BE6907", True, False) + assert (store.root / "BE6907" / "mlg" / "BE6907751.MLG").exists() + + +def test_empty_file_without_known_serial_is_unresolved(tmp_path): + db, store = _env(tmp_path) + res = _ingest(db, store, "BE6907751.MLG") + assert (res["status"], res["serial"], res["serial_unresolved"]) == ("ok", None, True) + assert (store.root / "_unresolved" / "mlg" / "BE6907751.MLG").exists() + + +def test_empty_file_takes_the_serial_hint(tmp_path): + db, store = _env(tmp_path) + res = _ingest(db, store, "BE6907751.MLG", serial_hint="BE6907") + assert (res["serial"], res["serial_unresolved"]) == ("BE6907", False) + + +def test_empty_file_takes_the_longest_known_serial(): + assert resolve_serial("BE11010304.MLG", None, None, {"BE1101", "BE11010"}) == "BE11010" + assert resolve_serial("XY123.MLG", None, None, {"BE1101"}) is None + assert resolve_serial("BE6907751.MLG", "BE12844", "BE6907", {"BE6907"}) == "BE12844" + assert resolve_serial("be6907751.mlg", None, None, {"BE6907"}) == "BE6907" + assert resolve_serial("BE6907X51.MLG", None, None, {"BE6907"}) is None # not digits after + + +def test_file_mtime_and_call_in_are_stored(tmp_path): + db, store = _env(tmp_path) + mtime = datetime.datetime(2026, 9, 6, 22, 46, tzinfo=UTC) + res = _ingest(db, store, "BE128443065.MLG", file_mtime=mtime, call_in=False) + f = db.get_mlg_file(res["file_id"]) + assert (f["file_mtime"], f["call_in"]) == ("2026-09-06T22:46:00+00:00", 0)