Let shielded model-stream cleanup finish when an outer `anyio` cancel ends a debounced `stream_text()`, `stream_output()` or `stream_response()`
This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.
No linked issue: the team found this bug while reviewing #10341. No user has reported it.
Why we make these changes
With a float debounce_by (default 0.1), stream_text(), stream_output() and stream_response() pull the model stream in a separate task inside group_by_temporal. On teardown, _cleanup_temporal_group cancelled that task once and then awaited it plainly, so every re-cancel from a cancelled outer anyio scope (move_on_after, fail_after, a failing task-group sibling) reached the source as a native cancel, which ignores anyio shields. That cut short shielded source cleanup, such as a FunctionModel stream function's finally or a ProcessEventStream observer's teardown; httpx connections and concurrency slots were released either way. The teardown now drains the pull with _utils.cancel_and_drain and reads task.result() afterwards, so a source failure still propagates, and agent_docs/concurrency.md records that pattern.
It also carries ebadada93, a one-line anchor in agent_docs/concurrency.md that tags the ProcessEventStream native-cancel rule with its code site. That commit missed #10449's merge.
New public surface
None.
User-visible behavior
async def stream_function(messages, info):
try:
yield 'first'
await anyio.sleep_forever()
finally:
with anyio.CancelScope(shield=True):
await release_resource() # before: interrupted; after: finishes
with anyio.move_on_after(1):
async with agent.run_stream('hello') as result:
async for text in result.stream_text():
...
Verification
test_run_stream_outer_cancel_during_debounce_lets_source_cleanup_finish, parametrized overstream_text()andstream_response()test_source_cleanup_finishes_when_cancelled_during_debounced_pull, aProcessEventStreamobserver under the default debounce
All three cases fail on main and pass on this branch.
What changes for existing users
Shielded source cleanup now finishes when an outer anyio cancel ends a debounced stream, and a second native Task.cancel() landing during that teardown now propagates instead of being swallowed.
Not in this PR: a plain break out of a debounced stream_text() with no outer cancel also cuts shielded source cleanup, through the abandoned generator's finalizer; that belongs to the dropped-iterator family in #8767.
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.