agents icon indicating copy to clipboard operation
agents copied to clipboard

Public `JobContext.create_task()` for background tasks that end with the job

Open Harshil-Jani opened this issue 4 weeks ago • 6 comments

Feature Type: Would make my life easier

What we're trying to do

Our voice agent starts many small background tasks during a call. For example: a silence watchdog, a loop that saves call quality stats, and a prefetch of some data.

When the job ends, these tasks should stop too. If a task fails, we want to see the error in the logs.

What we do today

The framework already does this for its own tasks (delete_room, add_sip_participant). It uses JobContext._track_pending_task(). That method is private, so we copy the idea in our own code:

bg_tasks: set[asyncio.Task] = set()

def track_task(coro):
    task = asyncio.ensure_future(coro)
    bg_tasks.add(task)
    task.add_done_callback(bg_tasks.discard)
    return task

# later, in our shutdown code
for task in bg_tasks:
    task.cancel()

We have this in two entrypoints. It works, but every user has to write it, and it is easy to get wrong. Ours does not log errors, for example.

The small API we'd like

task = ctx.create_task(watch_silence(), name="silence_watchdog")

It would just call asyncio.create_task() and then self._track_pending_task(). So the job:

  • keeps a reference to the task, so it is not garbage collected,
  • logs the error if the task fails,
  • cancels the task if it is still running when the job ends.

It returns the normal asyncio.Task, so you can still await or cancel it yourself.

The job already cancels these tasks at the end of shutdown, after the shutdown callbacks. This new method uses that same step. Nothing about shutdown changes.

utils.aio.TaskSet is close, but it is not tied to the job, so nothing cancels its tasks at the end.

Question

Would you accept a PR for this? I have a small change ready: the method with a docstring, plus two tests (the task is cancelled after the shutdown callbacks, and a failing task is logged). Happy to change the name or put it somewhere else if you prefer.

Harshil-Jani avatar Nov 03 '26 23:11 Harshil-Jani

I'd like to pick this up, if it's wanted.

Some evidence that hand-rolling it is harder than it looks: #7052, merged this week, was exactly this bug inside the framework. RealtimeSession created _send_user_text and _deferred_tool_recycle with bare asyncio.create_task() and dropped the handles. The loop keeps only a weak reference, so either could be collected mid-flight — a generate_reply(user_input=...) would then wait forever — and neither was cancelled at aclose(), so one could wake after close and write to a stream that was already gone.

It took six rounds of review to land, and in several of them the problem found was a regression I had introduced in the previous round, mostly around shutdown ordering. That was with a maintainer reading it closely. So "every user has to write it, and it is easy to get wrong" matches my experience from the inside, and your note that yours does not log errors is the same class of thing.

What I would send: create_task() on JobContext, wrapping asyncio.create_task() and _track_pending_task(), with the done callback logging the exception rather than letting it disappear, a name passed through for the logs, and a test that the task is actually cancelled when the job ends.

Say the word and I will open it. If there is a reason _track_pending_task() was deliberately kept private, I would rather hear that first than send a PR against the intent.

Rehansanjay avatar Nov 05 '26 17:11 Rehansanjay

Reading the code on main, one detail matters for a silence watchdog. Tasks in _pending_tasks are cancelled in _cleanup_job, after all of _shutdown_job: https://github.com/livekit/agents/blob/0f3af69338cfbc8552b7852a5d6b537a64f8e477/livekit-agents/livekit/agents/ipc/job_proc_lazy_main.py#L466-L468

Before that, the job waits for the entrypoint (up to 15 s), closes the primary AgentSession, disconnects the room and runs the shutdown callbacks: https://github.com/livekit/agents/blob/0f3af69338cfbc8552b7852a5d6b537a64f8e477/livekit-agents/livekit/agents/ipc/job_proc_lazy_main.py#L474-L577

So a task from ctx.create_task() keeps running after the session has closed. If the watchdog calls session.say() in that window, it raises AgentSession isn't running, and _track_pending_task would log it as error in silence_watchdog: https://github.com/livekit/agents/blob/0f3af69338cfbc8552b7852a5d6b537a64f8e477/livekit-agents/livekit/agents/voice/agent_session.py#L1607-L1608

On the current release, the session's close event fires right after the activity teardown, before the room disconnects: https://github.com/livekit/agents/blob/0f3af69338cfbc8552b7852a5d6b537a64f8e477/livekit-agents/livekit/agents/voice/agent_session.py#L1363-L1367

