fix(devices): validate laser delay limits and keep config rollbacks working
This commit is contained in:
1 parent
1da2ab8998
commit
d324c63e24
2 files changed
+128
-10
No files matched your search
@@ -167,11 +167,12 @@ class _Constants:
|
||||
|
||||
|
||||
class CheckedSignal(Signal):
|
||||
"""Soft signal that validates every write, used for tunable constants.
|
||||
"""Soft signal that validates every write, used for tunable constants and the soft limits.
|
||||
|
||||
Writes come from the constructor and from runtime ``deviceConfig`` updates
|
||||
(``dev.laser_delay.set_device_config({...})``), so a bad value is rejected instead of being
|
||||
used in the next move.
|
||||
Writes come from the constructor, from runtime changes in the client
|
||||
(``dev.laser_delay.step_sleep.set(0.05).wait()``, ``dev.laser_delay.limits = [-20, 20]``) and
|
||||
from runtime ``deviceConfig`` updates, so a bad value is rejected instead of being used in the
|
||||
next move.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, validator: Callable[[object], None] | None = None, **kwargs):
|
||||
@@ -201,6 +202,44 @@ class ComputedPhaseSignal(SignalRO):
|
||||
return value
|
||||
|
||||
|
||||
class _ConstructorOnly:
|
||||
"""Read-only attribute for a constructor-only ``deviceConfig`` key (the PV names).
|
||||
|
||||
When a runtime ``deviceConfig`` update fails, BEC's device server re-applies the whole previous
|
||||
``deviceConfig`` with ``setattr``/``Signal.set`` per key. Without an attribute of that name the
|
||||
rollback itself fails ("Unknown config parameter delay_coarse_pv") and hides the real error.
|
||||
Writing the current value is a no-op; a new value needs a config reload.
|
||||
"""
|
||||
|
||||
def __set_name__(self, owner, name):
|
||||
self._key = name
|
||||
self._attr = f"_{name}"
|
||||
|
||||
def __get__(self, obj, objtype=None):
|
||||
if obj is None:
|
||||
return self
|
||||
return getattr(obj, self._attr)
|
||||
|
||||
def __set__(self, obj, value):
|
||||
if value != getattr(obj, self._attr):
|
||||
raise ValueError(
|
||||
f"{obj.name}: {self._key} can only be changed by reloading the device config "
|
||||
f"(current {getattr(obj, self._attr)!r}, requested {value!r})"
|
||||
)
|
||||
|
||||
|
||||
def _finite_number(name: str) -> Callable[[object], None]:
|
||||
def check(value):
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f"{name} must be a number, got {value!r}") from exc
|
||||
if not math.isfinite(number):
|
||||
raise ValueError(f"{name} must be a finite number, got {value!r}")
|
||||
|
||||
return check
|
||||
|
||||
|
||||
def _positive_number(name: str) -> Callable[[object], None]:
|
||||
def check(value):
|
||||
try:
|
||||
@@ -347,9 +386,20 @@ class LaserDelay(PSIDeviceBase, PositionerBase):
|
||||
CheckedSignal, value="stored", kind=Kind.config, validator=_phase_reference
|
||||
)
|
||||
|
||||
# Soft limits (BEC publishes them as the device limits)
|
||||
low_limit_travel = Cpt(Signal, value=0.0, kind=Kind.omitted)
|
||||
high_limit_travel = Cpt(Signal, value=0.0, kind=Kind.omitted)
|
||||
# Soft limits (BEC publishes them as the device limits). Equal values mean no limits.
|
||||
low_limit_travel = Cpt(
|
||||
CheckedSignal, value=0.0, kind=Kind.omitted, validator=_finite_number("low limit")
|
||||
)
|
||||
high_limit_travel = Cpt(
|
||||
CheckedSignal, value=0.0, kind=Kind.omitted, validator=_finite_number("high limit")
|
||||
)
|
||||
|
||||
# PV names: constructor-only deviceConfig keys, see _ConstructorOnly
|
||||
delay_coarse_pv = _ConstructorOnly()
|
||||
delay_fine_pv = _ConstructorOnly()
|
||||
evr_period_pv = _ConstructorOnly()
|
||||
phase_v1_pv = _ConstructorOnly()
|
||||
phase_v2_pv = _ConstructorOnly()
|
||||
|
||||
# pylint: disable=too-many-arguments,too-many-locals
|
||||
def __init__(
|
||||
@@ -397,8 +447,11 @@ class LaserDelay(PSIDeviceBase, PositionerBase):
|
||||
if limits is not None:
|
||||
if len(limits) != 2:
|
||||
raise ValueError(f"limits must be [low, high], got {limits!r}")
|
||||
self.low_limit_travel.put(float(limits[0]))
|
||||
self.high_limit_travel.put(float(limits[1]))
|
||||
low, high = float(limits[0]), float(limits[1])
|
||||
if low > high:
|
||||
raise ValueError(f"limits must be [low, high] with low <= high, got {limits!r}")
|
||||
self.low_limit_travel.put(low)
|
||||
self.high_limit_travel.put(high)
|
||||
|
||||
# ----------------------------------------------------------------------------------------- #
|
||||
# Positioner interface #
|
||||
@@ -412,7 +465,7 @@ class LaserDelay(PSIDeviceBase, PositionerBase):
|
||||
@property
|
||||
def limits(self) -> tuple[float, float]:
|
||||
"""Soft limits (low, high). Equal values mean no limits."""
|
||||
return (self.low_limit_travel.get(), self.high_limit_travel.get())
|
||||
return (float(self.low_limit_travel.get()), float(self.high_limit_travel.get()))
|
||||
|
||||
@property
|
||||
def moving(self) -> bool:
|
||||
@@ -430,6 +483,11 @@ class LaserDelay(PSIDeviceBase, PositionerBase):
|
||||
if not math.isfinite(number):
|
||||
raise ValueError(f"{self.name}: delay must be finite, got {value!r}")
|
||||
low, high = self.limits
|
||||
if low > high:
|
||||
raise LimitError(
|
||||
f"{self.name}: the limits [{low}, {high}] are inverted; set them again with "
|
||||
f"dev.{self.name}.limits = [low, high] (equal values mean no limits)"
|
||||
)
|
||||
if low < high and not low <= number <= high:
|
||||
raise LimitError(f"{self.name}: {number} ns is outside the limits [{low}, {high}]")
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
@@ -13,7 +14,10 @@ from unittest import mock
|
||||
import numpy as np
|
||||
import ophyd
|
||||
import pytest
|
||||
from bec_lib import messages
|
||||
from bec_lib.bec_yaml_loader import yaml_load
|
||||
from bec_lib.devicemanager import DeviceConfigError
|
||||
from bec_server.device_server.devices.config_update_handler import ConfigUpdateHandler
|
||||
from bec_server.device_server.devices.device_serializer import get_device_base_class
|
||||
from bec_server.device_server.devices.devicemanager import DeviceManagerDS
|
||||
from ophyd.signal import InternalSignalError
|
||||
@@ -175,6 +179,8 @@ def test_config_overrides_pvs_and_constants():
|
||||
{"vmax": float("nan")},
|
||||
{"step_sleep": -0.1},
|
||||
{"limits": [1.0]},
|
||||
{"limits": [5.0, -5.0]},
|
||||
{"limits": [-5.0, float("inf")]},
|
||||
],
|
||||
)
|
||||
def test_invalid_config_is_rejected(kwargs):
|
||||
@@ -194,6 +200,60 @@ def test_runtime_constant_update_is_validated(calibrated):
|
||||
assert calibrated._constants().phase_reference == "stored"
|
||||
|
||||
|
||||
def test_runtime_limits_are_validated(calibrated):
|
||||
"""BEC writes runtime limits (dev.laser_delay.limits = [...]) one signal at a time."""
|
||||
with pytest.raises(ValueError):
|
||||
calibrated.low_limit_travel.set(float("nan")).wait(timeout=2)
|
||||
calibrated.low_limit_travel.set(5.0).wait(timeout=2)
|
||||
calibrated.high_limit_travel.set(-5.0).wait(timeout=2)
|
||||
with pytest.raises(LimitError, match="inverted"):
|
||||
calibrated.set(0.0)
|
||||
calibrated.high_limit_travel.set(10.0).wait(timeout=2)
|
||||
with pytest.raises(LimitError, match="outside"):
|
||||
calibrated.set(0.0)
|
||||
calibrated.set(7.0).wait(timeout=10)
|
||||
assert calibrated.read()["laser_delay"]["value"] == 7.0
|
||||
|
||||
|
||||
def config_update_handler(device: LaserDelay, device_config: dict) -> ConfigUpdateHandler:
|
||||
"""BEC's ConfigUpdateHandler with just enough device manager for runtime deviceConfig updates."""
|
||||
entry = mock.MagicMock()
|
||||
entry.name, entry.enabled, entry.obj = device.name, True, device
|
||||
entry._config = {"deviceConfig": dict(device_config)}
|
||||
device_manager = mock.MagicMock()
|
||||
device_manager.devices = {device.name: entry}
|
||||
device_manager.update_config = functools.partial(DeviceManagerDS.update_config, device_manager)
|
||||
handler = ConfigUpdateHandler.__new__(ConfigUpdateHandler)
|
||||
handler.device_manager = device_manager
|
||||
return handler
|
||||
|
||||
|
||||
def test_runtime_config_update_errors_name_the_real_problem():
|
||||
"""A failed runtime deviceConfig update makes BEC re-apply the whole previous deviceConfig,
|
||||
including the PV names. That rollback must succeed so the user sees the actual error."""
|
||||
entry = yaml_load(str(CONFIG_DIR / "x10da_laser_delay.yaml"))["laser_delay"]
|
||||
with patched_device(LaserDelay, name="laser_delay", **entry["deviceConfig"]) as device:
|
||||
handler = config_update_handler(device, entry["deviceConfig"])
|
||||
|
||||
def update(config):
|
||||
msg = messages.DeviceConfigMessage(
|
||||
action="update", config={"laser_delay": {"deviceConfig": config}}
|
||||
)
|
||||
handler._update_config(msg, threading.Event())
|
||||
|
||||
with pytest.raises(DeviceConfigError, match="phase_reference must be one of"):
|
||||
update({"phase_reference": "readbak"})
|
||||
assert device.phase_reference.get() == "stored"
|
||||
with pytest.raises(DeviceConfigError, match="reloading the device config"):
|
||||
update({"phase_v1_pv": "X10DA-ES4:AO-03"})
|
||||
assert device.phase_v1.pvname == "X10DA-ES4:AO-02"
|
||||
with pytest.raises(DeviceConfigError, match="finite"):
|
||||
update({"limits": [float("nan"), 1.0]})
|
||||
update({"step_sleep": 0.05, "phase_v1_pv": "X10DA-ES4:AO-02", "limits": [-20, 20]})
|
||||
assert device.step_sleep.get() == 0.05
|
||||
assert device.limits == (-20.0, 20.0)
|
||||
|
||||
|
||||
def test_calibration_signals_are_internal(calibrated):
|
||||
"""Calibration can only change through calibrate()/set_calibration()/moves."""
|
||||
with pytest.raises(InternalSignalError):
|
||||
|
||||
Reference in new issue
Block a user