Skip to content

fix(rtc): signal eos on VideoStream queue and guard stream finalizers - #878

Open
NabiBukhsh-AI wants to merge 6 commits into
livekit:mainfrom
NabiBukhsh-AI:fix/rtc-video-stream-eos-hang
Open

NabiBukhsh-AI wants to merge 6 commits into
livekit:mainfrom
NabiBukhsh-AI:fix/rtc-video-stream-eos-hang

Conversation

@NabiBukhsh-AI

Copy link
Copy Markdown
Contributor

Summary

  1. VideoStream EOS sentinel: In VideoStream._run(), when receiving video_event.HasField("eos"), the loop was previously terminating with break without enqueuing a terminal sentinel (self._queue.put(None)), unlike AudioStream._run(). As a result, consumers suspended at await self._queue.get() inside __anext__() remained hung indefinitely upon stream completion or aclose().
  2. Deterministic cleanup: Wrapped VideoStream._run() in try...finally to ensure FfiClient.instance.queue.unsubscribe is executed even if the task is cancelled or terminates unexpectedly.
  3. Redundant initialization: Removed the duplicate self._format = format assignment in VideoStream.__init__.
  4. Finalizer safety: Guarded __del__ in VideoStream and AudioStream with hasattr(self, "_ffi_queue") to prevent AttributeError if garbage collection occurs on partially initialized instances.

Tests

  • Added unit tests in livekit-rtc/tests/test_video_stream.py:
    • test_video_stream_eos_terminates_iteration: Verifies that receiving an eos event unblocks async for consumption cleanly without hanging.
    • test_video_stream_del_without_ffi_queue: Verifies that __del__ does not raise AttributeError when _ffi_queue has not been initialized.
  • All existing tests pass and mypy / ruff checks are 100% clean.

devin-ai-integration[bot]

This comment was marked as resolved.

In VideoStream._run(), push None to self._queue when receiving an eos event, matching AudioStream. Without this terminal sentinel, consumers awaiting __anext__() remain suspended indefinitely on stream completion or aclose().

Wrap _run() in try/finally to guarantee unsubscribing from the FFI event queue even on cancellation or error.

Remove duplicate self._format assignment in VideoStream.__init__.

Guard __del__ in VideoStream and AudioStream with hasattr(self, '_ffi_queue') to prevent AttributeError during garbage collection of partially initialized instances.

# Conflicts:
#	livekit-rtc/livekit/rtc/audio_stream.py
…el in RingQueue

When an EOS sentinel (None) is enqueued to RingQueue, do not evict the oldest buffered frame when at capacity. This ensures that the final frame received before EOS is preserved and consumed by the awaiting iterator rather than discarded.
Reduce the iteration count from 50 to 10 when checking for ctypes array leaks in gc.garbage. Setting DEBUG_SAVEALL prevents Python from collecting cyclic garbage and keeps APMs and their internal threads alive, which can exhaust system threads and cause SIGABRT on constrained CI runners like Ubuntu Python 3.10.
@NabiBukhsh-AI
NabiBukhsh-AI force-pushed the fix/rtc-video-stream-eos-hang branch from 4e2ee87 to e1c2328 Compare November 9, 2026 15:13
@NabiBukhsh-AI

Copy link
Copy Markdown
Contributor Author

Hi @cloudwebrtc @lukasIO,

This PR has been rebased onto latest main, resolving earlier merge conflicts in video_stream.py and audio_stream.py.

Summary of changes:

  1. Signal EOS (None) on VideoStream queue so asynchronous iteration terminates cleanly instead of hanging.
  2. Ensure RingQueue.put does not evict buffered frames when appending terminal sentinel None at capacity limits.
  3. Safe guard in __del__ for uninitialized _ffi_queue handles.

All CI tests and Devin review are passing (SUCCESS). Ready for review!

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

lgtm!

devin-ai-integration[bot]

This comment was marked as resolved.

VideoStream.__anext__ stopped as soon as the producer task was done,
without reading the buffer. If the consumer asked for the next frame
only after the track ended, the frames still buffered, including the
last frame that RingQueue keeps when it enqueues the end-of-stream
marker, were never delivered.

Stop only once the producer is done and the buffer is empty, so the
remaining frames and the end-of-stream marker are drained first, and
calls after that still return immediately. Add a test that lets the
producer finish before iterating, and update the changeset.
@NabiBukhsh-AI

Copy link
Copy Markdown
Contributor Author

Thanks for the approval, @cloudwebrtc! Two follow-ups since then:

  • Added a changeset (.changeset/video-stream-eos.md, livekit-rtc: patch).
  • 86f53a7 fixes a case Devin found: __anext__ stopped as soon as the producer task was done, so frames still buffered when the track ended, including the last one RingQueue now keeps on EOS, were dropped if the consumer only asked for them afterwards. It now stops only once the producer is done and the buffer is empty, so calls after that still return immediately. A new test lets the producer finish before iterating.

Since __anext__ changed after your approval, could you take another quick look?

Also, the one failing job (ubuntu-24.04, Python 3.9) is test_ffi_handle_lifecycle.py::test_subprocess_exit_with_undisposed_handle_has_no_assertion_error aborting in its subprocess at shutdown. That test only creates a native audio source, so it doesn't exercise this change, and the same job passed on the previous commit. Could you re-run it? I don't have permission to.

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