Await `ProcessEventStream` cleanup after early exit and cancellation
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
- test_processor_cleanup, test_processor_cleanup_on_cancellation, test_observer_async_cleanup_after_consumer_error, test_observer_cleanup_finishes_when_cancelled_after_eof, and test_observer_cleanup_on_cancellation cover processor and observer cleanup.
- test_source_cleanup_finishes_when_cancelled_after_observer_returns covers source cleanup when the consumer is cancelled after the observer returns. It fails if the pull is awaited with a plain
await. - test_streamed_request_releases_slot, targeted streaming tests, the FunctionModel test module, Pyright, Ruff, the offline audit, and the branch MRE passed. Targeted coverage exercised every new production cleanup statement and branch.
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.