fix(sfm): a change that fails after the send says so; the audit row records sent + states; S3 unknown states refused

Final fix wave for phase 3 (start/stop monitoring), per the whole-phase review.

- I1 + M2: every failure after the send has started is a ChangeUnconfirmed
  (audit_id, sent = "acknowledged" | "unknown", the cause's HTTP status) whose
  message says the frame was sent and names the audit record -- the ring in
  place of the ack, the four lost-ack follow-ups, and the three read-back
  paths.  Series4Session releases the line on it.  Every audit finish goes
  through one helper; a finish that fails is AuditIncomplete (500) and still
  says what happened to the unit.  The line is kept.
- I2: device_commands gains `sent` (1 acknowledged, 0 nothing sent, NULL
  unknown) and `states` (before / seen / after), with an idempotent ADD COLUMN
  in _migrate for a table created earlier on this branch.
- M1: a RADIO RING already buffered is caught before 0x96/0x97 goes out
  (pre_send = read_unsolicited, one 10 ms transport read).  That is a
  CallHomeInProgress with sent=0, not ChangeUnconfirmed.
- M3: Series 3 reads the raw 0x1C flag (new MonitorStatus.state_flag); a byte
  other than 0x00/0x10, or a short section, is unknown(...) and refused.
- M8: even_if_already on a unit already in the state notes that the read-back
  proves nothing.
- M10: a scan pins `.protocol.execute(` to sfm/device_access/s4.py; both
  scans fail closed on a file that does not parse.
- M11: docs corrected (CLAUDE.md phase-2 sentence, phase-3 bullet, REST list;
  micromate/protocol.py scope and the 0x49 read_state docstring; s4.py; route
  docstrings).  "No command has ever been originated" is NOT retracted.
- M12: GET /db/device_commands normalises the serial.
- Minors: unused imports, S3 dry-run frames and 120 s timeout pinned, test
  rename, serial-cache and short-0x49 tests, _RUN_STATES comment.

Schema: two NULLable columns on the branch-new device_commands table, added
by _migrate on open; no backfill.  No codec change, TOOL_VERSION unchanged.

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-23 19:16:45 -04:00
1 parent ac33c8ffa4
commit 8f68b09f5e
18 files changed
+806 -107

No files matched your search

+28 -6
View File
@@ -143,7 +143,9 @@ CREATE TABLE IF NOT EXISTS device_commands (
verified TEXT, -- "ok" | "mismatch" | "not_checked"
outcome TEXT NOT NULL, -- "pending" | "sent" | "skipped" | "failed"
error TEXT,
caller TEXT -- "webapp" | "terra-view" | "script" | ...
caller TEXT, -- "webapp" | "terra-view" | "script" | ...
sent INTEGER, -- did a frame go out: 1 acknowledged, 0 nothing sent, NULL unknown
states TEXT -- JSON: {"before": ..., "seen": [...], "after": ...}
);
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
"""
@@ -302,6 +304,17 @@ class SeismoDb:
log.info("_migrate: device_family backfill complete (remaining NULL=%d)",
remaining)
# Migration 1d: device_commands gained `sent` and `states` after the
# table first shipped on feat/series4-sfm-parity. NULLable, so rows
# written before read NULL (= unknown).
existing_cols = {
r[1] for r in conn.execute("PRAGMA table_info(device_commands)").fetchall()
}
for col, ddl in (("sent", "INTEGER"), ("states", "TEXT")):
if col not in existing_cols:
log.info("_migrate: device_commands ADD COLUMN %s %s", col, ddl)
conn.execute(f"ALTER TABLE device_commands ADD COLUMN {col} {ddl}")
# Migration 2: change monitor_log UNIQUE from (serial, waveform_key) to
# (serial, start_time) — same reasoning as events.
row = conn.execute(
@@ -429,16 +442,25 @@ class SeismoDb:
verified: Optional[str],
ack: Optional[dict],
error: Optional[str],
sent: Optional[int] = None,
states: Optional[dict] = None,
) -> None:
"""Record the result of a command begun with begin_device_command()."""
"""Record the result of a command begun with begin_device_command().
`sent`: 1 a frame went out and was acknowledged, 0 nothing was sent,
None unknown (the ack was lost). `states`: what was read from the unit,
``{"before": ..., "seen": [...], "after": ...}``.
"""
ts = datetime.datetime.now(datetime.timezone.utc).isoformat()
with self._connect() as conn:
cur = conn.execute(
"UPDATE device_commands SET finished_ts=?, outcome=?, verified=?, "
"ack=?, error=? WHERE id=? AND outcome='pending'",
"ack=?, error=?, sent=?, states=? WHERE id=? AND outcome='pending'",
(ts, outcome, verified,
json.dumps(ack) if ack is not None else None,
error, command_id),
error, sent,
json.dumps(states) if states is not None else None,
command_id),
)
if cur.rowcount == 0:
known = conn.execute(
@@ -453,7 +475,7 @@ class SeismoDb:
serial: Optional[str] = None,
limit: int = 100,
) -> list[dict]:
"""Return audit rows, newest first, with request/ack parsed from JSON."""
"""Return audit rows, newest first, with request/ack/states parsed from JSON."""
with self._connect() as conn:
if serial:
rows = conn.execute(
@@ -466,7 +488,7 @@ class SeismoDb:
out = []
for r in rows:
d = dict(r)
for k in ("request", "ack"):
for k in ("request", "ack", "states"):
if d[k] is not None:
d[k] = json.loads(d[k])
out.append(d)