(Solved) Session never closes when participant disconnects before AgentTask

We ran into an issue where our solution never cleared the memory, causing our pods in Azure Kubernetes to crash. This was due to a process that never stopped running as we got stuck in the on_enter() of our main agent. This blocked the shutdown, and prevented the shutdown_callback from being executed. We are running LiveKit version 1.5.6.

The issue is similar to another one that was patched in an earlier release of LiveKit: AgentSession close path hangs indefinitely when participant disconnects mid-speech · Issue #5497 · livekit/agents · GitHub

Cause and solution:
A rough outline of the agent is as follows, with the tasks being AgentTasks

class MainAgent(Agent):
async def on_enter():
await self.session.generate_reply( welcome_message )
await Task1
await Task2

The issue occurs when a participant disconnects during the generate_reply, which correctly executes the on_participant_disconnect event handler. However the code will then try to execute await Task1 where it will completely freeze, and is thus stuck in the on_enter() of the MainAgent indefinitely, blocking the shutdown processes.

Our solution for this was to, after the generate_reply, add a check if the participant was disconnected and exit the on_enter, which allows the shutdown to be executed (see pseudo code below). This solution worked for us, but we can imagine this issue occuring again for other users of LiveKit in other scenarios.

class MainAgent(Agent):
async def on_enter():
await self.session.generate_reply( welcome_message )

if participant_disconnected:
return

await Task1
await Task2

I’ve highlighted this to our agents team. It would be good to know if you can reproduce this on livekit-agents@1.5.17.

This is a PR for this issue