Fix `RuntimeError: coroutine ignored GeneratorExit` and an escaping `KeyboardInterrupt` on `Agent.iter()` teardown
This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.
Closes #10249
Why we make these changes
Closing an async generator that owns an Agent.iter() run, or raising GeneratorExit inside the run, raised RuntimeError: coroutine ignored GeneratorExit. A KeyboardInterrupt raised inside the run escaped the event loop even when the caller caught it. Both came from _run_lifecycle_hooks letting the wrap_run task fail with the exception and then awaiting that task. asyncio resumes the waiter through throw(), which closes its whole await chain on GeneratorExit, and re-raises KeyboardInterrupt out of the loop.
On these two exceptions the run now cancels and drains the wrap_run task, the same way a break out of iter() already does.
New public surface
none
User-visible behavior
async def first_event(agent):
async with agent.iter('Hello') as run:
node = await run.next(run.next_node)
async with node.stream(run.ctx) as stream:
yield await anext(aiter(stream))
events = first_event(agent)
await anext(events)
await events.aclose() # before: RuntimeError: coroutine ignored GeneratorExit; now: returns
A capability's wrap_run gets asyncio.CancelledError from handler() in these cases, as it already did for a break. Its cleanup finishes before the async with block exits. The wrap_run docstring now says so.
Verification
- Closing a run-owning generator and a realtime session: the cleanup is drained before
aclose()returns, and the run has no result. GeneratorExitin the body propagates as raised, andKeyboardInterruptpropagates from the caller.- A
wrap_runthat callshandler()again gets theGeneratorExitback, andon_run_errornever sees it. - The four teardown tests fail on
mainand pass on Python 3.11 and 3.13.
What changes for existing users
Closing a generator that owns an iter() run or a realtime session, or raising GeneratorExit/KeyboardInterrupt inside one, now propagates the original exception after cleanup instead of crashing teardown.
PR decisions
- 2026-10-27 · Decisions before this entry are backfilled from resolved review threads. Source: https://github.com/pydantic/pydantic-ai/pull/10258
- 2026-10-27 · Land order vs #10479: this PR lands first, and #10479 resolves the conflict in
_run_lifecycle_hookson its side. David's call. Source: https://github.com/pydantic/pydantic-ai/pull/10479 - 2026-10-27 · Drain the
wrap_runtask instead of only cancelling it, peragent_docs/concurrency.mdownership. The first version leftwrap_runcleanup running afteraclose()returned. Source: https://github.com/pydantic/pydantic-ai/issues/10249 - 2026-10-27 ·
_SHUTDOWN_EXCEPTIONSnames the(GeneratorExit, KeyboardInterrupt)set its three guards share. The tests were rewritten without sleeps or loop exception handler swaps, and a realtime session test was added. Source: https://github.com/pydantic/pydantic-ai/pull/10258 - 2026-10-27 · No durable-engine teardown test. A DBOS run shows the same
CancelledErrorand no leftover state, and no durablewrap_runbranches on the exception type. Source: https://github.com/pydantic/pydantic-ai/pull/10258 - 2026-10-27 · Cleanup errors from a cancelled
wrap_runare discarded, as on thebreakpath.cancel_and_drainretrieves them, andaclose()would swallow aGeneratorExit's context anyway. Source: https://github.com/pydantic/pydantic-ai/pull/10258 - 2026-10-27 · Pre-push review 1 of 3 at 2779aa2bb (tree f784c817a6445149c1555dd6bd3b18904dff01bb, full branch from 14ed34cdb): ran the detach-path and durable suites; rewrote the
_do_runguard comment and kept the guard rather than deleting it as unreachable. Source: https://github.com/pydantic/pydantic-ai/pull/10258 - 2026-10-27 · e258997e3 needs no second pre-push review: from the reviewed 2779aa2bb it changes only a comment, a removed pragma and one coverage test. Source: https://github.com/pydantic/pydantic-ai/pull/10258
- 2026-10-27 · The
_do_runshutdown guard is kept and pinned by a test, not excluded from coverage. It keepson_run_errorfrom seeing these exceptions whenwrap_runcallshandler()again. Source: https://github.com/pydantic/pydantic-ai/pull/10258 - 2026-10-27 · Pre-existing defects found in review are not folded in:
_extract_errorreplacing aGeneratorExitafter a caught node error, and the realtime session's_translate_cancellationhaving noKeyboardInterruptarm. Both behave the same onmain. Two comment nits are left to #10479, which rewrites those lines. David's call. Source: https://github.com/pydantic/pydantic-ai/pull/10479 - 2026-10-27 · #10479 redoes its conflict resolution against this PR's
cancel_and_drainchange after this PR merges; nothing changes here. Source: https://github.com/pydantic/pydantic-ai/pull/10479 - 2026-10-27 · No test for
KeyboardInterruptrun state throughiter(): the caller'sRunCancelled.from_cancellation()state is identical onmainand this head, so it would pin behaviour this PR does not change. Source: https://github.com/pydantic/pydantic-ai/pull/10258 - 2026-10-27 · 2911f9b23 needs no second pre-push review: from the reviewed 2779aa2bb it adds only the removal of one unreachable test line, the only line CI coverage reported missed. Source: https://github.com/pydantic/pydantic-ai/actions/runs/40551070084
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it. (N/A: the changed paths crashed on
main.) - PR title is fit for the release changelog.