Files
seismo-relay/sfm/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

360 lines
15 KiB
Python

"""
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, in the same file; 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. Sessions are built in start order, but an event
always joins the "monitoring started" record of its own file, so a call-in on
the step day cannot move an event into the wrong session.
Every session and call-in names the records and files it rests on, so a shot
report can attach the original .MLG (GET /db/mlg_files/{id}).
"""
from __future__ import annotations
import datetime
import json
from dataclasses import dataclass
from typing import Optional
from minimateplus.event_file_io import monitor_log_description
_STARTED = 0xFFFF
_RECORDED = 0x0001
_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",
}
# A call-in takes minutes (BE12844 2, BE8081 5, measured). A longer gap after a
# Modem Exit, with no call-in file missing, is a unit that did not restart (BE6907
# for 14 days from 2026-10-07; BE8081 over Labor Day 2019).
_LONG_CALL_IN_MINUTES = 60
NO_RESTART = "no restart after a call-in"
# Each call-in file holds everything since the previous one and is numbered
# <serial><counter>. Records can be missing only where a number is: then the
# gap cannot say the unit was not monitoring.
RECORDS_MISSING = "records missing"
_MISSING_LISTED = 20
@dataclass
class _Rec:
id: str
file_id: str
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]:
if not value:
return None
if value.endswith("Z"): # Python 3.10's fromisoformat rejects "Z"
value = value[:-1] + "+00:00"
return datetime.datetime.fromisoformat(value)
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 or r.stop is None:
return "start" # no stop: monitoring began here, its end is not known
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": [], "record_ids": [], "file_ids": []}
def _note(s: dict, r: _Rec) -> None:
s["record_ids"].append(r.id)
if r.file_id not in s["file_ids"]:
s["file_ids"].append(r.file_id)
def _event(r: _Rec) -> dict:
return {"start": r.start, "stop": r.stop, "trigger_source": r.source,
"trigger_level": r.trigger_level, "record_id": r.id,
"description": monitor_log_description(r.flags).strip()}
def _last_running_point(s: dict) -> datetime.datetime:
if s["events"]:
return s["events"][-1]["stop"] or s["events"][-1]["start"]
return s["start"]
def _sessions(recs: list[_Rec]) -> list[dict]:
sessions: list[dict] = []
pending: Optional[dict] = None # a session whose stop is not known yet
started_in_file: dict[str, dict] = {} # file id -> the session its latest start record opened
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
def own_file_session(r: _Rec) -> Optional[dict]:
s = started_in_file.get(r.file_id)
if s is None or r.start < s["start"]:
return None
if s["stop"] is not None and r.start > s["stop"]:
return None
return s
for r in recs:
kind = _kind(r)
if kind == "start":
close_pending(r.start)
pending = _session(r.start, trigger_level=r.trigger_level)
_note(pending, r)
started_in_file[r.file_id] = pending
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
_note(pending, r)
pending = None
else:
close_pending(r.start)
s = _session(r.start, stop=r.stop, kind="histogram",
ended_by=_ended_by(r.flags), trigger_level=r.trigger_level)
_note(s, r)
sessions.append(s)
elif kind == "event":
own = own_file_session(r)
last = sessions[-1] if sessions else None
if own is not None:
own["events"].append(_event(r))
_note(own, r)
if own is pending:
if _ended_by(r.flags):
own.update(stop=r.stop, ended_by=_ended_by(r.flags))
pending = None
elif own["stop"] is None:
# A later session (another file) closed its window first: the
# unit's clock stepped back at the call-in after this event.
own["end_after"] = _last_running_point(own)
if own["end_before"] is not None and own["end_after"] > own["end_before"]:
own["end_before"] = None
elif last is not None and last["stop"] is not None and last["start"] <= r.start <= last["stop"]:
last["events"].append(_event(r))
_note(last, r)
elif pending is not None:
pending["events"].append(_event(r))
_note(pending, 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))
_note(s, 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)
s = _session(r.start, stop=r.stop, ended_by=_ended_by(r.flags),
trigger_level=r.trigger_level)
_note(s, r)
sessions.append(s)
if pending is not None:
pending["running_at_last_report"] = True
pending["end_after"] = _last_running_point(pending)
return sessions
def _counter(file_name: str, serial: Optional[str]) -> Optional[int]:
"""The call-in number in <serial><counter>.MLG; a bare <serial>.MLG is 0."""
stem = file_name[:-4] if file_name.upper().endswith(".MLG") else file_name
if not serial or not stem.upper().startswith(serial.upper()):
return None
rest = stem[len(serial):]
if rest == "":
return 0
return int(rest) if rest.isdigit() else None
def _missing_between(a: Optional[int], b: Optional[int], received: set[int]) -> list[int]:
if a is None or b is None or b <= a + 1:
return []
return [c for c in range(a + 1, b) if c not in received][:_MISSING_LISTED]
def _gaps_and_steps(sessions: list[dict], counter_of: dict[str, Optional[int]],
received: set[int]) -> 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})
continue
missing = _missing_between(counter_of.get(prev["file_ids"][-1]),
counter_of.get(nxt["file_ids"][0]), received)
meaning = _GAP_MEANING.get(prev["ended_by"], "unknown")
if missing:
meaning = RECORDS_MISSING
elif meaning == "call-in" and minutes > _LONG_CALL_IN_MINUTES:
meaning = NO_RESTART
gaps.append({"start": end, "stop": nxt["start"], "minutes": minutes, "meaning": meaning,
"missing_files": missing})
return gaps, steps
def _call_ins(files: list[dict]) -> list[dict]:
"""From each file's own call summary, written when it arrived (a record
stored once may have come first in another file)."""
out = []
for f in files:
if not f["call_in"]:
continue
base = {"file_name": f["file_name"], "file_id": f["id"]}
file_time = _iso(_dt(f["file_mtime"] or f["received_at"]))
if not f["record_count"]:
out.append({"kind": "nothing_new", "unit_time": None, "file_time": file_time, **base})
continue
for stop in json.loads(f["no_file_stops"] or "[]"):
out.append({"kind": "no_file", "unit_time": stop, "file_time": None, **base})
out.append({"kind": "delivered", "unit_time": f["last_stop"], "file_time": file_time, **base})
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(r["id"], r["file_id"], _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)
counter_of = {f["id"]: _counter(f["file_name"], f["serial"]) for f in files if f["call_in"]}
received = {c for c in counter_of.values() if c is not None}
gaps, steps = _gaps_and_steps(sessions, counter_of, received)
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(files)}
def window(timeline: dict, from_dt: Optional[datetime.datetime],
to_dt: Optional[datetime.datetime]) -> dict:
"""The parts of a timeline that overlap [from_dt, to_dt] (the unit's clock).
Sessions, gaps and clock steps are on the unit's clock and filter exactly.
A call-in with a unit time filters by it. A nothing_new call-in has only
the PC's file time (UTC); it is kept when within a day of the window, since
the unit's local clock and UTC differ by hours and cannot be compared
exactly."""
lo = from_dt or datetime.datetime.min
hi = to_dt or datetime.datetime.max
def overlaps(start: Optional[str], end: Optional[str]) -> bool:
s = _dt(start) or datetime.datetime.min
e = _dt(end) or datetime.datetime.max
return s <= hi and e >= lo
def call_in_kept(c: dict) -> bool:
if c["unit_time"]:
return lo <= _dt(c["unit_time"]) <= hi
if not c["file_time"]:
return True
t = _dt(c["file_time"]).replace(tzinfo=None)
day = datetime.timedelta(days=1)
return (lo == datetime.datetime.min or t >= lo - day) and (hi == datetime.datetime.max or t <= hi + day)
return {
"sessions": [s for s in timeline["sessions"]
if overlaps(s["start"], None if s["running_at_last_report"]
else s["stop"] or s["end_before"])],
"gaps": [g for g in timeline["gaps"] if overlaps(g["start"], g["stop"])],
"clock_steps": [c for c in timeline["clock_steps"] if overlaps(c["next_start"], c["previous_stop"])],
"call_ins": [c for c in timeline["call_ins"] if call_in_kept(c)],
}
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, where a call-in file is
missing (records missing), 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 s["end_before"] is not None and 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"]):
if g["meaning"] == RECORDS_MISSING:
result.update(gap=g, reason="call-in file(s) not received: "
+ ", ".join(f"#{c}" for c in g["missing_files"]))
else:
result.update(status="not_monitoring", gap=g, reason=g["meaning"])
return result
return result