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
|
||||
Reference in new issue
Block a user