Skip to content

Fix Notifier async callback error handling - #2096

Merged
zariiii9003 merged 7 commits into
hardbyte:mainfrom
timothyanderson096-ocdealcheck:fix-notifier-async-errors-1912
Nov 29, 2026
Merged

zariiii9003 merged 7 commits into
hardbyte:mainfrom
timothyanderson096-ocdealcheck:fix-notifier-async-errors-1912

Conversation

@timothyanderson096-ocdealcheck

Copy link
Copy Markdown
Contributor

Summary

Route listener exceptions through Notifier._on_error() when a Notifier is using an asyncio event loop.

With a loop configured, thread-backed receivers currently schedule _on_message_received() using call_soon_threadsafe(). Exceptions raised by synchronous listeners therefore occur later on the event-loop thread and bypass _rx_thread()'s exception handler. Coroutine listeners have the same problem because their tasks are only discarded on completion, so task exceptions are never passed to _on_error().

This change:

  • wraps event-loop message dispatch so synchronous listener exceptions populate Notifier.exception and call _on_error()
  • applies the same guarded dispatch to file-descriptor based loop readers
  • inspects completed coroutine tasks, routes their exceptions through _on_error(), and keeps cancelled tasks quiet
  • adds regression tests for both synchronous and asynchronous listener failures while an asyncio loop is configured

The existing no-loop receive-thread behavior is unchanged.

Fixes #1912.

@mergify

mergify Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@zariiii9003

Copy link
Copy Markdown
Collaborator

AI Review: Fix Notifier async callback error handling (#2096)

#1912 is a valid bug: since asyncio support was added (#388), listener exceptions are dispatched outside _rx_thread's error handling when a loop is configured, so they bypass Listener.on_error() and Notifier.exception, unlike the no-loop mode. This PR restores parity on both the thread and file-descriptor reader paths and for coroutine callbacks, while unhandled errors still reach the loop's exception handler. Both new tests fail without the fix. Three items need action.

Findings

  • can/notifier.py, _on_task_done: KeyboardInterrupt/SystemExit are raised twice.
    The task has already propagated these out of the loop. raise exc in the done callback raises them again during asyncio.run()'s task cancellation and aborts the runner's cleanup. The caller's finally block then runs only at interpreter finalization, where notifier.stop() fails with PythonFinalizationError, so listeners are never stopped or flushed. main shuts down cleanly. Ignore such exceptions; this also covers None:

    exc = task.exception()
    if not isinstance(exc, Exception):
        return
  • can/notifier.py, _on_message_available: the file-descriptor path is untested.
    Both tests use the virtual bus, which has no fileno(). Reverting the _on_message_available change leaves the whole suite green, yet this is the path SocketCAN users take with asyncio. CI provides vcan0, so run the sync test on both readers:

    from .config import TEST_INTERFACE_SOCKETCAN
    ...
        def test_sync_listener_error_calls_on_error_with_loop(self):
            buses = {
                "thread reader": lambda: can.Bus(
                    "sync-listener-error", interface="virtual", receive_own_messages=True
                )
            }
            if TEST_INTERFACE_SOCKETCAN:
                buses["fd reader"] = lambda: can.Bus(
                    "vcan0", interface="socketcan", receive_own_messages=True
                )
            for name, make_bus in buses.items():
                with self.subTest(name):
                    asyncio.run(self._sync_listener_error(make_bus))
    
        async def _sync_listener_error(self, make_bus):
            # former run_it() body, with `with make_bus() as bus:`
  • Missing news fragment. The contribution guide (doc/development.rst, "Add a News Fragment for the Changelog") requires one for every user-facing change. Add e.g. doc/changelog.d/1912.fixed.rst:

    Call ``Listener.on_error()`` and set ``Notifier.exception`` for exceptions raised by synchronous listeners and coroutine callbacks when ``can.Notifier`` runs with an asyncio event loop.

Verdict

request changes

Copy link
Copy Markdown
Contributor Author

Addressed all three review requests in 7355f0d: avoid duplicate KeyboardInterrupt/SystemExit propagation, exercise the file-descriptor path with real SocketCAN (vcan0), and add the changelog entry. Hosted verification: 21 tests and 2 subtests passed; Black and Ruff passed. Separate checks reproduced both duplicate exceptions on the previous revision and neither on the corrected revision. Reverting the FD dispatch change makes the new SocketCAN regression fail as expected. Changes and verification were AI-assisted. Ready for maintainer re-review.

@zariiii9003

Copy link
Copy Markdown
Collaborator

AI Review: Fix Notifier async callback error handling (#2096)

Thank you for addressing all three requests from the previous review. The fix now restores Listener.on_error() and Notifier.exception for listener errors on the thread reader, file-descriptor reader and coroutine paths. Each of these changes is guarded by a test that fails when the change is reverted, and the SocketCAN test runs on CI's vcan0. One small item remains.

Findings

  • test/notifier_test.py, test_base_exception_from_task_is_not_raised_twice: tests private internals.
    It drives _tasks and _on_task_done directly, and on a regression the re-raised KeyboardInterrupt aborts the whole pytest session instead of failing the test. Replace it with this test, which uses only the public interface and fails when the BaseException guard in _on_task_done is removed:
    def test_keyboard_interrupt_from_coroutine_stops_notifier(self):
        listener = can.BufferedReader()
    
        async def raising_callback(msg: can.Message) -> None:
            raise KeyboardInterrupt
    
        async def run_it():
            with can.Bus("kbi", interface="virtual", receive_own_messages=True) as bus:
                with can.Notifier(
                    bus,
                    [raising_callback, listener],
                    0.1,
                    loop=asyncio.get_running_loop(),
                ):
                    bus.send(can.Message())
                    await asyncio.sleep(1)
    
        with self.assertRaises(KeyboardInterrupt):
            asyncio.run(run_it())
        self.assertTrue(listener.is_stopped)

Verdict

request changes

Copy link
Copy Markdown
Contributor Author

Replaced the private-internals regression with the suggested public Notifier/BufferedReader cleanup test in 69aeed2. The production implementation is unchanged. The new revision is undergoing the upstream CI matrix; I will leave the verification status to those checks. Thank you for the concrete test suggestion.

@zariiii9003 zariiii9003 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thank you

@zariiii9003
zariiii9003 merged commit c62a8ef into hardbyte:main Nov 29, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Errors in callbacks when running async is not calling _on_error()

2 participants