From d0cfcac2491783dcc4fa54eb80ffbe99cfc38b5e Mon Sep 17 00:00:00 2001 From: David Perl Date: Tue, 3 Nov 2026 13:34:35 +0100 Subject: [PATCH] feat: hack in state change --- .../widgets/aare_bec/task_panel.py | 19 ++++++ mx_bec/tasks.py | 59 ++++++++++++++++--- tests/unit/test_change_state_task.py | 43 ++++++++++++++ tests/unit/test_service.py | 44 +++++++++++++- 4 files changed, 153 insertions(+), 12 deletions(-) create mode 100644 tests/unit/test_change_state_task.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 139deee..72bf021 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -7,6 +7,7 @@ from bec_widgets.utils.error_popups import SafeSlot from qtpy.QtWidgets import ( QDoubleSpinBox, QFormLayout, + QGridLayout, QGroupBox, QHBoxLayout, QLineEdit, @@ -56,6 +57,7 @@ class MxTaskPanel(BECWidget, QWidget): PLUGIN = True ICON_NAME = "play_arrow" USER_ACCESS = ["request_task"] + STATE_BUTTONS_PER_ROW = 4 def __init__( self, @@ -70,8 +72,25 @@ class MxTaskPanel(BECWidget, QWidget): layout = QVBoxLayout(self) for task, fields in TASK_FORMS.items(): layout.addWidget(self._task_box(task, fields)) + layout.addWidget(self._change_state_box()) layout.addStretch() + def _change_state_box(self) -> QGroupBox: + """One button per beamline state, each requesting the `change_state` task.""" + from pxii_bec.macros.beamline_planner import ( # pyright: ignore[reportMissingImports] + BeamlineState, + ) + + box = QGroupBox("change_state", parent=self) + grid = QGridLayout(box) + for i, state in enumerate(BeamlineState): + button = QPushButton(state.value, parent=box) + button.clicked.connect( + lambda *_, state=state.value: self.request_task("change_state", state=state) + ) + grid.addWidget(button, i // self.STATE_BUTTONS_PER_ROW, i % self.STATE_BUTTONS_PER_ROW) + return box + def _task_box(self, task: str, fields: list[tuple[str, int | float | str]]) -> QGroupBox: box = QGroupBox(task, parent=self) form = QFormLayout() diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index c27e7a5..7e6bdbc 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -14,6 +14,8 @@ from mx_bec.jfjoch import RasterScan from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskQueueChangedMessage if TYPE_CHECKING: + from pxii_bec.macros.beamline_planner import StateChangePlanner + from mx_bec.messages import MXTaskExecutionMessage from mx_bec.service import AareBec @@ -32,27 +34,54 @@ class MxTasks: def __init__(self, client: AareBec): self._client = client self._busy_lock = RLock() + self._planner: StateChangePlanner | None = None + + @property + def planner(self) -> StateChangePlanner: + """The beamline state planner, built on first use: `init_beamline_environment` needs the + BEAMLINE environment variable and the beamline devices.""" + if self._planner is None: + # pyright: ignore[reportMissingImports, reportMissingModuleSource] + from pxii_bec.scripts.init_beamline import init_beamline_environment + + _, _, self._planner = init_beamline_environment() + return self._planner @classmethod def is_task(cls, name: str) -> bool: - """Whether `name` can be requested as a task, i.e. is a method decorated with - `with_lock`.""" + """Whether `name` can be requested as a task, i.e. is a method decorated with `task`.""" return getattr(inspect.getattr_static(cls, name, None), "is_mx_task", False) @staticmethod - def with_lock(method: Callable[P, R]) -> Callable[P, R]: - """Mark the decorated method as a task and run it while holding `self._busy_lock`, so - that only one task runs at a time.""" + def task(method: Callable[P, R]) -> Callable[P, R]: + """Mark the decorated method as a task. It runs while holding `self._busy_lock`, so that + only one task runs at a time, and if it raises, the task queue is paused before the + exception propagates, so that queued tasks don't carry on from a failed state.""" @functools.wraps(method) def wrapper(self: MxTasks, *args, **kwargs): - with self._busy_lock: # pylint: disable=protected-access - return method(self, *args, **kwargs) + # pylint: disable=protected-access + with self._busy_lock: + try: + return method(self, *args, **kwargs) + except Exception: + self._pause_queue_after_failure(method.__name__) + raise wrapper.is_mx_task = True return wrapper # type: ignore # self is part of P - @with_lock + def _pause_queue_after_failure(self, task_name: str) -> None: + if (queue := getattr(self._client, "task_queue", None)) is None: + return + logger.warning(f"Task {task_name} failed, pausing the task queue") + try: + queue.pause() + except Exception: # pylint: disable=broad-except + # the task's own exception is the one to surface + logger.exception("Failed to pause the task queue") + + @task def run_optical_centering(self, sample_id: int): """Rotate the Aerotech to each angle from the config, update the optical centering prediction and tell the Smargon to move there. Publishes the `optical_centering_done` @@ -79,7 +108,19 @@ class MxTasks: MXMeasurementSequenceMessage(sample_id=sample_id, success=success), ) - @with_lock + @task + def change_state(self, state: str, modifier: str | None = None) -> None: + """Move the beamline devices to `state`, the value of a `BeamlineState` (e.g. + "sample_alignment"), optionally with a temperature `modifier` ("cryo" or "room_temp").""" + from pxii_bec.macros.beamline_planner import ( # pyright: ignore[reportMissingImports] + BeamlineState, + ) + + target = BeamlineState(state) # reject unknown states before anything moves + logger.info(f"Changing beamline state to {target.value}, modifier={modifier}") + self.planner.move_to(target, modifier) + + @task def run_grid_scan( self, n_x: int, diff --git a/tests/unit/test_change_state_task.py b/tests/unit/test_change_state_task.py new file mode 100644 index 0000000..c74de02 --- /dev/null +++ b/tests/unit/test_change_state_task.py @@ -0,0 +1,43 @@ +from unittest.mock import MagicMock, patch + +import pytest +from pxii_bec.macros.beamline_planner import BeamlineState + +from mx_bec.tasks import MxTasks + + +@pytest.fixture +def tasks(): + tasks = MxTasks(MagicMock()) + tasks._planner = MagicMock() + return tasks + + +def test_planner_is_built_lazily_from_the_beamline_environment(monkeypatch): + monkeypatch.delenv("BEAMLINE", raising=False) + tasks = MxTasks(MagicMock()) # must not need the beamline environment yet + env, devices, planner = MagicMock(), MagicMock(), MagicMock() + with patch( + "pxii_bec.scripts.init_beamline.init_beamline_environment", + return_value=(env, devices, planner), + ) as init: + assert tasks.planner is planner + assert tasks.planner is planner + init.assert_called_once() + + +@pytest.mark.parametrize("modifier", [None, "cryo"]) +def test_change_state_moves_to_the_state(tasks, modifier): + tasks.change_state("sample_alignment", modifier) + tasks.planner.move_to.assert_called_once_with(BeamlineState.SAMPLE_ALIGNMENT, modifier) + + +def test_change_state_rejects_unknown_states(tasks): + with pytest.raises(ValueError, match="no_such_state"): + tasks.change_state("no_such_state") + tasks.planner.move_to.assert_not_called() + + +def test_change_state_is_a_task_and_planner_is_not(): + assert MxTasks.is_task("change_state") + assert not MxTasks.is_task("planner") diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 9cb5c91..1bb3812 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -110,8 +110,9 @@ NOT_TASKS = [ "_publish_optical_centering_done", # private method "_client", # private attribute "_busy_lock", - "with_lock", # public, but a helper rather than a task + "task", # public, but the decorator rather than a task "is_task", + "planner", # property ] @@ -127,9 +128,9 @@ def test_task_request_for_non_task_name_is_rejected(service, name): assert name in logger.warning.call_args.args[0] -def test_tasks_are_exactly_the_methods_decorated_with_with_lock(): +def test_tasks_are_exactly_the_decorated_methods(): class Tasks(MxTasks): - @MxTasks.with_lock + @MxTasks.task def decorated(self): ... def plain(self): ... @@ -140,6 +141,43 @@ def test_tasks_are_exactly_the_methods_decorated_with_with_lock(): assert all(not MxTasks.is_task(name) for name in NOT_TASKS) +class _FailingTasks(MxTasks): + @MxTasks.task + def boom(self): + raise RuntimeError("boom") + + @MxTasks.task + def fine(self): + return "ok" + + +def test_failed_task_pauses_the_queue_and_reraises(): + client = MagicMock() + with pytest.raises(RuntimeError, match="boom"): + _FailingTasks(client).boom() + client.task_queue.pause.assert_called_once() + + +def test_successful_task_does_not_pause_the_queue(): + client = MagicMock() + assert _FailingTasks(client).fine() == "ok" + client.task_queue.pause.assert_not_called() + + +def test_failed_task_reraises_without_a_queue(): + client = MagicMock() + client.task_queue = None # the queue only exists once the service has started + with pytest.raises(RuntimeError, match="boom"): + _FailingTasks(client).boom() + + +def test_failed_task_reraises_even_if_pausing_fails(): + client = MagicMock() + client.task_queue.pause.side_effect = ConnectionError("redis gone") + with pytest.raises(RuntimeError, match="boom"): + _FailingTasks(client).boom() + + @pytest.fixture def mock_client(): client = MagicMock()