Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Close the connection a Mattermost bot socket leaves open on its loop

Petr Bauch2c72c5fbd404
diff --git a/core/pyproject.toml b/core/pyproject.toml
index 269a1ea97..145699452 100644
--- a/core/pyproject.toml
+++ b/core/pyproject.toml
@@ -30,6 +30,7 @@ dependencies = [
"Markdown>=3,<4",
"slack-sdk>=3.41.0",
"mattermostdriver>=7.3.2",
+ "websockets>=14,<17",
"aiohttp>=3.14.3,<4",
"cryptography>=50.0.0,<51",
"fastmcp>=3.2.0,<4",
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index dea330783..ac805174e 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -7,6 +7,7 @@ import logging
import re
import threading
import uuid
+import weakref
from collections import OrderedDict
from collections.abc import Awaitable, Callable
from contextvars import ContextVar
@@ -27,6 +28,7 @@ from mattermostdriver.exceptions import (
ResourceNotFound,
)
from pydantic import field_validator
+from websockets.asyncio.client import ClientConnection
from switch_core.bridges.collaboration.adapter import (
ActivityMark,
@@ -98,6 +100,10 @@ _MAX_BOT_ICON_BYTES = 5 * 1024 * 1024
# to wait for ever, so a server that accepts the connection and never answers
# would hold the call, and anything waiting on it, indefinitely.
_MM_REQUEST_TIMEOUT_SECONDS = 10.0
+# How long a bot socket's closing handshake may take before the connection is
+# dropped: it runs on the socket's own thread, between one connection and the
+# next.
+_MM_SOCKET_CLOSE_TIMEOUT_SECONDS = 2.0
# Mattermost channel types a bot can be *added* to: open and private channels.
# Membership of a DM ("D") or group DM ("G") is a property of the conversation
@@ -298,14 +304,34 @@ def _ephemeral(text: str) -> dict[str, Any]:
return {"ephemeral_text": text, "skip_slack_parsing": True}
+class _BotSocketConnection(ClientConnection):
+ """A bot socket's `websockets` connection, remembered so `_close_loop` can
+ close it: mattermostdriver holds it in a local variable and leaves it open
+ when its loop stops, so its transport and file descriptor would otherwise
+ last until the garbage collector found them."""
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ _BOT_SOCKET_CONNECTIONS.add(self)
+
+
+_BOT_SOCKET_CONNECTIONS: weakref.WeakSet[_BotSocketConnection] = weakref.WeakSet()
+
+
def _close_loop(loop: asyncio.AbstractEventLoop) -> None:
- """Cancel what is still running on `loop`, then close it.
+ """Close the connections opened on `loop`, cancel what is still running on
+ it, then close it.
A socket's `websockets` connection runs a keepalive task beside it that
outlives the socket's own coroutine. A loop dropped with that task still
pending is reported as "Task was destroyed but it is pending!" whenever it
is collected, at ERROR, in the middle of whatever the server is doing.
"""
+ connections = [c for c in list(_BOT_SOCKET_CONNECTIONS) if c.loop is loop]
+ if connections:
+ loop.run_until_complete(
+ asyncio.gather(*(c.close() for c in connections), return_exceptions=True)
+ )
pending = asyncio.all_tasks(loop)
for task in pending:
task.cancel()
@@ -2890,6 +2916,10 @@ class MattermostAdapter(PlatformAdapter):
"port": port,
"verify": self._config.verify_tls,
"request_timeout": _MM_REQUEST_TIMEOUT_SECONDS,
+ "websocket_kw_args": {
+ "create_connection": _BotSocketConnection,
+ "close_timeout": _MM_SOCKET_CLOSE_TIMEOUT_SECONDS,
+ },
}
if token:
opts["token"] = token
diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_bot_sockets.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_bot_sockets.py
index 00b7c5209..2e03f4133 100644
--- a/core/tests/switch_core/bridges/collaboration/test_mattermost_bot_sockets.py
+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_bot_sockets.py
@@ -13,7 +13,14 @@ import threading
from collections.abc import Callable
from typing import Any
-from switch_core.bridges.collaboration.mattermost.adapter import MattermostAdapter
+from websockets.asyncio.client import ClientConnection, connect
+from websockets.asyncio.server import ServerConnection, serve
+
+from switch_core.bridges.collaboration.mattermost.adapter import (
+ MattermostAdapter,
+ _BotSocketConnection,
+ _close_loop,
+)
from tests.switch_core.bridges.collaboration.test_bridge_agent_display_names import (
_agent,
_bridge,
@@ -149,3 +156,56 @@ def test_a_closed_socket_leaves_no_task_pending_on_its_loop() -> None:
assert bot.keepalive is not None and bot.keepalive.cancelled()
assert bot.loop is not None and bot.loop.is_closed()
+
+
+def test_closing_a_socket_loop_closes_the_connection_left_open_on_it() -> None:
+ """mattermostdriver keeps its connection in a local variable and leaves it
+ open when the socket stops, so the loop's closing has to close it, or its
+ file descriptor lasts until the garbage collector finds it."""
+ server_saw_close = threading.Event()
+ listening = threading.Event()
+ port: list[int] = []
+ stop_server = threading.Event()
+
+ def serve_forever() -> None:
+ async def handler(connection: ServerConnection) -> None:
+ await connection.wait_closed()
+ server_saw_close.set()
+
+ async def main() -> None:
+ async with serve(handler, "127.0.0.1", 0) as server:
+ port.append(next(iter(server.sockets)).getsockname()[1])
+ listening.set()
+ await asyncio.to_thread(stop_server.wait, 10)
+
+ asyncio.run(main())
+
+ server_thread = threading.Thread(target=serve_forever, daemon=True)
+ server_thread.start()
+ assert listening.wait(5)
+
+ opened: list[ClientConnection] = []
+
+ def socket_thread() -> None:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+
+ async def open_and_return() -> None:
+ opened.append(
+ await connect(
+ f"ws://127.0.0.1:{port[0]}",
+ create_connection=_BotSocketConnection,
+ close_timeout=2,
+ )
+ )
+
+ loop.run_until_complete(open_and_return())
+ _close_loop(loop)
+
+ thread = threading.Thread(target=socket_thread)
+ thread.start()
+ thread.join(10)
+ stop_server.set()
+
+ assert opened and opened[0].transport.is_closing()
+ assert server_saw_close.wait(5)
diff --git a/core/uv.lock b/core/uv.lock
index f87ef335c..ae1289887 100644
--- a/core/uv.lock
+++ b/core/uv.lock
@@ -2359,6 +2359,7 @@ dependencies = [
{ name = "slack-sdk" },
{ name = "sqlalchemy", extra = ["asyncio"] },
{ name = "uvicorn" },
+ { name = "websockets" },
]
[package.dev-dependencies]
@@ -2395,6 +2396,7 @@ requires-dist = [
{ name = "slack-sdk", specifier = ">=3.41.0" },
{ name = "sqlalchemy", extras = ["asyncio"], specifier = ">=2,<3" },
{ name = "uvicorn", specifier = ">=0.34,<1" },
+ { name = "websockets", specifier = ">=14,<17" },
]
[package.metadata.requires-dev]