Cancel in-flight model stream when `InputGuardrail(parallel=True)` blocks

Closed
NA
2mo ago
+103-8

Description

Closes #9279.

When an InputGuardrail(parallel=True) blocks a run that is already streaming model output, the model keeps producing chunks until the whole stream drains — the consumer only sees the guard's block response after the full stream completes.

This PR makes a parallel input guardrail block cancel the in-flight model stream:

  • Adds a short-circuit watcher in ModelRequestNode.stream() that awaits asyncio.shield(wrap_task). If the parallel guard's wrap_task raises SkipModelRequest after the stream has been handed to the consumer, the watcher calls AgentStream.aclose_events() so iteration stops promptly instead of draining the stream.
  • A post-handoff SkipModelRequest is passed to _finish_handling(ctx, e.response), so the run ends with the guard's normal block response rather than surfacing the raw exception to the consumer.
  • Handler teardown is serialized with active stream pulls by acquiring the stream's _anext_lock, avoiding an anext(): asynchronous generator is already running race when cancellation lands mid-pull.
  • model_request_stream() shields sr.aclose() with anyio.CancelScope(shield=True) so cleanup completes under outer cancellation.

Testing

  • New regression test TestInputGuardrailStreaming::test_parallel_block_interrupts_stream_and_ends_with_block_message (public API, event-based, no sleeps): the guard blocks after the first model chunk is pulled, the run ends with the guard's block message, and prompt interruption is asserted.
  • tests/harness/guardrails/test_input_guardrail.py: 49 passed.
  • tests/harness/guardrails/: 305 passed.
  • Pyright (targeted, pydantic_ai/_agent_graph.py): 0 errors, 0 warnings.
  • Ruff check and format check: passed.
  • Manual end-to-end repro (20 model chunks): before the fix the consumer drained all chunks and saw the block after ~2.1s; after the fix the run completes in ~0.3s with 5 consumer events and the guard's block message.