Files
seismo-relay/sfm/device_access/change.py
T
serversdownandClaude Opus 5.5 cdc6360ec0 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-23 19:36:00 -04:00

238 lines
13 KiB
Python

"""The series-independent core of a start/stop request.
Identity -> state -> (dry run | skip | audit -> pre-send drain -> send once ->
read back -> audit). Each series supplies only its own pieces as callables:
how to read the serial, how to read the run-state name, how to send (returning
the ack record), how to recognise a refusal or a ring, and optionally what to
drain from the line just before sending. Nothing in here retries: `send` is
called at most once, and every path after `audit.begin` calls `audit.finish`
exactly once, through `finish` below.
Once the send has started, a failure is never reported as if nothing went out:
it is a `ChangeUnconfirmed` naming the audit row, carrying the status its cause
would have had. The row's `sent` column says whether a frame went out (1),
did not (0), or may have (NULL), and `states` keeps every state read.
The state names `calling_home` and `unknown*` are Series-4 states, except
`unknown(...)`, which Series 3 also produces for a flag byte never measured.
Series 3 never produces `calling_home` or a ring, so those branches are simply
never taken there.
"""
from __future__ import annotations
from typing import Any, Callable, Dict, List, NoReturn, Optional
from .errors import (
AuditIncomplete, AuditUnavailable, CallHomeInProgress, ChangeUnconfirmed, NotSupported,
UnitStateUnknown, WrongUnit, translate,
)
from .models import ChangeResult, UnitAddress
from .series import normalise_serial
CALL_HOME_MESSAGE = ("the unit started calling home; SFM hung up so the call can "
"reach THOR -- try again in a few minutes")
_HUNG_UP = "SFM hung up so the call can reach THOR"
# The row's `sent` column.
SENT_ACKNOWLEDGED, NOTHING_SENT, SENT_UNKNOWN = 1, 0, None
def _never(exc: BaseException) -> bool:
return False
def run_change(*, serial: str, series: int, 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,
read_serial: Callable[[], str],
read_state: Callable[[], str],
describe_plan: Callable[[], Dict[str, Any]],
send: Callable[[], Dict[str, Any]],
is_refusal: Callable[[BaseException], bool] = _never,
is_ring: Callable[[BaseException], bool] = _never,
pre_send: Optional[Callable[[], None]] = None) -> ChangeResult:
action = "start monitoring" if start else "stop monitoring"
want = "monitoring" if start else "idle"
became = "started" if start else "stopped"
reported = normalise_serial(read_serial())
if reported != serial:
raise WrongUnit(f"asked for {serial} but {reported} answered at {address.key} -- "
"nothing sent")
before = read_state()
if before == "calling_home":
raise CallHomeInProgress(CALL_HOME_MESSAGE)
if before.startswith("unknown") and not dry_run:
raise UnitStateUnknown(f"the unit reports run state {before}, which has never "
"been measured -- nothing sent")
planned = dict(describe_plan(), sends_nothing=dry_run)
base = dict(serial=serial, series=series, action=action, plan=planned, state_before=before)
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}
try:
cid = audit.begin(serial=serial, series=series, 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
def states(seen: List[str], after: Optional[str]) -> Dict[str, Any]:
return {"before": before, "seen": list(seen), "after": after}
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. `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}",
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, 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
def status_of(exc: BaseException) -> int:
return translate(exc, connecting=False).http_status
if before == want and not even_if_already:
finish(f"nothing was sent ({serial} is already {want})",
outcome="skipped", verified="not_checked", ack=None, error=f"already {want}",
sent=NOTHING_SENT, states=states([before], None))
return ChangeResult(dry_run=False, sent=False, outcome="skipped",
verified="not_checked", state_after=before,
audit_id=cid, detail={"reason": f"the unit is already {want}"}, **base)
if pre_send is not None:
try:
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)", 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})", 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))
raise # the link is suspect
try:
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})", release_line=True,
outcome="failed", verified="not_checked", ack=None,
error=f"refused before sending: {exc}",
sent=NOTHING_SENT, states=states([before], None))
raise
if is_ring(exc):
unconfirmed(f"{action} was sent, but a call-home began in place of the "
f"acknowledgement -- whether it {became} is unknown; {_HUNG_UP}",
exc, went_out="unknown", status=CallHomeInProgress.http_status,
outcome="failed", verified="not_checked", ack=None,
error=f"a call-home began in place of the ack: {exc}",
states=states([before], None))
try:
after: Optional[str] = read_state()
except Exception as follow: # noqa: BLE001
if is_ring(follow):
unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and "
f"the unit then began calling home -- whether it {became} is "
f"unknown; {_HUNG_UP}",
follow, went_out="unknown", status=CallHomeInProgress.http_status,
outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}; a call-home began: {follow}",
states=states([before], None))
unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and "
f"reading the state afterwards failed ({follow}) -- whether it "
f"{became} is unknown",
exc, went_out="unknown", status=status_of(exc),
outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}; the follow-up read failed: {follow}",
states=states([before], None))
if after == "calling_home":
unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and "
f"the unit then began calling home -- whether it {became} is "
f"unknown; {_HUNG_UP}",
exc, went_out="unknown", status=CallHomeInProgress.http_status,
outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}; the unit is now calling home",
states=states([before], after))
finish(f"{action} was sent but the acknowledgement was lost ({exc}); the unit "
f"now reads {after}",
outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}", sent=SENT_UNKNOWN, states=states([before], after))
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)
seen = [before]
def last_poll() -> Optional[str]:
return seen[-1] if len(seen) > 1 else None
polls = int(verify_timeout_s // verify_interval_s)
try:
for _ in range(polls):
sleep(verify_interval_s)
seen.append(read_state())
if seen[-1] == want or seen[-1] == "calling_home":
break
except Exception as exc: # noqa: BLE001 -- the row must not stay pending
if is_ring(exc):
unconfirmed(f"{action} was sent and acknowledged, but the unit then began "
f"calling home before its state could be read back -- whether it "
f"{became} is unknown; {_HUNG_UP}",
exc, went_out="acknowledged", status=CallHomeInProgress.http_status,
outcome="sent", verified="not_checked", ack=ack,
error=f"sent and acknowledged; a call-home began while reading the "
f"state back: {exc}",
states=states(seen, last_poll()))
unconfirmed(f"{action} was sent and acknowledged, but reading the state back "
f"failed: {exc}",
exc, went_out="acknowledged", status=status_of(exc),
outcome="sent", verified="not_checked", ack=ack,
error=f"sent and acknowledged; reading the state back failed: {exc}",
states=states(seen, last_poll()))
if seen[-1] == "calling_home":
cause = CallHomeInProgress(CALL_HOME_MESSAGE)
unconfirmed(f"{action} was sent and acknowledged, but the unit then began calling "
f"home -- whether it {became} is unknown; {_HUNG_UP}",
cause, went_out="acknowledged", status=cause.http_status,
outcome="sent", verified="not_checked", ack=ack,
error="sent and acknowledged; the unit then began calling home",
states=states(seen, last_poll()))
ok = seen[-1] == want
outcome, verified = ("sent", "ok") if ok else ("failed", "mismatch")
error = None if ok else f"unit reads {seen[-1]}, expected {want}"
detail: Dict[str, Any] = {"states_seen": seen, "ack": ack}
if even_if_already and before == want:
note = (f"the unit was already {want} before sending; the read-back cannot show "
"that this send changed anything")
detail["note"] = note
if error is None:
error = note
finish(f"{action} was sent and verified" if ok else
f"{action} was sent and acknowledged, but the unit reads {seen[-1]}, not {want}",
outcome=outcome, verified=verified, ack=ack, error=error,
sent=SENT_ACKNOWLEDGED, states=states(seen, last_poll()))
return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified,
state_after=seen[-1], audit_id=cid, detail=detail, **base)