skrawcz opened a new pull request, #1027:
URL: https://github.com/apache/burr/pull/1027
Closing `Application.astream_iterate()` (or abandoning an
`AsyncStreamingResultContainer`) partway through an action leaves the action's
generator chain suspended until garbage collection or
`loop.shutdown_asyncgens()`. Anything the action holds open (HTTP/SSE streams,
DB cursors, OTel spans, `async with` blocks) is released late and in an
arbitrary context, and any cleanup error is only logged by the asyncgen
finalizer.
The cause is that every async forwarding layer uses a bare `async for` and
never closes the generator it reads from:
```
astream_iterate ─► AsyncStreamingResultContainer ─► _arun_*_streaming_action
─► FunctionBasedStreamingAction._a_stream_run_and_update ─► pydantic
async_action_generator
─► (user action)
```
Minimal repro on `main`:
```python
async def producer():
try:
yield "a"; yield "b"
finally:
await asyncio.sleep(0) # e.g. closing an HTTP stream
closed.append("producer")
@streaming_action(reads=[], writes=["x"])
async def act(state):
async with contextlib.aclosing(producer()) as p:
async for c in p:
yield {"c": c}, None
yield {"c": "done"}, state.update(x=1)
steps = app.astream_iterate(halt_after=["act"])
async for _, container in steps:
async for _ in container:
break
break
await steps.aclose()
# main: closed == [] (runs later during loop shutdown, plus
"aclose(): asynchronous generator is already running")
# branch: closed == ["producer"]
```
## Changes
- **`AsyncStreamingResultContainer.aclose()`** (new, public): stops the
stream without draining it, closes the action's generator chain, and runs the
post-step callback exactly once. It is idempotent, and `get()` afterwards
returns `(None, initial_state)`. Exceptions raised by the action's cleanup
propagate to the caller, and the callback still receives them. The container
now keeps a handle to its `__aiter__` iterator so that `aclose()` can close it
too.
- **`Application.astream_iterate`**: if it is closed at its `yield`, it
calls `aclose()` on the in-flight container before re-raising `GeneratorExit`.
- **`_arun_single_step_streaming_action` /
`_arun_multi_step_streaming_action`**: `finally: await generator.aclose()`.
- **`FunctionBasedStreamingAction._a_stream_run_and_update`**, the
`type_eraser` async-gen wrapper, and the pydantic **`async_action_generator`**
now wrap the inner generator in `contextlib.aclosing(...)`.
Streams that are fully consumed behave the same as before; closing an
already-finished generator does nothing.
## How I tested this
- New tests in `tests/core/test_application.py`:
- closing `astream_iterate` mid-action, both with and without consuming an
item first: the action's cleanup runs right away, the action is not advanced,
and `post_end_stream` fires exactly once;
- `aclose()` called twice is safe, and `get()` afterwards returns the
initial state;
- an exception raised during cleanup propagates out of `aclose()`, and the
callback receives it.
- The new tests fail on `main` and pass on this branch.
- Full suite (excluding `tests/integrations/persisters`): 708 passed, 4
skipped. Pre-commit passes.
- Downstream check: in an internal consumer that was working around this
with an `AsyncExitStack` passed in through action inputs, this branch plus
`contextlib.aclosing(...)` around `astream_iterate` made that workaround
unnecessary (its 8 regression tests pass without it).
## Notes
- **Behavior change:** cleanup exceptions from a closed action now propagate
to whoever closes the stream, where before the asyncgen finalizer swallowed
them and only logged them. I think that's correct, but it's worth calling out
in the release notes.
- **Not covered here:** the sync path (`stream_iterate` /
`StreamingResultContainer`) has the same pattern and isn't changed. I'm happy
to do it in a follow-up PR or add it here.
- `contextlib.aclosing` needs Python 3.10+, which matches `requires-python`.
## Checklist
- [x] PR has an informative and human-readable title (this will be pulled
into the release notes)
- [x] Changes are limited to a single goal (no scope creep)
- [x] Code passed the pre-commit check & code is left cleaner/nicer than
when first encountered.
- [x] Any _change_ in functionality is tested
- [x] New functions are documented (with a description, list of inputs, and
expected output)
- [x] Placeholder code is flagged / future TODOs are captured in comments
- [ ] Project documentation has been updated if adding/changing
functionality.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]