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

オープン 初心者向け
#8,366 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
62/100
issue の種類
機能追加
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
python
領域
backend

調査の方向性

ジョブのコンテキストとそのプライベートメソッド _track_pending_task()、および shutdown コールバックの後に追跡中のタスクをキャンセルするシャットダウン経路から始めてください。delete_room と add_sip_participant がこの追跡をどのように使っているかを読んでください。完了の条件は、参照を保持し、失敗をログに記録し、シャットダウン時にキャンセルされる公開の create_task() があり、キャンセル順序とエラーログのテストがあることです。

索引モデルが issue の本文から書いたものです。

説明

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.

主要言語
Python
スター
14.6k
フォーク
3.9k
平均マージ
2日 23時間
マージ済み PR(30日)
263

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

livekit/agents のほかの issue

livekit/agents の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。