Files
seismo-relay/tests/test_micromate_execute.py
T
serversdownandClaude Opus 5.5 8f68b09f5e 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
2026-10-23 19:16:45 -04:00

286 lines
9.6 KiB
Python

"""execute(plan): the only write path -- exact frames, one call's permission, a ceiling."""
from __future__ import annotations
import os
import ast
import pathlib
import subprocess
import sys
from types import SimpleNamespace
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from micromate.framing import FLAGS_THOR, build_request # noqa: E402
from micromate.opcodes import ENABLEABLE_WRITES, OpcodeRefused # noqa: E402
from micromate.protocol import ACK_DATA_LEN, TimeoutError as MmTimeout, UnexpectedResponse # noqa: E402
from micromate.writes import ( # noqa: E402
WritePlan, WriteStep, plan_call_home_enabled, plan_start_monitoring,
plan_stop_monitoring,
)
from test_micromate_protocol import frame, proto # noqa: E402
ACK_START = frame(0x69, bytes(ACK_DATA_LEN))
POLL_RSP = frame(0xA4, bytes(48))
def _ready(responses):
"""A protocol that has already seen one Micromate-flagged reply (a POLL)."""
p, t = proto([POLL_RSP] + responses)
p.poll()
t.written.clear()
return p, t
def test_the_ceiling_is_start_and_stop_only():
assert ENABLEABLE_WRITES == frozenset({0x96, 0x97})
def test_execute_sends_exactly_the_plans_frame_and_returns_the_ack():
p, t = _ready([ACK_START])
acks = p.execute(plan_start_monitoring())
assert t.written == [build_request(0x96, 0xFFFF)]
assert [a.sub for a in acks] == [0x69]
def test_permission_ends_with_the_call():
p, t = _ready([ACK_START])
p.execute(plan_start_monitoring())
with pytest.raises(OpcodeRefused):
p._send(build_request(0x96, 0xFFFF))
assert len(t.written) == 1
def test_a_plan_beyond_the_ceiling_is_refused_and_nothing_is_sent():
content = bytes(5) + b"\x05" + bytes(120)
p, t = _ready([])
with pytest.raises(OpcodeRefused, match="ceiling"):
p.execute(plan_call_home_enabled(content, False))
assert t.written == []
def test_execute_refuses_before_any_micromate_reply_has_been_seen():
p, t = proto([ACK_START])
with pytest.raises(OpcodeRefused, match="Micromate"):
p.execute(plan_start_monitoring())
assert t.written == []
def test_execute_refuses_after_a_non_micromate_flags_reply():
p, t = proto([frame(0xA4, bytes(48), flags=0x10), ACK_START])
p.poll()
t.written.clear()
with pytest.raises(OpcodeRefused):
p.execute(plan_stop_monitoring())
assert t.written == []
def test_a_wrong_ack_sub_raises_after_one_send():
p, t = _ready([frame(0x68, bytes(ACK_DATA_LEN))]) # stop's ack, for a start
with pytest.raises(UnexpectedResponse):
p.execute(plan_start_monitoring())
assert len(t.written) == 1
def test_thor_flags_are_accepted_too():
p, t = proto([frame(0xA4, bytes(48), flags=FLAGS_THOR), frame(0x68, bytes(ACK_DATA_LEN))])
p.poll()
p.execute(plan_stop_monitoring())
assert t.written[-1] == build_request(0x97, 0xFFFF)
# -- fix round 1: the ceiling is enforced where frames leave --------------------
def test_a_permit_beyond_the_ceiling_cannot_send():
p, t = _ready([])
with pytest.raises(OpcodeRefused):
p._send(build_request(0x8E, 0), permit=frozenset({0x8E}))
assert t.written == []
def test_a_duck_typed_plan_is_refused():
p, t = _ready([])
fake = SimpleNamespace(subs=frozenset({0x96}), steps=(WriteStep(0x7E, 0),))
with pytest.raises(TypeError):
p.execute(fake)
assert t.written == []
def test_a_forged_step_in_a_real_plan_is_refused_at_the_step():
p, t = _ready([])
plan = plan_start_monitoring()
object.__setattr__(plan, "steps", (WriteStep(0x7E, 0),)) # subs now reads 0x7E too
with pytest.raises(OpcodeRefused):
p.execute(plan)
assert t.written == []
def test_a_forged_step_hidden_behind_a_good_plan_is_refused():
class Lying(WritePlan):
@property
def subs(self):
return frozenset({0x96})
plan = Lying("x", (WriteStep(0x96, 0xFFFF), WriteStep(0x7E, 0)))
p, t = _ready([ACK_START])
with pytest.raises(OpcodeRefused):
p.execute(plan)
assert t.written == []
# -- a lost ack is never retried, inside the real execute ------------------------
def test_a_lost_ack_raises_after_exactly_one_send():
p, t = _ready([])
with pytest.raises(MmTimeout):
p.execute(plan_start_monitoring())
assert len(t.written) == 1
def test_a_lost_first_ack_stops_a_two_step_plan():
plan = WritePlan("start then stop",
(WriteStep(0x96, 0xFFFF), WriteStep(0x97, 0xFFFF)))
p, t = _ready([])
with pytest.raises(MmTimeout):
p.execute(plan)
assert t.written == [build_request(0x96, 0xFFFF)]
def test_trust_is_the_most_recent_request_not_an_earlier_one():
p, t = _ready([])
with pytest.raises(MmTimeout):
p.poll() # sent, never answered
t.written.clear()
with pytest.raises(OpcodeRefused):
p.execute(plan_start_monitoring())
assert t.written == []
def test_execute_works_right_after_a_valid_read():
p, t = _ready([ACK_START])
p.execute(plan_start_monitoring())
assert len(t.written) == 1
def test_a_successful_two_step_plan_sends_both_in_order():
plan = WritePlan("start then stop",
(WriteStep(0x96, 0xFFFF), WriteStep(0x97, 0xFFFF)))
p, t = _ready([ACK_START, frame(0x68, bytes(ACK_DATA_LEN))])
acks = p.execute(plan)
assert t.written == [build_request(0x96, 0xFFFF), build_request(0x97, 0xFFFF)]
assert [a.sub for a in acks] == [0x69, 0x68]
def test_an_in_ceiling_frame_sub_mismatch_is_refused():
class Liar(WriteStep):
@property
def frame(self):
return build_request(0x97, 0xFFFF)
p, t = _ready([ACK_START])
plan = WritePlan("x", (Liar(0x96, 0xFFFF),))
with pytest.raises(OpcodeRefused):
p.execute(plan)
assert t.written == []
@pytest.mark.parametrize("bad", [
frame(0x99, bytes(48)), # Micromate flags, wrong SUB
frame(0xA4, bytes(48))[:-2] + b"\x00\x03", # Micromate flags, bad checksum
])
def test_a_flagged_reply_that_fails_validation_leaves_no_trust(bad):
p, t = _ready([bad])
with pytest.raises(Exception):
p.poll()
assert p.last_flags is None
t.written.clear()
with pytest.raises(OpcodeRefused):
p.execute(plan_start_monitoring())
assert t.written == []
# -- nothing outside protocol.py reaches the wire with permission -----------------
def scan_source(src: str, name: str = "<s>") -> list[str]:
"""Hits: a `permit=` keyword, `**kw` into _send/_request, any `._request` call."""
hits = []
for node in ast.walk(ast.parse(src)):
if not isinstance(node, ast.Call):
continue
fn = node.func
fname = fn.attr if isinstance(fn, ast.Attribute) else getattr(fn, "id", "")
if any(k.arg == "permit" for k in node.keywords):
hits.append(f"{name}:{node.lineno} permit=")
if fname in ("_send", "_request") and any(k.arg is None for k in node.keywords):
hits.append(f"{name}:{node.lineno} **kwargs into {fname}")
if isinstance(fn, ast.Attribute) and fn.attr == "_request":
hits.append(f"{name}:{node.lineno} ._request call")
return hits
@pytest.mark.parametrize("src", [
"p._send(build_request(0x96, 0xFFFF), permit=frozenset({0x96}))",
"p._send(frame, **kw)",
"p._request(frame, 0x69, permit=x)",
"p._request(frame, 0x69)",
])
def test_the_scanner_catches_each_shape(src):
assert scan_source(src)
def test_the_scanner_ignores_ordinary_calls():
assert scan_source("p._send(frame)\nf(a, b=1)") == []
def scan_file(scanner, src: str, rel: str) -> list[str]:
"""Fails closed: a file the scanner cannot parse is a hit, not a pass."""
try:
return scanner(src, rel)
except SyntaxError as exc:
return [f"{rel}: does not parse, so it cannot be scanned ({exc})"]
def scan_tracked(scanner, skip) -> list[str]:
root = pathlib.Path(__file__).resolve().parent.parent
files = subprocess.run(["git", "ls-files", "*.py"], cwd=root, capture_output=True,
text=True, check=True).stdout.split()
hits = []
for rel in files:
if rel.startswith("tests/") or skip(rel):
continue
hits += scan_file(scanner, (root / rel).read_text(errors="ignore"), rel)
return hits
def test_a_file_that_does_not_parse_fails_the_scan():
assert scan_file(scan_source, "def broken(:\n", "x.py")
assert scan_file(scan_execute_callers, "def broken(:\n", "x.py")
def test_only_protocol_py_grants_write_permission():
assert scan_tracked(scan_source, lambda rel: rel == "micromate/protocol.py") == []
# -- nothing outside the safety layer calls protocol.execute( -------------------
def scan_execute_callers(src: str, name: str = "<s>") -> list[str]:
"""Hits: any `<x>.protocol.execute(...)` call -- the Series-4 write entry."""
hits = []
for node in ast.walk(ast.parse(src)):
if not isinstance(node, ast.Call):
continue
fn = node.func
if (isinstance(fn, ast.Attribute) and fn.attr == "execute"
and isinstance(fn.value, ast.Attribute) and fn.value.attr == "protocol"):
hits.append(f"{name}:{node.lineno} .protocol.execute call")
return hits
def test_the_execute_scanner_catches_a_protocol_execute_and_not_sqlite():
assert scan_execute_callers("client.protocol.execute(plan)")
assert scan_execute_callers("conn.execute('SELECT 1')") == []
def test_only_the_safety_layer_calls_protocol_execute():
assert scan_tracked(scan_execute_callers,
lambda rel: rel == "sfm/device_access/s4.py") == []