Async generator entrypoint keeps running after the client disconnects (follow-up to #482)
維護者通常 1 天內回覆
還沒有人認領這個 Issue。
評估
研究方向
從 runtime 應用模組中 entrypoint 分支到 StreamingResponse(self._sync_stream_with_error_handling(result), media_type="text/event-stream") 的地方開始,閱讀 _async_gen_to_sync_gen 及其 finally,了解它為何從不執行。用這裡提供的 12-step async generator 和正在中斷連線的用戶端來重現,然後把 sync stream 包進一個 async iterator,讓它在 finally 中同時關閉 stream 和 source generator。將 test_handler_is_closed_after_disconnect 加到 tests/integration/runtime/test_streaming_disconnect_integration.py,並將它與 test_app.py 一起執行;完成的意思是 handler 在中斷連線後的下一次 yield 周圍記錄 CancelledError,而不是一路執行到完成。
由索引模型根據 Issue 內容生成。
描述
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.
- 主要語言
- Python
- 星號
- 786
- 分支
- 163
- 平均合併
- 4 小時
- 30 天內合併 PR
- 22
環境準備
- 沒有 Dockerfile 或 Docker Compose 檔案
- 沒有 Pull Request 範本
- 閱讀貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
aws/bedrock-agentcore-sdk-python 的其他 Issue
-
bug
難度 2/5 1-3 小時 新手友好度 82/100
aws/bedrock-agentcore-sdk-python#751 · 1 個 reaction ·
維護者通常 1 天內回覆
-
delete_all_long_term_memories_in_namespace deletes only the first 10 records可能已有人在做 @Fire162 於 18 天前認領。 未關閉bug high-severity
難度 2/5 1-3 小時 新手友好度 75/100
aws/bedrock-agentcore-sdk-python#727 ·
維護者通常 1 天內回覆
-
MPP: credential is always sent in Authorization, ignoring header="Payment-Authorization" in the challenge可能已有人在做 @abhiramshaji-cyber 於 24 天前認領。 未關閉bug
難度 2/5 1-3 小時 新手友好度 68/100
aws/bedrock-agentcore-sdk-python#702 ·
維護者通常 1 天內回覆
-
[Bug] update_message fails with parameter validation error when SessionMessage.message_id is a Strands positional integer index可能已有人在做 @citizen204 於 144 天前認領。 未關閉
難度 2/5 1-3 小時 新手友好度 68/100
aws/bedrock-agentcore-sdk-python#556 ·
維護者通常 1 天內回覆
-
CodeInterpreter should not require a region argument可能已有人在做 @citizen204 於 159 天前認領。 未關閉
難度 2/5 1-3 小時 新手友好度 68/100
aws/bedrock-agentcore-sdk-python#511 ·
維護者通常 1 天內回覆
查看 aws/bedrock-agentcore-sdk-python 的全部 Issue
相似的 Issue
-
難度 1/5 1 小時以內 新手友好度 88/100
snap-stanford/Biomni#380 ·
-
難度 2/5 1-3 小時 新手友好度 74/100
microsoft/playwright-python#3361 ·
維護者通常 1 天內回覆
-
documentation priority: low size: S status: needs triage
難度 2/5 1-3 小時 新手友好度 74/100
cubrid-lab/sqlalchemy-cubrid#1397 ·
維護者通常 1 天內回覆
-
documentation priority: low size: S status: needs triage
難度 2/5 1-3 小時 新手友好度 72/100
cubrid-lab/pycubrid#1307 ·
維護者通常 1 天內回覆
-
[Bug]: Installer hides SSL certificate errors as bare URLError, and the suggested fix can't work未關閉bug
難度 2/5 1-3 小時 新手友好度 80/100
ShaftHQ/chaosengine-harness#143 ·
維護者通常 1 天內回覆