fix(mlg): final-review fixes

A fresh whole-branch review found four Important issues; three of its
Minors and one item it set aside were re-graded up.  Each has a test that
failed first.

- A windowed timeline 500'd when a file came without its modified time
  (Python 3.10 rejects the 'Z' of received_at).  received_at is now
  +00:00 and timeline times parse 'Z' too.
- On the clock-step day an event-triggered call-in moved the event into
  the next session and lost the step.  An event now joins the 'monitoring
  started' record of its own file.
- A call-in whose records came first in another file (a cable download)
  read 'nothing_new'.  Each file now keeps its own call summary
  (last_stop, no_file_stops) from when it arrived.
- Sessions and call-ins now carry record_ids / file_ids / file_id, the
  shot report's proof (spec 5).
- A non-'started' record with no stop made the unit's timeline 500 for
  good; it now opens a session whose end is unknown.
- A serial from a file's bytes (or a hint) could write outside the store;
  only plain serials are used, and records with no serial are refused, not
  dropped.
- Times with a UTC offset, an empty 'at', or a bad mtimes value gave 500s
  (or stored half a request); they are now 400s, checked first.
- A missing call-in file made the gap after its Modem Exit read 'not
  monitoring' for days.  Files are numbered <serial><counter>; a gap
  across a missing number is now 'records missing' (unknown).  A long gap
  after a call-in with no number missing is 'no restart after a call-in':
  real outages on the DL2 data (BE6907 14 days from 2026-10-07; BE8081
  over Labor Day 2019).  Real fixtures BE6907 #899-#902 added.
- Docs: BE8081 did write one empty file (BE80811.MLG).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-13 14:17:08 -05:00
1 parent 35bac40dd5
commit ba826dfac6
16 files changed
+359 -77

