This message was deleted.
# ask-ai
s
This message was deleted.
t
Thanks for reaching out, Basile. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're already on the right track. When you call
self.session.shutdown(drain=True)
, any shutdown callbacks you registered on the
JobContext
with
ctx.add_shutdown_callback()
will be executed as part of the session cleanup. Key points to ensure they run: • Register callbacks before calling shutdown: call
ctx.add_shutdown_callback(your_callback)
in your entrypoint (or otherwise while the session/context is active). • Use
drain=True
if you want the agent to finish speaking before shutdown. • Call
await self.session.shutdown(drain=True)
from your inactivity handler (or
session.shutdown(drain=True)
if synchronous in your code path). • The framework will run the callbacks during post-processing and waits (up to the framework timeout) for them to complete. If your callbacks are not being invoked, tell me: • Where you register the callbacks (entrypoint or elsewhere), • Whether you call shutdown from a background task, • Any errors or logs you see when shutdown runs. Sources: Job lifecycle | LiveKit docs
Thanks — I reviewed your entrypoint. The shutdown callbacks you add with
ctx.add_shutdown_callback(...)
will run only if the framework executes the JobContext shutdown flow. To narrow this down, please check/confirm the following so I can pinpoint the issue: 1. Where and how does your
LifecycleController
call
session.shutdown(drain=True)
? ◦ Is it calling
await session.shutdown(drain=True)
(async) or calling it without awaiting? ◦ Is that call made from
lifecycle.on_user_state_changed
or a background task started by
lifecycle.start_hard_limit()
? 1. Do you see logs that confirm shutdown ran? Share any logs around the shutdown time (e.g., "Session shutting down", "Draining", exceptions, or canceled tasks). 2. Are any exceptions thrown from your shutdown callbacks (e.g., in
write_transcript
,
flush_trace
,
log_usage
) that might abort the post-processing? If so, paste the stack trace or error message. 3. Is the process being terminated abruptly (SIGTERM/SIGKILL) before callbacks finish? If you have orchestration logs (container exit code, platform timeout), include them. Quick checklist to try now: • Ensure
session.shutdown(drain=True)
is awaited from an async context. • Register callbacks before shutdown happens (you already do this in entrypoint — keep it there). • Make callbacks resilient: catch exceptions inside each callback and log them. • Add a short debug callback to confirm invocation:
Copy code
async def _debug_shutdown():
      logger.info("DEBUG: shutdown callback invoked")
  ctx.add_shutdown_callback(_debug_shutdown)
If you share where
LifecycleController
triggers shutdown and any shutdown-time logs, I’ll give the exact fix. Would you like help adding safe exception-handling wrappers to your callbacks?
Thanks — this is enough to diagnose the most likely cause. What’s happening • You call
self.session.shutdown(drain=True)
inside your async tasks but never await it.
session.shutdown(...)
is async, so calling it without
await
schedules the coroutine but does not run the shutdown flow to completion. That prevents the JobContext post-processing from running and your
ctx.add_shutdown_callback(...)
callbacks from being executed. Fix • Await the shutdown call inside your tasks. Minimal changes: 1. In
_user_presence_task
replace:
Copy code
self.session.shutdown(drain=True)
with:
Copy code
await self.session.shutdown(drain=True)
1. In
_hard_limit
replace:
Copy code
self.session.shutdown(drain=True)
with:
Copy code
await self.session.shutdown(drain=True)
Additional recommendations • Wrap each shutdown callback body in try/except and log exceptions so a failing callback doesn’t prevent others from running. • Add a small debug shutdown callback (logs immediately) to confirm callbacks run. • Ensure the task that calls
await session.shutdown(...)
is not cancelled or the process killed before shutdown completes. If you want, I can show the updated controller methods with awaits and safe shutdown-callback wrappers.
Thanks — I see the session closed with reason "user_initiated" but your callbacks still aren't observed. Let’s narrow this down. What I need from you • Confirm the exact place you call
ctx.add_shutdown_callback(...)
— is it the same
ctx
object passed into
entrypoint
(your snippet shows it is, but please confirm you didn't shadow
ctx
elsewhere). • Share any logs around the time after "session closed" for the next ~10–60s (search for any callback logs or errors). The framework waits up to 60s for callbacks. • Confirm whether the process/container is being terminated by the platform (SIGTERM→SIGKILL) right after session close. Platform timeouts can abort callbacks. Quick checks to run now (one-line changes you can add to reproduce and gather info) 1. Add an immediate debug callback to confirm registration and invocation:
Copy code
async def _debug_shutdown():
    logger.info("DEBUG: shutdown callback invoked")
