ERROR:asyncio:Task was destroyed but it is pending...
# ask-ai
e
ERRORasyncioTask was destroyed but it is pending! task: <Task pending name='Task-11' coro=<AVSynchronizer._capture_video() running at /home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/rtc/synchronizer.py:103> wait_for=<Future pending cb=[Task.task_wakeup()]>>
t
Thanks for reaching out, blue. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm sorry to hear you're encountering the "Task was destroyed but it is pending" error. This usually happens when asyncio tasks aren't properly cancelled or awaited during the shutdown of your application. Let's work through some steps together to help resolve this in your LiveKit Python application: 1. Make Sure All Tasks Are Explicitly Cancelled During Cleanup: Try using
asyncio.wait()
to await your tasks and cancel any that are still pending when you’re tearing down. 2. Use Reliable Task Cancellation: Tools like
utils.aio.cancel_and_wait()
can be really helpful to safely cancel and await tasks, which prevents that "destroyed but pending" issue. 3. Keep Track and Cancel Long-Lived Tasks: It’s a good idea to hold references to background tasks created with
asyncio.create_task()
and cancel them all together when shutting down. 4. Implement a Graceful Shutdown: Catch termination signals and run cleanup routines to ensure all tasks are cancelled before the event loop closes. 5. Detect Leaked Tasks Early: Using test fixtures to spot any uncancelled tasks after execution can save you headaches later on. Remember to pair every
asyncio.create_task()
call with proper cancellation logic, and consider using structured cleanup patterns in
finally
blocks or dedicated shutdown routines. If you’d like, I’m here to help you through any of these steps or answer any questions you have! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | README.md | stream_audio.py