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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-06 14:52:50 -05:00
1 parent d2fe675650
commit 89c5234ac0
6 files changed
+214 -71

No files matched your search

+12 -52
View File
@@ -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 ───────────────────────────────────────────────────────────
+3 -2
View File
@@ -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
+11 -8
View File
@@ -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)
+8 -6
View File
@@ -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))
+19 -3
View File
@@ -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 ──────────────────────────────────────
+161
View File
@@ -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