feat(sfm): start/stop monitoring for Series 4 -- identity, state, dry run, audit, read-back, never retried

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 16:29:03 -04:00
1 parent ff0cce1cb2
commit eada7ba767
7 files changed
+326 -13

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@ from .errors import (
translate, translate,
) )
from .models import ( from .models import (
DownloadedEvent, EventDownload, EventList, EventRef, UnitAddress, UnitInfo, ChangeResult, DownloadedEvent, EventDownload, EventList, EventRef, UnitAddress, UnitInfo,
UnitSettings, UnitStatus, UnitSettings, UnitStatus,
) )
from .series import normalise_serial, series_for_serial from .series import normalise_serial, series_for_serial
+35 -6
View File
@@ -12,10 +12,10 @@ from typing import Any, Callable, Dict, Optional
from .errors import ConnectFailed, DeviceError, NoAnswer, WrongUnit from .errors import ConnectFailed, DeviceError, NoAnswer, WrongUnit
from .events import parse_event_id from .events import parse_event_id
from .locks import UnitLocks from .locks import UnitLocks
from .models import DownloadedEvent, EventList, UnitAddress, UnitInfo, UnitSettings, UnitStatus from .models import ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo, UnitSettings, UnitStatus
from .s3 import Series3Adapter, default_s3_client_factory from .s3 import Series3Adapter, default_s3_client_factory
from .s4 import ( from .s4 import (
Series4Session, default_s4_client_factory, s4_download_event, s4_identify, s4_list_events, Series4Session, default_s4_client_factory, s4_change_monitoring, s4_download_event, s4_identify, s4_list_events,
s4_settings, s4_status, s4_settings, s4_status,
) )
from .series import normalise_serial, series_for_serial from .series import normalise_serial, series_for_serial
@@ -34,7 +34,15 @@ class DeviceAccess:
idle_hangup_s: float = 300.0, idle_hangup_s: float = 300.0,
reaper_interval_s: float = 5.0, reaper_interval_s: float = 5.0,
start_reaper: bool = True, start_reaper: bool = True,
audit: Any = None,
sleep: Callable[[float], None] = time.sleep,
verify_timeout_s: float = 60.0,
verify_interval_s: float = 2.0,
) -> None: ) -> None:
self._audit = audit
self._sleep = sleep
self._verify_timeout_s = verify_timeout_s
self._verify_interval_s = verify_interval_s
self._locks = UnitLocks(lock_timeout) self._locks = UnitLocks(lock_timeout)
self._s3 = Series3Adapter(s3_client_factory) self._s3 = Series3Adapter(s3_client_factory)
self._s4_factory = s4_client_factory self._s4_factory = s4_client_factory
@@ -70,6 +78,27 @@ class DeviceAccess:
lambda a, s: self._s3.download_event(a, s, key, stamp), lambda a, s: self._s3.download_event(a, s, key, stamp),
lambda c, s: s4_download_event(c, s, key, stamp)) lambda c, s: s4_download_event(c, s, key, stamp))
def start_monitoring(self, address: UnitAddress, serial: str, *, dry_run: bool = False,
even_if_already: bool = False, caller: str = "api") -> ChangeResult:
return self._change_monitoring(address, serial, start=True, dry_run=dry_run,
even_if_already=even_if_already, caller=caller)
def stop_monitoring(self, address: UnitAddress, serial: str, *, dry_run: bool = False,
even_if_already: bool = False, caller: str = "api") -> ChangeResult:
return self._change_monitoring(address, serial, start=False, dry_run=dry_run,
even_if_already=even_if_already, caller=caller)
def _change_monitoring(self, address, serial, *, start, dry_run, even_if_already, caller):
kw = dict(start=start, dry_run=dry_run, even_if_already=even_if_already,
audit=self._audit, caller=caller, sleep=self._sleep,
verify_timeout_s=self._verify_timeout_s,
verify_interval_s=self._verify_interval_s)
return self._dispatch(
address, serial,
lambda a, s: self._s3.change_monitoring(a, s, **kw),
lambda c, s: s4_change_monitoring(c, s, address=address, **kw),
change=True)
def held_serial(self, address: UnitAddress) -> Optional[str]: def held_serial(self, address: UnitAddress) -> Optional[str]:
"""Serial of the OPEN held Series-4 line at this address, else None. No I/O.""" """Serial of the OPEN held Series-4 line at this address, else None. No I/O."""
with self._sessions_guard: with self._sessions_guard:
@@ -92,7 +121,7 @@ class DeviceAccess:
def _dispatch(self, address: UnitAddress, serial: str, def _dispatch(self, address: UnitAddress, serial: str,
s3_op: Callable[[UnitAddress, str], Any], s3_op: Callable[[UnitAddress, str], Any],
s4_op: Callable[[Any, str], Any]) -> Any: s4_op: Callable[[Any, str], Any], *, change: bool = False) -> Any:
serial = normalise_serial(serial) serial = normalise_serial(serial)
series = series_for_serial(serial) # raises BadRequest before any I/O series = series_for_serial(serial) # raises BadRequest before any I/O
with self._locks.hold(address.key): with self._locks.hold(address.key):
@@ -115,9 +144,9 @@ class DeviceAccess:
# learns at EOF), so the first request on it times out or fails. # learns at EOF), so the first request on it times out or fails.
# Call up fresh and retry ONCE. Safe only because every operation # Call up fresh and retry ONCE. Safe only because every operation
# here is a read (identify, status, settings, list, download -- all # here is a read (identify, status, settings, list, download -- all
# idempotent); writes (phase 3) must NOT # idempotent). A change (`change=True`) is never retried, by
# inherit this -- a write whose ack was lost must never be sent twice. # construction: a write whose ack was lost must never be sent twice.
if was_held and isinstance(exc, (NoAnswer, ConnectFailed)): if was_held and not change and isinstance(exc, (NoAnswer, ConnectFailed)):
self._drop(address.key, session) self._drop(address.key, session)
session.hang_up() session.hang_up()
session = self._session_for(address, serial) session = self._session_for(address, serial)
+19
View File
@@ -132,3 +132,22 @@ class DownloadedEvent:
timestamp: Optional[datetime.datetime] = None timestamp: Optional[datetime.datetime] = None
record: Dict[str, Any] = field(default_factory=dict) record: Dict[str, Any] = field(default_factory=dict)
detail: Dict[str, Any] = field(default_factory=dict) detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class ChangeResult:
"""The outcome of a change request. `outcome`: "dry_run" | "skipped" | "sent" |
"failed". `verified`: "ok" | "mismatch" | "not_checked". `plan` is the exact
frames planned (dry run) or sent."""
serial: str
series: int
action: str
dry_run: bool
sent: bool
outcome: str
verified: str
state_before: Optional[str]
state_after: Optional[str]
audit_id: Optional[str]
plan: Dict[str, Any] = field(default_factory=dict)
detail: Dict[str, Any] = field(default_factory=dict)
+4 -1
View File
@@ -11,7 +11,7 @@ from minimateplus import MiniMateClient
from minimateplus.blastware_file import blastware_filename from minimateplus.blastware_file import blastware_filename
from minimateplus.transport import TcpTransport from minimateplus.transport import TcpTransport
from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, StaleEvent, WrongUnit, translate from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported, StaleEvent, WrongUnit, translate
from .events import iso_of, make_event_id, stamp_of from .events import iso_of, make_event_id, stamp_of
from .models import DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus from .models import DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
@@ -85,6 +85,9 @@ class Series3Adapter:
def __init__(self, client_factory: Callable[..., Any] = default_s3_client_factory) -> None: def __init__(self, client_factory: Callable[..., Any] = default_s3_client_factory) -> None:
self._factory = client_factory self._factory = client_factory
def change_monitoring(self, address: UnitAddress, serial: str, **kw: Any) -> Any:
raise NotSupported("Series 3 start/stop through DeviceAccess arrives in Task 5")
def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None) -> Any: def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None) -> Any:
def attempt() -> Any: def attempt() -> Any:
client = self._factory(address) if timeout is None else self._factory(address, timeout=timeout) client = self._factory(address) if timeout is None else self._factory(address, timeout=timeout)
+90 -2
View File
@@ -12,13 +12,15 @@ from typing import Any, Callable, Optional, TypeVar
from micromate.client import MicromateClient from micromate.client import MicromateClient
from micromate.protocol import THOR_CHUNK_SIZE from micromate.protocol import THOR_CHUNK_SIZE
from micromate.writes import plan_start_monitoring, plan_stop_monitoring
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
from .errors import ( from .errors import (
CallHomeInProgress, DeviceError, EventNotFound, MalformedReply, StaleEvent, WrongUnit, translate, CallHomeInProgress, DeviceError, EventNotFound, MalformedReply, NotSupported, StaleEvent,
WrongUnit, translate,
) )
from .events import iso_of, make_event_id, stamp_of from .events import iso_of, make_event_id, stamp_of
from .models import DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
from .series import normalise_serial from .series import normalise_serial
log = logging.getLogger("sfm.device_access") log = logging.getLogger("sfm.device_access")
@@ -121,6 +123,8 @@ class Series4Session:
so it hangs up too -- conservative, since the link may be fine. Operations so it hangs up too -- conservative, since the link may be fine. Operations
added in later phases must keep to this: never wrap a link failure in a added in later phases must keep to this: never wrap a link failure in a
`DeviceError` inside an op, or the line stays open on a broken link. `DeviceError` inside an op, or the line stays open on a broken link.
The one exception: `CallHomeInProgress` and `WrongUnit` release the line,
because the line itself is the problem.
""" """
def __init__(self, address: UnitAddress, serial: str, def __init__(self, address: UnitAddress, serial: str,
@@ -168,6 +172,14 @@ class Series4Session:
log.warning("RADIO RING from %s -- released the line so the call reaches THOR", log.warning("RADIO RING from %s -- released the line so the call reaches THOR",
self.address.key) self.address.key)
raise CallHomeInProgress(_RING_MESSAGE) from exc raise CallHomeInProgress(_RING_MESSAGE) from exc
except (CallHomeInProgress, WrongUnit) as exc:
# The line itself is the problem: a call-home rides whatever holds the
# modem's single TCP session, and a line held for X that answers as Y
# must not stay held.
self.hang_up()
log.warning("%s at %s -- released the line: %s", type(exc).__name__,
self.address.key, exc)
raise
except DeviceError: except DeviceError:
# The operation's own verdict (event not found, stale id): the line # The operation's own verdict (event not found, stale id): the line
# is healthy, so keep it. Library errors still hang up below. # is healthy, so keep it. Library errors still hang up below.
@@ -306,3 +318,79 @@ def s4_download_event(client: Any, serial: str, key: bytes, stamp: Optional[str]
detail={"size_bytes": ref.size, "pvs_error": err}, detail={"size_bytes": ref.size, "pvs_error": err},
) )
raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again") raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again")
def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool,
even_if_already: bool, audit: Any, address: UnitAddress,
caller: str, sleep: Callable[[float], None],
verify_timeout_s: float, verify_interval_s: float) -> ChangeResult:
"""Identity -> state -> (dry run | skip | audit -> send -> read back -> audit)."""
action = "start monitoring" if start else "stop monitoring"
want = "monitoring" if start else "idle"
reported = normalise_serial(client.serial(refresh=True))
if reported != serial:
raise WrongUnit(f"asked for {serial} but {reported} answered at {address.key} -- "
"nothing sent")
before = client.read_run_state()
if before.name == "calling_home":
raise CallHomeInProgress(_RING_MESSAGE)
plan = plan_start_monitoring() if start else plan_stop_monitoring()
planned = dict(plan.describe(), sends_nothing=dry_run)
base = dict(serial=serial, series=4, action=action, plan=planned,
state_before=before.name)
if dry_run:
return ChangeResult(dry_run=True, sent=False, outcome="dry_run",
verified="not_checked", state_after=None, audit_id=None, **base)
if audit is None:
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
"without one (nothing sent)")
request = {"plan": planned, "even_if_already": even_if_already}
cid = audit.begin(serial=serial, series=4, address=address.key, action=action,
tier="change", request=request, caller=caller)
if before.name == want and not even_if_already:
audit.finish(cid, outcome="skipped", verified="not_checked", ack=None,
error=f"already {want}")
return ChangeResult(dry_run=False, sent=False, outcome="skipped",
verified="not_checked", state_after=before.name,
audit_id=cid, detail={"reason": f"the unit is already {want}"}, **base)
try:
acks = client.protocol.execute(plan)
except Exception as exc: # noqa: BLE001 -- recorded, never retried
after = _try_run_state(client)
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}")
if after is None:
raise # the line is suspect: let _exchange hang up
return ChangeResult(dry_run=False, sent=True, outcome="failed",
verified="not_checked", state_after=after, audit_id=cid,
detail={"error": f"no clean ack: {exc}"}, **base)
ack = {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
seen = [before.name]
polls = int(verify_timeout_s // verify_interval_s)
try:
for _ in range(polls):
sleep(verify_interval_s)
seen.append(client.read_run_state().name)
if seen[-1] == want:
break
except Exception as exc: # noqa: BLE001 -- the row must not stay pending
audit.finish(cid, outcome="failed", verified="not_checked", ack=ack,
error=f"sent, but the read-back failed: {exc}")
raise
ok = seen[-1] == want
audit.finish(cid, outcome="sent" if ok else "failed", verified="ok" if ok else "mismatch",
ack=ack, error=None if ok else f"unit reads {seen[-1]}, expected {want}")
return ChangeResult(dry_run=False, sent=True, outcome="sent" if ok else "failed",
verified="ok" if ok else "mismatch", state_after=seen[-1],
audit_id=cid, detail={"states_seen": seen, "ack": ack}, **base)
def _try_run_state(client: Any) -> Optional[str]:
try:
return client.read_run_state().name
except Exception: # noqa: BLE001
return None
+26 -3
View File
@@ -157,12 +157,24 @@ class _FakeProtocol:
def poll(self): def poll(self):
self._owner._step("poll") self._owner._step("poll")
def execute(self, plan):
self._owner._step("execute")
self._owner.executed.append(plan)
if self._owner.execute_error is not None:
raise self._owner.execute_error
return [type("Ack", (), {"sub": s.ack_sub, "data": bytes(11)})() for s in plan.steps]
class FakeMicromateClient(_Base): class FakeMicromateClient(_Base):
def __init__(self, serial="UM20147", *, monitoring=False, events=5, def __init__(self, serial="UM20147", *, monitoring=False, events=5,
unsolicited=b"", event_refs=None, **kw): unsolicited=b"", event_refs=None, run_states=None,
serial_reported=None, execute_error=None, **kw):
super().__init__(**kw) super().__init__(**kw)
self.serial = serial self.unit_serial = serial # not `serial`: that is the client's method
self.run_states = list(run_states) if run_states else [0x00]
self.serial_reported = serial if serial_reported is None else serial_reported
self.execute_error = execute_error
self.executed = []
self.monitoring = monitoring self.monitoring = monitoring
self.events = events self.events = events
self.unsolicited = unsolicited self.unsolicited = unsolicited
@@ -177,10 +189,21 @@ class FakeMicromateClient(_Base):
def connect(self) -> MicromateDeviceInfo: def connect(self) -> MicromateDeviceInfo:
self._step("connect") self._step("connect")
return MicromateDeviceInfo( return MicromateDeviceInfo(
serial=self.serial, manufacturer="Instantel", model="MM/ISEE/S", serial=self.unit_serial, manufacturer="Instantel", model="MM/ISEE/S",
firmware_line="thor", monitoring=self.monitoring, active_setup="test2.MMB", firmware_line="thor", monitoring=self.monitoring, active_setup="test2.MMB",
) )
def serial(self, *, refresh=False):
self._step("serial")
return self.serial_reported
def read_run_state(self):
from micromate.models import MicromateRunState
self._step("read_run_state")
code = self.run_states.pop(0) if len(self.run_states) > 1 else self.run_states[0]
names = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
return MicromateRunState(code, names.get(code, f"unknown(0x{code:02X})"))
def get_state(self) -> MicromateState: def get_state(self) -> MicromateState:
self._step("get_state") self._step("get_state")
return MicromateState( return MicromateState(
+151
View File
@@ -0,0 +1,151 @@
"""Start/stop through the safety layer: identity, state, dry run, audit, read-back, no retry."""
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 micromate.protocol as mm_proto # noqa: E402
from device_access_fakes import FakeMicromateClient # noqa: E402
from sfm.device_access.access import DeviceAccess # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
CallHomeInProgress, NotSupported, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
class Audit:
def __init__(self):
self.rows = {}
def begin(self, **f):
cid = f"c{len(self.rows) + 1}"
self.rows[cid] = dict(f, outcome="pending")
return cid
def finish(self, cid, **f):
self.rows[cid].update(f)
def access(fake, audit="default"):
return DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False,
audit=Audit() if audit == "default" else audit,
sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0)
def test_a_dry_run_returns_the_exact_frames_and_sends_nothing():
fake = FakeMicromateClient(run_states=[0x00])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147", dry_run=True)
assert (r.dry_run, r.sent, r.outcome, r.state_before) == (True, False, "dry_run", "idle")
assert r.plan["steps"][0]["frame"] == "41021010009600ffff00000000000000000000a403"
assert r.plan["sends_nothing"] is True
assert fake.executed == [] and da._audit.rows == {}
def test_start_sends_once_and_verifies_by_reading_back():
fake = FakeMicromateClient(run_states=[0x00, 0x00, 0x02])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert (r.sent, r.outcome, r.verified, r.state_after) == (True, "sent", "ok", "monitoring")
assert len(fake.executed) == 1
row = da._audit.rows[r.audit_id]
assert (row["outcome"], row["verified"], row["action"]) == ("sent", "ok", "start monitoring")
assert r.detail["states_seen"][-1] == "monitoring"
assert r.plan["sends_nothing"] is False
assert row["request"]["plan"]["sends_nothing"] is False
def test_already_in_state_is_skipped_and_audited_as_skipped():
fake = FakeMicromateClient(run_states=[0x02])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert (r.sent, r.outcome) == (False, "skipped") and fake.executed == []
assert da._audit.rows[r.audit_id]["outcome"] == "skipped"
def test_even_if_already_sends_anyway():
fake = FakeMicromateClient(run_states=[0x02])
r = access(fake).start_monitoring(ADDR, "UM20147", even_if_already=True)
assert r.sent and len(fake.executed) == 1
def test_a_unit_calling_home_is_refused_and_nothing_is_sent():
fake = FakeMicromateClient(run_states=[0x03])
da = access(fake)
with pytest.raises(CallHomeInProgress):
da.stop_monitoring(ADDR, "UM20147")
assert fake.executed == []
assert fake.is_open() is False # the line was released for THOR
assert da.held_serial(ADDR) is None # and the session dropped
def test_a_different_unit_on_the_fresh_serial_read_is_refused_before_writing():
fake = FakeMicromateClient(serial_reported="UM12947")
da = access(fake)
with pytest.raises(WrongUnit):
da.start_monitoring(ADDR, "UM20147")
assert fake.executed == []
assert fake.is_open() is False
assert da.held_serial(ADDR) is None
def test_a_live_change_without_an_audit_sink_is_refused():
fake = FakeMicromateClient()
with pytest.raises(NotSupported, match="audit"):
access(fake, audit=None).start_monitoring(ADDR, "UM20147")
assert fake.executed == []
def test_a_clean_ack_but_no_state_change_is_a_failed_change():
fake = FakeMicromateClient(run_states=[0x00]) # never leaves idle
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert (r.outcome, r.verified, r.state_after) == ("failed", "mismatch", "idle")
assert len(r.detail["states_seen"]) == 4 # 6 s window / 2 s + the first read
assert da._audit.rows[r.audit_id]["verified"] == "mismatch"
def test_a_lost_ack_is_never_retried():
fake = FakeMicromateClient(run_states=[0x00, 0x02],
execute_error=mm_proto.TimeoutError("no ack"))
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert len(fake.executed) == 1
assert (r.outcome, r.state_after) == ("failed", "monitoring")
assert "no ack" in r.detail["error"]
assert da._audit.rows[r.audit_id]["outcome"] == "failed"
def test_a_change_on_a_dropped_held_line_is_not_retried():
fake = FakeMicromateClient(run_states=[0x00])
da = access(fake)
da.status(ADDR, "UM20147") # hold the line
fake.fail = [mm_proto.TimeoutError("peer gone")] # next call fails
with pytest.raises(Exception):
da.start_monitoring(ADDR, "UM20147")
assert fake.executed == [] # never reached the write, never re-tried
def test_a_read_back_that_fails_still_finishes_the_audit_row():
fake = FakeMicromateClient(run_states=[0x00])
da = access(fake)
orig = fake.read_run_state
calls = []
def flaky():
calls.append(1)
if len(calls) == 2: # the first read-back
raise mm_proto.TimeoutError("dropped")
return orig()
fake.read_run_state = flaky
with pytest.raises(Exception):
da.start_monitoring(ADDR, "UM20147")
(row,) = da._audit.rows.values()
assert len(fake.executed) == 1
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")