"""Start/stop through the safety layer: identity, state, dry run, audit, read-back, no retry.""" from __future__ import annotations import os import sys 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 AuditIncomplete, AuditUnavailable, CallHomeInProgress, ChangeUnconfirmed, ConnectFailed, DeviceError, NoAnswer, NotSupported, UnitStateUnknown, WrongUnit, ) 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 access(fake, audit="default"): return DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False, audit=Audit() if audit == "default" else audit, sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0) def unconfirmed(excinfo, da, *, sent, status): """A failure after the send: it names the one audit row, says a frame went out (or may have), and carries its cause's status. Returns the row.""" ((cid, row),) = da._audit.rows.items() e = excinfo.value assert (e.audit_id, e.sent, e.http_status) == (cid, sent, status) assert f"audit record {cid}" in str(e) assert "was sent" in str(e) and "nothing sent" not in str(e) return row def released(fake, da): return fake.is_open() is False and ADDR.key not in da._sessions def test_a_dry_run_returns_the_exact_frames_and_sends_nothing(): fake = FakeMicromateClient(run_states=[0x00]) da = access(fake) r = da.start_monitoring(ADDR, "UM20147", dry_run=True) assert (r.dry_run, r.sent, r.outcome, r.state_before) == (True, False, "dry_run", "idle") assert r.plan["steps"][0]["frame"] == "41021010009600ffff00000000000000000000a403" assert r.plan["sends_nothing"] is True assert fake.executed == [] and da._audit.rows == {} def test_start_sends_once_and_verifies_by_reading_back(): fake = FakeMicromateClient(run_states=[0x00, 0x00, 0x02]) da = access(fake) r = da.start_monitoring(ADDR, "UM20147") assert (r.sent, r.outcome, r.verified, r.state_after) == (True, "sent", "ok", "monitoring") 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"] == ["idle", "idle", "monitoring"] assert r.plan["sends_nothing"] is False assert row["request"]["plan"]["sends_nothing"] is False def test_already_in_state_is_skipped_and_audited_as_skipped(): fake = FakeMicromateClient(run_states=[0x02]) da = access(fake) r = da.start_monitoring(ADDR, "UM20147") assert (r.sent, r.outcome) == (False, "skipped") and fake.executed == [] assert da._audit.rows[r.audit_id]["outcome"] == "skipped" def test_even_if_already_sends_anyway(): fake = FakeMicromateClient(run_states=[0x02]) r = access(fake).start_monitoring(ADDR, "UM20147", even_if_already=True) assert r.sent and len(fake.executed) == 1 def test_a_unit_calling_home_is_refused_and_nothing_is_sent(): fake = FakeMicromateClient(run_states=[0x03]) da = access(fake) with pytest.raises(CallHomeInProgress): da.stop_monitoring(ADDR, "UM20147") 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(): fake = FakeMicromateClient(serial_reported="UM12947") da = access(fake) with pytest.raises(WrongUnit): da.start_monitoring(ADDR, "UM20147") 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 == [] and fake.opened == 0 and fake.calls == [] def test_a_clean_ack_but_no_state_change_is_a_failed_change(): fake = FakeMicromateClient(run_states=[0x00]) # never leaves idle da = access(fake) r = da.start_monitoring(ADDR, "UM20147") 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_recorded_once_and_not_resent(): fake = FakeMicromateClient(run_states=[0x00, 0x02], execute_error=mm_proto.TimeoutError("no ack")) da = access(fake) r = da.start_monitoring(ADDR, "UM20147") assert len(fake.executed) == 1 assert (r.outcome, r.state_after) == ("failed", "monitoring") assert "no ack" in r.detail["error"] assert da._audit.rows[r.audit_id]["outcome"] == "failed" def test_a_change_on_a_dropped_held_line_is_not_retried(): fake = FakeMicromateClient(run_states=[0x00]) da = access(fake) da.status(ADDR, "UM20147") # hold the line fake.fail = [mm_proto.TimeoutError("peer gone")] # next call fails with pytest.raises(Exception): da.start_monitoring(ADDR, "UM20147") assert fake.executed == [] # never reached the write, never re-tried def test_a_read_back_that_fails_still_finishes_the_audit_row(): fake = FakeMicromateClient(run_states=[0x00]) da = access(fake) orig = fake.read_run_state calls = [] def flaky(): calls.append(1) if len(calls) == 2: # the first read-back raise mm_proto.TimeoutError("dropped") return orig() fake.read_run_state = flaky with pytest.raises(ChangeUnconfirmed) as e: da.start_monitoring(ADDR, "UM20147") row = unconfirmed(e, da, sent="acknowledged", status=504) assert "sent and acknowledged" in str(e.value) and "dropped" in str(e.value) 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 row["sent"] == 1 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(ChangeUnconfirmed) as e: da.start_monitoring(ADDR, "UM20147") row = unconfirmed(e, da, sent="unknown", status=503) assert "hung up so the call can reach THOR" in str(e.value) assert "whether it started is unknown" in str(e.value) assert len(fake.executed) == 1 assert fake.is_open() is False and ADDR.key not in da._sessions assert (row["outcome"], row["verified"]) == ("failed", "not_checked") assert "call-home began in place of the ack" in row["error"] assert row["sent"] is None def test_calling_home_seen_while_polling_releases_the_line(): fake = FakeMicromateClient(run_states=[0x00, 0x03]) da = access(fake) with pytest.raises(ChangeUnconfirmed) as e: da.start_monitoring(ADDR, "UM20147") row = unconfirmed(e, da, sent="acknowledged", status=503) assert "hung up so the call can reach THOR" in str(e.value) assert len(fake.executed) == 1 assert fake.calls.count("read_run_state") == 2 # the read before + the one poll assert fake.is_open() is False and ADDR.key not in da._sessions assert (row["outcome"], row["verified"]) == ("sent", "not_checked") assert row["ack"] is not None assert row["sent"] == 1 assert row["states"] == {"before": "idle", "seen": ["idle", "calling_home"], "after": "calling_home"} 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(ChangeUnconfirmed) as e: da.start_monitoring(ADDR, "UM20147") row = unconfirmed(e, da, sent="unknown", status=503) assert "acknowledgement was lost" in str(e.value) assert "whether it started is unknown" in str(e.value) assert "hung up so the call can reach THOR" in str(e.value) assert fake.is_open() is False and ADDR.key not in da._sessions assert (row["outcome"], row["verified"]) == ("failed", "not_checked") assert row["sent"] is None assert row["states"] == {"before": "idle", "seen": ["idle"], "after": "calling_home"} 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(ChangeUnconfirmed) as e: da.start_monitoring(ADDR, "UM20147") row = unconfirmed(e, da, sent="unknown", status=504) assert "acknowledgement was lost" in str(e.value) and "gone" in str(e.value) assert len(fake.executed) == 1 assert fake.is_open() is False and ADDR.key not in da._sessions assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "not_checked", None) 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) def test_a_ring_on_the_follow_up_read_after_a_lost_ack_finishes_the_row(): fake = FakeMicromateClient(run_states=[0x00], execute_error=mm_proto.TimeoutError("no ack")) da = access(fake) orig, n = fake.read_run_state, [] def ringing(): n.append(1) if len(n) == 2: # the first follow-up read raise RingDetected("RADIO RING") return orig() fake.read_run_state = ringing with pytest.raises(ChangeUnconfirmed) as e: da.start_monitoring(ADDR, "UM20147") row = unconfirmed(e, da, sent="unknown", status=503) assert "hung up so the call can reach THOR" in str(e.value) assert len(fake.executed) == 1 assert (row["outcome"], row["verified"]) == ("failed", "not_checked") assert "a call-home began" in row["error"] assert row["sent"] is None assert fake.is_open() is False and ADDR.key not in da._sessions def test_a_type_error_after_sending_is_recorded_as_no_clean_ack(): fake = FakeMicromateClient(run_states=[0x00, 0x02], execute_error=TypeError("parser bug")) da = access(fake) r = da.start_monitoring(ADDR, "UM20147") assert len(fake.executed) == 1 and r.sent is True assert "no clean ack" in da._audit.rows[r.audit_id]["error"] assert "refused before sending" not in da._audit.rows[r.audit_id]["error"] def test_a_malformed_serial_is_422_even_without_an_audit_sink(): from sfm.device_access.errors import BadRequest with pytest.raises(BadRequest): access(FakeMicromateClient(), audit=None).start_monitoring(ADDR, "XX123") # ── Series 3 ────────────────────────────────────────────────────────────────── import minimateplus.protocol as mmp_proto # noqa: E402 from device_access_fakes import FakeMiniMateClient # noqa: E402 TCP3 = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None) def access3(fake, audit="default", sleep=lambda s: None): seen = [] def factory(a, **kw): seen.append(kw) return fake da = DeviceAccess(s3_client_factory=factory, start_reaper=False, audit=Audit() if audit == "default" else audit, sleep=sleep, verify_timeout_s=6.0, verify_interval_s=2.0) da.factory_calls = seen return da def test_series3_dry_run_returns_its_own_frame_and_sends_nothing(): fake = FakeMiniMateClient(monitor_states=[False]) r = access3(fake).start_monitoring(TCP3, "BE18193", dry_run=True) assert (r.series, r.outcome, r.state_before) == (3, "dry_run", "idle") assert r.plan["steps"][0]["sub"] == "0x96" and fake.writes == [] assert r.plan["steps"][0]["expect_ack"] == "0x69" and r.plan["sends_nothing"] is True assert r.plan["steps"][0]["frame"] == "41021010009600000000000000000000000000a603" stop = access3(FakeMiniMateClient(monitor_states=[True])).stop_monitoring( TCP3, "BE18193", dry_run=True) assert stop.plan["steps"][0]["frame"] == "41021010009700000000000000000000000000a703" assert stop.plan["steps"][0]["expect_ack"] == "0x68" and stop.outcome == "dry_run" def test_series3_start_is_verified_by_monitor_status(): fake = FakeMiniMateClient(monitor_states=[False, False, True]) da = access3(fake) r = da.start_monitoring(TCP3, "BE18193") assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "monitoring") assert fake.writes == ["start_monitoring"] assert da._audit.rows[r.audit_id]["ack"] == {"subs": ["0x69"]} assert da.factory_calls == [{"timeout": 120.0}] def test_series3_stop_acks_0x68(): fake = FakeMiniMateClient(monitor_states=[True, False]) da = access3(fake) r = da.stop_monitoring(TCP3, "BE18193") assert r.verified == "ok" and fake.writes == ["stop_monitoring"] assert da._audit.rows[r.audit_id]["ack"] == {"subs": ["0x68"]} def test_series3_wrong_unit_is_refused_before_writing(): fake = FakeMiniMateClient(serial="BE11529") with pytest.raises(WrongUnit): access3(fake).stop_monitoring(TCP3, "BE18193") assert fake.writes == [] def test_series3_a_lost_ack_with_a_good_read_back_is_one_write(): fake = FakeMiniMateClient(monitor_states=[False, True], write_error=mmp_proto.TimeoutError("no ack")) da = access3(fake) r = da.start_monitoring(TCP3, "BE18193") assert fake.writes == ["start_monitoring"] # one send, no cold-boot retry assert r.outcome == "failed" and r.state_after == "monitoring" def test_series3_already_in_state_is_skipped(): fake = FakeMiniMateClient(monitor_states=[True]) da = access3(fake) r = da.start_monitoring(TCP3, "BE18193") assert (r.sent, r.outcome) == (False, "skipped") and fake.writes == [] assert da._audit.rows[r.audit_id]["outcome"] == "skipped" def test_series3_a_state_that_never_changes_is_a_mismatch(): fake = FakeMiniMateClient(monitor_states=[False]) da = access3(fake) r = da.start_monitoring(TCP3, "BE18193") assert (r.outcome, r.verified, r.state_after) == ("failed", "mismatch", "idle") assert da._audit.rows[r.audit_id]["verified"] == "mismatch" def test_series3_a_failing_read_back_is_audited_then_raised(): fake = FakeMiniMateClient(monitor_states=[False]) da = access3(fake) real = fake.get_monitor_status calls = [] def flaky(): calls.append(1) if len(calls) > 1: raise mmp_proto.TimeoutError("quiet") return real() fake.get_monitor_status = flaky with pytest.raises(ChangeUnconfirmed) as e: da.start_monitoring(TCP3, "BE18193") row = unconfirmed(e, da, sent="acknowledged", status=504) assert (row["outcome"], row["verified"]) == ("sent", "not_checked") assert "reading the state back failed" in row["error"] assert fake.writes == ["start_monitoring"] def test_series3_audit_begin_failing_sends_nothing(): class Broken(Audit): def begin(self, **f): raise RuntimeError("disk full") fake = FakeMiniMateClient(monitor_states=[False]) with pytest.raises(AuditUnavailable): access3(fake, audit=Broken()).start_monitoring(TCP3, "BE18193") assert fake.writes == [] def test_series3_lost_ack_with_unreadable_follow_up_raises_and_is_not_retried(): fake = FakeMiniMateClient(monitor_states=[False], write_error=mmp_proto.TimeoutError("no ack")) da = access3(fake) real = fake.get_monitor_status n = [] def second_fails(): n.append(1) if len(n) > 1: raise mmp_proto.TimeoutError("still quiet") return real() fake.get_monitor_status = second_fails with pytest.raises(ChangeUnconfirmed) as e: da.start_monitoring(TCP3, "BE18193") row = unconfirmed(e, da, sent="unknown", status=504) assert fake.writes == ["start_monitoring"] assert len(da.factory_calls) == 1 # no second TCP attempt assert row["outcome"] == "failed" # The other Series-3 operations still retry once over TCP on a cold unit: # tests/test_device_access_s3.py::test_a_cold_unit_over_tcp_gets_one_retry. # ── final fix wave: after-send honesty, the audit row, pre-send ring, S3 states ── from sfm.audit import DbAudit # noqa: E402 from sfm.database import SeismoDb # noqa: E402 def test_a_lost_stop_ack_then_a_call_home_says_whether_it_stopped_is_unknown(): fake = FakeMicromateClient(run_states=[0x02, 0x03], execute_error=mm_proto.TimeoutError("no ack")) da = access(fake) with pytest.raises(ChangeUnconfirmed) as e: da.stop_monitoring(ADDR, "UM20147") unconfirmed(e, da, sent="unknown", status=503) assert str(e.value).startswith("stop monitoring was sent but the acknowledgement was lost") assert "whether it stopped is unknown" in str(e.value) assert released(fake, da) def test_a_ring_on_a_read_back_poll_is_unconfirmed_and_releases_the_line(): fake = FakeMicromateClient(run_states=[0x00]) da = access(fake) orig, n = fake.read_run_state, [] def ringing(): n.append(1) if len(n) == 2: # the first read-back poll raise RingDetected("RADIO RING") return orig() fake.read_run_state = ringing with pytest.raises(ChangeUnconfirmed) as e: da.start_monitoring(ADDR, "UM20147") row = unconfirmed(e, da, sent="acknowledged", status=503) assert "hung up so the call can reach THOR" in str(e.value) assert len(fake.executed) == 1 assert (row["outcome"], row["verified"], row["sent"]) == ("sent", "not_checked", 1) assert row["ack"] is not None and "call-home began" in row["error"] assert released(fake, da) def test_a_ring_already_waiting_before_the_send_sends_nothing(): fake = FakeMicromateClient(run_states=[0x00]) def buffered_ring(): fake.calls.append("read_unsolicited") raise RingDetected("RADIO RING") fake.read_unsolicited = buffered_ring da = access(fake) with pytest.raises(CallHomeInProgress) as e: da.start_monitoring(ADDR, "UM20147") assert not isinstance(e.value, ChangeUnconfirmed) assert fake.executed == [] (row,) = da._audit.rows.values() assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "not_checked", 0) assert row["error"] == "a call-home began before sending -- nothing sent" assert released(fake, da) def test_the_pre_send_drain_runs_after_the_state_read_and_before_the_send(): fake = FakeMicromateClient(run_states=[0x00, 0x02]) access(fake).start_monitoring(ADDR, "UM20147") assert fake.calls.index("read_unsolicited") > fake.calls.index("read_run_state") assert fake.calls.index("read_unsolicited") < fake.calls.index("execute") def test_a_skip_does_not_drain_the_line(): fake = FakeMicromateClient(run_states=[0x02]) access(fake).start_monitoring(ADDR, "UM20147") assert "read_unsolicited" not in fake.calls def test_a_link_fault_on_the_pre_send_drain_sends_nothing_and_finishes_the_row(): fake = FakeMicromateClient(run_states=[0x00]) def dead(): raise OSError("connection reset") fake.read_unsolicited = dead da = access(fake) with pytest.raises(ConnectFailed): da.start_monitoring(ADDR, "UM20147") assert fake.executed == [] (row,) = da._audit.rows.values() assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "not_checked", 0) assert "nothing sent" in row["error"] assert released(fake, da) class FinishFails(Audit): def finish(self, cid, **f): raise OSError("disk full") def test_a_finish_that_fails_after_a_verified_send_is_audit_incomplete_and_keeps_the_line(): fake = FakeMicromateClient(run_states=[0x00, 0x02]) da = access(fake, audit=FinishFails()) with pytest.raises(AuditIncomplete) as e: da.start_monitoring(ADDR, "UM20147") assert e.value.http_status == 500 assert "start monitoring was sent and verified" in str(e.value) assert "audit record c1 could not be finished: disk full" in str(e.value) assert len(fake.executed) == 1 assert fake.is_open() is True and da.held_serial(ADDR) == "UM20147" def test_a_finish_that_fails_on_a_skip_says_nothing_was_sent(): fake = FakeMicromateClient(run_states=[0x02]) with pytest.raises(AuditIncomplete, match="nothing was sent .*already monitoring"): access(fake, audit=FinishFails()).start_monitoring(ADDR, "UM20147") assert fake.executed == [] def test_a_finish_that_fails_while_unconfirmed_keeps_the_unit_outcome(): fake = FakeMicromateClient(run_states=[0x00], execute_error=RingDetected("RADIO RING")) with pytest.raises(AuditIncomplete) as e: access(fake, audit=FinishFails()).start_monitoring(ADDR, "UM20147") assert "start monitoring was sent" in str(e.value) assert "whether it started is unknown" in str(e.value) assert "could not be finished: disk full" in str(e.value) def test_even_if_already_notes_that_the_read_back_proves_nothing(): fake = FakeMicromateClient(run_states=[0x02]) da = access(fake) r = da.start_monitoring(ADDR, "UM20147", even_if_already=True) note = ("the unit was already monitoring before sending; the read-back cannot show " "that this send changed anything") assert (r.outcome, r.verified) == ("sent", "ok") assert r.detail["note"] == note assert da._audit.rows[r.audit_id]["error"] == note def test_without_even_if_already_there_is_no_note(): fake = FakeMicromateClient(run_states=[0x00, 0x02]) da = access(fake) r = da.start_monitoring(ADDR, "UM20147") assert "note" not in r.detail and da._audit.rows[r.audit_id]["error"] is None # -- the audit row records whether a frame went out, and the states, in the real DB def db_access(fake, tmp_path): db = SeismoDb(tmp_path / "s.db") da = access(fake, audit=DbAudit(lambda: db)) return da, db def test_db_row_for_a_skip_says_nothing_was_sent(tmp_path): da, db = db_access(FakeMicromateClient(run_states=[0x02]), tmp_path) da.start_monitoring(ADDR, "UM20147") (row,) = db.query_device_commands() assert (row["outcome"], row["sent"]) == ("skipped", 0) assert row["states"] == {"before": "monitoring", "seen": ["monitoring"], "after": None} def test_db_row_for_a_verified_send(tmp_path): da, db = db_access(FakeMicromateClient(run_states=[0x00, 0x00, 0x02]), tmp_path) da.start_monitoring(ADDR, "UM20147") (row,) = db.query_device_commands() assert (row["outcome"], row["verified"], row["sent"]) == ("sent", "ok", 1) assert row["states"] == {"before": "idle", "seen": ["idle", "idle", "monitoring"], "after": "monitoring"} def test_db_row_for_a_mismatch(tmp_path): da, db = db_access(FakeMicromateClient(run_states=[0x00]), tmp_path) da.start_monitoring(ADDR, "UM20147") (row,) = db.query_device_commands() assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "mismatch", 1) assert row["states"] == {"before": "idle", "seen": ["idle"] * 4, "after": "idle"} def test_db_row_for_a_lost_ack_with_a_readable_follow_up(tmp_path): fake = FakeMicromateClient(run_states=[0x00, 0x02], execute_error=mm_proto.TimeoutError("no ack")) da, db = db_access(fake, tmp_path) da.start_monitoring(ADDR, "UM20147") (row,) = db.query_device_commands() assert (row["outcome"], row["sent"]) == ("failed", None) assert row["states"] == {"before": "idle", "seen": ["idle"], "after": "monitoring"} def test_db_row_for_a_read_back_failure(tmp_path): fake = FakeMicromateClient(run_states=[0x00]) orig, n = fake.read_run_state, [] def flaky(): n.append(1) if len(n) == 3: # the second read-back poll raise mm_proto.TimeoutError("dropped") return orig() fake.read_run_state = flaky da, db = db_access(fake, tmp_path) with pytest.raises(ChangeUnconfirmed) as e: da.start_monitoring(ADDR, "UM20147") (row,) = db.query_device_commands() assert e.value.audit_id == row["id"] assert (row["outcome"], row["verified"], row["sent"]) == ("sent", "not_checked", 1) assert row["states"] == {"before": "idle", "seen": ["idle", "idle"], "after": "idle"} def test_db_row_for_a_pre_send_ring_says_nothing_was_sent(tmp_path): fake = FakeMicromateClient(run_states=[0x00]) def buffered_ring(): raise RingDetected("RADIO RING") fake.read_unsolicited = buffered_ring da, db = db_access(fake, tmp_path) with pytest.raises(CallHomeInProgress): da.start_monitoring(ADDR, "UM20147") (row,) = db.query_device_commands() assert (row["outcome"], row["sent"]) == ("failed", 0) # -- Series 3: the raw state byte, never collapsed into "idle" ---------------------- def test_series3_an_unmeasured_state_byte_is_refused_with_nothing_written(): fake = FakeMiniMateClient(monitor_states=[0x07]) da = access3(fake) with pytest.raises(UnitStateUnknown, match="0x07"): da.start_monitoring(TCP3, "BE18193") assert fake.writes == [] and da._audit.rows == {} @pytest.mark.parametrize("flag,state", [(0x00, "idle"), (0x10, "monitoring"), (0x07, "unknown(0x07)"), (None, "unknown(short)")]) def test_series3_state_names_come_from_the_raw_flag(flag, state): fake = FakeMiniMateClient(monitor_states=[flag]) r = access3(fake).start_monitoring(TCP3, "BE18193", dry_run=True) assert r.state_before == state @pytest.mark.parametrize("flag,monitoring", [(0x00, False), (0x10, True), (0x0B, True), (0x07, None)]) def test_series3_status_shows_the_change_paths_reading(flag, monitoring): # 0x0B: BE9441 recording a histogram (2026-10-26) once showed "not monitoring" st = access3(FakeMiniMateClient(monitor_states=[flag])).status(TCP3, "BE18193") assert st.monitoring is monitoring def test_series3_monitor_status_decode_keeps_the_raw_flag(): from minimateplus.client import _decode_monitor_status tail = bytes.fromhex("02a8000effc0000e9e52") # battery + memory: the last 10 bytes for flag, monitoring in ((0x00, False), (0x10, True), (0x0B, True), (0x07, False)): st = _decode_monitor_status(bytes(11) + bytes([0x00, flag]) + bytes(34) + tail) 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 # -- Series 3: a monitoring unit answers only after the wake ---------------------- def test_series3_wakes_the_unit_before_every_state_read(): # BE9441, 2026-10-26 23:41: the start was acked, then one bare 0x1C read got # nothing for 120 s -- a monitoring unit ignores everything until SESSION_RESET # + POLL (measured 2026-04-08), which only the connect had sent. fake = FakeMiniMateClient(monitor_states=[False, True]) r = access3(fake).start_monitoring(TCP3, "BE18193") assert r.outcome == "sent" and r.verified == "ok" after = fake.calls[fake.calls.index("start_monitoring") + 1:] reads = [i for i, c in enumerate(after) if c == "get_monitor_status"] assert reads and all(after[i - 1] == "wake" for i in reads) def test_series3_a_start_waits_out_the_sensor_check_before_its_first_read(): # Brian (2026-10-26): every unit runs a ~30 s sensor check before # "Recording..."; a stop's read-back needs no such wait. from sfm.device_access.s3 import S3_SENSOR_CHECK_S for start, waited in ((True, True), (False, False)): slept = [] fake = FakeMiniMateClient(monitor_states=[not start, start]) da = access3(fake, sleep=slept.append) (da.start_monitoring if start else da.stop_monitoring)(TCP3, "BE18193") assert (S3_SENSOR_CHECK_S in slept) is waited