Close inner event streams so a raising listener cancels in-flight tool calls

Merged
KL
1mo ago
+200-75

When a stream-dispatched on_event listener raises, agent.run() raised while the tool call that emitted the event was still running. The generators between dispatch_event_stream and the tool tasks re-yielded from their inner streams without closing them, so the tool was cancelled only when the garbage collector got to it, after run() had already raised. Each link now closes the stream it reads from, so the tool is cancelled and awaited before the exception leaves run().

What changes

 _run_context.py :: dispatch_event_stream()          listener raises here (closes its stream, from #11009)
 └─ _agent_graph.py :: _with_event_stream_buffer()
+   closes `CallToolsNode._run_stream()` (outer, then inner)
+   └─ CallToolsNode._handle_tool_calls()
+      └─ _tool_execution.py :: process_tool_calls() -> _ToolCallProcessor.run()
+         ├─ _run_strategy()
+         │   early:      -> _run_function_calls() -> _call_tools()
+         │   graceful:   -> flush_pending() (in the loop and at the end) -> _run_function_calls() -> _call_tools()
+         │   exhaustive: owns its tool tasks directly
+         └─ _finalize_deferred() -> _resolve_deferred_calls() -> _call_tools()   (approved deferred calls resolved inline)

The same closing applies when a run(event_stream_handler=...) handler raises, or when user code raises inside async with node.stream(ctx) on a CallToolsNode. In all three cases capture_run_messages now ends with the interrupted request when the exception leaves run(), not later at garbage collection, matching the existing cancellation path. Runs that complete, and break/return out of node.stream(), are unchanged.

Return annotations on the touched private generators change from AsyncIterator to AsyncGenerator so they fit aclosing.

Verification

test_stream_listener_exception_cancels_in_flight_tool in tests/test_on_event.py has a tool emit an event and then block. A listener raises, and the test asserts the tool's finally has run by the time run() raises. It runs 8 cases: every end_strategy with a function tool, graceful and exhaustive with a function tool followed by an output tool, and every strategy with an approved deferred tool resolved inline by HandleDeferredToolCalls.

The test holds every generator started in _agent_graph, _tool_execution and _run_context. Without that, removing any single link still passed: the generators below it became unreachable, and the garbage collector closed them during run()'s teardown. With it, reverting any one of the 15 links fails at least one case.

Not in this PR

_iter_completed_or_buffered inside _call_tools is still left for the garbage collector. It owns no tool tasks.

PR decisions

2026-10-26 · pre-push review 1 of 3 at 2c37350b31 (merge of main) · iter -

  • Decision: merge resolution sound; finding: end_strategy='early' left _run_function_calls unclosed; test covered graceful only
  • Why: fresh Opus reviewer; probe showed early tool cancelled only by GC finalizer after run() raised, and a finished tool's return lost from history; fixed in 6cced9181b (aclosing + test over all strategies)
  • Source: https://github.com/pydantic/pydantic-ai/pull/8822

2026-10-26 · test hardening at 6cced9181b · iter -

  • Decision: hold generators via asyncgen firstiter hook in the regression test
  • Why: single-link reverts all passed before: GC finalizer closed orphaned links during run() teardown and masked them; with generators held every link revert fails
  • Source: https://github.com/pydantic/pydantic-ai/pull/8822

2026-10-26 · pre-push review 2 of 3 at 6cced9181b · iter -

  • Decision: early fix correct; findings: graceful in-loop flush_pending unclosed; inline-approved deferred path (_finalize_deferred -> _resolve_deferred_calls -> _call_tools) unclosed on all strategies (pre-existing on main)
  • Why: both reproduced with reviewer's probe on HEAD; same claim and chain, 4 aclosing sites, so fixed here in 0d5bd0658a with 5 more test cases; each of 15 links verified caught by >=1 case
  • Source: https://github.com/pydantic/pydantic-ai/pull/8822

2026-10-26 · pre-push review 3 of 3 at 0d5bd0658a · iter -

  • Decision: no code defects; PR description stale (test shape, CI note, event_stream_handler/node.stream scope, interrupted history at raise)
  • Why: fresh Opus reviewer: only _call_tools and exhaustive _run_strategy own tool tasks and every route to them is closed; per-link nullcontext matrix: every link fails >=1 of 8 cases; base vs HEAD probe confirms tool cleaned and history interrupted at raise time
  • Source: https://github.com/pydantic/pydantic-ai/pull/8822

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.

AI Disclaimer

This PR was developed with the assistance of either Claude or Codex. I've reviewed and verified the changes.