From 89c5234ac03afacd8d2cde3c40a990665bd28c03 Mon Sep 17 00:00:00 2001 From: serversdown Date: Fri, 6 Nov 2026 14:52:50 -0500 Subject: [PATCH 1/3] fix(framing): an escaped checksum no longer leaves its 0x10 in a reply's data (#58) A MiniMate sends a checksum of 02, 03 or 04 as `10 X`. S3FrameParser kept both bytes and _finalise took only the last as the checksum, so the frame's data ended in a stray 0x10. It now takes the pair. Measured on every recorded reply (60 captures, March to October 2026): SUM8 of the unescaped payload is the checksum on 7,747 of 7,747; 272 arrived escaped, all valid as an escape pair. What the stray byte did: - 1C status: battery and memory are counted from the end; 12 of 760 recorded status replies read 419.84 V / 251,654,656 bytes (6.76 V / 983,026). - 2C call-home read: one byte long, refused as "monitoring". - 1A, 09 reads: already trimmed (bench 2026-11-04); the trims stay as guards. - 5A file builder: compensated in _frame_body_bytes; that pairing is removed, else a real 0x10 ending a chunk (one in ten do) would be dropped. Stored .a5.pkl frames: A5_PICKLE_VERSION 2; load_a5 drops the stray 0x10 from version-1 frames. All 28 pickles on this box rebuild byte-identical to dev's build. Operational consequence: none for prod's stored events (S3 events arrive through save_imported_bw, which keeps no frames); no schema change, no TOOL_VERSION bump, no backfill. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- minimateplus/blastware_file.py | 64 +++--------- minimateplus/client.py | 5 +- minimateplus/framing.py | 19 ++-- minimateplus/protocol.py | 14 +-- sfm/waveform_store.py | 22 +++- tests/test_s3_escaped_checksum.py | 161 ++++++++++++++++++++++++++++++ 6 files changed, 214 insertions(+), 71 deletions(-) create mode 100644 tests/test_s3_escaped_checksum.py diff --git a/minimateplus/blastware_file.py b/minimateplus/blastware_file.py index 9dcbcb4..2a9755b 100644 --- a/minimateplus/blastware_file.py +++ b/minimateplus/blastware_file.py @@ -104,17 +104,11 @@ M529LIY6 (example event) using raw_s3_20260403_153508.bin capture): DLE strip rule (applied AFTER slicing): Strip any 0x10 byte that is immediately followed by 0x02, 0x03, or 0x04. This undoes the DLE-escape that S3FrameParser preserves as literal pairs. - Applied to frame.data[skip:] + bytes([frame.chk_byte]) together, then - conditionally exclude the trailing chk_byte from the output. - chk_byte absorption: - When frame.data[-1] == 0x10 AND frame.chk_byte ∈ {0x02, 0x03, 0x04}, - the last byte of frame.data is the DLE prefix of a split DLE+chk pair. - Including chk_byte in the strip buffer allows the pair to be stripped as - a unit. After stripping, the trailing chk_byte is ALWAYS removed — because - _strip_inner_frame_dles keeps the byte after the DLE (the chk_byte value), - and that value is the checksum, never payload. This applies to all three - cases (chk ∈ {0x02, 0x03, 0x04}) identically. + chk_byte absorption (retired 2026-11-06, #58): + The escape 0x10 of a checksum sent as `10 02/03/04` used to stay at the end + of frame.data, and this builder dropped it here. The parser now drops it, + so a 0x10 ending frame.data is real data (one A5 chunk in ten ends in one). MLG CRC: The algorithm that produces the 2-byte CRC at the start of each MLG record @@ -297,29 +291,16 @@ def _frame_body_bytes(frame: S3Frame, skip: int) -> bytes: Extract the waveform body contribution from one A5 S3Frame. The contribution is frame.data[skip:] with inner-frame DLE pairs stripped - per _strip_inner_frame_dles(). The chk_byte is temporarily appended before - stripping to handle the split-pair edge case where a DLE at the end of - frame.data is paired with chk_byte. + per _strip_inner_frame_dles(). - Split-pair edge case (confirmed for A5[8] of M529LIY6 (example event), 2026-04-21): - - S3FrameParser appends DLE+XX pairs as two literal bytes when XX ∉ {DLE, ETX}. - When the LAST occurrence of such a pair straddles the payload/checksum boundary - (i.e., DLE is the last byte of raw_payload and XX is the checksum), the parser - splits them: - - DLE ends up as the last byte of frame.data (frame.data[-1] == 0x10) - - XX is stored as frame.chk_byte - - To strip the pair correctly, we reunite the bytes before calling the strip - function. Since chk_byte is the checksum (not payload data), it is excluded - from the final output regardless of whether it was part of a pair. - - Post-strip chk_byte removal (ALL cases): - _strip_inner_frame_dles strips the 0x10 and KEEPS chk_byte in all cases. - Chk_byte is always the checksum (not payload), so always strip it off. + Until #58 (2026-11-06) an escaped checksum (`10 02/03/04`) left its 0x10 as + the last byte of frame.data, and this function dropped it by pairing it with + chk_byte (first seen on A5[8] of M529LIY6, 2026-04-21). The parser drops it + now, so a 0x10 here is data and is kept. Args: - frame: S3Frame with frame.data and frame.chk_byte populated. + frame: S3Frame from S3FrameParser (or a store pickle loaded by + WaveformStore.load_a5, which converts pre-#58 frames). skip: Number of leading bytes in frame.data to exclude (frame header). Returns: @@ -327,28 +308,7 @@ def _frame_body_bytes(frame: S3Frame, skip: int) -> bytes: """ if skip >= len(frame.data): return b"" - - relevant = frame.data[skip:] - - # Detect split DLE+chk pair at the frame boundary. - has_split_pair = ( - len(relevant) > 0 - and relevant[-1] == 0x10 - and frame.chk_byte in {0x02, 0x03, 0x04} - ) - - if has_split_pair: - # Reunite the split pair so the strip function sees both bytes together. - buf = relevant + bytes([frame.chk_byte]) - stripped = _strip_inner_frame_dles(buf) - # _strip_inner_frame_dles strips the DLE (0x10) and KEEPS chk_byte. - # chk_byte is the received checksum — never payload — so remove it. - # This is correct for all values in {0x02, 0x03, 0x04}. - if stripped: - stripped = stripped[:-1] - return stripped - else: - return _strip_inner_frame_dles(relevant) + return _strip_inner_frame_dles(frame.data[skip:]) # ── Filename helper ─────────────────────────────────────────────────────────── diff --git a/minimateplus/client.py b/minimateplus/client.py index 89d0ed7..e8b36a9 100644 --- a/minimateplus/client.py +++ b/minimateplus/client.py @@ -2354,8 +2354,9 @@ def _decode_monitor_status(data: bytes) -> MonitorStatus: header, so field offsets below are relative to data[11]). NOTE: frame.data has the checksum byte already stripped by S3FrameParser - (_finalise returns raw_payload[5:] where raw_payload = body[:-1]). - There is NO trailing checksum byte in section. + (_finalise returns raw_payload[5:], the checksum and, since #58, the 10 of + an escaped checksum removed). There is NO trailing checksum byte in section; + before #58 one status reply in 63 kept that 10 and read 419.84 V. Monitoring flag (confirmed 4-8-26/2ndtry, byte diff of all 144 data frames): section[1] == 0x00 → idle diff --git a/minimateplus/framing.py b/minimateplus/framing.py index 5efa2a9..2c803b2 100644 --- a/minimateplus/framing.py +++ b/minimateplus/framing.py @@ -535,8 +535,10 @@ def unescape_reply(data: bytes) -> bytes: """A reply's data with each kept escape removed: `10 02/03/04` → `02/03/04`. The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do - (748/748 replies, 2026-10-26). S3FrameParser collapses `10 10` but keeps the - `10` of `10 02/03/04` (inner-frame markers to it), so its `.data` carries an + (checksum included: 7,747 of 7,747 recorded replies, March to October 2026, + #58; the 748 measured on 2026-10-26 were Blastware's requests). S3FrameParser + collapses `10 10` but keeps the `10` of `10 02/03/04` (inner-frame markers to + it) everywhere but the checksum, so its `.data` carries an extra byte before each 02/03/04 value -- harmless for fields read before the escape, one byte off for any read after it, or counted from the end.""" out, i = bytearray(), 0 @@ -632,11 +634,8 @@ class S3Frame: page_lo: int # PAGE_LO from header data: bytes # payload data section (payload[5:], checksum already stripped) checksum_valid: bool - chk_byte: int = 0 # actual checksum byte received from wire (body[-1]) - # needed for waveform file reconstruction: when the last data byte - # is 0x10 and chk_byte ∈ {0x02, 0x03, 0x04}, the DLE+chk pair - # must be included in the DLE-strip operation to correctly - # reconstruct the Blastware binary body. + chk_byte: int = 0 # actual checksum byte received from wire (body[-1]); an + # escaped one (`10 02/03/04`) leaves no 10 in `data` (#58) @property def page_key(self) -> int: @@ -759,7 +758,11 @@ class S3FrameParser: if len(body) < 6: return None - raw_payload = body[:-1] # everything except the trailing checksum byte + # A checksum of 02, 03 or 04 arrives escaped, `10 X`, and _step keeps both + # bytes; that 10 is the escape, never data (#58: 272 of 7,747 recorded + # replies, every one an escape pair). Any other checksum is one byte. + n_chk = 2 if body[-2] == DLE and body[-1] in (STX, ETX, 0x04) else 1 + raw_payload = body[:-n_chk] # everything except the checksum chk_received = body[-1] chk_computed = checksum(raw_payload) diff --git a/minimateplus/protocol.py b/minimateplus/protocol.py index 4cf5720..464c172 100644 --- a/minimateplus/protocol.py +++ b/minimateplus/protocol.py @@ -196,10 +196,11 @@ def assemble_compliance_content(frames: "list[bytes]", lengths: "Optional[tuple] `lengths`: the content each frame was asked for (SFM's read: 1024, 1024, 42). Each frame then gives exactly that. Measured at the bench 2026-11-04 (BE9441): - when a frame's checksum byte is itself escaped (02 / 03 / 04), the parser keeps - the escape's 0x10 and strips only the byte after it, so the frame arrives one - byte long, ending in a lone 0x10. That one byte is dropped; any other leftover - is kept, and the block then fails is_compliance_content.""" + when a frame's checksum byte was itself escaped (02 / 03 / 04), the parser kept + the escape's 0x10, so the frame arrived one byte long, ending in a lone 0x10. + The parser drops it since #58; this trim stays as a guard. That one byte is + dropped; any other leftover is kept, and the block then fails + is_compliance_content.""" parts = [unescape_reply(bytes(f))[11:] for f in frames] parts = [p[1:] for p in parts[:-1]] + parts[-1:] if lengths is not None and len(lengths) == len(parts): @@ -633,8 +634,9 @@ class MiniMateProtocol: data_rsp = self._recv_one(expected_sub=rsp_sub) raw = unescape_reply(data_rsp.data)[11:] # unescaped, as read_event_index - # An escaped checksum byte leaves its 0x10 behind (bench 2026-11-04; see - # assemble_compliance_content): one stray byte beyond what was asked is dropped. + # An escaped checksum byte left its 0x10 behind until #58 (bench 2026-11-04; + # see assemble_compliance_content): kept as a guard, one stray byte beyond + # what was asked is dropped. if len(raw) == length + 1 and raw[-1:] == b"\x10": raw = raw[:-1] log.debug("read_waveform_data_raw: got %d bytes", len(raw)) diff --git a/sfm/waveform_store.py b/sfm/waveform_store.py index 5ac0788..6a1a2a2 100644 --- a/sfm/waveform_store.py +++ b/sfm/waveform_store.py @@ -46,7 +46,19 @@ from sfm.shape_metrics import shape_from_h5, offset_from_h5 log = logging.getLogger("sfm.waveform_store") -A5_PICKLE_VERSION = 1 +# 2 (2026-11-06, #58): frames as the parser gives them since an escaped checksum +# stopped leaving its 0x10 in `data`. A version-1 frame with a checksum of 02, 03 +# or 04 still ends in that 0x10; load_a5 drops it (_frame_from_v1). +A5_PICKLE_VERSION = 2 + + +def _frame_from_v1(f: S3Frame) -> S3Frame: + """A frame pickled before #58, as the parser reads its reply now. Its 02/03/04 + checksum arrived as `10 X` (every recorded one did), and the 10 ended `data`.""" + if f.chk_byte in (0x02, 0x03, 0x04) and f.data[-1:] == b"\x10": + return S3Frame(sub=f.sub, page_hi=f.page_hi, page_lo=f.page_lo, data=f.data[:-1], + checksum_valid=f.checksum_valid, chk_byte=f.chk_byte) + return f def _frame_to_dict(f: S3Frame) -> dict: @@ -801,7 +813,8 @@ class WaveformStore: def load_a5(self, serial: str, filename: str) -> Optional[list[S3Frame]]: """ - Re-hydrate the pickled A5 frame stream for a stored event. + Re-hydrate the pickled A5 frame stream for a stored event, as the parser + reads it now (a version-1 pickle's frames are converted). Returns None if the sidecar is missing. """ _, a5_path = self.paths_for(serial, filename) @@ -812,7 +825,10 @@ class WaveformStore: if not isinstance(payload, dict) or "frames" not in payload: log.warning("WaveformStore.load_a5: malformed sidecar at %s", a5_path) return None - return [_dict_to_frame(d) for d in payload["frames"]] + frames = [_dict_to_frame(d) for d in payload["frames"]] + if payload.get("version", 1) < 2: + frames = [_frame_from_v1(f) for f in frames] + return frames # ── modern .sfm.json sidecar accessors ────────────────────────────────────── diff --git a/tests/test_s3_escaped_checksum.py b/tests/test_s3_escaped_checksum.py new file mode 100644 index 0000000..e8b699e --- /dev/null +++ b/tests/test_s3_escaped_checksum.py @@ -0,0 +1,161 @@ +"""#58: a reply whose checksum byte is 02, 03 or 04 arrives as `10 X`. + +The unit escapes 02, 03, 04 and 10 in a reply, the checksum included. The +parser kept the `10` of an escaped checksum as the frame's last data byte, so +the data came out one byte long, ending in a lone 0x10 (measured on BE9441's +1A read at the bench, 2026-11-04). + +Across every recorded reply (60 captures, March to October 2026), SUM8 of the +unescaped payload is the checksum on 7,747 of 7,747. 272 checksums arrived +escaped, and every one checks as an escape pair: the `10` is never data. +""" +from __future__ import annotations + +import os +import pickle +import sys +from dataclasses import replace +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 _frame_body_bytes, write_blastware_file # noqa: E402 +from minimateplus.client import _decode_monitor_status # noqa: E402 +from minimateplus.framing import S3FrameParser, unescape_reply # noqa: E402 +from minimateplus.models import Event # noqa: E402 +from minimateplus.protocol import is_call_home_block # noqa: E402 +from sfm.waveform_store import A5_PICKLE_VERSION, WaveformStore, _frame_to_dict # noqa: E402 +from test_5a_blastware_walk import ByAddress # noqa: E402 + +FIX = Path(__file__).parent / "fixtures" + + +def _escape(b: bytes) -> bytes: + """The unit's encoding: 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 reply(sub: int, data: bytes, page: bytes = b"\x00\x00") -> bytes: + """A reply as the unit sends it: header, data and SUM8 checksum, escaped.""" + payload = bytes([0x00, 0x10, sub]) + page + data + return b"\x10\x02" + _escape(payload + bytes([sum(payload) & 0xFF])) + b"\x03" + + +def data_for(chk: int, last: int, sub: int = 0xE3) -> bytes: + """Data ending in `last` whose reply checksum comes out as `chk`.""" + base = bytes(11) + b"#58" + fill = (chk - (0x10 + sub + sum(base) + last)) & 0xFF + return base + bytes([fill, last]) + + +def one(wire: bytes): + frames = S3FrameParser().feed(wire) + assert len(frames) == 1 + return frames[0] + + +@pytest.mark.parametrize("chk", [0x02, 0x03, 0x04]) +def test_an_escaped_checksum_leaves_nothing_in_the_data(chk): + data = data_for(chk, last=0x55) + f = one(reply(0xE3, data)) + assert (unescape_reply(f.data), f.chk_byte) == (data, chk) + + +@pytest.mark.parametrize("chk", [0x02, 0x03, 0x04]) +def test_a_last_data_byte_of_0x10_survives_an_escaped_checksum(chk): + # Wire `10 10 10 0X`: a real 0x10, then the escaped checksum. Not in any + # recording; one A5 chunk in ten ends in a real 0x10. + data = data_for(chk, last=0x10) + f = one(reply(0xE3, data)) + assert (unescape_reply(f.data), f.chk_byte) == (data, chk) + + +@pytest.mark.parametrize("chk", [0x10, 0x00, 0x55]) +def test_any_other_checksum_reads_as_before(chk): + data = data_for(chk, last=0x10) + f = one(reply(0xE3, data)) + assert (unescape_reply(f.data), f.chk_byte) == (data, chk) + + +# Two 1C replies recorded from BE11529 on 2026-04-08, checksums 03 and 02 escaped. +# The battery and memory are counted from the end, so the stray byte read them as +# 430.08 V / 251,654,656 bytes total. +STATUS_REPLIES = [ + ("4-8-26/mid-monitor/raw_s3_20260408_181417", + "1002001010e300002c0000000000000000000000100408100407ea00120e2c000000000000010107cb" + "00060000010107cb0015000000001002a8000efff2000e9d80100303", 6.80, 983026, 957824), + ("4-8-26/raw_s3_20260408_013431", + "1002001010e300002c0000000000000000000000100408100407ea00012312000000000000010107cb" + "00060000010107cb0015000000001002a4000efff2000e9e98100203", 6.76, 983026, 958104), +] + + +@pytest.mark.parametrize("capture,wire,volts,total,free", STATUS_REPLIES) +def test_a_recorded_status_reply_with_an_escaped_checksum_reads_whole(capture, wire, volts, total, free): + st = _decode_monitor_status(one(bytes.fromhex(wire)).data) + assert (st.battery_v, st.memory_total, st.memory_free) == (volts, total, free) + + +def test_a_call_home_read_with_an_escaped_checksum_is_a_call_home_block(): + # BE11529's 2C reply (2026-04-20), its block untouched; one header pad byte is + # set so the checksum comes out 02. The stray byte made it 125 bytes, and SFM + # refused the unit as monitoring. + recorded = S3FrameParser().feed( + (FIX / "s3-call-home-bw" / "raw_s3_20260420_162148_pull_call_home_options.bin").read_bytes()) + data = bytearray(unescape_reply(next(f for f in recorded if f.sub == 0xD3 and len(f.data) > 11).data)) + data[10] = (0x02 - (0x10 + 0xD3 + sum(data) - data[10])) & 0xFF + f = one(reply(0xD3, bytes(data))) + assert f.chk_byte == 0x02 + assert is_call_home_block(f.data[11:]) + assert unescape_reply(f.data[11:]) == bytes(data[11:]) + + +@pytest.mark.parametrize("chk", [0x02, 0x03, 0x04]) +def test_the_file_builder_keeps_a_real_0x10_before_an_escaped_checksum(chk): + # An A5 chunk reply: 12 header bytes, then the body bytes it carries. + data = data_for(chk, last=0x10, sub=0xA5) + f = one(reply(0xA5, data)) + assert _frame_body_bytes(f, 12) == data[12:] + + +# -- the waveform store's .a5.pkl frames, saved by the parser as it was --------------- + +def _write_pickle(store: WaveformStore, name: str, version: int, frames: list) -> None: + _bw, a5_path = store.paths_for("BE9441", name) + a5_path.parent.mkdir(parents=True, exist_ok=True) + with a5_path.open("wb") as fp: + pickle.dump({"version": version, "frames": [_frame_to_dict(f) for f in frames]}, fp) + + +def test_a_pickle_saved_before_58_still_builds_blastwares_file(tmp_path, monkeypatch): + # BE9441's K441LTOG.000 (10-26 recording): two of its chunk replies have an + # escaped checksum. A pickle from before #58 holds their stray 0x10s. + fast_clock(monkeypatch) + frames = mp.MiniMateProtocol(ByAddress()).read_bulk_waveform_stream( + bytes.fromhex("0112a0b6"), stop_after_metadata=False, include_terminator=True, strict=True) + old = [replace(f, data=f.data + b"\x10") if f.chk_byte in (0x02, 0x03, 0x04) else f + for f in frames] + assert sum(o.data != f.data for o, f in zip(old, frames)) == 2 + store = WaveformStore(tmp_path / "waveforms") + _write_pickle(store, "K441LTOG.000", 1, old) + + loaded = store.load_a5("BE9441", "K441LTOG.000") + assert [f.data for f in loaded] == [f.data for f in frames] + ev = Event(index=0) + ev.timestamp = None + write_blastware_file(ev, loaded, tmp_path / "K441LTOG.000") + bw = FIX / "minimate-bench-10-26-26-blastware" / "blastware" / "K441LTOG.000" + assert (tmp_path / "K441LTOG.000").read_bytes() == bw.read_bytes() + + +def test_a_pickle_saved_now_loads_as_saved(tmp_path): + # A real 0x10 before an escaped checksum: the conversion is for old pickles only. + f = one(reply(0xA5, data_for(0x02, last=0x10, sub=0xA5))) + store = WaveformStore(tmp_path / "waveforms") + _write_pickle(store, "K441LTOG.000", A5_PICKLE_VERSION, [f]) + assert store.load_a5("BE9441", "K441LTOG.000")[0].data == f.data From 47da0ddef0ab72ba2955a592c93721154f306a87 Mon Sep 17 00:00:00 2001 From: serversdown Date: Fri, 6 Nov 2026 14:54:45 -0500 Subject: [PATCH 2/3] fix(framing): checksum_valid sums the reply's payload unescaped S3FrameParser summed its payload with the kept `10` of each `10 02/03/04` still in, so checksum_valid was False on about a third of good replies (the old "S3 checksums frequently fail" belief). SUM8 of the unescaped payload is the unit's checksum on 7,747 of 7,747 recorded replies; the test pins it on the 2,509 in the committed October fixtures (62 with an escaped checksum), which also proves #58's split of data from checksum on real replies. Nothing decides on checksum_valid; seismo_lab's display stops crying wolf. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- minimateplus/framing.py | 4 +++- tests/test_s3_escaped_checksum.py | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/minimateplus/framing.py b/minimateplus/framing.py index 2c803b2..cab24be 100644 --- a/minimateplus/framing.py +++ b/minimateplus/framing.py @@ -764,7 +764,9 @@ class S3FrameParser: n_chk = 2 if body[-2] == DLE and body[-1] in (STX, ETX, 0x04) else 1 raw_payload = body[:-n_chk] # everything except the checksum chk_received = body[-1] - chk_computed = checksum(raw_payload) + # SUM8 of the payload unescaped: the kept `10` of a `10 02/03/04` is not + # summed (7,747 of 7,747 recorded replies check this way). + chk_computed = checksum(unescape_reply(raw_payload)) if len(raw_payload) < 5: return None diff --git a/tests/test_s3_escaped_checksum.py b/tests/test_s3_escaped_checksum.py index e8b699e..1493362 100644 --- a/tests/test_s3_escaped_checksum.py +++ b/tests/test_s3_escaped_checksum.py @@ -75,6 +75,20 @@ def test_a_last_data_byte_of_0x10_survives_an_escaped_checksum(chk): assert (unescape_reply(f.data), f.chk_byte) == (data, chk) +REPLY_RECORDINGS = ["minimate-bench-10-25-26/BE9441_event0_01110000_rx.bin", + "minimate-bench-10-25-26/BE9441_event1_0111646a_rx.bin", + "minimate-bench-10-26-26-blastware/unit_replies.bin", + "minimate-bench-10-26-26-histogram/unit_replies.bin"] + + +@pytest.mark.parametrize("name", REPLY_RECORDINGS) +def test_every_recorded_reply_checks(name): + # BE9441, October 2026: 2,509 replies, 62 with an escaped checksum. + frames = S3FrameParser().feed((FIX / name).read_bytes()) + assert frames + assert [i for i, f in enumerate(frames) if not f.checksum_valid] == [] + + @pytest.mark.parametrize("chk", [0x10, 0x00, 0x55]) def test_any_other_checksum_reads_as_before(chk): data = data_for(chk, last=0x10) From 7b45647b231d15bcb852faec5d20d0e53e5c98dd Mon Sep 17 00:00:00 2001 From: serversdown Date: Fri, 6 Nov 2026 14:57:39 -0500 Subject: [PATCH 3/3] docs: #58 in the reference and CLAUDE.md; unescape_reply's 748 were replies Reference row 2026-11-06: an escaped checksum is the checksum, measured on 7,747 / 7,747 recorded replies, with what the stray byte misread. CLAUDE.md's phase-5 warning marked fixed, and the reply rule widened. Corrects 89c5234's unescape_reply docstring: the 2026-10-26 recording's 748/748 was measured on its replies (it also has 748 requests); I had called them Blastware's requests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- CLAUDE.md | 20 +++++++++++++------- docs/instantel_protocol_reference.md | 1 + minimateplus/framing.py | 14 +++++++------- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index bf2795d..2c7d049 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -340,9 +340,12 @@ Read this first when picking the project back up. - ⚠ **A MiniMate's open setup menu wins:** a change sent while it is open is lost when the operator presses Cancel or Save (the menu writes its whole-block copy back). The preview warns; nobody in the menus while the office sends. - - ⚠ An escaped checksum byte leaves a stray `0x10` in a Series-3 reply's data - (about 1 frame in 85). The settings and waveform reads take exactly what they - asked for; other reads are unaudited for it. + - ~~⚠ An escaped checksum byte leaves a stray `0x10` in a Series-3 reply's data + (about 1 frame in 85).~~ **Fixed in the parser (#58, 2026-11-06, measured):** + a checksum of 02/03/04 arrives as `10 X`, and that `10` is never data (7,747 / + 7,747 recorded replies check). It had misread 1C battery/memory (419.84 V) and + the 2C call-home read; the 5A file builder's own compensation is gone with it, + and pre-fix `.a5.pkl` frames are converted on load (pickle version 2). - ⚠ The Micromate scheduler switch is not in any block SFM reads, so a leftover schedule blocks a change even with the scheduler Off. **Ring path measured the same night:** with THOR's watchdog off, a call-home @@ -475,9 +478,11 @@ Read this first when picking the project back up. retracted 5A model: SUB 71's "offset 0x1004" reads as length 0x0400 escaped, and Blastware escapes `03` in write data. A write whose payload holds a bare 02/03/04/10 may be malformed. One Blastware config-write capture settles it. - 🔑 **Replies follow the same rule (measured, 748/748):** every 02/03/04/10 escaped, - checksum = SUM8 of the unescaped payload. The "S3 checksums frequently fail" belief - is `S3FrameParser` summing its output with the `10` of `10 02/03/04` still in it. + 🔑 **Replies follow the same rule (measured, 748/748; 7,747 / 7,747 across every + recording, #58):** every 02/03/04/10 escaped, the checksum too, and checksum = SUM8 + of the unescaped payload. The "S3 checksums frequently fail" belief was + `S3FrameParser` summing its output with the `10` of `10 02/03/04` still in it + (fixed 2026-11-06: `checksum_valid` holds on every recorded reply). ~~**⚠ KNOWN BUG — the 5A walk breaks once a unit's buffer crosses 64 KB.**~~ `parse_strt_end_offset()` returns only `(end_key[2] << 8) | end_key[3]`, discarding the key's page byte. An event starting at `0x0111F2A2` and ending @@ -2026,7 +2031,8 @@ A re-analysis in the prior session incorrectly concluded `section[1]` is always and is device-specific. The 2026-04-09 re-analysis confirms `section[1]` was right. **IMPORTANT — `frame.data` has checksum already stripped** by `S3FrameParser._finalise()` -(`raw_payload = body[:-1]`; `data = raw_payload[5:]`). There is NO trailing checksum byte in +(`raw_payload` = the body less its checksum, and less the `10` of an escaped one since #58; +`data = raw_payload[5:]`). There is NO trailing checksum byte in `section`. All relative-from-end offsets must account for this. Battery and memory fields are present in **both** states: diff --git a/docs/instantel_protocol_reference.md b/docs/instantel_protocol_reference.md index 18b4500..8b83583 100644 --- a/docs/instantel_protocol_reference.md +++ b/docs/instantel_protocol_reference.md @@ -11,6 +11,7 @@ | Date | Section | Change | |---|---|---| +| 2026-11-06 | §3 (replies), SUB 1C, 2C, 15, 5A file build | ✅ **An escaped checksum is the checksum, not data (#58, measured).** A reply whose checksum is 02, 03 or 04 sends it as `10 X`, and `S3FrameParser` kept that `10` as the frame's last data byte (first seen on BE9441's 1A read, 2026-11-04). **Across every recorded reply** (60 captures, March to October 2026, three units) SUM8 of the unescaped payload is the checksum on **7,747 / 7,747**, widening 2026-10-26 (4)'s 748 / 748. **272** checksums arrived escaped; every one checks as an escape pair, and no checksum ever arrived as a bare 02/03/04. **What the stray byte did:** **SUB 1C** battery and memory are counted from the end, so 12 of 760 recorded status replies read 419.84 V and 251,654,656 bytes (for 6.76 V and 983,026). A **SUB 2C** call-home read came out one byte long and was refused as "monitoring". The **SUB 15 probe reply** (`00 00 00 00 0a …`, the same on BE11529, BE18189 and BE9441) always has an escaped checksum: 230 of the 272, harmless, as nothing reads it. The **5A file builder** had compensated since 2026-04-21 (the "split pair" rule). With the parser fixed, that rule would drop a real `0x10` ending a chunk (one A5 chunk in ten ends in one; none recorded with an escaped checksum as well), so it is removed. The 1A and 09 reads' length trims (2026-11-04) stay as guards. `checksum_valid` now sums the unescaped payload, and every recorded reply checks. | | 2026-11-05 | Appendix D.6.12 (NEW), D.6.11, §7.8.9 | ✅ **The unit's own event summary, in every event file.** The embedded event record is the first of a `[length][id][payload]` chain. It holds the vector-sum peak's sample (6,492 / 6,493). Then one 22-byte record per channel, ids `0x32` Tran … `0x35` MicL: min, max, peak sample, **half-period** and a **displacement integral**. Blastware prints them as they are. **ZC frequency** = (rate / 2) / half-period, with the interval rule's words: 25,966 / 25,966 waveform and 253,958 / 253,958 histogram channel values. **Peak displacement** = half the integral: 19,479 / 19,479. Recomputing from the samples had reached 46% and 84%: the unit works at full resolution. **Times of peak** follow the unit's peak sample. That differs from the samples only on **O117I1NK.R70W**, whose stored samples wrap at the trigger by 65,536 counts (Blastware's own table has the same values). Peak acceleration is Blastware's own computation from the stored samples (group D part 1, documented here too). The unit stores its own largest step at `[15:21]` (inferred), which Blastware does not print. §7.8.9's "constant, meaning ❓" bytes amended in place. 59 of 88 report fields now match on every DL2 event (47 before group D). | | 2026-11-04 | SUB 1A / 09 reads, SUB 68–74 settings write, the keypad | **SFM's settings write, benched on BE9441 (Brian at the unit; ~12 writes, each with his go).** **Every write** -- trigger 0.04 ↔ 0.05, a note, several fields at once (Project, job number + its report flag, trigger), the alarm 1.0 ↔ 1.5, and a full restore -- was acknowledged on all nine steps (`97 8C 8E×5 8D 7D 7C 96 8B 8D`), read back as sent, and **confirmed on the unit's own screen**; the unit ended byte for byte as found. Moved bytes were exactly the field's: trigger f32 at each geophone channel +30 (`+31..+33` moved), **alarm f32 at channel +38** (`+39` moved; the first Series-3 alarm write), job number `[40:42]`, its report bit `[39]` `0x02`, a note's value window. **`[26:28]`** went `01 7f` → `00 00` on SFM's first write (Blastware's value) and the unit **set `01 7f` again during the next monitoring session**. The **two bytes after the block** went out as `00 00` (Blastware sends a per-unit constant) and were taken. **🔑 Escaped-checksum artifact:** when a reply's checksum byte is itself escaped (02 / 03 / 04, ~1 frame in 85), `S3FrameParser` keeps the escape's `0x10` and strips only the byte after it, so the frame's data gains one trailing `0x10`. It hit the first live 1A read (frame B 1,026 bytes after the header); the 12 recorded reads never had. SFM's settings read and waveform read now take exactly the length they asked for. **🔑 The keypad menu wins:** a write sent while the setup menu was open was acknowledged and read back, then **lost when the operator pressed Cancel or Save** -- the menu writes its own copy of the **whole** block back (both times the block returned byte for byte to its state when the menu was opened). A keypad Cancel with nothing pending leaves the block unchanged. **While monitoring**, the 1A read returns the device-info block (SFM refuses, nothing sent), and the opening poll was answered only intermittently (2 of 3 attempts timed out). Code: `minimateplus.protocol.read_compliance_content` / `read_waveform_data_raw`, `micromate.setup_fields`; notes `~/bench-logs/2026-11-04-sfm-settings/`. | | 2026-11-03 (5) | SUB 1A / 71 / 69 (settings read and write) | **The settings block, read and written as content (measured, BE9441's 10-26 recording and BE11529's 2026-04-20 captures).** **Read:** unescape each 1A data frame and take `data[11:]`; every frame but the last starts with one `00` that is not content; dropped, the frames join into **2,090 bytes headed by N = 2090: Series IV's `0x1A` content layout** (12 / 12 reads, Blastware's 4 × 512 + 42 and SFM's 1024 + 1024 + 42). The old "stable anchor" `be 80 00 00 00 00` is content `[12:18]` (pre-trigger −0.25 + stop mode Fixed). **Round trip:** the read after each of Blastware's two 10-26 writes equals the image it had just written, all 2,090 bytes (2 / 2). While monitoring, the read returns the device-info block (`0e 'BE9441' …`, 5 / 5). **`[26:28]`:** Blastware writes `00 00` on all 11 writes; the unit reads `01 7f` after a monitoring session (BE9441 10-26, BE11529 4-20 15:19) and sets it by itself; meaning unknown. **The two bytes after the block** (`[2090:2092]` of the 0x71 image) are Blastware's own per-unit constant -- `7c ea` on all nine of BE11529's writes, `0c e9` on both of BE9441's -- not the block's CRC-16/AUG, and in no reply of BE9441's three-hour session; SFM sends `00 00`. **`0x09` `[200:202]`:** Blastware echoed the unit's `8c 76` on all nine April writes; on 10-26 it read `17 17` and wrote `78 76` (read back so); meaning unknown. **Blastware re-renders the mic trigger level:** on BE11529's first write (4-20 15:19) the unit read 0.005 and 0.01 psi in its two `MicL` channel blocks (3 and 7; Series 3 carries 8 channel blocks of 48 bytes from `[1708]`, the second four prefixed `0x32`) and Blastware wrote 0.004983 and 0.010058 -- the same levels to its 0.1 dB; every other write left them alone. **Every one of the 11 Blastware writes reproduces** from the block before it with only the fields Blastware changed (plus that re-render and, on 10-26, the mic bit of `[25]`). Code: `minimateplus.protocol.assemble_compliance_content`, `read_compliance_content`, `micromate.setup_fields`; tests `tests/test_s3_settings_read.py`, `tests/test_setup_fields.py`. | diff --git a/minimateplus/framing.py b/minimateplus/framing.py index cab24be..4d027c0 100644 --- a/minimateplus/framing.py +++ b/minimateplus/framing.py @@ -534,13 +534,13 @@ STRT_MARKER = b"STRT" def unescape_reply(data: bytes) -> bytes: """A reply's data with each kept escape removed: `10 02/03/04` → `02/03/04`. - The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do - (checksum included: 7,747 of 7,747 recorded replies, March to October 2026, - #58; the 748 measured on 2026-10-26 were Blastware's requests). S3FrameParser - collapses `10 10` but keeps the `10` of `10 02/03/04` (inner-frame markers to - it) everywhere but the checksum, so its `.data` carries an - extra byte before each 02/03/04 value -- harmless for fields read before the - escape, one byte off for any read after it, or counted from the end.""" + The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do, + the checksum included (748/748 replies, 2026-10-26; 7,747 / 7,747 across every + recording, March to October 2026, #58). S3FrameParser collapses `10 10` but + keeps the `10` of `10 02/03/04` (inner-frame markers to it) everywhere but the + checksum, so its `.data` carries an extra byte before each 02/03/04 value -- + harmless for fields read before the escape, one byte off for any read after it, + or counted from the end.""" out, i = bytearray(), 0 while i < len(data): if data[i] == DLE and i + 1 < len(data) and data[i + 1] in (STX, ETX, 0x04):