refactor(sfm): run_change takes a ChangeKind -- start/stop unchanged, call-home next (phase 4)

run_change named its change and its target state from a start/stop bool.  A
ChangeKind (action, want, became) now says what the change is called and which
state read back means it took; monitoring_change(start) gives exactly today's
names, call_home_change(enabled) the new ones.  An optional snapshot hook
records what the unit holds after the change in the result and the audit row
(never the verdict; one that raises is recorded as its error).

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-11-02 16:53:48 -05:00
1 parent 5b37ea22cc
commit 1dd5bfa464
4 files changed
+136 -11

No files matched your search

+43 -7
View File
@@ -1,4 +1,6 @@
"""The series-independent core of a start/stop request. """The series-independent core of a change request: start/stop monitoring,
call-home on/off. A `ChangeKind` says what the change is called and which state
read back means it took.
Identity -> state -> (dry run | skip | audit -> pre-send drain -> send once -> Identity -> state -> (dry run | skip | audit -> pre-send drain -> send once ->
read back -> audit). Each series supplies only its own pieces as callables: read back -> audit). Each series supplies only its own pieces as callables:
@@ -20,6 +22,7 @@ never taken there.
""" """
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, NoReturn, Optional from typing import Any, Callable, Dict, List, NoReturn, Optional
from .errors import ( from .errors import (
@@ -41,7 +44,37 @@ def _never(exc: BaseException) -> bool:
return False return False
def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_already: bool, @dataclass(frozen=True)
class ChangeKind:
"""What a change is called (the audit row's action, the messages' subject),
the state `read_state` returns once it took, and the past tense for messages."""
action: str
want: str
became: str
def monitoring_change(start: bool) -> ChangeKind:
return (ChangeKind("start monitoring", "monitoring", "started") if start
else ChangeKind("stop monitoring", "idle", "stopped"))
def call_home_change(enabled: bool) -> ChangeKind:
return (ChangeKind("enable call-home", "enabled", "enabled") if enabled
else ChangeKind("disable call-home", "disabled", "disabled"))
def _take_snapshot(snapshot: Optional[Callable[[], Dict[str, Any]]]) -> Optional[Dict[str, Any]]:
"""The caller's record of what the unit holds after the change -- for the
result and the audit row only. It never decides the outcome."""
if snapshot is None:
return None
try:
return dict(snapshot())
except Exception as exc: # noqa: BLE001 -- a record, never a verdict
return {"error": str(exc)}
def run_change(*, kind: ChangeKind, serial: str, series: int, dry_run: bool, even_if_already: bool,
audit: Any, address: UnitAddress, caller: str, audit: Any, address: UnitAddress, caller: str,
sleep: Callable[[float], None], verify_timeout_s: float, verify_interval_s: float, sleep: Callable[[float], None], verify_timeout_s: float, verify_interval_s: float,
read_serial: Callable[[], str], read_serial: Callable[[], str],
@@ -50,10 +83,9 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
send: Callable[[], Dict[str, Any]], send: Callable[[], Dict[str, Any]],
is_refusal: Callable[[BaseException], bool] = _never, is_refusal: Callable[[BaseException], bool] = _never,
is_ring: Callable[[BaseException], bool] = _never, is_ring: Callable[[BaseException], bool] = _never,
pre_send: Optional[Callable[[], None]] = None) -> ChangeResult: pre_send: Optional[Callable[[], None]] = None,
action = "start monitoring" if start else "stop monitoring" snapshot: Optional[Callable[[], Dict[str, Any]]] = None) -> ChangeResult:
want = "monitoring" if start else "idle" action, want, became = kind.action, kind.want, kind.became
became = "started" if start else "stopped"
reported = normalise_serial(read_serial()) reported = normalise_serial(read_serial())
if reported != serial: if reported != serial:
@@ -229,9 +261,13 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
detail["note"] = note detail["note"] = note
if error is None: if error is None:
error = note error = note
row_states = states(seen, last_poll())
snap = _take_snapshot(snapshot)
if snap is not None:
detail["snapshot"] = row_states["snapshot"] = snap
finish(f"{action} was sent and verified" if ok else finish(f"{action} was sent and verified" if ok else
f"{action} was sent and acknowledged, but the unit reads {seen[-1]}, not {want}", f"{action} was sent and acknowledged, but the unit reads {seen[-1]}, not {want}",
outcome=outcome, verified=verified, ack=ack, error=error, outcome=outcome, verified=verified, ack=ack, error=error,
sent=SENT_ACKNOWLEDGED, states=states(seen, last_poll())) sent=SENT_ACKNOWLEDGED, states=row_states)
return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified, return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified,
state_after=seen[-1], audit_id=cid, detail=detail, **base) state_after=seen[-1], audit_id=cid, detail=detail, **base)
+2 -2
View File
@@ -15,7 +15,7 @@ from minimateplus.protocol import SUB_START_MONITORING, SUB_STOP_MONITORING
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, StaleEvent, WrongUnit, translate
from .change import run_change from .change import monitoring_change, run_change
from .events import iso_of, make_event_id, stamp_of from .events import iso_of, make_event_id, stamp_of
from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
@@ -257,7 +257,7 @@ class Series3Adapter:
return s3_run_state(client.get_monitor_status()) return s3_run_state(client.get_monitor_status())
return run_change( return run_change(
serial=serial, series=3, start=start, dry_run=dry_run, kind=monitoring_change(start), serial=serial, series=3, dry_run=dry_run,
even_if_already=even_if_already, audit=audit, address=address, caller=caller, even_if_already=even_if_already, audit=audit, address=address, caller=caller,
sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s, sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=read_serial, read_serial=read_serial,
+3 -2
View File
@@ -26,7 +26,7 @@ from .errors import (
AuditIncomplete, CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound, AuditIncomplete, CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound,
MalformedReply, StaleEvent, WrongUnit, translate, MalformedReply, StaleEvent, WrongUnit, translate,
) )
from .change import CALL_HOME_MESSAGE, run_change from .change import CALL_HOME_MESSAGE, monitoring_change, run_change
from .events import iso_of, make_event_id, stamp_of from .events import iso_of, make_event_id, stamp_of
from .models import ChangeResult, 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
@@ -357,7 +357,8 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]} return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
return run_change( return run_change(
serial=serial, series=4, start=start, dry_run=dry_run, even_if_already=even_if_already, kind=monitoring_change(start), serial=serial, series=4, dry_run=dry_run,
even_if_already=even_if_already,
audit=audit, address=address, caller=caller, sleep=sleep, audit=audit, address=address, caller=caller, sleep=sleep,
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=lambda: client.serial(refresh=True), read_serial=lambda: client.serial(refresh=True),
+88
View File
@@ -0,0 +1,88 @@
"""run_change is kind-agnostic (phase 4): a ChangeKind names the change and the
state that means it took, so call-home rides the audited path start/stop uses.
Fake callables only -- no device."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sfm.device_access.change import ( # noqa: E402
ChangeKind, call_home_change, monitoring_change, run_change,
)
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 change(kind, states, *, verify=(6.0, 2.0), snapshot=None, audit=None):
states = list(states)
audit = audit or Audit()
result = run_change(
kind=kind, serial="UM20147", series=4, dry_run=False, even_if_already=False,
audit=audit, address=ADDR, caller="test", sleep=lambda s: None,
verify_timeout_s=verify[0], verify_interval_s=verify[1],
read_serial=lambda: "UM20147",
read_state=lambda: states.pop(0) if len(states) > 1 else states[0],
describe_plan=lambda: {"steps": []}, send=lambda: {"subs": ["0x81"]},
snapshot=snapshot)
return result, audit
def test_monitoring_kinds_are_todays_names():
assert monitoring_change(True) == ChangeKind("start monitoring", "monitoring", "started")
assert monitoring_change(False) == ChangeKind("stop monitoring", "idle", "stopped")
def test_call_home_kinds():
assert call_home_change(True) == ChangeKind("enable call-home", "enabled", "enabled")
assert call_home_change(False) == ChangeKind("disable call-home", "disabled", "disabled")
def test_a_call_home_change_is_verified_by_its_own_state():
r, _ = change(call_home_change(False), ["enabled", "disabled"])
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "disabled")
assert r.action == "disable call-home"
def test_a_call_home_read_back_that_did_not_change_is_a_mismatch():
r, _ = change(call_home_change(False), ["enabled"] * 4, verify=(3.0, 1.0))
assert (r.outcome, r.verified) == ("failed", "mismatch")
def test_the_snapshot_is_kept_in_the_result_and_the_audit():
r, audit = change(call_home_change(False), ["enabled", "disabled"], snapshot=lambda: {"after": "ab"})
assert r.detail["snapshot"] == {"after": "ab"}
((_, row),) = audit.rows.items()
assert row["states"]["snapshot"] == {"after": "ab"}
def test_a_failing_snapshot_does_not_change_the_outcome():
def broken():
raise RuntimeError("x")
r, _ = change(call_home_change(False), ["enabled", "disabled"], snapshot=broken)
assert (r.outcome, r.verified) == ("sent", "ok")
assert r.detail["snapshot"] == {"error": "x"}
def test_no_snapshot_leaves_the_result_as_before():
r, audit = change(monitoring_change(True), ["idle", "monitoring"])
assert "snapshot" not in r.detail
((_, row),) = audit.rows.items()
assert "snapshot" not in row["states"]