agents icon indicating copy to clipboard operation
agents copied to clipboard

OpenAI realtime `RealtimeSession.aclose()` blocks ~20s on WebSocket close (OpenAI never sends a CLOSE frame)

Open neo-lyzr opened this issue 4 months ago • 0 comments

Describe the bug

For OpenAI realtime sessions, RealtimeSession.aclose() blocks for ~20s during session/agent shutdown. The delay is the aiohttp WebSocket close handshake waiting for a server CLOSE frame that OpenAI's Realtime API never sends.

Root cause

In livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/realtime_model.py:

  • RealtimeSession.aclose() closes the message channel and awaits _main_atask.
  • _main_atask runs _run_ws, whose _send_task calls await ws_conn.close() once the outbound channel drains (there is a second await ws_conn.close() in the _run_ws finally).
  • aiohttp's ClientWebSocketResponse.close() sends a CLOSE frame and then waits for the peer's CLOSE frame up to its timeout. OpenAI's realtime server does not send a CLOSE frame on session end (it drops the connection with EOF), so the handshake waits out the full timeout.

There is no timeout bound on that close inside the plugin, so aclose() — and therefore the AgentSession.aclose() / job shutdown that awaits it — stalls for ~20s.

To reproduce

  1. Run an agent using openai.realtime.RealtimeModel (e.g. gpt-realtime).
  2. Have the remote participant disconnect (or otherwise end the session).
  3. Measure the time from the disconnect to aclose() / the on_session_end callback returning → consistently ~20s.

Expected behavior

aclose() should return promptly. Because the server never sends a CLOSE frame, waiting for the handshake is pointless; a short bounded wait followed by force-detaching the transport is correct.

Environment

  • livekit-agents 1.6.4 (latest), livekit-plugins-openai 1.6.4
  • Model: OpenAI Realtime API (gpt-realtime) over WebSocket

Additional context

  • OpenAI Developer Community — "Lack of realtime websocket CLOSE frame": https://community.openai.com/t/lack-of-realtime-websocket-close-frame/1369160 — a participant said they'd add a CLOSE frame, but it remains unimplemented as of ~May 2026.
  • #5875 bounded AgentSession.aclose() at the job-supervisor level with a 60s ceiling. That prevents an indefinite hang, but it sits far above this ~20s stall and doesn't address the WebSocket close cause. The targeted fix is to bound ws_conn.close() inside the OpenAI plugin.

I have a fix and will open a PR referencing this issue.

neo-lyzr avatar Jul 06 '26 22:07 neo-lyzr