Skip to content

fix(rtc): offload FFI handle disposal to thread in aclose and add sync close - #872

Open
NabiBukhsh-AI wants to merge 9 commits into
livekit:mainfrom
NabiBukhsh-AI:fix/832-audio-source-aclose-hang
Open

NabiBukhsh-AI wants to merge 9 commits into
livekit:mainfrom
NabiBukhsh-AI:fix/832-audio-source-aclose-hang

Conversation

@NabiBukhsh-AI

Copy link
Copy Markdown
Contributor

Fixes #832

Problem

In AudioSource, VideoSource, AudioStream, and VideoStream, aclose() is declared async, but it directly executed self._ffi_handle.dispose() synchronously on the event loop thread. Because handle disposal invokes the native C FFI call livekit_ffi_drop_handle, any stall or wait in native teardown blocked the asyncio event loop and stalled other tasks in the process until a watchdog fired.

Additionally:

  • AudioSource, VideoSource, AudioStream, and VideoStream lacked a synchronous close() method, unlike DataStream and DataTrack, making it difficult to cleanly close resources in synchronous contexts outside of an event loop.
  • In AudioSource, calling aclose() did not release pending wait_for_playout() futures or cancel the scheduled _join_handle timer callback.
  • In VideoSource.capture_frame(), frames pushed after disposal were not guarded against calling the FFI with a disposed handle.

Solution

  1. Non-blocking aclose(): Run self._ffi_handle.dispose() via asyncio.to_thread in AudioSource.aclose(), VideoSource.aclose(), AudioStream.aclose(), and VideoStream.aclose(). This ensures the synchronous native drop never blocks the asyncio event loop.
  2. Synchronous close(): Added synchronous close() methods to AudioSource, VideoSource, AudioStream, and VideoStream for parity with DataStream / DataTrack.
  3. Playout waiter & timer cleanup: In AudioSource._release_waiter(), explicitly cancel self._join_handle if active. Call _release_waiter() from both close() and aclose() so tasks awaiting wait_for_playout() are promptly unblocked.
  4. Disposal guard: Added if self._ffi_handle.disposed: return guard to VideoSource.capture_frame() (mirroring AudioSource).

Verification

  • Added regression tests in livekit-rtc/tests/test_source_stream_close.py:
    • Verified AudioSource.aclose() releases pending wait_for_playout waiters and cancels active timer handles.
    • Verified AudioSource.close() synchronous cleanup.
    • Verified capturing frames after close is a safe no-op.
    • Verified VideoSource.close() and aclose(), and that post-close capture is safely ignored.
    • Verified closing is idempotent across all classes.
  • Ran test suite and verified all passed: uv run pytest livekit-rtc/tests/test_source_stream_close.py
  • Verified type check with uv run mypy livekit-protocol livekit-api livekit-rtc (106 files clean).
  • Verified code formatting and linting with uv run ruff check and uv run ruff format.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

