fix(minimateplus): a built call-home image is framed once, never unescaped again (phase-4 review)

call_home_image returns the unescaped N + 2 image, but the send path handed it
to write_call_home_config, whose write_image unescapes again -- and unescaping
is not idempotent: a real 0x10 before 02/03/04 loses its 0x10.  A call-in time
of 16:02-16:04 (hour 0x10) is exactly that.  One such time made the send refuse
before the wire yet audited as 'sent, acknowledgement lost'; two made it send a
block shifted by two bytes from [101] (num_retries and the time fields wrong).
The Blastware-frame test could not see it: it checked the image builder, not
the bytes the protocol framed.

- MiniMateProtocol.write_call_home_image(image) frames a built image once
  (0x7E, ack 0x81, 0x7F, ack 0x80), raising ImageRefused before any byte when
  it is not a whole block; write_call_home_config (the legacy multi-field path)
  is write_image once + that.  Its stale 127-byte docstring is gone.
- MiniMateClient.write_call_home_image uses it.
- The Series-3 change passes is_refusal=ImageRefused, so a pre-wire refusal is
  audited as nothing sent (sent = 0), not as a lost ack.

Tests drive the real client -> protocol over a stub answering with BE11529's
recorded acks: the unit's own read, a 16:02 time, and 16:03 + 16:04 all go out
exactly as built; a short image is refused with nothing written.

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-02 17:23:59 -05:00
1 parent 3e1d42e04b
commit bdd76b8f74
5 files changed
+186 -36

No files matched your search

