Close the whole `AgentStream` event stream when a consumer leaves `node.stream()` early

Merged
AD
1mo ago
+105-31

Why we make these changes

When a consumer leaves node.stream() before the stream ends, aclose_events() closes the capability wrappers and dispatch_event_stream, and stops there. Below that, _events_iter, the token-limit wrapper and _model_events read from their source with anext() / async for and never close it, so the garbage collector closes them later. Since #10003, _model_events is collected only when agent.iter() exits, so its aclose() task is still pending after the run returns. Each of these layers now closes the iterator it reads from.

The dispatch_event_stream change is the same hunk as #8822 (approved, not merged). Without it the close never reaches the layers below. Whichever PR lands second has a conflict on identical lines.

New public surface

None.

User-visible behavior

 _agent_graph.py :: ModelRequestNode._stream()   (consumer left the stream early)
 └─ result.py :: AgentStream.aclose_events()
   └─ capability wrappers, closed
     └─ _run_context.py :: dispatch_event_stream()
+      └─ result.py :: AgentStream._events_iter(), closed
+        └─ result.py :: _usage_checking_iterator(), closed (token limits only)
+          └─ result.py :: AgentStream._model_events(), closed
-      (rest closed later by the garbage collector; `_model_events` after `agent.iter()` returns)

Verification

  • test_node_stream_early_exit_closes_event_stream in tests/test_streaming.py, with and without token limits. It holds every generator AgentStream starts, so the garbage collector can't close them in its place, and asserts each is closed right after node.stream() exits. It fails on main, and fails again if any one of the three finally blocks is reverted.

What changes for existing users

Nothing, except that an early exit no longer leaves cleanup work pending after the run. Model-side generators (StreamedResponse.__aiter__ wrappers) still close later through the garbage collector. The provider call itself is already closed by model_request_stream, so that is left as a follow-up.

PR decisions

2026-10-22 · pre-push review 1 of 3 at 417bb124a2b07a314c67573e81dc12bd638ef100 · iter -

2026-10-22 · exempt CI repair at 9963a77ab1f495b85db684bb09a85c06065d5efa · iter -

2026-10-26 · pre-push review 2 of 3 at 9963a77ab1f495b85db684bb09a85c06065d5efa · iter -

  • Decision: no defects; one optional test tightening (assert right after node.stream() exits, not after agent.iter())
  • Why: fresh Opus reviewer, full branch 04dc4c2fe3..9963a77ab1; ownership of every closed source, cancel scopes, two-task design, mechanism and test checked; evidence script verified stronger claim holds on HEAD and fails on base
  • Source: https://github.com/pydantic/pydantic-ai/pull/11009

2026-10-26 · exempt test-only delta at 89399180e542afa4839993c068b545561ee4c852 · iter -

  • Decision: no review: review-2 finding applied, assertions moved inside the run
  • Why: delta from reviewed 9963a77ab1 is tests/test_streaming.py only, moving two existing asserts before break; passes on HEAD, fails on base result.py/_run_context.py; pyright+ruff clean
  • Source: https://github.com/pydantic/pydantic-ai/pull/11009

Checklist

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