From b3ab0bd8514073eaa03b5f55fc0c9e8f690e959a Mon Sep 17 00:00:00 2001 From: zariiii9003 <52598363+zariiii9003@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:50:04 +0000 Subject: [PATCH 1/3] Route listener exceptions only to the failing listener's on_error in Notifier --- can/listener.py | 10 +- can/notifier.py | 102 +++++-- .../+notifier-listener-errors.changed.rst | 1 + test/notifier_test.py | 277 +++++++++++++++--- 4 files changed, 320 insertions(+), 70 deletions(-) create mode 100644 doc/changelog.d/+notifier-listener-errors.changed.rst diff --git a/can/listener.py b/can/listener.py index a3988d3ea..960a0d750 100644 --- a/can/listener.py +++ b/can/listener.py @@ -40,9 +40,15 @@ def __call__(self, msg: Message) -> None: self.on_message_received(msg) def on_error(self, exc: Exception) -> None: - """This method is called to handle any exception in the receive thread. + """Handle an exception related to this listener. - :param exc: The exception causing the thread to stop + This method is called when receiving messages for this listener fails or + when this listener fails to process a message. Return normally if the + exception is handled. The default implementation raises + :class:`NotImplementedError` to signal that this listener does not handle + exceptions. See :class:`~can.Notifier` for how it calls this method. + + :param exc: The exception to handle """ raise NotImplementedError() diff --git a/can/notifier.py b/can/notifier.py index 66270a12c..8eca1efc1 100644 --- a/can/notifier.py +++ b/can/notifier.py @@ -120,6 +120,22 @@ def __init__( Remember to call :meth:`~can.Notifier.stop` after all messages are received as many listeners carry out flush operations to persist data. + If receiving from a bus fails, the notifier calls + :meth:`~can.Listener.on_error` of every listener that implements it. After + such a bus error, reception from that bus continues only if the notifier + runs without an event loop and at least one listener handled the error. + + If a listener, or a coroutine it returned, raises an exception, the notifier + calls :meth:`~can.Listener.on_error` of that listener only and keeps + delivering messages to the other listeners. If the listener does not handle + the exception, the notifier logs it and, while running, removes the + listener and calls its ``stop()`` method. + + An exception counts as handled if ``on_error()`` returns normally. If + ``on_error()`` raises :class:`NotImplementedError` or any other exception, + the original exception counts as not handled; any other exception is also + logged. + :param bus: A :ref:`bus` or a list of buses to consume messages from. @@ -138,7 +154,8 @@ def __init__( self.timeout = timeout self._loop = loop - #: Exception raised in thread + #: The most recent exception raised by a bus or a listener, + #: whether or not it was handled. self.exception: Exception | None = None self._stopped = False @@ -213,7 +230,7 @@ def stop(self, timeout: float = 5.0) -> None: elif self._loop: # reader is a file descriptor self._loop.remove_reader(reader) - for listener in self.listeners: + for listener in tuple(self.listeners): if hasattr(listener, "stop"): listener.stop() @@ -226,7 +243,7 @@ def _rx_thread(self, bus: BusABC) -> None: if self._loop: handle_message: Callable[[Message], Any] = functools.partial( self._loop.call_soon_threadsafe, - self._on_message_received_with_error_handling, # type: ignore[arg-type] + self._on_message_received, # type: ignore[arg-type] ) else: handle_message = self._on_message_received @@ -260,29 +277,24 @@ def _on_message_available(self, bus: BusABC) -> None: logger.debug("suppressed exception: %s", exc) else: if msg: - self._on_message_received_with_error_handling(msg) - - def _on_message_received_with_error_handling(self, msg: Message) -> None: - try: - self._on_message_received(msg) - except Exception as exc: # pylint: disable=broad-except - self.exception = exc - if not self._on_error(exc): - raise - logger.debug("suppressed exception: %s", exc) + self._on_message_received(msg) def _on_message_received(self, msg: Message) -> None: - for callback in self.listeners: + for callback in tuple(self.listeners): if self._stopped: return - res = callback(msg) + try: + res = callback(msg) + except Exception as exc: # noqa: BLE001 # pylint: disable=broad-except + self._on_listener_error(callback, exc) + continue if res and self._loop and asyncio.iscoroutine(res): # Schedule coroutine and keep a reference to the task task = self._loop.create_task(res) self._tasks.add(task) - task.add_done_callback(self._on_task_done) + task.add_done_callback(functools.partial(self._on_task_done, callback)) - def _on_task_done(self, task: asyncio.Task) -> None: + def _on_task_done(self, callback: MessageRecipient, task: asyncio.Task) -> None: self._tasks.discard(task) if task.cancelled(): return @@ -292,10 +304,29 @@ def _on_task_done(self, task: asyncio.Task) -> None: if not isinstance(exc, Exception): return + self._on_listener_error(callback, exc) + + def _on_listener_error(self, callback: MessageRecipient, exc: Exception) -> None: + """Pass an exception raised by a listener to that listener only. + + Log the exception if the listener does not handle it, and stop and + remove the listener while the notifier runs. + """ self.exception = exc - if not self._on_error(exc): - raise exc - logger.debug("suppressed exception: %s", exc) + if self._call_error_handler(callback, exc): + logger.debug("suppressed exception: %s", exc) + elif not self._stopped and callback in self.listeners: + self.remove_listener(callback) + logger.error( + "removed listener %r after unhandled exception", callback, exc_info=exc + ) + if hasattr(callback, "stop"): + try: + callback.stop() + except Exception: # pylint: disable=broad-except + logger.exception("stopping listener %r failed", callback) + else: + logger.error("unhandled exception in listener %r", callback, exc_info=exc) def _on_error(self, exc: Exception) -> bool: """Calls ``on_error()`` for all listeners if they implement it. @@ -304,17 +335,32 @@ def _on_error(self, exc: Exception) -> bool: """ was_handled = False - for listener in self.listeners: - if hasattr(listener, "on_error"): - try: - listener.on_error(exc) - except NotImplementedError: - pass - else: - was_handled = True + for listener in tuple(self.listeners): + if self._call_error_handler(listener, exc): + was_handled = True return was_handled + @staticmethod + def _call_error_handler(listener: MessageRecipient, exc: Exception) -> bool: + """Call ``on_error()`` of *listener* if it implements it. + + :returns: ``True`` if the error handler returned normally. + """ + on_error: Callable[[Exception], None] | None = getattr( + listener, "on_error", None + ) + if on_error is None: + return False + try: + on_error(exc) + except NotImplementedError: + return False + except Exception: # pylint: disable=broad-except + logger.exception("error handler of listener %r failed", listener) + return False + return True + def add_listener(self, listener: MessageRecipient) -> None: """Add new Listener to the notification set. diff --git a/doc/changelog.d/+notifier-listener-errors.changed.rst b/doc/changelog.d/+notifier-listener-errors.changed.rst new file mode 100644 index 000000000..3b7b3a672 --- /dev/null +++ b/doc/changelog.d/+notifier-listener-errors.changed.rst @@ -0,0 +1 @@ +``can.Notifier`` passes an exception raised by a listener or its coroutine only to that listener's ``on_error()``, no longer to the ``on_error()`` of all listeners, and still delivers the message to all other listeners; if the failing listener does not handle the exception, the notifier logs it, removes the listener and calls its ``stop()`` method instead of stopping the receive thread or reporting to the event loop's exception handler, so a listener that relied on another listener's ``on_error()`` to keep receiving messages must now implement ``on_error()`` itself. An exception raised by ``on_error()``, also for receive errors of a bus, is now logged and counts as not handled by that listener. diff --git a/test/notifier_test.py b/test/notifier_test.py index a50125ca2..937b34de7 100644 --- a/test/notifier_test.py +++ b/test/notifier_test.py @@ -43,22 +43,21 @@ def shutdown(self): self.writer.close() -class RaisingListener(can.Listener): - def on_message_received(self, msg: can.Message) -> None: - raise ValueError("listener failed") - - class ErrorCollector(can.Listener): - def __init__(self, event: asyncio.Event) -> None: - self.event = event + def __init__(self) -> None: + self.messages: list[can.Message] = [] self.errors: list[Exception] = [] def on_message_received(self, msg: can.Message) -> None: - pass + self.messages.append(msg) def on_error(self, exc: Exception) -> None: self.errors.append(exc) - self.event.set() + + +class RaisingListener(ErrorCollector): + def on_message_received(self, msg: can.Message) -> None: + raise ValueError("listener failed") class NotifierTest(unittest.TestCase): @@ -126,6 +125,71 @@ def test_registry(self): # find_instance must return the existing instance self.assertEqual(can.Notifier.find_instances(bus), (notifier,)) + def test_listener_errors_stay_with_their_listener(self): + """ + Test Scope: + Exceptions raised by listeners of a threaded Notifier. + Preconditions: + A threaded Notifier on a virtual bus with a listener that raises and + handles its own errors, a listener that raises and keeps the default + ``on_error`` and has a raising ``stop``, a listener whose + ``on_message_received`` and ``on_error`` both raise, and a + well-behaved listener. + Events: + Two messages are sent on the bus. + Evaluate: + The well-behaved listener receives both messages and no errors, the + raising listener receives its own two errors and stays registered, + the two listeners with unhandled errors are removed and logged once + each, the one with ``stop`` is stopped and its failure is logged, + and ``Notifier.exception`` holds a listener error. + """ + + class Unhandled(can.Listener): + def __init__(self): + self.stopped = False + + def on_message_received(self, msg): + raise RuntimeError("callable failed") + + def stop(self): + self.stopped = True + raise OSError("stop failed") + + class BrokenHandler(RaisingListener): + def on_error(self, exc): + raise KeyError("handler failed") + + unhandled = Unhandled() + raising = RaisingListener() + broken = BrokenHandler() + bystander = ErrorCollector() + with ( + can.Bus("isolate", interface="virtual", receive_own_messages=True) as bus, + self.assertLogs("can.Notifier", "ERROR") as logs, + can.Notifier(bus, [unhandled, raising, broken, bystander], 0.1) as notifier, + ): + bus.send(can.Message(arbitration_id=1)) + bus.send(can.Message(arbitration_id=2)) + deadline = time.monotonic() + 1 + while (len(bystander.messages) < 2 or len(raising.errors) < 2) and ( + time.monotonic() < deadline + ): + time.sleep(0.01) + + self.assertEqual([m.arbitration_id for m in bystander.messages], [1, 2]) + self.assertEqual(bystander.errors, []) + self.assertEqual(len(raising.errors), 2) + self.assertTrue(all(isinstance(e, ValueError) for e in raising.errors)) + self.assertIsInstance(notifier.exception, (RuntimeError, ValueError)) + self.assertEqual(notifier.listeners, {raising, bystander}) + self.assertTrue(unhandled.stopped) + logged = [str(r.exc_info[1]) for r in logs.records if r.exc_info] + self.assertEqual(logged.count("callable failed"), 1) + self.assertEqual(logged.count("listener failed"), 1) + self.assertIn("handler failed", "\n".join(logs.output)) + self.assertIn("stop failed", "\n".join(logs.output)) + class AsyncNotifierTest(unittest.TestCase): def test_receive_error_reaches_buffered_reader_in_order(self): @@ -233,24 +297,119 @@ def stop_and_record(msg): asyncio.run(run_it()) - def test_active_listener_error_is_reported_to_event_loop(self): + def test_unhandled_listener_error_is_logged(self): + """ + Test Scope: + Unhandled exception of a coroutine listener in an asyncio Notifier. + Preconditions: + An asyncio Notifier on a virtual bus with a coroutine callable that + has no ``on_error`` and fails once released, and a well-behaved + listener. + Events: + Two messages are sent on the bus; once both coroutines have started + and the well-behaved listener has both messages, the coroutines are + released and fail. + Evaluate: + The well-behaved listener receives both messages and no errors, the + failing callable is removed, both failures are logged, the error is + stored in ``Notifier.exception``, and the event loop's exception + handler is not called. + """ + + started = [] + release = asyncio.Event() + + async def raising_callable(msg): + started.append(msg) + await release.wait() + raise RuntimeError("callable failed") + async def run_it(): loop = asyncio.get_running_loop() - errors = [] - loop.set_exception_handler(lambda loop, context: errors.append(context)) + loop_errors = [] + loop.set_exception_handler(lambda _loop, ctx: loop_errors.append(ctx)) + bystander = ErrorCollector() + with ( + can.Bus( + "unhandled", interface="virtual", receive_own_messages=True + ) as bus, + self.assertLogs("can.Notifier", "ERROR") as logs, + can.Notifier( + bus, [raising_callable, bystander], 0.1, loop=loop + ) as notifier, + ): + bus.send(can.Message(arbitration_id=1)) + bus.send(can.Message(arbitration_id=2)) + for _ in range(100): + if len(bystander.messages) == 2 and len(started) == 2: + break + await asyncio.sleep(0.01) + release.set() + for _ in range(100): + if len([r for r in logs.records if r.exc_info]) == 2: + break + await asyncio.sleep(0.01) + self.assertEqual([m.arbitration_id for m in bystander.messages], [1, 2]) + self.assertEqual(bystander.errors, []) + self.assertEqual(notifier.listeners, {bystander}) + self.assertIsInstance(notifier.exception, RuntimeError) + self.assertEqual(len([r for r in logs.records if r.exc_info]), 2) + self.assertEqual(loop_errors, []) - def raising_listener(msg): - raise ValueError("active listener failed") + asyncio.run(run_it()) - notifier = can.Notifier([], [raising_listener], loop=loop) - try: - loop.call_soon_threadsafe(notifier._on_message_received, can.Message()) - await asyncio.sleep(0) - self.assertEqual(len(errors), 1) - self.assertIsInstance(errors[0]["exception"], ValueError) - self.assertEqual(str(errors[0]["exception"]), "active listener failed") - finally: - notifier.stop() + def test_listener_failing_after_stop_is_not_stopped_again(self): + """ + Test Scope: + Unhandled exception of a coroutine returned by a listener after + ``Notifier.stop()`` in an asyncio Notifier. + Preconditions: + An asyncio Notifier on a virtual bus with a listener that has no + ``on_error``, counts its ``stop()`` calls, and returns a coroutine + that fails once released. + Events: + A message is sent on the bus, the Notifier is stopped while the + coroutine waits, then the coroutine is released and fails. + Evaluate: + The failure is logged once and the listener's ``stop()`` was called + exactly once. + """ + + class FailingListener(can.Listener): + def __init__(self) -> None: + self.started = asyncio.Event() + self.release = asyncio.Event() + self.stop_calls = 0 + + def on_message_received(self, msg: can.Message) -> None: + raise NotImplementedError + + async def __call__(self, msg: can.Message) -> None: + self.started.set() + await self.release.wait() + raise RuntimeError("listener failed") + + def stop(self) -> None: + self.stop_calls += 1 + + async def run_it(): + listener = FailingListener() + with ( + can.Bus("late", interface="virtual", receive_own_messages=True) as bus, + self.assertLogs("can.Notifier", "ERROR") as logs, + ): + with can.Notifier( + bus, [listener], 0.1, loop=asyncio.get_running_loop() + ): + bus.send(can.Message()) + await asyncio.wait_for(listener.started.wait(), 1) + listener.release.set() + for _ in range(100): + if logs.records: + break + await asyncio.sleep(0.01) + self.assertEqual(len(logs.records), 1) + self.assertEqual(listener.stop_calls, 1) asyncio.run(run_it()) @@ -276,12 +435,26 @@ def test_sync_listener_error_calls_on_error_with_socketcan(self): asyncio.run(self._sync_listener_error("vcan0", "socketcan")) async def _sync_listener_error(self, channel, interface): - event = asyncio.Event() - collector = ErrorCollector(event) + """ + Test Scope: + Exception of a synchronous listener in an asyncio Notifier, read + through a receive thread (virtual) or a file descriptor (socketcan). + Preconditions: + An asyncio Notifier with a raising listener that handles its own + errors and a well-behaved listener. + Events: + A message is sent on the bus. + Evaluate: + Only the raising listener receives the error, the well-behaved + listener receives the message, and ``Notifier.exception`` holds the + error. + """ + raising = RaisingListener() + bystander = ErrorCollector() with can.Bus(channel, interface=interface, receive_own_messages=True) as bus: notifier = can.Notifier( bus, - [RaisingListener(), collector], + [raising, bystander], 0.1, loop=asyncio.get_running_loop(), ) @@ -289,10 +462,15 @@ async def _sync_listener_error(self, channel, interface): if interface == "socketcan": self.assertIn(bus.fileno(), notifier._readers) bus.send(can.Message()) - await asyncio.wait_for(event.wait(), 1.0) - self.assertEqual(len(collector.errors), 1) - self.assertIsInstance(collector.errors[0], ValueError) - self.assertIs(notifier.exception, collector.errors[0]) + for _ in range(100): + if raising.errors and bystander.messages: + break + await asyncio.sleep(0.01) + self.assertEqual(len(raising.errors), 1) + self.assertIsInstance(raising.errors[0], ValueError) + self.assertEqual(len(bystander.messages), 1) + self.assertEqual(bystander.errors, []) + self.assertIs(notifier.exception, raising.errors[0]) finally: notifier.stop() @@ -318,28 +496,47 @@ async def run_it(): self.assertTrue(listener.is_stopped) def test_async_listener_error_calls_on_error(self): - async def run_it(): - event = asyncio.Event() - collector = ErrorCollector(event) - - async def raising_callback(msg: can.Message) -> None: + """ + Test Scope: + Exception of a coroutine returned by a listener in an asyncio Notifier. + Preconditions: + An asyncio Notifier on a virtual bus with a listener whose coroutine + raises and which handles its own errors, and a well-behaved listener. + Events: + A message is sent on the bus. + Evaluate: + Only the raising listener receives the error, the well-behaved + listener receives the message, and ``Notifier.exception`` holds the + error. + """ + + class AsyncRaisingListener(ErrorCollector): + async def __call__(self, msg: can.Message) -> None: raise RuntimeError("async listener failed") + async def run_it(): + raising = AsyncRaisingListener() + bystander = ErrorCollector() with can.Bus( "async-listener-error", interface="virtual", receive_own_messages=True ) as bus: notifier = can.Notifier( bus, - [raising_callback, collector], + [raising, bystander], 0.1, loop=asyncio.get_running_loop(), ) try: bus.send(can.Message()) - await asyncio.wait_for(event.wait(), 0.5) - self.assertEqual(len(collector.errors), 1) - self.assertIsInstance(collector.errors[0], RuntimeError) - self.assertIs(notifier.exception, collector.errors[0]) + for _ in range(100): + if raising.errors and bystander.messages: + break + await asyncio.sleep(0.01) + self.assertEqual(len(raising.errors), 1) + self.assertIsInstance(raising.errors[0], RuntimeError) + self.assertEqual(len(bystander.messages), 1) + self.assertEqual(bystander.errors, []) + self.assertIs(notifier.exception, raising.errors[0]) finally: notifier.stop() From 2fca24c5b1e50e838dd40d943b215eab99efb735 Mon Sep 17 00:00:00 2001 From: zariiii9003 <52598363+zariiii9003@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:33:09 +0000 Subject: [PATCH 2/3] rename fragments --- .../{+etas-constructor-filters.fixed.rst => 2167.fixed.rst} | 0 .../{+etas-filter-id-mask.fixed.rst => 2178.fixed.rst} | 0 .../{+notifier-listener-errors.changed.rst => 2183.changed.rst} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename doc/changelog.d/{+etas-constructor-filters.fixed.rst => 2167.fixed.rst} (100%) rename doc/changelog.d/{+etas-filter-id-mask.fixed.rst => 2178.fixed.rst} (100%) rename doc/changelog.d/{+notifier-listener-errors.changed.rst => 2183.changed.rst} (100%) diff --git a/doc/changelog.d/+etas-constructor-filters.fixed.rst b/doc/changelog.d/2167.fixed.rst similarity index 100% rename from doc/changelog.d/+etas-constructor-filters.fixed.rst rename to doc/changelog.d/2167.fixed.rst diff --git a/doc/changelog.d/+etas-filter-id-mask.fixed.rst b/doc/changelog.d/2178.fixed.rst similarity index 100% rename from doc/changelog.d/+etas-filter-id-mask.fixed.rst rename to doc/changelog.d/2178.fixed.rst diff --git a/doc/changelog.d/+notifier-listener-errors.changed.rst b/doc/changelog.d/2183.changed.rst similarity index 100% rename from doc/changelog.d/+notifier-listener-errors.changed.rst rename to doc/changelog.d/2183.changed.rst From 01ced6f73da69ef2c82a39d8b8f3c1242ef8eb2a Mon Sep 17 00:00:00 2001 From: zariiii9003 <52598363+zariiii9003@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:55:32 +0000 Subject: [PATCH 3/3] test: cover raising on_error() for bus receive errors in asyncio Notifier --- test/notifier_test.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/test/notifier_test.py b/test/notifier_test.py index 937b34de7..867863bc8 100644 --- a/test/notifier_test.py +++ b/test/notifier_test.py @@ -193,6 +193,20 @@ def on_error(self, exc): class AsyncNotifierTest(unittest.TestCase): def test_receive_error_reaches_buffered_reader_in_order(self): + """ + Test Scope: + A bus receive error in an asyncio Notifier. + Preconditions: + An asyncio Notifier on a bus with an AsyncBufferedReader and a + listener whose ``on_error`` raises. + Events: + The bus yields a message, a receive error and another message. + Evaluate: + The reader yields the first message and then raises the receive + error, receives nothing after it, ``Notifier.exception`` holds the + error, and the event loop's exception handler is never called. + """ + async def run_it(): loop = asyncio.get_running_loop() if not isinstance(loop, asyncio.SelectorEventLoop): @@ -202,12 +216,14 @@ async def run_it(): lambda _loop, context: loop_errors.append(context) ) reader = can.AsyncBufferedReader() + broken = ErrorCollector() + broken.on_error = lambda exc: {}["handler failed"] first = can.Message(arbitration_id=1) following = can.Message(arbitration_id=2) failure = can.CanOperationError("interface disconnected") with ( ReadableBus() as bus, - can.Notifier(bus, [reader], loop=loop) as notifier, + can.Notifier(bus, [reader, broken], loop=loop) as notifier, ): bus.inject(first) bus.inject(failure)