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

Abierto Apto para principiantes
#8,366 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
62/100
Tipo de issue
Nueva funcionalidad
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python
Área
backend

Línea de trabajo

Empieza por el contexto del job y su método privado _track_pending_task(), así como por la ruta de apagado que cancela las tareas rastreadas tras los callbacks de shutdown. Lee cómo delete_room y add_sip_participant usan ese rastreo. Está terminado cuando existe un create_task() público que mantiene una referencia, registra los fallos y se cancela al apagar, con pruebas para el orden de cancelación y el registro de errores.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.

Lenguaje dominante
Python
Estrellas
14.6k
Forks
3.9k
Merge medio
2 d 23 h
PR fusionados (30 d)
263

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de livekit/agents

Todos los issues de livekit/agents

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.