Correct the `ProcessEventStream` docs on observer work interrupted when the stream ends early

Merged
DS
2mo ago
+15-6

This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.

Docs-only correction following #10341. That PR documented that an observer that stops reading early can have its shielded cleanup interrupted if the stream then ends early. The hazard is broader: when forwarding stops before end of stream (consumer break or error, cancellation, source error), teardown sends the observer task one native Task.cancel(), which on asyncio interrupts any shielded work the observer is in the middle of, including a shielded write in its loop body.

This PR rewrites the limitation in the ProcessEventStream docstring, docs/capabilities/process-event-stream.md, agent_docs/concurrency.md, and the comment at the handler_task.cancel() site, and documents the workaround: keep iterating to the end of the stream instead of breaking out, then run the shielded cleanup in finally.

No code fix: each alternative cancel strategy probed either leaves an observer interrupted mid-loop unable to finish an unshielded finally, or hangs teardown on an observer stuck mid-loop.

Verification

Each sentence was checked against in-process probes:

  • Observer stops iterating, then shielded cleanup: interrupted on agent.iter() + node.stream(), run_stream() (stream_text()/stream_output(), from the second event), run_stream_events(), and a cancelled agent.run(), for consumer break, error and cancel.
  • Shielded per-event write in the loop body: interrupted.
  • Keep iterating, shielded cleanup in finally: finishes on every path above, plus a source error.
Minimal repro
import asyncio

import anyio

from pydantic_ai import Agent
from pydantic_ai.capabilities import ProcessEventStream
from pydantic_ai.models.function import FunctionModel


async def tokens(messages, info):
    for t in 'abcdef':
        yield t


async def main():
    for breaks in (True, False):
        result = {}

        async def observer(ctx, stream):
            try:
                async for _ in stream:
                    if breaks:
                        break
            finally:
                with anyio.CancelScope(shield=True):
                    try:
                        await anyio.sleep(0.1)
                        result['cleanup'] = 'done'
                    except asyncio.CancelledError:
                        result['cleanup'] = 'interrupted'
                        raise

        agent = Agent(FunctionModel(stream_function=tokens), capabilities=[ProcessEventStream(observer)])
        async with agent.run_stream_events('hello') as events:
            async for _ in events:
                await anyio.sleep(0.02)
                break
        await anyio.sleep(0.2)
        print(f'observer breaks={breaks}: cleanup {result["cleanup"]}')
        #> observer breaks=True: cleanup interrupted
        #> observer breaks=False: cleanup done


asyncio.run(main())

What changes for existing users

Nothing: docs and comments only.

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.