is it technically possible that @session.on("close...
# ask-ai
b
is it technically possible that @session.on("close") hook will not execute or silently fail?
t
Thanks for reaching out, mateuszkasprowicz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking whether the
@session.on("close")
hook can fail to run or silently not execute — yes, that can happen in certain situations. Why it might not run: • If the process is terminated abruptly (crash,
SIGKILL
, host shutdown), the event loop may never run and the
close
event won't be emitted. • If an unrecoverable internal error or forced termination occurs before session shutdown completes, the handler may not run. • Shutdown hooks have timeouts (default 60s); if the process is killed before callbacks finish or the timeout is reached, they may not complete. What you can do to reduce risk: • Keep cleanup idempotent so missed runs are safe to retry later. • Persist critical state externally (database, durable store) during normal operation rather than relying solely on the close hook. • Use external monitoring/health checks and a separate cleanup worker that reconciles state for sessions that never properly closed. • Ensure graceful shutdown handling in your host/container (catch signals, allow time for shutdown hooks to finish). If you want, tell me how you currently use the
close
hook (what cleanup it does) and I can suggest a concreter, minimal-rewrite or alternative pattern. Sources: Events and error handling | LiveKit docs | Job lifecycle | LiveKit docs
b
@session.on("close") def _on_close(_event_: CloseEvent): logger.info( f"Session closed at: {get_current_strftime()} with reason: {event.reason}" ) asyncio.create_task( finish_interview_hook(session, usage_collector, speech_analyzer, metadata) )
t
Thanks — seeing your handler helps. Your handler logs the close and spins off cleanup via
asyncio.create_task(finish_interview_hook(...))
. Two reliability concerns to note: • If the process is terminated abruptly (kill, crash, host shutdown) the
close
event may never be emitted and your handler won't run. • Even if the handler runs,
asyncio.create_task
schedules the coroutine but doesn't await it. If shutdown continues and the event loop stops (or the process exits) before the task completes,
finish_interview_hook
may never finish. Recommended changes to improve reliability: • Make cleanup idempotent and persist critical state proactively (DB) during normal operation instead of relying only on shutdown. • Await the cleanup or ensure it has time to run during shutdown. For example, convert the handler to async and
await finish_interview_hook(...)
, or track the created task and await it in a controlled shutdown flow. • If you must fire-and-forget, add a mechanism that retries or reconciles incomplete work (a background worker or reconcilier that scans unfinished sessions). • Ensure your host/container performs graceful shutdown (catch SIGTERM, allow sufficient time for shutdown hooks to complete). If you want, share what
finish_interview_hook
does (IO, DB writes, external API calls) and I’ll suggest the minimal code change to make it more robust.
b
but I can't use coroutine directly in the hook "Cannot register an async callback with
.on()
. Use
asyncio.create_task
within your synchronous callback instead."
t
Thanks — you're right: the
.on()
handler must be synchronous, so
asyncio.create_task
is the correct way to start async work there. Given that constraint, here are concise, practical ways to make your cleanup more reliable. What to change (priority order) 1. Track the background task you create • Store the Task object (e.g., in
session.metadata
or a global map keyed by session id) instead of fire-and-forget. That lets you await or inspect it later. 1. Await the task from a guaranteed shutdown hook • Use your environment's shutdown callback (the framework's shutdown hook or your process SIGTERM handler) to await tracked tasks with a timeout. Example flow: ◦ On close: create task and save reference. ◦ On shutdown: gather tracked tasks,
await asyncio.wait(tasks, timeout=...)
, then cancel remaining tasks if needed. 1. Use timeouts and cancellation • Wrap
finish_interview_hook
with a timeout (e.g.,
asyncio.wait_for
) so you can cancel it cleanly if it hangs. 1. Make cleanup idempotent and persist critical steps early • Write key state to DB as you go so that if the close handler never runs or is interrupted, a reconcilier can finish work later. 1. Add a reconciliation job • Run a periodic background worker that scans for sessions left in an incomplete state and finishes them. This handles crashes and missed close events. Quick code sketch (conceptual)
Copy code
# synchronous close handler
@session.on("close")
def _on_close(evt):
    task = asyncio.create_task(finish_interview_hook(...))
    session.metadata["finish_task"] = task  # or global map[session.id] = task
Then in your shutdown flow (async):
Copy code
tasks = [session.metadata.get("finish_task") for session in open_sessions if task]
await asyncio.wait(tasks, timeout=60)
for t in tasks still pending:
    t.cancel()
If you can't change the host shutdown path, at minimum: • Persist intermediate results inside
finish_interview_hook
as they complete, and • Run a periodic reconciler to detect and finish incomplete interviews. If you share what
finish_interview_hook
does (DB writes, external API calls, duration), I can suggest the minimal wrapping (timeouts, save-points) and an exact pattern to track/await the task in your environment. Would you like that?
b
external API call
t
Thanks — since your cleanup calls an external API and the handler must be synchronous, here are concrete, minimal patterns to make it reliable. Key idea: start the async work in the close handler but make sure it can be awaited or retried elsewhere. 1) Track the task so you can await it on shutdown • In the sync close handler create the task and save the Task object where your shutdown logic can find it (session metadata, global dict keyed by session id).
Copy code
@session.on("close")
def _on_close(evt):
    task = asyncio.create_task(finish_interview_hook(...))
    session.metadata["finish_task"] = task
