Skip to content

fix(pipeline,aiocqhttp): close streaming/stage async generators and guard ResultStore.add - #11642

Open
JosephTian876 wants to merge 1 commit into
AstrBotDevs:masterfrom
JosephTian876:fix/pipeline-scheduler-aclosing-and-aiocqhttp-ws-guard
Open

JosephTian876 wants to merge 1 commit into
AstrBotDevs:masterfrom
JosephTian876:fix/pipeline-scheduler-aclosing-and-aiocqhttp-ws-guard

Conversation

@JosephTian876

@JosephTian876 JosephTian876 commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Prevents reverse WebSocket disconnects in the aiocqhttp OneBot 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:

  1. Guard aiocqhttp.api_impl.ResultStore.add against 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.
  2. Close traced_stream() and result.async_stream deterministically in RespondStage.process() when event.send_streaming() raises or exits early mid-stream, and wrap the remaining unguarded async for stage/handler async generators in contextlib.aclosing(...) (completing the aclosing cleanup introduced in #10077).

Root Cause

  1. aiocqhttp Reverse WebSocket Crash (ResultStore.add → InvalidStateError):

    • In aiocqhttp/api_impl.py, ResultStore.add() looks up future = cls._futures.get(seq) and calls future.set_result(result) without checking future.done().
    • When an OneBot API call times out or its awaiting task is cancelled, future transitions to cancelled/done before ResultStore.fetch() resumes on the event loop to run finally: del cls._futures[seq]. If the OneBot backend's echo arrives in that window — or if a duplicate echo arrives for the same seq — future.set_result(result) raises asyncio.InvalidStateError.
    • Neither CQHttp._handle_wsr_universal() nor CQHttp._handle_wsr_api() catches InvalidStateError, so the exception escapes the Quart WebSocket handler and tears down the entire /ws connection, aborting all in-flight replies and streams.
    • Additionally, _handle_wsr_api() forwards json.loads(...) directly to ResultStore.add(), where a non-dict JSON frame raises AttributeError.
  2. Remaining Unclosed Async Generators in Pipeline Delivery & Stages:

    • While #10077 added contextlib.aclosing(...) to PipelineScheduler._process_stages(), AgentRequestSubStage, StarRequestSubStage, and most loops in ProcessStage, several async generators in the same execution chain were still left unclosed on early exit or mid-stream delivery errors:
      • RespondStage.process() passed traced_stream() to event.send_streaming() without closing either traced_stream() or the underlying result.async_stream in finally:. If send_streaming() fails mid-stream (e.g., on WebSocket disconnect), third-party streaming runners (_stream_runner_chain after mark_stream_consumed() cancels its watchdog) and live TTS streams (stream_speech background feeder_task / tts_task) never run their finally: cleanup promptly.
      • ProcessStage.process() iterated self.star_request_sub_stage.process(event) without aclosing(...), and call_handler() in context_utils.py iterated plugin async generators without aclosing(...), preventing deterministic unwinding of suspended plugin generators when downstream stages fail or stop propagation.
      • InternalAgentSubStage (non-streaming chains loop), ThirdPartyAgentSubStage (run_third_party_agent, _handle_streaming_response, _handle_non_streaming_response), and ResultDecorateStage (content_safe_check_stage) also iterated async generators without explicit closing.

Changes

  1. Defensive aiocqhttp.api_impl.ResultStore.add Guard (astrbot/core/platform/sources/aiocqhttp/aiocqhttp_platform_adapter.py)

    • Add an idempotent _patch_aiocqhttp_result_store() helper invoked during AiocqhttpAdapter.__init__().
    • Ignore non-dict payloads safely, check future.done() before delegating to the original ResultStore.add, catch asyncio.InvalidStateError defensively, and leave cls._futures[seq] removal to ResultStore.fetch()'s finally: block so fetch() never raises KeyError.
    • Preserves normal behavior for all pending futures and remains a safe no-op if aiocqhttp.api_impl is mocked or unavailable.
  2. Deterministic Stream & Stage Async-Generator Cleanup

    • astrbot/core/pipeline/respond/stage.py: wrap traced = traced_stream() in async with aclosing(traced): and close result.async_stream (aclose()) in finally: after resetting streaming_response_event.
    • astrbot/core/pipeline/process_stage/stage.py: wrap self.star_request_sub_stage.process(event) in async with aclosing(...).
    • astrbot/core/pipeline/context_utils.py: wrap plugin async generator ready_to_call in async with aclosing(ready_to_call):.
    • astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py: wrap non-streaming chains iteration in async with aclosing(chains):.
    • astrbot/core/pipeline/process_stage/method/agent_sub_stages/third_party.py: close runner.step_until_done(...) in finally: of run_third_party_agent(), and wrap run_third_party_agent(), _handle_streaming_response(), and _handle_non_streaming_response() in async with aclosing(...).
    • astrbot/core/pipeline/result_decorate/stage.py: wrap self.content_safe_check_stage.process(...) in async with aclosing(...).
  3. Tests (No New Standalone Test Files)

    • Extended tests/unit/test_aiocqhttp_group_info.py to verify that AiocqhttpAdapter installs the idempotent ResultStore.add guard, ignores echoes for cancelled/done futures without deleting entries owned by fetch(), ignores duplicate echoes and non-dict frames, and still resolves normal pending futures.
    • Extended tests/unit/test_event_execution.py to verify that RespondStage.process() closes result.async_stream immediately when event.send_streaming() fails mid-stream, and that PipelineScheduler → ProcessStage → StarRequestSubStage → call_handler unwinds suspended plugin async generators immediately on downstream failures.

Files Changed

  • astrbot/core/platform/sources/aiocqhttp/aiocqhttp_platform_adapter.py
  • astrbot/core/pipeline/respond/stage.py
  • astrbot/core/pipeline/process_stage/stage.py
  • astrbot/core/pipeline/context_utils.py
  • astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py
  • astrbot/core/pipeline/process_stage/method/agent_sub_stages/third_party.py
  • astrbot/core/pipeline/result_decorate/stage.py
  • tests/unit/test_aiocqhttp_group_info.py
  • tests/unit/test_event_execution.py

Verification

  • python -m py_compile on all 9 modified files: passed.
  • ruff check on all 9 modified files: passed (All checks passed!).
  • ruff format --check on 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)

  • Independent fix; can be merged in any order:
    • Touches astrbot/core/platform/sources/aiocqhttp/aiocqhttp_platform_adapter.py only in lines 30–106 (module helper + __init__), completely non-overlapping with #11611 (fix/aiocqhttp-at-member-fallback, lines 347–405; clean merge verified via git merge-tree --write-tree).
    • Zero file overlap with all other sibling PRs (#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:

  • Prevent late or duplicate OneBot API echoes, including non-object payloads, from disrupting aiocqhttp reverse WebSocket handling.

Enhancements:

  • Close streaming results, plugin handlers, and pipeline stage async generators deterministically when processing or delivery exits early.

Tests:

  • Add coverage for safe handling of completed API futures and async-generator cleanup after streaming or downstream failures.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

if original_func is not None:
original_func(cls, result)
else:
original_add(result)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant