Files
seismo-relay/tests/test_minimate_5a_strict.py
serversdownandClaude Opus 5.5 8acb9512a9 fix(minimateplus): size the 5A chunk cap from STRT, refuse a misread STRT, TERM only a tail
Follow-ups from the review of 887e75d (verdict: keep, with fixes; no critical).

- The cap: a caller's max_chunks (client.py passes 128) now bounds only a walk
  whose end is unknown.  With STRT it cut every event past ~66 KB short --
  2,545 of 63,500 archived histograms are bigger (the review's count, DL2).
  Strict raised; legacy sent a TERM for most of the event, or a bare ValueError.
- A STRT claiming less than one 0x200 chunk, or more than 4 MiB (a sanity bound,
  not a measured limit), is refused as a misread, in both modes -- once a bare
  ValueError and a 500.
- TERM is sent only for a true tail (< 0x200).  After an early end the legacy
  walk returns what arrived and sends none.
- build_5a_request wraps build_bw_frame; the old 5A helpers are marked
  superseded (kept for tests/test_5a_protocol.py) and their imports dropped.

Tests: all 8 recorded events (were 4) walk exactly as Blastware and rebuild its
own files; an end key holding escaped bytes; a 300 KB event past a 128 cap; both
misread-STRT refusals; the 1A frames BE9441 answered post-fix; the checksum
vectors retargeted.  Mutants the review saw survive (no STRT un-escape; a
standard-request escape revert) and 3 new ones are each caught.

Measured on the way: a reply's checksum is SUM8 of its unescaped payload,
748/748.  The 'S3 checksums frequently fail' note was the parser summing its
own kept escape bytes; noted, parser unchanged.

Docs: the crossing count corrected to four (events 1, 3, 5, 7); the remaining
stale 5A sections in CLAUDE.md annotated; the write-frame suspicion recorded as
inferred only.  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-26 15:16:10 -04:00

135 lines
5.4 KiB
Python

"""A one-event download must not keep an event whose 5A stream ended early.
BE9441 rebooted mid-download at the bench (2026-10-25): the chunk at 0x7D06 got
one stray byte and then silence, the loop logged "unexpected end-of-stream --
proceeding to TERM", the TERM got no reply either, and the short event was
stored as a success. In strict mode (the one-event download) every early end
now raises, each with its own message; the legacy full walk keeps its
tolerance. Driven by BE9441's recorded A5 replies.
"""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import minimateplus.protocol as mp # noqa: E402
from minimate_replay import FIX, FIX_EVENT0, fast_clock, recorded_replies # noqa: E402
KEY = bytes.fromhex("0111646a")
KEY0 = bytes.fromhex("01110000")
@pytest.fixture(autouse=True)
def _fast(monkeypatch):
fast_clock(monkeypatch)
def a5_replies(path=FIX) -> list:
return [raw for sub, raw in recorded_replies(path) if sub == 0xA5]
class Replay:
"""One recorded A5 reply per 5A request, in order. From request `silent_from`
on: one stray 0x41 and then silence -- what BE9441 sent as it rebooted."""
def __init__(self, replies, silent_from=None):
self.replies, self.silent_from, self.sent, self._buf = list(replies), silent_from, 0, b""
def write(self, data):
n, self.sent = self.sent, self.sent + 1
if self.silent_from is None or n < self.silent_from:
self._buf += self.replies[n]
elif n == self.silent_from:
self._buf += b"\x41"
def read(self, n):
out, self._buf = self._buf[:n], self._buf[n:]
return out
def stream(replies, key=KEY, silent_from=None, **kw):
p = mp.MiniMateProtocol(Replay(replies, silent_from))
return p.read_bulk_waveform_stream(key, stop_after_metadata=False, include_terminator=True, **kw)
def test_the_recorded_stream_replays_whole():
assert len(stream(a5_replies(), strict=True)) == 51
def test_strict_raises_when_a_chunk_gets_no_reply():
with pytest.raises(mp.ProtocolError, match="no reply for the chunk at 0x"):
stream(a5_replies(), silent_from=40, strict=True)
def test_strict_raises_when_the_term_gets_no_reply():
with pytest.raises(mp.ProtocolError, match="no reply to the TERM request"):
stream(a5_replies(), silent_from=50, strict=True) # every chunk answered, the TERM not
def test_strict_raises_when_the_first_events_second_chunk_gets_no_reply():
# once called the "metadata page at 0x1002": it is event 0's chunk at 0x0200
with pytest.raises(mp.ProtocolError, match="no reply for the chunk at 0x01110200"):
stream(a5_replies(FIX_EVENT0), key=KEY0, silent_from=1, strict=True)
def test_strict_raises_on_a_terminator_mid_stream():
r = a5_replies()
r[10] = r[-1] # the TERM reply in place of chunk 10
with pytest.raises(mp.ProtocolError, match="sent its terminator"):
stream(r, strict=True)
def test_a_known_end_is_not_cut_short_by_the_callers_chunk_cap():
# STRT bounds the walk; a cap (client.py passes 128) once cut every event past
# ~66 KB short -- a large histogram, say. It now bounds only a walk with no end.
assert len(stream(a5_replies(), max_chunks=5, strict=True)) == 51
def test_the_cap_still_bounds_a_legacy_walk_with_no_strt():
r = a5_replies()
r[0] = r[0].replace(b"STRT", b"XXXX")
frames = stream(r, max_chunks=5)
assert len(frames) == 1 + 5 + 1 # first chunk, 5 capped chunks, TERM
def test_strict_raises_when_the_probe_has_no_strt():
r = a5_replies()
assert b"STRT" in r[0]
r[0] = r[0].replace(b"STRT", b"XXXX")
with pytest.raises(mp.ProtocolError, match="no STRT record"):
stream(r, strict=True)
def test_the_legacy_walk_keeps_its_tolerance():
frames = stream(a5_replies(), silent_from=40)
assert 0 < len(frames) < 51 # short, returned, not raised -- as before
def test_strict_refuses_a_strt_whose_end_is_not_after_its_start():
"""An event that crosses a 64 KB page now downloads (tests/test_5a_blastware_walk.py);
an end at or before the start can only be a corrupt STRT."""
r = a5_replies()
i = r[0].find(b"STRT")
assert r[0][i + 6:i + 10] == bytes.fromhex("0111c92c") # the end key
r[0] = r[0][:i + 6] + bytes.fromhex("01110000") + r[0][i + 10:] # ... before the start
p = mp.MiniMateProtocol(Replay(r))
with pytest.raises(mp.ProtocolError, match="at or before its start"):
p.read_bulk_waveform_stream(KEY, stop_after_metadata=False, include_terminator=True,
strict=True)
assert p._transport.sent == 1 # the first chunk, and nothing after
def test_the_legacy_walk_sends_no_term_for_most_of_an_event():
# After an early end, the "remainder" is most of the event, not a tail; a TERM
# for it once asked for kilobytes (or, past 64 KB, raised a bare ValueError).
t = Replay(a5_replies(), silent_from=40)
frames = mp.MiniMateProtocol(t).read_bulk_waveform_stream(
KEY, stop_after_metadata=False, include_terminator=True)
assert len(frames) == 40
assert t.sent == 41 # 40 answered, the one met by silence, and no TERM