Skip to content

fix(rtc): reject async callbacks in EventEmitter.once - #903

Open
NabiBukhsh-AI wants to merge 3 commits into
livekit:mainfrom
NabiBukhsh-AI:fix/rtc-emitter-once-reject-async
Open

NabiBukhsh-AI wants to merge 3 commits into
livekit:mainfrom
NabiBukhsh-AI:fix/rtc-emitter-once-reject-async

Conversation

@NabiBukhsh-AI

Copy link
Copy Markdown
Contributor

Summary

EventEmitter.on() rejects coroutine functions, functools.partial(async_fn), and unittest.mock.AsyncMock by raising:

ValueError("Cannot register an async callback with `.on()`. Use `asyncio.create_task` within your synchronous callback instead.")

However, EventEmitter.once() wrapped the provided callback in a synchronous wrapper (once_callback) and passed it to self.on(), bypassing the check entirely.

When an async callback was registered via emitter.once(event, async_fn) or @emitter.once(event):

  1. Registration succeeded silently.
  2. On emit(), once_callback invoked the async callback and received a coroutine object.
  3. Because once_callback is synchronous, the returned coroutine was never awaited and was dropped with a Python RuntimeWarning: coroutine '...' was never awaited.
  4. The user's callback logic silently never ran.

Changes

  • Extracted _check_async_callback(callback, method_name) to validate callbacks consistently across both on() and once().
  • Both methods now reject coroutine functions, partials wrapping coroutine functions, sentinel-tagged coroutines (_ASYNCIO_COROUTINE_MARKER), and AsyncMock with a descriptive ValueError.

Testing

Added unit tests in tests/rtc/test_emitter.py:

  • test_once_rejects_async_callback: rejects direct async callbacks, functools.partial(async_fn), and @emitter.once decorated async functions.

  • test_once_rejects_sentinel_tagged_callback: rejects callbacks tagged with _ASYNCIO_COROUTINE_MARKER.

  • test_once_rejects_async_mock: rejects unittest.mock.AsyncMock.

  • uv run pytest tests/rtc/test_emitter.py -v -W error (15/15 passed)

  • uv run ruff check livekit-rtc/livekit/rtc/event_emitter.py tests/rtc/test_emitter.py (passed)

  • uv run ruff format --check livekit-rtc/livekit/rtc/event_emitter.py tests/rtc/test_emitter.py (passed)

  • uv run mypy livekit-rtc/livekit/rtc/event_emitter.py tests/rtc/test_emitter.py (0 issues)

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@NabiBukhsh-AI

Copy link
Copy Markdown
Contributor Author

Hi @cloudwebrtc @lukasIO,

Gentle check-in on this PR. EventEmitter.once wraps callbacks in a synchronous wrapper, but coroutine functions passed to once() previously returned an unawaited coroutine and triggered runtime warnings. This patch explicitly rejects or safely handles coroutine callbacks matching on() conventions.

All CI checks and Devin review are green. Ready for review when time permits!

@cloudwebrtc cloudwebrtc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The fix looks correct: once() now runs the same async check as on() before wrapping the callback, so async callbacks no longer slip through the sync once_callback wrapper and silently never run. A few small notes inline.

```
"""
if callback is not None:
_check_async_callback(callback, "once")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: This is a user-visible behavior change. Passing an async callback to .once() used to register without error (the handler just never ran); it now raises ValueError, and for a module-level @room.once(...) async def ... that happens at import time. Could you add a .changeset/*.md entry (patch, livekit-rtc) so it shows up in the release notes? Recent fix PRs (#918, #936, #942, #945) all include one.

_ASYNCIO_COROUTINE_MARKER = getattr(asyncio.coroutines, "_is_coroutine", None)


def _check_async_callback(callback: Callable, method_name: str) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pre-existing, optional: an instance of a class with async def __call__ still passes this check for both .on() and .once(), since neither inspect.iscoroutinefunction(callback) nor the _is_coroutine marker looks at callback.__call__. On emit the coroutine is created and dropped with a "never awaited" warning, and the handler never runs.

class H:
    async def __call__(self, *args): ...

emitter.once("connected", H())  # accepted

Since this helper is now shared, it would be a cheap place to also reject inspect.iscoroutinefunction(getattr(callback, "__call__", 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."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: Following this hint literally (e.g. emitter.once("x", lambda: asyncio.create_task(coro()))) leaves no reference to the task, and the event loop only keeps a weak reference, so it can be garbage-collected before it finishes. Maybe mention keeping a reference to the task in the message.

…ack 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.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 1 new potential issue.

1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

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.
@NabiBukhsh-AI

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @cloudwebrtc. All three points are addressed in 497651a:

  • Changeset: added .changeset/emitter-once-reject-async.md (livekit-rtc: patch), noting that .once() now raises for async callbacks, including @room.once(...) on an async def.
  • Task reference: the error now says to keep a reference to the task returned by asyncio.create_task, and why.
  • async def __call__: the shared check now also rejects such instances, for both .on() and .once(). A class passed as the callback is still accepted, since calling it only constructs an instance.

Devin then caught that a functools.partial wrapping such an instance still got through; 6c7ac48 checks a partial (nested ones too) by the callable it wraps. New tests cover each case, and the rejection tests fail against the earlier commits.

This branch has not been deployed

No deployments
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.

2 participants