From 01b9188f2500a84ba87a5aca80dc4927abee69b9 Mon Sep 17 00:00:00 2001 From: serversdown Date: Wed, 21 Oct 2026 17:38:34 -0400 Subject: [PATCH] fix(sfm): a stale Series-3 id is refused before the full download, not after Series3Adapter.download_event compared the timestamp only after download_event_by_key had run the whole 5A. A stale id cost a full download of the wrong event (minutes on cellular), could surface the 64 KB-page 502 instead of 409, and a lost 0C reply was reported as "the unit was erased". - get_events() gains only_key_timestamp: with only_key, if the target's 0C says another time (or none), the target takes the existing bypass -- no 1F(arm), no POLL, no 5A. A new branch only; it adds no command. - download_event_by_key(key4, *, expected_timestamp=None) passes it on. - The adapter converts the id's stamp to that ISO form and checks, in order: no event -> 404; no readable 0C timestamp -> 502 MalformedReply ("could not read ... record (0C)"); a different time -> 409 StaleEvent; no frames -> 502. - The fake's download mirrors the real walk (no frames on a mismatch) and records what it was asked for. - Legacy get_events() (none of the new options) is pinned by a test of its exact call sequence and 5A arguments, written before the change. Read-only; nothing new on the wire. No codec, store or DB change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- minimateplus/client.py | 26 ++++++++-- sfm/device_access/s3.py | 11 +++- tests/device_access_fakes.py | 21 +++++++- tests/test_device_access_s3_events.py | 22 ++++++-- tests/test_minimate_event_headers.py | 73 +++++++++++++++++++++++++-- 5 files changed, 141 insertions(+), 12 deletions(-) diff --git a/minimateplus/client.py b/minimateplus/client.py index 9a40328..e0755fd 100644 --- a/minimateplus/client.py +++ b/minimateplus/client.py @@ -450,7 +450,7 @@ class MiniMateClient: proto.confirm_erase_all() log.info("delete_all_events: erase confirmed — device memory cleared") - def get_events(self, full_waveform: bool = False, debug: bool = False, stop_after_index: Optional[int] = None, skip_waveform_for_keys: Optional[set] = None, skip_waveform_for_events: Optional[dict] = None, extra_chunks_after_metadata: int = 1, headers_only: bool = False, only_key: Optional[bytes] = None) -> list[Event]: + def get_events(self, full_waveform: bool = False, debug: bool = False, stop_after_index: Optional[int] = None, skip_waveform_for_keys: Optional[set] = None, skip_waveform_for_events: Optional[dict] = None, extra_chunks_after_metadata: int = 1, headers_only: bool = False, only_key: Optional[bytes] = None, only_key_timestamp: Optional[str] = None) -> list[Event]: """ Download all stored events from the device using the confirmed 1E → 0A → 0C → 5A → 1F event-iterator protocol. @@ -483,6 +483,11 @@ class MiniMateClient: only_key: download only the event with this key (in full, per full_waveform); walk the others without their 5A, and stop once that event is read. + only_key_timestamp: with only_key, the ISO timestamp (as + `_event_timestamp_iso` formats it, e.g. "2026-10-01T08:00:00") the + event was listed with. If the 0C at only_key says another time, or + gave none, that event is returned without its 5A -- 1F(arm), POLL + and 5A are not sent -- and the caller reports which. """ proto = self._require_proto() @@ -586,6 +591,14 @@ class MiniMateClient: # read; 1F(arm) + POLL + 5A are not sent, and 1F(browse) below is # safe because no 5A was ever started. skip_5a = True + elif (only_key is not None and only_key_timestamp is not None + and actual_ts != only_key_timestamp): + # The event at this key is not the one asked for -- erased or + # wrapped since it was listed, or its 0C reply was lost. Do + # not download it; the caller reports which. + log.info("get_events: key=%s is from %r, not %r -- no 5A", + cur_key.hex(), actual_ts, only_key_timestamp) + skip_5a = True arm_key4: Optional[bytes] = None a5_ok = False @@ -765,14 +778,21 @@ class MiniMateClient: """ return self.get_events(headers_only=True) - def download_event_by_key(self, key4: bytes) -> Optional[Event]: + def download_event_by_key(self, key4: bytes, *, expected_timestamp: Optional[str] = None) -> Optional[Event]: """Download ONE event in full; walk past the events before it without their 5A. None if no full record has that key. `get_events(stop_after_index=N)` downloads events 0..N in full and keeps one; this downloads only the one asked for. + + `expected_timestamp` (ISO, as `_event_timestamp_iso` writes it): the + time the event was listed with. If the 0C read at that key says + otherwise -- or could not be read -- the event comes back without its + 5A (`_a5_frames` None) and nothing is downloaded; the caller compares + the timestamp and says which. """ - for ev in self.get_events(full_waveform=True, only_key=key4): + for ev in self.get_events(full_waveform=True, only_key=key4, + only_key_timestamp=expected_timestamp): if ev._waveform_key == key4: return ev return None diff --git a/sfm/device_access/s3.py b/sfm/device_access/s3.py index 2c74b14..3d0c75b 100644 --- a/sfm/device_access/s3.py +++ b/sfm/device_access/s3.py @@ -176,11 +176,16 @@ class Series3Adapter: def download_event(self, address: UnitAddress, serial: str, key: bytes, stamp: Optional[str]) -> DownloadedEvent: + # The walk compares this with the target's 0C and, on a mismatch, sends + # no 5A: a stale id costs a header walk, not a full download of the + # wrong event. + iso = datetime.datetime.strptime(stamp, "%Y%m%d%H%M%S").isoformat() if stamp is not None else None + def op(client: Any) -> DownloadedEvent: info = client.connect() self._check(info.serial, serial, address) try: - ev = client.download_event_by_key(key) + ev = client.download_event_by_key(key, expected_timestamp=iso) except struct.error as exc: # Inferred, not measured here: the known 5A page bug. An event past the unit's # first 64 KB drives TERM's offset negative, and struct.pack rejects it @@ -192,6 +197,10 @@ class Series3Adapter: if ev is None: raise EventNotFound(f"no event {key.hex()} on {serial} -- list the events again") found = stamp_of(_s3_dt(ev)) + if stamp is not None and found is None: + raise MalformedReply( + f"could not read event {key.hex()}'s record (0C) to confirm it is the one " + "listed -- not downloaded; try again") if stamp is not None and found != stamp: raise StaleEvent( f"the event at {key.hex()} on {serial} is from {found}, not {stamp} -- " diff --git a/tests/device_access_fakes.py b/tests/device_access_fakes.py index 5c87a2d..ec71271 100644 --- a/tests/device_access_fakes.py +++ b/tests/device_access_fakes.py @@ -57,6 +57,15 @@ def s3_event(index, key_hex, when, *, record_type="Waveform", pvs=0.12, frames=T return ev +def _iso(ev): + """minimateplus.client._event_timestamp_iso's format; "" with no timestamp.""" + ts = ev.timestamp + if ts is None: + return "" + return datetime.datetime(ts.year, ts.month, ts.day, ts.hour or 0, ts.minute or 0, + ts.second or 0).isoformat() + + def default_s3_events(): return [ s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)), @@ -78,6 +87,8 @@ class FakeMiniMateClient(_Base): ) self.compliance = compliance self.events = default_s3_events() if events is None else events + self.download_requests: list = [] # (key4, expected_timestamp) per download + self.last_download = None def connect(self) -> DeviceInfo: self._step("connect") @@ -107,10 +118,18 @@ class FakeMiniMateClient(_Base): out.append(h) return out - def download_event_by_key(self, key4): + def download_event_by_key(self, key4, *, expected_timestamp=None): + """As the real walk: an event whose 0C time is not the expected one comes + back without its 5A.""" self._step("download_event_by_key") + self.download_requests.append((key4, expected_timestamp)) + self.last_download = None for ev in self.events: if ev._waveform_key == key4: + if expected_timestamp is not None and _iso(ev) != expected_timestamp: + ev = copy.copy(ev) + ev._a5_frames = None + self.last_download = ev return ev return None diff --git a/tests/test_device_access_s3_events.py b/tests/test_device_access_s3_events.py index eb6cf87..febcdf5 100644 --- a/tests/test_device_access_s3_events.py +++ b/tests/test_device_access_s3_events.py @@ -80,13 +80,29 @@ def test_a_key_that_is_not_stored_is_404(): def test_a_stale_id_is_refused_rather_than_downloading_another_event(): + fake = FakeMiniMateClient() with pytest.raises(StaleEvent, match="20261001080000"): - adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", FIRST, "20250101000000") + adapter(fake).download_event(TCP, "BE18193", FIRST, "20250101000000") + # The walk was told what to expect, so it compared after 0C and sent no 5A. + assert fake.download_requests == [(FIRST, "2025-01-01T00:00:00")] + assert fake.last_download is not None and fake.last_download._a5_frames is None def test_an_id_without_a_timestamp_skips_the_check(): - dl = adapter(FakeMiniMateClient()).download_event(TCP, "BE18193", FIRST, None) + fake = FakeMiniMateClient() + dl = adapter(fake).download_event(TCP, "BE18193", FIRST, None) assert dl.event_id == "BE18193:01110000:20261001080000" + assert fake.download_requests == [(FIRST, None)] + + +def test_a_target_whose_record_could_not_be_read_is_not_called_stale(): + # A lost 0C reply leaves no timestamp to compare: that is a bad reply, not an erase. + ev = s3_event(0, "01110000", datetime.datetime(2026, 10, 1, 8, 0, 0)) + ev.timestamp = None + fake = FakeMiniMateClient(events=[ev]) + with pytest.raises(MalformedReply, match="0C"): + adapter(fake).download_event(TCP, "BE18193", FIRST, "20261001080000") + assert fake.last_download._a5_frames is None def test_a_failed_5a_is_a_clear_error(): @@ -99,7 +115,7 @@ def test_a_failed_5a_is_a_clear_error(): def test_the_64k_page_bug_is_named_not_a_bare_500(): fake = FakeMiniMateClient() - def boom(key4): + def boom(key4, **kw): raise struct.error("argument out of range") fake.download_event_by_key = boom with pytest.raises(MalformedReply, match="64 KB"): diff --git a/tests/test_minimate_event_headers.py b/tests/test_minimate_event_headers.py index fee5322..9bdd0fe 100644 --- a/tests/test_minimate_event_headers.py +++ b/tests/test_minimate_event_headers.py @@ -22,13 +22,27 @@ STAMPS = { class FakeProto: - """Records every call; serves a three-event chain the way the unit does.""" + """Records every call; serves a three-event chain the way the unit does. - def __init__(self, keys=KEYS, partial=()): + `fail` injects lost replies: {(name, n): exc} raises exc on the n-th call + (1-based) of that name, after the call is recorded -- the request went out + and its reply never came. Names: "1E", "0A", "0C", "1F-browse", "1F-arm", + "POLL", "5A". With no `fail`, nothing changes. + """ + + def __init__(self, keys=KEYS, partial=(), fail=None): self.keys = list(keys) self.partial = set(partial) + self.fail = dict(fail or {}) self.calls: list[tuple] = [] self._pos = 0 + self._counts: dict[str, int] = {} + + def _maybe_fail(self, name): + n = self._counts[name] = self._counts.get(name, 0) + 1 + exc = self.fail.get((name, n)) + if exc is not None: + raise exc def _entry(self, i): if i >= len(self.keys): @@ -37,20 +51,24 @@ class FakeProto: def read_event_first(self, token=0): self.calls.append(("1E", token)) + self._maybe_fail("1E") if token == 0: self._pos = 0 return self._entry(self._pos) def read_waveform_header(self, key4): self.calls.append(("0A", key4)) + self._maybe_fail("0A") return b"", (0x2C if key4 in self.partial else 0x46) def read_waveform_record(self, key4): self.calls.append(("0C", key4)) + self._maybe_fail("0C") return key4 # decoded by the patched decoder below def advance_event(self, browse=False): self.calls.append(("1F", "browse" if browse else "arm")) + self._maybe_fail("1F-browse" if browse else "1F-arm") if browse: self._pos += 1 return self._entry(self._pos) @@ -58,9 +76,11 @@ class FakeProto: def poll(self): self.calls.append(("POLL",)) + self._maybe_fail("POLL") def read_bulk_waveform_stream(self, key4, **kw): - self.calls.append(("5A", key4)) + self.calls.append(("5A", key4, tuple(sorted(kw.items())))) + self._maybe_fail("5A") return ["frame"] @@ -110,7 +130,7 @@ def test_downloading_one_event_starts_exactly_one_5a(client): proto = FakeProto() ev = client(proto).download_event_by_key(KEYS[1]) assert ev is not None and ev._waveform_key == KEYS[1] - assert [c for c in proto.calls if c[0] == "5A"] == [("5A", KEYS[1])] + assert [c[:2] for c in proto.calls if c[0] == "5A"] == [("5A", KEYS[1])] assert ev._a5_frames == ["frame"] @@ -135,3 +155,48 @@ def test_a_partial_record_is_skipped_by_both(client): events = client(FakeProto(partial={KEYS[1]})).list_event_headers() assert [e._waveform_key for e in events] == [KEYS[0], KEYS[2]] assert client(FakeProto(partial={KEYS[1]})).download_event_by_key(KEYS[1]) is None + + +# ── the legacy walk, pinned: any call passing none of the new options ───────── + +_LEGACY_PER_EVENT = ["0A", "1E", "0C", "1F", "POLL", "POLL", "POLL", "5A", "1F"] + + +@pytest.mark.parametrize("full", [False, True]) +def test_legacy_get_events_sends_exactly_what_it_always_sent(client, full): + proto = FakeProto() + events = client(proto).get_events(full_waveform=full) + assert [e._waveform_key for e in events] == KEYS + assert _subs(proto) == ["1E"] + _LEGACY_PER_EVENT * len(KEYS) + mode = ({"include_terminator": True, "max_chunks": 128, "stop_after_metadata": False} if full else + {"extra_chunks_after_metadata": 1, "include_terminator": True, "max_chunks": 128, + "stop_after_metadata": True}) + assert [c for c in proto.calls if c[0] == "5A"] == [("5A", k, tuple(sorted(mode.items()))) + for k in KEYS] + assert [c for c in proto.calls if c[0] == "1F"] == [("1F", "arm"), ("1F", "browse")] * len(KEYS) + assert all(e._a5_frames == ["frame"] for e in events) + + +# ── a stale id: the target's 0C says another time, so no 5A goes out ────────── + +def test_a_target_from_another_time_gets_no_5a(client): + proto = FakeProto() + ev = client(proto).download_event_by_key(KEYS[1], expected_timestamp="2025-01-01T00:00:00") + assert [c for c in proto.calls if c[0] == "5A"] == [] + assert ("1F", "arm") not in proto.calls and ("POLL",) not in proto.calls + assert ev is not None and ev._waveform_key == KEYS[1] and ev._a5_frames is None + + +def test_the_target_at_its_listed_time_gets_exactly_one_5a(client): + proto = FakeProto() + ev = client(proto).download_event_by_key(KEYS[1], expected_timestamp="2026-10-02T09:30:15") + assert [c[:2] for c in proto.calls if c[0] == "5A"] == [("5A", KEYS[1])] + assert ev._a5_frames == ["frame"] + + +def test_a_target_whose_0c_reply_was_lost_gets_no_5a(client): + from minimateplus.protocol import TimeoutError as MMTimeout + proto = FakeProto(fail={("0C", 2): MMTimeout("0C lost")}) + ev = client(proto).download_event_by_key(KEYS[1], expected_timestamp="2026-10-02T09:30:15") + assert [c for c in proto.calls if c[0] == "5A"] == [] + assert ev is not None and ev.timestamp is None and ev._a5_frames is None