From 0aba4650de1a8ac2d9e6d1aaf1f82eeaece808c7 Mon Sep 17 00:00:00 2001 From: Nabi Bukhsh Date: Mon, 26 Oct 2026 13:08:57 +0500 Subject: [PATCH 1/3] fix(rtc): reject async callbacks in EventEmitter.once --- livekit-rtc/livekit/rtc/event_emitter.py | 20 ++++++---- tests/rtc/test_emitter.py | 51 ++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/livekit-rtc/livekit/rtc/event_emitter.py b/livekit-rtc/livekit/rtc/event_emitter.py index 38f549011..0e437852e 100644 --- a/livekit-rtc/livekit/rtc/event_emitter.py +++ b/livekit-rtc/livekit/rtc/event_emitter.py @@ -13,6 +13,17 @@ # function in 3.16, and a bare attribute access would then fail at import time. _ASYNCIO_COROUTINE_MARKER = getattr(asyncio.coroutines, "_is_coroutine", None) + +def _check_async_callback(callback: Callable, method_name: str) -> None: + if inspect.iscoroutinefunction(callback) or ( + _ASYNCIO_COROUTINE_MARKER is not None + and getattr(callback, "_is_coroutine", None) is _ASYNCIO_COROUTINE_MARKER + ): + raise ValueError( + f"Cannot register an async callback with `.{method_name}()`. Use `asyncio.create_task` within your synchronous callback instead." + ) + + T_contra = TypeVar("T_contra", contravariant=True) @@ -115,6 +126,7 @@ def greet_once(name): ``` """ if callback is not None: + _check_async_callback(callback, "once") def once_callback(*args: Any, **kwargs: Any) -> None: self.off(event, once_callback) @@ -169,13 +181,7 @@ def greet(name): ``` """ if callback is not None: - if inspect.iscoroutinefunction(callback) or ( - _ASYNCIO_COROUTINE_MARKER is not None - and getattr(callback, "_is_coroutine", None) is _ASYNCIO_COROUTINE_MARKER - ): - raise ValueError( - "Cannot register an async callback with `.on()`. Use `asyncio.create_task` within your synchronous callback instead." - ) + _check_async_callback(callback, "on") if event not in self._events: self._events[event] = {} diff --git a/tests/rtc/test_emitter.py b/tests/rtc/test_emitter.py index 4f67f76a4..020943da8 100644 --- a/tests/rtc/test_emitter.py +++ b/tests/rtc/test_emitter.py @@ -186,6 +186,57 @@ def test_on_rejects_async_mock() -> None: emitter.on("connected", AsyncMock()) +def test_once_rejects_async_callback() -> None: + """`.once()` refuses coroutine functions, however they are spelled.""" + EventTypes = Literal["connected"] + + emitter = EventEmitter[EventTypes]() + + async def on_connected() -> None: + pass + + with pytest.raises(ValueError, match="Cannot register an async callback"): + emitter.once("connected", on_connected) + + with pytest.raises(ValueError, match="Cannot register an async callback"): + emitter.once("connected", functools.partial(on_connected)) + + with pytest.raises(ValueError, match="Cannot register an async callback"): + + @emitter.once("connected") + async def on_connected_decorated() -> None: + pass + + +def test_once_rejects_sentinel_tagged_callback() -> None: + """A callable tagged with asyncio's private coroutine sentinel is rejected by `.once()`.""" + marker = getattr(asyncio.coroutines, "_is_coroutine", None) + if marker is None: + pytest.skip("asyncio.coroutines._is_coroutine is not defined on this Python") + + EventTypes = Literal["connected"] + + emitter = EventEmitter[EventTypes]() + + def on_connected() -> None: + pass + + on_connected._is_coroutine = marker # type: ignore[attr-defined] + + with pytest.raises(ValueError, match="Cannot register an async callback"): + emitter.once("connected", on_connected) + + +def test_once_rejects_async_mock() -> None: + """`AsyncMock` is rejected by `.once()` on every supported version.""" + EventTypes = Literal["connected"] + + emitter = EventEmitter[EventTypes]() + + with pytest.raises(ValueError, match="Cannot register an async callback"): + emitter.once("connected", AsyncMock()) + + class _OrderedHandler: """A callable whose hash is fixed, so a set orders it independently of registration.""" From 497651a9222fbdfabc14e8aecc5784b43bdc8b9e Mon Sep 17 00:00:00 2001 From: Nabi Bukhsh Date: Sun, 29 Nov 2026 02:28:27 +0500 Subject: [PATCH 2/3] fix(rtc): reject async __call__ instances and clarify the async callback hint Address review feedback on the shared async callback check used by EventEmitter.on() and .once(): - Also reject an instance whose class defines `async def __call__`. Neither inspect.iscoroutinefunction(callback) nor the asyncio marker looks at __call__, so such a handler was accepted and its coroutine was dropped unawaited on emit. A class passed as the callback is still accepted, since calling it only constructs an instance. - Say in the error to keep a reference to the task created with asyncio.create_task: the event loop only holds tasks weakly, so an unreferenced task can be garbage-collected before it finishes. - Add a changeset, since .once() raising for async callbacks is a user-visible change. --- .changeset/emitter-once-reject-async.md | 5 +++ livekit-rtc/livekit/rtc/event_emitter.py | 20 +++++++-- tests/rtc/test_emitter.py | 56 ++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 4 deletions(-) create mode 100644 .changeset/emitter-once-reject-async.md diff --git a/.changeset/emitter-once-reject-async.md b/.changeset/emitter-once-reject-async.md new file mode 100644 index 000000000..ff1cecb35 --- /dev/null +++ b/.changeset/emitter-once-reject-async.md @@ -0,0 +1,5 @@ +--- +"livekit-rtc": patch +--- + +`EventEmitter.once()` now raises `ValueError` for an async callback, as `.on()` already did, instead of registering a handler that never ran. Both methods also reject an instance whose class defines `async def __call__`. Code that passed an async callback to `.once()`, including `@room.once(...)` on an `async def`, now fails at registration and should use a synchronous callback that starts a task. diff --git a/livekit-rtc/livekit/rtc/event_emitter.py b/livekit-rtc/livekit/rtc/event_emitter.py index 0e437852e..aaadd3c04 100644 --- a/livekit-rtc/livekit/rtc/event_emitter.py +++ b/livekit-rtc/livekit/rtc/event_emitter.py @@ -15,12 +15,24 @@ def _check_async_callback(callback: Callable, method_name: str) -> None: - if inspect.iscoroutinefunction(callback) or ( - _ASYNCIO_COROUTINE_MARKER is not None - and getattr(callback, "_is_coroutine", None) is _ASYNCIO_COROUTINE_MARKER + if ( + inspect.iscoroutinefunction(callback) + or ( + _ASYNCIO_COROUTINE_MARKER is not None + and getattr(callback, "_is_coroutine", None) is _ASYNCIO_COROUTINE_MARKER + ) + # An instance whose class defines `async def __call__`. A class itself is left + # alone: calling it only constructs an instance, which is synchronous. + or ( + not inspect.isclass(callback) + and inspect.iscoroutinefunction(getattr(callback, "__call__", None)) + ) ): raise ValueError( - f"Cannot register an async callback with `.{method_name}()`. Use `asyncio.create_task` within your synchronous callback instead." + f"Cannot register an async callback with `.{method_name}()`. Use " + "`asyncio.create_task` within your synchronous callback instead, and keep a " + "reference to the returned task until it finishes: the event loop only holds " + "a weak reference, so an unreferenced task can be garbage-collected early." ) diff --git a/tests/rtc/test_emitter.py b/tests/rtc/test_emitter.py index 020943da8..fa8535e98 100644 --- a/tests/rtc/test_emitter.py +++ b/tests/rtc/test_emitter.py @@ -237,6 +237,62 @@ def test_once_rejects_async_mock() -> None: emitter.once("connected", AsyncMock()) +class _AsyncCallable: + async def __call__(self, *args: Any) -> None: + pass + + +def test_rejects_instance_with_async_call() -> None: + """An instance whose class defines `async def __call__` is rejected by `.on()` and `.once()`.""" + emitter = EventEmitter[str]() + + with pytest.raises(ValueError, match=r"Cannot register an async callback with `\.on\(\)`"): + emitter.on("connected", _AsyncCallable()) + + with pytest.raises(ValueError, match=r"Cannot register an async callback with `\.once\(\)`"): + emitter.once("connected", _AsyncCallable()) + + # nothing was registered, so emitting creates no never-awaited coroutine + with warnings.catch_warnings(): + warnings.simplefilter("error") + emitter.emit("connected") + + +def test_accepts_sync_callable_instance_and_class() -> None: + """Sync callable instances stay accepted, and so does a class: calling it only constructs it.""" + emitter = EventEmitter[str]() + calls: list[str] = [] + + class SyncCallable: + def __call__(self) -> None: + calls.append("instance") + + class Constructed: + def __init__(self) -> None: + calls.append("class") + + async def __call__(self) -> None: + pass + + emitter.on("connected", SyncCallable()) + emitter.once("connected", Constructed) + + emitter.emit("connected") + emitter.emit("connected") + assert calls == ["instance", "class", "instance"] + + +def test_async_callback_error_says_to_keep_a_task_reference() -> None: + emitter = EventEmitter[str]() + + async def on_connected() -> None: + pass + + for register in (emitter.on, emitter.once): + with pytest.raises(ValueError, match="keep a reference to the returned task"): + register("connected", on_connected) + + class _OrderedHandler: """A callable whose hash is fixed, so a set orders it independently of registration.""" From 6c7ac482f6ee318186c4cca2c19ba5cffc59a0c8 Mon Sep 17 00:00:00 2001 From: Nabi Bukhsh Date: Sun, 29 Nov 2026 11:04:24 +0500 Subject: [PATCH 3/3] fix(rtc): check a functools.partial callback by the callable it wraps A partial wrapping an instance with `async def __call__` passed the async callback check, because the check looked at the partial's own synchronous __call__. Unwrap partials, including nested ones, and run the checks on the wrapped callable, which is what calling the partial runs. --- livekit-rtc/livekit/rtc/event_emitter.py | 14 +++++++++---- tests/rtc/test_emitter.py | 25 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/livekit-rtc/livekit/rtc/event_emitter.py b/livekit-rtc/livekit/rtc/event_emitter.py index aaadd3c04..e5e8e2f76 100644 --- a/livekit-rtc/livekit/rtc/event_emitter.py +++ b/livekit-rtc/livekit/rtc/event_emitter.py @@ -1,4 +1,5 @@ import asyncio +import functools import inspect from typing import Any, Callable, Dict, Optional, Generic, TypeVar @@ -15,17 +16,22 @@ def _check_async_callback(callback: Callable, method_name: str) -> None: + # A partial is checked by what it wraps, since that is what calling it runs. + target = callback + while isinstance(target, functools.partial): + target = target.func + if ( - inspect.iscoroutinefunction(callback) + inspect.iscoroutinefunction(target) or ( _ASYNCIO_COROUTINE_MARKER is not None - and getattr(callback, "_is_coroutine", None) is _ASYNCIO_COROUTINE_MARKER + and getattr(target, "_is_coroutine", None) is _ASYNCIO_COROUTINE_MARKER ) # An instance whose class defines `async def __call__`. A class itself is left # alone: calling it only constructs an instance, which is synchronous. or ( - not inspect.isclass(callback) - and inspect.iscoroutinefunction(getattr(callback, "__call__", None)) + not inspect.isclass(target) + and inspect.iscoroutinefunction(getattr(target, "__call__", None)) ) ): raise ValueError( diff --git a/tests/rtc/test_emitter.py b/tests/rtc/test_emitter.py index fa8535e98..7bbff57b9 100644 --- a/tests/rtc/test_emitter.py +++ b/tests/rtc/test_emitter.py @@ -282,6 +282,31 @@ async def __call__(self) -> None: assert calls == ["instance", "class", "instance"] +def test_partial_is_checked_by_what_it_wraps() -> None: + """A partial of an async callable instance is rejected; one of a sync instance is not.""" + emitter = EventEmitter[str]() + + for wrapped in ( + functools.partial(_AsyncCallable(), "label"), + functools.partial(functools.partial(_AsyncCallable(), "label")), + ): + with pytest.raises(ValueError, match=r"`\.on\(\)`"): + emitter.on("connected", wrapped) + with pytest.raises(ValueError, match=r"`\.once\(\)`"): + emitter.once("connected", wrapped) + + calls: list[str] = [] + + class SyncCallable: + def __call__(self, label: str) -> None: + calls.append(label) + + emitter.on("connected", functools.partial(SyncCallable(), "on")) + emitter.once("connected", functools.partial(SyncCallable(), "once")) + emitter.emit("connected") + assert calls == ["on", "once"] + + def test_async_callback_error_says_to_keep_a_task_reference() -> None: emitter = EventEmitter[str]()