Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(channels): serialize reloads per channel, cancel in-flight starts on stop (#1520)

Haozhe Wucdb17c9215f4
diff --git a/agent/src/channels/manager.py b/agent/src/channels/manager.py
index 77b6bc022..05e7140bf 100644
--- a/agent/src/channels/manager.py
+++ b/agent/src/channels/manager.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import hashlib
import logging
+from collections import defaultdict
from collections.abc import Callable
from contextlib import suppress
from pathlib import Path
@@ -64,6 +65,10 @@ class ChannelManager:
self.channels: dict[str, BaseChannel] = {}
self._dispatch_task: asyncio.Task | None = None
self._start_tasks: set[asyncio.Task] = set()
+ # One reload at a time per channel, whoever calls it: the settings route
+ # locks its own file write, but two reloads of one channel racing here
+ # would each stop the adapter they saw and start their own.
+ self._reload_locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
self._origin_reply_fingerprints: dict[tuple[str, str, str], str] = {}
self._status: dict[str, dict[str, Any]] = {}
@@ -257,6 +262,14 @@ class ChannelManager:
await self._dispatch_task
self._dispatch_task = None
+ # A reload's background start() can still be connecting; left running it
+ # would bring an adapter up after the manager stopped (from #1521).
+ for task in list(self._start_tasks):
+ task.cancel()
+ with suppress(asyncio.CancelledError):
+ await task
+ self._start_tasks.clear()
+
# Iterate a snapshot: a concurrent reload_channel may pop/insert entries.
for name, channel in list(self.channels.items()):
try:
@@ -285,6 +298,10 @@ class ChannelManager:
Returns:
The updated ``_status[name]`` entry.
"""
+ async with self._reload_locks[name]:
+ return await self._reload_channel_locked(name, section)
+
+ async def _reload_channel_locked(self, name: str, section: dict | None) -> dict[str, Any]:
old = self.channels.get(name)
if old is not None:
try:
diff --git a/agent/src/channels/websocket.py b/agent/src/channels/websocket.py
index 1a19e8e99..23c071603 100644
--- a/agent/src/channels/websocket.py
+++ b/agent/src/channels/websocket.py
@@ -446,7 +446,7 @@ class WebSocketChannel(BaseChannel):
async def start(self) -> None:
# (stdlib logging handles websockets SDK output via propagation)
- ws_logger = websockets_server_logger()
+ ws_logger = websockets_server_logger
self._running = True
self._stop_event = asyncio.Event()
diff --git a/agent/tests/test_channel_manager_reload.py b/agent/tests/test_channel_manager_reload.py
index df2d1c561..cba061dfa 100644
--- a/agent/tests/test_channel_manager_reload.py
+++ b/agent/tests/test_channel_manager_reload.py
@@ -394,3 +394,44 @@ def test_reload_does_not_await_a_blocking_start(
await manager.stop_all()
asyncio.run(scenario())
+
+
+def test_concurrent_reloads_of_one_channel_leave_one_adapter_running(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Two reloads racing on one channel each stopped the adapter they saw and
+ started their own, so one replacement ran outside the manager."""
+
+ async def scenario() -> None:
+ manager = _build_manager(monkeypatch, {"fakea": {"enabled": True, "tag": "old", "slow_stop": True}})
+ await manager.start_all()
+ try:
+ await asyncio.gather(
+ manager.reload_channel("fakea", {"enabled": True, "tag": "a", "slow_stop": True}),
+ manager.reload_channel("fakea", {"enabled": True, "tag": "b", "slow_stop": True}),
+ )
+ await asyncio.sleep(0)
+ running = [c.tag for c in FakeChannel.instances if c.is_running]
+ assert running == [manager.channels["fakea"].tag]
+ finally:
+ await manager.stop_all()
+
+ asyncio.run(scenario())
+
+
+def test_stop_all_cancels_a_start_still_in_flight(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def scenario() -> None:
+ manager = _build_manager(monkeypatch, {"fakea": {"enabled": True, "tag": "old"}})
+ await manager.start_all()
+ await manager.reload_channel("fakea", {"enabled": True, "tag": "new", "hang_start": True})
+ pending = list(manager._start_tasks)
+ assert pending
+
+ await asyncio.wait_for(manager.stop_all(), timeout=2.0)
+
+ assert all(task.done() for task in pending)
+ assert not manager._start_tasks
+
+ asyncio.run(scenario())
diff --git a/agent/tests/test_websocket_channel_start.py b/agent/tests/test_websocket_channel_start.py
new file mode 100644
index 000000000..2c6a88cac
--- /dev/null
+++ b/agent/tests/test_websocket_channel_start.py
@@ -0,0 +1,48 @@
+"""The WebSocket channel must start: its logger symbol is a Logger, not a factory."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+
+from src.channels.websocket import WebSocketChannel
+from src.channelsui.websocket_logging import websockets_server_logger
+from src.channelsui.gateway_services import build_gateway_services
+
+
+def test_websockets_server_logger_is_a_logger_not_a_factory():
+ # the channel passes this object straight to websockets' logger= kwarg;
+ # calling it used to raise TypeError before start() bound anything
+ assert isinstance(websockets_server_logger, logging.Logger)
+
+
+def test_websocket_channel_starts_on_a_unix_socket():
+ from src.channels.bus.queue import MessageBus
+
+ # macOS caps unix socket paths at 104 chars, so keep it short
+ import tempfile, uuid as _uuid
+
+ sock = f"{tempfile.gettempdir()}/vt-{_uuid.uuid4().hex[:8]}.sock"
+ channel = WebSocketChannel(
+ {
+ "enabled": True,
+ "unix_socket_path": sock,
+ "path": "/ws",
+ "host": "127.0.0.1",
+ "port": 0,
+ },
+ MessageBus(),
+ gateway=build_gateway_services(),
+ )
+
+ async def run():
+ task = asyncio.create_task(channel.start())
+ await asyncio.sleep(0.5)
+ # start() reaches the serve loop: no TypeError from the logger line,
+ # the task is alive and the channel reports running
+ assert not task.done() or task.exception() is None
+ assert channel.is_running
+ await channel.stop()
+ await asyncio.wait_for(task, timeout=5)
+
+ asyncio.run(run())