…c close (livekit#832)

- In AudioSource, AudioStream, VideoSource, and VideoStream, add a synchronous close() method.
- In AudioSource, VideoSource, AudioStream, and VideoStream, run self._ffi_handle.dispose() via asyncio.to_thread in aclose() so the synchronous native drop call does not block the asyncio event loop.
- In AudioSource, cancel any pending _join_handle timer and resolve _join_fut when close() or aclose() is called so waiters on wait_for_playout are immediately unblocked.
- In VideoSource.capture_frame, safely ignore frames if the handle is already disposed.

Fixes livekit#832
…e FFI lifecycle test

# Conflicts:
#	livekit-rtc/tests/test_ffi_handle_lifecycle.py
…capture hang

# Conflicts:
#	livekit-rtc/livekit/rtc/audio_source.py
@NabiBukhsh-AI
NabiBukhsh-AI force-pushed the fix/832-audio-source-aclose-hang branch from 7ca3bac to 6601c38 Compare November 9, 2026 15:16
@NabiBukhsh-AI

Copy link
Copy Markdown
Contributor Author

Hi @cloudwebrtc @lukasIO,

Rebased on latest main and resolved all conflicts in audio_source.py with the updated event loop binding.

Key highlights:

All CI checks and Devin review are green (SUCCESS). Ready for review when convenient!

Comment thread livekit-rtc/livekit/rtc/audio_source.py Outdated

This method cleans up resources associated with the audio source.
"""
self._release_waiter()

@cloudwebrtc cloudwebrtc Nov 23, 2026 •

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.

aclose() still calls _release_waiter() directly, bypassing the cross-thread cleanup added for close().

This reproduces when the source belongs to a running event loop with a pending wait_for_playout() waiter, and another thread calls asyncio.run(source.aclose())—the workaround described in #832. _release_waiter() then completes the source loop’s Future from the wrong thread. With asyncio debug enabled, this raises RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one before dispose() runs. Without debug mode, the owning loop may not wake promptly.

Could aclose() use _release_waiter_threadsafe() as well? Please also add a regression test with an active playout waiter on the source loop and aclose() running in another thread, verifying that the waiter completes and the handle is disposed.

aclose() called _release_waiter() directly, so when it ran on another
thread's loop, as with the asyncio.run(source.aclose()) workaround from
livekit#832, it completed the source loop's playout future from the wrong
thread. In asyncio debug mode that raises "Non-thread-safe operation
invoked on an event loop other than the current one" before the handle
is disposed; otherwise the source's loop may never wake the waiter.

Use _release_waiter_threadsafe(), as close() and clear_queue() already
do, and add a regression test that closes the source from another thread
while its loop waits for playout, with debug mode on both loops.

Add a changeset for the release notes.
devin-ai-integration[bot]

This comment was marked as resolved.

…ueue

Address three playout-tracking issues in AudioSource:

- clear_queue() ran the native clear and the playout state reset as
  separate steps, so a capture landing in between was cleared natively
  but lost its duration and timer in Python, and wait_for_playout()
  returned while its audio was still queued. The native clear, and a
  capture's state update plus native submission, now run under the
  same lock, so a capture is ordered entirely before or after a clear.
- A clear_queue() from another thread only scheduled the release, so a
  capture on the source's loop before that callback ran kept the
  cleared audio's future, and its waiters then waited for the new
  audio to drain. clear_queue() now detaches the cleared future and
  timer under the lock and finishes those on their own loop, so a later
  capture starts with fresh ones.
- After the source moved to a new event loop, the timer that resets the
  backlog could have been dropped with the old loop, and the idle time
  since was subtracted from the next frame, so wait_for_playout()
  returned early. Clamp the remaining backlog at zero.

Add a regression test for each and update the changeset.
devin-ai-integration[bot]

This comment was marked as resolved.

wait_for_playout() read _join_fut once to check it and again to await
it. Since clear_queue() can now detach that future from another thread,
it could become None between the two reads, and asyncio.shield(None)
raised TypeError instead of the wait completing. Take one snapshot;
clear_queue() still releases the detached future, so a waiter holding
it completes.
@NabiBukhsh-AI

Copy link
Copy Markdown
Contributor Author

Thanks for catching this, @cloudwebrtc. Fixed in c3ac4f6: aclose() now uses _release_waiter_threadsafe(), like close() and clear_queue(). I added the regression test you suggested: the source's loop waits on wait_for_playout() while another thread runs asyncio.run(source.aclose()), with asyncio debug mode on both loops, and it checks that there's no error, the waiter completes, and the handle is disposed. Against the previous commit the waiter never wakes.

Devin's follow-up review then found playout-tracking issues around clear_queue() and loop changes, fixed in 280ef1c and c2cebf6:

  • The native clear, and a capture's state update plus native submission, now run under the same lock, so a capture is ordered entirely before or after a clear.
  • clear_queue() detaches the cleared future and timer under that lock and finishes them on their own loop, so a capture right after a cross-thread clear gets fresh ones, and the cleared waiters aren't held up by the new audio.
  • The remaining backlog is clamped at zero, so idle time after the source moves to a new loop no longer shortens the next frame.
  • wait_for_playout() reads the future once, since a cross-thread clear can now detach it.

The first three each have a regression test that fails on the previous commit. VideoSource has no playout waiter, so it isn't affected. I also updated the changeset.

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.

AudioSource.aclose() can hang forever in livekit_ffi_drop_handle` after the track is unpublished, and blocks the event loop while it does

2 participants