Await `ProcessEventStream` cleanup after early exit and cancellation

Merged
DS
2mo ago
+381-51

This pull request was posted by Codex Desktop using gpt-6.1-sol on behalf of David.

Consumers that break from or fail during a processed stream could leave processor resources open. During cancellation, cleanup in the observer, source pull, or FunctionModel stream could also be interrupted. This PR shields that cleanup and cancels the observer and source pull through their own AnyIO scopes, keeping one native cancel where an observer's unshielded finally must still await. Teardown awaits those tasks with asyncio.wait, because asyncio.shield reports their later exceptions to the loop on current CPython 3.14 and 3.15 releases (python/cpython#156321). An observer that stops reading early can still have its cleanup interrupted if the stream then ends early, as on main; the per-pull task arrangement and request-context task affinity are outside this change.

New public surface

None.

User-visible behavior

pydantic_ai_slim/pydantic_ai/agent/abstract.py :: AbstractAgent.run_stream()
└─ … unchanged graph machinery …
   ├─ pydantic_ai_slim/pydantic_ai/capabilities/process_event_stream.py :: ProcessEventStream.wrap_run_event_stream()
+  │  └─ pydantic_ai_slim/pydantic_ai/_utils.py :: aclose_if_supported(probe) → processor cleanup completes under a shield
   └─ … unchanged model dispatch …
      └─ pydantic_ai_slim/pydantic_ai/models/function.py :: FunctionModel.request_stream()
+         └─ pydantic_ai_slim/pydantic_ai/_utils.py :: PeekableAsyncStream.aclose() → source cleanup completes under a shield

On forwarding errors, observer teardown preserves the single edge Task.cancel(); after EOF it cancels its own scope. Teardown drains observer and pull tasks before source close.

Verification

The Trio attempt stops at the existing asyncio.create_task call before streaming starts.

What changes for existing users

Processor cleanup, and cleanup of an observer still reading the stream, now completes after early exit, errors, and cancellation, with no public API change.

No linked issue.

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.