ctx.add_shutdown_callback(_debug_shutdown)
1. Wrap callbacks to surface exceptions:
Copy code
def wrap(cb):
    async def wrapper():
        try:
            await cb()
        except Exception:
            logger.exception("shutdown callback failed")
    return wrapper

ctx.add_shutdown_callback(wrap(write_transcript))
ctx.add_shutdown_callback(wrap(flush_trace))
ctx.add_shutdown_callback(wrap(log_usage))
1. After your
await session.shutdown(drain=True)
add a debug log in the same task immediately after to confirm control returns:
Copy code
await self.session.shutdown(drain=True)
logger.info("shutdown() returned — should have run callbacks")
Likely causes and how to verify • Callbacks not registered on the same JobContext instance: confirm
ctx
is the entrypoint
JobContext
. • Callbacks raising and failing silently: wrapping with try/except will show stack traces. • Process killed before callbacks finish: check platform/container events and exit codes right after session close. • Another code path calling
await session.aclose()
or forcibly closing the process: search codebase for
aclose()
or direct process exits. If you share: • The extra logs after adding the debug callback/wrappers above, and • Whether the process exits immediately (exit code / platform logs), I’ll pinpoint the next fix and provide the exact code changes to ensure callbacks always run. Sources: Job lifecycle | LiveKit docs | Operational Best Practices | livekit/livekit_composite | DeepWiki | Agent server options | LiveKit docs | Events and error handling | LiveKit docs
Thanks — helpful confirmations. Since callbacks were registered on the correct
ctx
and you see no logs after "session closed", the most likely causes are (A) the process is being terminated immediately by the environment before callbacks run, or (B) callbacks are failing silently before logging. Let’s narrow it down with a couple small, non-invasive checks. Please add these three changes and paste the new logs: 1) Add an immediate debug callback (verifies callbacks were registered and invoked):
Copy code
async def _debug_shutdown():
    logger.info("DEBUG: shutdown callback invoked")
ctx.add_shutdown_callback(_debug_shutdown)
2) Wrap existing callbacks to log exceptions:
Copy code
def wrap(cb):
    async def wrapper():
        try:
            await cb()
        except Exception:
            logger.exception("shutdown callback failed")
    return wrapper

ctx.add_shutdown_callback(wrap(write_transcript))
ctx.add_shutdown_callback(wrap(flush_trace))
ctx.add_shutdown_callback(wrap(log_usage))
3) Log right after shutdown returns in the task that calls it:
Copy code
await self.session.shutdown(drain=True)
logger.info("DEBUG: session.shutdown returned — callbacks should have run")
Also answer these two quick questions: • Does your runtime/platform (Kubernetes, serverless, etc.) terminate the process immediately after the job ends or enforce a short SIGTERM → SIGKILL timeout? • Do you see any exit codes or container/platform events at the same timestamp as "session closed"? Send the new logs after adding the three changes above and the answers — I’ll analyze them and give the exact next fix.
Thanks — helpful to know the post-shutdown log never appears. That means the coroutine that calls
await session.shutdown(drain=True)
never resumes (it either never returns or the task/process is terminated before it can). Let's narrow root causes with two focused checks. 1) Confirm whether shutdown coroutine is started and where it stops • Add this around the shutdown call in both tasks (keep exactly as async):
Copy code
logger.info("DEBUG: about to call session.shutdown")
await self.session.shutdown(drain=True)
logger.info("DEBUG: session.shutdown returned")
You said the second log never appears — paste the first log timestamp if you see it. If you never see the first log either, the code path may not be reached. 2) Determine if the process is being terminated before shutdown completes • Immediately before calling shutdown, spawn a background watchdog that logs every 1s for 10s to detect abrupt termination:
Copy code
async def _watchdog():
    for i in range(10):
        logger.info(f"DEBUG: watchdog alive {i}")
        await asyncio.sleep(1)
