Files
seismo-relay/docs/superpowers/plans/2026-10-21-sfm-device-access-phase1b.md
T

1880 lines
79 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# SFM device access, phase 1b — events for both series — 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:** List a unit's events and download one, by serial, through the same contract for a MiniMate (Series 3) and a Micromate (Series 4). A download is stored in SFM's database.
**Architecture:** Two device-side operations join `DeviceAccess`: `list_events` and `download_event`. Each runs through the existing dispatch: series by serial prefix, per-unit lock, the held Micromate line, typed errors.
- The device side (`sfm/device_access/`) returns a `DownloadedEvent` and stores nothing.
- A new SDM module, `sfm/event_ingest.py`, stores it through the same waveform-store and `insert_events` calls every other ingest path uses.
- MiniMate listing switches from "download every event" to a header-only walk, built from the bypass `get_events()` already has.
- An `event_id` carries serial, key and timestamp, so a stale id fails loudly.
**Tech Stack:** Python 3, FastAPI, pytest. `minimateplus/` (Series 3), `micromate/` (Series 4), `sfm/` (server, store, DB).
**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`: the parity rows 4–5, and the "1b" decisions under *Build phases*.
## Global Constraints
- **Read-only on every unit.** Listing and downloading only. No new command reaches the wire: the MiniMate header walk sends only `0A`, `1E`, `0C`, `1F` (already sent by `get_events()` on every event), and the Micromate path only what `iter_events()` / `download_event()` already send.
- **Never send Series-3 bytes to a Micromate.** `sfm/device_access/s4.py` imports nothing from `minimateplus` except `transport`.
- **Requests without `serial` behave exactly as today.** The legacy body of `GET /device/events` is untouched except that `baud` becomes `Optional[int] = Query(None)`, defaulted to 38400 at the top of the legacy path, as phase 1a did for the other handlers.
- **Tiers:** `sfm/device_access/` must not import `sfm.waveform_store`, `sfm.database` or `sfm.server`. Storing lives in `sfm/event_ingest.py`.
- **Error statuses:** 404 event not found; 409 wrong unit or stale event; 422 bad input; 423 unit busy; 502 malformed reply; 503 could not connect, connection lost or calling home; 504 no answer; 501 not supported.
- **Tests call handlers directly with every parameter explicit.** `httpx` is not installed, so `TestClient` tests are skipped. FastAPI `Query()` defaults are FieldInfo objects, not values.
- **The suite's 16 pre-existing failures** (test_bw_ascii_report.py 15, test_event_file_io.py 1, missing gitignored fixtures) stay exactly that set. Nothing else may fail.
- **Branch `feat/series4-sfm-parity`.**
- Never commit to `main` or `dev`.
- Do not edit `CHANGELOG.md`.
- **After each commit, `git push`.**
- **Hardware:** only Task 9 touches `/dev/ttyACM0` (UM20147), under `sg dialout -c "..."`. Port 8200 is in use by another SFM; never start a server there.
- **Every commit message ends with:**
```
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
```
## Review Focus
The inputs the spec implies, most likely to bite first. Each has a test in the task named.
1. **An erase or memory wrap between list and download.** The key now holds a different event, and the download must refuse with 409, never fetch it (Tasks 4, 5, 8).
2. **The same key on two Micromates** (UM12947 and UM20147 both have `055d4a81`). An `event_id` from one unit used against another must be refused before any I/O (Tasks 3, 6).
3. **A decode that disagrees with the unit's own peak.** It must never be stored: 502, and the store is untouched (Tasks 5, 8).
4. **Storing an event already stored**, by an earlier download or by THOR's watcher. The row is refreshed, never duplicated, and the same `db_event_id` comes back (Task 7).
5. **RADIO RING mid-download.** The line is released, the request answers 503, and nothing is stored (Tasks 6, 8).
---
## File map
| file | change |
|---|---|
| `minimateplus/client.py` | `get_events(headers_only=, only_key=)`; new `list_event_headers()`, `download_event_by_key()` |
| `micromate/client.py` | new `fetch_event()` returning `(bytes, result)`; `get_event()` delegates to it |
| `sfm/device_access/models.py` | `EventRef`, `EventList`, `EventDownload`, `DownloadedEvent` |
| `sfm/device_access/errors.py` | `EventNotFound` (404), `StaleEvent` (409) |
| `sfm/device_access/events.py` | **new**: `event_id` make/parse, timestamp helpers |
| `sfm/device_access/s3.py` | `list_events`, `download_event`; factory and `_run` take a timeout |
| `sfm/device_access/s4.py` | `s4_list_events`, `s4_download_event` |
| `sfm/device_access/access.py` | `DeviceAccess.list_events`, `.download_event` |
| `sfm/device_access/__init__.py` | exports |
| `sfm/event_ingest.py` | **new**: `persist_download`, `backfill_series3_event` |
| `sfm/server.py` | `serial` on `GET /device/events`; new `POST /device/events/download`; guard paths; the legacy `blastware_file` route calls `backfill_series3_event` |
| `tests/device_access_fakes.py` | event support in both fakes |
| tests | `test_minimate_event_headers.py`, `test_device_access_events.py`, `test_device_access_s3_events.py`, `test_device_access_s4_events.py`, `test_device_access_event_dispatch.py`, `test_event_ingest.py`; additions to `test_micromate_events.py` and `test_server_device_access.py` |
| docs | `CLAUDE.md`, `README.md`, `docs/micromate_protocol_reference.md` (Task 9) |
---
### Task 1: MiniMate header-only walk
**Files:**
- Modify: `minimateplus/client.py`: `get_events` (line 453), and two new methods inserted before `def download_waveform` (line 744)
- Test: `tests/test_minimate_event_headers.py` (new)
**Interfaces:**
- Produces:
- `MiniMateClient.list_event_headers() -> list[Event]`: no `_a5_frames`.
- `MiniMateClient.download_event_by_key(key4: bytes) -> Optional[Event]`: with `_a5_frames`.
- `get_events(..., headers_only: bool = False, only_key: Optional[bytes] = None)`.
- [ ] **Step 1: Write the failing tests** in `tests/test_minimate_event_headers.py`:
```python
"""MiniMateClient's header-only walk: list without 5A, download one without the rest."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import minimateplus.client as mc # noqa: E402
from minimateplus.client import MiniMateClient # noqa: E402
from minimateplus.models import Timestamp # noqa: E402
END = b"\x00" * 8
KEYS = [bytes.fromhex(k) for k in ("01110000", "0111245a", "01114290")]
STAMPS = {
KEYS[0]: (2026, 10, 1, 8, 0, 0),
KEYS[1]: (2026, 10, 2, 9, 30, 15),
KEYS[2]: (2026, 10, 3, 17, 45, 59),
}
class FakeProto:
"""Records every call; serves a three-event chain the way the unit does."""
def __init__(self, keys=KEYS, partial=()):
self.keys = list(keys)
self.partial = set(partial)
self.calls: list[tuple] = []
self._pos = 0
def _entry(self, i):
if i >= len(self.keys):
return b"\x00\x00\x00\x00", END
return self.keys[i], self.keys[i] + b"\x00\x00\x00\x46"
def read_event_first(self, token=0):
self.calls.append(("1E", token))
if token == 0:
self._pos = 0
return self._entry(self._pos)
def read_waveform_header(self, key4):
self.calls.append(("0A", key4))
return b"", (0x2C if key4 in self.partial else 0x46)
def read_waveform_record(self, key4):
self.calls.append(("0C", key4))
return key4 # decoded by the patched decoder below
def advance_event(self, browse=False):
self.calls.append(("1F", "browse" if browse else "arm"))
if browse:
self._pos += 1
return self._entry(self._pos)
return self._entry(self._pos + 1)
def poll(self):
self.calls.append(("POLL",))
def read_bulk_waveform_stream(self, key4, **kw):
self.calls.append(("5A", key4))
return ["frame"]
@pytest.fixture
def client(monkeypatch):
def decode_record(record, ev):
y, mo, d, h, mi, s = STAMPS[record]
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=y, unknown_byte=0,
month=mo, day=d, hour=h, minute=mi, second=s)
ev.record_type = "Waveform"
monkeypatch.setattr(mc, "_decode_waveform_record_into", decode_record)
monkeypatch.setattr(mc, "_decode_a5_metadata_into", lambda frames, ev: None)
monkeypatch.setattr(mc, "_decode_a5_waveform", lambda frames, ev: None)
def make(proto):
c = MiniMateClient(port="/dev/null")
c._proto = proto
return c
return make
def _subs(proto):
return [c[0] for c in proto.calls]
def test_listing_headers_never_starts_a_5a(client):
proto = FakeProto()
events = client(proto).list_event_headers()
assert [e._waveform_key for e in events] == KEYS
assert "5A" not in _subs(proto) and "POLL" not in _subs(proto)
assert ("1F", "arm") not in proto.calls
assert all(e._a5_frames is None for e in events)
def test_listing_headers_sends_only_the_commands_get_events_already_sends(client):
proto = FakeProto()
client(proto).list_event_headers()
assert _subs(proto) == ["1E"] + ["0A", "1E", "0C", "1F"] * len(KEYS)
def test_listed_events_carry_their_timestamps(client):
events = client(FakeProto()).list_event_headers()
assert (events[1].timestamp.day, events[1].timestamp.second) == (2, 15)
def test_downloading_one_event_starts_exactly_one_5a(client):
proto = FakeProto()
ev = client(proto).download_event_by_key(KEYS[1])
assert ev is not None and ev._waveform_key == KEYS[1]
assert [c for c in proto.calls if c[0] == "5A"] == [("5A", KEYS[1])]
assert ev._a5_frames == ["frame"]
def test_downloading_one_event_stops_once_it_has_it(client):
proto = FakeProto()
client(proto).download_event_by_key(KEYS[1])
assert ("0A", KEYS[2]) not in proto.calls
def test_the_events_before_it_are_walked_without_their_5a(client):
proto = FakeProto()
client(proto).download_event_by_key(KEYS[2])
assert [c[1] for c in proto.calls if c[0] == "5A"] == [KEYS[2]]
assert proto.calls.count(("1F", "arm")) == 1
def test_a_key_that_is_not_stored_returns_none(client):
assert client(FakeProto()).download_event_by_key(bytes.fromhex("0111ffff")) is None
def test_a_partial_record_is_skipped_by_both(client):
events = client(FakeProto(partial={KEYS[1]})).list_event_headers()
assert [e._waveform_key for e in events] == [KEYS[0], KEYS[2]]
assert client(FakeProto(partial={KEYS[1]})).download_event_by_key(KEYS[1]) is None
```
- [ ] **Step 2: Run them, and watch them fail.**
Run: `.venv/bin/python -m pytest tests/test_minimate_event_headers.py -q`
Expected: FAIL with `AttributeError: 'MiniMateClient' object has no attribute 'list_event_headers'`.
- [ ] **Step 3: Implement.** In `minimateplus/client.py`:
(a) Extend the `get_events` signature. Replace the line
` def get_events(self, full_waveform: bool = False, debug: bool = False, stop_after_index: Optional[int] = None, skip_waveform_for_keys: Optional[set] = None, skip_waveform_for_events: Optional[dict] = None, extra_chunks_after_metadata: int = 1) -> list[Event]:`
with
` def get_events(self, full_waveform: bool = False, debug: bool = False, stop_after_index: Optional[int] = None, skip_waveform_for_keys: Optional[set] = None, skip_waveform_for_events: Optional[dict] = None, extra_chunks_after_metadata: int = 1, headers_only: bool = False, only_key: Optional[bytes] = None) -> list[Event]:`
(b) Add to the end of its docstring, just before the closing `"""` (after the `Raises:` block):
```
headers_only: never start a 5A -- every event takes the bypass below.
only_key: download only the event with this key (in full, per
full_waveform); walk the others without their 5A, and stop once
that event is read.
```
(c) Replace
```python
expected_ts = skip_evts.get(cur_key.hex(), "")
actual_ts = _event_timestamp_iso(ev)
skip_5a = bool(expected_ts and actual_ts and expected_ts == actual_ts)
if skip_5a:
log.info(
"get_events: key=%s (key, ts=%s) match — skipping 5A bulk download",
cur_key.hex(), actual_ts,
)
```
with
```python
expected_ts = skip_evts.get(cur_key.hex(), "")
actual_ts = _event_timestamp_iso(ev)
skip_5a = bool(expected_ts and actual_ts and expected_ts == actual_ts)
if skip_5a:
log.info(
"get_events: key=%s (key, ts=%s) match — skipping 5A bulk download",
cur_key.hex(), actual_ts,
)
elif headers_only or (only_key is not None and cur_key != only_key):
# The same bypass as a (key, ts) match: 0A + 1E(arm) + 0C were
# read; 1F(arm) + POLL + 5A are not sent, and 1F(browse) below is
# safe because no 5A was ever started.
skip_5a = True
```
(d) Replace
```python
events.append(ev)
idx += 1
# Early exit: if the caller only wants events up to a specific
```
with
```python
events.append(ev)
idx += 1
if only_key is not None and cur_key == only_key:
log.info("get_events: read key=%s -- stopping", cur_key.hex())
break
# Early exit: if the caller only wants events up to a specific
```
(e) Insert immediately before ` def download_waveform(self, event: Event) -> None:`:
```python
def list_event_headers(self) -> list[Event]:
"""Every stored event's 0C record -- timestamp, type, peaks -- without its 5A.
`get_events()` downloads every event in full even for metadata
(`stop_after_metadata` is a no-op), so listing that way costs one
complete download per event. This walks 0A + 1E(arm) + 0C + 1F(browse)
per event -- the bypass `skip_waveform_for_events` already takes -- and
never starts a 5A. The events carry no `_a5_frames`.
"""
return self.get_events(headers_only=True)
def download_event_by_key(self, key4: bytes) -> Optional[Event]:
"""Download ONE event in full; walk past the events before it without
their 5A. None if no full record has that key.
`get_events(stop_after_index=N)` downloads events 0..N in full and keeps
one; this downloads only the one asked for.
"""
for ev in self.get_events(full_waveform=True, only_key=key4):
if ev._waveform_key == key4:
return ev
return None
```
- [ ] **Step 4: Run the tests and watch them pass.**
Run: `.venv/bin/python -m pytest tests/test_minimate_event_headers.py -q`
Expected: 8 passed.
- [ ] **Step 5: Commit and push.**
```bash
git add minimateplus/client.py tests/test_minimate_event_headers.py
git commit -m "feat(minimateplus): list events from headers, download one without the rest
<trailer lines>"
git push
```
---
### Task 2: Micromate `fetch_event` (bytes + checked decode)
**Files:**
- Modify: `micromate/client.py`: `get_event` (line 530)
- Test: `tests/test_micromate_events.py` (append)
**Interfaces:**
- Produces: `MicromateClient.fetch_event(ref, *, verify=True, tolerance=0.01, chunk_size=None) -> tuple[bytes, IdfReadResult]`. It raises `DecodeMismatch` exactly as `get_event` does. `get_event` keeps its signature and behaviour.
- [ ] **Step 1: Write the failing tests.** Append to `tests/test_micromate_events.py`:
```python
# ── fetch_event: the bytes and the checked decode together ───────────────────
import math # noqa: E402
UM20147_W = Path(__file__).parent / "fixtures" / "thor-idf" / "UM20147_20250531135901.IDFW"
def _our_pvs(result):
from micromate.idf_file import geo_count_to_ips
ch = {k.lower(): v for k, v in result.samples.items()}
t, v, l = ch["tran"], ch["vert"], ch["long"]
return max(math.sqrt(geo_count_to_ips(t[i]) ** 2 + geo_count_to_ips(v[i]) ** 2
+ geo_count_to_ips(l[i]) ** 2)
for i in range(min(len(t), len(v), len(l))))
def _fixture_client(monkeypatch, blob):
mm, _t = client([])
monkeypatch.setattr(mm, "download_event", lambda ref, chunk_size=None: blob)
return mm
def _w_ref(pvs):
return MicromateEventRef(
index=0, key=bytes.fromhex("055d4a81"), size=UM20147_W.stat().st_size,
serial="UM20147", record_type="waveform",
timestamp=datetime.datetime(2025, 5, 31, 13, 59, 1), peak_vector_sum_ips=pvs)
def test_fetch_event_returns_the_downloaded_bytes_with_the_decode(monkeypatch):
blob = UM20147_W.read_bytes()
mm = _fixture_client(monkeypatch, blob)
probe = mm.fetch_event(_w_ref(None), verify=False)[1]
got, result = mm.fetch_event(_w_ref(_our_pvs(probe)))
assert got == blob and result.samples
def test_fetch_event_refuses_a_decode_that_disagrees_with_the_unit(monkeypatch):
mm = _fixture_client(monkeypatch, UM20147_W.read_bytes())
probe = mm.fetch_event(_w_ref(None), verify=False)[1]
with pytest.raises(DecodeMismatch):
mm.fetch_event(_w_ref(_our_pvs(probe) * 1.05))
def test_get_event_is_fetch_event_without_the_bytes(monkeypatch):
mm = _fixture_client(monkeypatch, UM20147_W.read_bytes())
assert mm.get_event(_w_ref(None), verify=False).samples
```
- [ ] **Step 2: Run them, and watch them fail.**
Run: `.venv/bin/python -m pytest tests/test_micromate_events.py -q -k fetch_event`
Expected: FAIL with `AttributeError: ... 'fetch_event'`.
- [ ] **Step 3: Implement.** In `micromate/client.py`, `get_event` keeps its docstring. Replace its body: everything from ` if not ref.record_type:` through the ` return result` that ends the method.
```python
return self.fetch_event(ref, verify=verify, tolerance=tolerance,
chunk_size=chunk_size)[1]
def fetch_event(self, ref: MicromateEventRef, *, verify: bool = True,
tolerance: float = 0.01, chunk_size: Optional[int] = None):
"""`get_event()`, returning the raw bytes too: `(blob, result)`.
For a caller that stores the file AND wants the self-check: the bytes go
to the waveform store unchanged, and a DecodeMismatch stops them being
stored at all.
"""
if not ref.record_type:
raise ValueError(
f"event {ref.key_hex}: record_type is unknown, so the codec "
f"cannot be dispatched. Use list_events(with_records=True)."
)
blob = self.download_event(ref, chunk_size=chunk_size)
import tempfile
from .idf_file import read_idf_file
# read_idf_file dispatches on the suffix, so the bytes need a name.
with tempfile.NamedTemporaryFile(suffix=ref.suffix, delete=False) as f:
f.write(blob)
tmp = f.name
try:
result = read_idf_file(tmp)
finally:
os.unlink(tmp)
if verify and not ref.is_histogram:
err = self.decode_error(ref, result)
if err is not None and abs(err) > tolerance:
raise DecodeMismatch(
f"event {ref.uid}: decoded peak vector sum differs from the "
f"device's own by {100 * err:+.3f}% (tolerance "
f"{100 * tolerance:.1f}%) — the decode is suspect, not the "
f"device. Stored {ref.peak_vector_sum_ips:.5f} in/s."
)
if err is not None:
log.debug("event %s: PVS agrees to %+.4f%%", ref.uid, 100 * err)
return blob, result
```
- [ ] **Step 4: Run the tests, and watch them pass.**
Run: `.venv/bin/python -m pytest tests/test_micromate_events.py -q`
Expected: all pass. The two replay tests may skip on a fresh clone; on the dev box they run and must still pass.
- [ ] **Step 5: Commit and push.** Message: `feat(micromate): fetch_event returns the bytes with the checked decode`.
---
### Task 3: Event models, errors and `event_id`
**Files:**
- Modify: `sfm/device_access/models.py`, `sfm/device_access/errors.py`, `sfm/device_access/__init__.py`
- Create: `sfm/device_access/events.py`
- Test: `tests/test_device_access_events.py` (new)
**Interfaces:**
- Produces:
- **Models:** `EventRef`, `EventList`, `EventDownload`, `DownloadedEvent` (fields below).
- **Errors:** `EventNotFound` (404), `StaleEvent` (409).
- **`events.py`:**
- `make_event_id(serial, key: bytes, stamp: Optional[str]) -> str`
- `parse_event_id(event_id, serial) -> tuple[bytes, Optional[str]]`
- `stamp_of(dt) -> Optional[str]` (`YYYYmmddHHMMSS`)
- `iso_of(dt) -> Optional[str]`
- [ ] **Step 1: Write the failing tests** in `tests/test_device_access_events.py`:
```python
"""Event identity: serial + key + timestamp, so a stale or foreign id fails loudly."""
from __future__ import annotations
import datetime
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sfm.device_access.errors import BadRequest, EventNotFound, StaleEvent # noqa: E402
from sfm.device_access.events import ( # noqa: E402
iso_of, make_event_id, parse_event_id, stamp_of,
)
KEY = bytes.fromhex("055d4a81")
WHEN = datetime.datetime(2025, 5, 31, 13, 59, 1)
def test_an_event_id_round_trips():
eid = make_event_id("um20147", KEY, stamp_of(WHEN))
assert eid == "UM20147:055d4a81:20250531135901"
assert parse_event_id(eid, "UM20147") == (KEY, "20250531135901")
def test_an_unknown_timestamp_round_trips_as_none():
eid = make_event_id("BE18193", bytes.fromhex("01110000"), None)
assert eid == "BE18193:01110000:-"
assert parse_event_id(eid, "be18193") == (bytes.fromhex("01110000"), None)
def test_an_id_from_another_unit_is_refused():
# UM12947 and UM20147 both have an event 055d4a81
with pytest.raises(BadRequest, match="UM12947"):
parse_event_id("UM12947:055d4a81:20250531135901", "UM20147")
@pytest.mark.parametrize("bad", ["", "UM20147", "UM20147:055d4a81",
"UM20147:zz:20250531135901", "UM20147:055d4a:20250531135901",
"UM20147:055d4a81:2025"])
def test_a_malformed_id_is_refused(bad):
with pytest.raises(BadRequest):
parse_event_id(bad, "UM20147")
def test_iso_and_stamp_of_none_are_none():
assert iso_of(None) is None and stamp_of(None) is None
assert iso_of(WHEN) == "2025-05-31T13:59:01"
def test_the_new_errors_have_their_statuses():
assert (EventNotFound.http_status, StaleEvent.http_status) == (404, 409)
```
- [ ] **Step 2: Run them, and watch them fail.**
Run: `.venv/bin/python -m pytest tests/test_device_access_events.py -q`
Expected: FAIL with `ImportError` (`EventNotFound`, `sfm.device_access.events`).
- [ ] **Step 3: Implement.**
`sfm/device_access/errors.py`: add after `class MalformedReply`:
```python
class EventNotFound(DeviceError):
http_status = 404
class StaleEvent(DeviceError):
"""The event at that key is not the one listed -- the unit was erased, or
its memory wrapped, since the list was read."""
http_status = 409
```
`sfm/device_access/models.py`: change `from typing import Any, Dict, Optional` to `from typing import Any, Dict, List, Optional`, and append:
```python
@dataclass
class EventRef:
"""One stored event, as listed. `event_id` is opaque: pass it back to
download the event. `index` is its position in the list right now; an
erase renumbers it, so it is for display, never identity."""
event_id: str
serial: str
series: int
index: int
timestamp: Optional[str] # ISO, the unit's own local time
record_type: Optional[str] # "waveform" | "histogram"
peak_vector_sum_ips: Optional[float]
peaks_ips: Dict[str, float] # geophones only: tran / vert / long
filename: Optional[str] # the name the vendor's software gives it
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EventList:
serial: str
series: int
events: List[EventRef]
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class EventDownload:
"""What a download stored. The file and waveform are then served at
/db/events/{db_event_id}/... ."""
event_id: str
serial: str
series: int
db_event_id: Optional[str]
stored_filename: str
filesize: int
sha256: Optional[str]
inserted: bool # False: already stored; the row was refreshed
verified: Optional[bool] # True: decode self-check passed; None: no check exists
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class DownloadedEvent:
"""The device side's result, before SFM stores it. Not an HTTP shape: it
carries the payload -- a Series-3 Event + its 5A frames + the compliance
config, or a Series-4 file's bytes -- to sfm.event_ingest."""
event_id: str
serial: str
series: int
filename: str
verified: Optional[bool]
idf_bytes: Optional[bytes] = field(default=None, repr=False)
event: Any = field(default=None, repr=False)
a5_frames: Optional[list] = field(default=None, repr=False)
compliance: Any = field(default=None, repr=False)
detail: Dict[str, Any] = field(default_factory=dict)
```
Create `sfm/device_access/events.py`:
```python
"""Event identity. An `event_id` is `<serial>:<key hex>:<YYYYmmddHHMMSS>`.
The key alone is not enough: both series reuse keys (a MiniMate restarts at
01110000 after an erase; every Micromate's counter starts at the same value).
The timestamp turns a stale id into a loud StaleEvent instead of a download of
whatever now sits at that key. "-" stands in for an unknown timestamp.
"""
from __future__ import annotations
import datetime
from typing import Optional, Tuple
from .errors import BadRequest
from .series import normalise_serial
_NO_STAMP = "-"
_STAMP_FMT = "%Y%m%d%H%M%S"
def stamp_of(dt: Optional[datetime.datetime]) -> Optional[str]:
return dt.strftime(_STAMP_FMT) if dt is not None else None
def iso_of(dt: Optional[datetime.datetime]) -> Optional[str]:
return dt.isoformat() if dt is not None else None
def make_event_id(serial: str, key: bytes, stamp: Optional[str]) -> str:
return f"{normalise_serial(serial)}:{key.hex()}:{stamp or _NO_STAMP}"
def parse_event_id(event_id: str, serial: str) -> Tuple[bytes, Optional[str]]:
"""(key, stamp) for an id that belongs to `serial`; BadRequest otherwise."""
parts = (event_id or "").strip().split(":")
if len(parts) != 3:
raise BadRequest(f"not an event_id: {event_id!r} -- take it from GET /device/events")
id_serial, key_hex, stamp = parts
if normalise_serial(id_serial) != normalise_serial(serial):
raise BadRequest(f"event_id {event_id!r} belongs to {id_serial}, not {serial}")
try:
key = bytes.fromhex(key_hex)
except ValueError:
key = b""
if len(key) != 4:
raise BadRequest(f"event_id {event_id!r}: the key must be 8 hex digits")
if stamp != _NO_STAMP:
try:
datetime.datetime.strptime(stamp, _STAMP_FMT)
except ValueError:
raise BadRequest(f"event_id {event_id!r}: bad timestamp {stamp!r}") from None
return key, (None if stamp == _NO_STAMP else stamp)
```
`sfm/device_access/__init__.py`: add `EventNotFound, StaleEvent` to the errors import, and `EventDownload, EventList, EventRef, DownloadedEvent` to the models import.
- [ ] **Step 4: Run the tests, and watch them pass.**
Run: `.venv/bin/python -m pytest tests/test_device_access_events.py -q`
Expected: 11 passed.
- [ ] **Step 5: Commit and push.** Message: `feat(sfm): event models and event_id -- serial, key and timestamp`.
---
### Task 4: Series-3 adapter: list and download
**Files:**
- Modify: `sfm/device_access/s3.py`, `tests/device_access_fakes.py`
- Test: `tests/test_device_access_s3_events.py` (new)
**Interfaces:**
- Consumes:
- Task 1's `list_event_headers()` and `download_event_by_key()`.
- Task 3's models, errors and `events.py`.
- Produces:
- `Series3Adapter.list_events(address, serial) -> EventList`
- `Series3Adapter.download_event(address, serial, key: bytes, stamp: Optional[str]) -> DownloadedEvent`
- `default_s3_client_factory(address, timeout: Optional[float] = None)`
- `Series3Adapter._run(address, fn, timeout=None)`. With a timeout, the factory is called as `factory(address, timeout=...)`.
- `S3_EVENT_TIMEOUT = 120.0`
- In the fakes: `s3_event(...)`, `default_s3_events()`, and `FakeMiniMateClient(events=...)` with `list_event_headers` / `download_event_by_key`.
- [ ] **Step 1: Extend the fakes.** In `tests/device_access_fakes.py`:
- Add `import copy` to the imports.
- Change the minimateplus import to `from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStatus, PeakValues, Timestamp`.
- Add these module-level helpers before `class FakeMiniMateClient`:
```python
def s3_event(index, key_hex, when, *, record_type="Waveform", pvs=0.12, frames=True):
ev = Event(index=index)
ev._waveform_key = bytes.fromhex(key_hex)
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=when.year, unknown_byte=0,
month=when.month, day=when.day, hour=when.hour,
minute=when.minute, second=when.second)
ev.record_type = record_type
ev.peak_values = PeakValues(tran=0.05, vert=0.08, long=0.03, micl=0.0001,
peak_vector_sum=pvs)
if frames:
ev._a5_frames = ["frame"]
return ev
def default_s3_events():
return [
s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)),
s3_event(1, "0111245a", datetime.datetime(2026, 10, 2, 9, 30, 15), record_type="Histogram"),
]
```
- Change the signature of `FakeMiniMateClient.__init__` to `def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None, **kw):`, and add `self.events = default_s3_events() if events is None else events` at the end of `__init__`.
- Add these methods to `FakeMiniMateClient`:
```python
def list_event_headers(self):
self._step("list_event_headers")
out = []
for ev in self.events:
h = copy.copy(ev)
h._a5_frames = None
out.append(h)
return out
def download_event_by_key(self, key4):
self._step("download_event_by_key")
for ev in self.events:
if ev._waveform_key == key4:
return ev
return None
```
- [ ] **Step 2: Write the failing tests** in `tests/test_device_access_s3_events.py`:
```python
"""Series-3 events: listed from headers, one downloaded, mapped into the shared shape."""
from __future__ import annotations
import datetime
import os
import struct
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from device_access_fakes import FakeMiniMateClient, s3_event # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
EventNotFound, MalformedReply, StaleEvent, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s3 import Series3Adapter # noqa: E402
TCP = UnitAddress(host="10.0.0.5", tcp_port=12345, port=None, baud=None)
FIRST = bytes.fromhex("01110000")
def adapter(*clients):
queue = list(clients)
seen = []
def factory(address, **kw):
seen.append(kw)
return queue.pop(0)
a = Series3Adapter(client_factory=factory)
a.seen = seen
return a
def test_listing_maps_each_header_into_the_shared_shape():
out = adapter(FakeMiniMateClient()).list_events(TCP, "BE18193")
assert (out.serial, out.series, len(out.events)) == ("BE18193", 3, 2)
e = out.events[1]
assert e.event_id == "BE18193:0111245a:20261002093015"
assert (e.index, e.timestamp, e.record_type) == (1, "2026-10-02T09:30:15", "histogram")
assert e.peaks_ips == {"tran": 0.05, "vert": 0.08, "long": 0.03}
assert e.peak_vector_sum_ips == 0.12 and e.detail["mic_psi"] == 0.0001
assert e.filename and e.filename.startswith("T193")
def test_listing_uses_the_header_walk_and_the_long_timeout():
fake = FakeMiniMateClient()
a = adapter(fake)
a.list_events(TCP, "BE18193")
assert "list_event_headers" in fake.calls and "download_event_by_key" not in fake.calls
assert a.seen == [{"timeout": 120.0}]
assert fake.closed == 1
def test_listing_refuses_a_different_unit():
with pytest.raises(WrongUnit):
adapter(FakeMiniMateClient(serial="BE11529")).list_events(TCP, "BE18193")
def test_download_returns_the_event_its_frames_and_the_settings():
fake = FakeMiniMateClient()
dl = adapter(fake).download_event(TCP, "BE18193", FIRST, "20261001080000")
assert (dl.series, dl.event_id, dl.verified) == (3, "BE18193:01110000:20261001080000", None)
assert dl.event is fake.events[0] and dl.a5_frames == ["frame"]
assert dl.compliance is fake.compliance and dl.filename.startswith("T193")
def test_download_refuses_a_different_unit_before_downloading():
fake = FakeMiniMateClient(serial="BE11529")
with pytest.raises(WrongUnit):
adapter(fake).download_event(TCP, "BE18193", FIRST, None)
assert "download_event_by_key" not in fake.calls
def test_a_key_that_is_not_stored_is_404():
with pytest.raises(EventNotFound):
adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", bytes.fromhex("0111ffff"), None)
def test_a_stale_id_is_refused_rather_than_downloading_another_event():
with pytest.raises(StaleEvent, match="20261001080000"):
adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", FIRST, "20250101000000")
def test_an_id_without_a_timestamp_skips_the_check():
dl = adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", FIRST, None)
assert dl.event_id == "BE18193:01110000:20261001080000"
def test_a_failed_5a_is_a_clear_error():
fake = FakeMiniMateClient(events=[s3_event(0, "01110000",
datetime.datetime(2026, 10, 1, 8, 0, 0), frames=False)])
with pytest.raises(MalformedReply, match="5A"):
adapter(fake).download_event(TCP, "BE18193", FIRST, None)
def test_the_64k_page_bug_is_named_not_a_bare_500():
fake = FakeMiniMateClient()
def boom(key4):
raise struct.error("argument out of range")
fake.download_event_by_key = boom
with pytest.raises(MalformedReply, match="64 KB"):
adapter(fake).download_event(TCP, "BE18193", FIRST, None)
```
- [ ] **Step 3: Run them, and watch them fail.**
Run: `.venv/bin/python -m pytest tests/test_device_access_s3_events.py -q`
Expected: FAIL with `AttributeError: 'Series3Adapter' object has no attribute 'list_events'`.
- [ ] **Step 4: Implement.** In `sfm/device_access/s3.py`:
Imports: change `from typing import Any, Callable` to `from typing import Any, Callable, Optional`, and add:
```python
import datetime
import struct
from minimateplus.blastware_file import blastware_filename
from .events import iso_of, make_event_id, stamp_of
from .models import DownloadedEvent, EventList, EventRef
```
Also extend the errors import with `EventNotFound, StaleEvent`.
Replace `default_s3_client_factory` with:
```python
S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use
def default_s3_client_factory(address: UnitAddress, timeout: Optional[float] = None) -> MiniMateClient:
if address.host:
return MiniMateClient(transport=TcpTransport(address.host, port=address.tcp_port),
timeout=10.0 if timeout is None else timeout)
if timeout is None:
return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD)
return MiniMateClient(address.port, address.baud or S3_DEFAULT_BAUD, timeout=timeout)
```
In `Series3Adapter._run`:
- change the signature to `def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None) -> Any:`;
- change `client = self._factory(address)` to `client = self._factory(address) if timeout is None else self._factory(address, timeout=timeout)`.
Add module-level helpers after `_close`:
```python
def _s3_dt(ev: Any) -> Optional[datetime.datetime]:
ts = getattr(ev, "timestamp", None)
if ts is None or ts.hour is None:
return None
try:
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
except (TypeError, ValueError):
return None
def _s3_filename(ev: Any, serial: str) -> Optional[str]:
try:
return blastware_filename(ev, serial)
except Exception: # noqa: BLE001
return None
def _s3_ref(ev: Any, serial: str) -> EventRef:
dt = _s3_dt(ev)
pv = ev.peak_values
peaks = {}
if pv is not None:
peaks = {k: v for k, v in (("tran", pv.tran), ("vert", pv.vert), ("long", pv.long))
if v is not None}
return EventRef(
event_id=make_event_id(serial, ev._waveform_key, stamp_of(dt)),
serial=serial, series=3, index=ev.index, timestamp=iso_of(dt),
record_type=ev.record_type.lower() if ev.record_type else None,
peak_vector_sum_ips=pv.peak_vector_sum if pv is not None else None,
peaks_ips=peaks, filename=_s3_filename(ev, serial),
detail={"mic_psi": pv.micl if pv is not None else None},
)
```
Add the methods to `Series3Adapter`, after `settings`:
```python
def list_events(self, address: UnitAddress, serial: str) -> EventList:
def op(client: Any) -> EventList:
info = client.connect()
self._check(info.serial, serial, address)
return EventList(serial=serial, series=3,
events=[_s3_ref(ev, serial) for ev in client.list_event_headers()])
return self._run(address, op, timeout=S3_EVENT_TIMEOUT)
def download_event(self, address: UnitAddress, serial: str, key: bytes,
stamp: Optional[str]) -> DownloadedEvent:
def op(client: Any) -> DownloadedEvent:
info = client.connect()
self._check(info.serial, serial, address)
try:
ev = client.download_event_by_key(key)
except struct.error as exc:
# 🔶 Inferred: the known 5A page bug. An event past the unit's
# first 64 KB drives TERM's offset negative, and struct.pack
# rejects it (CLAUDE.md, "KNOWN BUG").
raise MalformedReply(
f"event {key.hex()}: its download could not be assembled ({exc}) -- most "
"likely the known bug with events past the unit's first 64 KB; not saved"
) from exc
if ev is None:
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
found = stamp_of(_s3_dt(ev))
if stamp is not None and found != stamp:
raise StaleEvent(
f"the event at {key.hex()} on {serial} is from {found}, not {stamp} -- "
"the unit was erased or wrapped since the list was read; list again")
if not ev._a5_frames:
raise MalformedReply(f"event {key.hex()}: no waveform data received (the 5A download failed)")
filename = _s3_filename(ev, serial)
if filename is None:
raise MalformedReply(f"event {key.hex()} has no usable timestamp, so it cannot be named or stored")
return DownloadedEvent(
event_id=make_event_id(serial, key, found), serial=serial, series=3,
filename=filename, verified=None, event=ev, a5_frames=ev._a5_frames,
compliance=info.compliance_config, detail={"a5_frames": len(ev._a5_frames)},
)
return self._run(address, op, timeout=S3_EVENT_TIMEOUT)
```
- [ ] **Step 5: Run the tests, and watch them pass.**
Run: `.venv/bin/python -m pytest tests/test_device_access_s3_events.py tests/test_device_access_s3.py -q`
Expected: all pass. The existing S3 tests use `lambda address:` factories, and those calls pass no timeout.
- [ ] **Step 6: Commit and push.** Message: `feat(sfm): Series-3 events -- header list, one-event download, stale ids refused`.
---
### Task 5: Series-4 operations: list and download
**Files:**
- Modify: `sfm/device_access/s4.py`, `tests/device_access_fakes.py`
- Test: `tests/test_device_access_s4_events.py` (new)
**Interfaces:**
- Consumes:
- Task 2's `fetch_event`.
- Task 3's models, errors and `events.py`.
- Produces:
- `s4_list_events(client, serial) -> EventList`
- `s4_download_event(client, serial, key: bytes, stamp: Optional[str]) -> DownloadedEvent`
- In the fakes: `s4_ref(...)`, `default_s4_refs()`, and `FakeMicromateClient(event_refs=...)` with `list_events`, `iter_events`, `fetch_event` and `decode_error`.
- [ ] **Step 1: Extend the fakes.** In `tests/device_access_fakes.py`:
- Add `from micromate.models import MicromateEventRef` (extend the existing micromate import).
- Add `THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"` after `SETUP_FIXTURE`.
- Add these module-level helpers before `class _FakeProtocol`:
```python
def s4_ref(index, key_hex, when, record_type, *, pvs=0.2):
"""Fixture-backed: the filename it produces names a real file in thor-idf/."""
ref = MicromateEventRef(index=index, key=bytes.fromhex(key_hex), size=0, serial="UM20147",
record_type=record_type, timestamp=when, peak_vector_sum_ips=pvs,
peaks_ips={"Tran": 0.1, "Vert": 0.15, "Long": 0.05, "Mic": 0.0002})
ref.size = (THOR_IDF / ref.filename).stat().st_size
return ref
def default_s4_refs():
return [
s4_ref(0, "055d4a81", datetime.datetime(2025, 5, 31, 13, 59, 1), "waveform"),
s4_ref(1, "055d4a83", datetime.datetime(2025, 3, 30, 7, 1, 10), "histogram"),
]
```
- Change the signature of `FakeMicromateClient.__init__` to `def __init__(self, serial="UM20147", *, monitoring=False, events=5, unsolicited=b"", event_refs=None, **kw):`.
- Add to the end of `__init__`:
```python
self.event_refs = default_s4_refs() if event_refs is None else event_refs
self.cursor = None
self.fetched: list = []
```
- Add these methods to `FakeMicromateClient`:
```python
def list_events(self, *, with_records=True):
self._step("list_events")
return list(self.event_refs)
def iter_events(self, *, with_records=True):
self._step("iter_events")
for ref in self.event_refs:
self.cursor = ref.index
yield ref
def fetch_event(self, ref, *, verify=True, tolerance=0.01, chunk_size=None):
self._step("fetch_event")
self.fetched.append((ref.key_hex, chunk_size))
return (THOR_IDF / ref.filename).read_bytes(), object()
@staticmethod
def decode_error(ref, result):
return None if ref.record_type == "histogram" else 0.0
```
- [ ] **Step 2: Write the failing tests** in `tests/test_device_access_s4_events.py`:
```python
"""Series-4 events: the chain walk mapped into the shared shape; download at the cursor."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from device_access_fakes import THOR_IDF, FakeMicromateClient # noqa: E402
from micromate.protocol import THOR_CHUNK_SIZE # noqa: E402
from sfm.device_access.errors import EventNotFound, StaleEvent # noqa: E402
from sfm.device_access.s4 import s4_download_event, s4_list_events # noqa: E402
W_KEY, H_KEY = bytes.fromhex("055d4a81"), bytes.fromhex("055d4a83")
def test_listing_maps_each_ref_into_the_shared_shape():
out = s4_list_events(FakeMicromateClient(), "UM20147")
assert (out.serial, out.series, len(out.events)) == ("UM20147", 4, 2)
e = out.events[0]
assert e.event_id == "UM20147:055d4a81:20250531135901"
assert (e.index, e.timestamp, e.record_type) == (0, "2025-05-31T13:59:01", "waveform")
assert e.peaks_ips == {"tran": 0.1, "vert": 0.15, "long": 0.05}
assert e.filename == "UM20147_20250531135901.IDFW"
assert e.detail["mic"] == 0.0002 and e.detail["size_bytes"] > 0
def test_download_walks_to_the_event_and_uses_thors_chunk_size():
fake = FakeMicromateClient()
dl = s4_download_event(fake, "UM20147", W_KEY, "20250531135901")
assert "iter_events" in fake.calls and "list_events" not in fake.calls
assert fake.fetched == [("055d4a81", THOR_CHUNK_SIZE)]
assert dl.idf_bytes == (THOR_IDF / "UM20147_20250531135901.IDFW").read_bytes()
assert (dl.series, dl.filename, dl.verified) == (4, "UM20147_20250531135901.IDFW", True)
def test_the_walk_stops_at_the_event_rather_than_reading_ahead():
fake = FakeMicromateClient()
s4_download_event(fake, "UM20147", W_KEY, None)
assert fake.cursor == 0
def test_a_histogram_has_no_self_check_so_verified_is_none():
dl = s4_download_event(FakeMicromateClient(), "UM20147", H_KEY, None)
assert dl.verified is None and dl.filename.endswith(".IDFH")
def test_a_stale_id_is_refused_and_nothing_is_downloaded():
fake = FakeMicromateClient()
with pytest.raises(StaleEvent, match="20250531135901"):
s4_download_event(fake, "UM20147", W_KEY, "20240101000000")
assert fake.fetched == []
def test_a_key_that_is_not_stored_is_404():
with pytest.raises(EventNotFound):
s4_download_event(FakeMicromateClient(), "UM20147", bytes.fromhex("deadbeef"), None)
```
- [ ] **Step 3: Run them, and watch them fail.**
Run: `.venv/bin/python -m pytest tests/test_device_access_s4_events.py -q`
Expected: FAIL with `ImportError: cannot import name 's4_download_event'`.
- [ ] **Step 4: Implement.** In `sfm/device_access/s4.py`, add these imports (`micromate.protocol` is Series 4's own package, so the module-header rule holds):
```python
from micromate.protocol import THOR_CHUNK_SIZE
from .errors import EventNotFound, MalformedReply, StaleEvent
from .events import iso_of, make_event_id, stamp_of
from .models import DownloadedEvent, EventList, EventRef
```
Merge these into the existing `.errors` and `.models` import lines. Then append at the end of the file:
```python
def _s4_ref(ref: Any, serial: str) -> EventRef:
peaks = ref.peaks_ips or {}
return EventRef(
event_id=make_event_id(serial, ref.key, stamp_of(ref.timestamp)),
serial=serial, series=4, index=ref.index, timestamp=iso_of(ref.timestamp),
record_type=ref.record_type, peak_vector_sum_ips=ref.peak_vector_sum_ips,
peaks_ips={k.lower(): v for k, v in peaks.items() if k in ("Tran", "Vert", "Long")},
filename=ref.filename,
detail={"size_bytes": ref.size, "mic": peaks.get("Mic"), "setup": ref.setup,
"sensor_location": ref.sensor_location},
)
def s4_list_events(client: Any, serial: str) -> EventList:
return EventList(serial=serial, series=4,
events=[_s4_ref(r, serial) for r in client.list_events(with_records=True)])
def s4_download_event(client: Any, serial: str, key: bytes, stamp: Optional[str]) -> DownloadedEvent:
"""Walk to the event and download it there -- the order THOR uses, the only
one captured. Downloading at a parked cursor has never been tried."""
for ref in client.iter_events(with_records=True):
if ref.key != key:
continue
found = stamp_of(ref.timestamp)
if stamp is not None and found != stamp:
raise StaleEvent(
f"the event at {key.hex()} on {serial} is from {found}, not {stamp} -- "
"the unit was erased or wrapped since the list was read; list again")
if ref.filename is None:
raise MalformedReply(
f"event {key.hex()}: its record gave no type or timestamp, so it cannot be named or stored")
# THOR's chunk size. A 16 KB chunk takes ~7 s on cellular against the
# 10 s receive deadline; 1 KB is what THOR itself sends.
blob, result = client.fetch_event(ref, chunk_size=THOR_CHUNK_SIZE)
err = client.decode_error(ref, result)
return DownloadedEvent(
event_id=make_event_id(serial, key, found), serial=serial, series=4,
filename=ref.filename, verified=True if err is not None else None,
idf_bytes=blob, detail={"size_bytes": ref.size, "pvs_error": err},
)
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
```
- [ ] **Step 5: Run the tests, and watch them pass.**
Run: `.venv/bin/python -m pytest tests/test_device_access_s4_events.py tests/test_device_access_s4.py -q`
Expected: all pass.
- [ ] **Step 6: Commit and push.** Message: `feat(sfm): Series-4 events -- chain-walk list, download at THOR's cursor`.
---
### Task 6: `DeviceAccess.list_events` / `download_event`
**Files:**
- Modify: `sfm/device_access/access.py`, and `sfm/device_access/s4.py` (`Series4Session._exchange`)
- Test: `tests/test_device_access_event_dispatch.py` (new)
**Interfaces:**
- Consumes: Tasks 3–5.
- Produces:
- `DeviceAccess.list_events(address, serial) -> EventList`
- `DeviceAccess.download_event(address, serial, event_id) -> DownloadedEvent`
- [ ] **Step 1: Write the failing tests** in `tests/test_device_access_event_dispatch.py`:
```python
"""Events through the one door: same shape both series, the held line, ring safety."""
from __future__ import annotations
import dataclasses
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from device_access_fakes import FakeMicromateClient, FakeMiniMateClient # noqa: E402
from sfm.device_access.access import DeviceAccess # noqa: E402
from sfm.device_access.errors import BadRequest, CallHomeInProgress # noqa: E402
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s4 import RingDetected # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
def access(s3=(), s4=()):
s3q, s4q = list(s3), list(s4)
return DeviceAccess(s3_client_factory=lambda a, **kw: s3q.pop(0),
s4_client_factory=lambda a, **kw: s4q.pop(0), start_reaper=False)
def test_both_series_list_events_in_the_same_shape():
s3 = access(s3=[FakeMiniMateClient()]).list_events(ADDR, "BE18193")
s4 = access(s4=[FakeMicromateClient()]).list_events(ADDR, "UM20147")
f3 = [set(dataclasses.asdict(e)) for e in s3.events]
f4 = [set(dataclasses.asdict(e)) for e in s4.events]
assert all(f == f3[0] for f in f3 + f4)
def test_no_shared_field_is_empty_for_either_series():
# A field one series cannot fill belongs under `detail`, not at the top level.
for out in (access(s3=[FakeMiniMateClient()]).list_events(ADDR, "BE18193"),
access(s4=[FakeMicromateClient()]).list_events(ADDR, "UM20147")):
for e in out.events:
empty = {k for k, v in dataclasses.asdict(e).items() if v is None}
assert empty == set(), (out.series, empty)
def test_a_micromate_list_and_download_share_one_held_line():
fake = FakeMicromateClient()
da = access(s4=[fake])
listed = da.list_events(ADDR, "UM20147")
dl = da.download_event(ADDR, "UM20147", listed.events[0].event_id)
assert fake.opened == 1 and dl.idf_bytes
assert da.held_serial(ADDR) == "UM20147"
def test_an_id_from_another_unit_is_refused_before_any_io():
fake = FakeMicromateClient()
with pytest.raises(BadRequest):
access(s4=[fake]).download_event(ADDR, "UM20147", "UM12947:055d4a81:20250531135901")
assert fake.opened == 0
def test_a_minimate_download_goes_through_the_series3_adapter():
dl = access(s3=[FakeMiniMateClient()]).download_event(ADDR, "BE18193", "BE18193:01110000:-")
assert dl.series == 3 and dl.a5_frames == ["frame"]
def test_a_ring_mid_download_releases_the_line_and_downloads_nothing():
fake = FakeMicromateClient()
def ring(*a, **kw):
raise RingDetected("RADIO RING")
fake.fetch_event = ring
da = access(s4=[fake])
with pytest.raises(CallHomeInProgress):
da.download_event(ADDR, "UM20147", "UM20147:055d4a81:20250531135901")
assert fake.closed == 1 and da.held_serial(ADDR) is None
def test_a_stale_or_missing_event_keeps_the_line():
# The operation's own verdict (404/409) says nothing is wrong with the link;
# hanging up would cost a call-up for no reason.
from sfm.device_access.errors import EventNotFound, StaleEvent
fake = FakeMicromateClient()
da = access(s4=[fake])
with pytest.raises(StaleEvent):
da.download_event(ADDR, "UM20147", "UM20147:055d4a81:20240101000000")
with pytest.raises(EventNotFound):
da.download_event(ADDR, "UM20147", "UM20147:deadbeef:-")
assert fake.opened == 1 and fake.closed == 0
assert da.held_serial(ADDR) == "UM20147"
```
- [ ] **Step 2: Run them, and watch them fail.**
Run: `.venv/bin/python -m pytest tests/test_device_access_event_dispatch.py -q`
Expected: FAIL with `AttributeError: 'DeviceAccess' object has no attribute 'list_events'`.
- [ ] **Step 3: Implement.** In `sfm/device_access/access.py`:
- Imports: add `DownloadedEvent, EventList` to the `.models` import, `s4_download_event, s4_list_events` to the `.s4` import, and `from .events import parse_event_id`.
- Add after `settings`:
```python
def list_events(self, address: UnitAddress, serial: str) -> EventList:
return self._dispatch(address, serial, self._s3.list_events, s4_list_events)
def download_event(self, address: UnitAddress, serial: str, event_id: str) -> DownloadedEvent:
"""Read-only on the unit. Holds the unit for the whole download, so
other requests for it wait, then get 423."""
key, stamp = parse_event_id(event_id, serial) # BadRequest before any I/O
return self._dispatch(
address, serial,
lambda a, s: self._s3.download_event(a, s, key, stamp),
lambda c, s: s4_download_event(c, s, key, stamp))
```
- In `_dispatch`, replace the comment line `# Call up fresh and retry ONCE. Safe only because phase 1a` and the next line `# operations are reads (idempotent); writes (phase 3) must NOT` with:
```python
# Call up fresh and retry ONCE. Safe only because every operation
# here is a read (identify, status, settings, list, download -- all
# idempotent); writes (phase 3) must NOT
```
Leave the comment's last line, `# inherit this -- a write whose ack was lost must never be sent twice.`, as it is.
In `sfm/device_access/s4.py`, add `DeviceError` to the `.errors` import. In `Series4Session._exchange`, add a clause between the `except RingDetected` block and the `except Exception` block:
```python
except DeviceError:
# The operation's own verdict (event not found, stale id): the line
# is healthy, so keep it. Library errors still hang up below.
raise
```
- [ ] **Step 4: Run the tests, and watch them pass.**
Run: `.venv/bin/python -m pytest tests/test_device_access_event_dispatch.py tests/test_device_access.py -q`
Expected: all pass.
- [ ] **Step 5: Commit and push.** Message: `feat(sfm): DeviceAccess lists and downloads events for both series`.
---
### Task 7: SDM ingest: `sfm/event_ingest.py`
**Files:**
- Create: `sfm/event_ingest.py`
- Modify: `sfm/server.py`. The legacy `device_event_blastware_file` calls `backfill_series3_event` instead of its inline copy; behaviour is identical.
- Test: `tests/test_event_ingest.py` (new)
**Interfaces:**
- Consumes:
- Task 3's `DownloadedEvent` and `EventDownload`.
- `WaveformStore.save()` / `.save_imported_idf()`.
- `SeismoDb.insert_events()` / `.query_events()`.
- Produces:
- `persist_download(dl, *, store, db) -> EventDownload`
- `backfill_series3_event(ev, cc) -> None`
- `IngestError`
- [ ] **Step 1: Write the failing tests** in `tests/test_event_ingest.py`:
```python
"""Storing a downloaded event: the same store + DB writes every ingest path makes."""
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 device_access_fakes import FakeMiniMateClient, s3_event # noqa: E402
from sfm.database import SeismoDb # noqa: E402
from sfm.device_access.models import DownloadedEvent # noqa: E402
from sfm.event_ingest import backfill_series3_event, persist_download # noqa: E402
from sfm.waveform_store import WaveformStore # noqa: E402
THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
@pytest.fixture
def sdm(tmp_path):
return WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo.db")
def s4_download(name, verified=True):
return DownloadedEvent(event_id=f"UM20147:055d4a81:{name[8:22]}", serial="UM20147", series=4,
filename=name, verified=verified, idf_bytes=(THOR_IDF / name).read_bytes())
def test_a_series4_waveform_is_stored_and_findable(sdm):
store, db = sdm
out = persist_download(s4_download("UM20147_20250531135901.IDFW"), store=store, db=db)
assert out.stored_filename == "UM20147_20250531135901.IDFW" and out.inserted
assert (store.root / "UM20147" / out.stored_filename).exists()
row = db.get_event(out.db_event_id)
assert row["serial"] == "UM20147" and row["device_family"] == "series4"
assert out.verified is True and out.sha256
def test_a_series4_histogram_is_stored(sdm):
store, db = sdm
out = persist_download(s4_download("UM20147_20250330070110.IDFH", verified=None), store=store, db=db)
assert out.inserted and out.db_event_id and out.verified is None
def test_storing_the_same_event_twice_refreshes_rather_than_duplicates(sdm):
store, db = sdm
first = persist_download(s4_download("UM20147_20250531135901.IDFW"), store=store, db=db)
again = persist_download(s4_download("UM20147_20250531135901.IDFW"), store=store, db=db)
assert (first.inserted, again.inserted) == (True, False)
assert again.db_event_id == first.db_event_id
assert len(db.query_events(serial="UM20147")) == 1
class RecordingStore:
def __init__(self):
self.saved = []
def save(self, ev, serial, a5_frames, *, geo_range="normal", source_kind="sfm-live"):
self.saved.append((ev, serial, a5_frames, geo_range))
return {"filename": "T193LQ9K.OE0", "filesize": 8708, "sha256": "ab" * 32}
def test_a_series3_event_is_backfilled_then_stored_as_series3(tmp_path):
db = SeismoDb(tmp_path / "seismo.db")
store = RecordingStore()
fake = FakeMiniMateClient()
ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0))
dl = DownloadedEvent(event_id="BE18193:01110000:20261001080000", serial="BE18193", series=3,
filename="T193LQ9K.OE0", verified=None, event=ev, a5_frames=["frame"],
compliance=fake.compliance)
out = persist_download(dl, store=store, db=db)
saved_ev, serial, frames, geo_range = store.saved[0]
assert (serial, frames, geo_range) == ("BE18193", ["frame"], 0)
assert saved_ev.sample_rate == 1024 and saved_ev.rectime_seconds == 3.0
assert db.get_event(out.db_event_id)["device_family"] == "series3"
assert out.stored_filename == "T193LQ9K.OE0"
def test_backfill_derives_total_samples_only_when_the_decoded_one_is_implausible():
cc = FakeMiniMateClient().compliance # 1024 sps, 3.0 s
ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1))
ev.total_samples = 40_000
backfill_series3_event(ev, cc)
assert ev.total_samples == 3072
ev.total_samples = 3000
backfill_series3_event(ev, cc)
assert ev.total_samples == 3000
def test_backfill_without_settings_changes_nothing():
ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1))
backfill_series3_event(ev, None)
assert ev.sample_rate is None
```
- [ ] **Step 2: Run them, and watch them fail.**
Run: `.venv/bin/python -m pytest tests/test_event_ingest.py -q`
Expected: FAIL with `ModuleNotFoundError: No module named 'sfm.event_ingest'`.
- [ ] **Step 3: Implement.** Create `sfm/event_ingest.py`:
```python
"""Store an event SFM downloaded from a unit -- the SDM side of
POST /device/events/download.
Both series end in the two writes every other ingest path makes: the waveform
store (file + sidecar + .h5) and SeismoDb.insert_events(). The database matches
rows on (serial, timestamp), so storing an event already there -- by an earlier
download, or by THOR's watcher -- refreshes the row instead of duplicating it.
"""
from __future__ import annotations
import datetime
from pathlib import Path
from typing import Any, Optional
from sfm.device_access.models import DownloadedEvent, EventDownload
class IngestError(Exception):
"""Downloaded from the unit, but could not be stored."""
def backfill_series3_event(ev: Any, cc: Any) -> None:
"""Compliance-config values that supersede what the 5A stream decoded.
Some STRT fields have ambiguous semantics (STRT[20] is rectime, but
STRT[8:10] / STRT[16:18] are device-specific scratch, not reliable sample or
pre-trigger counts). Shared with GET /device/event/{i}/blastware_file.
"""
if not cc:
return
if ev.sample_rate is None and cc.sample_rate:
ev.sample_rate = cc.sample_rate
if cc.record_time:
# Authoritative: the user-set value the unit followed when recording.
ev.rectime_seconds = cc.record_time
# Derive total_samples from sample_rate x rectime when we can; the
# STRT-derived value can land at a buffer offset rather than a count.
if ev.sample_rate and ev.rectime_seconds:
derived = int(round(ev.sample_rate * ev.rectime_seconds))
if (ev.total_samples is None
or ev.total_samples > derived * 2
or ev.total_samples < derived // 4):
ev.total_samples = derived
def _event_dt(ev: Any) -> Optional[datetime.datetime]:
ts = getattr(ev, "timestamp", None)
try:
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
except Exception: # noqa: BLE001
return None
def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownload:
if dl.series == 4:
ev, rec = store.save_imported_idf(dl.idf_bytes, source_path=Path(dl.filename),
serial_hint=dl.serial)
family = "series4"
else:
ev = dl.event
backfill_series3_event(ev, dl.compliance)
geo_range = getattr(dl.compliance, "geo_range", None) if dl.compliance else None
rec = store.save(ev, serial=dl.serial, a5_frames=dl.a5_frames,
geo_range=geo_range if geo_range is not None else "normal")
family = "series3"
if ev is None or ev._waveform_key is None:
raise IngestError(f"{dl.filename}: stored the file but could not build a database row")
inserted, _skipped = db.insert_events(
[ev], serial=dl.serial,
waveform_records={ev._waveform_key.hex(): rec}, device_family=family)
row_id = None
dt = _event_dt(ev)
if dt is not None:
rows = db.query_events(serial=dl.serial, from_dt=dt, to_dt=dt, limit=1)
row_id = rows[0]["id"] if rows else None
return EventDownload(
event_id=dl.event_id, serial=dl.serial, series=dl.series, db_event_id=row_id,
stored_filename=rec["filename"], filesize=rec["filesize"], sha256=rec.get("sha256"),
inserted=inserted > 0, verified=dl.verified, detail=dict(dl.detail),
)
```
In `sfm/server.py`:
- Add `from sfm.event_ingest import backfill_series3_event, persist_download` after `from sfm import db_snapshot`.
- In `device_event_blastware_file`, replace this block:
```python
cc = info.compliance_config
# Backfill authoritative compliance-config values onto the
# Event before persisting. These supersede whatever
# _decode_a5_waveform read from the STRT bytes (some of which
# have ambiguous semantics — e.g. STRT[20] is rectime but
# STRT[8:10] / STRT[16:18] are device-specific scratch fields
# that aren't reliable sample/pretrig counts).
if cc:
if ev.sample_rate is None and cc.sample_rate:
ev.sample_rate = cc.sample_rate
if cc.record_time:
# record_time from compliance is authoritative — the
# user-set value the device followed when recording.
ev.rectime_seconds = cc.record_time
# Derive total_samples from sample_rate × rectime when
# we can; the STRT-derived value can land at a buffer-
# offset rather than a sample count.
if ev.sample_rate and ev.rectime_seconds:
derived = int(round(ev.sample_rate * ev.rectime_seconds))
if (ev.total_samples is None
or ev.total_samples > derived * 2
or ev.total_samples < derived // 4):
ev.total_samples = derived
```
with
```python
cc = info.compliance_config
backfill_series3_event(ev, cc)
```
- [ ] **Step 4: Run the tests, and watch them pass.**
Run: `.venv/bin/python -m pytest tests/test_event_ingest.py -q`
Expected: 6 passed.
- [ ] **Step 5: Commit and push.** Message: `feat(sfm): store a downloaded event -- one ingest for both series`.
---
### Task 8: The endpoints
**Files:**
- Modify: `sfm/server.py`: `_SERIAL_AWARE_PATHS`, `device_events`, new `device_events_download`
- Modify: `tests/test_server_device_access.py`
**Interfaces:**
- Consumes: Tasks 6–7.
- Produces:
- `GET /device/events?serial=…` → `EventList` as JSON.
- `POST /device/events/download?serial=…&event_id=…` → `EventDownload` as JSON.
- [ ] **Step 1: Write the failing tests.** In `tests/test_server_device_access.py`:
- Change the `da` fixture's factories to `lambda a, **kw: s3q.pop(0)` and `lambda a, **kw: s4q.pop(0)`.
- Add `"/device/events", "/device/events/download"` to the path list of `test_guard_allows_um_serial_on_serial_aware_routes_and_hangup`.
- Append:
```python
# ── events ────────────────────────────────────────────────────────────────────
from sfm.database import SeismoDb # noqa: E402
from sfm.waveform_store import WaveformStore # noqa: E402
W_ID = "UM20147:055d4a81:20250531135901"
@pytest.fixture
def sdm(tmp_path, monkeypatch):
db = SeismoDb(tmp_path / "seismo.db")
store = WaveformStore(tmp_path / "waveforms")
monkeypatch.setattr(srv, "_get_db", lambda: db)
monkeypatch.setattr(srv, "_get_store", lambda: store)
return store, db
EV = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034)
@pytest.mark.parametrize("serial,series", [("UM20147", 4), ("BE18193", 3)])
def test_events_with_a_serial_return_the_shared_list(da, serial, series):
out = srv.device_events(debug=False, force=False, serial=serial, **EV)
assert (out["serial"], out["series"], len(out["events"])) == (serial, series, 2)
assert set(out["events"][0]) == {"event_id", "serial", "series", "index", "timestamp",
"record_type", "peak_vector_sum_ips", "peaks_ips",
"filename", "detail"}
def test_events_without_a_serial_run_the_legacy_path(monkeypatch):
class Legacy(Exception):
pass
def untouchable():
raise AssertionError("DeviceAccess must not be used without a serial")
def legacy_cache():
raise Legacy()
monkeypatch.setattr(srv, "_device_access", untouchable)
monkeypatch.setattr(srv, "get_cache", legacy_cache)
with pytest.raises(Legacy):
srv.device_events(debug=False, force=False, serial=None, **EV)
def test_download_stores_the_event_and_says_where(da, sdm):
out = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
assert out["inserted"] is True and out["verified"] is True
assert out["stored_filename"] == "UM20147_20250531135901.IDFW"
_store, db = sdm
assert db.get_event(out["db_event_id"])["serial"] == "UM20147"
def test_downloading_it_again_refreshes_the_same_row(da, sdm):
first = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
again = srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
assert again["inserted"] is False and again["db_event_id"] == first["db_event_id"]
@pytest.mark.parametrize("event_id,status", [
("UM12947:055d4a81:20250531135901", 422), # another unit's event
("garbage", 422),
("UM20147:055d4a81:20240101000000", 409), # stale: erased since listed
("UM20147:deadbeef:-", 404),
])
def test_download_errors_have_their_statuses(da, sdm, event_id, status):
with pytest.raises(HTTPException) as ei:
srv.device_events_download(serial="UM20147", event_id=event_id, **EV)
assert ei.value.status_code == status
assert sdm[1].query_events(serial="UM20147") == []
def test_a_decode_that_disagrees_is_502_and_nothing_is_stored(da, sdm, monkeypatch):
from micromate.client import DecodeMismatch
def mismatch(*a, **kw):
raise DecodeMismatch("decoded PVS differs by +5%")
fake = FakeMicromateClient()
fake.fetch_event = mismatch
monkeypatch.setattr(da, "_s4_factory", lambda a, **kw: fake)
with pytest.raises(HTTPException) as ei:
srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
assert ei.value.status_code == 502
assert sdm[1].query_events(serial="UM20147") == []
def test_a_store_failure_is_500_and_names_what_was_downloaded(da, monkeypatch):
class BrokenStore:
def save_imported_idf(self, *a, **kw):
raise OSError("disk full")
monkeypatch.setattr(srv, "_get_store", lambda: BrokenStore())
with pytest.raises(HTTPException) as ei:
srv.device_events_download(serial="UM20147", event_id=W_ID, **EV)
assert ei.value.status_code == 500
assert "UM20147_20250531135901.IDFW" in ei.value.detail and "disk full" in ei.value.detail
```
- [ ] **Step 2: Run them, and watch them fail.**
Run: `.venv/bin/python -m pytest tests/test_server_device_access.py -q`
Expected: FAIL with `TypeError: device_events() got an unexpected keyword argument 'serial'`, and `AttributeError ... device_events_download`.
- [ ] **Step 3: Implement.** In `sfm/server.py`:
`_SERIAL_AWARE_PATHS` becomes:
```python
_SERIAL_AWARE_PATHS = frozenset({
"/device/info", "/device/connect", "/device/monitor/status", "/device/settings",
"/device/events", "/device/events/download",
})
```
`device_events`:
- Change the `baud` line to ` baud: Optional[int] = Query(None, description="Serial baud (default 38400; 115200 for a Micromate)"),`.
- Add ` serial: Optional[str] = Query(None, description=_SERIAL_DOC),` as the last parameter.
- Add this paragraph at the top of its docstring:
```
**With `serial`** (UM... or BE.../BA...): the unit's events in the shared
shape for either series, read from headers only -- no event is downloaded
to list it -- and not cached. Each carries an `event_id` for
POST /device/events/download. Without `serial`, the legacy Series-3
behaviour below.
```
- Insert as the first statements after the docstring, before the `log.info(...)` line:
```python
if serial:
return _via_device_access(
lambda: _device_access().list_events(_unit_address(port, baud, host, tcp_port), serial))
baud = 38400 if baud is None else baud
```
Add the new handler right after `device_settings`:
```python
@app.post("/device/events/download")
def device_events_download(
serial: str = Query(..., description=_SERIAL_DOC),
event_id: str = Query(..., description="From GET /device/events?serial=..."),
port: Optional[str] = Query(None, description="Serial port (e.g. /dev/ttyACM0)"),
baud: Optional[int] = Query(None, description="Serial baud (default by series)"),
host: Optional[str] = Query(None, description="TCP host -- modem IP"),
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
) -> dict:
"""Download one event, check it, and store it in SFM's database.
Read-only on the unit. The stored file and waveform are then at
/db/events/{db_event_id}/... . Storing an event that is already stored
refreshes its row (`inserted: false`). The unit is busy for the whole
download: other requests for it wait, then get 423.
"""
try:
dl = _device_access().download_event(_unit_address(port, baud, host, tcp_port), serial, event_id)
except DeviceError as exc:
raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc
try:
out = persist_download(dl, store=_get_store(), db=_get_db())
except Exception as exc:
log.error("events/download: %s downloaded but not stored: %s", dl.event_id, exc, exc_info=True)
raise HTTPException(
status_code=500,
detail=f"downloaded {dl.filename} from the unit but could not store it: {exc}") from exc
return dataclasses.asdict(out)
```
- [ ] **Step 4: Run the tests, and watch them pass.**
Run: `.venv/bin/python -m pytest tests/test_server_device_access.py -q`
Expected: all pass.
- [ ] **Step 5: Run the full suite.**
Run: `.venv/bin/python -m pytest -q 2>&1 | tail -3`
Expected: exactly the 16 pre-existing failures; everything else passes.
- [ ] **Step 6: Commit and push.** Message: `feat(sfm): list and download events by serial for both series`.
---
### Task 9: Bench check on UM20147, and the record
**Files:**
- Modify: `CLAUDE.md`, `README.md`, `docs/micromate_protocol_reference.md`
- Scratch (not committed): a launcher and a probe script in the session scratchpad
Read-only throughout. UM20147 is on `/dev/ttyACM0`, which needs `sg dialout -c "..."`. The server runs on **port 8299** with a **scratch database**, never the dev DB and never port 8200. Start the server, query it and stop it **within one Bash command**: shell state does not persist between calls.
- [ ] **Step 1: Write the launcher** at `<scratchpad>/sfm_bench.py`:
```python
import sys
from pathlib import Path
sys.path.insert(0, "/home/serversdown/seismo-relay")
import uvicorn # noqa: E402
import sfm.server as srv # noqa: E402
srv._DEFAULT_DB_PATH = Path(sys.argv[1]) # scratch DB, created on first use
uvicorn.run(srv.app, host="127.0.0.1", port=8299, log_level="info")
```
- [ ] **Step 2: One command.** It must:
- start the launcher under `sg dialout`, with the DB at `<scratchpad>/bench1b/seismo.db` and the log at `<scratchpad>/bench1b/server.log`;
- wait for `GET /health`;
- run the calls below;
- kill the server by PID (`pgrep -f sfm_bench.py`) and confirm it is gone.
```bash
B="http://127.0.0.1:8299"; U="serial=UM20147&port=/dev/ttyACM0"
curl -s "$B/device/monitor/status?$U" # event_count
curl -s "$B/device/events?$U" > <scratchpad>/bench1b/events.json # the list
# pick the first waveform's and the first histogram's event_id from events.json (python -c ...)
curl -s -X POST "$B/device/events/download?$U&event_id=<W_ID>"
curl -s -X POST "$B/device/events/download?$U&event_id=<W_ID>" # again: inserted false, same db_event_id
curl -s -X POST "$B/device/events/download?$U&event_id=<H_ID>"
curl -s -o <scratchpad>/bench1b/w.bin "$B/db/events/<W_DB_ID>/blastware_file"
curl -s -o /dev/null -w "%{http_code}\n" -X POST "$B/device/events/download?$U&event_id=<W_ID with its timestamp changed>" # 409
curl -s -X POST "$B/device/hangup?port=/dev/ttyACM0"
```
Check each of these, and report every one:
- the list's length equals status's `event_count`;
- every event has a non-null timestamp, record_type and filename;
- the waveform download has `verified: true`, and the histogram `verified: null`;
- the second download has `inserted: false` with the same `db_event_id`;
- the size of `w.bin` equals that event's `detail.size_bytes`;
- the altered id gives 409;
- the server log shows ONE call-up for the whole sequence, then a hang-up.
- [ ] **Step 3: Measure direct-by-key download (a read; protocol finding).** With the server stopped, run a scratch script under `sg dialout`:
- `MicromateClient` over `SerialTransport("/dev/ttyACM0", 115200)`, then `open()` and `connect()`;
- `refs = list_events()`;
- for the same waveform, `direct = download_event(ref, chunk_size=1024)` with the cursor parked at the end of the chain;
- `walked = ` the same bytes via `iter_events()` at the cursor;
- compare `direct == walked` and both against `w.bin`.
Record the result in `docs/micromate_protocol_reference.md`, in the section on event download (find "iter_events" or "cursor"). Use a dated (2026-10-21+) and **graded** line: *measured on one unit over USB, N events*. Do NOT change `s4_download_event`; switching paths is a later decision.
- [ ] **Step 4: The record.**
- `CLAUDE.md`: in the "SFM speaks Series 4 by serial" bullet, add one sentence: phase 1b lists and downloads events by serial for both series (MiniMate list from headers only, no 5A), with downloads stored in SFM's DB. ⚠ The MiniMate header walk is **unproven on a unit; a MiniMate bench check is owed before the branch merges.**
- In the "SFM REST API" live-device list, add `GET /device/events?serial=` and `POST /device/events/download`.
- `README.md`: in the device endpoints section, document both, including:
- `event_id` and the 409-on-stale behaviour;
- that downloading stores the event and returns `db_event_id`;
- that a re-download refreshes the row;
- that the unit is busy for the whole download.
- [ ] **Step 5: Commit and push.** Message: `docs: phase 1b bench-checked on UM20147 -- events by serial for both series`.
---
## Self-review notes
- **Spec rows 4–5:**
- Tasks 1/4: S3 list and download.
- Tasks 2/5: S4.
- Task 6: one door.
- Task 7: store.
- Task 8: endpoints.
- Task 9: hardware.
- The 1b decisions in the spec map to Tasks 1 (header walk), 7 (download stores), 3 (event_id) and 5 (walk-to-event, THOR chunk size).
- **The MiniMate bench check is deliberately not a task.** No MiniMate is on the bench. Task 9 records it as owed before merge, in CLAUDE.md as well as in the spec.
- **Not in 1b:**
- event delete;
- the 64 KB page fix (only named, in Task 4);
- a byte-level verification for Series 3 (`verified` is None for Series 3: there is no self-check to run);
- caching on the serial path.