Cancelling there should stop the tasks earlier. I haven't run this:

def _cancel_bg_tasks(_ev) -> None:
    for task in list(bg_tasks):
        task.cancel()

session.on("close", _cancel_bg_tasks)

For the API: should tasks from ctx.create_task() be cancelled when the primary session closes, or at the end of cleanup like the framework's own tasks?

johnwils avatar Nov 16 '26 19:11 johnwils

Thanks, that matches what I see on main (03f4e4938): _pending_tasks are only cancelled in _cleanup_job, after the entrypoint wait, the primary session close, on_session_end, the room disconnect and the shutdown callbacks.

My answer: cancel them when the primary session closes, and keep cleanup as the fallback.

  • Almost everything you'd start with ctx.create_task() (a silence watchdog, a periodic say(), a reminder timer) talks to the session. Once the session is closed there's nothing useful left for it to do, and letting it run only produces the AgentSession isn't running errors you found.
  • Work that really has to outlive the session, like uploading a transcript, already has a place: ctx.add_shutdown_callback(), which runs after the session closes and is awaited.
  • If the job never starts a session, or a task is created after the session closed, _cleanup_job still cancels it, as today.

One catch for the implementation: _pending_tasks also holds the framework's own tasks (delete_room, add_sip_participant, transfer_sip_participant via _track_pending_task). Those shouldn't be cancelled when the session closes; a delete_room() issued at the end of a call has to finish. So tasks from ctx.create_task() would need their own set.

In code: when the primary session emits close, cancel that set; and in _shutdown_job, right after _aclose_impl(), await them with aio.cancel_and_wait() so they're fully stopped before on_session_end and the shutdown callbacks run. Cancelling from the close handler only requests the cancel; awaiting it is what guarantees a watchdog can't wake up in the middle of the shutdown callbacks.

Your session.on("close", ...) snippet is the right workaround on the current release until something like this lands.

If a maintainer is OK with this behaviour, I'm happy to open the PR, with tests for both orders: the session closing before the job shuts down, and the job shutting down first.

Rehansanjay avatar Nov 17 '26 03:11 Rehansanjay

One thing I'd separate before anyone writes this: job lifetime and session lifetime are different scopes, and the cancel point decides which one ctx.create_task() really is.

If it's tied to the primary session's close, the name says job but the behavior says session. A session can be restarted, a job can run several sessions (the multi-user transcriber example) or none, and which one is primary is decided at start().

I tried the job-scoped version on a branch. User tasks go in their own set, not _pending_tasks, so delete_room() still finishes. They're cancelled in _shutdown_job after the entrypoint wait and before session._aclose_impl(), with a bounded wait like _SESSION_ACLOSE_TIMEOUT, and _cleanup_job cancels anything started later. That gives one rule: these tasks are stopped before the session closes and before on_session_end and the shutdown callbacks run, so the AgentSession isn't running race from johnwils' comment can't happen during shutdown. Seven tests in test_ipc.py cover order, logging, a task that swallows the cancel, tasks started in a shutdown callback, and framework tasks surviving.

task = ctx.create_task(watch_silence(), name="silence_watchdog")

Two questions for maintainers:

  1. Should the session-closed-early case (caller hangs up, job lingers until the room empties) be handled here, or on AgentSession as its own scope?
  2. Is a hardcoded bounded wait (5 s) fine for tasks that ignore cancellation, or should it come from the worker's options?

@Harshil-Jani and @Rehansanjay offered first, so this is input for whoever sends it. If it helps, I can push the tests or the branch.

ayushmnnit avatar Nov 21 '26 04:11 ayushmnnit

Your job-scoped version is the cleaner rule, and the tests cover the cases I had in mind. Please go ahead and open it; happy to review.

Rehansanjay avatar Nov 21 '26 06:11 Rehansanjay

I think the solution is to keep a reference to the task and cancel it in one of two places. If the task uses the session, cancel it when the session closes. session.on() accepts only sync callbacks, so this requests the cancel without waiting for it:

task = asyncio.create_task(watch_silence(session))
session.on("close", lambda _: task.cancel())

If the task must be fully stopped before the job ends, wait for it in a shutdown callback. That callback can be async, but it runs after the session has closed:

from livekit.agents import utils

task = asyncio.create_task(save_stats())

async def _stop_stats() -> None:
    await utils.aio.cancel_and_wait(task)

ctx.add_shutdown_callback(_stop_stats)

longcw avatar Dec 02 '26 02:12 longcw