fix(minimateplus): the boot-aware first POLL resets the parser; a drained or long-trailed banner is seen

Review of d73a27d: _await_poll_or_boot no longer reset the parser and pending
frames the way _recv_one(reset_parser=True) did, so a reused protocol object
with half a frame left over failed startup (UnexpectedResponse A4 vs A5).
Restored.  Also: the banner check now runs before the tail is trimmed (a read
carrying >48 bytes after the banner lost it), and a banner caught during the
200 ms drain is reported, so startup goes straight to the re-poll loop instead
of the full timeout.  Tests for all three.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-25 18:43:49 -04:00
1 parent 151782365b
commit f6166b4b04
2 files changed
+52 -6

No files matched your search

+22 -4
View File
@@ -212,7 +212,7 @@ class MiniMateProtocol:
ProtocolError: if either POLL step fails. ProtocolError: if either POLL step fails.
""" """
log.debug("startup: draining boot string") log.debug("startup: draining boot string")
self._drain_boot_string() booting = self._drain_boot_string()
# Send session-reset signal (ACK+ETX) before the first POLL probe. # Send session-reset signal (ACK+ETX) before the first POLL probe.
# Confirmed from 4-8-26 BW TX captures: Blastware always sends this # Confirmed from 4-8-26 BW TX captures: Blastware always sends this
@@ -223,7 +223,15 @@ class MiniMateProtocol:
log.debug("startup: POLL probe") log.debug("startup: POLL probe")
self._send(POLL_PROBE) self._send(POLL_PROBE)
probe_rsp = self._await_poll_or_boot(self._recv_timeout) try:
# A banner already drained means the unit is booting: a short wait,
# then the re-poll loop, rather than the full timeout.
probe_rsp = self._await_poll_or_boot(
self._BOOT_POLL_S if booting else self._recv_timeout)
except TimeoutError:
if not booting:
raise
probe_rsp = None
if probe_rsp is None: if probe_rsp is None:
probe_rsp = self._poll_until_booted() probe_rsp = self._poll_until_booted()
log.debug( log.debug(
@@ -1581,6 +1589,8 @@ class MiniMateProtocol:
"""The first POLL probe's reply -- or None the moment the unit sends its """The first POLL probe's reply -- or None the moment the unit sends its
boot banner, because a POLL sent before the banner is never answered.""" boot banner, because a POLL sent before the banner is never answered."""
expected = _expected_rsp_sub(SUB_POLL) expected = _expected_rsp_sub(SUB_POLL)
self._parser.reset() # as _recv_one(reset_parser=True) did here
self._pending_frames.clear()
deadline = time.monotonic() + timeout deadline = time.monotonic() + timeout
tail = b"" tail = b""
while time.monotonic() < deadline: while time.monotonic() < deadline:
@@ -1594,9 +1604,10 @@ class MiniMateProtocol:
self._pending_frames.extend(frames[1:]) self._pending_frames.extend(frames[1:])
self._validate_frame(frames[0], expected) self._validate_frame(frames[0], expected)
return frames[0] return frames[0]
tail = (tail + chunk)[-64:] tail += chunk
if self._BOOT_BANNER in tail: if self._BOOT_BANNER in tail:
return None return None
tail = tail[-64:] # trimmed after the check, so a long read keeps it
raise TimeoutError( raise TimeoutError(
f"No S3 frame received within {timeout:.1f}s (expected SUB 0x{expected:02X})") f"No S3 frame received within {timeout:.1f}s (expected SUB 0x{expected:02X})")
@@ -1618,7 +1629,7 @@ class MiniMateProtocol:
f"the unit sent its boot message but did not answer a POLL within " f"the unit sent its boot message but did not answer a POLL within "
f"{self._BOOT_GRACE_S:.0f} s") f"{self._BOOT_GRACE_S:.0f} s")
def _drain_boot_string(self, drain_ms: int = 200) -> None: def _drain_boot_string(self, drain_ms: int = 200) -> bool:
""" """
Read and discard any boot-string bytes ("Operating System") the device Read and discard any boot-string bytes ("Operating System") the device
may send before entering binary protocol mode. may send before entering binary protocol mode.
@@ -1626,14 +1637,21 @@ class MiniMateProtocol:
We simply read with a short timeout and throw the bytes away. The We simply read with a short timeout and throw the bytes away. The
S3FrameParser's IDLE state already handles non-frame bytes gracefully, S3FrameParser's IDLE state already handles non-frame bytes gracefully,
but it's cleaner to drain them explicitly before the first real frame. but it's cleaner to drain them explicitly before the first real frame.
Returns whether the boot banner was among them (the unit is booting).
""" """
deadline = time.monotonic() + (drain_ms / 1000) deadline = time.monotonic() + (drain_ms / 1000)
discarded = 0 discarded = 0
tail, saw_banner = b"", False
while time.monotonic() < deadline: while time.monotonic() < deadline:
chunk = self._transport.read(256) chunk = self._transport.read(256)
if chunk: if chunk:
discarded += len(chunk) discarded += len(chunk)
tail += chunk
saw_banner = saw_banner or self._BOOT_BANNER in tail
tail = tail[-len(self._BOOT_BANNER):] # a banner split across reads still matches
else: else:
time.sleep(0.005) time.sleep(0.005)
if discarded: if discarded:
log.debug("drain_boot_string: discarded %d bytes", discarded) log.debug("drain_boot_string: discarded %d bytes", discarded)
return saw_banner
+30 -2
View File
@@ -33,9 +33,12 @@ class Booting(SessionReplay):
"""Banner instead of an answer to the first POLL; then `deaf` more POLL probes """Banner instead of an answer to the first POLL; then `deaf` more POLL probes
go unanswered (still booting); after that, the recorded session as normal.""" go unanswered (still booting); after that, the recorded session as normal."""
def __init__(self, replies, deaf=2, banner=True): def __init__(self, replies, deaf=2, banner=True, banner_on_open=False, noise_after=0):
super().__init__(replies) super().__init__(replies)
self.deaf, self.banner, self.polls = deaf, banner, 0 self.deaf, self.banner, self.polls = deaf, banner, 0
self.noise_after = noise_after # non-frame bytes sent after the banner
if banner_on_open: # the banner lands inside the drain window
self._buf, self.banner = BANNER, False
def write(self, data): def write(self, data):
data = bytes(data) data = bytes(data)
@@ -43,7 +46,7 @@ class Booting(SessionReplay):
self.polls += 1 self.polls += 1
if self.polls == 1: if self.polls == 1:
if self.banner: if self.banner:
self._buf += BANNER self._buf += BANNER + b"." * self.noise_after
return return
if self.polls <= 1 + self.deaf: if self.polls <= 1 + self.deaf:
return return
@@ -75,3 +78,28 @@ def test_a_silent_unit_without_a_banner_fails_as_before():
connect(t) connect(t)
assert "boot" not in str(e.value) assert "boot" not in str(e.value)
assert t.polls == 1 # no re-polling without the banner assert t.polls == 1 # no re-polling without the banner
def test_startup_on_a_reused_protocol_ignores_leftover_bytes():
replies = recorded_replies()
p = mp.MiniMateProtocol(SessionReplay(replies))
a5 = next(raw for sub, raw in replies if sub == 0xA5)
p._parser.feed(a5[:20]) # half a frame left over from an earlier exchange
assert p.startup().sub == 0xA4
def test_a_banner_followed_by_more_text_in_the_same_read_is_still_seen():
t = Booting(recorded_replies(), deaf=1, noise_after=200)
assert connect(t)[1].serial == "BE9441"
def test_a_banner_caught_while_draining_is_acted_on(monkeypatch):
t_now = [0.0]
def fine(): # fine enough that the 200 ms drain really reads
t_now[0] += 0.01
return t_now[0]
monkeypatch.setattr(mp.time, "monotonic", fine)
t = Booting(recorded_replies(), deaf=1, banner_on_open=True)
assert connect(t)[1].serial == "BE9441"
assert t._buf == b"" # the drain consumed the banner