Files
seismo-relay/docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md
T

636 lines
37 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: Series-4 parity and a device safety layer — design
**Date:** 2026-10-20 · **Branch:** `feat/series4-sfm-parity` · **Status:** draft for review
**Decided with:** Brian, in conversation 2026-10-19/20.
## In plain terms
SFM can already *read* a Micromate almost as well as it reads a MiniMate, but
only through the Python library and bench scripts. SFM's web endpoints still
only speak Series 3. This design does three things:
1. Gives Series 4 the same everyday jobs in SFM that Series 3 has: identify a
unit, check its status, read its settings, list and download events,
start/stop monitoring, and change its settings.
2. Adds a **safety layer** every device request goes through. It makes sure a
command only reaches the unit it was meant for, logs every change, and
checks every change by reading the unit back.
3. Lets SFM **stay on the line** with a Micromate. It calls up once, confirms
the serial, and keeps the connection open for later commands instead of
reconnecting each time.
**The guiding principle (Brian): talking to a Series 3 unit and talking to a
Series 4 unit is the same for the user.** It is the same screens, the same
endpoints, the same way of naming a unit, and the same shape of answer. The
only visible difference is the serial (`UM…` vs `BE…`) and the settings each
model has. The differences live underneath, in one adapter per series.
It does **not** cover the emergency tools (runaway-unit stops, rescue, erase),
the call-home receiver, or anything async. Those come later, as features
shared by both series.
**Production reach, stated honestly:** while THOR is set to stay connected to
production Micromates, a modem's single connection is taken. SFM can't reach
those units until THOR lets go or SFM takes over call-home. In this phase,
Series-4 SFM is for the bench and for units THOR is not holding.
---
## Decisions
| decision | why | who |
|---|---|---|
| **One user experience for both series** | the user's method is identical; only the serial prefix and each model's settings differ; adapters absorb the rest | Brian |
| Match **jobs**, not endpoints | some Series-3 endpoints only exist to work around Series-3 quirks | agreed |
| **No Series-4 emergency tools** yet (runaway stop, rescue, erase) | Micromates rarely need them | Brian |
| The series comes from the **serial prefix**: `UM` = Micromate, `BE` = MiniMate Plus, `BA` = Blastmate | the prefixes are definitive, so there is no probing | Brian |
| Before any **write**, confirm the unit that answered is the one named | SFM addresses units by IP; a moved modem or stale IP means a different unit answers | agreed |
| **Synchronous** endpoints for now; async later, for both series together | parity first, then shared features | agreed |
| **No library of setup files on the PC** (unlike THOR). The unit's own settings are the truth: SFM reads them from the unit, and verifies every push by reading the unit back | THOR keeps one copy of each setup on the PC and another on the unit, linked only by file name. Nothing checks the contents match, so the PC's `test2` and the unit's `test2` can say different things | Brian |
| **Sessions for Series 4 now; Series 3 only after a bench test** | THOR holds Micromate lines daily without harm; a MiniMate's hangup/DCD behaviour is untested | Brian |
| Audit log in **SFM's database** (new table) | Terra-View can show it; it fits the existing `CREATE TABLE IF NOT EXISTS` pattern | proposed |
---
## Scope: the parity table
Rows 8 and 11 of the original inventory (runaway stops, rescue/erase) are out
of scope by decision. Row 6 (monitor log) moved to the parking lot: it is its
own piece of work, together with call-in monitor-log ingest.
| # | job | Series 3 in SFM today | Series 4: protocol status | Series 4 in this phase |
|---|---|---|---|---|
| 1 | Identify a unit | `/device/info` (walks the whole chain, slow) | implemented: `connect()` | dispatch to the Micromate client |
| 2 | Quick status (monitoring, battery, memory, clock) | `monitor/status`, `storage_range`, `events/index` | implemented: `get_state()`; the `0x06` event count is decoded only in the bench tool | same endpoints; move the count decode into the client |
| 3 | Read settings | compliance in `/device/info`; `GET /device/call_home` | `get_setup()` implemented and verified on hardware; call-home: enable + dial string observed, rest unmapped | setup in full; call-home returns enable + dial string + raw |
| 4 | List events | `/device/events` (downloads every event to list them) | implemented, and cheap: the chain walk returns sizes | the same event-list shape as Series 3, each event carrying an `event_id` |
| 5 | Download an event | `/event/{i}`, `/waveform`, `/blastware_file` | implemented: streams the `.IDFW`/`.IDFH` itself, with a decode self-check | the same download and save-to-DB actions as Series 3. Underneath, Series 4 saves through `/db/import/idf_file` |
| 7 | Start / stop monitoring | `monitor/start`, `monitor/stop` | mapped, identical to Series 3 (`0x96`/`0x97`, acks `0x69`/`0x68`); never sent | **first write.** Verify with `0x49` state |
| 9 | Change call-home settings | `POST /device/call_home` | write mapped (`0x2C` → `0x7E`/`0x7F`, same as Series 3); field map mostly unknown | enable/disable only; the rest waits for the THOR round |
| 10 | Change recording settings | `POST /device/config` | sequence mapped (`0xDA` → `0x68/73` → `0x82/83` → `0x71/72`); no encoder | read-modify-write, stop → push → restart, verify with `get_setup()` |
---
## Architecture
### One door for every device request
A new module, `sfm/device_access.py`, sits between the `/device/*` handlers and
the two device libraries. No handler opens a transport or picks a library
itself any more.
```
/device/* handler
│ (serial, address, action, tier)
▼
device_access ── series from serial prefix ── session / per-unit lock
│ │ │
│ ▼ ▼
│ minimateplus (S3) or micromate (S4) audit table
▼
read-back verification (changes only)
```
- **Naming a unit is the same for both: `serial` + address.** The prefix picks
the adapter: `UM` → Series 4 (`micromate`); `BE` or `BA` → Series 3
(`minimateplus`); any other prefix → 422. A request with no `serial` is
treated as Series 3. That is a **legacy path** kept only so existing scripts
keep working; the webapp and every new caller always send `serial`.
- **One contract.** Same `/device/*` paths, same request parameters, and
**the same response models for both series**:
- `UnitInfo`, `UnitStatus`, `UnitSettings`, `EventRef`, `ChangeResult`
- Anything only one series has goes under a `detail` object inside the same
model, never as a different top-level shape. `"series": 3 | 4` is
informational.
- **Events have one identity.** An opaque `event_id` string from the event
list, passed back to download it. Underneath it is Series 3's position or
Series 4's device key, plus the serial; the user never handles either.
- **Not-yet-supported is uniform.** If one series can't do something yet,
the endpoint still exists and answers **501 "not supported for Series N
yet"**. It is never a missing route or a different call.
- **Work separate from HTTP.** Each operation is a plain function taking the
session. The handler is a thin wrapper, so making an operation an async job
later means changing the wrapper, not the operation.
### Adapters
Each series implements the same operation set behind `device_access`:
| operation | Series 3 adapter | Series 4 adapter |
|---|---|---|
| `identify` | STARTUP + serial + config | `connect()` |
| `status` | `0x1C` (+ `0x06`) | `get_state()` + `0x06` count |
| `read_settings` | `0x1A` compliance decode | `get_setup()` |
| `list_events` | today's walk | chain walk (cheap) |
| `download_event` | 5A → Blastware file | 5A → `.IDFW`/`.IDFH` |
| `start` / `stop` | `0x96` / `0x97` (exists) | `0x96` / `0x97` (new) |
| `read_call_home` / `set_call_home_enabled` | exists | `0x2C` / `0x7E`+`0x7F` |
| `push_settings` | `/device/config` path (exists) | setup push (new) |
| `call_up` / `hang_up` | connect-per-request underneath, until the bench test | held session |
Each adapter maps its native data into the shared models. `UnitSettings` keeps
the fields both series have under the same names and units: record mode,
sample rate, record time, histogram interval, trigger levels, the notes as
label → value. Model-specific fields go under `detail`.
**Requests that include `serial` get the shared models; requests without it
keep today's Series-3 shapes, unchanged.** Nothing breaks in between: the
webapp moves to `serial` in phase 1c, and the old path retires after that and
after `watch_unit.sh` moves. Terra-View does not call `/device/*`. The
emergency endpoints (`stop_monitoring_*`, `rescue`, `events/erase`) are not
touched and stay Series-3 only; a `UM` serial gets 501.
### The webapp
The same screens for both series. You name a unit by serial + address (today
it takes host/port only), and the series shows as a badge, nothing more. Read
panels for both series land in phase 1; each write button appears for Series 4
in the phase that adds that write.
### The safety layer
**Tiers.** Every operation declares one:
| tier | examples | what the layer does |
|---|---|---|
| read | info, status, setup, events, download | runs; no identity check |
| change | start/stop, call-home, setup push | identity check → audit → send → **read back** → audit the result |
| destructive | delete, erase (none in this phase) | everything above + the caller must send the unit's serial as `confirm` |
**Identity check (changes only).** Before the first change in a connection,
compare the serial the unit reports with the one requested; on a mismatch,
refuse (409) and send nothing. Series 4 already reads the serial in
`connect()`. A Series-3 change adds one serial read (`SUB 0x15`), about one
round trip.
**Opcode guard.** A send-side check that refuses known cross-series
collisions. It starts with **`0xA2`**, which is CONFIRM ERASE on Series 3 and
"end call-home" on Series 4. This phase never sends `0xA2`; the guard makes
that impossible by accident. The table of colliding opcodes lives in one
place.
**One connection per unit.** A per-unit lock keyed by address
(`tcp:host:port` / `serial:port`). A request for a busy unit waits up to
**20 s** (configurable; under Terra-View's 60 s proxy timeout), then gets
**423 "unit busy"** instead of opening a second connection. This applies to Series 3 as well. The webapp's Diagnostics
refresh currently fires three device requests at once against a modem that
allows one; under the lock they queue.
**Read-back verification.** A zero-data ack has never been proof that a write
applied. Every change is followed by a read:
- start/stop → `0x49` state: start expects `0x02`, stop expects `0x00`. Record
the value either way; `0x03` is the in-call-home state
- call-home → re-read `0x2C` and compare the edited bytes
- setup push → `get_setup()` and compare every field that was set
A mismatch is reported as a failed change (and audited as one), even if the
ack was clean.
**Errors that say what happened.** Distinct responses for:
- 503: couldn't connect
- 504: connected but the unit didn't answer
- 423: unit busy
- 409: wrong unit
- 422: bad input
- 502: the reply was malformed
Today 502 covers both of the first two.
**Audit table.** New table `device_commands`, created on startup like the
others. It is additive, but still a schema change, so the changelog says so.
One row per change attempt:
| column | content |
|---|---|
| `ts`, `serial`, `series`, `address` | who and where |
| `action`, `tier` | e.g. `monitor_stop`, `change` |
| `request` | parameters, plus hex of what was sent |
| `ack` | reply summary |
| `verified` | read-back result: `ok` / `mismatch` / `not_checked` |
| `outcome`, `error` | final result |
| `caller` | best-effort origin (`webapp`, `terra-view`, `script`) |
Reads are not audited.
### Sessions
1. **Call up.** Connect, `connect()` (POLL / SERIAL / STATE), identity check
against the requested serial.
2. **On the line.** Requests for that unit run in turn on the same connection,
behind the per-unit lock.
3. **Keep-alive.** A POLL every 60 s while idle. The ACEmanager TCP idle
timeout is 2 min.
4. **Hang up.** On `POST /device/hangup`, after 5 idle minutes, or on any
transport error. A reconnect is a new session with a new identity check.
5. **Ring safety.** If `RADIO RING` arrives on an SFM session, log it and hang
up **immediately**. Until SFM is the call-home destination, the unit's
retry should reach THOR. 🔶 *Inferred:* the unit retries; its `0x2C`
retries field reads 3.
**Call up and hang up are the same for both series.** Underneath, the
Series-3 adapter keeps today's connect-per-request behaviour until the bench
test under *Testing*; the user sees the same actions either way.
### Series-4 write path
**Encoder.** Extend `micromate/framing.py`:
- a request builder that carries a data section
- the same escape set `{02,03,04,10}`, applied to data, params and checksum
- plain SUM8 of the destuffed payload (*not* Series 3's write format)
Rules: `micromate_protocol_reference.md` → *The escape set — exactly four bytes*,
*Checksum — plain SUM8 of the de-stuffed payload*, *Write-frame destuffing*.
**Dry run.** Every Series-4 write accepts `dry_run=true`. It returns the exact
frames it would send and sends nothing. The first live send of each write is
reviewed this way first.
**Per operation:**
| operation | frames | verify | open questions it settles |
|---|---|---|---|
| start / stop | `0x96` / `0x97`, offset `0xFFFF`, zero params | `0x49` | the ack when already in that state |
| call-home enable/disable | read `0x2C` → `0x7E` (126 B content, offset `0x007E`) → `0x7F` | re-read `0x2C` | none new; bit 0 of `write[5]` |
| setup push | read `0x08`, `0x2E`, `0x1A` → `0xDA` (name) → `0x68`/`0x73` → `0x82`/`0x83` → `0x71`/`0x72` | `get_setup()` | the offset rule; whether `0x68`/`0x82` are needed |
**Setup push, details:**
- Read-modify-write of **all three** blocks, as THOR appears to do.
🔶 *Inferred from two captures:* `0x68` = the preferences content with
`[0:3]` zeroed; `0x82` = the `0x2E` content with `[0:3]` and the CRC slot
zeroed; `0x71` = the `0x1A` content `[0:2090]` with the length echo zeroed.
- Offsets come from THOR's observed constants. 🔶 The hypothesis "offset =
the read block's length + 2" fits all four, but each has been seen at one
size only.
- The edited fields come from `MicromateSetup` and are written back at the
offsets `setup_block.py` already uses. Only fields graded **measured** may
be edited.
- Sequence: stop monitoring (if running) → push → restart (if it was running)
→ verify. THOR's "must be idle" is policy, not the device, but stopping
first removes a variable from the first live write.
- ⚠ **Edit-buffer hazard.** `0x1A` reads the keypad's unsaved edits, so a
read-modify-write taken while someone is in the menu would commit them.
This can't be detected from the wire; it is documented in the endpoint and
audited.
- **Target file:** the active setup, overwritten in place, by default. A
named target is allowed, but overwriting a *non-active* setup or
`factory.MMB` is untested, so it is refused in this phase.
---
## Testing
**Offline (CI-capable):**
- **Frame reproduction.** The new encoder must reproduce THOR's captured write
frames byte for byte: `0x96`/`0x97`, `0x7E`/`0x7F`, and the full setup push,
from the 9-24 / 9-25 / 10-14 captures. This is the same method that proved
the reads (218/218). The needed frames are copied into force-added fixtures,
since `bridges/captures/` is gitignored.
- **Safety layer on fakes:**
- series by prefix
- identity mismatch → 409, nothing sent
- `0xA2` refused
- lock → 423
- read-back mismatch → failed change
- audit row written for every change attempt
- RADIO RING → session ends
- **Endpoints** through FastAPI's `TestClient` against the scripted transport
already used in `tests/test_micromate_client.py`.
- **Contract tests.** The same test, run against both adapters with fakes,
asserts that each job returns the same model with the same field names and
units. A field present for one series and absent for the other is a test
failure unless it lives under `detail`. This is the test that keeps the
guiding principle true as the code grows.
**Bench (UM20147, with Brian):** each write's first live send follows the same
protocol:
1. Dry run.
2. Review the frames.
3. Send once, with a capture running.
4. Read back.
5. Write the result into the reference.
Order: stop/start → call-home off/on → setup push of one field → setup push of
several fields.
**Series-3 session test (before Series-3 sessions are built):** hold a call-up
session open to a MiniMate that is monitoring, for several minutes. Record:
- does it keep monitoring (does an event still record)?
- after hangup, is it monitoring?
- does it behave differently on an RV55 with the DCD issue?
---
## Build phases
Each safety piece arrives with its first real use, so nothing sits untested.
1. **One contract, reads only.** `device_access.py`, the two adapters, the
shared models, series selection, the per-unit lock, the error mapping, and
sessions with ring safety. Rows 1–5 for **both** series through the same
endpoints. **No writes.** Split into three plans:
- 1a. The foundation plus identify / status / settings for both series.
- 1b. Event list and download for both series (rows 4–5). Decided with
Brian 2026-10-21:
- **MiniMate events are listed from their headers** (`0A` + `1E` arm +
`0C` + `1F` browse, no `5A`) instead of downloading every event to list
it, and one event downloads without the ones before it. It reuses the
bypass `skip_waveform_for_events` already takes, so no new command
reaches the wire. The legacy serial-less `/device/events` keeps its
full-download walk. 🔶 Unproven on a unit: **a MiniMate bench check is
owed before this branch merges.** Its scope (final review,
2026-10-21):
- a list of three or more events, confirming `1F(browse)` advances
after a `1E(arm)` without `1F(arm)`;
- a non-first event;
- a histogram-mode event, capturing its `0C` (which would let Series
3's `record_type`, `null` today, be decoded);
- an event past 64 KB, expecting the named 502;
- a stale-id download, confirming no `5A` goes out;
- a download of an event Blastware's call-home already delivered (one
waveform, one histogram), expecting `already_stored`. This is the
only way to measure that Series 3's (serial, timestamp) agrees
between the unit's `0C` and the watcher's import; if it does not,
a download silently stores a duplicate row (never a downgrade).
Measured for Series 4: 1,016/1,016 watcher imports found by the
lookup (2026-10-21).
- a dropped reply, via `bridges/mm_link.py`-style fault injection.
- **Download = fetch, check, store** in SFM's database, the same as
Series 3's `blastware_file` route, and returns the stored row's id. The
file and waveform are then served by the existing `/db/events/{id}/…`
routes. The database matches on (serial, timestamp), so storing an
event already stored, including one THOR's watcher forwarded, ~~refreshes
the row instead of duplicating it~~. **Changed by the final review
(2026-10-21):** it returns the existing row and writes nothing
(`inserted: false`, `detail.already_stored: true`). Never merge: the
watcher's copy, with its paired report, is the richer one, and a
refresh measurably downgraded it (PVS, project strings and ZC
frequencies went NULL).
- **`event_id` = `<serial>:<key>:<YYYYmmddHHMMSS>`.** Both series reuse
keys (after an erase, and across Micromates), so a download whose key
now holds a different event fails with 409 instead of fetching it.
- **Micromate downloads walk to the event first** (the only order captured
from THOR), with THOR's 1,024-byte chunks.
- 1c. **The webapp:** serial + address, and the same read panels for both
series.
- ~~**HARD PREREQUISITE:** before any poller or webapp sends `serial`, add a
per-address cool-down after a RADIO RING~~ -- **changed 2026-10-23
(Brian): test first, build only if needed.** Before any poller or webapp
sends `serial`, run the ring-path bench test under *Open questions this
design leaves for the bench*. If Run B shows a poller keeps the call
from reaching THOR, add the per-address cool-down: call-ups to that
address answer 503 + `Retry-After` until it expires, and
`POST /device/hangup` clears it, with its length taken from Run A. If
THOR gets the call anyway, no cool-down is needed.
2. **Encoder + opcode guard + dry run + frame-reproduction tests.** Still
nothing sent.
(2026-10-22) "Dry run" in this phase means the **write plan**: the exact
frames, in order, with their expected acks, built from the unit's own reads
(`micromate.writes`), plus a bench tool that prints one from a live unit's
reads (`bridges/mm_dry_run.py`). Each write endpoint's `dry_run=true`
arrives with that write in phases 3-5 and returns the plan. The opcode
guard is a **send-side gate** in `MicromateProtocol._send`: every write SUB
is refused unless the connection was built with it allowed (none is, in
this phase), and `0xA2` is refused always.
3. **Start/stop monitoring** (row 7): the first live write, at the bench.
Brings the identity check, the audit table and the read-back framework.
- **Preconditions from the phase-2 final review (2026-10-22):**
- **Write permission is scoped to one call, not a connection.**
`MicromateProtocol.execute(plan)` is the only write path: it transmits
exactly that plan's frames and nothing else. The connection's own
`allowed_writes` stays empty -- a held `Series4Session` lives for
minutes, and a grant made at call-up would outlive the request.
- **A code-reviewed ceiling** in `micromate/opcodes.py` lists the write
SUBs any code may transmit: `{0x96, 0x97}` in this phase, each later
phase adding its own. Delete (`0xA8`/`0xAA`), raw file writes
(`0x8D`/`0x8E` -- they could reach the modem settings) and `0xA2` are
enabled only by a spec change.
- **A write is never retried.** `DeviceAccess._dispatch`'s retry-once
refuses change-tier operations structurally, not by comment.
- **Build the plan inside the unit lock, on the same line, right before
sending.** A plan returned by an earlier dry run is never transmitted;
optionally the dry run returns a digest the live call must echo.
- **Read state first** (`0x49` for start/stop, `0x2C` for call-home) and
decide on purpose whether "already in that state" is skipped or is the
experiment.
- **Refuse writes unless this connection's responses carried Micromate
flags** (0xC5/0x03), alongside the serial identity check.
4. **Call-home enable/disable** (row 9).
5. **Setup push** (row 10): one field first, then several.
Each phase is its own implementation plan. **All phases land on
`feat/series4-sfm-parity` and merge to `dev` once, when everything here is
implemented** (Brian, 2026-10-21) — not one merge per phase.
---
## Out of scope (this phase)
- Series-4 emergency tools: runaway stops, rescue, per-event delete, erase.
(Erase-all is also unmapped.)
- Async jobs; auth (Terra-View as jump host); the call-home receiver. These
are shared features for later.
- Scheduler read/write/enable; clock set; remote sensor check; restart;
firmware.
- Series-3 sessions, pending the bench test.
- Mapping the rest of `0x2C` (the THOR round).
## Fix list (found 2026-10-19, separate small changes)
- `bridges/ach_server.py:524`: `seen_keys` is undefined. Series-3 call-home
monitor-log collection has failed every session since `9afa348`
(2026-05-07).
- `bridges/mm_ach_server.py:262`: `_cstring`/`_content` aren't imported, so
the ring-answer path would raise `NameError`. From `8f67608` (2026-10-14).
- Series-3 `5A` 64 KB page-boundary bug (known; surfaces as HTTP 500).
- `POST /device/config` writes a fixed 29-byte `0x82` blob from one 3-11-26
capture, whatever the unit's trigger settings.
- `/device/events` runs a full 5A download per event just to list headers.
- `0x08` is named `read_event_index` in `micromate/`; it is the preferences
block.
## Left open by the phase 1a review (2026-10-21)
Minor findings from the whole-branch review, parked here so they outlive the
plan's scratch ledger. None blocks 1a; the phase each one matters to is named.
- **CORS ordering (1c, if a browser calls SFM directly).** The `/device` guard
middleware is registered after CORS, so it sits outside it: its 409/501
responses carry no `access-control-allow-origin`, and an OPTIONS preflight to
a guarded URL gets the guard's refusal instead of CORS's 200. Register CORS
last, or let OPTIONS through. Terra-View proxies server-side and is not
affected.
- **Legacy handlers take no unit lock (1c / phase 3).** The guard checks for a
held line and then lets the legacy handler run unlocked; a legacy request
admitted just before a Series-4 call-up at the same address can overlap it.
- **Address keys are not normalised.** `tcp:<host>:<port>` is the raw string:
a hostname vs an IP, or `/dev/serial/by-id/...` vs `/dev/ttyACM0`, gets two
locks for one link.
- **A serial-less request to an UNHELD Micromate still runs Series-3 bytes.**
The guard only knows about lines SFM holds. ~~This is the phase-2 opcode
guard's job.~~
**Measured by the phase-2 final review (2026-10-22):** the phase-2 gate
covers `micromate/` only and cannot see this traffic. Only the three blind
stop tools (`/device/stop_monitoring_blind`, `_slow_drip`, `_spam`) send a
write before any parsed reply. Every other legacy write route needs a
parsed `0xA4` POLL reply, and `S3FrameParser` never yields one from
Micromate bytes (364 real responses → 29 spurious frames, none `0xA4`). So
erase, config and call-home writes cannot reach a Micromate. Worst case
(inferred): an unheld Micromate at the address stops monitoring, via the
Series-3 `0x97` at offset 0x0000, never sent to one. The hazard is identity
(a moved modem or a stale IP), not series. **Brian's decision** (the legacy
routes are bound by 'behave exactly as today'): accept until the legacy path
retires after 1c, then require `serial` on the blind tools; or, as an
interim, refuse a blind tool when SFM's DB last saw a `UM` serial at that
host.
- **`tcp_port` coercion mismatch.** The guard parses with `int()`, pydantic
coerces more loosely (`"9034.0"`), so such a request passes the guard
unchecked. Parse with pydantic's own int coercion, or fail closed.
- **Test gaps.** The middleware wrapper itself is untested (a raw ASGI call
works without httpx); the contract test compares field names of one shared
dataclass, which cannot fail, and does not enforce "a field absent for one
series lives under `detail`".
- **`_ensure_reaper` race.** Two first Series-4 requests at once can start two
reaper threads; harmless because `try_hold` keeps them off each other's units.
- **Held serial lines share `/dev/ttyACM0` silently.** pyserial's open is not
exclusive, so a bench script beside a held line interleaves bytes with the
keep-alive; it looks like a dead unit. Open with `exclusive=True`, or don't
hold serial links.
## Left open by the phase 1b review (2026-10-21)
Parked from the whole-branch review of 1b; none blocks it. The phase each
matters to is named.
- **Retry re-runs a whole download (1c).** The retry-once on a held-line timeout re-runs the full download, roughly doubling time-to-error; narrow it to failures before the first reply.
- **`last_used` after a kept-line error (1c).** It is not refreshed when an op's verdict (404/409) keeps the line, so the idle hang-up comes early.
- **`verified: null` is ambiguous (1c).** It means both "a histogram" (no check exists) and "a waveform whose check could not run".
- **Mic naming and the Series-4 mic decode (1c).** `detail.mic_psi` on Series 3, `detail.mic` on Series 4; Series 4's `0x0C` mic decodes as a denormal (~5e-39) — fix the decode before 1c shows it.
- **500 detail leaks paths (1c, before SFM is reachable beyond Terra-View).** The download handler's 500 detail includes raw exception text, filesystem paths included.
- **Serial as a directory name (1c).** The serial is never checked against `[A-Z0-9]+` before it names a store directory; only the unit can choose it, but the check is cheap.
- **No server-level RADIO RING mid-download test (1c).** Covered structurally (DeviceAccess-level test + the ring transport), not through the handler.
- **Series-3 stored `record_type` (MiniMate bench check).** Rows SFM stores for Series 3 still say "Waveform" for histograms — pre-existing, the same as the legacy `blastware_file` route; fix it with the `0C` decode.
- **A fresh Series-4 download's gaps (1c).** No `sample_rate` is stored, and the sidecar has no vector sum; the DB row has the unit's PVS (overlaid from `0x0C`).
- **Orphan files (SDM).** An event file in the store with no DB row is still overwritten by a download.
- **Same-second collisions (SDM).** Two events of one unit in the same second collide on (serial, timestamp) — a DB-wide dedup property, not 1b's.
- **423 without `Retry-After` (1c).** Add `Retry-After` to the 423 a request gets while a download holds the unit.
- **A lost `0C` during a Series-3 list (1c).** The strict walk raises on a lost `0A`
or `1F`, but a lost `0C` still lists the event with no timestamp and an
`event_id` ending `:-`. Downloading that id skips the stale check and runs the
full `5A`. If the `0C` is lost again it is refused (no timestamp, no filename);
if it reads, whatever event now sits at that key is stored with no stale check:
self-consistent data, but possibly not the event that was listed. Fix: raise on a lost `0C` in strict mode, or
refuse `:-` ids for Series 3.
- **A lost reply on a Series-3 TCP walk re-runs it once (1c)** under the adapter's
cold-boot retry before the 504, doubling time-to-error on a bad link.
- **A Series-3 download of an already-stored event still runs the full `5A`**
before the database lookup finds it (the lookup is on the SDM side, after the
device layer). Wasted transfer, not bad data (1c).
## Left open by the phase 2 review (2026-10-22)
- **`plan_setup_push` takes any name (phase 5).** It is not tied to the `0x41`
read, and it does not refuse `factory.MMB` or a non-active target, which the
spec requires; the name's case varies (`test2.MMB` vs `test2.mmb`).
- **Stripped-name caveat.** `get_active_setup()` strips whitespace, so a name
with leading or trailing spaces does not round-trip.
- **Bench questions.** Whether a Micromate honours offset 0x0000 on
`0x96`/`0x97`, accepts a no-op call-home write, or accepts 0x00 at `[5]`.
Settle all three at the bench.
- **Phase-5 lead (inferred).** Comparing `0x1A` against the active `.MMB` read
through `0x94`/`0x48` may detect unsaved keypad edits, which would undercut
"can't be detected from the wire". One bench check.
## Table 2: to be added later (both series)
| area | item |
|---|---|
| infrastructure | async jobs; auth via Terra-View |
| THOR has it, SFM doesn't | clock set; remote sensor check; scheduler; one setup to many units; restart |
| call-home receiver | hold lines open (S4); "already downloaded" tracking; rules by serial prefix (copy events, monitor log, delete, set clock); detect "Monitor While Calling Home" blocking deletes (⚠ one unexplained 21 → 5 count drop in THOR's log); hand off to `/db/import/*` instead of the watchers |
| settings, the no-PC-files way | intended settings per deployment; drift report (intended vs actual); push then verify |
| notifications | email/SMS by event type and PPV (THOR does it; may belong in Terra-View) |
| emergency tools for S4 | if a Micromate ever needs them |
## Parking lot
**Monitor logs.** Its own piece of work, data side as much as device side.
A unit calls in at least once or twice a day. With no events (e.g. waveform
mode, no blast that day) it still delivers a **monitor log**: "monitoring from
X to Y". The watchers (one for BW-ACH / Series 3, one for THOR-ACH / Series 4)
use the newest file per unit, event or `.MLG`, as SFM's "last heard from" age.
They forward waveform and histogram files but **not** monitor logs. To decide:
- Ingest call-in monitor logs into SFM. SFM's DB **already has** a
`monitor_log` table (one row per interval, deduped by serial + start time),
and `minimateplus/blastware_file.py` already parses Series-3 `.MLG`.
Missing: anything that takes `.MLG` in from the watchers, and knowledge of
THOR's Series-4 monitor-log file format.
- A live monitor-log read over a connection (Series 4: `0x0A` exists, no
wrapper or decoder; Series 3 in SFM: none).
- What it is for: proof of coverage ("was it monitoring when they blasted?")
and visible gaps.
- Related fix-list item: `ach_server.py`'s `seen_keys`.
**How SFM handles setup files and schedules.** This phase only reads and
pushes the unit's *active* setup, with no PC-side library (the `.mmb`
same-name/different-contents gotcha). Still to decide, as one question because
the two are coupled:
- The unit stores up to 25 named `.MMB` files. Should SFM manage them (list,
select, rename, delete, push to a named file), or only ever touch the active
one?
- **Schedules name setup files.** A schedule entry switches the unit to a
setup by name, so a schedule is only as reliable as the files it points to.
What if it points to a file that isn't there? That is untested.
- How "intended settings per deployment" (Table 2) fits with files and
schedules.
- Scheduler read/write is mostly mapped (file transfer + `0x47`); **disable has
never been captured**.
**A modem-side agent on the RX55.** AirLink
OS on the RX55 has "Container Applications (Early Adopter)", and Brian already
runs `slmm-proxy` there. A small program owning the unit's serial port could:
- let THOR and SFM share the line
- dial out to SFM, avoiding the IP whitelist
- handle `RADIO RING` locally
- **Brian's hunch:** make RX55s work with Series 3 by driving DTR/DCD itself
Open questions:
- Can a container open the RS-232 port?
- Can it set the control lines?
- How is it deployed to a fleet, and does it Autostart?
- Will a firmware update keep the beta feature?
## Open questions this design leaves for the bench
- **Ring path and retries: does a Micromate's call-home reach THOR when SFM
holds its line?** (Test designed 2026-10-23; decides whether 1c needs a
cool-down.)
- *Already measured (10-14):* with THOR holding the line, the ring arrived on
THOR's own outbound connection (`TcpClientSystemNet ... RADIO RING IS
RECEIVED FROM IP:...:9034`), so the modem did not divert it to the
destination. Unmeasured: the same with SFM as the holder, and what the
unit does after the holder releases.
- *Known from the firmware strings:* "three attempts and it's over".
🔶 Inferred: 60 s between attempts (`0x2C` content `[120:122]` = `00 3c`,
Series III's "time between retries" offset), and about 21 s of ringing per
attempt (10-14 capture).
- *Setup:* a bench Micromate on a modem whose destination is the office
THOR-ACH server, and a unit THOR is not otherwise watching. SFM runs on a
test port with a scratch DB. Keep THOR's ACH log open.
- **Run A, one call-up:** SFM calls the unit up and holds the line (any
serial-named read). Trigger a call-home on the unit. Record:
- whether SFM logs the RADIO RING and hangs up, with the time;
- whether and when THOR starts a session (its ACH log);
- the number and spacing of rings and attempts.
- **Run B, a poller:** as A, but a script requests the unit's status every
~10 s throughout. If THOR still gets the call, no cool-down is needed; if
the poller keeps the call from reaching THOR, build it, sized from Run A.
- *Also settles:* whether the modem routes a call-home to its destination
on its own, in which case SFM never sees a ring and THOR gets the call
while SFM is still connected.
- The ack for start/stop when the unit is already in that state.
- The offset rule, and whether `0x68`/`0x82` are required, for the setup push.
- Whether the device ever refuses a write while monitoring. Only THOR's policy
has been seen.
- How a failed write is signalled. It has never been observed.
- MiniMate behaviour with a held session (above).