• In your process shutdown/cleanup coroutine gather and await these tasks with a timeout, then cancel remaining tasks:
Copy code
tasks = [m["finish_task"] for m in all_sessions_metadata if m.get("finish_task")]
await asyncio.wait(tasks, timeout=60)
for t in tasks that are still pending: t.cancel()
2) Add timeouts + retries inside the async hook • Wrap the external API call with
asyncio.wait_for
for an upper bound, and implement retry with backoff (idempotent requests or use an idempotency key).
Copy code
async def finish_interview_hook(...):
    for attempt in range(max_retries):
        try:
            await asyncio.wait_for(call_external_api(...), timeout=10)
            return
        except (asyncio.TimeoutError, transient_exc):
            await asyncio.sleep(backoff)
    # on permanent failure, record failure state for reconciliation
3) Persist progress and make operations idempotent • Persist key steps (DB row or status) as they complete so a reconcilier can pick up where things left off if the task never ran or was killed. • Use idempotency keys for external API calls so retries are safe. 4) Add a reconciliation worker • Periodically scan for sessions with incomplete finalization and call the same
finish_interview_hook
(or a safe variant). This covers crashes, SIGKILL, and missed close events. 5) Ensure graceful host shutdown • Catch SIGTERM, run your shutdown coroutine that awaits tracked tasks, and give enough time for completion before exiting. If you want, paste
finish_interview_hook
(or describe the external API usage and expected duration) and I’ll suggest the smallest code edits to add timeouts, retries, and idempotency. Would you like that?
b
how quick 'close' event is emitted after 202935 INFO livekit.agents closing agent session due to participant disconnect (disable via {"worker_id": "AW_CSqtqUTLR7NH", "room_name":?
t
You're asking how quickly the
close
event is emitted after the log line "closing agent session due to participant disconnect" — short answer: the
close
event is emitted as soon as the AgentSession enters its closed state, which is typically immediate after the session shutdown sequence starts, but exact timing can vary depending on shutdown processing and host lifecycle. Details that matter: • Emission happens when the session is closed (user ended conversation,
session.aclose()
called, room deleted, or unrecoverable error). That log indicates shutdown started; the
close
event is emitted during that shutdown flow. • If shutdown proceeds normally, the handler runs almost immediately after the session state flips to closed. • If the process is being terminated abruptly (SIGKILL, crash, host shutdown), the event may never be emitted because the event loop won't get a chance to run. • If other synchronous operations in the same thread block the event loop, emission may be delayed until the loop is free to run callbacks. Given your constraints (sync
.on()
handler and using
asyncio.create_task
for the external API call), assume emission is prompt but not guaranteed to complete the async work unless you ensure the background task gets time to finish (track the Task and await it during process shutdown, add timeouts/retries, and persist progress so a reconciler can finish work if needed). If you want precise timing in your environment, I can suggest a small instrumentation you can add to measure the delta between the log line and when your
_on_close
handler runs — would you like that snippet?
b
why am I seeing 10-20 seconds difference between INFO livekit.agents closing agent session due to participant disconnect (disable via and the start of the @session.on("close")
t
You're seeing a 10–20s gap because the log line marks the start of the shutdown sequence, not the instant your close handler runs. Common causes for that delay and what to check: • Shutdown sequencing & async work: shutdown may do other synchronous or async cleanup before the AgentSession state flips to closed and emits the event. Any work the agent framework runs first can delay the callback. • Event loop scheduling: the
.on("close")
handler is invoked by the event loop; if the loop is busy (blocking sync work, long tasks, or many concurrent callbacks) the handler won't run until the loop gets CPU. • Network/IO or retries earlier in shutdown: if the agent or other components perform network calls or retries during shutdown, that can add seconds. • Graceful-disconnect timers: the framework or transport may wait for timeouts or ACKs when a participant disconnects (reconnect windows, cleanup of participant state) before formally closing the session. • Host/container lifecycle: if the host delays running shutdown callbacks (draining containers, kubelet grace periods), the session close can be deferred. How to narrow it down (quick checks) • Instrument timestamps: ◦ Log timestamp at the exact start of your
_on_close
handler. ◦ Log earlier points in the shutdown path (immediately after the "closing agent session" log if you can). ◦ Correlate logs to see which component is taking time. • Check for blocking code on the main thread: search for sync sleeps, heavy CPU loops, or blocking I/O in your agent process. • Look for pre-close retries/timeouts in agent logs that might run between the disconnect and session close. How to reduce impact / ensure cleanup runs • Track the task you create in
@session.on("close")
so shutdown can await it (store Task in session metadata or global map). • Add timeouts/retries and idempotency to your external API calls so partial runs are safe. • Add a reconciler that scans incomplete sessions and retries finalization (covers missed or delayed close handlers). • Ensure your process/container handles SIGTERM gracefully and allows enough time for shutdown awaits. If you want, I can provide: • A tiny instrumentation snippet to measure the exact delta between log line and
_on_close
execution. • A minimal pattern to track the
asyncio.Task
and await it in your shutdown flow. Which would you prefer?