No files matched your search

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+5 -4
View File
@@ -29,19 +29,20 @@ def test_import_dir_counts(tmp_path, capsys):
assert main(args + ["--dry-run"]) == 0
dry = _counts(capsys.readouterr().out)
assert (dry["files"], dry["error"], dry["empty"]) == (12, 0, 1)
assert (dry["files"], dry["error"], dry["empty"]) == (16, 0, 3)
assert not db_path.exists() and not store.exists()
assert main(args) == 0
first = _counts(capsys.readouterr().out)
assert (first["files"], first["ok"], first["error"], first["empty"], first["unresolved"]) == (12, 12, 0, 1, 0)
assert (first["files"], first["ok"], first["error"], first["empty"], first["unresolved"]) == (16, 16, 0, 3, 0)
assert first["skipped"] == 3 # BE115292.MLG repeats BE11529.MLG's records
assert [f["file_name"] for f in SeismoDb(db_path).query_mlg_files("BE6907")] == [
"BE6907750.MLG", "BE6907751.MLG"]
"BE6907750.MLG", "BE6907751.MLG", "BE6907899.MLG", "BE6907900.MLG",
"BE6907901.MLG", "BE6907902.MLG"]
assert main(args) == 0
again = _counts(capsys.readouterr().out)
assert (again["duplicate"], again["ok"], again["inserted"]) == (12, 0, 0)
assert (again["duplicate"], again["ok"], again["inserted"]) == (16, 0, 0)
def test_empty_files_are_resolved_whatever_the_folder_order(tmp_path, capsys):
+1 -1
View File
@@ -35,7 +35,7 @@ def test_crc_matches_the_micromate_rule():
def test_every_fixture_record_passes_its_checksum():
files = sorted(FIX.glob("*.MLG"))
assert len(files) == 12
assert len(files) == 16
for p in files:
assert parse_mlg(p.read_bytes()).crc_failures == [], p.name
+25
View File
@@ -99,3 +99,28 @@ def test_file_mtime_and_call_in_are_stored(tmp_path):
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)
def test_a_serial_that_is_not_a_plain_serial_is_refused(tmp_path):
from minimateplus.mlg_file import mlg_bytes, parse_mlg
db, store = _env(tmp_path)
good = parse_mlg((FIX / "BE128443065.MLG").read_bytes())
for r in good.records:
r.serial = "../hdr"
bad = mlg_bytes(type(good)(serial="../hdr", records=good.records))
res = _ingest(db, store, "BE128443065.MLG", bad)
assert res["status"] == "error" and "serial" in res["detail"]
res = _ingest(db, store, "BE6907751.MLG", serial_hint="../escaped")
assert res["status"] == "error" and "serial" in res["detail"]
assert not (tmp_path / "hdr").exists() and not (tmp_path / "escaped").exists()
assert not list(tmp_path.rglob("*.MLG"))
def test_records_with_no_serial_are_refused_not_dropped(tmp_path):
from minimateplus.mlg_file import mlg_bytes, parse_mlg
db, store = _env(tmp_path)
m = parse_mlg((FIX / "BE128443065.MLG").read_bytes())
for r in m.records:
r.serial = ""
res = _ingest(db, store, "XX0001.MLG", mlg_bytes(type(m)(serial="", records=m.records)))
assert res["status"] == "error" and "serial" in res["detail"]
+20
View File
@@ -109,3 +109,23 @@ def test_mlg_file_route_returns_original_bytes(tmp_path, monkeypatch):
with pytest.raises(HTTPException) as exc:
srv.db_mlg_file(file_id="no-such-id")
assert exc.value.status_code == 404
def test_times_with_an_offset_or_empty_are_400(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
for at in ("2019-04-14T12:00:00Z", "2019-04-14T12:00:00+00:00", ""):
with pytest.raises(HTTPException) as exc:
srv.db_unit_monitoring_at(serial="BE8081", at=at)
assert exc.value.status_code == 400, at
with pytest.raises(HTTPException) as exc:
srv.db_mlg_records(serial="BE8081", from_dt="2019-04-14T12:00:00Z", to_dt=None)
assert exc.value.status_code == 400
def test_bad_mtime_values_are_refused_before_anything_is_stored(tmp_path, monkeypatch):
srv, db, _ = _env(tmp_path, monkeypatch)
with pytest.raises(HTTPException) as exc:
_import(srv, [_fixture("BE128443065.MLG"), _fixture("BE128443067.MLG")],
mtimes='{"BE128443067.MLG": "noon"}')
assert exc.value.status_code == 400
assert db.query_mlg_files("BE12844") == []
+102 -1
View File
@@ -104,7 +104,7 @@ def test_weekend_battery_outage_and_missed_calls(tmp_path):
g = tl["gaps"]
assert [x["meaning"] for x in g] == ["call-in", "call-in", "lost power"]
assert [x["minutes"] for x in g] == pytest.approx([5.233, 5.233, 2999.833], abs=0.01)
assert tl["call_ins"] == [
assert [{k: v for k, v in c.items() if k != "file_id"} for c in tl["call_ins"]] == [
{"kind": "no_file", "unit_time": "2019-04-12T18:33:00", "file_time": None,
"file_name": "BE8081321.MLG"},
{"kind": "no_file", "unit_time": "2019-04-13T07:00:01", "file_time": None,
@@ -158,3 +158,104 @@ def test_window_filters_call_ins_by_unit_time_and_empty_files_by_file_time(tmp_p
around_file = window(tl, dt(2025, 12, 31), dt(2026, 1, 2))
assert [c["kind"] for c in around_file["call_ins"]] == ["nothing_new"]
assert window(tl, None, None)["call_ins"] == tl["call_ins"]
# ── Final-review fixes ────────────────────────────────────────────────────────
from minimateplus.mlg_file import mlg_bytes
from minimateplus.models import MlgFile, MlgRecord
def _rec(index, start, stop, flags, src=0, serial="BE12844"):
return MlgRecord(index=index, start=start, stop=stop, flags=flags, trigger_source=src,
serial=serial, text_raw=b"Geo: 0.0500 in/s".ljust(254, b"\x00"))
def _ingest_bytes(tmp_path, serial, files):
"""files: [(name, bytes, call_in)] in arrival order."""
db, store = SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "w")
for i, (name, data, call_in) in enumerate(files):
res = ingest_mlg(db, store, name, data, call_in=call_in,
file_mtime=BASE + datetime.timedelta(hours=i))
assert res["status"] == "ok", res
return db, build_timeline(db.query_mlg_records(serial), db.query_mlg_files(serial))
def test_windowed_timeline_without_file_mtime(tmp_path):
from sfm.mlg_timeline import window
db, store = SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "w")
for name in ("BE6907750.MLG", "BE6907751.MLG"):
ingest_mlg(db, store, name, (FIX / name).read_bytes()) # no file_mtime
tl = build_timeline(db.query_mlg_records("BE6907"), db.query_mlg_files("BE6907"))
assert all(c["file_time"] is None or c["file_time"].endswith("+00:00") for c in tl["call_ins"])
out = window(tl, dt(2026, 8, 1), None)
assert [c["kind"] for c in out["call_ins"]][:2] == ["no_file", "delivered"]
def test_event_triggered_call_on_the_clock_step_day(tmp_path):
a = mlg_bytes(MlgFile("BE12844", [_rec(1, dt(2026, 11, 1, 6, 0, 13), None, 0xFFFF),
_rec(2, dt(2026, 11, 1, 13, 38, 22), dt(2026, 11, 1, 13, 38, 25), 0x0001, 1)]))
b = mlg_bytes(MlgFile("BE12844", [_rec(1, dt(2026, 11, 1, 12, 41, 16), dt(2026, 11, 1, 18, 45), 0x0020)]))
_, tl = _ingest_bytes(tmp_path, "BE12844", [("BE128449001.MLG", a, True), ("BE128449002.MLG", b, True)])
first = tl["sessions"][0]
assert first["start"] == "2026-11-01T06:00:13" and len(first["events"]) == 1
assert tl["sessions"][1]["events"] == []
(step,) = tl["clock_steps"]
assert (step["previous_stop"], step["next_start"]) == ("2026-11-01T13:38:25", "2026-11-01T12:41:16")
assert tl["gaps"] == []
assert monitoring_at(tl, dt(2026, 11, 1, 10, 0))["status"] == "monitoring"
def test_call_in_whose_records_came_first_in_a_cable_download(tmp_path):
files = [("BE11529.MLG", (FIX / "BE11529.MLG").read_bytes(), False),
("BE115292.MLG", (FIX / "BE115292.MLG").read_bytes(), True)]
_, tl = _ingest_bytes(tmp_path, "BE11529", files)
assert [(c["kind"], c["unit_time"], c["file_name"]) for c in tl["call_ins"]] == [
("delivered", "2026-04-22T21:06:57", "BE115292.MLG")]
def test_sessions_and_call_ins_carry_their_records_and_files(tmp_path):
db, tl = _ingest_bytes(tmp_path, "BE8081", [
("BE8081321.MLG", (FIX / "BE8081321.MLG").read_bytes(), True)])
(f,) = db.query_mlg_files("BE8081")
ids = {r["id"] for r in db.query_mlg_records("BE8081")}
for s in tl["sessions"]:
assert s["file_ids"] == [f["id"]] and s["record_ids"] and set(s["record_ids"]) <= ids
assert sum(len(s["record_ids"]) for s in tl["sessions"]) == 6
assert {c["file_id"] for c in tl["call_ins"]} == {f["id"]}
m = monitoring_at(tl, dt(2019, 4, 12, 18, 0))
assert m["sessions"][0]["file_ids"] == [f["id"]]
def test_a_record_without_a_stop_does_not_break_the_timeline(tmp_path):
a = mlg_bytes(MlgFile("BE12844", [_rec(1, dt(2026, 9, 1, 6, 0), None, 0x0020)]))
_, tl = _ingest_bytes(tmp_path, "BE12844", [("BE128449003.MLG", a, True)])
assert monitoring_at(tl, dt(2026, 9, 1, 12, 0))["status"] == "unknown"
def test_a_missing_call_in_file_is_unknown_not_not_monitoring(tmp_path):
# #3066 and #3067 are not imported: the records of 09-06 18:47 to 09-08 13:38 are missing.
_, tl = _ingest_bytes(tmp_path, "BE12844", [
("BE128443065.MLG", (FIX / "BE128443065.MLG").read_bytes(), True),
("BE128443068.MLG", (FIX / "BE128443068.MLG").read_bytes(), True)])
(gap,) = tl["gaps"][-1:]
assert gap["start"] == "2026-09-06T18:45:00" and gap["meaning"] == "records missing"
assert gap["missing_files"] == [3066, 3067]
assert monitoring_at(tl, dt(2026, 9, 7, 12, 0))["status"] == "unknown"
# a real call-in gap (2 minutes) still reads as one
_, tl2 = _ingest_bytes(tmp_path / "b", "BE12844", [
("BE128443067.MLG", (FIX / "BE128443067.MLG").read_bytes(), True),
("BE128443068.MLG", (FIX / "BE128443068.MLG").read_bytes(), True)])
assert monitoring_at(tl2, dt(2026, 9, 8, 13, 40))["status"] == "unknown"
def test_a_unit_that_did_not_restart_after_a_call_in_was_not_monitoring(tmp_path):
# BE6907, real files #899-#902: no number is missing (#900, #901 are its usual empty
# call-ins), yet nothing was recorded from the 10-07 18:30 call-in until 10-21 11:42.
names = ["BE6907899.MLG", "BE6907900.MLG", "BE6907901.MLG", "BE6907902.MLG"]
_, tl = _ingest_bytes(tmp_path, "BE6907", [(n, (FIX / n).read_bytes(), True) for n in names])
gap = next(g for g in tl["gaps"] if g["start"] == "2026-10-07T18:30:00")
assert gap["stop"] == "2026-10-21T11:42:43" and gap["meaning"] == "no restart after a call-in"
assert gap["missing_files"] == []
m = monitoring_at(tl, dt(2026, 10, 14, 12, 0))
assert m["status"] == "not_monitoring" and m["gap"]["meaning"] == "no restart after a call-in"