merge: monitor logs (.MLG) and each unit's monitoring timeline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-16 11:06:39 -05:00
commit 03c272316f
38 files changed
+3196 -239

No files matched your search

+18 -1
View File
@@ -31,6 +31,17 @@ Read this first when picking the project back up.
3. switch ingest so reports are kept only for checking (retire the overlay)
4. stop the watchers forwarding reports
- Until step 3, prod keeps the report as truth wherever one exists.
- **🔑 Monitor logs (.MLG) and each unit's timeline (2026-11-13, `feat/mlg-import`).**
- **What:** every unit sends an `.MLG` at every call-in, in every mode. SFM reads it
(`minimateplus/mlg_file.py`, reference D.4) and keeps each unit's monitoring timeline:
sessions, gaps and what they mean, clock steps, and the call-ins, including calls that
left no file.
- **Why (Brian, 2026-11-09):** shot reports need proof that a unit which did not trigger was
monitoring. Continuous-mode units send no file on a quiet day. Outage history is the
second use.
- **Spec:** `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md`.
- **Not yet:** the watcher still does not forward `.MLG`s (its repo, Brian's call), and
Terra-View shows none of it.
- **🔑 The Series-3 decode checker (2026-10-29; v0.33.0).**
- **Goal:** SFM produces everything Blastware reports, from the event file
alone (spec and plan in `docs/superpowers/`).
@@ -1859,10 +1870,16 @@ GET /db/monitor_log?serial=BE11529&from_dt=&to_dt= ← monitoring intervals
GET /db/sessions?serial=BE11529&limit=50 ← ACH call-home sessions, newest first
PATCH /db/events/{id}/false_trigger?value=true ← flag/unflag false triggers
GET /db/device_commands?serial=UM20147&limit=100 ← start/stop audit trail (sent, states), newest first
POST /db/import/mlg_file?serial=&call_in=true ← Blastware .MLG upload (form field mtimes = JSON {name: unix s UTC})
GET /db/units/{serial}/timeline?from_dt=&to_dt= ← sessions, gaps (+ meaning), clock steps, call-ins, from .MLGs
GET /db/units/{serial}/monitoring_at?at= ← monitoring / not_monitoring / unknown at a unit-clock time
GET /db/mlg_records?serial=BE8081&from_dt=&to_dt= ← raw .MLG records, oldest first
GET /db/mlg_files/{id} ← the original .MLG, byte for byte
```
DB file: `bridges/captures/seismo_relay.db` (default; override with `--db-path` at startup).
All DB endpoints are read-only except `PATCH /db/events/{id}/false_trigger`.
All DB endpoints are read-only except `PATCH /db/events/{id}/false_trigger` and the
`/db/import/*` uploads.
---
+132 -5
View File
@@ -11,6 +11,7 @@
| Date | Section | Change |
|---|---|---|
| 2026-11-13 | Appendix D.4 (rewritten), D.4.1–D.4.4 | ✅ **The `.MLG` format, measured.** An 18-byte prefix, then 292-byte records `[length 290 LE][id 0e a0 header / 0e 80 log][…][00 00][CRC]`. The CRC is **CRC-16/AUG-CCITT over `[0:288]`, little-endian** (3,329 / 3,329 records, 1,282 files). Fields: times with the year LE, the monitor-log flag word and trigger source LE, the serial, Blastware's text. Also: one file per call-in, how sessions appear, and a Modem Exit that is not a file's last record was a call that left no file. Cross-checked against DL2 event footers: 785 / 785 for BE8081. The old D.4.1–D.4.3 (308-byte header, CRC at the start) are kept, marked retracted. Reader/writer `minimateplus/mlg_file.py`. |
| 2026-11-11 | Appendix D.3.3 | ✅ **The footer's last two bytes are a CRC-16/AUG-CCITT** (init `0x1D0F`), big-endian, over the footer record from its length prefix `00 1a` through footer `[0:22]`: 70,041 / 70,041 DL2 files. Found by the `.MLG` session, verified here. Retracts 2026-11-08's "no common CRC-16 fits": every attempt had started at the footer itself. Same CRC family as the Series IV `0x1A` block's and the `.MLG` record's. |
| 2026-11-09 | Appendix D.6.15 (NEW), D.6.6, D.6.11 | ✅ **Over range and the mic.** **D.6.15:** a peak past full scale (2,000 units = 32,000 counts; the mic in counts) is Blastware's `OORANGE`, per channel and per histogram interval, from the unit's own summary peaks. The vector sum is `OORANGE` exactly when a geophone is (43 / 43); never on its own (38 / 38 numeric), which retracts D.6.11's open "vector sum alone" case. The `<OORANGE>` line marks the mic over (18 / 18). **D.6.6:** the mic has its own range byte (label + 29): at 1 a count is an eighth, 7 DL2 events SFM read 8× high. The dB offset is **81.938216**: [81.9383, 81.9385] was too high, and every count Blastware printed leaves [81.9382058, 81.9382266]. Blastware's mic unit labels do not hold on every report; some mix dB and psi in one column. **80 of 88 report fields now match on every DL2 event.** |
| 2026-11-08 | Appendix D.6.14 (NEW), D.3.3, D.6.11 | ✅ **The monitor log is in the footer.** Every DL2 report prints one Monitor Log line: the footer's ts1 and ts2, then words for the footer's flag word `[18:20]` (`0x0001` Event Recorded, `0x0002` Keyboard Exit, `0x0004` Remote Exit, `0x0008` Selfcheck Passed, `0x0010` Timer Stop, `0x0020` Modem Exit, `0x0200` Battery Low Exit, `0x0800` Memory Full Exit; the higher session-end bit wins, from one file). Rebuilt, it equals Blastware's character for character on 69,983 / 69,983. **D.3.3:** footer `[20:22]` is the trigger source again, `[22:24]` is zero; `[24:26]` still unknown, and no common CRC-16 or sum fits. **72 of 88 report fields now match on every DL2 event.** |
@@ -3504,11 +3505,134 @@ The footer terminates the N00 file. Its bytes come directly from the terminator
> the length prefix. It is the same CRC family as the Series IV `0x1A` block's and the `.MLG`
> record's (D.4).
### D.4 MLG File Format — Monitor Log
### D.4 MLG File Format — Monitor Log ✅ 2026-11-13
**File layout:** `[308B header] [N × 292B records]`
Measured on **1,273 DL2 files** from Blastware's ACH folder (`C:\Blastware 10\Event\autocall
home`: BE6907 and BE12844 from 2026, BE8081 from 2018–19; local copy `~/dl2-archive/mlg/`) and
**9 bench files** (`example-events/`). Reader and writer: `minimateplus/mlg_file.py`. SFM's
storage and each unit's timeline: `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md`.
#### D.4.1 MLG Header (308 bytes)
**File layout:** an 18-byte prefix, then whole 292-byte records. The size is always
`18 + 292·n` (1,282 / 1,282 files) ✅.
#### D.4.1 The prefix and the records ✅
| Offset | Bytes | Field |
|---|---|---|
| 0 | 18 | prefix `10 00 01 80 00 00 "Instantel\0" 07 2c` (the event file's first 18 bytes) |
| 18 | 292 | the header record (absent in an empty file) |
| 310 | 292 × n | log records |
Every record, header and log alike:
| Offset | Bytes | Field |
|---|---|---|
| 0 | 2 | length, uint16 **LE** = `0x0122` (290): the bytes after it |
| 2 | 2 | id: `0e a0` the header record (always first), `0e 80` a log record |
| 4 | 284 | content (D.4.2) |
| 288 | 2 | `00 00`, not covered by the CRC |
| 290 | 2 | CRC (D.4.3), **LE** |
- **The header record** holds only the serial, at `[24:34]` (NUL-padded ASCII). Every other
byte of it is zero on all 1,273 DL2 files.
- **An empty file** is the 18-byte prefix alone: no header record, no serial. 231 of the 1,273
DL2 files are empty.
This is the same `[length][id][payload]` shape as the event file's record chain (D.6.13); the
log record's id `0e` is the footer's. The old reading below (a 308-byte header, a CRC at each
record's start) cut every record two bytes early: the "CRC" it saw at `record[0:2]` was the
previous record's tail.
#### D.4.2 A log record's fields ✅
Offsets from the record's length field:
| Offset | Bytes | Field |
|---|---|---|
| 4 | 8 | start: day, month, year **LE**, 0, hour, minute, second (D.2) |
| 12 | 8 | stop, same format; all zeros = no stop |
| 20 | 2 | monitor-log flag word, uint16 LE: the event footer's (D.3.3, D.6.14); `0xFFFF` = monitoring started |
| 22 | 2 | trigger source, uint16 LE: `0x0001`–`0x0008` a channel, `0x0400` a histogram, 0 none |
| 24 | 10 | serial, NUL-padded ASCII |
| 34 | 254 | text, NUL-padded |
**The text** (Blastware's, not the unit's: see below):
- **"monitoring started":** `Trigger Level : Geo: 0.0500 in/s Mic: 125.0 dB(L)`, or
`Trigger Level : Histogram`
- **an event:** `08`, then the event's time in 8 bytes (year LE), then
`Geo: 0.0500 in/s Mic: 125.0 dB(L)\rTran: 0.0500 in/s`
- **a histogram:** `08`, its time, `Histogram\r`
- **a closed session:** `Geo: 0.0500 in/s Mic: 125.0 dB(L)`
⚠ **The text is written by Blastware.** Two bench copies of the same three records
(`ach-vs-manual/BE11529.MLG`, `BE115292.MLG`) differ only in `Trigger Level: Histogram` vs
`Trigger Level : Histogram`, and so in their CRCs. A record's identity is its times, flag word
and trigger source, never its text.
#### D.4.3 The CRC ✅ solved 2026-11-09
**CRC-16/AUG-CCITT** (poly `0x1021`, init `0x1D0F`, no reflection), over `record[0:288]` (from
the length field), stored **little-endian** at `[290:292]`. It matches **3,329 / 3,329** records
(1,282 files, header records included).
It is the same rule as the Series IV setup blocks (`content[0:2]` = N, CRC over `[0:N-2]`, stored
at `[N:N+2]`) and the event footer (D.3.3), which store it big-endian.
`minimateplus/crc.py` computes it for all three.
#### D.4.4 How Blastware writes them, and how a session appears
Measured on the three DL2 units unless marked:
- **One file per call-in**, named `<serial><counter>.MLG` with nothing between, e.g.
`BE11010304.MLG`. DL2's first file has no counter (`BE8081.MLG`). The name cannot be split by
reading it; the serial inside the file is authoritative.
- **No log record appears in two call-in files.** Each holds what happened since the previous
call-in. A cable or direct download is cumulative: the bench `4-3-26-multi/BE11529.MLG`
repeats the 4-1 records.
- **A file is written 1–2 minutes after the unit stops for its call-in** ("Modem Exit"), so the
unit's clock and the PC's agree to within those minutes.
- ⚠ Through a Windows zip, file dates read an hour early from March to October (Windows
converts with the offset in force at zip time). robocopy keeps true times.
- **A Modem Exit that is not a file's last record was a call that left no file.** Example:
`BE8081321.MLG` holds Modem Exits on 2019-04-12 18:33, 04-13 07:00 and 04-15 17:15, and only
the last produced a file.
- 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 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
at the call-in.
**How a session appears:**
- **No events:** one closed record (start, stop, flag word = why it stopped).
- **With events:** a "monitoring started" record (`0xFFFF`, no stop), then one record per event
(`0x0001` + the channel).
- The unit calls in minutes after each event, and monitoring resumes as a *new* session.
- The first session's end is written nowhere; it lies between its last event's stop and the
next start.
- **A histogram:** a "monitoring started" record at T, then a histogram record from T+1 s to
the stop, carrying the stop reason (`0x0021` = Event Recorded + Modem Exit, source `0x0400`).
Waveform event records whose start falls inside it belong to that histogram session.
**Cross-check (2026-11-13, `scratch/check_mlg_vs_events.py`):** each Event Recorded record was
matched to a DL2 event file by stop time + flag word + trigger source.
- **BE8081:** 785 / 785 records match a file, and every one of its 785 event files in that period
has its record.
- **BE6907 and BE12844:** all 25 event files have a record. The 42 records with no file all stop
after 2026-08-25, where the DL2 copy ends.
- **The footer CRCs:** all 4,303 of those three units' event files pass (D.3.3).
> ⚠ **RETRACTED 2026-11-13: D.4.1–D.4.3 below (the old reading).** The 308-byte header, the CRC
> at `record[0:2]`, the big-endian times, the 4-byte "record flags" table and the unknown CRC are
> all superseded by the sections above. They are kept as history, per this document's convention.
> The 2026-11-09 note inside them (little-endian, the flag word) was the first step of the new
> reading.
#### D.4.1 (retracted) MLG Header (308 bytes)
| Offset | Length | Field | Notes |
|---|---|---|---|
@@ -3517,7 +3641,7 @@ The footer terminates the N00 file. Its bytes come directly from the terminator
| 0x2A | 8 | serial number | null-padded ASCII (e.g. `"BE11529"`) |
| 0x32 | remainder | zero pad | pads to 308 bytes total |
#### D.4.2 MLG Record (292 bytes each)
#### D.4.2 (retracted) MLG Record (292 bytes each)
| Offset | Length | Field | Notes |
|---|---|---|---|
@@ -3564,7 +3688,10 @@ The footer terminates the N00 file. Its bytes come directly from the terminator
| 1–8 | ts1 copy (8B big-endian) |
| 9+ | `"Geo: X.XXX in/s\x00"` ASCII geo threshold |
#### D.4.3 MLG CRC
#### D.4.3 (retracted) MLG CRC
> ⚠ **Solved 2026-11-09:** CRC-16/AUG-CCITT over the record from its length field, at the record's
> end (the new D.4.3 above). Every attempt below looked for it at the record's start.
The 2-byte CRC at record[0:2] uses an unconfirmed algorithm. Tested against CRC-16/CCITT, CRC-16/IBM, CRC-32 (truncated), word sums, XOR variants, and 40+ polynomial/init combinations — none matched. The writer emits `00 00`. Blastware may reject files with incorrect CRCs (impact on import unknown — TODO: test).
@@ -0,0 +1,655 @@
# Monitor logs (.MLG) and each unit's monitoring timeline — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** SFM reads Blastware `.MLG` files, stores them, and answers "was unit X monitoring at
time T?" and "when was it not, and why?" from each unit's monitoring timeline.
**Architecture:**
- **Codec library:** a pure reader and writer in `minimateplus/mlg_file.py`.
- **SFM:**
- two new tables, plus the original files kept in the waveform store
- one ingest function shared by the HTTP route and the bulk-import script
- the timeline as a pure function over stored rows, computed on each request
**Tech Stack:** Python 3.10, FastAPI, SQLite (`sfm/database.py`), pytest.
**Spec:** `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md`. Read it first: the
measured format, session shapes and anti-goals are there and are not repeated here.
## Global Constraints
- **Where to work:** worktree `~/seismo-relay-mlg`, branch `feat/mlg-import`.
- Never commit to `dev` or `main`.
- Do not touch `CHANGELOG.md` (it is written on `dev` at merge).
- **Do not edit** `minimateplus/event_file_io.py`, `decode_check.py`, `histogram_codec.py` or
`waveform_codec.py`. Another session owns them; import from them only.
- **Running tests:** `cd ~/seismo-relay-mlg && ~/seismo-relay/.venv/bin/python -m pytest …`.
- The worktree has no venv. The tests put the worktree first on `sys.path`.
- `httpx` is not installed, so `starlette.testclient` tests skip silently. Test routes by
calling the route functions directly.
- **Baseline:** 1,659 passed, 63 skipped, 0 failed. Every commit keeps 0 failed. Read the
summary line, not just the exit code.
- That baseline needs the main checkout's git-ignored fixtures in the worktree. They were
copied on 2026-11-13; without them, 13 `idf`/`save_shape` tests fail.
- If they are missing: `rsync -a --ignore-existing ~/seismo-relay/tests/fixtures/ tests/fixtures/`
- **The codec library stays pure:** `minimateplus/` never imports `sfm`, never touches a DB,
and does no I/O beyond reading a path it was given.
- **The checksum:** CRC-16/AUG-CCITT (poly `0x1021`, init `0x1D0F`, no reflection), over
`record[0:288]`, stored little-endian at `record[290:292]`. Bytes `[288:290]` are `00 00`.
- **The format:**
- prefix `10 00 01 80 00 00 "Instantel\0" 07 2c` (18 bytes), then whole 292-byte records
- each record starts with its length `22 01` (290 LE)
- id `0e a0` is the header record (always first), `0e 80` a log record
- year little-endian in every timestamp
- **Time:** unit times are naive `datetime`s on the unit's own clock, stored with
`.isoformat()` and never converted. File times are aware UTC `datetime`s.
- **Fixtures:** `tests/fixtures/` is git-ignored, so new fixtures need `git add -f`.
- **Docs:** `docs/instantel_protocol_reference.md` is LF (enforced by `tests/test_line_endings.py`).
- **Commit messages** end with:
```
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
```
## Review Focus
1. **An empty file whose name prefix matches two known serials** (`BE11010304.MLG` with both
`BE1101` and `BE11010` known) resolves to the longest, `BE11010`. Test: Task 4,
`test_empty_file_takes_the_longest_known_serial`.
2. **One request with a good file and a corrupted one** stores the good file and refuses the bad
one per file. Nothing of the bad one lands: no row, no file in the store. Test: Task 6,
`test_import_route_stores_good_file_and_refuses_bad_one`.
3. **The same open "monitoring started" record arriving in a second file** (a re-forward, or a
cable download) is stored once, despite its NULL stop. Test: Task 3,
`test_open_record_is_stored_once`.
4. **A serial with no `.MLG` data** gets an empty timeline and `unknown`, never a 500 or a
"not monitoring". Test: Task 6, `test_timeline_routes_for_unknown_serial`.
5. **`at` exactly on a session's start or stop, or inside the repeated hour after the
clock step back,** gives a defined answer: boundaries count as monitoring, and the repeated
hour is `ambiguous`. Tests: Task 5, `test_monitoring_at_boundaries_are_inclusive`,
`test_clock_step_back_is_not_a_negative_gap`.
---
### Task 1: The reader, and one shared CRC
**Files:**
- Create: `minimateplus/crc.py`, `minimateplus/mlg_file.py`, `tests/test_mlg_file.py`
- Modify: `minimateplus/models.py` (add `MlgRecord`, `MlgFile` after `MonitorLogEntry`)
- Modify: `micromate/setup_block.py:63-69` (`_crc16_aug_ccitt` calls the shared function)
- Fixtures: `tests/fixtures/mlg-11-9-26/` (force-added)
**Interfaces:**
- Produces:
- `minimateplus.crc.crc16_aug_ccitt(data: bytes) -> int`
- `models.MlgRecord`, with fields:
- `index: int`: position in the file; 0 is the header record
- `start: datetime`, `stop: Optional[datetime]`
- `flags: int`, `trigger_source: int`, `serial: str`
- `text_raw: bytes`: exactly `record[34:288]`
- `event_time: Optional[datetime]`
- `text: str`, `trigger_level: Optional[str]`, `description: str`
- `crc_ok: bool`
- property `is_start` (`flags == 0xFFFF`)
- `models.MlgFile`:
- fields `serial: Optional[str]`, `records: list[MlgRecord]` (log records only, file order)
- properties `empty` (no records and no serial) and `crc_failures -> list[int]` (the indexes)
- `mlg_file.MlgFormatError(ValueError)`, `mlg_file.MLG_PREFIX: bytes`,
`mlg_file.RECORD_SIZE = 292`
- `mlg_file.parse_mlg(data: bytes) -> MlgFile`, `mlg_file.read_mlg(path) -> MlgFile`
- [ ] **Step 1: Copy the fixtures and force-add them**
Copy into `tests/fixtures/mlg-11-9-26/` with `cp -p`:
- from `~/dl2-archive/mlg/mlg-slice/`: `BE128443065.MLG`, `BE128443067.MLG`,
`BE128443068.MLG`, `BE128443155.MLG`, `BE128443156.MLG`, `BE6907750.MLG`, `BE6907751.MLG`
- from `~/dl2-archive/mlg/mlg-slice2/`: `BE8081.MLG`, `BE8081321.MLG`
- from `~/seismo-relay/example-events/ach-vs-manual/`: `BE11529.MLG`, `BE115292.MLG`
- from `~/seismo-relay/example-events/10-26-26/`: `BE94412.MLG`
Then `git add -f tests/fixtures/mlg-11-9-26`. Expected: 12 files, about 14 KB.
- [ ] **Step 2: Write the failing tests** in `tests/test_mlg_file.py`
Use `FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"` and
`dt = datetime.datetime`.
```python
def test_crc_matches_the_micromate_rule():
from micromate.setup_block import _crc16_aug_ccitt
assert crc16_aug_ccitt(b"123456789") == _crc16_aug_ccitt(b"123456789") == 0xE5CC
def test_every_fixture_record_passes_its_checksum():
for p in FIX.glob("*.MLG"):
assert parse_mlg(p.read_bytes()).crc_failures == [], p.name
def test_closed_records(): # BE128443065
m = read_mlg(FIX / "BE128443065.MLG")
assert m.serial == "BE12844" and len(m.records) == 2
r1, r2 = m.records
assert (r1.index, r1.start, r1.stop, r1.flags, r1.trigger_source) == (
1, dt(2026, 9, 5, 18, 47, 26), dt(2026, 9, 5, 20, 0, 0), 0x0010, 0)
assert r1.description == "Timer Stop"
assert r1.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert (r2.start, r2.stop, r2.description) == (
dt(2026, 9, 6, 6, 0, 13), dt(2026, 9, 6, 18, 45, 0), "Modem Exit")
def test_monitoring_started_and_an_event(): # BE128443067
m = read_mlg(FIX / "BE128443067.MLG")
start, ev = m.records[1], m.records[2]
assert start.is_start and start.stop is None and start.description == "Monitoring started"
assert start.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert (ev.flags, ev.trigger_source, ev.description) == (0x0001, 0x0001, "Event Recorded")
assert ev.event_time == dt(2026, 9, 8, 13, 38, 22)
assert ev.text == "Geo: 0.0500 in/s Mic: 125.0 dB(L)\rTran: 0.0500 in/s"
assert ev.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
def test_histogram_with_a_waveform_event(): # BE8081.MLG
r = read_mlg(FIX / "BE8081.MLG").records
assert (r[1].flags, r[1].trigger_source, r[1].description) == (
0x0021, 0x0400, "Event Recorded Modem Exit")
assert r[1].trigger_level == "Histogram"
assert (r[2].trigger_source, r[2].trigger_level) == (0x0002, "Geo: 0.300 in/s")
def test_trigger_level_with_or_without_a_space_before_the_colon():
a = read_mlg(FIX / "BE11529.MLG").records[0]
b = read_mlg(FIX / "BE115292.MLG").records[0]
assert a.text == "Trigger Level: Histogram" and b.text == "Trigger Level : Histogram"
assert a.trigger_level == b.trigger_level == "Histogram"
def test_empty_file():
m = read_mlg(FIX / "BE6907751.MLG")
assert m.serial is None and m.records == [] and m.empty
def test_a_flipped_byte_fails_only_its_record():
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 292 + 40] ^= 0xFF # inside record 1's text
m = parse_mlg(bytes(data))
assert m.crc_failures == [1]
assert m.records[0].crc_ok is False and m.records[1].crc_ok is True
@pytest.mark.parametrize("mangle", [
lambda d: d[:-1], # not 18 + 292·n
lambda d: b"\x00" + d[1:], # wrong prefix
lambda d: d[:18] + b"\x23" + d[19:], # header length field not 290
])
def test_structure_errors_raise(mangle):
with pytest.raises(MlgFormatError):
parse_mlg(mangle((FIX / "BE128443065.MLG").read_bytes()))
```
- [ ] **Step 3: Run them to verify they fail**
Run: `~/seismo-relay/.venv/bin/python -m pytest tests/test_mlg_file.py -q`
Expected: collection error, `ModuleNotFoundError: minimateplus.crc`.
- [ ] **Step 4: Implement**
**The shared CRC.** `crc16_aug_ccitt` uses the same bitwise loop as `setup_block`. Point
`setup_block._crc16_aug_ccitt` at it, keeping the name, since its tests import it.
**Timestamps.** A timestamp is `day, month, year LE (2 bytes), 0, hour, minute, second`, and
all-zero means `None`.
**`parse_mlg` raises `MlgFormatError`, naming the record, when:**
- `len < 18`, or the prefix differs
- `(len - 18) % 292 != 0`
- any record's length field is not 290
- record 0's id is not `0e a0`, or a later record's id is not `0e 80`
- a start time cannot be decoded
**A checksum failure does not raise.** It only sets `crc_ok=False`.
**The text:**
- If `text_raw[0] == 0x08`, then `event_time` is `text_raw[1:9]` and the text starts at
`text_raw[9]`.
- `text` is the bytes up to the first NUL, latin-1.
- `trigger_level` is `text`'s first line (split on `\r`), with a leading `Trigger Level :` or
`Trigger Level:` removed and stripped. An empty result is `None`.
**`description`** is `"Monitoring started"` for `is_start`. Otherwise it is
`event_file_io.monitor_log_description(flags).strip()`.
**The header record** gives `MlgFile.serial` (`record[24:34]`, NUL-stripped ASCII).
- [ ] **Step 5: Run the tests, then the whole suite**
Run: `~/seismo-relay/.venv/bin/python -m pytest tests/test_mlg_file.py tests/test_micromate_setup.py -q`
Expected: all pass.
Then the full suite. Expected: `0 failed`.
- [ ] **Step 6: Commit**
```bash
git add minimateplus/crc.py minimateplus/mlg_file.py minimateplus/models.py micromate/setup_block.py tests/test_mlg_file.py
git commit -m "feat(mlg): read Blastware .MLG files, every record's checksum verified"
```
---
### Task 2: The writer, and the old MLG code retired
**Files:**
- Modify: `minimateplus/mlg_file.py` (add the writer)
- Modify: `minimateplus/blastware_file.py`:
- delete `_build_mlg_header`, `_build_mlg_record`, the old `write_mlg`, the `read_mlg` stub,
`_MLG_*` and `MLG_FLAGS_*`
- the module docstring's MLG sections become one line pointing at `minimateplus/mlg_file.py`
- ⚠ **Do not re-export from `blastware_file`.** `event_file_io` imports `blastware_file`
and `mlg_file` imports `event_file_io`, so a re-export makes an import cycle. Nothing outside
`blastware_file.py` uses the old names (checked 2026-11-13).
- Test: `tests/test_mlg_file.py`
**Interfaces:**
- Consumes: `MlgFile`, `MlgRecord` (Task 1)
- Produces:
- `mlg_file.mlg_bytes(mlg: MlgFile) -> bytes`
- `mlg_file.write_mlg(mlg: MlgFile, path) -> None`
- [ ] **Step 1: Write the failing tests**
```python
@pytest.mark.parametrize("name", sorted(p.name for p in FIX.glob("*.MLG")))
def test_rebuilds_every_fixture_byte_for_byte(name):
raw = (FIX / name).read_bytes()
assert mlg_bytes(parse_mlg(raw)) == raw
def test_old_mlg_code_is_gone():
import minimateplus.blastware_file as bw
assert not hasattr(bw, "read_mlg") and not hasattr(bw, "MLG_FLAGS_TRIGGER")
```
- [ ] **Step 2: Run them to verify they fail** (`ImportError: mlg_bytes`)
- [ ] **Step 3: Implement `mlg_bytes`**
Write the prefix, then for a non-empty file the header record:
- length, id `0e a0`, zeros, the serial at `[24:34]`, zeros, then the CRC
Every other byte of the header record is zero on all 1,273 DL2 files (measured).
Then each log record, from its fields:
- length, id `0e 80`, both times, flags and source LE, the serial
- `text_raw`, then `00 00`, then the CRC
An empty `MlgFile` is the prefix alone. Confirm nothing else imports the deleted names:
`grep -rn "MLG_FLAGS_\|_build_mlg\|_MLG_" --include=*.py .`
- [ ] **Step 4: Run the tests and the full suite.** Expected: 12 rebuilds pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): write .MLG files as Blastware does; retire the old writer"`
---
### Task 3: Storage
**Files:**
- Modify: `sfm/database.py`: the two tables appended to `_SCHEMA`, and the methods below.
- The docstring's table list gains both tables.
- No migration: `CREATE … IF NOT EXISTS` runs on every start.
- Modify: `sfm/waveform_store.py`: add `save_mlg`
- Test: `tests/test_mlg_storage.py`
**Interfaces:**
- Consumes: `MlgRecord` (Task 1)
- Produces:
- `WaveformStore.save_mlg(serial: Optional[str], file_name: str, data: bytes) -> str`.
- Writes `<root>/<serial or "_unresolved">/mlg/<file_name>` and returns that path
relative to the root (posix).
- If that path already holds different bytes, it uses `<stem>.<sha256[:8]><suffix>`.
- If it holds the same bytes, it reuses the path.
- `SeismoDb.mlg_file_exists(file_name: str, sha256: str) -> bool`
- `SeismoDb.insert_mlg(*, serial, file_name, sha256, size, empty, call_in, file_mtime, stored_path, records) -> tuple[Optional[str], int, int]`
- One transaction; returns `(file_id, inserted, skipped)`.
- Returns `(None, 0, 0)` when `(file_name, sha256)` already exists.
- `SeismoDb.query_mlg_records(serial: str, from_dt=None, to_dt=None) -> list[dict]`:
- ascending by `start_time`, then `seq`
- keys: `id, serial, start_time, stop_time, flags, trigger_source, text, trigger_level,
event_time, file_id, seq`
- `SeismoDb.query_mlg_files(serial: str) -> list[dict]`:
- ascending by `COALESCE(file_mtime, received_at)`
- keys: `id, serial, file_name, sha256, size, record_count, empty, call_in, file_mtime,
received_at, stored_path`
- `SeismoDb.get_mlg_file(file_id: str) -> Optional[dict]`
- `SeismoDb.known_serials() -> set[str]`: distinct non-null serials from `events`,
`mlg_files` and `mlg_records`
Schema:
```sql
CREATE TABLE IF NOT EXISTS mlg_files (
id TEXT PRIMARY KEY, serial TEXT, file_name TEXT NOT NULL, sha256 TEXT NOT NULL,
size INTEGER NOT NULL, record_count INTEGER NOT NULL, empty INTEGER NOT NULL,
call_in INTEGER NOT NULL DEFAULT 1, file_mtime TEXT,
received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
stored_path TEXT, UNIQUE(file_name, sha256));
CREATE TABLE IF NOT EXISTS mlg_records (
id TEXT PRIMARY KEY, serial TEXT NOT NULL, start_time TEXT NOT NULL, stop_time TEXT,
flags INTEGER NOT NULL, trigger_source INTEGER NOT NULL, text TEXT, trigger_level TEXT,
event_time TEXT, file_id TEXT NOT NULL REFERENCES mlg_files(id), seq INTEGER NOT NULL);
CREATE UNIQUE INDEX IF NOT EXISTS ux_mlg_records_identity
ON mlg_records(serial, start_time, COALESCE(stop_time, ''), flags, trigger_source);
CREATE INDEX IF NOT EXISTS idx_mlg_files_serial ON mlg_files(serial);
```
- [ ] **Step 1: Write the failing tests**
- `test_insert_and_query_round_trip`: insert BE128443067's records; query returns 3 rows in
start order, with the open record's `stop_time` None.
- `test_same_file_twice_is_a_duplicate`: the second `insert_mlg` returns `(None, 0, 0)` and
there is still one file row.
- `test_open_record_is_stored_once`: insert the same `MlgFile` under two names (as a cable
download would arrive). The second returns `inserted == 0, skipped == 3`.
- `test_records_differing_only_in_text_are_the_same_record`: `BE11529.MLG`, then
`BE115292.MLG`. The second is `(id, 0, 3)`.
- `test_known_serials`, and `test_save_mlg_keeps_both_when_names_collide`: same name,
different bytes, two paths.
- [ ] **Step 2: Run them to verify they fail** (`AttributeError: insert_mlg`)
- [ ] **Step 3: Implement** the schema and the methods above. `record_count` is
`len(records)`.
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): store .MLG files and records, each record once"`
---
### Task 4: Ingest
**Files:**
- Create: `sfm/mlg_ingest.py`, `tests/test_mlg_ingest.py`
**Interfaces:**
- Consumes: `parse_mlg`, `MlgFormatError` (Task 1); `insert_mlg`, `mlg_file_exists`,
`known_serials`, `save_mlg` (Task 3)
- Produces:
- `resolve_serial(file_name: str, header_serial: Optional[str], hint: Optional[str], known: set[str]) -> Optional[str]`
- `ingest_mlg(db, store, file_name: str, data: bytes, *, serial_hint=None, file_mtime: Optional[datetime]=None, call_in: bool=True) -> dict`
Keys: `filename, status ("ok" | "duplicate" | "error"), detail, serial, serial_unresolved,
empty, records, inserted, skipped, file_id`.
**Rules:**
- **Serial:** the header serial wins. Otherwise the hint. Otherwise the longest known serial
that the name starts with (case-insensitive), as long as only digits follow it before
`.MLG`. Otherwise `None`.
- **Order of work:**
1. parse
2. a `MlgFormatError`, or any checksum failure, is `status "error"`, with `detail` naming
the record (e.g. `"record 1 fails its checksum"`); nothing is written
3. `mlg_file_exists` gives `"duplicate"`
4. `save_mlg`
5. `insert_mlg`
- [ ] **Step 1: Write the failing tests** (a tmp `SeismoDb` and `WaveformStore`, as
`tests/test_db_snapshot_endpoints.py::_client` builds them)
- `test_ingest_ok`: BE128443067 gives `status "ok"`, serial `BE12844`, `records 3`,
`inserted 3`. The file exists in the store under `BE12844/mlg/`.
- `test_ingest_twice_is_duplicate`
- `test_corrupted_file_stores_nothing`: flip byte `18+292+40`. Expect `"error"`, `"record 1"`
in `detail`, no `mlg_files` row, and no `mlg/` directory in the store.
- `test_truncated_file_is_an_error`
- `test_empty_file_takes_known_serial`: ingest `BE6907750` then `BE6907751`. The second is
`serial "BE6907"`, `empty True`.
- `test_empty_file_without_known_serial_is_unresolved`: serial `None`,
`serial_unresolved True`, stored under `_unresolved/mlg/`.
- `test_empty_file_takes_the_longest_known_serial`:
- `resolve_serial("BE11010304.MLG", None, None, {"BE1101", "BE11010"}) == "BE11010"`
- `resolve_serial("XY123.MLG", None, None, {"BE1101"}) is None`
- `resolve_serial("BE6907751.MLG", "BE12844", "BE6907", {"BE6907"}) == "BE12844"` (the
header wins)
- `test_file_mtime_and_call_in_are_stored`
- [ ] **Step 2: Run them to verify they fail**
- [ ] **Step 3: Implement `sfm/mlg_ingest.py`**
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): ingest one .MLG: verify, resolve the serial, keep the original"`
---
### Task 5: The timeline
**Files:**
- Create: `sfm/mlg_timeline.py`, `tests/test_mlg_timeline.py`
**Interfaces:**
- Consumes: rows from `query_mlg_records` and `query_mlg_files` (Task 3)
- Produces:
- `build_timeline(records: list[dict], files: list[dict]) -> dict`, with keys `sessions`,
`gaps`, `clock_steps`, `call_ins`. All times are ISO strings.
- **a session:** `start, stop, end_after, end_before, ended_by, kind ("histogram" |
"monitoring"), trigger_level, running_at_last_report, events`
- **an event:** `start, stop, trigger_source, trigger_level, description`
- **a gap:** `start, stop, minutes, meaning`
- **a clock step:** `previous_stop, next_start, minutes` (negative)
- **a call-in:** `kind ("delivered" | "no_file" | "nothing_new"), unit_time, file_time,
file_name`
- `monitoring_at(timeline: dict, at: datetime) -> dict`, with keys `status ("monitoring" |
"not_monitoring" | "unknown"), ambiguous, sessions, gap, trigger_level, reason`
**Rules.** These are the spec's §4 rules, made exact.
- **Sort:** records by `(start_time, 0 if flags == 0xFFFF else 1, seq)`.
- **Record kinds:**
- **start:** `flags == 0xFFFF`
- **histogram:** `flags & 1` and `trigger_source == 0x0400`
- **event:** `flags & 1` and any other non-zero source
- **closed:** everything else
- **Building sessions, walking the sorted records:**
- **A start record opens a pending session.** Close any pending one first, with
`end_after` = its last event's stop (or its own start) and `end_before` = this start.
- **A histogram record joins the pending session** when its start is ≤ 2 s after the pending
start, giving the session `stop` and `kind "histogram"`. Otherwise it is a session of its
own.
- **An event record:**
- joins the last session if its start lies within that session's `[start, stop]`
- otherwise it joins the pending session
- an event carrying an end bit closes a pending (non-histogram) session at its stop
- with no session to join, it opens one at its own start
- **A closed record** first closes any pending session (as above, `end_before` = its start),
then is a session `[start, stop]`.
- **A session still pending at the end** has `running_at_last_report True` and
`end_after` = its last event's stop, or its start.
- **`ended_by`** is `monitor_log_description(flags & ~1).strip()` of the record that set
`stop`, or `None`. `trigger_level` is the start record's, else the stop record's.
- **Gaps:** from a session's end (`stop`, else `end_after`) to the next session's start.
- If the next start is earlier than that end, it is a clock step, not a gap.
- The meaning comes from `ended_by`:
- Modem Exit: "call-in"
- Timer Stop: "scheduled off"
- Battery Low Exit: "lost power"
- Keyboard Exit and Remote Exit: "stopped by a person"
- Memory Full Exit: "memory full"
- anything else: "unknown"
- **Call-ins**, per file in `query_mlg_files` order (`file_time` = `file_mtime`, else
`received_at`):
- **An empty file** gives `nothing_new`.
- **A `call_in` file with records** gives `delivered`, with `unit_time` = the stop of the
file's last record (by `seq`). Each Modem Exit (`flags & 0x20`, not a start) that is not
the file's last record gives `no_file`, with `unit_time` = its stop and `file_time` None.
- **Non-call-in files** give nothing.
- **`monitoring_at`:**
- **monitoring:** `start ≤ at ≤ stop`, or `≤ end_after` when the stop is unknown. Two or more
matches set `ambiguous True`.
- **unknown:** inside an unknown end window, or after `end_after` of a session running at the
last report.
- **not_monitoring:** inside a gap, with the gap.
- **unknown:** anything else, including no data.
- [ ] **Step 1: Write the failing tests.** Ingest fixtures into a tmp DB with explicit
`file_mtime` values, then call `build_timeline(db.query_mlg_records(s), db.query_mlg_files(s))`.
- `test_sessions_gaps_and_an_event_session` (BE128443067 + 068):
- three sessions: `09-07 18:47:27 → 20:00:00 "Timer Stop"`; `09-08 06:00:13`, stop None,
`end_after 13:38:25`, `end_before 13:41:16`, 1 event; `13:41:16 → 18:45:00 "Modem Exit"`
- gaps: `"scheduled off"`, `minutes ≈ 600.217`; then `"unknown"`, `≈ 2.85`
- `test_monitoring_at`, on the same data:
- `09-08 10:00` is `monitoring`, trigger level `"Geo: 0.0500 in/s Mic: 125.0 dB(L)"`
- `09-08 13:40:00` is `unknown`
- `09-07 23:00` is `not_monitoring` with meaning `"scheduled off"`
- `2027-01-01` is `unknown`
- `test_monitoring_at_boundaries_are_inclusive`: `09-07 18:47:27` and `09-07 20:00:00` are
both `monitoring`.
- `test_clock_step_back_is_not_a_negative_gap` (BE128443155 + 156):
- no gap with negative minutes
- one clock step: `previous_stop 2026-11-01T18:45:00`, `next_start 2026-11-01T17:47:25`,
`minutes ≈ -57.58`
- `monitoring_at(11-01 18:00)` is `monitoring`, `ambiguous True`, 2 sessions
- `test_weekend_battery_outage_and_missed_calls` (BE8081321 alone):
- sessions start at `04-12 17:17:59` (histogram, from the start record),
`04-12 18:38:14`, `04-13 07:05:15` ("Battery Low Exit") and `04-15 12:47:05`
- the gap `04-13 10:47:15 → 04-15 12:47:05` is `"lost power"`, `minutes ≈ 2999.83`
- two `"call-in"` gaps of `≈ 5.23`
- call-ins: `no_file` at `2019-04-12T18:33:00`, `no_file` at `2019-04-13T07:00:01`,
`delivered` at `2019-04-15T17:15:00`, with `file_name "BE8081321.MLG"`
- `monitoring_at(2019-04-14 12:00)` is `not_monitoring`, `"lost power"`
- `test_histogram_session_keeps_its_waveform_event` (BE8081.MLG):
- one session `2018-02-16 15:15:31 → 15:15:49`, `kind "histogram"`,
`trigger_level "Histogram"`
- one event with `trigger_source 2` and `trigger_level "Geo: 0.300 in/s"`
- `test_event_with_an_end_bit_inside_a_histogram` (BE94412):
- the histogram session `16:06:34 → 16:07:21` keeps its stop and `"Keyboard Exit"`
- it holds the Memory Full event
- the `17:00:36` histogram is a session of its own
- `test_call_in_kinds` (BE6907750 + 751): `no_file` at `2026-08-22T18:30:00`, `delivered` at
`2026-08-23T18:30:00`, then `nothing_new`.
- [ ] **Step 2: Run them to verify they fail**
- [ ] **Step 3: Implement `sfm/mlg_timeline.py`** (pure: no DB, no I/O)
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): each unit's monitoring timeline, and was it monitoring at T"`
---
### Task 6: Routes
**Files:**
- Modify: `sfm/server.py`: the routes go after `db_import_idf_file`
- Create: `tests/test_mlg_routes.py`
**Interfaces:**
- Consumes: `ingest_mlg` (Task 4); `build_timeline`, `monitoring_at` (Task 5); Task 3's queries
- Produces:
- `POST /db/import/mlg_file` → `db_import_mlg_file(files: list[UploadFile] = File(...), serial: Optional[str] = Query(None), call_in: bool = Query(True), mtimes: Optional[str] = Form(None))`.
`mtimes` is JSON `{filename: unix_seconds_utc}`. Returns `{"count", "results": [ingest
dicts]}`.
- `GET /db/units/{serial}/timeline?from_dt=&to_dt=` → `db_unit_timeline(...)`: the full
timeline, with sessions, gaps and call-ins filtered to those overlapping the window.
- `GET /db/units/{serial}/monitoring_at?at=` → `db_unit_monitoring_at(...)`
- `GET /db/mlg_records?serial=&from_dt=&to_dt=` → `db_mlg_records(...)`
- `GET /db/mlg_files/{file_id}` → `db_mlg_file(...)`: the original bytes as a `FileResponse`
with the original `file_name`; 404 if unknown.
- [ ] **Step 1: Write the failing tests.** Set up as `_client` does (monkeypatch `srv._db` and
`srv._store`). Call the route functions directly: `asyncio.run(...)` for the import, with
`UploadFile(file=io.BytesIO(data), filename=name)`.
- `test_import_route_stores_good_file_and_refuses_bad_one`:
- two files, BE128443065 and a corrupted copy named `BE128443099.MLG`
- results: `["ok", "error"]`
- one `mlg_files` row; only the good file under the store's `mlg/`
- `test_import_route_reads_mtimes`: `mtimes='{"BE128443065.MLG": 1788734760}'` stores
`file_mtime` `2026-09-06T22:46:00+00:00`.
- `test_timeline_and_monitoring_at_routes`, with BE8081321 imported: the timeline has 4
sessions, and `monitoring_at` at `2019-04-14T12:00:00` is `not_monitoring`.
- `test_timeline_routes_for_unknown_serial`: `BE0000` gives empty `sessions`, `gaps` and
`call_ins`, and `monitoring_at` is `unknown`.
- `test_mlg_file_route_returns_original_bytes`, and a 404 for an unknown id.
- [ ] **Step 2: Run them to verify they fail**
- [ ] **Step 3: Implement the routes.** They stay thin: parse the query, call Tasks 3–5.
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Commit**
`git commit -m "feat(mlg): /db routes: import .MLG, a unit's timeline, monitoring at T"`
---
### Task 7: Bulk import and the cross-check
**Files:**
- Create: `scripts/import_mlg_dir.py`, `scratch/check_mlg_vs_events.py`,
`tests/test_import_mlg_dir.py`
**Interfaces:**
- Consumes: `ingest_mlg` (Task 4), `parse_mlg` (Task 1), `crc16_aug_ccitt` (Task 1)
- Produces:
- **`scripts/import_mlg_dir.py <dir> --db-path P --store-root S [--dry-run] [--not-call-in]`**
- `main(argv) -> int`, following `scripts/backfill_event_shape.py`
- walks `*.MLG` (case-insensitive) recursively
- **two passes:** files with records first, then the empty ones, each oldest file time
first. Every unit's serial is then known before its empty files arrive, whatever the
folder order.
- `file_mtime` from `os.stat` as UTC
- prints counts: files, ok, duplicate, error, empty, unresolved, inserted, skipped
- dry run: parse and checksums only, nothing written
- **`scratch/check_mlg_vs_events.py <mlg dir> <event dir>`**
- matches every non-start record with the Event Recorded bit to an event file by
`(serial, stop, flag word, trigger source)`
- an event file's serial number comes from its name, via
`sfm.waveform_store._serial_number_from_bw_filename`, compared with the MLG serial's
digits
- only event files inside each serial's MLG period count (its first record's start to its
last record's stop). DL2 holds years of event files from before the `.MLG`s.
- reads each event file's footer straight from its last 28 bytes: `00 1a 0e 08`, both times
with a big-endian year, flag word and source BE. It checks the footer's CRC with
`crc16_aug_ccitt` too.
- prints matched / record-only / file-only per serial, with up to 5 examples each
- [ ] **Step 1: Write the failing test.** `test_import_dir_counts`:
- copy the fixture dir to `tmp_path`
- the dry run prints `files 12`, writes no DB file and returns 0
- a real run imports 12 files with 0 errors, and a second run reports 12 duplicates
- [ ] **Step 2: Run it to verify it fails**
- [ ] **Step 3: Implement both tools**
- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`.
- [ ] **Step 5: Run both tools on the real data, on the dev box only**
```bash
~/seismo-relay/.venv/bin/python scripts/import_mlg_dir.py ~/dl2-archive/mlg --db-path /tmp/claude-1000/mlg-check.db --store-root /tmp/claude-1000/mlg-check-store
~/seismo-relay/.venv/bin/python scratch/check_mlg_vs_events.py ~/dl2-archive/mlg ~/dl2-archive/files
```
Expected:
- 1,273 files, 0 errors, 231 empty, 0 unresolved
- BE8081: 785 matched, 0 record-only, 0 file-only
- BE6907: 6 matched, 5 record-only, 0 file-only
- BE12844: 19 matched, 37 record-only, 0 file-only
- every record-only one stops after 2026-08-25, where the DL2 copy ends
Put the numbers in the commit message.
- [ ] **Step 6: Commit**
`git commit -m "feat(mlg): bulk import, and a cross-check against the event files"`
---
### Task 8: Documentation
**Files:**
- Modify: `docs/instantel_protocol_reference.md`:
- D.4 to D.4.3 rewritten from the spec's "What was measured", each claim graded
- the old D.4.2 table kept under a ⚠ RETRACTED banner (its CRC position, BE timestamps
and flag table)
- a row in the Changelog table at the top
- Modify: `CLAUDE.md`:
- the "SFM REST API" `/db` list gains the five routes
- one line under "Where things stand" pointing at the spec
- Modify: `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md` §8: the footer CRC
note becomes "recorded on dev, `8544e9c`"
- [ ] **Step 1: Edit the three files**
- [ ] **Step 2: Run `tests/test_line_endings.py` and the full suite.** Expected: `0 failed`.
- [ ] **Step 3: Commit**
`git commit -m "docs: the .MLG format measured (reference D.4), and the new /db routes"`
@@ -0,0 +1,333 @@
# Monitor logs (.MLG) and each unit's monitoring timeline — design
**Date:** 2026-11-09 · **Branch:** `feat/mlg-import` (worktree `~/seismo-relay-mlg`) ·
**Status:** design, for review
## Why this exists
Every Series-3 unit sends a Blastware monitor log, an `.MLG` file, at every call-in, whatever mode
it is recording in. It lists each time the unit started monitoring, each event, and each time it
stopped and why. Event files cannot replace it: a unit in continuous (waveform) mode sends an event
file only when something triggers, so a quiet day leaves no file at all.
Brian named two uses (2026-11-09):
1. **Shot reports.** Every event from every unit on a site goes in the report. A unit that did not
trigger (often the farthest one) is listed as "did not trigger", with its printed `.MLG`
attached as proof it was monitoring at the time of the blast. Example: BE6907 and BE12844
monitored the same job, June to November 2026, both in continuous mode. BE6907 is much farther
away and recorded 10 events to BE12844's 55.
2. **Outage history.** It is good to know when a unit was not recording, for how long, and why. A
unit on solar and battery can die for a weekend and nobody would notice. Most units keep
recording when they cannot call in; only losing the power and then the internal battery stops
them. So this is history seen once the unit calls in again, not a live alarm.
The `.MLG` is also what the watcher's heartbeat sniffs today to show that a unit is still calling
in. SFM holding the files would later let it answer that itself.
## Goals
1. Read a Blastware `.MLG` into its records, with every record's checksum verified.
2. Accept forwarded `.MLG`s through a new import route, storing each record once.
3. Keep each unit's monitoring timeline, derived from its records: when it was recording, how each
session ended, the events inside, and the call-ins. It must answer two questions:
- was unit X monitoring at time T, and with what trigger level?
- when was it not monitoring, for how long, and why?
4. Serve the records and the timeline through `/db/*`, for Terra-View to use later.
5. Bulk-import a directory of `.MLG`s (DL2 holds about 86,000), and cross-check the records against
the event files' footers.
## Non-goals
- **The watcher forwarding `.MLG`s.** That is a change in `../series3-watcher`, Brian's call, and a
separate piece. Until it lands, `.MLG`s reach SFM only through the import route and the bulk tool.
- **Anything in Terra-View:** the timeline view, the shot report, taking "last call-in" from SFM
instead of the heartbeat. Later pieces.
- **Live "missed its call-in" alerts.** A dead unit sends nothing; this timeline shows the gap
once it is back.
- **Series 4.** Thor writes no `.MLG`.
- **Editing the event decoders** (`event_file_io.py`, `decode_check.py`, `histogram_codec.py`,
`waveform_codec.py`). Another session owns them; this project imports from them only.
## Anti-goals (would make it a failure even if it works)
- **Claiming monitoring the data does not show.** A session still open at the last call-in is
"running at the last call-in", never "running now". Where a session's end is not recorded, the
timeline says so and gives the window it lies in.
- **Dropping a damaged file or record silently.** A record that fails its checksum is reported,
never half-read into the timeline.
- **Taking the serial from the file name when the file carries it.** Names are `<serial><counter>`
with nothing between, so `BE11010304` cannot be split by reading it.
- **Mixing clocks.** Record times are the unit's own local clock. File times are the PC's. They are
stored and labelled separately.
## What was measured
Grades: **measured** means checked on the files named; **inferred** means a reading of them that
has not been tested.
**Files examined:** 1,273 `.MLG`s from DL2's `C:\Blastware 10\Event\autocall home` (BE6907 369 and
BE12844 197, from 2026; BE8081 707, 2018–19), in `~/dl2-archive/mlg/`. Also the 9 bench files in
`example-events/`. Analysis scripts used for this section are in the session scratchpad and are
not part of the build.
### The file format (measured on all 1,282 files)
- **Layout:** an 18-byte prefix `10 00 01 80 00 00 "Instantel\0" 07 2c`, then whole 292-byte
records. The size is always `18 + 292·n`.
- **Every record** is `[length uint16 LE = 0x0122 (290)][id 2 bytes] … [CRC 2 bytes]`. Id `0e a0` is
the header record (one, first, carrying the serial). Id `0e 80` is a log record.
- **Checksum:** CRC-16/AUG-CCITT (poly 0x1021, init 0x1D0F, no reflection) over the record's bytes
`[0:288]`, stored little-endian at `[290:292]`. Bytes `[288:290]` are `00 00` and not covered.
This is the rule the Micromate setup blocks use (`micromate.setup_block`). It matches **3,329 of
3,329** records, with no failures.
- The reference (D.4.2) put a CRC at the *start* of each record. That was the previous record's
tail, which is also why every file had 2 unexplained bytes at its end.
- **A log record** (offsets from its length field):
| offset | field |
|---|---|
| `[4:12]` | start: day, month, year **LE**, 0, hour, min, sec |
| `[12:20]` | stop, same format; all zeros = no stop |
| `[20:22]` | monitor-log flag word, uint16 LE: the same word as the event footer's (D.6.14) |
| `[22:24]` | trigger source, uint16 LE: `0x0001`–`0x0008` a channel, `0x0400` a histogram |
| `[24:34]` | serial, null-padded ASCII |
| `[34:…]` | text, null-padded (below) |
- **Text:**
- a "monitoring started" record: `Trigger Level : Geo: 0.0500 in/s Mic: 125.0 dB(L)`, or
`Trigger Level : Histogram`
- an event record: `08`, then the event time in 8 bytes (LE year), then
`Geo: 0.0500 in/s Mic: 125.0 dB(L)`
- a closed session: `Geo: 0.0500 in/s Mic: 125.0 dB(L)`
- **Empty files:** some files are the 18-byte prefix alone, with no records and so no serial inside.
### How Blastware writes them (measured on the 3 DL2 units)
- **One file per call-in**, named `<serial><counter>.MLG`, the counter going up by one each time.
- **No record appears in two files.** Each holds what happened since the previous call-in.
- **A file is written 1–2 minutes after the unit stops for its call-in** ("Modem Exit"). The unit's
clock and DL2's agree to within those 2 minutes.
- ⚠ Dates of files that came through a Windows zip read an hour early from March to October.
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 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.
- Inferred: the call failed, or the PC did not take it.
- Either way, this is the "missed call-in" history Brian asked about.
- **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` (unit still on EDT). It called in at 17:46 EST,
and its next session is `17:47:25 → 18:45:00`. BE6907 shows the same. So local times on that day
overlap. Inferred: Blastware sets the unit's clock at the call-in, and in spring the clock
steps forward the same way.
- **Blastware writes the text, not the unit.** The two bench copies of the same records
(`ach-vs-manual/BE11529.MLG`, `BE115292.MLG`) differ only in `Trigger Level: Histogram` vs
`Trigger Level : Histogram`. A record's identity must not include its text or its checksum.
- **Cable or direct downloads are cumulative.** The bench `4-3-26-multi/BE11529.MLG` repeats the
4-1 records. Only the call-in files hold "only what is new".
### How a session appears (measured on the 3 DL2 units)
- **A session with no events** is one closed record: start, stop and why it stopped. BE12844's day:
`06:00:13 → 18:45:00` "Modem Exit" (its call-in), then `18:47 → 20:00` "Timer Stop" (a
work-hours timer).
- **A session with events** is an open "monitoring started" record (flag word `ffff`, no stop),
then one record per event (`0x0001` + the channel). The unit calls in minutes after each event,
and monitoring resumes as a *new* session minutes later. Example, BE12844 on 9-8:
- `06:00:13` started, then an event `13:38:22 → 13:38:25` (Tran)
- a file written about a minute later
- next file: `13:41:16 → 18:45:00` "Modem Exit"
The first session's end is not written anywhere. It lies between the last event's stop and the
next session's start (inferred: the call-in after the event ended it).
- **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 (`0x0021` = Event Recorded + Modem Exit, source `0x0400`).
- **A histogram + waveform session** also has waveform event records whose start falls inside the
histogram record's span (BE8081, 5 in 2018). Example: histogram `15:15:32 → 15:15:49`, with a
Vert event `15:15:47 → 15:15:49`. Its trigger-level text says only "Histogram". The geophone
level appears only on its event records.
### Cross-check against the event files (measured)
Each "Event Recorded" record was matched to DL2's event files by **stop time + flag word + trigger
source**:
- **BE8081:** 785 / 785 records match an event file, and all 785 of its DL2 event files in that
period have a record. 714 histogram footers start exactly at the session's "monitoring started"
record; the other 71 start where the record does.
- **BE6907 / BE12844:** 25 / 25 event files have a record. The 42 records with no file all stop
after 2026-08-25, where the DL2 copy ends.
- On 2026-08-27 both units triggered at 13:00:42 / 13:00:43, the same blast.
## Design
### 1. The reader (codec library: pure, no I/O beyond the file)
`read_mlg(path)` replaces the stub in `minimateplus/blastware_file.py` and returns a new model
(`MlgFile`, `MlgRecord` in `models.py`). It does not reuse `MonitorLogEntry`, which is the live
0x0A shape. Per record:
- start, stop (None when open), flag word, trigger source
- Blastware's words, from `event_file_io.monitor_log_description()` (imported, not copied)
- the text, plus the trigger level and the event time parsed from it
- whether the checksum passed
Per file: the serial (from the header record; None for an empty file), the records, whether the
file is whole. A file whose size is not `18 + 292·n`, or with a bad prefix, raises. A record that
fails its checksum is returned flagged; the caller decides.
### 2. `write_mlg()` (last, small)
Fix it to write what Blastware writes: little-endian times, the length-led framing and the CRC.
Test: rebuild bench and DL2 files byte for byte from what the reader returns. If the header
record's unread bytes stop that, say so and leave the writer as it is.
### 3. Storage (`sfm/database.py`)
- **The original file is kept, byte for byte,** in the waveform store beside the unit's event
files. Files are tiny (18 bytes to a few KB). It is the shot-report proof, and Blastware can
open and print it. Rows alone cannot rebuild it, because Blastware's text varies.
- **`mlg_files`:** one row per file received:
- serial, file name, size, SHA-256, record count, an empty flag
- received time, and the file's modified time (UTC, when the sender gives it)
- whether it is a call-in file (default yes; a cable download is not)
The same name with the same bytes is a re-send and is skipped. Empty files all share one
hash, so the name keeps them apart. Some names have no counter (`BE8081.MLG` was DL2's first),
so name alone is not enough. This table is the call-in history, and the only trace of an empty
file.
- **`mlg_records`:** one row per log record: serial, start, stop, flag word, trigger source, text,
and the file it first came in. Stored once:
- unique on `(serial, start, stop, flag word, trigger source)`
- ⚠ an open record's stop is NULL, and SQLite treats NULLs as distinct in a UNIQUE constraint.
The key must handle that, for example with an index on `COALESCE(stop, '')`.
- **The existing `monitor_log` table is left alone.** It holds live 0x0A rows from
`bridges/ach_server.py`, which is not in production. A future SFM call-in server would write
`.MLG`-shaped records into `mlg_records` instead.
### 4. The timeline (computed when asked, not stored)
From a unit's records in time order:
- **A closed record** with no event bit is a session `[start, stop]`, ended for its reason.
- **A histogram record** is a session from its "monitoring started" record (or its own start, when
there is none) to its stop, ended for its reason.
- **A "monitoring started" record followed by events** is a session from that start. Its end is
"between the last event's stop and the next session's start".
- **A "monitoring started" record with nothing after it yet** is "running at the last call-in".
Gaps between sessions take the reason the previous session ended with:
| previous session ended with | the gap means |
|---|---|
| Modem Exit | a call-in |
| Timer Stop | scheduled off |
| Battery Low Exit | lost power |
| Keyboard Exit / Remote Exit | stopped by a person |
| Memory Full Exit | memory full |
| none known | unknown |
- **Waveform events inside a histogram session** belong to that session. They are not sessions
of their own.
- **Trigger level is reported as logged:** the session's text, plus any geophone level its event
records carry. It is never borrowed from a neighbouring session. A histogram session with no
events says "Histogram", geophone level not logged.
- **Clock steps:** a session that starts before the previous one stopped is a clock step, not an
overlap. The timeline shows it as such, with no negative gap. Times are the unit's local clock,
as SFM's event times are; `at`, `from_dt` and `to_dt` are in that clock. If `at` falls in a
repeated hour and matches two sessions, `monitoring_at` returns both and says so. The spring
step forward will show as a gap an hour too long on that one day; that is accepted.
**Call-ins** are listed by the call each file came from:
- **Delivered:** a call-in file's last Modem Exit (unit clock), paired with the file (PC clock).
- **No file:** the earlier Modem Exits in the same file. Calls that left no file.
- **Nothing new:** an empty file, at its file time.
Cable-download files are not call-ins.
### 5. Routes (`sfm/server.py`)
- `POST /db/import/mlg_file`: one or more files, an optional serial hint, each file's modified
time when the sender has it, and `call_in` (default true).
- Mirrors `/db/import/blastware_file`: each file gets its own status, and good files are stored
even when another in the same request is not.
- Per file it returns the serial, records inserted and skipped, and whether it was empty.
- A file with any failed checksum, or that is not whole, stores nothing of itself. Its status
names the record.
- `GET /db/mlg_files/{id}`: the original file, for printing or opening in Blastware.
- `GET /db/units/{serial}/timeline?from_dt=&to_dt=`: sessions (start, end or end window, how it
ended, its events, its trigger level), gaps with their meaning, and call-ins.
- `GET /db/units/{serial}/monitoring_at?at=`: `monitoring` / `not_monitoring` / `unknown`, with the
session and records that say so, and the trigger level. This is the shot report's question.
- `GET /db/mlg_records?serial=&from_dt=&to_dt=`: the raw records.
### 6. Serial of an empty file
An empty file holds no serial. Take, in order:
1. the request's serial hint
2. the longest serial SFM already knows (units, events, `.MLG` headers) that the name starts with
3. otherwise store the file with no serial and report it as unresolved
### 7. Tools
- **`scripts/import_mlg_dir.py <dir>`:** imports a directory tree of `.MLG`s straight into the DB,
with a dry run that prints the counts. Same pattern as the backfill scripts. For DL2's ~86,000.
- Every file it reads is a call-in file (it is pointed at the ACH folder's copy).
- It records file times as found, but they matter only for empty files. A zipped copy's times
are an hour early from March to October.
- The full DL2 import should come from a robocopy copy, which keeps true times.
- **`scratch/check_mlg_vs_events.py <mlg dir> <event dir>`:** the cross-check above, in both
directions, for the whole archive.
### 8. Documentation
- Rewrite the reference's D.4 (`docs/instantel_protocol_reference.md`) with the measured framing,
checksum, fields and file behaviour, keeping the old text as a retraction. Mark D.4.3 solved.
The file is CRLF: edit it with the Edit tool.
- 🔑 **The event-file footer's checksum** (D.3.3, open since April) is the same rule:
AUG-CCITT over the footer record from its length `00 1a` through byte 24, stored big-endian,
**70,041 / 70,041** DL2 files. Recorded on `dev` by the decoder session (`8544e9c`,
2026-11-11). Inferred: every record in the event file's tail chain (D.6.13) carries one.
## Testing
TDD. Fixtures go in a dated `tests/fixtures/` directory (force-added if ignored). A small set
covering each shape:
- a closed-records day (BE12844)
- a session with an event (BE12844 #3067–#3068)
- a histogram day (BE8081)
- a Battery Low Exit (BE8081)
- an empty 18-byte file (BE6907)
- a file with calls that left no file (`BE8081321`)
- the clock step back (BE12844 #3155–#3156)
- a histogram + waveform session (`BE8081.MLG`, 2018-02-16)
- the 4 bench files, including the `ach-vs-manual` pair whose text differs
Plus one file with a byte flipped, for the checksum.
The reader, the storage (including that an open record imported twice is stored once), the
timeline cases above and the routes each get tests. The full suite has 16 known failures; read the
failure list before committing.
## Left to the builder
- Model and helper names; the exact JSON shapes of the routes.
- Whether `read_mlg` moves into its own module later.
- What the header record's other bytes hold (all zero on the files seen).
- **Not in this project:** linking a session's events to SFM's stored event ids. Terra-View may
want that later. It needs a matcher, because the events table stores neither the stop time nor
the flag word, and its times moved in 0.32.0 and 0.34.0.
## Later pieces (not this project)
- **The watcher** forwards `.MLG`s with their modified time, and the heartbeat stops sniffing them.
- **Terra-View** shows each unit's timeline, puts "monitoring during the blast" on shot reports,
and takes "last call-in" from SFM.
- **BE6907's extra call-ins:** worth a look at its modem and call-home settings.
+2 -10
View File
@@ -15,6 +15,8 @@ from __future__ import annotations
import struct
from minimateplus.crc import crc16_aug_ccitt as _crc16_aug_ccitt
from .models import MicromateSetup
from .protocol import ProtocolError
@@ -23,8 +25,6 @@ class SetupChecksumError(ProtocolError):
"""A config block's trailing CRC does not match its contents."""
_CRC_POLY = 0x1021
_CRC_INIT = 0x1D0F # CRC-16/AUG-CCITT
_CONTENT_SIZE = 2092 # = content[0:2] (2090) + the 2-byte CRC
# ── Head of the block ─────────────────────────────────────────────────────────
@@ -60,14 +60,6 @@ _ACTIVE_MIC = 3 # block index (0-based)
_MIC_TYPES = {2: "linear", 9: "sound_level"}
def _crc16_aug_ccitt(data: bytes) -> int:
c = _CRC_INIT
for b in data:
c ^= b << 8
for _ in range(8):
c = ((c << 1) ^ _CRC_POLY) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
def crc_ok(content: bytes) -> bool:
"""True if a config block's trailing checksum matches its contents.
+5 -219
View File
@@ -3,7 +3,8 @@ blastware_file.py — Blastware binary file codec for bidirectional interoperabi
Reads and writes the proprietary Instantel/Blastware file formats:
Waveform events (.CE0W, .VM0H, .440, .7M0, etc.) (extension encoding UNKNOWN — see below)
.MLG — Monitor log (monitoring session history)
Monitor logs (.MLG) live in minimateplus/mlg_file.py (reader and writer, 2026-11-13).
All waveform formats share a common 22-byte file header prefix and identical
internal binary structure (same type tag 00 12 03 00, same STRT record layout).
@@ -61,27 +62,6 @@ Waveform file structure (confirmed from example-events/4-3-26-multi/M529LIY6 (ex
Timestamp format (big-endian, 8 bytes):
[day] [month] [year_HI] [year_LO] [0x00] [hour] [min] [sec]
MLG (monitor log, confirmed from example-events/4-3-26-multi/BE11529.MLG):
[308B header] [N × 292B records]
Header (308 bytes):
Offset 0x00: 10 00 01 80 00 00 Instantel\x00 07 2c 22 01 0e a0 — fixed (16B)
Offset 0x10: ... (unknown structure, written as zeros + serial)
Offset 0x2A: serial number (8 bytes, null-padded ASCII, e.g. "BE11529")
... zero-padded to 308 bytes total
Record (292 bytes each):
[2B CRC] — unknown algorithm; written as 0x00 0x00
22 01 0e 80 — record marker
[ts1: 8B big-endian timestamp] — start time
[ts2: 8B big-endian timestamp] — stop time (zeros if no stop)
[4B flags] — see MLG_FLAGS_* constants below
[10B serial] — null-padded serial number ASCII
[text] — for trigger records: [0x08][8B ts1_copy] then ASCII "Geo: X.XXX in/s"
for monitoring records: b'' (or minimal separator)
[zero-padded to 292 bytes]
─── Critical implementation notes ──────────────────────────────────────────────
Waveform body reconstruction algorithm (confirmed 2026-04-21 from verification against
@@ -110,14 +90,6 @@ M529LIY6 (example event) using raw_s3_20260403_153508.bin capture):
of frame.data, and this builder dropped it here. The parser now drops it,
so a 0x10 ending frame.data is real data (one A5 chunk in ten ends in one).
MLG CRC:
The algorithm that produces the 2-byte CRC at the start of each MLG record
is unknown. All examined records use non-zero values that do not match
CRC-16/CCITT, CRC-16/IBM, CRC-32 (truncated), word sums, XOR variants, or
any of the 40+ polynomial/init combinations tested. The writer emits 0x0000.
This produces files that Blastware may reject or display without the CRC check —
the exact impact on BW import is unknown (TODO: test).
─── Public API ──────────────────────────────────────────────────────────────────
blastware_filename(event, serial)
@@ -133,13 +105,6 @@ MLG CRC:
read_blastware_file(path) → Event
Parse a Blastware waveform file into an Event object with waveform data populated.
(Not yet implemented — placeholder raises NotImplementedError.)
write_mlg(entries, serial, path)
Create a .MLG file from a list of MonitorLogEntry objects.
read_mlg(path) → list[MonitorLogEntry]
Parse a .MLG file into MonitorLogEntry objects.
(Not yet implemented — placeholder raises NotImplementedError.)
"""
from __future__ import annotations
@@ -152,7 +117,7 @@ from pathlib import Path
from typing import Optional, Union
from .framing import S3Frame
from .models import Event, MonitorLogEntry, Timestamp
from .models import Event, Timestamp
log = logging.getLogger(__name__)
@@ -169,9 +134,6 @@ _FILE_HEADER_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c" # 17 byt
# Waveform file type tag (4 bytes after common prefix) — shared by ALL waveform extensions
_WAVEFORM_TYPE_TAG = b"\x00\x12\x03\x00" # confirmed from M529LIY6 (example event) — same tag for .CE0W, .VM0H, etc.
# MLG type tag (4 bytes after common prefix)
_MLG_TYPE_TAG = b"\x22\x01\x0e\xa0" # confirmed from BE11529.MLG offset 0x11..0x14
# Total header sizes
_WAVEFORM_HEADER_SIZE = 22 # 17 + 4 = 21... wait. Let me recalculate.
# From binary: first 22 bytes = header, then STRT at byte 22.
@@ -180,17 +142,6 @@ _WAVEFORM_HEADER_SIZE = 22 # 17 + 4 = 21... wait. Let me recalculate.
# Re-count: b"\x10\x00\x01\x80\x00\x00" = 6B + b"Instantel\x00" = 10B + b"\x07\x2c" = 2B = 18B prefix.
_FILE_HEADER_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c" # 18 bytes
_WAVEFORM_HEADER_SIZE = 22 # 18 + 4 = 22 bytes ✅
_MLG_HEADER_SIZE = 308 # confirmed from BE11529.MLG
# MLG record marker (4 bytes after 2-byte CRC at start of each record)
_MLG_RECORD_MARKER = b"\x22\x01\x0e\x80"
_MLG_RECORD_SIZE = 292 # bytes per record (confirmed from BE11529.MLG)
# MLG record flags (4 bytes at record[22:26])
# Confirmed from BE11529.MLG binary inspection:
MLG_FLAGS_START_ONLY = b"\xff\xff\x00\x00" # monitoring start with no stop
MLG_FLAGS_TRIGGER = b"\x01\x00\x02\x00" # triggered event (has ts1 + ts2)
MLG_FLAGS_INTERVAL = b"\x02\x00\x00\x00" # monitoring interval (has ts1 + ts2)
# ── Timestamp helpers ─────────────────────────────────────────────────────────
@@ -199,7 +150,8 @@ def _encode_ts_be(ts: Optional[datetime.datetime]) -> bytes:
"""
Encode a datetime as an 8-byte big-endian Blastware timestamp.
Format (waveform file and MLG record timestamps):
Format (event file timestamps; an .MLG stores the year little-endian,
see minimateplus/mlg_file.py):
[day][month][year_HI][year_LO][0x00][hour][min][sec]
Big-endian year confirmed from M529LIY6 (example event) footer:
@@ -936,169 +888,3 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
NotImplementedError: always (pending implementation).
"""
raise NotImplementedError("read_blastware_file() is not yet implemented")
# ── MLG file writer ───────────────────────────────────────────────────────────
def _build_mlg_header(serial: str) -> bytes:
"""
Build the 308-byte MLG file header.
Header structure (confirmed from BE11529.MLG binary inspection):
Offset 0x00: 10 00 01 80 00 00 Instantel\x00 07 2c 22 01 0e a0 (22B)
Offset 0x16: ... (16B unknown — observed as zeros in BE11529.MLG)
Offset 0x2A: serial number (8 bytes, null-padded ASCII)
... rest zero-padded to 308 bytes
The serial string "BE11529" appears at offset 0x2A (42 decimal).
"""
buf = bytearray(_MLG_HEADER_SIZE)
# Common prefix + MLG type tag
prefix = _FILE_HEADER_PREFIX + _MLG_TYPE_TAG # 22 bytes
buf[0:len(prefix)] = prefix
# Serial number at offset 0x2A
serial_bytes = serial.encode("ascii", errors="replace")[:8]
serial_padded = serial_bytes.ljust(8, b"\x00")
buf[0x2A : 0x2A + 8] = serial_padded
return bytes(buf)
def _build_mlg_record(
entry: MonitorLogEntry,
serial: str,
) -> bytes:
"""
Build one 292-byte MLG record from a MonitorLogEntry.
Record layout (confirmed from BE11529.MLG binary inspection):
[0:2] CRC — 2-byte CRC (algorithm unknown; written as 0x0000)
[2:6] marker — 22 01 0e 80
[6:14] ts1 — 8B big-endian start timestamp
[14:22] ts2 — 8B big-endian stop timestamp
[22:26] flags — 4B record flags (see MLG_FLAGS_* constants)
[26:36] serial — 10B null-padded serial number
[36:] text — for triggered events: [0x08][8B ts1_copy]["Geo: X.XXX in/s"]
for monitoring intervals: b"" or minimal separator
[... zero-padded to 292 bytes]
Flags based on entry type:
- MonitorLogEntry with start_time only (no stop_time): MLG_FLAGS_START_ONLY
- MonitorLogEntry with both times and geo_threshold_ips set: MLG_FLAGS_TRIGGER
- MonitorLogEntry with both times (monitoring interval): MLG_FLAGS_INTERVAL
The triggered-event text block (flags = MLG_FLAGS_TRIGGER):
[0x08] [ts1: 8B] [ASCII "Geo: X.XXX in/s\x00"]
Confirmed from BE11529.MLG records at offset 0x0134 and 0x0258.
"""
buf = bytearray(_MLG_RECORD_SIZE)
start_dt = (
datetime.datetime(
entry.start_time.year, entry.start_time.month, entry.start_time.day,
entry.start_time.hour, entry.start_time.minute, entry.start_time.second,
)
if entry.start_time else None
)
stop_dt = (
datetime.datetime(
entry.stop_time.year, entry.stop_time.month, entry.stop_time.day,
entry.stop_time.hour, entry.stop_time.minute, entry.stop_time.second,
)
if entry.stop_time else None
)
# [0:2] CRC placeholder
buf[0:2] = b"\x00\x00"
# [2:6] Record marker
buf[2:6] = _MLG_RECORD_MARKER
# [6:14] ts1
buf[6:14] = _encode_ts_be(start_dt)
# [14:22] ts2
buf[14:22] = _encode_ts_be(stop_dt)
# [22:26] flags
if stop_dt is None:
flags = MLG_FLAGS_START_ONLY
elif entry.geo_threshold_ips is not None:
flags = MLG_FLAGS_TRIGGER
else:
flags = MLG_FLAGS_INTERVAL
buf[22:26] = flags
# [26:36] serial (10B null-padded)
serial_bytes = serial.encode("ascii", errors="replace")[:10]
buf[26 : 26 + len(serial_bytes)] = serial_bytes
# [36:] text content
pos = 36
if flags == MLG_FLAGS_TRIGGER:
# Extra ts1 copy: [0x08][ts1: 8B]
buf[pos] = 0x08
pos += 1
buf[pos : pos + 8] = _encode_ts_be(start_dt)
pos += 8
if entry.geo_threshold_ips is not None:
geo_text = f"Geo: {entry.geo_threshold_ips:.3f} in/s\x00".encode("ascii")
buf[pos : pos + len(geo_text)] = geo_text
pos += len(geo_text)
return bytes(buf)
def write_mlg(
entries: list[MonitorLogEntry],
serial: str,
path: Union[str, Path],
) -> None:
"""
Write a Blastware .MLG monitor log file.
Args:
entries: List of MonitorLogEntry objects (from get_monitor_log_entries()).
Each entry produces one 292-byte record in the file.
serial: Device serial number string (e.g. "BE11529").
Written to the file header and each record.
path: Destination file path. Extension is not enforced — use ".MLG".
File layout:
[308B header] [N × 292B records]
Note: The 2-byte CRC at the start of each record is written as 0x0000.
The CRC algorithm is unknown (see module docstring).
Raises:
OSError: if the file cannot be written.
"""
path = Path(path)
header = _build_mlg_header(serial)
with open(path, "wb") as f:
f.write(header)
for entry in entries:
record = _build_mlg_record(entry, serial)
f.write(record)
def read_mlg(path: Union[str, Path]) -> list[MonitorLogEntry]:
"""
Parse a Blastware .MLG file into a list of MonitorLogEntry objects.
NOT YET IMPLEMENTED.
Args:
path: Path to the .MLG file.
Returns:
List of MonitorLogEntry objects.
Raises:
NotImplementedError: always (pending implementation).
"""
raise NotImplementedError("read_mlg() is not yet implemented")
+23
View File
@@ -0,0 +1,23 @@
"""
minimateplus/crc.py — Instantel's record checksum, shared by every reader that checks one.
CRC-16/AUG-CCITT: poly 0x1021, init 0x1D0F, no reflection, no final XOR. The
same rule covers a Micromate's setup blocks (0x1A, 0x08, 0x2E; stored big-endian),
a Blastware event file's footer (big-endian) and every .MLG record (little-endian).
Each block says where its checksum sits; this module only computes it.
"""
from __future__ import annotations
_POLY = 0x1021
_INIT = 0x1D0F
def crc16_aug_ccitt(data: bytes) -> int:
"""CRC-16/AUG-CCITT of `data` (check value: b"123456789" -> 0xE5CC)."""
c = _INIT
for b in data:
c ^= b << 8
for _ in range(8):
c = ((c << 1) ^ _POLY) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
+185
View File
@@ -0,0 +1,185 @@
"""
minimateplus/mlg_file.py — Blastware's monitor log (.MLG): reader and writer.
Blastware writes one .MLG per call-in, named <serial><counter>.MLG, holding what
the unit logged since the previous call-in: each time monitoring started, each
event, and each time it stopped and why. Measured on 1,273 DL2 files and 9
bench files (2026-11-09; reference D.4, spec
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md):
[18-byte prefix 10 00 01 80 00 00 "Instantel\\0" 07 2c]
[292-byte records ...] size is always 18 + 292*n
Every record:
[0:2] length, uint16 LE = 290
[2:4] id: 0e a0 the header record (first, carries the serial), 0e 80 a log record
[4:12] start: day, month, year LE, 0, hour, minute, second
[12:20] stop, same format; all zeros = no stop
[20:22] monitor-log flag word, uint16 LE (the event footer's, D.6.14); 0xFFFF = started
[22:24] trigger source, uint16 LE: 0x0001-0x0008 a channel, 0x0400 a histogram
[24:34] serial, NUL-padded ASCII
[34:288] text, NUL-padded; an event's starts 0x08 + its 8-byte time
[288:290] 00 00
[290:292] CRC-16/AUG-CCITT over [0:288], little-endian
An empty file is the prefix alone: no header record, no serial. Pure: no I/O
beyond reading the path it is given.
"""
from __future__ import annotations
import datetime
import struct
from pathlib import Path
from typing import Optional, Union
from .crc import crc16_aug_ccitt
from .event_file_io import monitor_log_description
from .models import MlgFile, MlgRecord
MLG_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c"
RECORD_SIZE = 292
_RECORD_LENGTH = 290
_HEADER_ID = b"\x0e\xa0"
_LOG_ID = b"\x0e\x80"
_EVENT_TIME_MARK = 0x08
_TRIGGER_LEVEL_PREFIXES = ("Trigger Level :", "Trigger Level:")
class MlgFormatError(ValueError):
"""The bytes are not a whole .MLG file."""
def _ts(raw: bytes) -> Optional[datetime.datetime]:
"""8-byte MLG time (year little-endian); all zeros = None. Raises ValueError."""
if raw == bytes(8):
return None
year = struct.unpack_from("<H", raw, 2)[0]
return datetime.datetime(year, raw[1], raw[0], raw[5], raw[6], raw[7])
def _crc_ok(record: bytes) -> bool:
return crc16_aug_ccitt(record[:288]) == struct.unpack_from("<H", record, 290)[0]
def _trigger_level(text: str) -> Optional[str]:
line = text.split("\r", 1)[0]
for prefix in _TRIGGER_LEVEL_PREFIXES:
if line.startswith(prefix):
line = line[len(prefix):]
break
line = line.strip()
return line or None
def _log_record(index: int, rec: bytes) -> MlgRecord:
try:
start = _ts(rec[4:12])
stop = _ts(rec[12:20])
except ValueError as exc:
raise MlgFormatError(f"record {index}: a time cannot be decoded ({exc})") from None
if start is None:
raise MlgFormatError(f"record {index}: no start time")
flags, source = struct.unpack_from("<HH", rec, 20)
text_raw = rec[34:288]
body, event_time = text_raw, None
if text_raw[0] == _EVENT_TIME_MARK:
try:
event_time = _ts(text_raw[1:9])
except ValueError as exc:
raise MlgFormatError(f"record {index}: the event time cannot be decoded ({exc})") from None
body = text_raw[9:]
text = body.split(b"\x00", 1)[0].decode("latin-1")
is_start = flags == 0xFFFF
return MlgRecord(
index=index,
start=start,
stop=stop,
flags=flags,
trigger_source=source,
serial=rec[24:34].split(b"\x00", 1)[0].decode("ascii", errors="replace"),
text_raw=text_raw,
event_time=event_time,
text=text,
trigger_level=_trigger_level(text),
description="Monitoring started" if is_start else monitor_log_description(flags).strip(),
crc_ok=_crc_ok(rec),
)
def parse_mlg(data: bytes) -> MlgFile:
"""Parse the bytes of a .MLG file.
Raises MlgFormatError when the bytes are not a whole .MLG. A record whose
checksum fails is returned with crc_ok=False (MlgFile.crc_failures lists
them); the caller decides what to do with it."""
if len(data) < len(MLG_PREFIX) or not data.startswith(MLG_PREFIX):
raise MlgFormatError("not an MLG: the 18-byte Instantel prefix is missing")
body = data[len(MLG_PREFIX):]
if len(body) % RECORD_SIZE:
raise MlgFormatError(f"not an MLG: size {len(data)} is not 18 + 292*n")
records = [body[i:i + RECORD_SIZE] for i in range(0, len(body), RECORD_SIZE)]
if not records:
return MlgFile(serial=None)
for index, rec in enumerate(records):
length = struct.unpack_from("<H", rec, 0)[0]
if length != _RECORD_LENGTH:
raise MlgFormatError(f"record {index}: length field {length}, expected 290")
expected = _HEADER_ID if index == 0 else _LOG_ID
if rec[2:4] != expected:
raise MlgFormatError(f"record {index}: id {rec[2:4].hex()}, expected {expected.hex()}")
header = records[0]
return MlgFile(
serial=header[24:34].split(b"\x00", 1)[0].decode("ascii", errors="replace"),
records=[_log_record(i, rec) for i, rec in enumerate(records) if i > 0],
header_crc_ok=_crc_ok(header),
)
def read_mlg(path: Union[str, Path]) -> MlgFile:
"""Read and parse a .MLG file."""
return parse_mlg(Path(path).read_bytes())
# ── Writer ────────────────────────────────────────────────────────────────────
def _ts_bytes(ts: Optional[datetime.datetime]) -> bytes:
if ts is None:
return bytes(8)
return bytes([ts.day, ts.month]) + struct.pack("<H", ts.year) + bytes([0, ts.hour, ts.minute, ts.second])
def _serial_field(serial: str) -> bytes:
return serial.encode("ascii", errors="replace")[:10].ljust(10, b"\x00")
def _sealed(body: bytes) -> bytes:
"""`body` is record[0:288]; append the two zero bytes and the LE checksum."""
return body + b"\x00\x00" + struct.pack("<H", crc16_aug_ccitt(body))
def _header_record(serial: str) -> bytes:
# Every byte but the serial is zero on all 1,273 DL2 files (measured 2026-11-13).
body = struct.pack("<H", _RECORD_LENGTH) + _HEADER_ID + bytes(20) + _serial_field(serial)
return _sealed(body.ljust(288, b"\x00"))
def _log_record_bytes(r: MlgRecord) -> bytes:
body = (struct.pack("<H", _RECORD_LENGTH) + _LOG_ID + _ts_bytes(r.start) + _ts_bytes(r.stop)
+ struct.pack("<HH", r.flags, r.trigger_source) + _serial_field(r.serial)
+ r.text_raw.ljust(254, b"\x00")[:254])
return _sealed(body)
def mlg_bytes(mlg: MlgFile) -> bytes:
"""The bytes of a .MLG file, as Blastware writes them: little-endian times,
length-led records, each record's checksum computed. An empty MlgFile is
the prefix alone."""
if mlg.empty:
return MLG_PREFIX
return MLG_PREFIX + _header_record(mlg.serial or "") + b"".join(_log_record_bytes(r) for r in mlg.records)
def write_mlg(mlg: MlgFile, path: Union[str, Path]) -> None:
"""Write `mlg` to `path` (see mlg_bytes)."""
Path(path).write_bytes(mlg_bytes(mlg))
+46
View File
@@ -729,6 +729,52 @@ class MonitorLogEntry:
return f"MonitorLog#{self.index} key={self.key} {start}→{stop}{dur}"
# ── Blastware monitor log (.MLG) ──────────────────────────────────────────────
@dataclass
class MlgRecord:
"""One log record of a Blastware .MLG file (minimateplus/mlg_file.py).
Times are the unit's own local clock. `flags` is the monitor-log flag word
(the event footer's, reference D.6.14); 0xFFFF means monitoring started
and has no stop yet."""
index: int # position in the file; 0 is the header record
start: datetime.datetime
stop: Optional[datetime.datetime]
flags: int
trigger_source: int # 0x0001-0x0008 a channel, 0x0400 a histogram, 0 none
serial: str
text_raw: bytes = field(repr=False) # record[34:288] exactly, for write_mlg
event_time: Optional[datetime.datetime] = None
text: str = "" # Blastware's text, after any event time
trigger_level: Optional[str] = None # e.g. "Geo: 0.0500 in/s Mic: 125.0 dB(L)", "Histogram"
description: str = "" # "Monitoring started", or Blastware's words
crc_ok: bool = True
@property
def is_start(self) -> bool:
return self.flags == 0xFFFF
@dataclass
class MlgFile:
"""A whole .MLG file: the serial from its header record and its log records,
in file order. An empty file (the 18-byte prefix alone) has neither."""
serial: Optional[str]
records: list[MlgRecord] = field(default_factory=list)
header_crc_ok: bool = True
@property
def empty(self) -> bool:
return self.serial is None and not self.records
@property
def crc_failures(self) -> list[int]:
"""Indexes of the records whose checksum fails (0 is the header record)."""
head = [] if self.header_crc_ok else [0]
return head + [r.index for r in self.records if not r.crc_ok]
# ── MonitorStatus ─────────────────────────────────────────────────────────────
@dataclass
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Cross-check .MLG records against Blastware event files, in both directions.
check_mlg_vs_events.py <mlg dir> <event dir>
Every .MLG record with the Event Recorded bit (not a "monitoring started" one)
should have an event file whose footer has the same stop time, flag word and
trigger source; and every event file inside a unit's .MLG period (its first
record's start to its last record's stop) should have such a record. The
footer is read straight from each event file's last 28 bytes, independently of
the event decoder, and its CRC-16/AUG-CCITT is checked on the way.
Spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §7. Read-only.
"""
from __future__ import annotations
import collections
import datetime
import os
import struct
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from minimateplus.crc import crc16_aug_ccitt
from minimateplus.mlg_file import MlgFormatError, read_mlg
from sfm.waveform_store import _serial_number_from_bw_filename
_FOOTER_HEAD = b"\x00\x1a\x0e\x08"
def _ts_be(raw: bytes):
try:
return datetime.datetime(struct.unpack(">H", raw[2:4])[0], raw[1], raw[0], raw[5], raw[6], raw[7])
except ValueError:
return None
def _serial_number(serial: str):
digits = "".join(ch for ch in serial if ch.isdigit())
return int(digits) if digits else None
def mlg_side(mlg_dir: Path):
"""{unit number: (serial, [(stop, flags, source)], first start, last stop)}"""
units = {}
for path in sorted(p for p in mlg_dir.rglob("*") if p.is_file() and p.suffix.upper() == ".MLG"):
try:
mlg = read_mlg(path)
except MlgFormatError as exc:
print(f" skipped {path}: {exc}")
continue
if not mlg.serial or not mlg.records:
continue
n = _serial_number(mlg.serial)
serial, keys, lo, hi = units.get(n, (mlg.serial, [], None, None))
for r in mlg.records:
lo = min(lo, r.start) if lo else r.start
if r.stop:
hi = max(hi, r.stop) if hi else r.stop
if not r.is_start and r.flags & 0x0001:
keys.append((r.stop, r.flags, r.trigger_source))
units[n] = (serial, keys, lo, hi)
return units
def event_side(event_dir: Path, wanted: set):
"""{unit number: [(stop, flags, source, file name)]}, plus footer CRC failures."""
files = collections.defaultdict(list)
crc_bad = 0
for entry in os.scandir(event_dir):
if not entry.is_file():
continue
n = _serial_number_from_bw_filename(entry.name)
if n not in wanted:
continue
with open(entry.path, "rb") as f:
f.seek(0, 2)
if f.tell() < 28:
continue
f.seek(-28, 2)
tail = f.read(28)
if not tail.startswith(_FOOTER_HEAD):
continue
if crc16_aug_ccitt(tail[0:24]) != struct.unpack(">H", tail[26:28])[0]:
crc_bad += 1
flags, source = struct.unpack(">HH", tail[20:24])
files[n].append((_ts_be(tail[12:20]), flags, source, entry.name))
return files, crc_bad
def main(argv=None) -> int:
argv = argv if argv is not None else sys.argv[1:]
if len(argv) != 2:
print(__doc__)
return 2
units = mlg_side(Path(argv[0]))
files, crc_bad = event_side(Path(argv[1]), set(units))
checked = sum(len(v) for v in files.values())
print(f"event-file footers checked (units with .MLGs only): {checked}, failing their CRC: {crc_bad}")
for n, (serial, keys, lo, hi) in sorted(units.items(), key=lambda kv: kv[1][0]):
in_period = [f for f in files.get(n, []) if f[0] and lo <= f[0] <= hi]
file_keys = {f[:3] for f in in_period}
rec_keys = set(keys)
matched = [k for k in keys if k in file_keys]
record_only = [k for k in keys if k not in file_keys]
file_only = [f for f in in_period if f[:3] not in rec_keys]
print(f"\n{serial}: .MLG period {lo} -> {hi}")
print(f" matched {len(matched)}, record-only {len(record_only)}, file-only {len(file_only)}")
for k in record_only[:5]:
print(f" record-only: stop {k[0]} flags {k[1]:#06x} source {k[2]:#06x}")
if record_only:
print(f" record-only stops run {min(k[0] for k in record_only)} -> {max(k[0] for k in record_only)}")
for f in file_only[:5]:
print(f" file-only: {f[3]} stop {f[0]} flags {f[1]:#06x} source {f[2]:#06x}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Import every Blastware .MLG under a directory into SFM's DB and waveform store.
import_mlg_dir.py <dir> --db-path P --store-root S [--dry-run] [--not-call-in]
For a copy of an ACH folder (DL2 holds ~86,000). Idempotent: a file already
stored (same name, same bytes) counts as a duplicate. Files with records go
first, then the empty ones, so every unit's serial is known before its empty
files arrive whatever the folder order. Each file's modified time is stored
as its call-in time: copy with robocopy, not a Windows zip, whose dates read
an hour early from March to October.
Operational consequence: writes rows to mlg_files / mlg_records and copies each
original into <store>/<serial>/mlg/. The dry run writes nothing.
"""
from __future__ import annotations
import argparse
import datetime
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from minimateplus.mlg_file import MLG_PREFIX, MlgFormatError, parse_mlg
from sfm.database import SeismoDb
from sfm.mlg_ingest import ingest_mlg
from sfm.waveform_store import WaveformStore
log = logging.getLogger("import_mlg_dir")
_COUNTS = ("files", "ok", "duplicate", "error", "empty", "unresolved", "inserted", "skipped")
def _mlg_files(root: Path) -> list[Path]:
"""Files with records first, then empty ones; each group oldest first."""
found = [p for p in root.rglob("*") if p.is_file() and p.suffix.upper() == ".MLG"]
key = lambda p: (p.stat().st_size <= len(MLG_PREFIX), p.stat().st_mtime, p.name)
return sorted(found, key=key)
def import_dir(root: Path, db_path: str, store_root: str, *, dry_run: bool = False,
call_in: bool = True) -> dict:
counts = dict.fromkeys(_COUNTS, 0)
db = store = None
if not dry_run:
db, store = SeismoDb(db_path), WaveformStore(store_root)
for path in _mlg_files(root):
counts["files"] += 1
data = path.read_bytes()
if dry_run:
try:
mlg = parse_mlg(data)
except MlgFormatError as exc:
counts["error"] += 1
log.warning("%s: %s", path, exc)
continue
counts["error" if mlg.crc_failures else "ok"] += 1
counts["empty"] += mlg.empty
continue
mtime = datetime.datetime.fromtimestamp(path.stat().st_mtime, datetime.timezone.utc)
res = ingest_mlg(db, store, path.name, data, file_mtime=mtime, call_in=call_in)
counts[res["status"]] += 1
if res["status"] == "error":
log.warning("%s: %s", path, res["detail"])
continue
counts["empty"] += res["empty"]
counts["unresolved"] += res["serial_unresolved"]
counts["inserted"] += res["inserted"]
counts["skipped"] += res["skipped"]
return counts
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("dir")
ap.add_argument("--db-path", required=True)
ap.add_argument("--store-root", required=True)
ap.add_argument("--dry-run", action="store_true", help="parse and check only; write nothing")
ap.add_argument("--not-call-in", action="store_true",
help="these are cable / direct downloads, not call-ins")
a = ap.parse_args(argv)
logging.basicConfig(level=logging.WARNING)
counts = import_dir(Path(a.dir), a.db_path, a.store_root, dry_run=a.dry_run,
call_in=not a.not_call_in)
for key in _COUNTS:
print(f"{key} {counts[key]}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+159 -3
View File
@@ -1,11 +1,15 @@
"""
sfm/database.py — SQLite persistence layer for seismo-relay.
Three tables, all keyed by unit serial number:
Tables, all keyed by unit serial number:
ach_sessions — one row per inbound ACH call-home
events — one row per triggered waveform event (deduped by serial+timestamp)
monitor_log — one row per monitoring interval (deduped by serial+start_time)
monitor_log — one row per monitoring interval (deduped by serial+start_time);
live 0x0A reads by bridges/ach_server.py only
mlg_files — one row per Blastware .MLG received (deduped by file name+sha256)
mlg_records — one row per .MLG log record (deduped by serial, start, stop,
flag word, trigger source — never the text, which Blastware writes)
The DB file lives at:
<output_dir>/seismo_relay.db (default: bridges/captures/seismo_relay.db)
@@ -43,7 +47,7 @@ from pathlib import Path
from typing import Optional
from minimateplus.blastware_file import blastware_filename_time
from minimateplus.models import Event, MonitorLogEntry
from minimateplus.models import Event, MlgRecord, MonitorLogEntry
log = logging.getLogger("sfm.database")
@@ -150,6 +154,43 @@ CREATE TABLE IF NOT EXISTS device_commands (
states TEXT -- JSON: {"before": ..., "seen": [...], "after": ...}
);
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
-- Blastware monitor logs (.MLG): spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
-- Record times are the unit's own local clock (naive ISO); file_mtime is UTC (+00:00).
CREATE TABLE IF NOT EXISTS mlg_files (
id TEXT PRIMARY KEY,
serial TEXT, -- NULL: an empty file whose unit is not known yet
file_name TEXT NOT NULL,
sha256 TEXT NOT NULL,
size INTEGER NOT NULL,
record_count INTEGER NOT NULL, -- log records in the file (header excluded)
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:%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);
CREATE TABLE IF NOT EXISTS mlg_records (
id TEXT PRIMARY KEY,
serial TEXT NOT NULL,
start_time TEXT NOT NULL,
stop_time TEXT, -- NULL: "monitoring started", no stop yet
flags INTEGER NOT NULL, -- monitor-log flag word; 65535 = started
trigger_source INTEGER NOT NULL, -- 1-8 a channel, 1024 a histogram, 0 none
text TEXT,
trigger_level TEXT,
event_time TEXT,
file_id TEXT NOT NULL REFERENCES mlg_files(id), -- the file it first came in
seq INTEGER NOT NULL -- its position in that file (1 = first log record)
);
-- NULL stops are distinct to a UNIQUE constraint, so the identity uses COALESCE.
CREATE UNIQUE INDEX IF NOT EXISTS ux_mlg_records_identity
ON mlg_records(serial, start_time, COALESCE(stop_time, ''), flags, trigger_source);
"""
@@ -1259,6 +1300,121 @@ class SeismoDb:
).fetchall()
return [dict(r) for r in rows]
# ── Blastware monitor logs (.MLG) ─────────────────────────────────────────
def mlg_file_exists(self, file_name: str, sha256: str) -> bool:
with self._connect() as conn:
row = conn.execute(
"SELECT 1 FROM mlg_files WHERE file_name = ? AND sha256 = ?",
(file_name, sha256),
).fetchone()
return row is not None
def insert_mlg(
self,
*,
serial: Optional[str],
file_name: str,
sha256: str,
size: int,
empty: bool,
call_in: bool,
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; 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, 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, self._iso(last_stop),
no_file_json),
)
except sqlite3.IntegrityError:
return None, 0, 0
for r in records:
cur = conn.execute(
"""
INSERT OR IGNORE INTO mlg_records
(id, serial, start_time, stop_time, flags, trigger_source,
text, trigger_level, event_time, file_id, seq)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(self._new_id(), serial, self._iso(r.start), self._iso(r.stop), r.flags,
r.trigger_source, r.text, r.trigger_level, self._iso(r.event_time),
file_id, r.index),
)
if cur.rowcount:
inserted += 1
else:
skipped += 1
log.debug("insert_mlg %s inserted=%d skipped=%d", file_name, inserted, skipped)
return file_id, inserted, skipped
def query_mlg_records(
self,
serial: str,
from_dt: Optional[datetime.datetime] = None,
to_dt: Optional[datetime.datetime] = None,
) -> list[dict]:
"""A unit's .MLG records, oldest first (start time, then position in file)."""
clauses, params = ["serial = ?"], [serial]
if from_dt:
clauses.append("start_time >= ?")
params.append(from_dt.isoformat())
if to_dt:
clauses.append("start_time <= ?")
params.append(to_dt.isoformat())
with self._connect() as conn:
rows = conn.execute(
f"SELECT * FROM mlg_records WHERE {' AND '.join(clauses)} "
f"ORDER BY start_time, seq",
params,
).fetchall()
return [dict(r) for r in rows]
def query_mlg_files(self, serial: str) -> list[dict]:
"""A unit's received .MLG files, oldest file time first."""
with self._connect() as conn:
rows = conn.execute(
"SELECT * FROM mlg_files WHERE serial = ? "
"ORDER BY COALESCE(file_mtime, received_at), file_name",
(serial,),
).fetchall()
return [dict(r) for r in rows]
def get_mlg_file(self, file_id: str) -> Optional[dict]:
with self._connect() as conn:
row = conn.execute("SELECT * FROM mlg_files WHERE id = ?", (file_id,)).fetchone()
return dict(row) if row else None
def known_serials(self) -> set[str]:
"""Every serial SFM holds data for: events, .MLG files and records."""
with self._connect() as conn:
rows = conn.execute(
"SELECT serial FROM events WHERE serial IS NOT NULL "
"UNION SELECT serial FROM mlg_files WHERE serial IS NOT NULL "
"UNION SELECT serial FROM mlg_records"
).fetchall()
return {r["serial"] for r in rows if r["serial"]}
# ── Fleet overview ────────────────────────────────────────────────────────
def query_units(self) -> list[dict]:
+130
View File
@@ -0,0 +1,130 @@
"""
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
+359
View File
@@ -0,0 +1,359 @@
"""
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
+115 -1
View File
@@ -43,6 +43,7 @@ or:
from __future__ import annotations
import datetime
import json
import logging
import socket
import sys
@@ -54,7 +55,7 @@ from typing import Any, Dict, Mapping, Optional
# FastAPI / Pydantic
try:
from fastapi import Body, FastAPI, File, HTTPException, Query, Response, UploadFile
from fastapi import Body, FastAPI, File, Form, HTTPException, Query, Response, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
@@ -84,6 +85,8 @@ from sfm.live_cache import LiveCache as _LiveCache
from sfm.waveform_store import WaveformStore
from sfm import db_snapshot
from sfm.event_ingest import backfill_series3_event, persist_download
from sfm.mlg_ingest import ingest_mlg
from sfm.mlg_timeline import build_timeline, monitoring_at as mlg_monitoring_at, window as mlg_window
import dataclasses
from sfm.device_access import DeviceAccess, DeviceError, UnitAddress
from sfm.device_access.errors import BadRequest, ChangeUnconfirmed
@@ -3067,6 +3070,117 @@ async def db_import_idf_file(
return {"count": len(results), "results": results}
# ── Blastware monitor logs (.MLG) ─────────────────────────────────────────────
# Spec: docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §5.
# Record and timeline times are the unit's own local clock; file times are UTC.
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:
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:
db = _get_db()
return build_timeline(db.query_mlg_records(serial), db.query_mlg_files(serial))
@app.post("/db/import/mlg_file")
async def db_import_mlg_file(
files: list[UploadFile] = File(...),
serial: Optional[str] = Query(None, description="Serial hint, used only for a file with no serial inside (an empty one)"),
call_in: bool = Query(True, description="False for a cable / direct download: its records are kept, but it is not a call-in"),
mtimes: Optional[str] = Form(None, description='Each file\'s modified time: JSON {"<file name>": <unix seconds, UTC>}'),
) -> dict:
"""
Multipart upload of one or more Blastware .MLG monitor logs.
Each file gets its own status ("ok" / "duplicate" / "error"); good files
are stored even when another in the same request is not. A file that is
not whole, or any of whose records fails its checksum, stores nothing.
The original is kept byte for byte in the waveform store.
"""
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")
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] = []
for upload in files:
name = upload.filename or "unnamed.MLG"
try:
data = await upload.read()
except Exception as exc:
results.append({"filename": name, "status": "error", "detail": f"read failed: {exc}"})
continue
results.append(ingest_mlg(db, store, name, data, serial_hint=serial,
file_mtime=file_times.get(name), call_in=call_in))
return {"count": len(results), "results": results}
@app.get("/db/units/{serial}/timeline")
def db_unit_timeline(
serial: str,
from_dt: Optional[str] = Query(None, description="ISO-8601, the unit's clock (inclusive)"),
to_dt: Optional[str] = Query(None, description="ISO-8601, the unit's clock (inclusive)"),
) -> dict:
"""A unit's monitoring timeline from its .MLGs: sessions (how each ended,
its events, its trigger level), gaps and what each means, clock steps, and
call-ins (delivered / no_file / nothing_new)."""
lo, hi = _parse_unit_time(from_dt, "from_dt"), _parse_unit_time(to_dt, "to_dt")
timeline = _mlg_timeline(serial)
if lo or hi:
timeline = mlg_window(timeline, lo, hi)
return {"serial": serial, **timeline}
@app.get("/db/units/{serial}/monitoring_at")
def db_unit_monitoring_at(
serial: str,
at: str = Query(..., description="ISO-8601, the unit's clock"),
) -> 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", required=True)
return {"serial": serial, "at": at, **mlg_monitoring_at(_mlg_timeline(serial), when)}
@app.get("/db/mlg_records")
def db_mlg_records(
serial: str = Query(..., description="Unit serial"),
from_dt: Optional[str] = Query(None, description="ISO-8601 start (record start, inclusive)"),
to_dt: Optional[str] = Query(None, description="ISO-8601 end (record start, inclusive)"),
) -> dict:
"""A unit's raw .MLG records, oldest first."""
rows = _get_db().query_mlg_records(
serial, _parse_unit_time(from_dt, "from_dt"), _parse_unit_time(to_dt, "to_dt"))
return {"count": len(rows), "records": rows}
@app.get("/db/mlg_files/{file_id}")
def db_mlg_file(file_id: str):
"""The original .MLG, byte for byte, for printing or opening in Blastware."""
row = _get_db().get_mlg_file(file_id)
path = _get_store().root / row["stored_path"] if row and row["stored_path"] else None
if path is None or not path.is_file():
raise HTTPException(404, f"no stored .MLG with id {file_id}")
return FileResponse(path, filename=row["file_name"], media_type="application/octet-stream")
@app.get("/db/units/{serial}/waveforms.zip")
def db_unit_waveforms_zip(
serial: str,
+20
View File
@@ -30,6 +30,7 @@ Roles:
from __future__ import annotations
import datetime
import hashlib
import logging
import pickle
import re
@@ -105,6 +106,25 @@ class WaveformStore:
d.mkdir(parents=True, exist_ok=True)
return d
def save_mlg(self, serial: Optional[str], file_name: str, data: bytes) -> str:
"""Keep an original .MLG byte for byte, at <serial or _unresolved>/mlg/<file_name>.
Blastware reuses some names (a cable download is always <serial>.MLG), so
a name already holding different bytes gets the hash in its name instead.
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
if path.exists() and path.read_bytes() != data:
digest = hashlib.sha256(data).hexdigest()[:8]
path = d / f"{path.stem}.{digest}{path.suffix}"
if not path.exists():
path.write_bytes(data)
return path.relative_to(self.root).as_posix()
def paths_for(self, serial: str, filename: str) -> tuple[Path, Path]:
"""Return (blastware_path, a5_pickle_path) for a given serial+filename.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+58
View File
@@ -0,0 +1,58 @@
"""
Tests for scripts/import_mlg_dir.py — bulk import of a directory of .MLGs (spec §7).
"""
from __future__ import annotations
import os
import shutil
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from scripts.import_mlg_dir import main
from sfm.database import SeismoDb
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
def _counts(text: str) -> dict:
return {k: int(v) for k, v in (line.split() for line in text.strip().splitlines())}
def test_import_dir_counts(tmp_path, capsys):
src = tmp_path / "in" / "nested"
shutil.copytree(FIX, src)
db_path, store = tmp_path / "t.db", tmp_path / "store"
args = [str(tmp_path / "in"), "--db-path", str(db_path), "--store-root", str(store)]
assert main(args + ["--dry-run"]) == 0
dry = _counts(capsys.readouterr().out)
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"]) == (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", "BE6907899.MLG", "BE6907900.MLG",
"BE6907901.MLG", "BE6907902.MLG"]
assert main(args) == 0
again = _counts(capsys.readouterr().out)
assert (again["duplicate"], again["ok"], again["inserted"]) == (16, 0, 0)
def test_empty_files_are_resolved_whatever_the_folder_order(tmp_path, capsys):
"""The empty file sorts first by name and by time here; the two-pass order still
gives it its unit."""
d = tmp_path / "in"
d.mkdir()
shutil.copy2(FIX / "BE6907751.MLG", d / "BE6907751.MLG")
shutil.copy2(FIX / "BE6907750.MLG", d / "BE6907750.MLG")
os.utime(d / "BE6907751.MLG", (1_700_000_000, 1_700_000_000)) # older than its real file
os.utime(d / "BE6907750.MLG", (1_800_000_000, 1_800_000_000))
assert main([str(d), "--db-path", str(tmp_path / "t.db"), "--store-root", str(tmp_path / "s")]) == 0
assert _counts(capsys.readouterr().out)["unresolved"] == 0
+130
View File
@@ -0,0 +1,130 @@
"""
Tests for minimateplus/mlg_file.py — Blastware's monitor log (.MLG) reader and writer.
Fixtures (tests/fixtures/mlg-11-9-26/) are real files: DL2's ACH folder
(BE12844, BE6907 from 2026; BE8081 from 2018-19) and three bench files.
Expected values come from an independent scratch parser that was checked
against DL2's event-file footers (785 / 785 BE8081 records matched by stop,
flag word and trigger source), never from the code under test. Format:
docs/instantel_protocol_reference.md D.4, spec
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
"""
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 minimateplus.crc import crc16_aug_ccitt
from minimateplus.mlg_file import MlgFormatError, mlg_bytes, parse_mlg, read_mlg, write_mlg
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
dt = datetime.datetime
def test_crc_matches_the_micromate_rule():
from micromate.setup_block import _crc16_aug_ccitt
assert crc16_aug_ccitt(b"123456789") == _crc16_aug_ccitt(b"123456789") == 0xE5CC
def test_every_fixture_record_passes_its_checksum():
files = sorted(FIX.glob("*.MLG"))
assert len(files) == 16
for p in files:
assert parse_mlg(p.read_bytes()).crc_failures == [], p.name
def test_closed_records():
m = read_mlg(FIX / "BE128443065.MLG")
assert m.serial == "BE12844" and len(m.records) == 2
r1, r2 = m.records
assert (r1.index, r1.start, r1.stop, r1.flags, r1.trigger_source) == (
1, dt(2026, 9, 5, 18, 47, 26), dt(2026, 9, 5, 20, 0, 0), 0x0010, 0)
assert r1.description == "Timer Stop"
assert r1.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert r1.serial == "BE12844"
assert (r2.start, r2.stop, r2.description) == (
dt(2026, 9, 6, 6, 0, 13), dt(2026, 9, 6, 18, 45, 0), "Modem Exit")
def test_monitoring_started_and_an_event():
m = read_mlg(FIX / "BE128443067.MLG")
start, ev = m.records[1], m.records[2]
assert start.is_start and start.stop is None
assert start.description == "Monitoring started"
assert start.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert (ev.flags, ev.trigger_source, ev.description) == (0x0001, 0x0001, "Event Recorded")
assert ev.event_time == dt(2026, 9, 8, 13, 38, 22)
assert ev.text == "Geo: 0.0500 in/s Mic: 125.0 dB(L)\rTran: 0.0500 in/s"
assert ev.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
def test_histogram_with_a_waveform_event():
r = read_mlg(FIX / "BE8081.MLG").records
assert (r[1].flags, r[1].trigger_source, r[1].description) == (
0x0021, 0x0400, "Event Recorded Modem Exit")
assert r[1].trigger_level == "Histogram"
assert (r[2].trigger_source, r[2].trigger_level) == (0x0002, "Geo: 0.300 in/s")
def test_trigger_level_with_or_without_a_space_before_the_colon():
a = read_mlg(FIX / "BE11529.MLG").records[0]
b = read_mlg(FIX / "BE115292.MLG").records[0]
assert a.text == "Trigger Level: Histogram" and b.text == "Trigger Level : Histogram"
assert a.trigger_level == b.trigger_level == "Histogram"
def test_empty_file():
m = read_mlg(FIX / "BE6907751.MLG")
assert m.serial is None and m.records == [] and m.empty
def test_a_flipped_byte_fails_only_its_record():
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 292 + 40] ^= 0xFF # inside record 1's text
m = parse_mlg(bytes(data))
assert m.crc_failures == [1]
assert m.records[0].crc_ok is False and m.records[1].crc_ok is True
def test_a_flipped_byte_in_the_header_record_is_reported():
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 100] ^= 0xFF # inside the header record's zero area
assert parse_mlg(bytes(data)).crc_failures == [0]
@pytest.mark.parametrize("mangle", [
lambda d: d[:-1], # not 18 + 292·n
lambda d: b"\x00" + d[1:], # wrong prefix
lambda d: d[:18] + b"\x23" + d[19:], # header length field not 290
lambda d: d[:6], # shorter than the prefix
], ids=["not-whole", "prefix", "length-field", "short"])
def test_structure_errors_raise(mangle):
with pytest.raises(MlgFormatError):
parse_mlg(mangle((FIX / "BE128443065.MLG").read_bytes()))
# ── Writer ────────────────────────────────────────────────────────────────────
@pytest.mark.parametrize("name", sorted(p.name for p in FIX.glob("*.MLG")))
def test_rebuilds_every_fixture_byte_for_byte(name):
raw = (FIX / name).read_bytes()
assert mlg_bytes(parse_mlg(raw)) == raw
def test_write_mlg_writes_the_same_bytes(tmp_path):
raw = (FIX / "BE8081321.MLG").read_bytes()
out = tmp_path / "BE8081321.MLG"
write_mlg(parse_mlg(raw), out)
assert out.read_bytes() == raw
def test_old_mlg_code_is_gone():
import minimateplus.blastware_file as bw
assert not hasattr(bw, "read_mlg") and not hasattr(bw, "MLG_FLAGS_TRIGGER")
+126
View File
@@ -0,0 +1,126 @@
"""
Tests for sfm/mlg_ingest.py — one .MLG in: verified, its serial resolved, the
original kept, its records stored once (spec §3, §5, §6).
"""
from __future__ import annotations
import datetime
import os
import sys
from pathlib import Path
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, resolve_serial
from sfm.waveform_store import WaveformStore
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
UTC = datetime.timezone.utc
def _env(tmp_path):
return SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "waveforms")
def _ingest(db, store, name, data=None, **kw):
return ingest_mlg(db, store, name, data if data is not None else (FIX / name).read_bytes(), **kw)
def test_ingest_ok(tmp_path):
db, store = _env(tmp_path)
res = _ingest(db, store, "BE128443067.MLG")
assert (res["status"], res["serial"], res["records"], res["inserted"], res["skipped"]) == (
"ok", "BE12844", 3, 3, 0)
assert res["empty"] is False and res["serial_unresolved"] is False and res["file_id"]
assert (store.root / "BE12844" / "mlg" / "BE128443067.MLG").read_bytes() == (
FIX / "BE128443067.MLG").read_bytes()
def test_ingest_twice_is_duplicate(tmp_path):
db, store = _env(tmp_path)
_ingest(db, store, "BE128443067.MLG")
res = _ingest(db, store, "BE128443067.MLG")
assert res["status"] == "duplicate" and res["inserted"] == 0
assert len(db.query_mlg_files("BE12844")) == 1
def test_corrupted_file_stores_nothing(tmp_path):
db, store = _env(tmp_path)
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 292 + 40] ^= 0xFF
res = _ingest(db, store, "BE128443065.MLG", bytes(data))
assert res["status"] == "error" and "record 1" in res["detail"]
assert db.query_mlg_files("BE12844") == [] and db.query_mlg_records("BE12844") == []
assert not list(store.root.rglob("mlg"))
def test_truncated_file_is_an_error(tmp_path):
db, store = _env(tmp_path)
res = _ingest(db, store, "BE128443065.MLG", (FIX / "BE128443065.MLG").read_bytes()[:-5])
assert res["status"] == "error" and "not an MLG" in res["detail"]
assert not list(store.root.rglob("mlg"))
def test_empty_file_takes_known_serial(tmp_path):
db, store = _env(tmp_path)
_ingest(db, store, "BE6907750.MLG")
res = _ingest(db, store, "BE6907751.MLG")
assert (res["status"], res["serial"], res["empty"], res["serial_unresolved"]) == (
"ok", "BE6907", True, False)
assert (store.root / "BE6907" / "mlg" / "BE6907751.MLG").exists()
def test_empty_file_without_known_serial_is_unresolved(tmp_path):
db, store = _env(tmp_path)
res = _ingest(db, store, "BE6907751.MLG")
assert (res["status"], res["serial"], res["serial_unresolved"]) == ("ok", None, True)
assert (store.root / "_unresolved" / "mlg" / "BE6907751.MLG").exists()
def test_empty_file_takes_the_serial_hint(tmp_path):
db, store = _env(tmp_path)
res = _ingest(db, store, "BE6907751.MLG", serial_hint="BE6907")
assert (res["serial"], res["serial_unresolved"]) == ("BE6907", False)
def test_empty_file_takes_the_longest_known_serial():
assert resolve_serial("BE11010304.MLG", None, None, {"BE1101", "BE11010"}) == "BE11010"
assert resolve_serial("XY123.MLG", None, None, {"BE1101"}) is None
assert resolve_serial("BE6907751.MLG", "BE12844", "BE6907", {"BE6907"}) == "BE12844"
assert resolve_serial("be6907751.mlg", None, None, {"BE6907"}) == "BE6907"
assert resolve_serial("BE6907X51.MLG", None, None, {"BE6907"}) is None # not digits after
def test_file_mtime_and_call_in_are_stored(tmp_path):
db, store = _env(tmp_path)
mtime = datetime.datetime(2026, 9, 6, 22, 46, tzinfo=UTC)
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"]
+131
View File
@@ -0,0 +1,131 @@
"""
Tests for the .MLG routes in sfm/server.py (spec §5).
httpx is not installed in this venv, so starlette's TestClient tests skip; these
call the route functions directly, passing every parameter (a FastAPI Query()
default is not a value).
"""
from __future__ import annotations
import asyncio
import io
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 fastapi import HTTPException, UploadFile
from sfm.database import SeismoDb
from sfm.waveform_store import WaveformStore
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
def _env(tmp_path, monkeypatch):
import sfm.server as srv
db, store = SeismoDb(tmp_path / "t.db"), WaveformStore(tmp_path / "waveforms")
monkeypatch.setattr(srv, "_db", db, raising=False)
monkeypatch.setattr(srv, "_store", store, raising=False)
return srv, db, store
def _import(srv, uploads, *, serial=None, call_in=True, mtimes=None):
files = [UploadFile(file=io.BytesIO(data), filename=name) for name, data in uploads]
return asyncio.run(srv.db_import_mlg_file(files=files, serial=serial, call_in=call_in, mtimes=mtimes))
def _fixture(name):
return name, (FIX / name).read_bytes()
def test_import_route_stores_good_file_and_refuses_bad_one(tmp_path, monkeypatch):
srv, db, store = _env(tmp_path, monkeypatch)
name, good = _fixture("BE128443065.MLG")
bad = bytearray(good)
bad[18 + 292 + 40] ^= 0xFF
out = _import(srv, [(name, good), ("BE128443099.MLG", bytes(bad))])
assert out["count"] == 2
assert [r["status"] for r in out["results"]] == ["ok", "error"]
assert "record 1" in out["results"][1]["detail"]
assert [f["file_name"] for f in db.query_mlg_files("BE12844")] == ["BE128443065.MLG"]
assert sorted(p.name for p in store.root.rglob("*.MLG")) == ["BE128443065.MLG"]
def test_import_route_reads_mtimes(tmp_path, monkeypatch):
srv, db, _ = _env(tmp_path, monkeypatch)
out = _import(srv, [_fixture("BE128443065.MLG")], mtimes='{"BE128443065.MLG": 1788734760}')
f = db.get_mlg_file(out["results"][0]["file_id"])
assert f["file_mtime"] == "2026-09-06T22:46:00+00:00"
def test_import_route_rejects_bad_mtimes(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
with pytest.raises(HTTPException) as exc:
_import(srv, [_fixture("BE128443065.MLG")], mtimes="not json")
assert exc.value.status_code == 400
def test_timeline_and_monitoring_at_routes(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
_import(srv, [_fixture("BE8081321.MLG")])
tl = srv.db_unit_timeline(serial="BE8081", from_dt=None, to_dt=None)
assert tl["serial"] == "BE8081" and len(tl["sessions"]) == 4
windowed = srv.db_unit_timeline(serial="BE8081", from_dt="2019-04-13T00:00:00", to_dt=None)
assert [s["start"] for s in windowed["sessions"]] == [
"2019-04-12T18:38:14", "2019-04-13T07:05:15", "2019-04-15T12:47:05"]
assert [g["meaning"] for g in windowed["gaps"]] == ["call-in", "lost power"]
m = srv.db_unit_monitoring_at(serial="BE8081", at="2019-04-14T12:00:00")
assert m["serial"] == "BE8081" and m["status"] == "not_monitoring"
with pytest.raises(HTTPException) as exc:
srv.db_unit_monitoring_at(serial="BE8081", at="yesterday")
assert exc.value.status_code == 400
def test_timeline_routes_for_unknown_serial(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
tl = srv.db_unit_timeline(serial="BE0000", from_dt=None, to_dt=None)
assert (tl["sessions"], tl["gaps"], tl["call_ins"], tl["clock_steps"]) == ([], [], [], [])
assert srv.db_unit_monitoring_at(serial="BE0000", at="2026-09-08T10:00:00")["status"] == "unknown"
def test_mlg_records_route(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
_import(srv, [_fixture("BE8081321.MLG")])
out = srv.db_mlg_records(serial="BE8081", from_dt=None, to_dt=None)
assert out["count"] == 6 and out["records"][0]["start_time"] == "2019-04-12T17:17:59"
def test_mlg_file_route_returns_original_bytes(tmp_path, monkeypatch):
srv, _, _ = _env(tmp_path, monkeypatch)
name, data = _fixture("BE8081321.MLG")
file_id = _import(srv, [(name, data)])["results"][0]["file_id"]
resp = srv.db_mlg_file(file_id=file_id)
assert Path(resp.path).read_bytes() == data and resp.filename == name
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") == []
+94
View File
@@ -0,0 +1,94 @@
"""
Tests for .MLG storage: SeismoDb's mlg_files / mlg_records tables and
WaveformStore.save_mlg (spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §3).
"""
from __future__ import annotations
import datetime
import hashlib
import os
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.mlg_file import read_mlg
from sfm.database import SeismoDb
from sfm.waveform_store import WaveformStore
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
UTC = datetime.timezone.utc
def _insert(db: SeismoDb, name: str, *, as_name: str | None = None, call_in: bool = True):
raw = (FIX / name).read_bytes()
mlg = read_mlg(FIX / name)
return db.insert_mlg(
serial=mlg.serial, file_name=as_name or name, sha256=hashlib.sha256(raw).hexdigest(),
size=len(raw), empty=mlg.empty, call_in=call_in,
file_mtime=datetime.datetime(2026, 9, 8, 17, 39, 52, tzinfo=UTC),
stored_path=f"{mlg.serial}/mlg/{as_name or name}", records=mlg.records,
)
def test_insert_and_query_round_trip(tmp_path):
db = SeismoDb(tmp_path / "t.db")
file_id, inserted, skipped = _insert(db, "BE128443067.MLG")
assert file_id and (inserted, skipped) == (3, 0)
rows = db.query_mlg_records("BE12844")
assert [r["start_time"] for r in rows] == [
"2026-09-07T18:47:27", "2026-09-08T06:00:13", "2026-09-08T13:38:22"]
assert rows[1]["stop_time"] is None and rows[1]["flags"] == 0xFFFF
assert (rows[2]["trigger_source"], rows[2]["event_time"], rows[2]["seq"]) == (
1, "2026-09-08T13:38:22", 3)
assert rows[2]["trigger_level"] == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert {r["file_id"] for r in rows} == {file_id}
f = db.get_mlg_file(file_id)
assert (f["file_name"], f["record_count"], f["empty"], f["call_in"]) == ("BE128443067.MLG", 3, 0, 1)
assert f["file_mtime"] == "2026-09-08T17:39:52+00:00"
assert [x["id"] for x in db.query_mlg_files("BE12844")] == [file_id]
def test_same_file_twice_is_a_duplicate(tmp_path):
db = SeismoDb(tmp_path / "t.db")
_insert(db, "BE128443067.MLG")
assert _insert(db, "BE128443067.MLG") == (None, 0, 0)
assert len(db.query_mlg_files("BE12844")) == 1
raw = (FIX / "BE128443067.MLG").read_bytes()
assert db.mlg_file_exists("BE128443067.MLG", hashlib.sha256(raw).hexdigest())
assert not db.mlg_file_exists("BE128443067.MLG", "0" * 64)
def test_open_record_is_stored_once(tmp_path):
db = SeismoDb(tmp_path / "t.db")
_insert(db, "BE128443067.MLG")
file_id, inserted, skipped = _insert(db, "BE128443067.MLG", as_name="BE12844.MLG", call_in=False)
assert file_id and (inserted, skipped) == (0, 3)
assert len(db.query_mlg_records("BE12844")) == 3
def test_records_differing_only_in_text_are_the_same_record(tmp_path):
db = SeismoDb(tmp_path / "t.db")
assert _insert(db, "BE11529.MLG")[1:] == (3, 0)
file_id, inserted, skipped = _insert(db, "BE115292.MLG")
assert file_id and (inserted, skipped) == (0, 3)
def test_known_serials(tmp_path):
db = SeismoDb(tmp_path / "t.db")
assert db.known_serials() == set()
_insert(db, "BE128443067.MLG")
_insert(db, "BE8081.MLG")
assert db.known_serials() == {"BE12844", "BE8081"}
def test_save_mlg_keeps_both_when_names_collide(tmp_path):
store = WaveformStore(tmp_path / "waveforms")
a = store.save_mlg("BE11529", "BE11529.MLG", b"one")
assert a == "BE11529/mlg/BE11529.MLG"
assert store.save_mlg("BE11529", "BE11529.MLG", b"one") == a # same bytes: reused
b = store.save_mlg("BE11529", "BE11529.MLG", b"two")
assert b != a and b.startswith("BE11529/mlg/BE11529.") and b.endswith(".MLG")
assert (store.root / a).read_bytes() == b"one" and (store.root / b).read_bytes() == b"two"
assert store.save_mlg(None, "BE6907751.MLG", b"x") == "_unresolved/mlg/BE6907751.MLG"
+261
View File
@@ -0,0 +1,261 @@
"""
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"