The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(feishu): stop the worker loop only on receive-loop exceptions; publish retrying/connected
teknium16d7b53a48aff
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex 26b6c4c8ded..42a2579f1e5 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -1045,42 +1045,34 @@ def _install_lark_ws_isolation(ws_client_module: Any) -> None:_dispatch_connect.__name__ = getattr(real_connect, "__name__", "connect")ws_client_module.websockets.connect = _dispatch_connect- client_cls = getattr(ws_client_module, "Client", None)- original_receive_loop = (- getattr(client_cls, "_receive_message_loop", None)- if client_cls is not None- else None- )- if original_receive_loop is not None:-- async def _receive_message_loop_exit_notify(self: Any) -> None:- try:- await original_receive_loop(self)- except Exception:- # The bare create_task above leaves this exception unretrieved;- # log the root cause here so it survives next to the supervisor's- # rebuild line instead of dying inside the SDK (#113662).- logger.exception(- "[Feishu] lark WS receive loop died; stopping the worker "- "loop so the supervisor can rebuild"- )- raise- finally:- # ``Client.start()`` parks in ``run_until_complete(_select())``, which only- # returns when this worker loop stops, and the receive loop runs as a bare- # ``create_task`` whose exception nobody retrieves. With the SDK's own- # reconnect ladder disabled, a dead receive loop would therefore leave a- # deaf-but-ESTABLISHED socket whose executor future never completes and the- # supervisor never rebuilds (#113662). Stopping the loop makes ``start()``- # raise, completing the future so ``_supervise_websocket_thread`` runs; the- # deliberate-disconnect paths are unaffected because they nil ``_ws_client``- # first and the supervisor exits without restarting.- try:- asyncio.get_running_loop().stop()- except RuntimeError: # pragma: no cover - no running loop- pass+ original_receive_loop = ws_client_module.Client._receive_message_loop++ async def _receive_message_loop_exit_notify(self: Any) -> None:+ # The SDK schedules this coroutine right after the websocket handshake succeeded, so its+ # entry is the only in-thread proof that a (re)built link is actually up.+ on_link_up = getattr(_ws_isolation_state, "on_link_up", None)+ if on_link_up is not None:+ on_link_up()+ try:+ await original_receive_loop(self)+ except Exception:+ # ``Client.start()`` parks in ``run_until_complete(_select())``, which only returns+ # when this worker loop stops, and the receive loop runs as a bare ``create_task``+ # whose exception nobody retrieves — so every unrecoverable exit (reconnect ladder+ # disabled, or its ``ClientException``/``ServerUnreachableException`` re-raise)+ # left a deaf-but-ESTABLISHED socket whose executor future never completed and the+ # supervisor never rebuilt (#113662). Log the root cause here and stop the loop so+ # ``start()`` raises, the future completes and ``_supervise_websocket_thread`` fires.+ # A *normal* return means the SDK's own ladder already reconnected (it scheduled a+ # fresh receive loop) and must NOT stop the loop. Deliberate disconnects nil+ # ``_ws_client`` first, so the supervisor exits without restarting.+ logger.exception(+ "[Feishu] lark WS receive loop died; stopping the worker "+ "loop so the supervisor can rebuild"+ )+ asyncio.get_running_loop().stop()- client_cls._receive_message_loop = _receive_message_loop_exit_notify+ ws_client_module.Client._receive_message_loop = _receive_message_loop_exit_notify_WS_ISOLATION_INSTALLED = True@@ -1107,9 +1099,19 @@ def _run_official_feishu_ws_client(ws_client: Any, adapter: Any) -> None:for key, value in (("ping_interval", adapter._ws_ping_interval), ("ping_timeout", adapter._ws_ping_timeout))if value is not None}+ adapter_loop = adapter._loop++ def _on_link_up() -> None:+ # Fired on the WS thread when the SDK scheduled a receive loop (handshake done); hop to the+ # adapter loop so the ``connected`` re-stamp after a supervisor rebuild runs where the adapter's+ # state lives.+ if adapter_loop is not None and not adapter_loop.is_closed():+ adapter_loop.call_soon_threadsafe(adapter._ws_link_up, ws_client)+_install_lark_ws_isolation(ws_client_module)_ws_isolation_state.loop = loop_ws_isolation_state.connect_kwargs = connect_overrides+ _ws_isolation_state.on_link_up = _on_link_updef _configure_with_overrides(conf: Any) -> Any:if original_configure is None:@@ -1128,6 +1130,7 @@ def _run_official_feishu_ws_client(ws_client: Any, adapter: Any) -> None:finally:_ws_isolation_state.loop = None_ws_isolation_state.connect_kwargs = None+ _ws_isolation_state.on_link_up = Noneif original_configure is not None:setattr(ws_client, "_configure", original_configure)pending = [t for t in asyncio.all_tasks(loop) if not t.done()]@@ -3750,6 +3753,11 @@ class FeishuAdapter(BasePlatformAdapter):if ws_future is not last_dead:logger.error("[Feishu] WebSocket client thread exited unexpectedly; restarting in %.0fs", backoff)last_dead = ws_future+ # Still running, link unproven: ``connected`` stays wrong until ``_ws_link_up`` re-stamps it.+ self._write_runtime_status_safe(+ "ws_link_lost", platform_state="retrying", error_code=None,+ error_message="Feishu websocket link lost; rebuilding",+ )await asyncio.sleep(backoff)if not self._running:return@@ -3760,6 +3768,11 @@ class FeishuAdapter(BasePlatformAdapter):logger.warning("[Feishu] WebSocket restart failed (retrying): %s", exc)backoff = min(backoff * 2, 60.0)+ def _ws_link_up(self, ws_client: Any) -> None:+ """WS thread reports its link is up (SDK receive loop scheduled); re-stamp ``connected`` after a rebuild."""+ if self._running and self._ws_client is ws_client:+ self._mark_connected()+async def _connect_websocket(self) -> None:if not FEISHU_WEBSOCKET_AVAILABLE:raise RuntimeError("websockets not installed; websocket mode unavailable")diff --git a/tests/gateway/test_feishu.py b/tests/gateway/test_feishu.pyindex 352cc256900..135b31d266b 100644--- a/tests/gateway/test_feishu.py+++ b/tests/gateway/test_feishu.py@@ -335,6 +335,7 @@ class TestAdapterModule(unittest.TestCase):fake_client = _FakeWSClient()fake_adapter = SimpleNamespace(+ _loop=None,_ws_thread_loop=None,_ws_reconnect_nonce=2,_ws_reconnect_interval=3,@@ -344,6 +345,7 @@ class TestAdapterModule(unittest.TestCase):fake_client_module = ModuleType("lark_oapi.ws.client")fake_client_module.loop = Nonefake_client_module.websockets = SimpleNamespace(connect=AsyncMock())+ fake_client_module.Client = type("Client", (), {"_receive_message_loop": lambda self: None})fake_ws_module = ModuleType("lark_oapi.ws")fake_ws_module.client = fake_client_modulefake_root_module = ModuleType("lark_oapi")diff --git a/tests/gateway/test_feishu_profile_scope_hops.py b/tests/gateway/test_feishu_profile_scope_hops.pyindex 057f1f3bef9..5991cd174bb 100644--- a/tests/gateway/test_feishu_profile_scope_hops.py+++ b/tests/gateway/test_feishu_profile_scope_hops.py@@ -90,6 +90,7 @@ def test_ws_client_thread_and_its_loop_callbacks_carry_the_adapter_profile_scopeclient_mod = types.ModuleType("lark_oapi.ws.client")client_mod.loop = SimpleNamespace(name="sdk-default-loop")client_mod.websockets = SimpleNamespace(connect=lambda *a, **k: None)+ client_mod.Client = type("Client", (), {"_receive_message_loop": lambda self: None})lark_ws = types.ModuleType("lark_oapi.ws")lark_ws.client = client_modlark = types.ModuleType("lark_oapi")diff --git a/tests/gateway/test_feishu_ws_multiplex_isolation.py b/tests/gateway/test_feishu_ws_multiplex_isolation.pyindex 2b8767375d2..302b98b1bcd 100644--- a/tests/gateway/test_feishu_ws_multiplex_isolation.py+++ b/tests/gateway/test_feishu_ws_multiplex_isolation.py@@ -27,6 +27,12 @@ def _inject_fake_lark_module(monkeypatch, connect=None):client_mod = types.ModuleType("lark_oapi.ws.client")client_mod.loop = SimpleNamespace(name="sdk-default-loop")client_mod.websockets = SimpleNamespace(connect=connect)++ class Client: # the SDK class whose receive loop the isolation shim wraps+ async def _receive_message_loop(self):+ await asyncio.sleep(3600)++ client_mod.Client = Clientlark.ws = lark_wslark_ws.client = client_modmonkeypatch.setitem(sys.modules, "lark_oapi", lark)@@ -38,6 +44,7 @@ def _inject_fake_lark_module(monkeypatch, connect=None):def _adapter_stub(**overrides):stub = SimpleNamespace(+ _loop=None,_ws_thread_loop=None,_ws_reconnect_nonce=None,_ws_reconnect_interval=None,@@ -108,8 +115,8 @@ def test_dead_receive_loop_unparks_start_and_exits_the_thread(monkeypatch, caploself._auto_reconnect = Falseasync def _receive_message_loop(self):- # Mirror lark_oapi 1.6.8: bare raise (no reconnect) out of an- # unawaited create_task when Hermes disables _auto_reconnect.+ # Mirror lark_oapi 1.6.8: bare raise out of an unawaited create_task+ # (reconnect ladder disabled, or its ClientException re-raise).await asyncio.sleep(0.01)raise ConnectionError("simulated half-open peer")@@ -145,17 +152,19 @@ def test_dead_receive_loop_unparks_start_and_exits_the_thread(monkeypatch, caploassert "simulated half-open peer" in caplog.text-def test_live_receive_loop_keeps_start_parked(monkeypatch):- """The exit-notify wrap must only fire when the receive loop actually- dies — a healthy socket keeps start() parked (no false-positive stop)."""+def test_receive_loop_normal_return_keeps_start_parked(monkeypatch):+ """The exit-notify wrap must only fire on an exception. When the SDK's own+ reconnect ladder succeeds, the old receive loop *returns* (a fresh one was+ scheduled by ``_connect``) — stopping the loop there would tear down the+ healthy rebuilt link on every transient blip."""client_mod = _inject_fake_lark_module(monkeypatch)- parked = threading.Event()+ returned = threading.Event()loop_holder = {}class FakeSDKClient:async def _receive_message_loop(self):- parked.set()- await asyncio.sleep(3600)+ await asyncio.sleep(0.01)+ returned.set() # ladder reconnected: coroutine returns normallydef start(self):loop = client_mod.loop@@ -178,12 +187,11 @@ def test_live_receive_loop_keeps_start_parked(monkeypatch):thread = threading.Thread(target=run, daemon=True)thread.start()- assert parked.wait(timeout=10)+ assert returned.wait(timeout=10)thread.join(timeout=0.5)- assert thread.is_alive() # healthy link: start() stays parked- # Clean teardown for the test process: wake the parked selector and stop- # the worker loop from this (foreign) thread, then let the thread's own- # finally block close it out.+ assert thread.is_alive() # start() stays parked on the rebuilt link+ # Clean teardown for the test process: stop the worker loop from this+ # (foreign) thread, then let the thread's own finally block close it out.loop_holder["loop"].call_soon_threadsafe(loop_holder["loop"].stop)thread.join(timeout=10)assert not thread.is_alive()@@ -197,7 +205,9 @@ def _supervisor_stub():_ws_restart_backoff=0.01,connect_calls=0,connect_should_fail=0,+ status_writes=[],)+ stub._write_runtime_status_safe = lambda context, **kw: stub.status_writes.append(kw["platform_state"])async def _connect_websocket():stub.connect_calls += 1@@ -236,9 +246,12 @@ def test_supervisor_restarts_a_dead_ws_thread_with_backoff():await taskexcept asyncio.CancelledError:pass- return stub.connect_calls+ return stub- assert asyncio.run(scenario()) == 2 # failed restart, then a successful one+ stub = asyncio.run(scenario())+ assert stub.connect_calls == 2 # failed restart, then a successful one+ # The lost link is published as ``retrying`` (``connected`` is re-stamped by ``_ws_link_up``).+ assert stub.status_writes[0] == "retrying"def test_supervisor_stops_when_disconnect_nils_the_client():