Files
seismo-relay/tests/test_mlg_timeline.py
T
serversdownandClaude Opus 5.5 ba826dfac6 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
2026-11-13 14:17:08 -05:00

262 lines
13 KiB
Python

"""
Tests for sfm/mlg_timeline.py — a unit's monitoring timeline from its .MLG
records, and "was it monitoring at T" (spec §4).
Each case is a real file; the expected sessions were read off the records by
hand (docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md,
"How a session appears").
"""
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 sfm.database import SeismoDb
from sfm.mlg_ingest import ingest_mlg
from sfm.mlg_timeline import build_timeline, monitoring_at
from sfm.waveform_store import WaveformStore
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
UTC = datetime.timezone.utc
dt = datetime.datetime
BASE = dt(2026, 1, 1, tzinfo=UTC)
def _timeline(tmp_path, serial, *names):
db, store = SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "w")
for i, name in enumerate(names):
res = ingest_mlg(db, store, name, (FIX / name).read_bytes(),
file_mtime=BASE + datetime.timedelta(hours=i))
assert res["status"] == "ok", res
return build_timeline(db.query_mlg_records(serial), db.query_mlg_files(serial))
def test_sessions_gaps_and_an_event_session(tmp_path):
tl = _timeline(tmp_path, "BE12844", "BE128443067.MLG", "BE128443068.MLG")
s = tl["sessions"]
assert len(s) == 3
assert (s[0]["start"], s[0]["stop"], s[0]["ended_by"], s[0]["kind"]) == (
"2026-09-07T18:47:27", "2026-09-07T20:00:00", "Timer Stop", "monitoring")
assert s[0]["trigger_level"] == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert (s[1]["start"], s[1]["stop"], s[1]["end_after"], s[1]["end_before"]) == (
"2026-09-08T06:00:13", None, "2026-09-08T13:38:25", "2026-09-08T13:41:16")
assert s[1]["running_at_last_report"] is False
assert [(e["start"], e["stop"], e["trigger_source"]) for e in s[1]["events"]] == [
("2026-09-08T13:38:22", "2026-09-08T13:38:25", 1)]
assert (s[2]["start"], s[2]["stop"], s[2]["ended_by"]) == (
"2026-09-08T13:41:16", "2026-09-08T18:45:00", "Modem Exit")
g = tl["gaps"]
assert [(x["start"], x["stop"], x["meaning"]) for x in g] == [
("2026-09-07T20:00:00", "2026-09-08T06:00:13", "scheduled off"),
("2026-09-08T13:38:25", "2026-09-08T13:41:16", "unknown")]
assert g[0]["minutes"] == pytest.approx(600.217, abs=0.01)
assert g[1]["minutes"] == pytest.approx(2.85, abs=0.01)
assert tl["clock_steps"] == []
def test_monitoring_at(tmp_path):
tl = _timeline(tmp_path, "BE12844", "BE128443067.MLG", "BE128443068.MLG")
m = monitoring_at(tl, dt(2026, 9, 8, 10, 0))
assert (m["status"], m["ambiguous"], len(m["sessions"])) == ("monitoring", False, 1)
assert m["trigger_level"] == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert monitoring_at(tl, dt(2026, 9, 8, 13, 38, 0))["status"] == "monitoring"
assert monitoring_at(tl, dt(2026, 9, 8, 13, 40, 0))["status"] == "unknown"
off = monitoring_at(tl, dt(2026, 9, 7, 23, 0))
assert off["status"] == "not_monitoring" and off["gap"]["meaning"] == "scheduled off"
assert monitoring_at(tl, dt(2027, 1, 1))["status"] == "unknown"
assert monitoring_at(tl, dt(2026, 1, 1))["status"] == "unknown"
def test_monitoring_at_boundaries_are_inclusive(tmp_path):
tl = _timeline(tmp_path, "BE12844", "BE128443067.MLG", "BE128443068.MLG")
for at in (dt(2026, 9, 7, 18, 47, 27), dt(2026, 9, 7, 20, 0, 0), dt(2026, 9, 8, 6, 0, 13)):
assert monitoring_at(tl, at)["status"] == "monitoring", at
def test_clock_step_back_is_not_a_negative_gap(tmp_path):
tl = _timeline(tmp_path, "BE12844", "BE128443155.MLG", "BE128443156.MLG")
assert [s["start"] for s in tl["sessions"]] == [
"2026-10-31T18:47:28", "2026-11-01T06:00:13", "2026-11-01T17:47:25"]
assert all(g["minutes"] >= 0 for g in tl["gaps"])
assert [g["meaning"] for g in tl["gaps"]] == ["scheduled off"]
(step,) = tl["clock_steps"]
assert (step["previous_stop"], step["next_start"]) == ("2026-11-01T18:45:00", "2026-11-01T17:47:25")
assert step["minutes"] == pytest.approx(-57.583, abs=0.01)
m = monitoring_at(tl, dt(2026, 11, 1, 18, 0))
assert (m["status"], m["ambiguous"], len(m["sessions"])) == ("monitoring", True, 2)
def test_weekend_battery_outage_and_missed_calls(tmp_path):
tl = _timeline(tmp_path, "BE8081", "BE8081321.MLG")
s = tl["sessions"]
assert [x["start"] for x in s] == [
"2019-04-12T17:17:59", "2019-04-12T18:38:14", "2019-04-13T07:05:15", "2019-04-15T12:47:05"]
assert [x["kind"] for x in s] == ["histogram"] * 4
assert [x["ended_by"] for x in s] == ["Modem Exit", "Modem Exit", "Battery Low Exit", "Modem Exit"]
assert s[0]["stop"] == "2019-04-12T18:33:00"
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 [{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,
"file_name": "BE8081321.MLG"},
{"kind": "delivered", "unit_time": "2019-04-15T17:15:00",
"file_time": "2026-01-01T00:00:00+00:00", "file_name": "BE8081321.MLG"},
]
m = monitoring_at(tl, dt(2019, 4, 14, 12, 0))
assert m["status"] == "not_monitoring" and m["gap"]["meaning"] == "lost power"
def test_histogram_session_keeps_its_waveform_event(tmp_path):
tl = _timeline(tmp_path, "BE8081", "BE8081.MLG")
(s,) = tl["sessions"]
assert (s["start"], s["stop"], s["kind"], s["trigger_level"], s["ended_by"]) == (
"2018-02-16T15:15:31", "2018-02-16T15:15:49", "histogram", "Histogram", "Modem Exit")
(e,) = s["events"]
assert (e["start"], e["trigger_source"], e["trigger_level"]) == (
"2018-02-16T15:15:47", 2, "Geo: 0.300 in/s")
def test_event_with_an_end_bit_inside_a_histogram(tmp_path):
tl = _timeline(tmp_path, "BE9441", "BE94412.MLG")
s = tl["sessions"]
assert [(x["start"], x["stop"], x["ended_by"], x["kind"]) for x in s] == [
("2026-10-26T16:06:34", "2026-10-26T16:07:21", "Keyboard Exit", "histogram"),
("2026-10-26T17:00:36", "2026-10-26T18:53:53", "Remote Exit", "histogram")]
assert [e["description"] for e in s[0]["events"]] == ["Event Recorded Memory Full Exit"]
assert [g["meaning"] for g in tl["gaps"]] == ["stopped by a person"]
def test_call_in_kinds(tmp_path):
tl = _timeline(tmp_path, "BE6907", "BE6907750.MLG", "BE6907751.MLG")
assert [(c["kind"], c["unit_time"], c["file_name"]) for c in tl["call_ins"]] == [
("no_file", "2026-08-22T18:30:00", "BE6907750.MLG"),
("delivered", "2026-08-23T18:30:00", "BE6907750.MLG"),
("nothing_new", None, "BE6907751.MLG")]
def test_no_data_gives_an_empty_timeline():
tl = build_timeline([], [])
assert tl == {"sessions": [], "gaps": [], "clock_steps": [], "call_ins": []}
assert monitoring_at(tl, dt(2026, 9, 8))["status"] == "unknown"
def test_window_filters_call_ins_by_unit_time_and_empty_files_by_file_time(tmp_path):
from sfm.mlg_timeline import window
tl = _timeline(tmp_path, "BE6907", "BE6907750.MLG", "BE6907751.MLG") # files at BASE, BASE+1h (UTC)
late = window(tl, dt(2026, 8, 23), None)
assert [(c["kind"], c["unit_time"]) for c in late["call_ins"]] == [("delivered", "2026-08-23T18:30:00")]
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"