asyncio.create_task(_watchdog())
logger.info("DEBUG: calling shutdown now")
await self.session.shutdown(drain=True)
logger.info("DEBUG: shutdown finished")
If watchdog logs stop at the same time as "calling shutdown now", the platform is killing the process quickly. If watchdog continues while shutdown hangs, shutdown is stuck. 3) Check for external termination signals / exit codes • Share container/orchestrator logs around the shutdown time (SIGTERM/SIGKILL, pod events, exit code). If your platform enforces a short SIGTERM→SIGKILL window, callbacks may be aborted. 4) Quick local verification • Run the same entrypoint locally (or in a dev container) and trigger the inactivity shutdown to confirm shutdown callbacks run outside your platform. If they run locally but not in production, the platform is the culprit. What I’ll do next after you run these: • If watchdog logs stop immediately when shutdown is called → tell me your runtime (Kubernetes/Cloud Run/etc.) and I’ll explain how platform timeouts interrupt draining. • If watchdog continues but shutdown never returns → I’ll show how to instrument session internals and add a cancellable timeout around
await session.shutdown(...)
to capture exceptions. • If you can paste the exact logs for the DEBUG lines above, I’ll pinpoint the next code change. Which of the two tests (1 — simple debug logs, 2 — watchdog) can you run first?
You're asking for the best practice to shut down a session from an async background task and ensure shutdown callbacks run. Summary and concrete steps: 1) Always await shutdown from the async task • Use: await session.shutdown(drain=True) • This ensures the framework runs the drain sequence and invokes
ctx.add_shutdown_callback()
hooks. 2) Ensure callbacks are registered early on the same JobContext • Call
ctx.add_shutdown_callback(...)
in entrypoint before any background task can trigger shutdown. 3) If the agent may be speaking, wait for playout first • Use
await ctx.wait_for_playout()
(or equivalent) before shutdown so in-flight speech finishes cleanly. 4) Make callbacks resilient and observable • Wrap callbacks to catch/log exceptions so one failing callback doesn’t hide others. • Add a small debug callback that logs immediately to verify invocation. Example wrapper:
Copy code
def wrap(cb):
    async def wrapper():
        try:
            await cb()
        except Exception:
            logger.exception("shutdown callback failed")
    return wrapper
5) Instrument the shutdown path to detect external termination • Log immediately before and after calling shutdown:
Copy code
logger.info("DEBUG: calling session.shutdown")
await session.shutdown(drain=True)
logger.info("DEBUG: session.shutdown returned")
• Add a watchdog task that logs every second to detect platform kills. 6) Avoid
aclose()
for graceful teardown •
aclose()
can bypass the drain/cleanup sequence. Use
shutdown(drain=True)
for normal shutdown. 7) Account for platform SIGTERM → SIGKILL timeouts • If your platform kills the process too quickly, increase the shutdown/grace timeout so callbacks can finish. If you want, I can: • Show the precise edits to your LifecycleController to add
await
+ watchdog + wrapped callbacks, or • Provide a small reproducible snippet you can run locally to confirm callbacks run outside your platform. Which would you prefer? Sources: Job lifecycle | LiveKit docs | Agent speech and audio | LiveKit docs | Agent server options | LiveKit docs | Deploying to custom environments | LiveKit Docs