From ba826dfac61ef77eaf7d547dcdd0b6ac00b5a096 Mon Sep 17 00:00:00 2001 From: serversdown Date: Fri, 13 Nov 2026 14:17:08 -0500 Subject: [PATCH] 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 ; 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 Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1 --- docs/instantel_protocol_reference.md | 5 +- .../2026-11-09-mlg-unit-timeline-design.md | 3 +- sfm/database.py | 17 +- sfm/mlg_ingest.py | 30 ++- sfm/mlg_timeline.py | 190 +++++++++++++----- sfm/server.py | 27 ++- sfm/waveform_store.py | 5 +- tests/fixtures/mlg-11-9-26/BE6907899.MLG | Bin 0 -> 894 bytes tests/fixtures/mlg-11-9-26/BE6907900.MLG | Bin 0 -> 18 bytes tests/fixtures/mlg-11-9-26/BE6907901.MLG | Bin 0 -> 18 bytes tests/fixtures/mlg-11-9-26/BE6907902.MLG | Bin 0 -> 894 bytes tests/test_import_mlg_dir.py | 9 +- tests/test_mlg_file.py | 2 +- tests/test_mlg_ingest.py | 25 +++ tests/test_mlg_routes.py | 20 ++ tests/test_mlg_timeline.py | 103 +++++++++- 16 files changed, 359 insertions(+), 77 deletions(-) create mode 100644 tests/fixtures/mlg-11-9-26/BE6907899.MLG create mode 100644 tests/fixtures/mlg-11-9-26/BE6907900.MLG create mode 100644 tests/fixtures/mlg-11-9-26/BE6907901.MLG create mode 100644 tests/fixtures/mlg-11-9-26/BE6907902.MLG diff --git a/docs/instantel_protocol_reference.md b/docs/instantel_protocol_reference.md index eefc7f9..7f38019 100644 --- a/docs/instantel_protocol_reference.md +++ b/docs/instantel_protocol_reference.md @@ -3599,8 +3599,9 @@ Measured on the three DL2 units unless marked: - 38 files of the 1,273 hold more than one Modem Exit. - 🔶 Inferred: the call failed, or the PC did not take it. - **Empty files:** BE6907 writes one or two 2–3 minutes after nearly every real call-in (230 of - its 369 files). BE12844 and BE8081 never do. 🔶 Inferred: the unit calls back and has nothing - new. + its 369 files). BE12844 never does; BE8081 did once in 707 (`BE80811.MLG`, 2018-02-19). So the + 231 empty DL2 files are BE6907's 230 and that one. 🔶 Inferred: the unit calls back and has + nothing new. - **The unit's clock steps back an hour at the first call-in after daylight saving ends.** On 2026-11-01 BE12844 ran `06:00:13 → 18:45:00` (still EDT), called in at 17:46 EST, and its next session is `17:47:25 → 18:45:00`; BE6907 likewise. 🔶 Inferred: Blastware sets the unit's clock diff --git a/docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md b/docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md index 8dc86a7..f5a67b6 100644 --- a/docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md +++ b/docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md @@ -112,7 +112,8 @@ not part of the build. Windows converts with the offset in force at zip time, not the one at the file's date. A robocopy copy keeps the true time. - **BE6907 writes two empty files 2–3 minutes after nearly every real one** (230 of its 369). - BE12844 and BE8081 never do. Inferred: the unit calls back in and has nothing new. + BE12844 never does; BE8081 did once in 707 (`BE80811.MLG`, 2018-02-19; corrected 2026-11-13 + by the final review). Inferred: the unit calls back in and has nothing new. - **Some files hold more than one Modem Exit:** 38 files (BE8081 33, BE6907 3, BE12844 2). A file is written just after its *last* Modem Exit. The earlier ones are calls that left no file. Example: `BE8081321` holds Modem Exits on 2019-04-12 18:33, 04-13 07:00 and 04-15 17:15. diff --git a/sfm/database.py b/sfm/database.py index 530ea86..557cd42 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -167,8 +167,10 @@ CREATE TABLE IF NOT EXISTS mlg_files ( empty INTEGER NOT NULL, -- 1: the 18-byte prefix alone call_in INTEGER NOT NULL DEFAULT 1, -- 0: a cable / direct download file_mtime TEXT, -- the file's modified time, when the sender gave it - received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%S+00:00', 'now')), stored_path TEXT, -- the original file, relative to the waveform store + last_stop TEXT, -- the stop of the file's last record: the call that sent it + no_file_stops TEXT, -- JSON: earlier Modem Exit stops in it, calls that left no file UNIQUE(file_name, sha256) ); CREATE INDEX IF NOT EXISTS idx_mlg_files_serial ON mlg_files(serial); @@ -1320,25 +1322,30 @@ class SeismoDb: file_mtime: Optional[datetime.datetime], stored_path: Optional[str], records: list[MlgRecord], + last_stop: Optional[datetime.datetime] = None, + no_file_stops: Optional[list[datetime.datetime]] = None, ) -> tuple[Optional[str], int, int]: """Store one .MLG file and its log records, in one transaction. Returns (file_id, inserted, skipped); (None, 0, 0) when this file name with these bytes is already stored. A record already stored (from an - earlier file) is skipped and keeps pointing at that file.""" + earlier file) is skipped and keeps pointing at that file; the file's own + call summary (last_stop, no_file_stops) is kept on its row either way.""" file_id = self._new_id() inserted = skipped = 0 + no_file_json = json.dumps([self._iso(t) for t in (no_file_stops or [])]) with self._connect() as conn: try: conn.execute( """ INSERT INTO mlg_files (id, serial, file_name, sha256, size, record_count, empty, - call_in, file_mtime, stored_path) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + call_in, file_mtime, stored_path, last_stop, no_file_stops) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (file_id, serial, file_name, sha256, size, len(records), int(empty), - int(call_in), self._iso(file_mtime), stored_path), + int(call_in), self._iso(file_mtime), stored_path, self._iso(last_stop), + no_file_json), ) except sqlite3.IntegrityError: return None, 0, 0 diff --git a/sfm/mlg_ingest.py b/sfm/mlg_ingest.py index 8dd3d2e..2e10e54 100644 --- a/sfm/mlg_ingest.py +++ b/sfm/mlg_ingest.py @@ -11,6 +11,7 @@ from __future__ import annotations import datetime import hashlib import logging +import re from pathlib import Path from typing import Optional @@ -18,6 +19,15 @@ from minimateplus.mlg_file import MlgFormatError, parse_mlg log = logging.getLogger("sfm.mlg_ingest") +_MODEM_EXIT = 0x0020 +# A serial becomes a directory in the waveform store, and a header serial comes +# from the file's own bytes: only plain serials (BE6907, UM20147) are used. +_SERIAL_RE = re.compile(r"[A-Za-z0-9]{1,16}") + + +def usable_serial(serial: Optional[str]) -> bool: + return bool(serial) and _SERIAL_RE.fullmatch(serial) is not None + def resolve_serial( file_name: str, @@ -78,10 +88,27 @@ def ingest_mlg( 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()) + header = mlg.serial or None + for label, value in (("the file's serial", header), ("the serial hint", serial_hint)): + if value is not None and not usable_serial(value): + result["detail"] = f"{label} {value!r} is not a plain serial" + return result + known = db.known_serials() if not (header or serial_hint) else set() + serial = resolve_serial(file_name, header, serial_hint, known) + if mlg.records and serial is None: + result["detail"] = "no serial: the file's header carries none and no hint was given" + return result result["serial"] = serial result["serial_unresolved"] = serial is None + # What this file says about calls, kept per file: a record stored once may + # have arrived first in another file (a cable download). The file was sent + # by the call that ended its last record; every earlier Modem Exit in it was + # a call that left no file. + last_stop = mlg.records[-1].stop if mlg.records else None + no_file_stops = [r.stop for r in mlg.records[:-1] + if not r.is_start and r.flags & _MODEM_EXIT and r.stop] + sha256 = hashlib.sha256(data).hexdigest() if db.mlg_file_exists(file_name, sha256): result["status"] = "duplicate" @@ -92,6 +119,7 @@ def ingest_mlg( 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, + last_stop=last_stop, no_file_stops=no_file_stops, ) if file_id is None: # stored between the check and the insert result["status"] = "duplicate" diff --git a/sfm/mlg_timeline.py b/sfm/mlg_timeline.py index 3749c85..088daaa 100644 --- a/sfm/mlg_timeline.py +++ b/sfm/mlg_timeline.py @@ -8,21 +8,27 @@ 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 + 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. +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 -from collections import defaultdict +import json from dataclasses import dataclass from typing import Optional @@ -30,7 +36,6 @@ 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 @@ -42,10 +47,22 @@ _GAP_MEANING = { "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 +# . 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 @@ -55,7 +72,11 @@ class _Rec: def _dt(value: Optional[str]) -> Optional[datetime.datetime]: - return datetime.datetime.fromisoformat(value) if value else None + 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]: @@ -67,8 +88,8 @@ def _ended_by(flags: int) -> Optional[str]: def _kind(r: _Rec) -> str: - if r.flags == _STARTED: - return "start" + 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" @@ -77,56 +98,96 @@ def _kind(r: _Rec) -> str: 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": []} + "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, + "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 - - def last_running_point(s: dict) -> datetime.datetime: - return s["events"][-1]["stop"] if s["events"] else s["start"] + 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_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) - sessions.append(_session(r.start, stop=r.stop, kind="histogram", - ended_by=_ended_by(r.flags), trigger_level=r.trigger_level)) + 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 last is not None and last["stop"] is not None and last["start"] <= r.start <= last["stop"]: + 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: @@ -134,60 +195,83 @@ def _sessions(recs: list[_Rec]) -> list[dict]: 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)) + 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) + pending["end_after"] = _last_running_point(pending) return sessions -def _gaps_and_steps(sessions: list[dict]) -> tuple[list[dict], list[dict]]: +def _counter(file_name: str, serial: Optional[str]) -> Optional[int]: + """The call-in number in .MLG; a bare .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}) - else: - gaps.append({"start": end, "stop": nxt["start"], "minutes": minutes, - "meaning": _GAP_MEANING.get(prev["ended_by"], "unknown")}) + 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(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) +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 - 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}) + 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 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}) + 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(_dt(r["start_time"]), _dt(r["stop_time"]), r["flags"], r["trigger_source"], - r["trigger_level"], r["seq"]) for r in records), + (_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) - gaps, steps = _gaps_and_steps(sessions) + 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]) @@ -197,8 +281,7 @@ def build_timeline(records: list[dict], files: list[dict]) -> dict: 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)} + return {"sessions": sessions, "gaps": gaps, "clock_steps": steps, "call_ins": _call_ins(files)} def window(timeline: dict, from_dt: Optional[datetime.datetime], @@ -221,6 +304,8 @@ def window(timeline: dict, from_dt: Optional[datetime.datetime], 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) @@ -240,8 +325,9 @@ def monitoring_at(timeline: dict, at: datetime.datetime) -> dict: 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.""" + 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 = [] @@ -259,11 +345,15 @@ def monitoring_at(timeline: dict, at: datetime.datetime) -> dict: 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"]): + 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"]): - result.update(status="not_monitoring", gap=g, reason=g["meaning"]) + 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 diff --git a/sfm/server.py b/sfm/server.py index b82a892..a57d195 100644 --- a/sfm/server.py +++ b/sfm/server.py @@ -3075,13 +3075,19 @@ async def db_import_idf_file( # Record and timeline times are the unit's own local clock; file times are UTC. -def _parse_unit_time(value: Optional[str], name: str) -> Optional[datetime.datetime]: +def _parse_unit_time(value: Optional[str], name: str, *, required: bool = False) -> Optional[datetime.datetime]: + """A time on the unit's own clock: ISO-8601 with no UTC offset. 400 otherwise.""" if not value: + if required: + raise HTTPException(400, f"{name} is required (ISO-8601, the unit's clock)") return None try: - return datetime.datetime.fromisoformat(value) + parsed = datetime.datetime.fromisoformat(value) except ValueError: raise HTTPException(400, f"{name} is not an ISO-8601 time: {value!r}") + if parsed.tzinfo is not None: + raise HTTPException(400, f"{name} is on the unit's own clock and carries no UTC offset: {value!r}") + return parsed def _mlg_timeline(serial: str) -> dict: @@ -3104,11 +3110,13 @@ async def db_import_mlg_file( not whole, or any of whose records fails its checksum, stores nothing. The original is kept byte for byte in the waveform store. """ - try: - file_times = json.loads(mtimes) if mtimes else {} - if not isinstance(file_times, dict): + try: # all of it checked before any file is stored + raw_times = json.loads(mtimes) if mtimes else {} + if not isinstance(raw_times, dict): raise ValueError("not an object") - except ValueError as exc: + file_times = {name: datetime.datetime.fromtimestamp(float(stamp), datetime.timezone.utc) + for name, stamp in raw_times.items()} + except (ValueError, TypeError, OverflowError, OSError) as exc: raise HTTPException(400, f"mtimes must be a JSON object of file name -> unix seconds: {exc}") db, store = _get_db(), _get_store() results: list[dict] = [] @@ -3119,11 +3127,8 @@ async def db_import_mlg_file( except Exception as exc: results.append({"filename": name, "status": "error", "detail": f"read failed: {exc}"}) continue - stamp = file_times.get(name) - file_mtime = (datetime.datetime.fromtimestamp(float(stamp), datetime.timezone.utc) - if stamp is not None else None) results.append(ingest_mlg(db, store, name, data, serial_hint=serial, - file_mtime=file_mtime, call_in=call_in)) + file_mtime=file_times.get(name), call_in=call_in)) return {"count": len(results), "results": results} @@ -3150,7 +3155,7 @@ def db_unit_monitoring_at( ) -> dict: """Was the unit monitoring at `at`? monitoring / not_monitoring / unknown, with the session or gap that says so and the trigger level as logged.""" - when = _parse_unit_time(at, "at") + when = _parse_unit_time(at, "at", required=True) return {"serial": serial, "at": at, **mlg_monitoring_at(_mlg_timeline(serial), when)} diff --git a/sfm/waveform_store.py b/sfm/waveform_store.py index 8670347..f3f8039 100644 --- a/sfm/waveform_store.py +++ b/sfm/waveform_store.py @@ -111,7 +111,10 @@ class WaveformStore: Blastware reuses some names (a cable download is always .MLG), so a name already holding different bytes gets the hash in its name instead. - Returns the path relative to the store root.""" + Returns the path relative to the store root. Raises ValueError for a + serial that is not plain letters and digits (it becomes a directory).""" + if serial is not None and not re.fullmatch(r"[A-Za-z0-9]{1,16}", serial): + raise ValueError(f"not a plain serial: {serial!r}") d = self.root / (serial or "_unresolved") / "mlg" d.mkdir(parents=True, exist_ok=True) path = d / Path(file_name).name diff --git a/tests/fixtures/mlg-11-9-26/BE6907899.MLG b/tests/fixtures/mlg-11-9-26/BE6907899.MLG new file mode 100644 index 0000000000000000000000000000000000000000..bb1320eb98a101b0f8527737d397acbb3c5dd0d7 GIT binary patch literal 894 zcmWe&U~FJu@XRYNNz5xr&0%2IQDWpofxtduTm}8L`aYDBDfnn6Z#`TJwK}baa zOp7ou2mr$Y5k~H*`Bn-BdIqKj1`3&Z`o#*qnaNfPhDN4(1_~)o8a|rCJk);g2Za$k WD2&(`c)_%g9D~AW7$L>`iw*#_ek2qC literal 0 HcmV?d00001 diff --git a/tests/fixtures/mlg-11-9-26/BE6907900.MLG b/tests/fixtures/mlg-11-9-26/BE6907900.MLG new file mode 100644 index 0000000000000000000000000000000000000000..0ea2b8d4750889a2f30190edacd585009cfb8274 GIT binary patch literal 18 ZcmWe&U~FJu@XRYNNz5xr&0%2I0RSc+1a|-c literal 0 HcmV?d00001 diff --git a/tests/fixtures/mlg-11-9-26/BE6907901.MLG b/tests/fixtures/mlg-11-9-26/BE6907901.MLG new file mode 100644 index 0000000000000000000000000000000000000000..0ea2b8d4750889a2f30190edacd585009cfb8274 GIT binary patch literal 18 ZcmWe&U~FJu@XRYNNz5xr&0%2I0RSc+1a|-c literal 0 HcmV?d00001 diff --git a/tests/fixtures/mlg-11-9-26/BE6907902.MLG b/tests/fixtures/mlg-11-9-26/BE6907902.MLG new file mode 100644 index 0000000000000000000000000000000000000000..95826ef63233570d04412ee15f0a305645e05c34 GIT binary patch literal 894 zcmWe&U~FJu@XRYNNz5xr&0%2IQDWpofxtduTm}8L`aYDBDfnn4j%Jqt!fm=%( z=KcTw85j^@6jGF#o}OBy;FDUGnxkN);GUXqrC^|EU}|8XkeR1ntl*oOY^7jmWU6PN tkm97_qX{!+n9#@Dk-|s^8dmy@3>-*d!~qr7As9Hkz|is;cER;)G5~)jFj4>j literal 0 HcmV?d00001 diff --git a/tests/test_import_mlg_dir.py b/tests/test_import_mlg_dir.py index ad5cc27..245b27e 100644 --- a/tests/test_import_mlg_dir.py +++ b/tests/test_import_mlg_dir.py @@ -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): diff --git a/tests/test_mlg_file.py b/tests/test_mlg_file.py index 755edae..7fbec3b 100644 --- a/tests/test_mlg_file.py +++ b/tests/test_mlg_file.py @@ -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 diff --git a/tests/test_mlg_ingest.py b/tests/test_mlg_ingest.py index 80b46c9..e7561b8 100644 --- a/tests/test_mlg_ingest.py +++ b/tests/test_mlg_ingest.py @@ -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"] diff --git a/tests/test_mlg_routes.py b/tests/test_mlg_routes.py index 1f3e7af..2472af2 100644 --- a/tests/test_mlg_routes.py +++ b/tests/test_mlg_routes.py @@ -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") == [] diff --git a/tests/test_mlg_timeline.py b/tests/test_mlg_timeline.py index f766aa8..b9d46c4 100644 --- a/tests/test_mlg_timeline.py +++ b/tests/test_mlg_timeline.py @@ -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"