feat(sfm): POST /device/settings/change; retire the legacy config write
DeviceAccess.change_settings refuses before any I/O a request with no changes, a live change without its preview's revision, or no audit log, then dispatches the series' change (never retried). The route returns the preview (fields old -> new, warnings, blocked, revision) or the result (fields old/new/now), statuses as the other changes, and marks the cached by-host config dirty after a live change. /device/config and /device/config/project now answer 410 with a pointer. Deleted with them: MiniMateClient.apply_config / set_project_info and the raw-offset _encode_compliance_config (#46 found it wrong), the lab script poc_set_project.py and experiments.py's EXP6, both of which wrote a live unit through it. Git keeps them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
66bb29b9d4
commit
e8eabee4a2
10 files changed
+316
-749
No files matched your search
@@ -0,0 +1,70 @@
|
||||
"""DeviceAccess.change_settings (phase 5): the series-independent entry point --
|
||||
what it refuses before any I/O, and that it dispatches a change (never retried)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from device_access_fakes import FakeMiniMateClient, FakeMicromateClient # noqa: E402
|
||||
from sfm.device_access.access import DeviceAccess # noqa: E402
|
||||
from sfm.device_access.errors import BadRequest, NotSupported # noqa: E402
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
|
||||
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
|
||||
|
||||
|
||||
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 _never(*a, **kw):
|
||||
raise AssertionError("no connection may be opened")
|
||||
|
||||
|
||||
def _access(s3=_never, s4=_never, audit="default"):
|
||||
return DeviceAccess(s3_client_factory=s3, s4_client_factory=s4, start_reaper=False,
|
||||
audit=Audit() if audit == "default" else audit, sleep=lambda s: None)
|
||||
|
||||
|
||||
def test_live_change_without_revision_is_refused_before_io():
|
||||
with pytest.raises(BadRequest, match="preview first"):
|
||||
_access().change_settings(ADDR, "UM20147", changes={"job_number": 7}, revision=None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [{}, None, "job_number=7"])
|
||||
def test_empty_changes_is_a_bad_request(changes):
|
||||
with pytest.raises(BadRequest):
|
||||
_access().change_settings(ADDR, "BE18193", changes=changes, revision="r", dry_run=True)
|
||||
|
||||
|
||||
def test_a_live_change_without_an_audit_log_is_refused():
|
||||
with pytest.raises(NotSupported, match="audit"):
|
||||
_access(audit=None).change_settings(ADDR, "BE18193", changes={"job_number": 7}, revision="r")
|
||||
|
||||
|
||||
def test_change_settings_dispatches_by_series_with_change_true(monkeypatch):
|
||||
access = _access(s3=lambda a, **kw: FakeMiniMateClient(), s4=lambda a, **kw: FakeMicromateClient())
|
||||
seen = []
|
||||
real = access._dispatch
|
||||
|
||||
def spy(address, serial, s3_op, s4_op, *, change=False):
|
||||
seen.append((serial, change))
|
||||
return real(address, serial, s3_op, s4_op, change=change)
|
||||
monkeypatch.setattr(access, "_dispatch", spy)
|
||||
r3 = access.change_settings(ADDR, "be18193", changes={"job_number": 7}, revision=None, dry_run=True)
|
||||
r4 = access.change_settings(ADDR, "UM20147", changes={"job_number": 7}, revision=None, dry_run=True)
|
||||
assert (r3.series, r4.series) == (3, 4) and r3.outcome == r4.outcome == "dry_run"
|
||||
assert seen == [("BE18193", True), ("UM20147", True)]
|
||||
@@ -213,40 +213,8 @@ def test_each_read_returns_the_block_blastware_then_wrote(read, sub, size):
|
||||
assert block[:-2] == want[:-2] if sub == 0x69 else block == want[:-2]
|
||||
|
||||
|
||||
# -- apply_config writes this unit's own trigger block ---------------------------
|
||||
|
||||
class StubProto:
|
||||
"""Serves BE9441's blocks as read on 2026-10-26; records every write."""
|
||||
|
||||
def __init__(self):
|
||||
self.writes = []
|
||||
|
||||
def read_event_index(self):
|
||||
return _image(0x68)[:-2]
|
||||
|
||||
def read_compliance_config(self):
|
||||
return _image(0x71)[:-2]
|
||||
|
||||
def read_waveform_data_raw(self):
|
||||
return _image(0x69)
|
||||
|
||||
def read_trigger_config(self):
|
||||
return _image(0x82)[:-2]
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name.startswith("write_"):
|
||||
return lambda *a, **k: self.writes.append((name, a))
|
||||
raise AttributeError(name)
|
||||
|
||||
|
||||
def test_apply_config_writes_the_units_own_trigger_block():
|
||||
from minimateplus.client import MiniMateClient
|
||||
c = MiniMateClient(transport=object())
|
||||
c._proto = StubProto()
|
||||
c.apply_config() # nothing changed: a round trip
|
||||
trig = [a[0] for n, a in c._proto.writes if n == "write_trigger_config"]
|
||||
assert trig == [_image(0x82)[:-2]]
|
||||
assert trig[0][5] == 0x01 # BE9441's; the March copy had 0x03
|
||||
# -- the unit's own trigger block is sent back: tests/test_device_access_s3_settings.py
|
||||
# (test_s3_trigger_change_sends_the_units_own_blocks), phase 5.
|
||||
|
||||
|
||||
def test_a_bad_block_is_refused_before_the_first_write_goes_out():
|
||||
|
||||
@@ -96,30 +96,5 @@ def test_a_reply_without_the_settings_block_reads_as_unknown():
|
||||
(None, None, None, None)
|
||||
|
||||
|
||||
# The write side (review finding, 2026-10-29). _encode_compliance_config patches
|
||||
# the RAW bytes at offsets measured at 1024 sps (April 2026), where an escape sits
|
||||
# between the mode and the anchor. At other rates the mode is one byte later, so
|
||||
# a mode change rewrote the byte in front of it. A payload that would not read
|
||||
# back as asked is refused before anything is sent.
|
||||
|
||||
from minimateplus.client import _encode_compliance_config # noqa: E402
|
||||
|
||||
|
||||
def _block(i):
|
||||
return _settings_replies()[i].ljust(2126, b"\x00") # a whole block's length
|
||||
|
||||
|
||||
@pytest.mark.parametrize("i, change", [
|
||||
(0, {"recording_mode": 0}), # 10-25 Continuous / 4096: mode sits at -7, not -8
|
||||
(1, {"sample_rate": 4096}), # 10-26 Histogram+Continuous / 2048: escaped mode shifts the rate
|
||||
])
|
||||
def test_a_change_that_would_not_read_back_is_refused(i, change):
|
||||
with pytest.raises(ValueError, match="read back"):
|
||||
_encode_compliance_config(_block(i), **change)
|
||||
|
||||
|
||||
def test_a_change_that_reads_back_as_asked_is_built():
|
||||
out = _encode_compliance_config(_block(0), record_time=7.0)
|
||||
cc = _decode(out)
|
||||
assert (cc.recording_mode, cc.sample_rate, cc.histogram_interval_sec, cc.record_time) == \
|
||||
(1, 4096, 5, 7.0)
|
||||
# The write side moved to the shared settings codec in phase 5 (2026-11-03):
|
||||
# tests/test_setup_fields.py reproduces every Blastware write byte for byte.
|
||||
@@ -23,7 +23,7 @@ from fastapi import HTTPException # noqa: E402
|
||||
|
||||
import sfm.server as srv # noqa: E402
|
||||
|
||||
WRITES = {"delete_all_events", "apply_config", "set_call_home_config", "stop_monitoring"}
|
||||
WRITES = {"delete_all_events", "set_call_home_config", "stop_monitoring"}
|
||||
ADDR = dict(port=None, baud=38400, host="10.0.0.9", tcp_port=9034)
|
||||
|
||||
|
||||
@@ -56,9 +56,6 @@ class Unit:
|
||||
def delete_all_events(self):
|
||||
self._rec("delete_all_events")
|
||||
|
||||
def apply_config(self, **kw):
|
||||
self._rec("apply_config")
|
||||
|
||||
def set_call_home_config(self, **kw):
|
||||
self._rec("set_call_home_config")
|
||||
|
||||
@@ -72,8 +69,6 @@ class Cache:
|
||||
|
||||
|
||||
def _call(route, serial):
|
||||
if route == "config":
|
||||
return srv.device_config(body=srv.DeviceConfigBody(), serial=serial, **ADDR)
|
||||
if route == "erase":
|
||||
return srv.device_events_erase(serial=serial, **ADDR)
|
||||
if route == "rescue":
|
||||
@@ -98,7 +93,7 @@ def unit(monkeypatch):
|
||||
return make
|
||||
|
||||
|
||||
ROUTES = ["config", "erase", "rescue", "call_home"]
|
||||
ROUTES = ["erase", "rescue", "call_home"] # /device/config is retired (410)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ROUTES)
|
||||
@@ -131,8 +126,8 @@ def test_guarded_route_proceeds_for_the_named_series3_unit(unit, route):
|
||||
|
||||
|
||||
def test_the_identity_check_reuses_connects_serial_where_there_is_one(unit):
|
||||
# speed: config and erase already read the serial in connect(); no extra read
|
||||
for route in ("config", "erase"):
|
||||
# speed: erase already reads the serial in connect(); no extra read
|
||||
for route in ("erase",):
|
||||
u = unit("BE9441")
|
||||
_call(route, None)
|
||||
assert "read_serial" not in u.calls
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""POST /device/settings/change (phase 5), and the legacy config write retired.
|
||||
Handlers are called directly, every parameter passed, as in
|
||||
test_server_device_access.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import micromate.protocol as mm_proto # noqa: E402
|
||||
import sfm.server as srv # noqa: E402
|
||||
from device_access_fakes import FakeMicromateClient, schedule_record # noqa: E402
|
||||
from fastapi import HTTPException # noqa: E402
|
||||
from sfm.device_access.access import DeviceAccess # noqa: E402
|
||||
|
||||
TCP = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
class Cache:
|
||||
def __init__(self):
|
||||
self.dirty = []
|
||||
|
||||
def mark_config_dirty(self, key):
|
||||
self.dirty.append(key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def unit(monkeypatch):
|
||||
def make(fake):
|
||||
access = DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False,
|
||||
audit=Audit(), sleep=lambda s: None)
|
||||
monkeypatch.setattr(srv, "_device_access_instance", access)
|
||||
cache = Cache()
|
||||
monkeypatch.setattr(srv, "get_cache", lambda: cache)
|
||||
return cache
|
||||
return make
|
||||
|
||||
|
||||
def _post(changes, *, revision=None, dry_run=False, serial="UM20147"):
|
||||
return srv.device_settings_change(body=srv.SettingsChangeBody(changes=changes, revision=revision),
|
||||
serial=serial, dry_run=dry_run, caller="test", **TCP)
|
||||
|
||||
|
||||
def _body(resp):
|
||||
return json.loads(resp.body)
|
||||
|
||||
|
||||
def test_route_dry_run_returns_fields_and_revision(unit):
|
||||
cache = unit(FakeMicromateClient())
|
||||
resp = _post({"geo_trigger_ips": 0.3}, dry_run=True)
|
||||
body = _body(resp)
|
||||
assert resp.status_code == 200 and body["outcome"] == "dry_run"
|
||||
assert body["plan"]["fields"]["geo_trigger_ips"] == {"label": "Geophone trigger", "old": 0.5, "new": 0.3}
|
||||
assert len(body["plan"]["revision"]) == 16 and cache.dirty == []
|
||||
|
||||
|
||||
def test_route_verified_change_is_200_and_mismatch_409(unit, monkeypatch):
|
||||
fake = FakeMicromateClient()
|
||||
cache = unit(fake)
|
||||
rev = _body(_post({"geo_trigger_ips": 0.3}, dry_run=True))["plan"]["revision"]
|
||||
resp = _post({"geo_trigger_ips": 0.3}, revision=rev)
|
||||
assert resp.status_code == 200 and _body(resp)["state_after"] == "as asked"
|
||||
assert len(cache.dirty) == 1 # a by-host read must not serve stale settings
|
||||
# a unit that acks but stores something else reads back "differs": 409
|
||||
fake2 = FakeMicromateClient()
|
||||
unit(fake2)
|
||||
rev = _body(_post({"job_number": 7}, dry_run=True))["plan"]["revision"]
|
||||
real = fake2.protocol.execute
|
||||
|
||||
def wrong(plan):
|
||||
acks = real(plan)
|
||||
fake2.setup = fake2.setup[:40] + b"\x00\x08" + fake2.setup[42:]
|
||||
from micromate.setup_block import with_crc
|
||||
fake2.setup = with_crc(fake2.setup)
|
||||
return acks
|
||||
monkeypatch.setattr(fake2.protocol, "execute", wrong)
|
||||
resp = _post({"job_number": 7}, revision=rev)
|
||||
assert resp.status_code == 409 and _body(resp)["verified"] == "mismatch"
|
||||
|
||||
|
||||
def test_route_unconfirmed_carries_sent_and_audit_id(unit, monkeypatch):
|
||||
fake = FakeMicromateClient()
|
||||
unit(fake)
|
||||
rev = _body(_post({"geo_trigger_ips": 0.3}, dry_run=True))["plan"]["revision"]
|
||||
real = fake.protocol.execute
|
||||
|
||||
def then_drop(plan):
|
||||
acks = real(plan)
|
||||
fake.run_states = [0x03] # it began calling home before the read-back
|
||||
return acks
|
||||
monkeypatch.setattr(fake.protocol, "execute", then_drop)
|
||||
resp = _post({"geo_trigger_ips": 0.3}, revision=rev)
|
||||
body = _body(resp)
|
||||
assert body["sent"] == "acknowledged" and body["audit_id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fake_kw, match", [
|
||||
(dict(schedule_body=schedule_record(14, 0x02, "other.mmb") + bytes(264)), "other.mmb"),
|
||||
(dict(active_name="factory.MMB"), "factory setup"),
|
||||
(dict(run_states=[0x02]), "stop it first"),
|
||||
])
|
||||
def test_route_refusal_is_409_with_reason(unit, fake_kw, match):
|
||||
fake = FakeMicromateClient(**fake_kw)
|
||||
unit(fake)
|
||||
rev = "0000000000000000"
|
||||
if 0x02 not in fake.run_states: # a monitoring unit refuses the preview too
|
||||
rev = _body(_post({"geo_trigger_ips": 0.3}, dry_run=True))["plan"]["revision"]
|
||||
with pytest.raises(HTTPException) as e:
|
||||
_post({"geo_trigger_ips": 0.3}, revision=rev)
|
||||
assert e.value.status_code == 409 and match in str(e.value.detail)
|
||||
|
||||
|
||||
def test_route_stale_preview_is_409(unit):
|
||||
unit(FakeMicromateClient())
|
||||
with pytest.raises(HTTPException) as e:
|
||||
_post({"geo_trigger_ips": 0.3}, revision="0000000000000000")
|
||||
assert e.value.status_code == 409 and "preview again" in str(e.value.detail)
|
||||
|
||||
|
||||
def test_route_live_without_revision_is_422(unit):
|
||||
unit(FakeMicromateClient())
|
||||
with pytest.raises(HTTPException) as e:
|
||||
_post({"geo_trigger_ips": 0.3})
|
||||
assert e.value.status_code == 422 and "preview first" in str(e.value.detail)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ["device_config", "device_config_project"])
|
||||
def test_legacy_config_routes_are_gone(route, monkeypatch):
|
||||
monkeypatch.setattr(srv, "_build_client", lambda *a, **kw: pytest.fail("no client may be built"))
|
||||
resp = getattr(srv, route)()
|
||||
assert resp.status_code == 410 and "/device/settings/change" in _body(resp)["detail"]
|
||||
|
||||
|
||||
def test_settings_change_is_serial_aware():
|
||||
assert "/device/settings/change" in srv._SERIAL_AWARE_PATHS
|
||||
assert srv._device_guard("/device/settings/change", {"serial": "UM20147", "host": "h"}) is None
|
||||
Reference in new issue
Block a user