Files
seismo-relay/tests/test_device_access_s3_settings.py
T
serversdownandClaude Opus 5.5 08d0a6c0d4 fix(settings): final-review fixes -- revision, resulting limits, logical writes
From the whole-branch review of phase 5:
- The preview's revision now covers the changes asked for, so a live
  change must be exactly what was previewed (any API caller, not only the
  page).  It covers what the preview showed -- the settings block (and a
  Micromate's setup name) -- not the blocks a write only echoes, which are
  re-read at send and sent as read (a MiniMate's trigger block byte 5
  differs by session, #46).
- The units' limits hold on the block that would result: a range, rate or
  mode change alone can no longer leave a held trigger, alarm or record
  time over them.
- Every MiniMate block read is logical, so push_config_raw no longer
  unescapes again (a job number of 4098, 10 02, was refused at Send); the
  preview runs the write's own block check, so a block it would refuse is
  shown as blocked.
- A MiniMate's monitoring refusal says a stop makes it call in (spec).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 22:10:49 -05:00

234 lines
9.9 KiB
Python

"""Changing a MiniMate's settings by serial (phase 5): preview, one audited send,
read back. The settings block is the 1A read assembled into its 2,090 logical
bytes; the write is push_config_raw's Blastware sequence (68 73 | 71 x n 72 |
82 83 | 69 74 72) with the event index, trigger and waveform blocks sent back as
read. Fixture blocks: BE9441, 2026-10-26."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import minimateplus.protocol as mp # noqa: E402
from device_access_fakes import FakeMiniMateClient, s3_settings_blocks # noqa: E402
from micromate.setup_fields import encode_setup, field_values # noqa: E402
from minimateplus.client import MiniMateClient # noqa: E402
from minimateplus.protocol import ImageRefused # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
BadRequest, DeviceError, SettingsChanged, UnitStateUnknown,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s3 import Series3Adapter # noqa: E402
TCP = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None)
BW_ORDER = ["0x68", "0x73", "0x71", "0x72", "0x82", "0x83", "0x69", "0x74", "0x72"]
class Audit:
def __init__(self):
self.rows = {}
def begin(self, **f):
cid = f"c{len(self.rows) + 1}"
self.rows[cid] = dict(f, outcome="pending")
return cid
def finish(self, cid, **f):
self.rows[cid].update(f)
def adapter(fake):
return Series3Adapter(client_factory=lambda address, **kw: fake)
def change(fake, changes, *, revision=None, dry_run=False, audit=None):
return adapter(fake).change_settings(
TCP, "BE18193", changes=changes, revision=revision, dry_run=dry_run,
audit=audit if audit is not None else Audit(), caller="test", sleep=lambda s: None,
verify_timeout_s=2.0, verify_interval_s=1.0)
def live(fake, changes, audit=None):
rev = change(fake, changes, dry_run=True).plan["revision"]
return change(fake, changes, revision=rev, audit=audit)
def test_s3_settings_read_uses_the_codec():
s = adapter(FakeMiniMateClient()).settings(TCP, "BE18193")
assert (s.record_mode, s.sample_rate, s.histogram_interval_s) == ("Histogram", 4096, 2)
assert (s.record_time_s, s.geo_trigger_ips) == (20.0, 0.04)
assert s.notes["Project"] == "TestUnit-Minimate" and s.notes["Client"] == "Terra-Mechanics"
assert s.detail["record_mode_code"] == 0x03 and s.detail["geo_range"] == "normal"
fields = {d["field"]: d for d in s.detail["editable"]}
assert fields["geo_range"]["value"] == "normal" and fields["note_1"]["label"] == "Project"
def test_s3_settings_read_of_a_monitoring_unit_says_why():
with pytest.raises(UnitStateUnknown, match="stop monitoring first"):
adapter(FakeMiniMateClient(monitoring_settings=True)).settings(TCP, "BE18193")
def test_s3_dry_run_previews_and_sends_nothing():
fake = FakeMiniMateClient()
r = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True)
assert r.outcome == "dry_run" and fake.writes == []
assert r.plan["fields"] == {"geo_trigger_ips": {"label": "Geophone trigger", "old": 0.04, "new": 0.05}}
assert [s["sub"] for s in r.plan["steps"]] == BW_ORDER
assert any("00 00" in w for w in r.plan["warnings"]) and r.plan["blocked"] == []
assert len(r.plan["revision"]) == 16
def test_s3_trigger_change_sends_the_units_own_blocks():
fake = FakeMiniMateClient()
blocks = s3_settings_blocks()
live(fake, {"geo_trigger_ips": 0.05})
event_index, compliance, trigger, waveform = fake.pushed
assert (event_index, trigger, waveform) == (blocks["event_index"], blocks["trigger"], blocks["waveform"])
assert compliance == encode_setup(blocks["compliance"], 3, {"geo_trigger_ips": 0.05})
def test_s3_change_verifies_by_read_back():
fake = FakeMiniMateClient()
r = live(fake, {"geo_trigger_ips": 0.05, "note_4": "Loc 2 - north wall"})
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "as asked")
rows = r.detail["snapshot"]["fields"]
assert rows["geo_trigger_ips"] == {"label": "Geophone trigger", "old": 0.04, "new": 0.05, "now": 0.05}
assert rows["note_4"]["now"] == "Loc 2 - north wall"
assert field_values(fake.settings_blocks["compliance"], 3)["geo_trigger_ips"] == 0.05
def test_s3_stale_revision_sends_nothing():
fake = FakeMiniMateClient()
rev = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True).plan["revision"]
fake.settings_blocks["compliance"] = encode_setup(fake.settings_blocks["compliance"], 3, {"job_number": 9})
audit = Audit()
with pytest.raises(SettingsChanged):
change(fake, {"geo_trigger_ips": 0.05}, revision=rev, audit=audit)
assert fake.writes == [] and audit.rows == {}
@pytest.mark.parametrize("dry_run", [True, False])
def test_s3_monitoring_is_refused(dry_run):
fake = FakeMiniMateClient(monitoring_settings=True)
with pytest.raises(UnitStateUnknown) as e:
change(fake, {"geo_trigger_ips": 0.05}, revision="x", dry_run=dry_run)
assert "stop monitoring first" in str(e.value) and "nothing sent" in str(e.value)
assert fake.writes == []
def test_s3_a_value_the_unit_does_not_allow_is_a_bad_request():
with pytest.raises(BadRequest):
change(FakeMiniMateClient(), {"record_time_s": 30.0}, dry_run=True) # 4096 sps: 26 s at most
def test_s3_a_refused_image_is_audited_as_nothing_sent():
audit = Audit()
fake = FakeMiniMateClient(write_error=ImageRefused("write SUB 0x71: not a whole block"))
rev = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True).plan["revision"]
with pytest.raises(DeviceError):
change(fake, {"geo_trigger_ips": 0.05}, revision=rev, audit=audit)
((_, row),) = audit.rows.items()
assert (row["outcome"], row["sent"]) == ("failed", 0)
assert row["error"].startswith("refused before sending")
class _Recorder:
def __init__(self):
self.sent = []
def write(self, data):
self.sent.append(bytes(data))
def read(self, n):
return b""
def test_push_config_raw_precheck_raises_image_refused():
t = _Recorder()
c = MiniMateClient("unused")
c._proto = mp.MiniMateProtocol(t, recv_timeout=0.2)
b = s3_settings_blocks()
with pytest.raises(ImageRefused):
c.push_config_raw(b["event_index"], b["compliance"][:2089], b["trigger"], b["waveform"])
assert t.sent == []
# Final review #1: the revision covers the changes previewed, not only the unit.
def test_s3_a_revision_covers_the_changes_previewed():
fake = FakeMiniMateClient()
rev = change(fake, {"job_number": 7}, dry_run=True).plan["revision"]
with pytest.raises(SettingsChanged):
change(fake, {"geo_trigger_ips": 0.05}, revision=rev)
assert fake.writes == []
# Ruling: the trigger block's byte 5 "differs by unit and session" (#46); the three
# echoed blocks are re-read at send and sent as read, so they are not in the revision.
def test_s3_an_echoed_block_moving_does_not_stale_the_preview():
fake = FakeMiniMateClient()
rev = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True).plan["revision"]
trig = bytearray(fake.settings_blocks["trigger"])
trig[5] = 0x03
fake.settings_blocks["trigger"] = bytes(trig)
assert change(fake, {"geo_trigger_ips": 0.05}, revision=rev).verified == "ok"
assert fake.pushed[2] == bytes(trig) # sent as read at send time
# Final review #4 (spec): the refusal says a stop makes the unit call in.
def test_s3_monitoring_refusal_says_a_stop_calls_in():
with pytest.raises(UnitStateUnknown) as e:
change(FakeMiniMateClient(monitoring_settings=True), {"geo_trigger_ips": 0.05}, dry_run=True)
assert "call in" in str(e.value) and "call-home" in str(e.value)
# Final review #3: the blocks are logical bytes; a block holding a literal
# 10 02 / 10 03 / 10 04 (job number 4098 = 0x1002) must be written intact, and a
# block the write would refuse must show in the preview, not only at Send.
def test_s3_a_bad_echoed_block_is_blocked_in_the_preview():
fake = FakeMiniMateClient()
fake.settings_blocks["event_index"] = fake.settings_blocks["event_index"][:-1]
r = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True)
assert r.plan["blocked"] and r.plan["steps"] == []
from sfm.device_access.errors import ChangeRefused
with pytest.raises(ChangeRefused):
change(fake, {"geo_trigger_ips": 0.05}, revision=r.plan["revision"])
assert fake.writes == []
def _acking():
from minimateplus.framing import build_bw_write_frame # noqa: F401 (frames are parsed below)
from test_minimate_write_frames import _payload
class Acks:
def __init__(self):
self.sent, self._buf = [], b""
def write(self, data):
data = bytes(data)
self.sent.append(data)
sub = _payload(data)[2]
body = bytes([0x00, 0x10, 0xFF - sub, 0x00, 0x00]) + bytes(11)
body += bytes([sum(body) & 0xFF])
self._buf += b"\x10\x02" + body.replace(b"\x10", b"\x10\x10") + b"\x03"
def read(self, n):
out, self._buf = self._buf[:n], self._buf[n:]
return out
return Acks()
def test_push_config_raw_writes_a_logical_block_with_a_literal_escape_byte_intact():
from test_minimate_write_frames import _payload
t = _acking()
c = MiniMateClient("unused")
c._proto = mp.MiniMateProtocol(t, recv_timeout=0.5)
b = s3_settings_blocks()
block = encode_setup(b["compliance"], 3, {"job_number": 4098}) # [40:42] = 10 02
assert block[40:42] == b"\x10\x02"
c.push_config_raw(b["event_index"], block, b["trigger"], b["waveform"])
sent = b"".join(_payload(f)[16:] for f in t.sent if _payload(f)[2] == 0x71)
assert sent == block + b"\x00\x00"