Async generator entrypoint keeps running after the client disconnects (follow-up to #482)

Đang mở Phù hợp với người mới
#752 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức phù hợp với người mới
72/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
python
Lĩnh vực
backend

Hướng nghiên cứu

Bắt đầu trong module ứng dụng runtime nơi entrypoint rẽ nhánh tới StreamingResponse(self._sync_stream_with_error_handling(result), media_type="text/event-stream"), và đọc _async_gen_to_sync_gen cùng finally của nó để xem vì sao nó không bao giờ chạy. Tái hiện với async generator 12 bước và client đang ngắt kết nối được đưa ra ở đây, sau đó bọc sync stream trong một async iterator đóng cả stream lẫn source generator trong finally. Thêm test_handler_is_closed_after_disconnect vào tests/integration/runtime/test_streaming_disconnect_integration.py và chạy nó cùng với test_app.py; xong nghĩa là handler ghi log CancelledError quanh lần yield tiếp theo sau khi ngắt kết nối thay vì chạy đến khi hoàn tất.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

bug high-severity

Describe the bug

When an async def generator entrypoint is streamed and the client disconnects, the handler is never closed. It keeps running to the end, and if more than 100 events remain, the producer task stays parked in _offer() forever (polling every 10 ms) for the life of the process.

#563 added cleanup for this in the finally of _async_gen_to_sync_gen (stop.set() + task.cancel()), but that finally never runs. Starlette's iterate_in_threadpool never calls close() on the sync generator it iterates, so no GeneratorExit reaches it. The unit test for #563 calls sync_gen.close() by hand (test_app.py, _abandon_after), and the integration test only checks that /ping and a fresh session still work, so this was not caught.

To Reproduce

bedrock-agentcore 1.27.0 (main @ 8467c9a), starlette 1.10.0, uvicorn 0.54.0, Python 3.12, macOS.

# server.py
import asyncio, time
from bedrock_agentcore.runtime import BedrockAgentCoreApp

app = BedrockAgentCoreApp()

@app.entrypoint
async def invoke(payload):
    try:
        for i in range(12):
            await asyncio.sleep(1)
            print(f"{time.time():.1f} step {i + 1}/12", flush=True)
            yield {"step": i + 1}
        print("finished all steps", flush=True)
    except BaseException as e:
        print(f"{time.time():.1f} closed: {type(e).__name__}", flush=True)
        raise

app.run(port=8080)
# client.py: read for 3 seconds, then disconnect
import time, httpx
start = time.time()
with httpx.Client(timeout=30) as c, c.stream("POST", "http://127.0.0.1:8080/invocations", json={}) as r:
    for _ in r.iter_raw():
        if time.time() - start >= 3:
            break
print(f"{time.time():.1f} client disconnected")

The client disconnects after step 3. The server prints steps 4 to 12 and then finished all steps.

With range(500) and asyncio.sleep(0.01), the server stops around step 103/500 and never prints anything again. That is 100 queued events plus a few in flight, with the producer parked in _offer().

Expected behavior

The handler is closed shortly after the disconnect, as the _async_gen_to_sync_gen docstring describes.

Possible fix

Iterate the sync generator ourselves and close it in finally:

-                return StreamingResponse(self._sync_stream_with_error_handling(result), media_type="text/event-stream")
+                return StreamingResponse(self._iterate_sync_stream(result), media_type="text/event-stream")
...
+    async def _iterate_sync_stream(self, generator):
+        stream = self._sync_stream_with_error_handling(generator)
+        try:
+            async for chunk in iterate_in_threadpool(stream):
+                yield chunk
+        finally:
+            stream.close()
+            generator.close()

With this change, the repro above logs closed: CancelledError at step 4, and the 500-step case stops at step 2. I added an integration test, test_handler_is_closed_after_disconnect, to test_streaming_disconnect_integration.py. It fails on main and passes with the change (5/5 runs). test_app.py passes (148).

Integration test (added to tests/integration/runtime/test_streaming_disconnect_integration.py)

The live_server handler records how it exits ("completed" or "closed") per sessionId in a module-level _handler_exits dict, cleared by the fixture.

def test_handler_is_closed_after_disconnect(live_server):
    """A mid-stream client disconnect closes the handler instead of leaving its producer parked."""
    base = live_server

    with httpx.Client(timeout=30.0) as c:
        with c.stream("POST", f"{base}/invocations", json={"sessionId": "A", "chunks": 5000}) as r:
            for i, _ in enumerate(r.iter_lines()):
                if i >= 3:
                    break

    deadline = time.time() + 5
    while "A" not in _handler_exits and time.time() < deadline:
        time.sleep(0.1)
    assert _handler_exits.get("A") == "closed"

Notes

  • Cleanup can be delayed. uvicorn reports ASGI spec 2.3, so Starlette cancels the response through a task group. That cancel waits for the in-flight next() in the thread pool, so cleanup happens when the handler yields its next event. A handler parked in a long call is closed only after that call returns.
  • Sync generator handlers change too. They go through the same path, so they also get closed on disconnect now.
  • Scope. I only checked this locally with uvicorn, not on AgentCore Runtime.
Ngôn ngữ chính
Python
Star
786
Fork
163
Merge trung bình
4 giờ
Pull request đã merge (30 ngày)
22

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của aws/bedrock-agentcore-sdk-python

Tất cả issue của aws/bedrock-agentcore-sdk-python

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.