docs(spec): SFM Series-4 parity and a device safety layer -- design for review

Parity of jobs with Series 3 for regular comms and settings (identify,
status, settings, events, download, monitor log, start/stop, call-home
enable/disable, setup push); Series-4 emergency tools deferred.  A single
device-access layer: series from the serial prefix, identity confirmed
before any write, a per-unit lock, an 0xA2 opcode guard, read-back
verification of every change, distinct error codes, and an audit table.
Series-4 sessions ("stay on the line") now; Series-3 sessions after a bench
test of MiniMate hangup/DCD behaviour.

Includes the fix list found in the 2026-10-19 inventory, the to-be-added
table, and the RX55 container idea as a parking-lot item.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-20 17:41:00 -04:00
1 parent 618fcb7770
commit 1c6aa04687
1 file changed
+343
@@ -0,0 +1,343 @@
# 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.
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 |
|---|---|---|
| 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 PC-side setup library** | a name is the only link between Thor's two copies, and nothing checks they match | 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.
| # | 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 | dispatch |
| 5 | Download an event | `/event/{i}`, `/waveform`, `/blastware_file` | implemented: streams the `.IDFW`/`.IDFH` itself, with a decode self-check | save through the existing `/db/import/idf_file` path |
| 6 | Monitor log | only via `ach_server` (broken, see the fix list) | `0x0A` read exists; no wrapper or decoder | client wrapper + partial decode |
| 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)
```
- **Series selection.** `serial` picks the library: `UM` → `micromate`; `BE`
or `BA` → `minimateplus`; any other prefix → 422. With no `serial`, the
request is Series 3, so existing Series-3 callers are unchanged.
**Series-4 requests must include `serial`.**
- **Endpoints.** The same `/device/*` paths, plus a `serial` query parameter.
Responses gain `"series": 3 | 4`. Where the two series genuinely differ (the
setup fields, the event identity), the body is series-specific under a
documented shape rather than forced into Series 3's.
- **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.
### 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 (Series 4)
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.
Series 3 keeps today's connect-per-request behaviour until the bench test
under *Testing*.
### 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`.
**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. **Series-4 reads in SFM.** `device_access.py`, series selection, the
per-unit lock (Series 3 too), the error mapping, and Series-4 sessions with
ring safety. Rows 1–6. **No writes.**
2. **Encoder + opcode guard + dry run + frame-reproduction tests.** Still
nothing sent.
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.
4. **Call-home enable/disable** (row 9).
5. **Setup push** (row 10): one field first, then several.
Each phase is its own implementation plan and its own merge.
---
## 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.
## 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
**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
- 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).