fix: include traceback context in ophyd callback logs

This commit is contained in:
wakonig_k committed 2026-09-28 22:17:51 +02:00
1 parent 27c1fe5fc9
commit 72fbf1e297
4 files changed
+318 -4

No files matched your search

+4
View File
@@ -1,3 +1,7 @@
from .utils.ophyd_callback_patch import install_ophyd_callback_patch
install_ophyd_callback_patch()
from .devices.sls_devices import SLSInfo, SLSOperatorMessages
from .sim.sim_camera import SimCamera, SimNegativeCamera
from .sim.sim_monitor import SimMonitor, SimMonitorAsync
@@ -0,0 +1,88 @@
"""Add useful traceback details to Ophyd subscription callback errors."""
import functools
import traceback
from bec_lib.logger import bec_logger
from ophyd.ophydobj import OphydObject, UnknownSubscription
_original_subscribe = getattr(
OphydObject.subscribe, "_ophyd_devices_original_subscribe", OphydObject.subscribe
)
def callback_name(callback) -> str:
"""Identify a callback without invoking a user-defined ``__repr__``."""
try:
name = getattr(callback, "__qualname__", None)
except Exception: # pylint: disable=broad-except
name = None
return name if isinstance(name, str) else type(callback).__name__
def object_name(obj) -> str:
"""Identify an Ophyd object without invoking a custom ``__repr__``."""
try:
name = getattr(obj, "name", None)
except Exception: # pylint: disable=broad-except
name = None
if not isinstance(name, str):
name = "<unnamed>"
return f"{type(obj).__name__}({name})"
@functools.wraps(_original_subscribe)
def _subscribe_with_traceback(self, callback, event_type=None, run=True):
"""Keep Ophyd's subscription behavior and enrich swallowed callback errors."""
if not callable(callback):
raise ValueError("callback must be callable")
if event_type is None:
event_type = self._default_sub
if event_type is None:
raise ValueError(
f"Subscription type not set and object {self.name} of class"
f" {self.__class__.__name__} has no default subscription set"
)
if event_type not in self.subscriptions:
raise UnknownSubscription(
f"Unknown subscription {event_type!r}, must be one of {self.subscriptions!r}"
)
registration_stack = traceback.extract_stack(limit=12)[:-1]
@functools.wraps(callback)
def wrapped_callback(*args, **kwargs):
try:
return callback(*args, **kwargs)
except Exception: # pylint: disable=broad-except
# Keep the traceback in the message for sinks that forward only text.
bec_logger.logger.error(
f"Subscription {kwargs.get('sub_type', event_type)} callback {callback_name(callback)} "
f"exception on {object_name(self)}.\n"
f"Registered from:\n{''.join(traceback.format_list(registration_stack))}"
f"Callback traceback:\n{traceback.format_exc()}"
)
# Match Ophyd's registration order and keep the original for clear_sub().
cid = next(self._cb_count)
self._unwrapped_callbacks[event_type][cid] = callback
self._callbacks[event_type][cid] = wrapped_callback
self._cid_to_event_mapping[cid] = event_type
if run:
cached = self._args_cache[event_type]
if cached is not None:
args, kwargs = cached
wrapped_callback(*args, **kwargs)
return cid
_subscribe_with_traceback._ophyd_devices_callback_patch = True
_subscribe_with_traceback._ophyd_devices_original_subscribe = _original_subscribe
def install_ophyd_callback_patch():
"""Install once, including when ophyd_devices is reloaded."""
if not getattr(OphydObject.subscribe, "_ophyd_devices_callback_patch", False):
OphydObject.subscribe = _subscribe_with_traceback
+15 -4
View File
@@ -21,6 +21,8 @@ from ophyd.status import Status as _Status
from ophyd.status import StatusBase as _StatusBase
from ophyd.utils import StatusTimeoutError
from .ophyd_callback_patch import callback_name, object_name
if TYPE_CHECKING: # pragma: no cover
from bec_lib.messages import ScanStatusMessage
from ophyd import Device, Signal
@@ -43,6 +45,15 @@ __all__ = [
logger = bec_logger.logger
def _log_callback_exception(status, exc: Exception) -> None:
"""Retain the traceback in callback logs even when only the message is forwarded."""
logger.error(
f"Error in {type(status).__name__} callback {callback_name(status.callback)} "
f"for {object_name(status.obj)}: {exc}\n{traceback.format_exc()}"
)
set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
OP_MAP = {
@@ -426,7 +437,7 @@ class SubscriptionStatus(StatusBase):
try:
success = self.callback(*args, **kwargs)
except Exception as e:
logger.error(f"Error in SubscriptionStatus callback: {e}")
_log_callback_exception(self, e)
self.set_exception(e)
return
if success:
@@ -539,7 +550,7 @@ class CompareStatus(SubscriptionStatus):
)
return self.op_map[self._operation_success](value, self._value)
except Exception as e:
logger.error(f"Error in CompareStatus callback: {e}")
_log_callback_exception(self, e)
self.set_exception(e)
return False
@@ -594,7 +605,7 @@ class ExceptionStatus(CompareStatus):
)
return False
except Exception as e:
logger.error(f"Error in ExceptionStatus callback: {e}")
_log_callback_exception(self, e)
self.set_exception(e)
return False
@@ -694,7 +705,7 @@ class TransitionStatus(SubscriptionStatus):
return self._index >= len(self._transitions)
except Exception as e:
# Catch any exception if the value comparison fails, e.g. value is numpy array
logger.error(f"Error in TransitionStatus callback: {e}")
_log_callback_exception(self, e)
self.set_exception(e)
return False
+211
View File
@@ -0,0 +1,211 @@
"""Regression coverage for diagnostics from Ophyd subscription callbacks."""
import os
import subprocess
import sys
import pytest
from bec_lib.logger import bec_logger
from ophyd import Signal
from ophyd.ophydobj import UnknownSubscription
from ophyd_devices.utils.psi_device_base_utils import SubscriptionStatus
@pytest.fixture
def bec_error_messages():
messages = []
sink_id = bec_logger.logger.add(
lambda message: messages.append(message.record["message"]), level="ERROR"
)
try:
yield messages
finally:
bec_logger.logger.remove(sink_id)
class BadReprCallback:
def __init__(self, error):
self.error = error
def __call__(self, **kwargs):
raise self.error
def __repr__(self):
raise RuntimeError("callback repr exploded")
def test_subscription_failure_message_contains_callback_traceback(bec_error_messages):
signal = Signal(name="traceback_signal")
delivered = []
def failing_callback(**kwargs):
raise RuntimeError("callback exploded")
def succeeding_callback(**kwargs):
delivered.append(kwargs["value"])
signal.subscribe(failing_callback, run=False)
signal.subscribe(succeeding_callback, run=False)
signal.put(3)
assert delivered == [3]
(message,) = bec_error_messages
assert "Traceback (most recent call last)" in message
assert "failing_callback" in message
assert "traceback_signal" in message
assert "value" in message
assert "RuntimeError: callback exploded" in message
def test_callback_with_bad_repr_does_not_interrupt_other_subscribers(bec_error_messages):
signal = Signal(name="bad_repr_signal")
delivered = []
signal.subscribe(BadReprCallback(ValueError("original callback failure")), run=False)
signal.subscribe(lambda **kwargs: delivered.append(kwargs["value"]), run=False)
signal.put(6)
assert delivered == [6]
(message,) = bec_error_messages
assert "BadReprCallback" in message
assert "ValueError: original callback failure" in message
assert "callback repr exploded" not in message
def test_original_callback_can_be_cleared_after_patch(bec_error_messages):
signal = Signal(name="clearable_signal")
invocations = []
def failing_callback(**kwargs):
invocations.append(kwargs["value"])
raise RuntimeError("clearable callback exploded")
signal.subscribe(failing_callback, run=False)
signal.put(1)
signal.clear_sub(failing_callback)
signal.put(2)
assert invocations == [1]
assert len(bec_error_messages) == 1
def test_cached_subscription_replay_logs_failure_and_keeps_subscription(bec_error_messages):
signal = Signal(name="replay_signal")
signal.put(7)
invocations = []
def replay_callback(**kwargs):
invocations.append(kwargs["value"])
raise ValueError("replayed callback exploded")
cid = signal.subscribe(replay_callback, run=True)
assert invocations == [7]
signal.put(8)
signal.unsubscribe(cid)
signal.put(9)
assert invocations == [7, 8]
assert len(bec_error_messages) == 2
assert all("replay_callback" in message for message in bec_error_messages)
assert all(
"ValueError: replayed callback exploded" in message for message in bec_error_messages
)
def test_subscription_failure_message_identifies_registration_site(bec_error_messages):
signal = Signal(name="registered_signal")
def failing_callback(**kwargs):
raise RuntimeError("registered callback exploded")
def register_from_named_helper():
signal.subscribe(failing_callback, run=False)
register_from_named_helper()
signal.put(4)
(message,) = bec_error_messages
assert "register_from_named_helper" in message
def test_subscription_status_callback_failure_has_traceback(bec_error_messages):
signal = Signal(name="status_signal")
def failing_status_callback(**kwargs):
raise RuntimeError("status callback exploded")
status = SubscriptionStatus(signal, callback=failing_status_callback, run=False)
signal.put(5)
with pytest.raises(RuntimeError, match="status callback exploded"):
status.wait(timeout=1)
(message,) = bec_error_messages
assert "Traceback (most recent call last)" in message
assert "failing_status_callback" in message
assert "status_signal" in message
assert "RuntimeError: status callback exploded" in message
def test_subscription_status_callback_with_bad_repr_keeps_original_error(bec_error_messages):
signal = Signal(name="bad_repr_status_signal")
original_error = ValueError("original status callback failure")
status = SubscriptionStatus(signal, callback=BadReprCallback(original_error), run=False)
signal.put(8)
with pytest.raises(ValueError) as exc_info:
status.wait(timeout=1)
assert exc_info.value is original_error
(message,) = bec_error_messages
assert "BadReprCallback" in message
assert "bad_repr_status_signal" in message
assert "ValueError: original status callback failure" in message
assert "callback repr exploded" not in message
def test_subscribe_preserves_validation_and_default_event():
signal = Signal(name="validated_signal")
with pytest.raises(ValueError, match="callback must be callable"):
signal.subscribe(None, run=False)
with pytest.raises(UnknownSubscription):
signal.subscribe(lambda **kwargs: None, event_type="missing", run=False)
events = []
signal.subscribe(lambda **kwargs: events.append(kwargs["sub_type"]), run=False)
signal.put(1)
assert events == ["value"]
def test_patch_installation_and_reload_do_not_stack_wrappers():
# Isolate module reload so a failing assertion cannot leave the process patched.
script = """
import importlib
import ophyd_devices
from ophyd import Signal
from ophyd.ophydobj import OphydObject
from ophyd_devices.utils import ophyd_callback_patch
original = OphydObject.subscribe.__wrapped__
ophyd_callback_patch.install_ophyd_callback_patch()
ophyd_callback_patch.install_ophyd_callback_patch()
assert OphydObject.subscribe.__wrapped__ is original
importlib.reload(ophyd_callback_patch)
ophyd_callback_patch.install_ophyd_callback_patch()
assert OphydObject.subscribe.__wrapped__ is original
signal = Signal(name="reload_signal")
received = []
signal.subscribe(lambda **kwargs: received.append(kwargs["value"]), run=False)
signal.put(5)
assert received == [5]
"""
env = os.environ.copy()
env["OPHYD_CONTROL_LAYER"] = "dummy"
result = subprocess.run([sys.executable, "-c", script], env=env, capture_output=True, text=True)
assert result.returncode == 0, result.stderr