Background work and the end of a run
Tools sometimes start work that outlives the tool call. An agent handling a help-desk case at Belgavi's Book Store asks a tool to re-index the case notes, and the tool starts the indexing in the background so the model can keep talking. Sub-agent tasks and long-running tool calls have the same shape. The question nobody asked in the original code is what happens to that work when the run ends. If the answer is "nothing", it may be abandoned half done, it may keep running after the caller has moved on, or its result may arrive when nobody is listening.
Pydantic AI 2.79.0, released on December 4, 2026, adds a run-level registry for exactly this question. The release notes describe it as a run-level in-flight work registry, RunContext.in_flight, that runs wait for before ending. The pull request that added it, number 13217, is unusually explicit about the design and about its current scope, and both are worth reading before adopting it.
Three end rules
Work enters the registry with one of three end rules, on_end:
- drain for work whose result belongs to this run. The run waits for it. When the run ends with output, it waits until the work has queued content or finished, so the model gets another turn on what was queued. At a pause for deferred tool requests or a pending model response, it waits for all draining work.
- cancel for best-effort work that is worthless once the run is over. The run cancels it when it ends.
- detach for work that lives in a resource that outlives the run, such as a shell job, a kept sandbox or a task an application object owns. The run lists it but never waits for it or cancels it.
A run that ends with an error, is cancelled, times out or hits a usage limit cancels everything except detached work. Two methods put work in the registry. ctx.in_flight.start(fn, kind=..., name=..., id=..., on_end=...) runs a coroutine as a task the run owns and accepts only drain, the default, or cancel. register() records work the caller runs itself and defaults to detach. The docstring of start asks for a deterministic id, such as the tool call identifier, so the same work gets the same identifier when a run is replayed.
Measured in a pinned environment
I installed pydantic-ai-slim 2.79.0 in a fresh environment with packages limited to those published by December 5, and drove a single agent run with a deterministic FunctionModel: the model calls one tool, the tool starts 300 ms of background work, and the model then answers. No provider was called. Three variants differ only in how the tool starts the work.
| How the tool starts the work | Did the run wait at least 300 ms | State of the work when the run returned |
|---|---|---|
asyncio.create_task, no registry | no | still running, not finished |
ctx.in_flight.start(..., on_end="drain") | yes | finished |
ctx.in_flight.start(..., on_end="cancel") | no | cancelled |
A fourth variant called start with on_end="detach"; the tool received a UserError, matching the documented rule that the run does not own detached work and that such work must be registered instead. The first row is the behaviour of code written before this release: the run returned its answer while the background task kept running with no owner.
@agent.tool
async def reindex_case(ctx: RunContext[None], case_id: str) -> str:
async def work():
await index.rebuild(case_id) # must let cancellation stop it
ctx.in_flight.start(work, kind="background_tool", name="reindex",
id=ctx.tool_call_id, on_end="drain")
return "re-index started"What the release does not do yet
The pull request states plainly that nothing changes for existing users because no producer uses the registry yet. It is the first of a planned series; the follow-ups start with moving the existing BackgroundTools capability onto the registry. Until then, the registry governs only work you place in it yourself. Code that relies on built-in background tool behaviour keeps its previous semantics in 2.79.
Durable execution has its own rules in this release. According to the pull request, ctx.in_flight is accepted in workflow and flow code on Temporal, Prefect, Azure Durable Task and Render, and refused with a UserError naming the engine on DBOS, AWS Lambda, Absurd and pgtask, in every mode, until a further change lands. The reason given is that those engines identify recorded units by start order, so recovery could hand the work and the run each other's recorded results. Inside activities, steps and tasks it still raises. The durable flag on start is recorded but, per its docstring, the run does not act on it yet.
The start docstring carries two warnings that matter in production. An error raised by the work ends the run once the current step finishes, so work should catch errors the model ought to hear about and enqueue them instead. And when the run ends, it waits for cancelled work to stop with nothing cutting that wait short, not even the run timeout, so the work must let cancellation stop it or the run never returns.
Choosing the rule
The useful discipline is to decide, for every piece of work a tool starts, who owns its result:
| Work | Owner of the result | Rule |
|---|---|---|
| Re-indexing the case the model is about to search | this run | drain |
| Prefetching suggestions the model may not use | nobody after the run | cancel |
| A nightly export job the tool merely triggered | the export system | detach, via register |
| Sending the customer reply | this run, and it must not be lost | not background work; run it as a step with its own retry |
The last row is the important one. A registry decides waiting and cancellation within one process. It does not make work durable: if the process dies, drained work dies with it. Side effects that must happen exactly once belong in a durable workflow step or an outbox, not in a background task with a drain rule.
Upgrade notes
- Pin 2.79.0 and search your tools for
asyncio.create_task,asyncio.ensure_futureand thread pools started from tool code. Each is a candidate for the registry. - For each, choose drain or cancel, or keep it outside the run and register it as detached.
- Make the work cancellation-safe: no bare
except BaseException, cleanup infinally, blocking calls moved off the event loop. - Catch expected errors inside the work and enqueue them as messages, so a failed re-index becomes something the model can explain rather than a run failure.
- If you run on a durable engine, check the accepted and refused lists above for your engine before calling
ctx.in_flightin workflow code. - Watch the follow-up releases: when built-in producers move onto the registry, their end-of-run behaviour may change.
Failure modes
Orphaned tasks. Work started with a bare task survives the run and may write results into a session that has already been answered.
Hung runs. Drained or cancelled work that ignores cancellation keeps the run open indefinitely; the run timeout does not help.
Unexpected run errors. An exception escaping started work ends the run at the next step boundary instead of being reported to the model.
Durable engine refusals. Code that works locally raises on engines that refuse the registry.
Mistaking drain for durability. Drain waits in memory; a crash loses the work.
Verification
- A test per tool that starts background work, asserting the work's state when the run returns.
- A cancellation test that ends the run with an error and asserts that cancel and drain work stopped and detached work did not.
- A timeout test with work that ignores cancellation, to prove the hazard and then the fix.
- A replay test that the work identifier is stable across runs.
The companion example contains the probe above as a test suite, pinned to 2.79.0, with no provider calls.