+4 -2
View File
@@ -1134,8 +1134,10 @@ class MiniMateClient:
def write_call_home_image(self, image: bytes) -> None:
"""Send a `0x7E` image (`call_home_image`) and its `0x7F` confirm, each ack
checked. No retry: what happened is the caller's to read back."""
self._require_proto().write_call_home_config(image)
checked -- framed once, never unescaped again. Raises ImageRefused before
any byte goes out for an image that is not a whole block. No retry: what
happened is the caller's to read back."""
self._require_proto().write_call_home_image(image)
def set_call_home_config(
self,
+35 -32
View File
@@ -165,6 +165,10 @@ def write_image(sub: int, data: bytes) -> bytes:
return image
class ImageRefused(ValueError):
"""A write refused before any byte was sent: the image is not a whole block."""
def call_home_enabled(raw: bytes) -> Optional[bool]:
"""The call-home switch of a `0x2C` reply payload, read UNESCAPED (an escaped
byte before it would move the raw index -- bench finding #1's lesson): byte 5,
@@ -1172,41 +1176,40 @@ class MiniMateProtocol:
def write_call_home_config(self, data: bytes) -> None:
"""
Write the auto call home configuration (SUB 0x7E → 0x7F confirm).
Write the call-home block as a read returned it (SUB 0x7E, then 0x7F).
Write sequence (confirmed from 4-20-26 call home settings captures):
SUB 0x7E write 127-byte payload → device acks SUB 0x81
SUB 0x7F confirm (no data) → device acks SUB 0x80
The 127-byte write payload = 125-byte read payload + b'\\x00\\x00'.
The offset field = data[1] + 2 = 0x7C + 2 = 0x7E = 126.
Write frame format: build_bw_write_frame (minimal DLE stuffing — only
BW_CMD is doubled; all other bytes are RAW). The \\x10\\x03 sequence
within the payload is preserved as-is (device interprets DLE+ETX as the
literal value 0x03 per the inner-frame terminator convention).
Args:
data: 127-byte write payload (read payload + \\x00\\x00 footer).
Must start with [0x00][0x7C][...] (standard header).
Raises:
ValueError: if data is not exactly 127 bytes or lacks expected header.
ProtocolError: on timeout or wrong response SUB.
`data` is the 0x2C read payload (125 B, the parser's kept escape bytes
in -- num_retries 3 arrives as 10 03), optionally + 00 00. `write_image`
removes the escapes once and makes the 126-byte image (N = 0x7C, + 2);
`write_call_home_image` sends it. The legacy multi-field path.
"""
rsp_sub_confirm = _expected_rsp_sub(SUB_CALL_HOME_CONFIRM) # 0xFF - 0x7F = 0x80
# 2026-10-27 (#46): the read payload holds the parser's kept escape bytes
# (num_retries 3 arrives as 10 03); write_image removes them, so the
# 127-byte "read + 00 00" goes out as its 126-byte image (N = 0x7C, + 2),
# escaped like every request. No Blastware call-home write is on record
# here to compare against -- inferred from the 77 other write frames.
self._write_block(SUB_CALL_HOME_WRITE, data)
log.debug("write_call_home_config: write acked; sending confirm 0x7F")
self.write_call_home_image(write_image(SUB_CALL_HOME_WRITE, data))
confirm_frame = build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"")
self._send(confirm_frame)
self.recv_write_ack(expected_sub=rsp_sub_confirm)
log.debug("write_call_home_config: confirm acked — done")
def write_call_home_image(self, image: bytes) -> None:
"""
Send a call-home image that is already built (`call_home_image`:
unescaped, N + 2 bytes) -- 0x7E, ack 0x81, then the 0x7F confirm, ack 0x80.
Never through `write_image` again: unescaping is not idempotent, and a
real 0x10 before 02/03/04 in the image -- a call-in time of 16:02-16:04
-- would lose its 0x10 (phase-4 final review, 2026-11-02). Measured: the
frames equal Blastware's 2026-04-20 enable / disable writes (BE11529),
tests/test_s3_call_home_bw_frames.py and test_s3_call_home_wire.py.
Raises ImageRefused, before any byte is sent, unless the image is a whole
block: its header N plus the two trailing bytes.
"""
image = bytes(image)
n = int.from_bytes(image[:2], "big") if len(image) >= 2 else -1
if len(image) != n + 2:
raise ImageRefused(f"write SUB 0x{SUB_CALL_HOME_WRITE:02X}: {len(image)} bytes, but its "
f"header says {n} (+ 2) -- not a whole image; nothing sent")
self._send(build_bw_write_frame(SUB_CALL_HOME_WRITE, image))
self.recv_write_ack(expected_sub=_expected_rsp_sub(SUB_CALL_HOME_WRITE))
log.debug("write_call_home_image: write acked; sending confirm 0x7F")
self._send(build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b""))
self.recv_write_ack(expected_sub=_expected_rsp_sub(SUB_CALL_HOME_CONFIRM))
log.debug("write_call_home_image: confirm acked — done")
# ── Monitoring ────────────────────────────────────────────────────────────
+4 -2
View File
@@ -13,7 +13,7 @@ from minimateplus.event_file_io import _GEO_INT16_FS
from minimateplus.framing import build_bw_write_frame, unescape_reply
from minimateplus.protocol import (
SUB_CALL_HOME_CONFIRM, SUB_CALL_HOME_WRITE, SUB_START_MONITORING, SUB_STOP_MONITORING,
call_home_enabled, call_home_image, write_image,
ImageRefused, call_home_enabled, call_home_image, write_image,
)
from minimateplus.transport import TcpTransport
@@ -418,7 +418,9 @@ class Series3Adapter:
even_if_already=even_if_already, audit=audit, address=address, caller=caller,
sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=read_serial, read_state=read_state,
describe_plan=describe_plan, send=send, snapshot=snapshot)
describe_plan=describe_plan, send=send, snapshot=snapshot,
# raised before the frame goes out: audited as nothing sent
is_refusal=lambda e: isinstance(e, ImageRefused))
return self._run(address, op, retry=False)
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
+18
View File
@@ -127,3 +127,21 @@ def test_s3_dry_run_with_an_unknown_byte_5_shows_no_frames():
fake = FakeMiniMateClient(call_home_raw=s3_call_home_raw(0x07))
r = change(adapter(fake), enabled=False, dry_run=True)
assert r.plan["steps"] == [] and any("0x07" in w for w in r.plan["warnings"])
def test_a_pre_wire_refusal_is_recorded_as_nothing_sent():
# Final review #2: a refusal raised before the frame went out must not be
# audited as "sent, acknowledgement lost".
from minimateplus.protocol import ImageRefused
audit = Audit()
fake = FakeMiniMateClient(write_error=ImageRefused("write SUB 0x7E: not a whole block"))
from sfm.device_access.errors import DeviceError
with pytest.raises(DeviceError) as e: # the adapter wraps it, as it does OpcodeRefused
adapter(fake).change_call_home(TCP, "BE18193", enabled=False, dry_run=False, even_if_already=False,
audit=audit, caller="test", sleep=lambda s: None,
verify_timeout_s=3.0, verify_interval_s=1.0)
assert isinstance(e.value.__cause__, ImageRefused)
((_, row),) = audit.rows.items()
assert (row["outcome"], row["sent"]) == ("failed", 0)
assert row["error"].startswith("refused before sending")
+125
View File
@@ -0,0 +1,125 @@
"""The MiniMate call-home send path frames the built image exactly once
(phase-4 final review #1, 2026-11-02).
`call_home_image` is already unescaped; passing it through `write_image` again
strips any real 0x10 that precedes 02/03/04 -- a call-in time of 16:02-16:04
(hour 0x10) is exactly that. One such time made the send refuse; two made it
send a block shifted by two bytes. Driven through the real MiniMateClient ->
MiniMateProtocol over a stub answering with the unit's recorded acks (BE11529,
2026-04-20).
"""
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__))))
import minimateplus.protocol as mp # noqa: E402
from minimateplus.client import MiniMateClient # noqa: E402
from minimateplus.framing import S3FrameParser, build_bw_write_frame # noqa: E402
from minimateplus.protocol import ( # noqa: E402
SUB_CALL_HOME, SUB_CALL_HOME_CONFIRM, SUB_CALL_HOME_WRITE, call_home_image, write_image,
)
from test_minimate_write_frames import _payload # noqa: E402
FIX = Path(__file__).parent / "fixtures" / "s3-call-home-bw"
def _recorded_ack(path: Path, ack_sub: int) -> bytes:
raw, start, p = path.read_bytes(), 0, S3FrameParser()
for i in range(len(raw)):
for f in p.feed(raw[i:i + 1]):
w = raw[start:i + 1]
if f.sub == ack_sub:
return w[w.index(b"\x10\x02"):]
start = i + 1
raise AssertionError(f"no 0x{ack_sub:02X} ack in {path.name}")
ENABLE_S3 = FIX / "raw_s3_20260420_162221_enable_auto_call_home.bin"
ACKS = {SUB_CALL_HOME_WRITE: _recorded_ack(ENABLE_S3, 0xFF - SUB_CALL_HOME_WRITE),
SUB_CALL_HOME_CONFIRM: _recorded_ack(ENABLE_S3, 0xFF - SUB_CALL_HOME_CONFIRM)}
class Acks:
def __init__(self):
self.sent, self._buf = [], b""
def write(self, data):
data = bytes(data)
self.sent.append(data)
self._buf += ACKS[_payload(data)[2]]
def read(self, n):
out, self._buf = self._buf[:n], self._buf[n:]
return out
def _client():
t = Acks()
c = MiniMateClient("unused")
c._proto = mp.MiniMateProtocol(t)
return c, t
def _fixture_read() -> bytes:
p = FIX / "raw_s3_20260420_162148_pull_call_home_options.bin"
return [bytes(f.data)[11:] for f in S3FrameParser().feed(p.read_bytes())
if f.sub == 0xFF - SUB_CALL_HOME and len(f.data) > 100][-1]
def _as_read(logical: bytes) -> bytes:
"""A block as S3FrameParser returns it: each 02/03/04 keeps its 10 escape
(a logical 0x10 arrives as 10 10, which the parser collapses to one 10)."""
out = bytearray()
for b in logical:
out += bytes([0x10, b]) if b in (0x02, 0x03, 0x04) else bytes([b])
return bytes(out)
def _with_times(t1: bytes, t2: bytes = None) -> bytes:
logical = bytearray(write_image(SUB_CALL_HOME_WRITE, _fixture_read())[:-2]) # the N = 124 bytes
logical[101:103] = t1
if t2 is not None:
logical[105:107] = t2
return _as_read(bytes(logical))
def _frames(image):
return [build_bw_write_frame(SUB_CALL_HOME_WRITE, image), build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"")]
@pytest.mark.parametrize("enabled", [True, False])
def test_the_units_own_read_goes_out_framed_once(enabled):
c, t = _client()
image = call_home_image(_fixture_read(), enabled)
c.write_call_home_image(image)
assert t.sent == _frames(image)
def test_a_16_02_call_in_time_is_sent_as_read():
raw = _with_times(b"\x10\x02")
image = call_home_image(raw, False)
assert image[101:103] == b"\x10\x02" # the image itself is right
c, t = _client()
c.write_call_home_image(image)
assert t.sent == _frames(image)
def test_two_such_times_are_not_shifted():
raw = _with_times(b"\x10\x03", b"\x10\x04")
image = call_home_image(raw, True)
c, t = _client()
c.write_call_home_image(image)
assert t.sent == _frames(image)
def test_a_malformed_image_is_refused_before_the_wire():
c, t = _client()
with pytest.raises(mp.ImageRefused):
c.write_call_home_image(call_home_image(_fixture_read(), True)[:-1])
assert t.sent == []