Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(channel): guard channel event subscriber tasks

程凯2679c9a4e3f9
diff --git a/jiuwenswarm/gateway/channel_manager/channel_manager.py b/jiuwenswarm/gateway/channel_manager/channel_manager.py
index 7568084174..80d1526da5 100644
--- a/jiuwenswarm/gateway/channel_manager/channel_manager.py
+++ b/jiuwenswarm/gateway/channel_manager/channel_manager.py
@@ -68,6 +68,9 @@ class ChannelManager(ABC):
self._dispatch_diag_count: int = 0
# Channel 连接事件订阅回调列表
self._channel_event_callbacks: list[Callable[[ChannelEvent], Awaitable[None]]] = []
+ # 分发 task 强引用集合:事件循环仅持 task 弱引用,不持强引用可能被
+ # GC 中途回收导致事件丢失(对齐 router_client._background_tasks 做法)。
+ self._channel_event_tasks: set[asyncio.Task] = set()
@staticmethod
def _resolve_app_id(channel: Any) -> str:
@@ -177,7 +180,26 @@ class ChannelManager(ABC):
user_id=user_id,
)
for cb in self._channel_event_callbacks:
- asyncio.create_task(cb(event))
+ task = asyncio.create_task(self._notify_channel_event(cb, event))
+ self._channel_event_tasks.add(task)
+ task.add_done_callback(self._channel_event_tasks.discard)
+
+ async def _notify_channel_event(
+ self,
+ cb: Callable[[ChannelEvent], Awaitable[None]],
+ event: ChannelEvent,
+ ) -> None:
+ """分发单个事件给订阅回调;异常兜底记日志,不静默丢失。"""
+ try:
+ await cb(event)
+ except Exception:
+ logger.exception(
+ "[ChannelManager] channel event callback error: "
+ "event_type=%s channel_type=%s user_id=%s",
+ event.event_type,
+ event.channel_type,
+ event.user_id,
+ )
def _try_set_event_reporter(self, channel: Any) -> None:
"""若 channel 支持 set_channel_event_reporter,则注入上报回调。"""
diff --git a/tests/unit_tests/gateway/test_channel_manager_events.py b/tests/unit_tests/gateway/test_channel_manager_events.py
new file mode 100644
index 0000000000..eca8352249
--- /dev/null
+++ b/tests/unit_tests/gateway/test_channel_manager_events.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+from jiuwenswarm.gateway.channel_manager.channel_manager import ChannelEvent, ChannelManager
+
+
+class _DummyMessageHandler:
+ async def handle_message(self, msg: Any) -> None: # pragma: no cover
+ raise AssertionError("not used in this test")
+
+
+class _RecordingSubscriber:
+ def __init__(self, fail_first: bool = False) -> None:
+ self.events: list[ChannelEvent] = []
+ self._fail_first = fail_first
+
+ async def __call__(self, event: ChannelEvent) -> None:
+ self.events.append(event)
+ if self._fail_first and len(self.events) == 1:
+ raise RuntimeError("boom")
+
+
+async def _drain(cm: ChannelManager) -> None:
+ await asyncio.gather(*cm._channel_event_tasks)
+ await asyncio.sleep(0)
+
+
+async def test_report_channel_event_dispatches_to_subscribers() -> None:
+ cm = ChannelManager(_DummyMessageHandler())
+ sub = _RecordingSubscriber()
+ cm.subscribe_channel_events(sub)
+
+ cm.report_channel_event("connected", "tui", "u1")
+ await _drain(cm)
+
+ assert [(e.event_type, e.channel_type, e.user_id) for e in sub.events] == [
+ ("connected", "tui", "u1")
+ ]
+ assert not cm._channel_event_tasks # 完成后引用已清理
+
+
+async def test_report_channel_event_swallows_callback_error() -> None:
+ cm = ChannelManager(_DummyMessageHandler())
+ sub = _RecordingSubscriber(fail_first=True)
+ cm.subscribe_channel_events(sub)
+
+ cm.report_channel_event("connected", "tui", "u1")
+ await _drain(cm)
+ cm.report_channel_event("disconnected", "tui", "u1")
+ await _drain(cm)
+
+ # 回调异常被兜底记录,不影响订阅与后续事件分发
+ assert [e.event_type for e in sub.events] == ["connected", "disconnected"]