Files
seismo-relay/tests/test_setup_fields.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

308 lines
13 KiB
Python

"""One settings codec for both series (phase 5): the field registry, the limits,
the byte patching, and the read-back verdict.
Ground truth:
* Series 3: Blastware's own compliance writes -- BE11529's nine on 2026-04-20
(bridges/captures/4-20-26) and BE9441's two on 2026-10-26 -- each reproduced
from the block before it with the fields Blastware changed.
* Series 4: the 15 UM20147 / UM12947 keypad fixtures, pairwise.
Limits are the units' own, from Instantel's manuals (Brian, 2026-11-03).
"""
from __future__ import annotations
import glob
import itertools
import os
import re
import struct
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from micromate import setup_fields as sf # noqa: E402
from micromate.setup_block import crc_ok # noqa: E402
from micromate.setup_fields import ( # noqa: E402
SettingsValueError, check_changes, editable_fields, encode_setup, field_bytes, field_values,
revision, settings_state,
)
from minimateplus.framing import S3FrameParser # noqa: E402
from minimateplus.protocol import assemble_compliance_content, is_compliance_content # noqa: E402
from test_minimate_write_frames import WRITES, _frames, _payload # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
APRIL = ROOT / "bridges" / "captures" / "4-20-26"
S4_FIX = sorted(glob.glob(str(ROOT / "tests" / "fixtures" / "micromate-setup" / "*.bin")))
TEN26 = ROOT / "tests" / "fixtures" / "minimate-bench-10-26-26-histogram"
def _s4(path) -> bytes:
b = Path(path).read_bytes()
return b[-2092:] if len(b) > 2092 else b
def _image(frames) -> bytes:
return b"".join(_payload(f)[16:] for f in frames if _payload(f)[2] == 0x71)
def _reads(replies: bytes) -> list:
"""Each 1A read in a reply stream, assembled (a probe reply starts each)."""
reads, cur = [], None
for f in S3FrameParser().feed(replies):
if f.sub != 0xE5:
continue
if len(f.data) == 11:
cur = []
reads.append(cur)
elif cur is not None:
cur.append(bytes(f.data))
return [assemble_compliance_content(r) for r in reads if r]
def _april_pairs() -> list:
"""(name, before, after) for BE11529's April writes, in time order."""
if not APRIL.is_dir():
return []
files = sorted(glob.glob(str(APRIL / "**" / "raw_bw_*.bin"), recursive=True),
key=lambda p: re.search(r"_(\d{6})_", os.path.basename(p)).group(1))
imgs = [(os.path.basename(p), _image(_frames(Path(p).read_bytes()))) for p in files]
imgs = [(n, i) for n, i in imgs if len(i) >= 2092]
pairs = []
first_name, first_img = imgs[0]
s3 = Path(str(Path(files[0]).parent / first_name.replace("raw_bw_", "raw_s3_")))
whole = [r for r in _reads(s3.read_bytes())] if s3.exists() else []
whole = [r for r in whole if is_compliance_content(r)]
if whole: # the read Blastware took before its first write
pairs.append((first_name, whole[0], first_img))
for (_, a), (n, b) in zip(imgs, imgs[1:]):
pairs.append((n, a, b))
return pairs
def _ten26_pairs() -> list:
reads = _reads((TEN26 / "unit_replies.bin").read_bytes())
i0, i1 = _image(WRITES[0:13]), _image(WRITES[13:26])
return [("10-26 send1", reads[0], i0), ("10-26 send2", i0, i1)]
def _changes(before: bytes, after: bytes, series: int) -> dict:
a, b = field_values(before, series), field_values(after, series)
return {f: b[f] for f in b if b[f] != a[f]}
def _with_mic(encoded: bytes, after: bytes) -> bytes:
"""Test-only: BE9441's 16:26 write also turned the mic on ([25] bit 0x08), a
byte v1 does not offer. Copy that one bit from Blastware's image."""
out = bytearray(encoded)
out[25] = (out[25] & ~0x08) | (after[25] & 0x08)
return bytes(out)
def _blastware_mic_rerender(before: bytes, after: bytes) -> bytes:
"""Blastware's write with the unit's own mic trigger levels put back where
Blastware re-rendered them through its dB value. Measured on BE11529's first
write of 2026-04-20 (15:19): the unit read 0.005 and 0.01 psi (channel blocks
3 and 7, `MicL`), Blastware wrote 0.004983 and 0.010058 -- the same levels to
its 0.1 dB. SFM echoes the unit's bytes instead; every other byte must match."""
out = bytearray(after)
for k in range(8):
o = 1708 + 48 * k
if before[o:o + 4] != b"MicL":
continue
a = struct.unpack_from(">f", before, o + 30)[0]
b = struct.unpack_from(">f", after, o + 30)[0]
if a != b and abs(a - b) <= 0.01 * abs(a): # 0.1 dB is 1.2 % in pressure
out[o + 30:o + 34] = before[o + 30:o + 34]
return bytes(out)
S3_PAIRS = _april_pairs() + _ten26_pairs()
@pytest.mark.parametrize("name,before,after", S3_PAIRS, ids=[p[0] for p in S3_PAIRS])
def test_s3_reproduces_every_blastware_write(name, before, after):
out = _with_mic(encode_setup(before[:2090], 3, _changes(before, after, 3)), after)
assert out[:2090] == _blastware_mic_rerender(before, after)[:2090]
def test_the_blastware_writes_are_all_here():
if not APRIL.is_dir():
pytest.skip("bridges/captures is not on this machine")
assert len(S3_PAIRS) >= 10 # 8 April pairs (+1 if its first read is whole) and 2 on 10-26
def _diffs(a: bytes, b: bytes) -> set:
return {i for i in range(2090) if a[i] != b[i]}
def test_s4_fixture_pairs_reproduce():
fb = field_bytes(4)
covered = 0
for pa, pb in itertools.permutations(S4_FIX, 2):
a, b = _s4(pa), _s4(pb)
d = _diffs(a, b)
if not d:
continue
touched = {f for f, bs in fb.items() if bs & d}
if d - set().union(*(fb[f] for f in touched)):
continue # a byte outside the registry moved: not a field-only pair
out = encode_setup(a, 4, {f: field_values(b, 4)[f] for f in touched})
assert out == b, (os.path.basename(pa), os.path.basename(pb))
covered += 1
assert covered >= 10
# ── limits (the units' own) ──────────────────────────────────────────────────
S3_BLOCK = _ten26_pairs()[1][2][:2090] # BE9441, 4096 sps, histogram, Normal range
S4_BLOCK = _s4(ROOT / "tests" / "fixtures" / "micromate-setup" / "um20147_baseline.bin")
def _refused(block, series, changes):
with pytest.raises(SettingsValueError):
check_changes(block, series, changes)
def test_trigger_checked_against_the_new_range():
_refused(S3_BLOCK, 3, {"geo_range": "sensitive", "geo_trigger_ips": 2.0})
assert check_changes(S3_BLOCK, 3, {"geo_range": "sensitive", "geo_trigger_ips": 1.25})
assert check_changes(S3_BLOCK, 3, {"geo_trigger_ips": 2.0})
def test_limits_refuse_outside_values():
for v in (0.004, 10.001, 0.3005):
_refused(S4_BLOCK, 4, {"geo_trigger_ips": v})
for v in (0, 10000):
_refused(S4_BLOCK, 4, {"job_number": v})
for v in (0.9, 90.1):
_refused(S4_BLOCK, 4, {"record_time_s": v})
assert check_changes(S4_BLOCK, 4, {"record_time_s": 90.0})
assert check_changes(S3_BLOCK, 3, {"record_time_s": 26.0}) # 4096 sps
_refused(S3_BLOCK, 3, {"record_time_s": 26.1})
assert check_changes(S3_BLOCK, 3, {"record_mode": "histogram_continuous", "record_time_s": 13.0})
_refused(S3_BLOCK, 3, {"record_mode": "histogram_continuous", "record_time_s": 13.1})
assert check_changes(S3_BLOCK, 3, {"sample_rate": 1024, "record_time_s": 100.0}) # the new rate counts
_refused(S3_BLOCK, 3, {"sample_rate": 8192})
_refused(S3_BLOCK, 3, {"histogram_interval_s": 30})
_refused(S3_BLOCK, 3, {"geo_trigger_ips": "0.3"}) # a number, not a string
_refused(S3_BLOCK, 3, {"job_number": True})
def test_field_not_offered_for_the_series():
with pytest.raises(SettingsValueError, match="Series 4"):
check_changes(S4_BLOCK, 4, {"geo_range": "sensitive"})
_refused(S4_BLOCK, 4, {"no_such_field": 1})
def test_alarm_is_read_only_until_measured():
assert sf.S3_ALARM_WRITE_MEASURED is False
_refused(S3_BLOCK, 3, {"geo_alarm_ips": 1.0})
alarm = next(d for d in editable_fields(S3_BLOCK, 3) if d["field"] == "geo_alarm_ips")
assert alarm["readonly"] is True
def _with_unit(block: bytes, unit: bytes) -> bytes:
out = bytearray(block)
for k in range(3):
out[1708 + 48 * k + 34: 1708 + 48 * k + 38] = unit
return bytes(out)
def test_metric_unit_string_refuses_level_writes():
_refused(_with_unit(S4_BLOCK, b"mm\x00\x00"), 4, {"geo_trigger_ips": 0.3})
assert check_changes(_with_unit(S4_BLOCK, b"in.\x00"), 4, {"geo_trigger_ips": 0.3})
assert check_changes(_with_unit(S4_BLOCK, b"in\x00\x00"), 4, {"geo_trigger_ips": 0.3})
assert check_changes(_with_unit(S4_BLOCK, b"mm\x00\x00"), 4, {"job_number": 5}) # not a level
def test_note_edges():
assert check_changes(S4_BLOCK, 4, {"note_1": ""})
assert check_changes(S4_BLOCK, 4, {"note_1": "x" * 41})
_refused(S4_BLOCK, 4, {"note_1": "x" * 42})
_refused(S4_BLOCK, 4, {"note_1": "café"})
_refused(S4_BLOCK, 4, {"note_1": "tab\there"})
out = encode_setup(S4_BLOCK, 4, {"note_1": ""})
assert out[144:186] == bytes(42)
def test_note_labels_are_never_written():
out = encode_setup(S4_BLOCK, 4, {"note_2": "Loc 9 - North wall"})
assert _diffs(S4_BLOCK, out) <= set(range(208, 250))
assert out[186:208] == S4_BLOCK[186:208]
def test_bit_fields_keep_unknown_bits():
b = bytearray(S4_BLOCK)
b[39] = 0x81
assert encode_setup(bytes(b), 4, {"job_number_shown": True})[39] == 0x83
b[39] = 0x83
assert encode_setup(bytes(b), 4, {"job_number_shown": False})[39] == 0x81
def test_s3_fixed_bytes():
b = bytearray(S3_BLOCK)
b[26:28] = b"\x01\x7f"
assert encode_setup(bytes(b), 3, {"job_number": 7})[26:28] == b"\x00\x00"
def test_s4_encode_recomputes_the_crc():
out = encode_setup(S4_BLOCK, 4, {"job_number": 7})
assert crc_ok(out) and out[40:42] == (7).to_bytes(2, "big")
def test_f32_values_read_back_as_asked():
written = encode_setup(S4_BLOCK, 4, {"geo_trigger_ips": 0.3})
assert struct.unpack_from(">f", written, 1708 + 30)[0] != 0.3 # f32: 0.30000001192
assert field_values(written, 4)["geo_trigger_ips"] == 0.3
assert settings_state(S4_BLOCK, written, written, series=4) == "as asked"
def test_settings_state():
written = encode_setup(S4_BLOCK, 4, {"job_number": 7})
assert settings_state(S4_BLOCK, written, S4_BLOCK, series=4) == "unchanged"
other = encode_setup(S4_BLOCK, 4, {"job_number": 8})
assert settings_state(S4_BLOCK, written, other, series=4) == "differs"
bad = bytearray(written)
bad[2091] ^= 0xFF
assert settings_state(S4_BLOCK, written, bytes(bad), series=4) == "differs"
# Series 3: a block that differs from its image only in Blastware's fixed bytes is as asked
before = bytearray(S3_BLOCK)
before[26:28] = b"\x01\x7f"
before = bytes(before)
assert settings_state(before, encode_setup(before, 3, {}), before, series=3) == "as asked"
def test_revision_is_stable_and_content_sensitive():
r = revision([S4_BLOCK, b"name"])
assert r == revision([S4_BLOCK, b"name"]) and len(r) == 16
assert r != revision([S4_BLOCK, b"nams"])
def test_editable_fields_describe_both_series():
s3 = {d["field"]: d for d in editable_fields(S3_BLOCK, 3)}
s4 = {d["field"]: d for d in editable_fields(S4_BLOCK, 4)}
assert {"geo_range", "geo_alarm_ips"} <= set(s3) and not {"geo_range", "geo_alarm_ips"} & set(s4)
assert s3["record_mode"]["value"] == "histogram" and s3["sample_rate"]["value"] == 4096
assert s3["note_1"]["label"] == "Project" and s3["note_1"]["maxlength"] == 41
assert s4["note_1"]["label"] == "Location"
assert s4["record_time_s"]["max"] == 90.0 and s3["record_time_s"]["max"] == 26.0
# Final review #2: the limits hold on the block that would result, not only on the
# fields in the request -- a one-field change must not leave the unit over them.
def test_limits_hold_on_the_resulting_block():
hot = encode_setup(S3_BLOCK, 3, {"geo_trigger_ips": 2.0})
_refused(hot, 3, {"geo_range": "sensitive"}) # trigger 2.0 > 1.25
alarm = bytearray(S3_BLOCK)
struct.pack_into(">f", alarm, 1708 + 38, 2.0)
for k in (1, 2):
struct.pack_into(">f", alarm, 1708 + 48 * k + 38, 2.0)
_refused(bytes(alarm), 3, {"geo_range": "sensitive"}) # alarm 2.0 > 1.25
_refused(S3_BLOCK, 3, {"record_mode": "histogram_continuous"}) # it holds 20 s; combo max 13
slow = encode_setup(S3_BLOCK, 3, {"sample_rate": 1024, "record_time_s": 100.0})
_refused(slow, 3, {"sample_rate": 4096}) # 100 s > 26 at 4096
assert check_changes(S3_BLOCK, 3, {"note_1": "x"}) # nothing limit-related touched
assert check_changes(hot, 3, {"geo_range": "normal"}) # 2.0 <= 10