fix(sfm): a ring or a refusal is never mistaken for a send; fresh serial pinned; unmeasured states refused
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
eada7ba767
commit
14ea80f5a4
6 files changed
+166
-21
No files matched your search
@@ -1,7 +1,7 @@
|
||||
"""One door for every device request -- see the 2026-10-20 parity spec."""
|
||||
from .errors import (
|
||||
BadRequest, CallHomeInProgress, ConnectFailed, DeviceError, EventNotFound,
|
||||
MalformedReply, NoAnswer, NotSupported, StaleEvent, UnitBusy, WrongUnit,
|
||||
AuditUnavailable, BadRequest, CallHomeInProgress, ConnectFailed, DeviceError, EventNotFound,
|
||||
MalformedReply, NoAnswer, NotSupported, StaleEvent, UnitBusy, UnitStateUnknown, WrongUnit,
|
||||
translate,
|
||||
)
|
||||
from .models import (
|
||||
|
||||
@@ -9,7 +9,7 @@ import threading
|
||||
import time
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
from .errors import ConnectFailed, DeviceError, NoAnswer, WrongUnit
|
||||
from .errors import ConnectFailed, DeviceError, NoAnswer, NotSupported, WrongUnit
|
||||
from .events import parse_event_id
|
||||
from .locks import UnitLocks
|
||||
from .models import ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||||
@@ -39,6 +39,8 @@ class DeviceAccess:
|
||||
verify_timeout_s: float = 60.0,
|
||||
verify_interval_s: float = 2.0,
|
||||
) -> None:
|
||||
if verify_interval_s <= 0 or verify_timeout_s < verify_interval_s:
|
||||
raise ValueError("verify_interval_s must be > 0 and verify_timeout_s >= verify_interval_s")
|
||||
self._audit = audit
|
||||
self._sleep = sleep
|
||||
self._verify_timeout_s = verify_timeout_s
|
||||
@@ -89,6 +91,9 @@ class DeviceAccess:
|
||||
even_if_already=even_if_already, caller=caller)
|
||||
|
||||
def _change_monitoring(self, address, serial, *, start, dry_run, even_if_already, caller):
|
||||
if not dry_run and self._audit is None:
|
||||
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
|
||||
"without one (nothing sent)")
|
||||
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,
|
||||
|
||||
@@ -21,6 +21,16 @@ class WrongUnit(DeviceError):
|
||||
http_status = 409
|
||||
|
||||
|
||||
class UnitStateUnknown(DeviceError):
|
||||
"""The unit reports a run state that has never been measured."""
|
||||
http_status = 409
|
||||
|
||||
|
||||
class AuditUnavailable(DeviceError):
|
||||
"""The audit row could not be written, so nothing was sent."""
|
||||
http_status = 503
|
||||
|
||||
|
||||
class UnitBusy(DeviceError):
|
||||
http_status = 423
|
||||
|
||||
|
||||
+45
-13
@@ -11,13 +11,14 @@ import time
|
||||
from typing import Any, Callable, Optional, TypeVar
|
||||
|
||||
from micromate.client import MicromateClient
|
||||
from micromate.opcodes import OpcodeRefused
|
||||
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 .errors import (
|
||||
CallHomeInProgress, DeviceError, EventNotFound, MalformedReply, NotSupported, StaleEvent,
|
||||
WrongUnit, translate,
|
||||
AuditUnavailable, CallHomeInProgress, DeviceError, EventNotFound, MalformedReply, NotSupported, StaleEvent,
|
||||
UnitStateUnknown, WrongUnit, translate,
|
||||
)
|
||||
from .events import iso_of, make_event_id, stamp_of
|
||||
from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||||
@@ -335,6 +336,9 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
|
||||
before = client.read_run_state()
|
||||
if before.name == "calling_home":
|
||||
raise CallHomeInProgress(_RING_MESSAGE)
|
||||
if before.name.startswith("unknown") and not dry_run:
|
||||
raise UnitStateUnknown(f"the unit reports run state {before.name}, which has never "
|
||||
"been measured -- nothing sent")
|
||||
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,
|
||||
@@ -347,8 +351,12 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
|
||||
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)
|
||||
try:
|
||||
cid = audit.begin(serial=serial, series=4, address=address.key, action=action,
|
||||
tier="change", request=request, caller=caller)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise AuditUnavailable(
|
||||
f"the audit log could not be written -- nothing sent: {exc}") from exc
|
||||
if before.name == want and not even_if_already:
|
||||
audit.finish(cid, outcome="skipped", verified="not_checked", ack=None,
|
||||
error=f"already {want}")
|
||||
@@ -358,8 +366,25 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
|
||||
|
||||
try:
|
||||
acks = client.protocol.execute(plan)
|
||||
except (OpcodeRefused, TypeError) as exc: # refused by the gate: nothing went out
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"refused before sending: {exc}")
|
||||
raise
|
||||
except RingDetected as exc:
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"a call-home began in place of the ack: {exc}")
|
||||
raise # _exchange releases the line
|
||||
except Exception as exc: # noqa: BLE001 -- recorded, never retried
|
||||
after = _try_run_state(client)
|
||||
try:
|
||||
after = _try_run_state(client)
|
||||
except RingDetected as ring:
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; a call-home began: {ring}")
|
||||
raise
|
||||
if after == "calling_home":
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; the unit is now calling home")
|
||||
raise CallHomeInProgress(_RING_MESSAGE) from exc
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}")
|
||||
if after is None:
|
||||
@@ -375,22 +400,29 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
|
||||
for _ in range(polls):
|
||||
sleep(verify_interval_s)
|
||||
seen.append(client.read_run_state().name)
|
||||
if seen[-1] == want:
|
||||
if seen[-1] == want or seen[-1] == "calling_home":
|
||||
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}")
|
||||
audit.finish(cid, outcome="sent", verified="not_checked", ack=ack,
|
||||
error=f"sent and acknowledged; reading the state back failed: {exc}")
|
||||
raise
|
||||
if seen[-1] == "calling_home":
|
||||
audit.finish(cid, outcome="sent", verified="not_checked", ack=ack,
|
||||
error="sent and acknowledged; the unit then began calling home")
|
||||
raise CallHomeInProgress(_RING_MESSAGE)
|
||||
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)
|
||||
outcome, verified = ("sent", "ok") if ok else ("failed", "mismatch")
|
||||
audit.finish(cid, outcome=outcome, verified=verified, ack=ack,
|
||||
error=None if ok else f"unit reads {seen[-1]}, expected {want}")
|
||||
return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified,
|
||||
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 RingDetected:
|
||||
raise
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
@@ -195,7 +195,7 @@ class FakeMicromateClient(_Base):
|
||||
|
||||
def serial(self, *, refresh=False):
|
||||
self._step("serial")
|
||||
return self.serial_reported
|
||||
return self.serial_reported if refresh else self.unit_serial
|
||||
|
||||
def read_run_state(self):
|
||||
from micromate.models import MicromateRunState
|
||||
|
||||
@@ -9,10 +9,12 @@ 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 micromate.opcodes import OpcodeRefused # noqa: E402
|
||||
from sfm.device_access.s4 import RingDetected # 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,
|
||||
AuditUnavailable, CallHomeInProgress, DeviceError, NoAnswer, NotSupported, UnitStateUnknown, WrongUnit,
|
||||
)
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
|
||||
@@ -56,7 +58,7 @@ def test_start_sends_once_and_verifies_by_reading_back():
|
||||
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.detail["states_seen"] == ["idle", "idle", "monitoring"]
|
||||
assert r.plan["sends_nothing"] is False
|
||||
assert row["request"]["plan"]["sends_nothing"] is False
|
||||
|
||||
@@ -83,6 +85,7 @@ def test_a_unit_calling_home_is_refused_and_nothing_is_sent():
|
||||
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
|
||||
assert ADDR.key not in da._sessions
|
||||
|
||||
|
||||
def test_a_different_unit_on_the_fresh_serial_read_is_refused_before_writing():
|
||||
@@ -93,13 +96,14 @@ def test_a_different_unit_on_the_fresh_serial_read_is_refused_before_writing():
|
||||
assert fake.executed == []
|
||||
assert fake.is_open() is False
|
||||
assert da.held_serial(ADDR) is None
|
||||
assert ADDR.key not in da._sessions
|
||||
|
||||
|
||||
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 == []
|
||||
assert fake.executed == [] and fake.opened == 0 and fake.calls == []
|
||||
|
||||
|
||||
def test_a_clean_ack_but_no_state_change_is_a_failed_change():
|
||||
@@ -109,9 +113,10 @@ def test_a_clean_ack_but_no_state_change_is_a_failed_change():
|
||||
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"
|
||||
assert da._audit.rows[r.audit_id]["outcome"] == "failed"
|
||||
|
||||
|
||||
def test_a_lost_ack_is_never_retried():
|
||||
def test_a_lost_ack_is_recorded_once_and_not_resent():
|
||||
fake = FakeMicromateClient(run_states=[0x00, 0x02],
|
||||
execute_error=mm_proto.TimeoutError("no ack"))
|
||||
da = access(fake)
|
||||
@@ -148,4 +153,97 @@ def test_a_read_back_that_fails_still_finishes_the_audit_row():
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
(row,) = da._audit.rows.values()
|
||||
assert len(fake.executed) == 1
|
||||
assert (row["outcome"], row["verified"]) == ("sent", "not_checked")
|
||||
assert row["ack"] is not None
|
||||
assert "reading the state back failed" in row["error"]
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
|
||||
|
||||
def test_a_ring_in_place_of_the_ack_is_a_call_home_not_a_send():
|
||||
fake = FakeMicromateClient(run_states=[0x00], execute_error=RingDetected("RADIO RING"))
|
||||
da = access(fake)
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
assert len(fake.executed) == 1
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
(row,) = da._audit.rows.values()
|
||||
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
|
||||
assert "call-home began in place of the ack" in row["error"]
|
||||
|
||||
|
||||
def test_calling_home_seen_while_polling_releases_the_line():
|
||||
fake = FakeMicromateClient(run_states=[0x00, 0x03])
|
||||
da = access(fake)
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
assert len(fake.executed) == 1
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
(row,) = da._audit.rows.values()
|
||||
assert (row["outcome"], row["verified"]) == ("sent", "not_checked")
|
||||
assert row["ack"] is not None
|
||||
|
||||
|
||||
def test_calling_home_after_a_lost_ack_releases_the_line():
|
||||
fake = FakeMicromateClient(run_states=[0x00, 0x03],
|
||||
execute_error=mm_proto.TimeoutError("no ack"))
|
||||
da = access(fake)
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
assert fake.is_open() is False
|
||||
(row,) = da._audit.rows.values()
|
||||
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
|
||||
|
||||
|
||||
def test_a_refusal_by_execute_is_not_a_send():
|
||||
fake = FakeMicromateClient(execute_error=OpcodeRefused("nope"))
|
||||
da = access(fake)
|
||||
with pytest.raises(DeviceError, match="nope"):
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
(row,) = da._audit.rows.values()
|
||||
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
|
||||
assert "refused before sending" in row["error"]
|
||||
|
||||
|
||||
def test_a_failed_audit_write_sends_nothing():
|
||||
class Broken(Audit):
|
||||
def begin(self, **f):
|
||||
raise OSError("disk full")
|
||||
fake = FakeMicromateClient()
|
||||
with pytest.raises(AuditUnavailable):
|
||||
access(fake, audit=Broken()).start_monitoring(ADDR, "UM20147")
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_lost_ack_and_failed_follow_up_read_on_a_held_line_releases_it():
|
||||
fake = FakeMicromateClient(run_states=[0x00], execute_error=mm_proto.TimeoutError("no ack"))
|
||||
da = access(fake)
|
||||
da.status(ADDR, "UM20147") # hold the line
|
||||
orig, n = fake.read_run_state, []
|
||||
|
||||
def flaky():
|
||||
n.append(1)
|
||||
if len(n) == 2: # the follow-up after the lost ack
|
||||
raise mm_proto.TimeoutError("gone")
|
||||
return orig()
|
||||
fake.read_run_state = flaky
|
||||
with pytest.raises(NoAnswer):
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
assert len(fake.executed) == 1
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
|
||||
|
||||
def test_a_live_change_in_an_unmeasured_state_is_refused_but_a_dry_run_is_not():
|
||||
fake = FakeMicromateClient(run_states=[0x07])
|
||||
da = access(fake)
|
||||
with pytest.raises(UnitStateUnknown):
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
assert fake.executed == [] and da._audit.rows == {}
|
||||
r = da.start_monitoring(ADDR, "UM20147", dry_run=True)
|
||||
assert r.state_before == "unknown(0x07)"
|
||||
|
||||
|
||||
def test_bad_verify_timings_are_rejected():
|
||||
with pytest.raises(ValueError):
|
||||
DeviceAccess(start_reaper=False, verify_interval_s=0)
|
||||
with pytest.raises(ValueError):
|
||||
DeviceAccess(start_reaper=False, verify_interval_s=5, verify_timeout_s=2)
|
||||
Reference in new issue
Block a user