From faa371a73b177be6e375df57467ccc6431047038 Mon Sep 17 00:00:00 2001 From: serversdown Date: Fri, 13 Nov 2026 13:48:13 -0500 Subject: [PATCH] feat(mlg): each unit's monitoring timeline, and was it monitoring at T sfm/mlg_timeline.py builds, from a unit's stored records: sessions (with how each ended, its events and its trigger level as logged), the gaps between them and what each means (call-in, scheduled off, lost power, stopped by a person, memory full), clock steps (a session starting before the previous one stopped, as at the end of daylight saving), and call-ins: delivered, no_file (a Modem Exit that left no file) and nothing_new (an empty file). monitoring_at() answers monitoring / not_monitoring / unknown, never claiming more than the records show. Tested on real files, including BE8081's weekend: Battery Low Exit Saturday 10:47, back Monday 12:47, two calls that left no file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1 --- sfm/mlg_timeline.py | 235 +++++++++++++++++++++++++++++++++++++ tests/test_mlg_timeline.py | 150 +++++++++++++++++++++++ 2 files changed, 385 insertions(+) create mode 100644 sfm/mlg_timeline.py create mode 100644 tests/test_mlg_timeline.py diff --git a/sfm/mlg_timeline.py b/sfm/mlg_timeline.py new file mode 100644 index 0000000..f5fa9f2 --- /dev/null +++ b/sfm/mlg_timeline.py @@ -0,0 +1,235 @@ +""" +sfm/mlg_timeline.py — a unit's monitoring timeline from its .MLG records. + +Pure: takes the rows SeismoDb.query_mlg_records / query_mlg_files return and +gives back plain dicts (times as ISO strings). Spec §4, +docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md. + +How sessions appear in a .MLG (measured on BE6907, BE12844, BE8081): + * a session with no events is one closed record: start, stop and why it stopped + * a session with events is a "monitoring started" record (flags 0xFFFF, no + stop), then the events; the unit calls in after each event and monitoring + resumes as a new session, so the first session's end is not written + anywhere -- it lies between its last event's stop and the next start + * a histogram session is a "monitoring started" record at T, then a histogram + record from T+1 s to the stop, carrying the stop reason + +Times are the unit's own clock. When it steps back an hour after daylight +saving ends, a session starts before the previous one stopped: that is a clock +step, never a negative gap. +""" + +from __future__ import annotations + +import datetime +from collections import defaultdict +from dataclasses import dataclass +from typing import Optional + +from minimateplus.event_file_io import monitor_log_description + +_STARTED = 0xFFFF +_RECORDED = 0x0001 +_MODEM_EXIT = 0x0020 +_HISTOGRAM_SOURCE = 0x0400 +_JOIN_SECONDS = 2 # a histogram record starts 1 s after its "started" record + +_GAP_MEANING = { + "Modem Exit": "call-in", + "Timer Stop": "scheduled off", + "Battery Low Exit": "lost power", + "Keyboard Exit": "stopped by a person", + "Remote Exit": "stopped by a person", + "Memory Full Exit": "memory full", +} + + +@dataclass +class _Rec: + start: datetime.datetime + stop: Optional[datetime.datetime] + flags: int + source: int + trigger_level: Optional[str] + seq: int + + +def _dt(value: Optional[str]) -> Optional[datetime.datetime]: + return datetime.datetime.fromisoformat(value) if value else None + + +def _iso(value: Optional[datetime.datetime]) -> Optional[str]: + return value.isoformat() if value else None + + +def _ended_by(flags: int) -> Optional[str]: + return monitor_log_description(flags & ~_RECORDED & 0xFFFF).strip() or None + + +def _kind(r: _Rec) -> str: + if r.flags == _STARTED: + return "start" + if r.flags & _RECORDED: + return "histogram" if r.source == _HISTOGRAM_SOURCE else "event" + return "closed" + + +def _session(start, *, stop=None, ended_by=None, kind="monitoring", trigger_level=None) -> dict: + return {"start": start, "stop": stop, "end_after": None, "end_before": None, + "ended_by": ended_by, "kind": kind, "trigger_level": trigger_level, + "running_at_last_report": False, "events": []} + + +def _event(r: _Rec) -> dict: + return {"start": r.start, "stop": r.stop, "trigger_source": r.source, + "trigger_level": r.trigger_level, + "description": monitor_log_description(r.flags).strip()} + + +def _sessions(recs: list[_Rec]) -> list[dict]: + sessions: list[dict] = [] + pending: Optional[dict] = None # a session whose stop is not known yet + + def last_running_point(s: dict) -> datetime.datetime: + return s["events"][-1]["stop"] if s["events"] else s["start"] + + def close_pending(before: datetime.datetime) -> None: + nonlocal pending + if pending is not None: + pending["end_after"] = last_running_point(pending) + pending["end_before"] = before + pending = None + + for r in recs: + kind = _kind(r) + if kind == "start": + close_pending(r.start) + pending = _session(r.start, trigger_level=r.trigger_level) + sessions.append(pending) + elif kind == "histogram": + if pending is not None and (r.start - pending["start"]).total_seconds() <= _JOIN_SECONDS: + pending.update(stop=r.stop, kind="histogram", ended_by=_ended_by(r.flags)) + pending["trigger_level"] = pending["trigger_level"] or r.trigger_level + pending = None + else: + close_pending(r.start) + sessions.append(_session(r.start, stop=r.stop, kind="histogram", + ended_by=_ended_by(r.flags), trigger_level=r.trigger_level)) + elif kind == "event": + last = sessions[-1] if sessions else None + if last is not None and last["stop"] is not None and last["start"] <= r.start <= last["stop"]: + last["events"].append(_event(r)) + elif pending is not None: + pending["events"].append(_event(r)) + if _ended_by(r.flags): + pending.update(stop=r.stop, ended_by=_ended_by(r.flags)) + pending = None + else: + s = _session(r.start, trigger_level=r.trigger_level) + s["events"].append(_event(r)) + if _ended_by(r.flags): + s.update(stop=r.stop, ended_by=_ended_by(r.flags)) + else: + pending = s + sessions.append(s) + else: + close_pending(r.start) + sessions.append(_session(r.start, stop=r.stop, ended_by=_ended_by(r.flags), + trigger_level=r.trigger_level)) + if pending is not None: + pending["running_at_last_report"] = True + pending["end_after"] = last_running_point(pending) + return sessions + + +def _gaps_and_steps(sessions: list[dict]) -> tuple[list[dict], list[dict]]: + gaps, steps = [], [] + for prev, nxt in zip(sessions, sessions[1:]): + end = prev["stop"] or prev["end_after"] + minutes = (nxt["start"] - end).total_seconds() / 60 + if nxt["start"] < end: + steps.append({"previous_stop": end, "next_start": nxt["start"], "minutes": minutes}) + else: + gaps.append({"start": end, "stop": nxt["start"], "minutes": minutes, + "meaning": _GAP_MEANING.get(prev["ended_by"], "unknown")}) + return gaps, steps + + +def _call_ins(records: list[dict], files: list[dict]) -> list[dict]: + by_file: dict[str, list[dict]] = defaultdict(list) + for r in records: + by_file[r["file_id"]].append(r) + out = [] + for f in files: + if not f["call_in"]: + continue + name = f["file_name"] + file_time = f["file_mtime"] or f["received_at"] + recs = sorted(by_file.get(f["id"], []), key=lambda r: r["seq"]) + if not recs: + out.append({"kind": "nothing_new", "unit_time": None, "file_time": file_time, + "file_name": name}) + continue + for r in recs[:-1]: + if r["flags"] != _STARTED and r["flags"] & _MODEM_EXIT: + out.append({"kind": "no_file", "unit_time": r["stop_time"], "file_time": None, + "file_name": name}) + out.append({"kind": "delivered", "unit_time": recs[-1]["stop_time"], + "file_time": file_time, "file_name": name}) + return out + + +def build_timeline(records: list[dict], files: list[dict]) -> dict: + """Sessions, gaps (with what each means), clock steps and call-ins.""" + recs = sorted( + (_Rec(_dt(r["start_time"]), _dt(r["stop_time"]), r["flags"], r["trigger_source"], + r["trigger_level"], r["seq"]) for r in records), + key=lambda r: (r.start, 0 if r.flags == _STARTED else 1, r.seq), + ) + sessions = _sessions(recs) + gaps, steps = _gaps_and_steps(sessions) + for s in sessions: + for key in ("start", "stop", "end_after", "end_before"): + s[key] = _iso(s[key]) + for e in s["events"]: + e["start"], e["stop"] = _iso(e["start"]), _iso(e["stop"]) + for g in gaps: + g["start"], g["stop"] = _iso(g["start"]), _iso(g["stop"]) + for c in steps: + c["previous_stop"], c["next_start"] = _iso(c["previous_stop"]), _iso(c["next_start"]) + return {"sessions": sessions, "gaps": gaps, "clock_steps": steps, + "call_ins": _call_ins(records, files)} + + +def monitoring_at(timeline: dict, at: datetime.datetime) -> dict: + """Was the unit monitoring at `at` (its own clock)? + + monitoring: inside a session (boundaries included); two sessions matching + (the repeated hour after a clock step back) set ambiguous. unknown: inside + a session's unrecorded end, after its last report, or where no record + reaches. not_monitoring: inside a gap, with what the gap means.""" + result = {"status": "unknown", "ambiguous": False, "sessions": [], "gap": None, + "trigger_level": None, "reason": "no record covers this time"} + matches = [] + for s in timeline["sessions"]: + start, end = _dt(s["start"]), _dt(s["stop"]) or _dt(s["end_after"]) + if start <= at <= end: + matches.append(s) + if matches: + result.update(status="monitoring", ambiguous=len(matches) > 1, sessions=matches, + trigger_level=matches[0]["trigger_level"], reason="inside a monitoring session") + return result + for s in timeline["sessions"]: + if s["stop"] is not None or _dt(s["end_after"]) >= at: + continue + if s["running_at_last_report"]: + result.update(sessions=[s], reason="after the unit's last report") + return result + if at < _dt(s["end_before"]): + result.update(sessions=[s], reason="the session's end was not recorded") + return result + for g in timeline["gaps"]: + if _dt(g["start"]) < at < _dt(g["stop"]): + result.update(status="not_monitoring", gap=g, reason=g["meaning"]) + return result + return result diff --git a/tests/test_mlg_timeline.py b/tests/test_mlg_timeline.py new file mode 100644 index 0000000..3ff9a07 --- /dev/null +++ b/tests/test_mlg_timeline.py @@ -0,0 +1,150 @@ +""" +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 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"