From cdc6360ec042baf150f309e095faa8fef9a727bc Mon Sep 17 00:00:00 2001 From: serversdown Date: Fri, 23 Oct 2026 19:36:00 -0400 Subject: [PATCH] fix(sfm): an audit finish that fails on a hang-up path still releases the line The final fix wave's AuditIncomplete landed in _exchange's `except DeviceError`, which keeps the line -- so on the nine ring / link-fault paths (and a refusal) a failed audit write turned a hang-up into a held Series-4 line, blocking a THOR call-home for up to the 5-minute idle hang-up and making "SFM hung up" false. AuditIncomplete now carries release_line, set by every finish whose path hangs up anyway, and _exchange honours it. Also pins the Series-3 change path's retry=False again (the rewritten lost-ack test no longer could). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- sfm/device_access/change.py | 17 ++++--- sfm/device_access/errors.py | 10 ++++- sfm/device_access/s4.py | 15 +++++-- tests/test_device_access_change.py | 72 +++++++++++++++++++++++++++++- 4 files changed, 102 insertions(+), 12 deletions(-) diff --git a/sfm/device_access/change.py b/sfm/device_access/change.py index 2af5fc0..f157c35 100644 --- a/sfm/device_access/change.py +++ b/sfm/device_access/change.py @@ -85,20 +85,23 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_ def states(seen: List[str], after: Optional[str]) -> Dict[str, Any]: return {"before": before, "seen": list(seen), "after": after} - def finish(unit: str, **fields: Any) -> None: + def finish(unit: str, *, release_line: bool = False, **fields: Any) -> None: """The only way a row is finished. `unit` says what happened to the - unit, so a finish that fails still says it.""" + unit, so a finish that fails still says it. `release_line` says whether + this path hangs up anyway, so a failed finish does not hold the line.""" try: audit.finish(cid, **fields) except Exception as exc: # noqa: BLE001 raise AuditIncomplete( - f"{unit} -- but audit record {cid} could not be finished: {exc}") from exc + f"{unit} -- but audit record {cid} could not be finished: {exc}", + release_line=release_line) from exc def unconfirmed(unit: str, cause: BaseException, *, went_out: str, status: int, **fields: Any) -> NoReturn: """Finish the row, then say the change went out (or may have) and name it. `went_out` is "acknowledged" or "unknown"; the row's `sent` follows it.""" - finish(unit, sent=SENT_ACKNOWLEDGED if went_out == "acknowledged" else SENT_UNKNOWN, + finish(unit, release_line=True, + sent=SENT_ACKNOWLEDGED if went_out == "acknowledged" else SENT_UNKNOWN, **fields) raise ChangeUnconfirmed(f"{unit} -- audit record {cid}", audit_id=cid, sent=went_out, http_status=status) from cause @@ -119,12 +122,12 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_ pre_send() # sends nothing: drains what is already waiting except Exception as exc: # noqa: BLE001 if is_ring(exc): - finish("nothing was sent (a call-home began before sending)", + finish("nothing was sent (a call-home began before sending)", release_line=True, outcome="failed", verified="not_checked", ack=None, error="a call-home began before sending -- nothing sent", sent=NOTHING_SENT, states=states([before], None)) raise CallHomeInProgress(CALL_HOME_MESSAGE) from exc - finish(f"nothing was sent (the line failed before sending: {exc})", + finish(f"nothing was sent (the line failed before sending: {exc})", release_line=True, outcome="failed", verified="not_checked", ack=None, error=f"the line failed before sending -- nothing sent: {exc}", sent=NOTHING_SENT, states=states([before], None)) @@ -134,7 +137,7 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_ ack = send() # the only send; nothing below can reach it again except Exception as exc: # noqa: BLE001 -- recorded, never retried if is_refusal(exc): # refused by the gate: nothing went out - finish(f"nothing was sent (refused before sending: {exc})", + finish(f"nothing was sent (refused before sending: {exc})", release_line=True, outcome="failed", verified="not_checked", ack=None, error=f"refused before sending: {exc}", sent=NOTHING_SENT, states=states([before], None)) diff --git a/sfm/device_access/errors.py b/sfm/device_access/errors.py index c954f5e..6f65e31 100644 --- a/sfm/device_access/errors.py +++ b/sfm/device_access/errors.py @@ -33,9 +33,17 @@ class AuditUnavailable(DeviceError): class AuditIncomplete(DeviceError): """The unit was dealt with, but its audit row could not be finished. The - message says what happened to the unit first, then names the row.""" + message says what happened to the unit first, then names the row. + + `release_line` is True when the path would have hung up had the finish + worked (a ring, a link fault, a refusal): the failed write to the audit log + must not turn that into a held line, which would block a call-home.""" http_status = 500 + def __init__(self, message: str, *, release_line: bool = False) -> None: + super().__init__(message) + self.release_line = release_line + class ChangeUnconfirmed(DeviceError): """A change failed after its frame went out, or may have gone out. diff --git a/sfm/device_access/s4.py b/sfm/device_access/s4.py index e0014fd..10961c6 100644 --- a/sfm/device_access/s4.py +++ b/sfm/device_access/s4.py @@ -23,8 +23,8 @@ from micromate.writes import plan_start_monitoring, plan_stop_monitoring from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport from .errors import ( - CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound, MalformedReply, StaleEvent, - WrongUnit, translate, + AuditIncomplete, CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound, + MalformedReply, StaleEvent, WrongUnit, translate, ) from .change import CALL_HOME_MESSAGE, run_change from .events import iso_of, make_event_id, stamp_of @@ -133,7 +133,8 @@ class Series4Session: The exceptions: `CallHomeInProgress` and `WrongUnit` release the line, because the line itself is the problem; so does `ChangeUnconfirmed`, which the change core raises only after a link fault or a ring, once the frame - has gone out. `AuditIncomplete` is an ordinary verdict: the line is kept. + has gone out. `AuditIncomplete` keeps the line unless its `release_line` + says the path would have hung up anyway (a ring, a link fault, a refusal). """ def __init__(self, address: UnitAddress, serial: str, @@ -192,6 +193,14 @@ class Series4Session: log.warning("%s at %s -- released the line: %s", type(exc).__name__, self.address.key, exc) raise + except AuditIncomplete as exc: + # A finish that failed on a path that hangs up anyway (ring, link + # fault, refusal) must still hang up; on a healthy path, keep the line. + if exc.release_line: + self.hang_up() + log.warning("AuditIncomplete at %s -- released the line: %s", + self.address.key, exc) + raise except DeviceError: # The operation's own verdict (event not found, stale id): the line # is healthy, so keep it. Library errors still hang up below. diff --git a/tests/test_device_access_change.py b/tests/test_device_access_change.py index 7dd9970..56b32d9 100644 --- a/tests/test_device_access_change.py +++ b/tests/test_device_access_change.py @@ -15,7 +15,7 @@ from device_access_fakes import FakeMicromateClient # no from sfm.device_access.access import DeviceAccess # noqa: E402 from sfm.device_access.errors import ( # noqa: E402 AuditIncomplete, AuditUnavailable, CallHomeInProgress, ChangeUnconfirmed, ConnectFailed, DeviceError, - NotSupported, UnitStateUnknown, WrongUnit, + NoAnswer, NotSupported, UnitStateUnknown, WrongUnit, ) from sfm.device_access.models import UnitAddress # noqa: E402 @@ -694,3 +694,73 @@ def test_series3_monitor_status_decode_keeps_the_raw_flag(): assert (st.state_flag, st.is_monitoring) == (flag, monitoring) assert _decode_monitor_status(bytes(12)).state_flag is None # no section[1] assert _decode_monitor_status(b"").state_flag is None + + +# ── an audit finish that fails must not turn a hang-up into a held line ─────── + +def _reads_then(fake, exc): + """read_run_state answers once (the state before the send), then raises.""" + orig, n = fake.read_run_state, [] + + def flaky(): + n.append(1) + if len(n) > 1: + raise exc + return orig() + fake.read_run_state = flaky + return fake + + +def _drain_raises(fake, exc): + def drain(): + raise exc + fake.read_unsolicited = drain + return fake + + +_LOST = mm_proto.TimeoutError("no ack") +_HANG_UP_PATHS = { + "ring in place of the ack": + lambda: FakeMicromateClient(run_states=[0x00], execute_error=RingDetected("RADIO RING")), + "lost ack, ring on the follow-up": + lambda: _reads_then(FakeMicromateClient(run_states=[0x00], execute_error=_LOST), + RingDetected("RADIO RING")), + "lost ack, follow-up reads calling_home": + lambda: FakeMicromateClient(run_states=[0x00, 0x03], execute_error=_LOST), + "lost ack, follow-up unreadable": + lambda: _reads_then(FakeMicromateClient(run_states=[0x00], execute_error=_LOST), + mm_proto.TimeoutError("silent")), + "read-back raises": + lambda: _reads_then(FakeMicromateClient(run_states=[0x00]), mm_proto.TimeoutError("silent")), + "read-back rings": + lambda: _reads_then(FakeMicromateClient(run_states=[0x00]), RingDetected("RADIO RING")), + "read-back reads calling_home": + lambda: FakeMicromateClient(run_states=[0x00, 0x03]), + "ring before the send": + lambda: _drain_raises(FakeMicromateClient(run_states=[0x00]), RingDetected("RADIO RING")), + "link fault before the send": + lambda: _drain_raises(FakeMicromateClient(run_states=[0x00]), OSError("connection reset")), + "refused by execute": + lambda: FakeMicromateClient(run_states=[0x00], execute_error=OpcodeRefused("nope")), +} + + +@pytest.mark.parametrize("path", sorted(_HANG_UP_PATHS)) +def test_a_finish_that_fails_on_a_hang_up_path_still_releases_the_line(path): + fake = _HANG_UP_PATHS[path]() + da = access(fake, audit=FinishFails()) + with pytest.raises(AuditIncomplete) as e: + da.start_monitoring(ADDR, "UM20147") + assert e.value.release_line is True + assert "could not be finished: disk full" in str(e.value) + assert len(fake.executed) <= 1 + assert released(fake, da) + + +def test_series3_a_cold_unit_during_a_change_is_not_retried(): + fake = FakeMiniMateClient(fail=[mmp_proto.TimeoutError("cold")]) + da = access3(fake) + with pytest.raises(NoAnswer): + da.start_monitoring(TCP3, "BE18193") + assert fake.writes == [] + assert len(da.factory_calls) == 1 # the change path never takes _run's retry