Repository navigation
fix(pipeline,aiocqhttp): close streaming/stage async generators and guard ResultStore.add - #11642
Conversation
…uard ResultStore.add
There was a problem hiding this comment.
Hey - I've found 5 issues
Sourcery assessment
Approval pending. 5 findings to address first.
Blocking findings: astrbot/core/platform/sources/aiocqhttp/aiocqhttp_platform_adapter.py:71, astrbot/core/pipeline/respond/stage.py:308, astrbot/core/pipeline/respond/stage.py:308, astrbot/core/pipeline/process_stage/method/agent_sub_stages/third_party.py:468, tests/unit/test_aiocqhttp_group_info.py:195
| if original_func is not None: | ||
| original_func(cls, result) | ||
| else: | ||
| original_add(result) |
There was a problem hiding this comment.
🟡 Medium · Malformed echoes still disconnect sessions
When a malformed OneBot frame is a dictionary with a non-dictionary echo value, original_add(result) receives dictionaries whose echo is not a dictionary; its nested echo access can raise AttributeError or TypeError, which this wrapper does not catch, so the exception can still escape the reverse WebSocket receive loop and disconnect the session.
Validate the echo structure before delegating and safely ignore malformed frames.
| await event.send_streaming(traced, realtime_segmenting) | ||
| finally: | ||
| streaming_response_event.reset(stream_token) | ||
| aclose = getattr(stream, "aclose", None) |
There was a problem hiding this comment.
🟡 Medium · Disconnected turns keep running
When stream delivery fails after the internal agent has yielded its streaming result, stream.aclose() closes the presentation iterator, but InternalAgentSubStage.process() has no GeneratorExit cleanup that stops its runtime-owned turn; because downstream failure closes that stage before it reaches turn.result(), the turn can continue consuming resources after delivery has failed.
Ensure closing the pipeline generator requests cancellation of its active turn, including on GeneratorExit.
| await event.send_streaming(traced, realtime_segmenting) | ||
| finally: | ||
| streaming_response_event.reset(stream_token) | ||
| aclose = getattr(stream, "aclose", None) |
There was a problem hiding this comment.
🟡 Medium · Upstream streams stay suspended
When a live stream backed by stream_speech() exits before consuming chains to completion, stream_speech() does not close chains when its generator closes: the no-TTS branch iterates it directly, and the TTS feeder is cancelled without explicitly closing it. The underlying agent-output generator remains suspended after delivery aborts, so its cleanup is deferred.
Explicitly close chains when stream_speech() exits, including when the TTS feeder is cancelled.
| mark_stream_consumed=mark_stream_consumed, | ||
| ): | ||
| yield | ||
| async with aclosing( |
There was a problem hiding this comment.
🟡 Medium · Unconsumed runner stream outlives stage
When downstream processing raises after the streaming result is set but before RespondStage consumes it, _handle_streaming_response() has already stored _stream_runner_chain() in the event result when it yields, but closing the handler does not close that separate stream. If downstream processing fails before RespondStage consumes it, the stream remains unstarted and the runner is left for the watchdog to close only after its timeout.
On early stage exit, close the event result's unconsumed async stream or otherwise close the runner immediately rather than relying on the watchdog timeout.
|
|
||
| # Duplicate echo after completion must not raise InvalidStateError. | ||
| ResultStore.add(duplicate_payload) | ||
| assert pending_future.result() == first_payload |
There was a problem hiding this comment.
🟡 Medium · Duplicate echo can remove fetch entry
When the duplicate-echo guard removes the completed future from _futures, test_aiocqhttp_result_store_guard_ignores_done_and_cancelled_futures checks only pending_future.result() at line 195, so it passes if handling the duplicate also removes its _futures entry; ResultStore.fetch() then raises KeyError during cleanup.
Assert that seq_done remains in ResultStore._futures after the duplicate echo.
Summary
Prevents reverse WebSocket disconnects in the
aiocqhttpOneBot v11 adapter from cancelled/duplicate API echoes and completes deterministic async-generator cleanup across the core message pipeline so mid-stream delivery errors never leave suspended generators, streaming runners, or background tasks unclosed:aiocqhttp.api_impl.ResultStore.addagainst finished futures (asyncio.InvalidStateError) so a late or duplicate OneBot API echo cannot crash the reverse WebSocket loop (/ws,/ws/api) and disconnect all active sessions.traced_stream()andresult.async_streamdeterministically inRespondStage.process()whenevent.send_streaming()raises or exits early mid-stream, and wrap the remaining unguardedasync forstage/handler async generators incontextlib.aclosing(...)(completing theaclosingcleanup introduced in#10077).Root Cause
aiocqhttpReverse WebSocket Crash (ResultStore.add→InvalidStateError):aiocqhttp/api_impl.py,ResultStore.add()looks upfuture = cls._futures.get(seq)and callsfuture.set_result(result)without checkingfuture.done().futuretransitions to cancelled/done beforeResultStore.fetch()resumes on the event loop to runfinally: del cls._futures[seq]. If the OneBot backend's echo arrives in that window — or if a duplicate echo arrives for the sameseq—future.set_result(result)raisesasyncio.InvalidStateError.CQHttp._handle_wsr_universal()norCQHttp._handle_wsr_api()catchesInvalidStateError, so the exception escapes the Quart WebSocket handler and tears down the entire/wsconnection, aborting all in-flight replies and streams._handle_wsr_api()forwardsjson.loads(...)directly toResultStore.add(), where a non-dictJSON frame raisesAttributeError.Remaining Unclosed Async Generators in Pipeline Delivery & Stages:
#10077addedcontextlib.aclosing(...)toPipelineScheduler._process_stages(),AgentRequestSubStage,StarRequestSubStage, and most loops inProcessStage, several async generators in the same execution chain were still left unclosed on early exit or mid-stream delivery errors:RespondStage.process()passedtraced_stream()toevent.send_streaming()without closing eithertraced_stream()or the underlyingresult.async_streaminfinally:. Ifsend_streaming()fails mid-stream (e.g., on WebSocket disconnect), third-party streaming runners (_stream_runner_chainaftermark_stream_consumed()cancels its watchdog) and live TTS streams (stream_speechbackgroundfeeder_task/tts_task) never run theirfinally:cleanup promptly.ProcessStage.process()iteratedself.star_request_sub_stage.process(event)withoutaclosing(...), andcall_handler()incontext_utils.pyiterated plugin async generators withoutaclosing(...), preventing deterministic unwinding of suspended plugin generators when downstream stages fail or stop propagation.InternalAgentSubStage(non-streamingchainsloop),ThirdPartyAgentSubStage(run_third_party_agent,_handle_streaming_response,_handle_non_streaming_response), andResultDecorateStage(content_safe_check_stage) also iterated async generators without explicit closing.Changes
Defensive
aiocqhttp.api_impl.ResultStore.addGuard (astrbot/core/platform/sources/aiocqhttp/aiocqhttp_platform_adapter.py)_patch_aiocqhttp_result_store()helper invoked duringAiocqhttpAdapter.__init__().dictpayloads safely, checkfuture.done()before delegating to the originalResultStore.add, catchasyncio.InvalidStateErrordefensively, and leavecls._futures[seq]removal toResultStore.fetch()'sfinally:block sofetch()never raisesKeyError.aiocqhttp.api_implis mocked or unavailable.Deterministic Stream & Stage Async-Generator Cleanup
astrbot/core/pipeline/respond/stage.py: wraptraced = traced_stream()inasync with aclosing(traced):and closeresult.async_stream(aclose()) infinally:after resettingstreaming_response_event.astrbot/core/pipeline/process_stage/stage.py: wrapself.star_request_sub_stage.process(event)inasync with aclosing(...).astrbot/core/pipeline/context_utils.py: wrap plugin async generatorready_to_callinasync with aclosing(ready_to_call):.astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py: wrap non-streamingchainsiteration inasync with aclosing(chains):.astrbot/core/pipeline/process_stage/method/agent_sub_stages/third_party.py: closerunner.step_until_done(...)infinally:ofrun_third_party_agent(), and wraprun_third_party_agent(),_handle_streaming_response(), and_handle_non_streaming_response()inasync with aclosing(...).astrbot/core/pipeline/result_decorate/stage.py: wrapself.content_safe_check_stage.process(...)inasync with aclosing(...).Tests (No New Standalone Test Files)
tests/unit/test_aiocqhttp_group_info.pyto verify thatAiocqhttpAdapterinstalls the idempotentResultStore.addguard, ignores echoes for cancelled/done futures without deleting entries owned byfetch(), ignores duplicate echoes and non-dictframes, and still resolves normal pending futures.tests/unit/test_event_execution.pyto verify thatRespondStage.process()closesresult.async_streamimmediately whenevent.send_streaming()fails mid-stream, and thatPipelineScheduler→ProcessStage→StarRequestSubStage→call_handlerunwinds suspended plugin async generators immediately on downstream failures.Files Changed
astrbot/core/platform/sources/aiocqhttp/aiocqhttp_platform_adapter.pyastrbot/core/pipeline/respond/stage.pyastrbot/core/pipeline/process_stage/stage.pyastrbot/core/pipeline/context_utils.pyastrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.pyastrbot/core/pipeline/process_stage/method/agent_sub_stages/third_party.pyastrbot/core/pipeline/result_decorate/stage.pytests/unit/test_aiocqhttp_group_info.pytests/unit/test_event_execution.pyVerification
python -m py_compileon all 9 modified files: passed.ruff checkon all 9 modified files: passed (All checks passed!).ruff format --checkon all 9 modified files: passed (9 files already formatted).git diff --check origin/master..HEAD: passed (0 issues).pytest -q tests/unit/test_event_execution.py tests/unit/test_aiocqhttp_group_info.py tests/unit/test_aiocqhttp_files.py tests/unit/test_aiocqhttp_poke.py tests/unit/test_aiocqhttp_reply.py tests/unit/test_aiocqhttp_buttons.py tests/unit/test_session_lock.py tests/unit/test_session_waiter_pipeline.py tests/unit/test_third_party_agent_sub_stage.py tests/unit/test_wakeup_pipeline.py tests/unit/test_message_tools.py tests/unit/test_astr_message_event.py tests/test_process_stage_images.py tests/test_preprocess_stage.py: 417 passed, 0 failed.建议合并顺序 (Recommended Merge Order)
astrbot/core/platform/sources/aiocqhttp/aiocqhttp_platform_adapter.pyonly in lines 30–106 (module helper +__init__), completely non-overlapping with#11611(fix/aiocqhttp-at-member-fallback, lines 347–405; clean merge verified viagit merge-tree --write-tree).#11609,#11610,#11612–#11617,perf/fail-fast-credential-500-and-fallback-cooldown).Summary by Sourcery
Keep aiocqhttp reverse WebSocket sessions resilient and ensure pipeline async generators are cleaned up on early exit.
Bug Fixes:
Enhancements:
Tests: