Repository navigation
fix(rtc): offload FFI handle disposal to thread in aclose and add sync close - #872
NabiBukhsh-AI wants to merge 9 commits into
Conversation
…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
7ca3bac to
6601c38
Compare
|
Hi @cloudwebrtc @lukasIO, Rebased on latest Key highlights:
All CI checks and Devin review are green ( |
|
|
||
| This method cleans up resources associated with the audio source. | ||
| """ | ||
| self._release_waiter() |
There was a problem hiding this comment.
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.
…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.
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.
|
Thanks for catching this, @cloudwebrtc. Fixed in c3ac4f6: Devin's follow-up review then found playout-tracking issues around
The first three each have a regression test that fails on the previous commit. |
Fixes #832
Problem
In
AudioSource,VideoSource,AudioStream, andVideoStream,aclose()is declaredasync, but it directly executedself._ffi_handle.dispose()synchronously on the event loop thread. Because handle disposal invokes the native C FFI calllivekit_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, andVideoStreamlacked a synchronousclose()method, unlikeDataStreamandDataTrack, making it difficult to cleanly close resources in synchronous contexts outside of an event loop.AudioSource, callingaclose()did not release pendingwait_for_playout()futures or cancel the scheduled_join_handletimer callback.VideoSource.capture_frame(), frames pushed after disposal were not guarded against calling the FFI with a disposed handle.Solution
aclose(): Runself._ffi_handle.dispose()viaasyncio.to_threadinAudioSource.aclose(),VideoSource.aclose(),AudioStream.aclose(), andVideoStream.aclose(). This ensures the synchronous native drop never blocks the asyncio event loop.close(): Added synchronousclose()methods toAudioSource,VideoSource,AudioStream, andVideoStreamfor parity withDataStream/DataTrack.AudioSource._release_waiter(), explicitly cancelself._join_handleif active. Call_release_waiter()from bothclose()andaclose()so tasks awaitingwait_for_playout()are promptly unblocked.if self._ffi_handle.disposed: returnguard toVideoSource.capture_frame()(mirroringAudioSource).Verification
livekit-rtc/tests/test_source_stream_close.py:AudioSource.aclose()releases pendingwait_for_playoutwaiters and cancels active timer handles.AudioSource.close()synchronous cleanup.VideoSource.close()andaclose(), and that post-close capture is safely ignored.uv run pytest livekit-rtc/tests/test_source_stream_close.pyuv run mypy livekit-protocol livekit-api livekit-rtc(106 files clean).uv run ruff checkanduv run ruff format.