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
288 lines
11 KiB
Python
288 lines
11 KiB
Python
"""SFM's MiniMate requests and 5A walk, against Blastware's own (recorded 2026-10-26).
|
|
|
|
Blastware downloaded all 8 of BE9441's events -- four of which cross a 64 KB page
|
|
-- while a bridge recorded both directions (fixture README). Every one of its 748
|
|
requests is the standard 16-byte payload with a SUM8 checksum and every 02 / 03 /
|
|
04 / 10 byte DLE-escaped; a 5A request carries a length (0x0200, or the remainder
|
|
for TERM) and a 4-byte linear address. The walk is the event's start, then
|
|
+0x200 at a time carrying into the page byte, then TERM at the next boundary for
|
|
exactly the remainder. SFM must send exactly those requests.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
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 fast_clock # noqa: E402
|
|
from minimateplus.blastware_file import extract_body_bytes, write_blastware_file # noqa: E402
|
|
from minimateplus.models import Event # noqa: E402
|
|
from minimateplus.framing import (S3FrameParser, build_5a_request, build_bw_frame, # noqa: E402
|
|
parse_strt_end_key, parse_strt_end_offset, waveform_key_params)
|
|
from minimateplus.waveform_codec import STREAM_END_ID, decode_waveform_v2, walk_records # noqa: E402
|
|
|
|
FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-blastware"
|
|
|
|
|
|
def _unstuff(b: bytes) -> bytes:
|
|
out, k = bytearray(), 0
|
|
while k < len(b):
|
|
if b[k] == 0x10 and k + 1 < len(b):
|
|
out.append(b[k + 1]); k += 2
|
|
else:
|
|
out.append(b[k]); k += 1
|
|
return bytes(out)
|
|
|
|
|
|
def bw_requests() -> list:
|
|
"""Blastware's requests, each as wire bytes; the SESSION_RESETs dropped."""
|
|
raw, out, i = (FIX / "blastware_requests.bin").read_bytes(), [], 0
|
|
while i < len(raw):
|
|
if raw[i:i + 2] == b"\x41\x03":
|
|
i += 2
|
|
continue
|
|
j = i + 2
|
|
while raw[j] != 0x03: # the first ETX not escaped by a DLE
|
|
j += 2 if raw[j] == 0x10 else 1
|
|
out.append(raw[i:j + 1])
|
|
i = j + 1
|
|
return out
|
|
|
|
|
|
def logical(frame: bytes) -> bytes:
|
|
return _unstuff(frame[2:-1])[:-1] # the 16-byte payload, checksum dropped
|
|
|
|
|
|
def unit_a5_replies() -> list:
|
|
raw, out, start, p = (FIX / "unit_replies.bin").read_bytes(), [], 0, S3FrameParser()
|
|
for i in range(len(raw)):
|
|
for f in p.feed(raw[i:i + 1]):
|
|
if f.sub == 0xA5:
|
|
out.append(raw[start:i + 1])
|
|
start = i + 1
|
|
return out
|
|
|
|
|
|
REQS = bw_requests()
|
|
FIVE_A = [f for f in REQS if logical(f)[2] == 0x5A]
|
|
|
|
|
|
def addr_len(frame: bytes) -> tuple:
|
|
p = logical(frame)
|
|
return int.from_bytes(p[6:10], "big"), int.from_bytes(p[4:6], "big")
|
|
|
|
|
|
def test_the_recording_is_what_the_readme_says():
|
|
assert (len(REQS), len(FIVE_A)) == (748, 540)
|
|
|
|
|
|
def test_every_blastware_5a_request_is_rebuilt_byte_for_byte():
|
|
assert [build_5a_request(*addr_len(f)) for f in FIVE_A] == FIVE_A
|
|
|
|
|
|
def test_every_other_blastware_request_is_rebuilt_byte_for_byte():
|
|
others = [f for f in REQS if logical(f)[2] != 0x5A]
|
|
assert len(others) == 208
|
|
for f in others:
|
|
p = logical(f)
|
|
assert build_bw_frame(p[2], p[5], p[6:16]) == f
|
|
|
|
|
|
def test_a_standard_request_escapes_02_03_04_in_its_params_and_checksum():
|
|
frame = build_bw_frame(0x0A, 0x46, waveform_key_params(bytes.fromhex("01120203")))
|
|
assert b"\x10\x02\x10\x03" in frame # the key's 02 and 03
|
|
for low in range(256): # a checksum of 0x03
|
|
f = build_bw_frame(0x0A, 0x46, waveform_key_params(bytes([0x01, 0x11, 0x50, low])))
|
|
if sum(_unstuff(f[2:-1])[:-1]) & 0xFF == 0x03:
|
|
assert f.endswith(b"\x10\x03\x03")
|
|
break
|
|
else:
|
|
pytest.fail("no key gave a checksum of 0x03")
|
|
|
|
|
|
# -- the walk ------------------------------------------------------------------
|
|
|
|
class ByAddress:
|
|
"""Answers each 5A request with Blastware's recorded reply for the same
|
|
(address, length); records what SFM sent."""
|
|
|
|
def __init__(self):
|
|
self.replies = {addr_len(q): r for q, r in zip(FIVE_A, unit_a5_replies())}
|
|
self.sent, self._buf = [], b""
|
|
|
|
def write(self, data):
|
|
data = bytes(data)
|
|
self.sent.append(data)
|
|
self._buf += self.replies.get(addr_len(data), b"")
|
|
|
|
def read(self, n):
|
|
out, self._buf = self._buf[:n], self._buf[n:]
|
|
return out
|
|
|
|
|
|
def blastware_walk(start: int) -> list:
|
|
"""Blastware's requests for the event that starts at `start`."""
|
|
i = next(k for k, f in enumerate(FIVE_A) if addr_len(f) == (start, 0x200))
|
|
walk = [FIVE_A[i]]
|
|
while addr_len(walk[-1])[1] == 0x200: # until TERM (a short read)
|
|
i += 1
|
|
walk.append(FIVE_A[i])
|
|
return walk
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _fast(monkeypatch):
|
|
fast_clock(monkeypatch)
|
|
|
|
|
|
# BE9441's 8 events; 1, 3, 5 and 7 cross into the next 64 KB page.
|
|
EVENTS = [("01110000", "K441LTOF.ZI0"), ("01118a2c", "K441LTOF.ZQ0"), ("011216c4", "K441LTOF.ZV0"),
|
|
("0112a0b6", "K441LTOG.000"), ("011329d2", "K441LTOG.050"), ("0113b072", "K441LTOG.0A0"),
|
|
("01143046", "K441LTOG.0L0"), ("0114b0b2", "K441LTOG.0S0")]
|
|
|
|
|
|
def test_the_crossing_events_are_the_ones_named():
|
|
ends = {k: addr_len(blastware_walk(int(k, 16))[-1]) for k, _ in EVENTS}
|
|
crossing = [k for k, (a, n) in ends.items() if (a + n) >> 16 != int(k, 16) >> 16]
|
|
assert crossing == ["01118a2c", "0112a0b6", "0113b072", "0114b0b2"]
|
|
|
|
|
|
@pytest.mark.parametrize("key", [k for k, _ in EVENTS])
|
|
def test_the_walk_sends_exactly_blastwares_requests_and_the_event_is_whole(key):
|
|
t = ByAddress()
|
|
frames = mp.MiniMateProtocol(t).read_bulk_waveform_stream(
|
|
bytes.fromhex(key), stop_after_metadata=False, include_terminator=True, strict=True)
|
|
want = blastware_walk(int(key, 16))
|
|
assert t.sent == want
|
|
assert len(frames) == len(want)
|
|
_s, body, _f = extract_body_bytes(frames)
|
|
recs = walk_records(body)
|
|
assert body[recs[-1]["end"] + 4] == STREAM_END_ID
|
|
dec = decode_waveform_v2(body)
|
|
assert len({len(dec[c]) for c in ("Tran", "Vert", "Long")}) == 1
|
|
|
|
|
|
@pytest.mark.parametrize("key,bw", EVENTS)
|
|
def test_the_file_built_from_the_walk_is_blastwares_own(key, bw, tmp_path):
|
|
frames = mp.MiniMateProtocol(ByAddress()).read_bulk_waveform_stream(
|
|
bytes.fromhex(key), stop_after_metadata=False, include_terminator=True, strict=True)
|
|
ev = Event(index=0)
|
|
ev.timestamp = None # the builder takes the footer from the TERM frame
|
|
path = tmp_path / bw
|
|
write_blastware_file(ev, frames, path)
|
|
assert path.read_bytes() == (FIX / "blastware" / bw).read_bytes()
|
|
|
|
|
|
# -- the requests BE9441 answered after the escape fix ---------------------------
|
|
|
|
def test_the_compliance_reads_be9441_answered_with_the_escaped_0x04():
|
|
# SUB 1A frames B and C are the only fixed requests whose bytes the fix changed
|
|
# (their 0x0400 length went out bare). These exact frames got full replies,
|
|
# 2,125 bytes, decoded correctly (bench 2026-10-26 14:38:43).
|
|
assert build_bw_frame(0x1A, 0x0400, bytes(7) + b"\x64\x00\x00").hex() == \
|
|
"41021010001a00100400000000000000006400009203"
|
|
assert build_bw_frame(0x1A, 0x0400, bytes([0, 0, 4, 0, 0, 0, 0, 0x64, 0, 0])).hex() == \
|
|
"41021010001a0010040000001004000000006400009603"
|
|
|
|
|
|
# -- synthetic replies: the unit's own encoding, with a chosen STRT end ----------
|
|
|
|
def _escape(b: bytes) -> bytes:
|
|
"""The unit's encoding (measured on 748 replies): 10 before 02, 03, 04 and 10."""
|
|
return b"".join(bytes([0x10, x]) if x in (0x02, 0x03, 0x04, 0x10) else bytes([x]) for x in b)
|
|
|
|
|
|
def _parse(wire: bytes):
|
|
frames = S3FrameParser().feed(wire)
|
|
assert len(frames) == 1
|
|
return frames[0]
|
|
|
|
|
|
def _logical(reply: bytes) -> bytes:
|
|
"""A recorded reply's payload, unescaped and without its checksum. Each
|
|
recorded reply opens with the unit's `41 03 41` before its `10 02`."""
|
|
return _unstuff(reply[reply.index(b"\x10\x02") + 2:-1])[:-1]
|
|
|
|
|
|
def first_reply_ending_at(end: int, event: int = 1) -> bytes:
|
|
"""A recorded first-chunk reply with STRT's end key set to `end`, re-encoded."""
|
|
q = FIVE_A.index(blastware_walk(int(EVENTS[event][0], 16))[0])
|
|
payload = bytearray(_logical(unit_a5_replies()[q]))
|
|
i = payload.find(b"STRT")
|
|
payload[i + 6:i + 10] = end.to_bytes(4, "big")
|
|
return b"\x10\x02" + _escape(bytes(payload) + bytes([sum(payload) & 0xFF])) + b"\x03"
|
|
|
|
|
|
def test_the_reply_encoder_is_the_units():
|
|
q = FIVE_A.index(blastware_walk(0x01118a2c)[0])
|
|
recorded = unit_a5_replies()[q]
|
|
payload = _logical(recorded)
|
|
i = payload.find(b"STRT")
|
|
end = int.from_bytes(payload[i + 6:i + 10], "big")
|
|
assert _parse(first_reply_ending_at(end)).data == _parse(recorded).data
|
|
|
|
|
|
def test_an_end_key_holding_escaped_bytes_reads_whole():
|
|
# None of the 8 recorded end keys holds a 02/03/04/10; this one holds 03 and 10.
|
|
data = _parse(first_reply_ending_at(0x01120310)).data
|
|
assert parse_strt_end_key(data) == 0x01120310
|
|
assert parse_strt_end_offset(data) != 0x0310 # the old reader's misread
|
|
|
|
|
|
class Synthetic:
|
|
"""Answers the first 5A request with `first`, each chunk with a recorded chunk
|
|
reply and the TERM with a recorded TERM reply; records (address, length)."""
|
|
|
|
def __init__(self, first: bytes):
|
|
replies = unit_a5_replies()
|
|
walk = blastware_walk(0x01118a2c)
|
|
self.first, self.sent, self._buf = first, [], b""
|
|
self.chunk = replies[FIVE_A.index(walk[1])]
|
|
self.term = replies[FIVE_A.index(walk[-1])]
|
|
|
|
def write(self, data):
|
|
a, n = addr_len(bytes(data))
|
|
self.sent.append((a, n))
|
|
self._buf += self.first if len(self.sent) == 1 else (self.chunk if n == 0x200 else self.term)
|
|
|
|
def read(self, n):
|
|
out, self._buf = self._buf[:n], self._buf[n:]
|
|
return out
|
|
|
|
|
|
def walk(first: bytes, start: int = 0x01118a2c, **kw):
|
|
t = Synthetic(first)
|
|
frames = mp.MiniMateProtocol(t).read_bulk_waveform_stream(
|
|
start.to_bytes(4, "big"), stop_after_metadata=False, include_terminator=True, **kw)
|
|
return t.sent, frames
|
|
|
|
|
|
def test_the_walk_ends_on_an_escaped_end_key():
|
|
sent, _ = walk(first_reply_ending_at(0x01120310), strict=True)
|
|
# chunks step from the start (...8a2c), so the TERM is at 0x0112022C for 0xE4
|
|
assert sent[-1] == (0x0112022C, 0x01120310 - 0x0112022C) # TERM: the tail, exactly
|
|
|
|
|
|
def test_a_large_event_walks_whole_past_the_callers_cap():
|
|
# 2,545 of 63,500 archived histograms exceed the ~66 KB a 128-chunk cap allowed.
|
|
start, end = 0x01118a2c, 0x01118a2c + 300_000
|
|
sent, frames = walk(first_reply_ending_at(end), start, strict=True, max_chunks=128)
|
|
n = (end - start) // 0x200
|
|
assert sent[:-1] == [(start + 0x200 * k, 0x200) for k in range(n)]
|
|
assert sent[-1] == (start + 0x200 * n, (end - start) % 0x200)
|
|
assert len(frames) == len(sent)
|
|
|
|
|
|
@pytest.mark.parametrize("strict", [True, False])
|
|
@pytest.mark.parametrize("size,why", [(0x100, "less than one 0x200 chunk"),
|
|
(0x500000, "more than any unit holds")])
|
|
def test_a_misread_strt_is_refused_in_both_modes(size, why, strict):
|
|
with pytest.raises(mp.ProtocolError, match=why):
|
|
walk(first_reply_ending_at(0x01118a2c + size), strict=strict)
|