The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): close leaked poller sockets in weixin/email adapters (#79889)
Teknium480342232a1d
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.pyindex 68a0e0a9e1b..3455c99f5e4 100644--- a/gateway/platforms/weixin.py+++ b/gateway/platforms/weixin.py@@ -1427,6 +1427,36 @@ class WeixinAdapter(BasePlatformAdapter):await asyncio.sleep(BACKOFF_DELAY_SECONDS if consecutive_failures >= MAX_CONSECUTIVE_FAILURES else RETRY_DELAY_SECONDS)if consecutive_failures >= MAX_CONSECUTIVE_FAILURES:consecutive_failures = 0+ # Recycle the poll session after a full failure streak.+ # Failed connection attempts through a local HTTP proxy+ # (e.g. Clash on 127.0.0.1:7890) can strand sockets that+ # never return to the connector's keepalive pool, so the+ # tight keepalive_timeout never reaps them. On macOS the+ # default 256-fd soft limit turns that drip into+ # `[Errno 24] Too many open files` and a gateway crash+ # (#79889). Closing the session tears down its connector+ # and every socket it holds; a fresh session starts the+ # next attempt from zero fds.+ await self._recycle_poll_session()++ async def _recycle_poll_session(self) -> None:+ """Replace ``_poll_session`` with a fresh one, closing the old.++ Swap-then-close so concurrent ``_process_message`` tasks that grab+ ``self._poll_session`` never observe a closed session; in-flight+ requests on the old session finish or fail independently.+ """+ if not self._running or aiohttp is None:+ return+ old = self._poll_session+ self._poll_session = aiohttp.ClientSession(+ trust_env=True, connector=_make_ssl_connector()+ )+ if old is not None and not old.closed:+ try:+ await old.close()+ except Exception as exc:+ logger.debug("[%s] old poll session close failed: %s", self.name, exc)async def _process_message_safe(self, message: Dict[str, Any]) -> None:try:diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.pyindex 317eae72e8e..704524e4efc 100644--- a/plugins/platforms/email/adapter.py+++ b/plugins/platforms/email/adapter.py@@ -112,6 +112,28 @@ MAX_MESSAGE_LENGTH = 50_000SMTP_CONNECT_TIMEOUT = 30+def _close_imap(imap: "imaplib.IMAP4") -> None:+ """Best-effort teardown that guarantees the underlying socket is closed.++ ``IMAP4.logout()`` only guards against ``OSError`` internally: a broken+ connection makes ``_simple_command('LOGOUT')`` raise ``IMAP4.abort``+ (which is *not* an ``OSError``), so ``logout()`` propagates before its+ own ``shutdown()`` call and the TCP socket stays open. On macOS, where+ the default soft fd limit is 256 and pollers may run through a local+ proxy, these abandoned sockets accumulate one per failed poll until the+ gateway hits ``[Errno 24] Too many open files`` (#79889). Always chase a+ failed ``logout()`` with ``shutdown()``, which closes the socket+ unconditionally.+ """+ try:+ imap.logout()+ except Exception:+ try:+ imap.shutdown()+ except Exception:+ pass++def _create_ipv4_connection(host: str,port: int,@@ -680,37 +702,46 @@ class EmailAdapter(BasePlatformAdapter):return Falsetry:- # Test IMAP connection- imap = imaplib.IMAP4_SSL(self._imap_host, self._imap_port, timeout=30)- imap.login(self._address, self._password)- _send_imap_id(imap)- imap.select("INBOX")- snapshot = self._seen_uids_snapshot.get(self._address)- if is_reconnect and snapshot is not None:- # Reconnect within the same process: restore the previous- # adapter's seen-UID baseline instead of re-marking the whole- # mailbox. Mail that arrived during the outage stays UNSEEN- # relative to the baseline and is dispatched by the next poll- # instead of being silently skipped.- self._seen_uids = set(snapshot)- self._trim_seen_uids()- imap.logout()- logger.info(- "[Email] IMAP reconnect test passed. Restored %d seen UIDs; "- "messages received during the outage will be processed.",- len(self._seen_uids),- )- else:- # First connect (or no snapshot): mark all existing messages as- # seen so we only process new ones.- status, data = imap.uid("search", None, "ALL")- if status == "OK" and data and data[0]:- for uid in data[0].split():- self._seen_uids.add(uid)- # Keep only the most recent UIDs to prevent unbounded growth- self._trim_seen_uids()- imap.logout()- logger.info("[Email] IMAP connection test passed. %d existing messages skipped.", len(self._seen_uids))+ # Test IMAP connection. The handle is closed in ``finally`` —+ # before this, a failure in login/select/search left the TCP+ # socket open with no owner, leaking one fd per connect attempt.+ # Under the gateway's reconnect watcher (fresh adapter instance+ # per retry) against an unreachable/proxied host this grew+ # monotonically until fd exhaustion on macOS's 256 soft limit+ # (#79889).+ imap = None+ try:+ imap = imaplib.IMAP4_SSL(self._imap_host, self._imap_port, timeout=30)+ imap.login(self._address, self._password)+ _send_imap_id(imap)+ imap.select("INBOX")+ snapshot = self._seen_uids_snapshot.get(self._address)+ if is_reconnect and snapshot is not None:+ # Reconnect within the same process: restore the previous+ # adapter's seen-UID baseline instead of re-marking the whole+ # mailbox. Mail that arrived during the outage stays UNSEEN+ # relative to the baseline and is dispatched by the next poll+ # instead of being silently skipped.+ self._seen_uids = set(snapshot)+ self._trim_seen_uids()+ logger.info(+ "[Email] IMAP reconnect test passed. Restored %d seen UIDs; "+ "messages received during the outage will be processed.",+ len(self._seen_uids),+ )+ else:+ # First connect (or no snapshot): mark all existing messages as+ # seen so we only process new ones.+ status, data = imap.uid("search", None, "ALL")+ if status == "OK" and data and data[0]:+ for uid in data[0].split():+ self._seen_uids.add(uid)+ # Keep only the most recent UIDs to prevent unbounded growth+ self._trim_seen_uids()+ logger.info("[Email] IMAP connection test passed. %d existing messages skipped.", len(self._seen_uids))+ finally:+ if imap is not None:+ _close_imap(imap)self._seen_uids_snapshot[self._address] = set(self._seen_uids)except Exception as e:logger.error("[Email] IMAP connection failed: %s", e)@@ -820,6 +851,7 @@ class EmailAdapter(BasePlatformAdapter):def _fetch_new_messages(self) -> List[Dict[str, Any]]:"""Fetch new (unseen) messages from IMAP. Runs in executor thread."""results = []+ imap: Optional[imaplib.IMAP4] = Nonetry:imap = imaplib.IMAP4_SSL(self._imap_host, self._imap_port, timeout=30)try:@@ -884,10 +916,9 @@ class EmailAdapter(BasePlatformAdapter):if parsed is not None:results.append(parsed)finally:- try:- imap.logout()- except Exception:- pass+ # _close_imap guarantees the socket dies even when logout()+ # raises IMAP4.abort on a broken connection (#79889).+ _close_imap(imap)except Exception as e:logger.error("[Email] IMAP fetch error: %s", e)self._last_fetch_failed = Truediff --git a/tests/gateway/test_poller_fd_lifecycle.py b/tests/gateway/test_poller_fd_lifecycle.pynew file mode 100644index 00000000000..2cc4353f458--- /dev/null+++ b/tests/gateway/test_poller_fd_lifecycle.py@@ -0,0 +1,197 @@+"""Poller socket lifecycle — proxied fd-leak regressions (#79889).++On macOS (256 soft fd limit) a gateway routing weixin/email pollers through+a local HTTP proxy leaked one TCP socket per failed poll/connect cycle until+``[Errno 24] Too many open files`` crashed the gateway. Two code-side gaps:++1. email: ``imaplib.IMAP4.logout()`` only swallows ``OSError``; on a broken+ connection ``LOGOUT`` raises ``IMAP4.abort`` *before* the internal+ ``shutdown()``, so the socket stayed open. And ``connect()`` had no+ try/finally at all — a login/select failure abandoned the connected+ socket entirely.+2. weixin: repeated poll failures through a proxy strand sockets in the+ aiohttp connector; the poll session was never recycled, so they+ accumulated for the life of the process.+"""++import asyncio+import imaplib+import os+import unittest+from unittest.mock import MagicMock, patch+++def _make_email_adapter(address="[email protected]"):+ from gateway.config import PlatformConfig++ with patch.dict(os.environ, {+ "EMAIL_ADDRESS": address,+ "EMAIL_PASSWORD": "secret",+ "EMAIL_IMAP_HOST": "imap.test.com",+ "EMAIL_SMTP_HOST": "smtp.test.com",+ }):+ from plugins.platforms.email.adapter import EmailAdapter++ return EmailAdapter(PlatformConfig(enabled=True))+++class TestCloseImap(unittest.TestCase):+ """_close_imap must guarantee socket teardown."""++ def test_logout_success_no_shutdown_needed(self):+ from plugins.platforms.email.adapter import _close_imap++ imap = MagicMock()+ _close_imap(imap)+ imap.logout.assert_called_once()+ imap.shutdown.assert_not_called()++ def test_logout_abort_falls_back_to_shutdown(self):+ from plugins.platforms.email.adapter import _close_imap++ imap = MagicMock()+ imap.logout.side_effect = imaplib.IMAP4.abort("socket error: EOF")+ _close_imap(imap)+ imap.shutdown.assert_called_once()++ def test_shutdown_failure_is_swallowed(self):+ from plugins.platforms.email.adapter import _close_imap++ imap = MagicMock()+ imap.logout.side_effect = imaplib.IMAP4.abort("broken")+ imap.shutdown.side_effect = OSError("already closed")+ _close_imap(imap) # must not raise+++class TestEmailConnectClosesSocket(unittest.TestCase):+ """connect() must close the IMAP socket on every path, incl. failures."""++ def test_login_failure_still_closes_socket(self):+ adapter = _make_email_adapter()+ mock_imap = MagicMock()+ mock_imap.login.side_effect = imaplib.IMAP4.error("AUTHENTICATIONFAILED")++ with patch("imaplib.IMAP4_SSL", return_value=mock_imap):+ result = asyncio.run(adapter.connect())++ self.assertFalse(result)+ # The failed handle must have been torn down (logout attempted;+ # abort fallback covered by TestCloseImap).+ mock_imap.logout.assert_called_once()++ def test_select_failure_still_closes_socket(self):+ adapter = _make_email_adapter()+ mock_imap = MagicMock()+ mock_imap.select.side_effect = imaplib.IMAP4.abort("connection lost")++ with patch("imaplib.IMAP4_SSL", return_value=mock_imap):+ result = asyncio.run(adapter.connect())++ self.assertFalse(result)+ mock_imap.logout.assert_called_once()+++class TestFetchClosesSocketOnBrokenLogout(unittest.TestCase):+ def test_fetch_logout_abort_falls_back_to_shutdown(self):+ adapter = _make_email_adapter()+ mock_imap = MagicMock()+ mock_imap.uid.return_value = ("OK", [b""])+ mock_imap.logout.side_effect = imaplib.IMAP4.abort("EOF")++ with patch("imaplib.IMAP4_SSL", return_value=mock_imap):+ results = adapter._fetch_new_messages()++ self.assertEqual(results, [])+ mock_imap.shutdown.assert_called_once()+ # A teardown failure is not a fetch failure.+ self.assertFalse(adapter._last_fetch_failed)+++class TestWeixinPollSessionRecycle(unittest.TestCase):+ """The weixin poll loop must recycle its session after a failure streak."""++ def _make_adapter(self):+ from gateway.config import PlatformConfig+ from gateway.platforms.weixin import WeixinAdapter++ return WeixinAdapter(+ PlatformConfig(+ enabled=True,+ token="test-token",+ extra={"account_id": "test-account"},+ )+ )++ def test_recycle_closes_old_and_installs_fresh_session(self):+ from gateway.platforms import weixin as weixin_mod++ adapter = self._make_adapter()+ adapter._running = True++ old_session = MagicMock()+ old_session.closed = False++ async def _close():+ old_session.close_called = True++ old_session.close = MagicMock(side_effect=lambda: _close())+ # close() must return an awaitable+ closed = {"v": False}++ async def _aclose():+ closed["v"] = True++ old_session.close = _aclose+ adapter._poll_session = old_session++ new_session = MagicMock()+ with patch.object(+ weixin_mod.aiohttp, "ClientSession", return_value=new_session+ ) as mk:+ asyncio.run(adapter._recycle_poll_session())++ mk.assert_called_once()+ self.assertIs(adapter._poll_session, new_session)+ self.assertTrue(closed["v"])++ def test_recycle_noop_when_not_running(self):+ adapter = self._make_adapter()+ adapter._running = False+ sentinel = MagicMock()+ adapter._poll_session = sentinel+ asyncio.run(adapter._recycle_poll_session())+ self.assertIs(adapter._poll_session, sentinel)++ def test_poll_loop_recycles_after_max_consecutive_failures(self):+ from gateway.platforms import weixin as weixin_mod++ adapter = self._make_adapter()+ adapter._running = True+ adapter._poll_session = MagicMock()++ calls = {"n": 0, "recycled": 0}++ async def _failing_get_updates(*args, **kwargs):+ calls["n"] += 1+ if calls["n"] > weixin_mod.MAX_CONSECUTIVE_FAILURES:+ adapter._running = False+ raise asyncio.CancelledError+ raise ConnectionError("Cannot connect to host via proxy")++ async def _fake_recycle():+ calls["recycled"] += 1++ async def _no_sleep(_secs):+ return None++ with patch.object(weixin_mod, "_get_updates", _failing_get_updates), \+ patch.object(weixin_mod, "_load_sync_buf", return_value=""), \+ patch.object(weixin_mod.asyncio, "sleep", _no_sleep), \+ patch.object(adapter, "_recycle_poll_session", _fake_recycle):+ asyncio.run(adapter._poll_loop())++ self.assertEqual(calls["recycled"], 1)+++if __name__ == "__main__":+ unittest.main()