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
131 lines
4.9 KiB
Python
131 lines
4.9 KiB
Python
"""
|
|
sfm/mlg_ingest.py — take in one Blastware .MLG: verify it, work out its unit,
|
|
keep the original, store its records once.
|
|
|
|
Shared by POST /db/import/mlg_file and scripts/import_mlg_dir.py. Spec:
|
|
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §3, §5, §6.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import hashlib
|
|
import logging
|
|
import re
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
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,
|
|
header_serial: Optional[str],
|
|
hint: Optional[str],
|
|
known: set[str],
|
|
) -> Optional[str]:
|
|
"""The unit a .MLG belongs to.
|
|
|
|
The serial inside the file wins; then the caller's hint. An empty file
|
|
carries none, and its name is <serial><counter> with nothing between, so
|
|
take the longest serial SFM already knows that the name starts with,
|
|
followed only by digits (or nothing: DL2's first file was BE8081.MLG).
|
|
None when nothing fits."""
|
|
if header_serial:
|
|
return header_serial
|
|
if hint:
|
|
return hint
|
|
stem = Path(file_name).name
|
|
if stem.upper().endswith(".MLG"):
|
|
stem = stem[:-4]
|
|
def fits(serial: str) -> bool:
|
|
counter = stem[len(serial):]
|
|
return stem.upper().startswith(serial.upper()) and (counter == "" or counter.isdigit())
|
|
|
|
candidates = [s for s in known if fits(s)]
|
|
return max(candidates, key=len) if candidates else None
|
|
|
|
|
|
def ingest_mlg(
|
|
db,
|
|
store,
|
|
file_name: str,
|
|
data: bytes,
|
|
*,
|
|
serial_hint: Optional[str] = None,
|
|
file_mtime: Optional[datetime.datetime] = None,
|
|
call_in: bool = True,
|
|
) -> dict:
|
|
"""Ingest one .MLG. Never raises for a bad file: the result says what happened.
|
|
|
|
status "error": not a whole .MLG, or any record fails its checksum — nothing
|
|
of it is stored. status "duplicate": this name with these bytes is already
|
|
stored. status "ok": the original is kept and its new records stored."""
|
|
result = {
|
|
"filename": file_name, "status": "error", "detail": None, "serial": None,
|
|
"serial_unresolved": False, "empty": False, "records": 0,
|
|
"inserted": 0, "skipped": 0, "file_id": None,
|
|
}
|
|
try:
|
|
mlg = parse_mlg(data)
|
|
except MlgFormatError as exc:
|
|
result["detail"] = str(exc)
|
|
return result
|
|
result["records"] = len(mlg.records)
|
|
result["empty"] = mlg.empty
|
|
if mlg.crc_failures:
|
|
result["detail"] = ", ".join(f"record {i}" for i in mlg.crc_failures) + " fails its checksum"
|
|
return result
|
|
|
|
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"
|
|
result["detail"] = "this file is already stored"
|
|
return result
|
|
|
|
stored_path = store.save_mlg(serial, file_name, data)
|
|
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"
|
|
result["detail"] = "this file is already stored"
|
|
return result
|
|
result.update(status="ok", file_id=file_id, inserted=inserted, skipped=skipped)
|
|
log.info("mlg %s serial=%s inserted=%d skipped=%d", file_name, serial, inserted, skipped)
|
|
return result
|