Files
seismo-relay/tests/test_minimate_event_headers.py
serversdownandClaude Opus 5.5 59dff06f1c fix(sfm): the Series-3 header walk fails loudly, and listing uses the normal timeout
One lost 1F reply made the list return 1 of 3 events as a 200, and on a
download gave a false 404.  The list also ran on the 120 s download
timeout, so each lost reply stalled the walk 120 s with the unit locked.

- get_events() strict mode (headers_only, or only_key): a lost 0A reply,
  a lost 1F(browse) reply on the success path and on the partial-record
  path all re-raise their ProtocolError; a 1F that hands back a key
  already walked raises ProtocolError("event chain did not advance ...").
  Legacy calls (none of the new options) behave exactly as before --
  pinned by tests of the same three faults under get_events().
- Series3Adapter.list_events runs on the default timeout (10 s on TCP);
  download_event keeps 120 s.
- FakeProto gains optional lost-reply injection; its default is unchanged.

The repeat-key guard sits at the loop head, which is reached only for a
non-null key -- equivalent to checking each 1F's key, in one place.

Read-only; nothing new on the wire.  No codec, store or DB change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-21 17:39:54 -04:00

270 lines
11 KiB
Python

"""MiniMateClient's header-only walk: list without 5A, download one without the rest."""
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 minimateplus.client as mc # noqa: E402
from minimateplus.client import MiniMateClient # noqa: E402
from minimateplus.models import Timestamp # noqa: E402
from minimateplus.protocol import ProtocolError # noqa: E402
END = b"\x00" * 8
KEYS = [bytes.fromhex(k) for k in ("01110000", "0111245a", "01114290")]
STAMPS = {
KEYS[0]: (2026, 10, 1, 8, 0, 0),
KEYS[1]: (2026, 10, 2, 9, 30, 15),
KEYS[2]: (2026, 10, 3, 17, 45, 59),
}
class FakeProto:
"""Records every call; serves a three-event chain the way the unit does.
`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):
return b"\x00\x00\x00\x00", END
return self.keys[i], self.keys[i] + b"\x00\x00\x00\x46"
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)
return self._entry(self._pos + 1)
def poll(self):
self.calls.append(("POLL",))
self._maybe_fail("POLL")
def read_bulk_waveform_stream(self, key4, **kw):
self.calls.append(("5A", key4, tuple(sorted(kw.items()))))
self._maybe_fail("5A")
return ["frame"]
@pytest.fixture
def client(monkeypatch):
def decode_record(record, ev):
y, mo, d, h, mi, s = STAMPS[record]
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=y, unknown_byte=0,
month=mo, day=d, hour=h, minute=mi, second=s)
ev.record_type = "Waveform"
monkeypatch.setattr(mc, "_decode_waveform_record_into", decode_record)
monkeypatch.setattr(mc, "_decode_a5_metadata_into", lambda frames, ev: None)
monkeypatch.setattr(mc, "_decode_a5_waveform", lambda frames, ev: None)
def make(proto):
c = MiniMateClient(port="/dev/null")
c._proto = proto
return c
return make
def _subs(proto):
return [c[0] for c in proto.calls]
def test_listing_headers_never_starts_a_5a(client):
proto = FakeProto()
events = client(proto).list_event_headers()
assert [e._waveform_key for e in events] == KEYS
assert "5A" not in _subs(proto) and "POLL" not in _subs(proto)
assert ("1F", "arm") not in proto.calls
assert all(e._a5_frames is None for e in events)
def test_listing_headers_sends_only_the_commands_get_events_already_sends(client):
proto = FakeProto()
client(proto).list_event_headers()
assert _subs(proto) == ["1E"] + ["0A", "1E", "0C", "1F"] * len(KEYS)
def test_listed_events_carry_their_timestamps(client):
events = client(FakeProto()).list_event_headers()
assert (events[1].timestamp.day, events[1].timestamp.second) == (2, 15)
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[:2] for c in proto.calls if c[0] == "5A"] == [("5A", KEYS[1])]
assert ev._a5_frames == ["frame"]
def test_downloading_one_event_stops_once_it_has_it(client):
proto = FakeProto()
client(proto).download_event_by_key(KEYS[1])
assert ("0A", KEYS[2]) not in proto.calls
def test_the_events_before_it_are_walked_without_their_5a(client):
proto = FakeProto()
client(proto).download_event_by_key(KEYS[2])
assert [c[1] for c in proto.calls if c[0] == "5A"] == [KEYS[2]]
assert proto.calls.count(("1F", "arm")) == 1
def test_a_key_that_is_not_stored_returns_none(client):
assert client(FakeProto()).download_event_by_key(bytes.fromhex("0111ffff")) is None
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
# ── the strict walk: listing and one-event download fail loudly ───────────────
# A lost reply must not become a short list (200) or a false 404.
def test_a_lost_1f_reply_fails_the_list_rather_than_shortening_it(client):
lost = ProtocolError("no reply to 1F")
with pytest.raises(ProtocolError) as ei:
client(FakeProto(fail={("1F-browse", 2): lost})).list_event_headers()
assert ei.value is lost
def test_a_lost_1f_reply_fails_the_download_rather_than_reporting_no_event(client):
lost = ProtocolError("no reply to 1F")
proto = FakeProto(fail={("1F-browse", 2): lost})
with pytest.raises(ProtocolError) as ei:
client(proto).download_event_by_key(KEYS[2])
assert ei.value is lost
assert [c for c in proto.calls if c[0] == "5A"] == []
@pytest.mark.parametrize("walk", ["list", "download"])
def test_a_lost_0a_reply_fails_the_walk(client, walk):
lost = ProtocolError("no reply to 0A")
c = client(FakeProto(fail={("0A", 2): lost}))
with pytest.raises(ProtocolError) as ei:
c.list_event_headers() if walk == "list" else c.download_event_by_key(KEYS[2])
assert ei.value is lost
def test_a_lost_1f_reply_after_a_partial_record_fails_the_list(client):
lost = ProtocolError("no reply to 1F")
with pytest.raises(ProtocolError) as ei:
client(FakeProto(partial={KEYS[1]}, fail={("1F-browse", 2): lost})).list_event_headers()
assert ei.value is lost
@pytest.mark.parametrize("walk", ["list", "download"])
def test_a_chain_that_does_not_advance_fails_the_walk(client, walk):
proto = FakeProto(keys=[KEYS[0], KEYS[1], KEYS[0]])
c = client(proto)
with pytest.raises(ProtocolError, match="did not advance.*01110000"):
c.list_event_headers() if walk == "list" else c.download_event_by_key(KEYS[2])
assert proto.calls.count(("0A", KEYS[0])) == 1 # stopped before re-reading it
# ── ... while legacy get_events() keeps doing exactly what it did ────────────
def test_legacy_get_events_still_returns_what_it_read_when_a_1f_reply_is_lost(client):
proto = FakeProto(fail={("1F-browse", 2): ProtocolError("no reply to 1F")})
events = client(proto).get_events()
assert [e._waveform_key for e in events] == KEYS[:2]
assert _subs(proto) == ["1E"] + _LEGACY_PER_EVENT * 2
def test_legacy_get_events_still_skips_an_event_whose_0a_reply_is_lost(client):
proto = FakeProto(fail={("0A", 2): ProtocolError("no reply to 0A")})
events = client(proto).get_events()
assert [e._waveform_key for e in events] == [KEYS[0], KEYS[2]]
assert _subs(proto) == ["1E"] + _LEGACY_PER_EVENT + ["0A", "1F"] + _LEGACY_PER_EVENT
def test_legacy_get_events_still_walks_a_repeated_key(client):
proto = FakeProto(keys=[KEYS[0], KEYS[1], KEYS[0]])
events = client(proto).get_events()
assert [e._waveform_key for e in events] == [KEYS[0], KEYS[1], KEYS[0]]