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
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-26 15:16:10 -04:00
1 parent f61fc3cc78
commit 8acb9512a9
15 files changed
+285 -73

No files matched your search

+42 -30
View File
@@ -29,14 +29,9 @@ from .framing import (
S3Frame,
S3FrameParser,
build_bw_frame,
build_5a_frame,
build_bw_write_frame,
waveform_key_params,
token_params,
bulk_waveform_params,
bulk_waveform_term_params,
bulk_waveform_term_v2,
parse_strt_end_offset,
parse_strt_end_key,
build_5a_request,
POLL_PROBE,
@@ -125,23 +120,15 @@ DATA_LENGTHS: dict[int, int] = {
# NOT handled here — requires specialised read logic.
}
# SUB 5A (BULK_WAVEFORM_STREAM) protocol constants.
#
# 2026-05-01 minimal-fix: the chunk-counter walk is now bounded by the event's
# `end_offset` extracted from the STRT record at data[23:27] of the probe
# response. Without this bound the loop kept asking for chunks past the event
# end and the device responded with post-event circular-buffer garbage,
# corrupting reconstructed Blastware files for events ≥ 2 sec.
#
# We keep the OLD 0x0400 chunk step here (BW actually uses 0x0200 — see §7.8.5
# of the protocol reference for the corrected understanding) because the
# existing blastware_file.py builder relies on the 0x0400-step frame structure
# to produce valid files. Switching to BW's 0x0200 step is a separate task
# that also requires updating the file builder.
# BW-exact protocol values (v0.14.0). Verified against 4-27-26 + 5-1-26 captures.
_BULK_CHUNK_OFFSET = 0x1002 # offset_word for probe + all chunk requests
_BULK_TERM_OFFSET = 0x005A # offset_word for the legacy terminator (fallback only)
_BULK_COUNTER_STEP = 0x0200 # chunk counter increment (matches chunk payload size)
# SUB 5A (BULK_WAVEFORM_STREAM) walk constants. A 5A request is a read of a
# LENGTH at a 32-bit ADDRESS (measured 2026-10-26 against Blastware; see
# read_bulk_waveform_stream and framing.build_5a_request).
_BULK_TERM_OFFSET = 0x005A # TERM length when the end is unknown (legacy fallback only)
_BULK_COUNTER_STEP = 0x0200 # bytes per chunk read, and the step between addresses
# A sanity bound on the size STRT claims, not a measured limit: BE units report
# 983,026 bytes of memory (SUB 1C) and the largest archived event is ~850 KB. A
# claim past this is a misread STRT, refused before walking megabytes of garbage.
_BULK_MAX_EVENT_BYTES = 0x400000 # 4 MiB
# Default timeout values (seconds).
# MiniMate Plus is a slow device — keep these generous.
@@ -561,7 +548,7 @@ class MiniMateProtocol:
tolerance stands: an early end proceeds to TERM and returns what arrived.
The walk (measured 2026-10-26: Blastware downloading all 8 of BE9441's
events, three crossing a 64 KB page -- tests/test_5a_blastware_walk.py
events, four crossing a 64 KB page -- tests/test_5a_blastware_walk.py
rebuilds its requests byte for byte):
1. Read 0x200 bytes at the event's own 32-bit address (the key). The
@@ -634,6 +621,16 @@ class MiniMateProtocol:
"before its start -- not downloaded")
log.warning("5A STRT end 0x%08X is not after the start 0x%08X -- ignored", end, start)
end = None
if end is not None and end - start < _BULK_COUNTER_STEP:
# The walk's first read is a whole chunk, so a smaller event cannot be
# bounded -- and no event is that small (the header alone is longer).
raise ProtocolError(
f"5A STRT for {key4.hex()} says the event is {end - start} bytes, less than "
"one 0x200 chunk -- a misread STRT; not downloaded")
if end is not None and end - start > _BULK_MAX_EVENT_BYTES:
raise ProtocolError(
f"5A STRT for {key4.hex()} says the event is {end - start:,} bytes, more than "
f"any unit holds ({_BULK_MAX_EVENT_BYTES:,}) -- a misread STRT; not downloaded")
have_end = end is not None
if not have_end:
log.warning(
@@ -644,13 +641,18 @@ class MiniMateProtocol:
end = start + (max_chunks + 2) * _BULK_COUNTER_STEP # the cap bounds the loop
else:
log.info("5A STRT start=0x%08X end=0x%08X size=0x%X", start, end, end - start)
# With the end known, STRT bounds the walk and the cap must not cut it short:
# a histogram can be several hundred KB (2,545 of 63,500 in the DL2 archive
# exceed the 128-chunk / ~66 KB a caller's cap allowed). The cap still
# bounds a walk whose end is unknown.
chunk_cap = max(max_chunks, (end - start) // _BULK_COUNTER_STEP) if have_end else max_chunks
# ── Step 3: chunks at +0x200, plain 32-bit addresses ─────────────────
address = start + _BULK_COUNTER_STEP
last = start
chunks_fetched = 0
while chunks_fetched < max_chunks:
while chunks_fetched < chunk_cap:
# Stop when the next chunk would straddle the event end.
if address + _BULK_COUNTER_STEP > end:
log.debug(
@@ -709,17 +711,27 @@ class MiniMateProtocol:
else:
if strict:
raise ProtocolError(
f"5A reached the {max_chunks}-chunk cap at 0x{address:08X} before the "
f"5A reached the {chunk_cap}-chunk cap at 0x{address:08X} before the "
f"event's end 0x{end:08X} -- the event was not kept")
log.warning(
"5A reached max_chunks=%d at address=0x%08X (end=0x%08X)",
max_chunks, address, end,
chunk_cap, address, end,
)
# ── Step 4: TERM -- the remainder, from the next boundary ───────────
boundary = last + _BULK_COUNTER_STEP
if have_end:
term_length = end - boundary
if not 0 <= term_length < _BULK_COUNTER_STEP:
# Only after an early end (the legacy tolerance): what is left is not a
# tail but most of the event, and a TERM for it is no TERM at all.
if strict:
raise ProtocolError(
f"5A TERM for {key4.hex()} would read 0x{term_length:X} bytes from "
f"0x{boundary:08X}, not a tail -- the event was not kept")
log.warning("5A stream ended 0x%X bytes before the event's end; no TERM sent",
term_length)
return frames_data
log.debug("5A TERM address=0x%08X length=0x%04X end=0x%08X",
boundary, term_length, end)
else:
@@ -1466,10 +1478,10 @@ class MiniMateProtocol:
def _validate_frame(frame: S3Frame, expected_sub: Optional[int]) -> None:
"""Validate SUB; log but do not raise on bad checksum.
S3 response checksums frequently fail SUM8 validation due to inner-frame
delimiter bytes being captured as the checksum byte. The original
s3_parser.py deliberately never validates S3 checksums for exactly this
reason. We log a warning and continue.
A reply's checksum is SUM8 of its unescaped payload (748/748, measured
2026-10-26). `checksum_valid` is usually False only because S3FrameParser
sums its output with the `10` of each kept `10 02/03/04` pair still in it
-- the parser's doing, not the unit's. We log and continue.
"""
if not frame.checksum_valid:
# S3 checksums frequently fail SUM8 due to inner-frame delimiter bytes