Files
mx_bec/tests/unit/test_tasks.py
perl_dandx10sa d18c33f3b6
CI for mx_bec / e2e tests with pxi_bec (push) Failing after 1m4s
CI for mx_bec / e2e tests with pxii_bec (push) Failing after 1m17s
CI for mx_bec / e2e tests with pxiii_bec (push) Failing after 1m17s
CI for mx_bec / unit tests with pxiii_bec (push) Failing after 1m47s
CI for mx_bec / unit tests with pxii_bec (push) Failing after 1m55s
CI for mx_bec / unit tests with pxi_bec (push) Failing after 1m55s
AareBec task service (#2)
# MX task architecture: AareBec service, tasks, queues and widgets

Brings the AareBec task architecture into `mx_bec`

## Components

- **AareBec service** (`service.py`, `main.py`): custom BEC client that owns the task queue,
  the actor manager and the external API clients.
- **Task framework** (`tasks/core.py`): `@task` decorator and `TaskManager` with `Server` and
  `Client` roles. The server runs tasks one at a time and pauses the queue on failure; clients
  request tasks over Redis. `MxTaskQueue` works off the execution list.
- **MX tasks** (`tasks/mx_tasks.py`): sample mount, optical centering, raster and multi-raster
  scans, X-ray centering, rotation data collection, beamline state change and cleanup.
- **Automation actors** (`actors/`, `actor_manager.py`): actors that react to sequence
  milestones and queue the next task, each switchable through a Redis config value.
- **External clients**: `AareDaq` REST client (Kerberos token, baton handling), `JFJoch`
  raster client, `OpticalPrediction` (AareLC). The `AareDaq` client is to be replaced with native BEC
  implementations.
- **Devices** (`devices/`): Aerotech, Smargon (smargopolo), HTTP device base, simulated stages
  and sample changer, plus a demo config.
- **Widgets** (`bec_widgets/widgets/aare_bec/`): actor config, task queue, task panel, sample
  queue and sample spreadsheet display - for development and admin use.
- **Endpoints and messages** for task requests, the execution list, queue-change
  notifications and sequence state.

## Notes

- BEC-driven optical centering was removed; it will be reimplemented from scratch.
- The sample spreadsheet is copied between Redis instances by a hack in the service, to be
  replaced by the sample database connection module.
- CI installs from the MX Gitea package index (`jfjoch_client` is pre-release only).

---------

Co-authored-by: x10sa <x10sa@psi.ch>
Reviewed-on: #2
Co-authored-by: David Perl <david.perl@psi.ch>
2026-11-24 14:41:31 +01:00

162 lines
5.3 KiB
Python

import time
from threading import Event
from unittest.mock import MagicMock, call, patch
import fakeredis
import pytest
from bec_lib.redis_connector import RedisConnector
from mx_bec.endpoints import QueueEndpoints
from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage
from mx_bec.tasks import MxTaskQueue, RoleT, Server, TaskManager, task
@pytest.fixture
def connector():
conn = RedisConnector("localhost:1", redis_cls=lambda *_, **__: fakeredis.FakeRedis())
conn._managed_connection.flushall()
yield conn
conn.shutdown()
@pytest.fixture
def client(connector):
client = MagicMock()
client.connector = connector
return client
class _Tasks(TaskManager[RoleT]):
"""Records the calls of its one task on `calls`."""
calls: MagicMock
@task
def run_optical_centering(self, sample_id: int) -> None:
self.calls.run_optical_centering(sample_id)
def _publish_optical_centering_done(self, sample_id: int) -> None:
self.calls._publish_optical_centering_done(sample_id)
@pytest.fixture
def tasks():
"""The recorder of the calls made to the tasks."""
return MagicMock()
@pytest.fixture
def queue(client, tasks):
manager = _Tasks[Server](client)
manager.calls = tasks
q = MxTaskQueue(client, manager, poll_interval_s=0.05)
yield q
q.shutdown()
def _request(name="run_optical_centering", *args):
return MXTaskExecutionMessage(name=name, args=args, kwargs={})
def _wait_for(predicate, timeout_s=3.0):
deadline = time.monotonic() + timeout_s
while time.monotonic() < deadline:
if predicate():
return
time.sleep(0.01)
raise AssertionError("condition not met in time")
def test_queue_runs_tasks_in_order(connector, queue, tasks):
for sample_id in (1, 2, 3):
connector.rpush(
QueueEndpoints.task_execution(), _request("run_optical_centering", sample_id)
)
queue.start()
_wait_for(lambda: tasks.run_optical_centering.call_count == 3)
assert tasks.run_optical_centering.call_args_list == [call(1), call(2), call(3)]
assert connector.llen(QueueEndpoints.task_execution()) == 0
def test_queue_announces_each_pop(connector, queue):
notifications = []
def on_changed(msg): # the connector keeps a weak ref: must be a function, not list.append
notifications.append(msg)
connector.register(QueueEndpoints.task_queue_changed(), cb=on_changed)
for sample_id in (1, 2):
connector.rpush(
QueueEndpoints.task_execution(), _request("run_optical_centering", sample_id)
)
queue.start()
_wait_for(lambda: len(notifications) == 2)
assert all(n.value == MXQueueChangedMessage() for n in notifications)
def test_queue_does_not_pop_while_paused(connector, queue, tasks):
queue.pause()
connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1))
queue.start()
time.sleep(0.3)
tasks.run_optical_centering.assert_not_called()
assert connector.llen(QueueEndpoints.task_execution()) == 1
queue.resume()
_wait_for(lambda: tasks.run_optical_centering.call_count == 1)
assert connector.llen(QueueEndpoints.task_execution()) == 0
def test_paused_flag_is_shared_through_redis(connector, queue):
# another client (here: a second config value on the same endpoint) can pause the queue
other = MagicMock()
other.connector = connector
other_queue = MxTaskQueue(other, _Tasks[Server](other))
try:
assert not queue.paused
other_queue.pause()
_wait_for(lambda: queue.paused)
other_queue.resume()
_wait_for(lambda: not queue.paused)
finally:
other_queue.shutdown()
def test_queue_skips_non_task_names(connector, queue, tasks):
connector.rpush(QueueEndpoints.task_execution(), _request("_publish_optical_centering_done", 1))
connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2))
with patch("mx_bec.tasks.core.logger") as logger:
queue.start()
_wait_for(lambda: tasks.run_optical_centering.call_count == 1)
tasks.run_optical_centering.assert_called_once_with(2)
tasks._publish_optical_centering_done.assert_not_called()
logger.warning.assert_called_once()
def test_failed_task_is_logged_and_queue_continues(connector, queue, tasks):
tasks.run_optical_centering.side_effect = [RuntimeError("boom"), None]
connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1))
connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2))
with patch("mx_bec.tasks.core.logger") as logger:
queue.start()
_wait_for(lambda: tasks.run_optical_centering.call_count == 2)
logger.exception.assert_called_once()
assert tasks.run_optical_centering.call_args_list == [call(1), call(2)]
def test_shutdown_waits_for_running_task(connector, queue, tasks):
started, release = Event(), Event()
def slow_task(*_):
started.set()
release.wait(timeout=3)
tasks.run_optical_centering.side_effect = slow_task
connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1))
queue.start()
assert started.wait(timeout=3)
assert queue._thread.is_alive()
release.set()
queue.shutdown()
assert not queue._thread.is_alive()