"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(channels): per-channel hot reload and channel-runtime reset
shadowinlife2774969cf1ec
diff --git a/agent/src/api/state.py b/agent/src/api/state.pyindex 614901a37..b9a28b598 100644--- a/agent/src/api/state.py+++ b/agent/src/api/state.py@@ -136,3 +136,21 @@ def _get_channel_runtime():_set_host_attr("_channel_bus", _channel_bus)_set_host_attr("_channel_manager", _channel_manager)return _channel_runtime+++def reset_channel_runtime() -> None:+ """Drop the cached IM channel runtime so the next access rebuilds from disk.++ ``_get_channel_runtime`` caches its singletons in this module's globals+ *and* on the ``api_server`` host attrs; clearing both — with ``None``,+ which is what makes the next call rebuild — is what lets an edited channel+ config apply without a process restart.+ """+ global _channel_runtime, _channel_bus, _channel_manager++ _channel_runtime = None+ _channel_bus = None+ _channel_manager = None+ _set_host_attr("_channel_runtime", None)+ _set_host_attr("_channel_bus", None)+ _set_host_attr("_channel_manager", None)diff --git a/agent/src/channels/manager.py b/agent/src/channels/manager.pyindex 3fb09030f..3da55791b 100644--- a/agent/src/channels/manager.py+++ b/agent/src/channels/manager.py@@ -32,6 +32,9 @@ _BOOL_CAMEL_ALIASES: dict[str, str] = {"show_reasoning": "showReasoning",}+# Bound the reload stop wait so a wedged adapter cannot stall a hot swap.+_RELOAD_STOP_TIMEOUT_S = 10.0+class ChannelManager:"""Manages chat channels and coordinates message routing.@@ -56,6 +59,7 @@ class ChannelManager:self._cron_service = cron_serviceself.channels: dict[str, BaseChannel] = {}self._dispatch_task: asyncio.Task | None = None+ self._start_tasks: set[asyncio.Task] = set()self._origin_reply_fingerprints: dict[tuple[str, str, str], str] = {}self._status: dict[str, dict[str, Any]] = {}@@ -65,77 +69,83 @@ class ChannelManager:"""Initialize channels discovered via pkgutil scan + entry_points plugins."""self._status = inspect_channels(self.config)enabled_names = {- name- for name, status in self._status.items()- if status.get("enabled") is True+ name for name, status in self._status.items() if status.get("enabled") is True}- plugin_classes = discover_plugins(enabled_names)- builtins = set(discover_channel_names())for name in sorted(enabled_names):section = self._get_channel_config(name)if section is None:continue- if self._status.get(name, {}).get("available") is False:- logger.warning(- "%s channel not available: %s",- name,- self._status[name].get("error", "unavailable"),- )- continue- try:- cls = load_channel_class(name) if name in builtins else plugin_classes[name]- except Exception as exc: # noqa: BLE001 - status endpoint must explain startup gaps- self._status.setdefault(name, {})- self._status[name].update(- {- "available": False,- "loaded": False,- "running": False,- "error": f"{type(exc).__name__}: {exc}",- }- )- logger.warning("%s channel not available: %s", name, exc)- continue-- try:- kwargs = self._build_channel_kwargs(name)- channel = cls(section, self.bus, **kwargs)- # Resolve global → per-channel boolean overrides- channel.send_progress = self._resolve_bool_override(- section, "send_progress", self._global_bool("send_progress", True),- )- channel.send_tool_hints = self._resolve_bool_override(- section, "send_tool_hints", self._global_bool("send_tool_hints", False),- )- channel.show_reasoning = self._resolve_bool_override(- section, "show_reasoning", self._global_bool("show_reasoning", True),- )+ channel = self._build_channel(name, section)+ if channel is not None:self.channels[name] = channel- self._status.setdefault(name, {})- self._status[name].update(- {- "available": True,- "loaded": True,- "running": channel.is_running,- "display_name": getattr(cls, "display_name", name),- "error": "",- }- )- logger.info("%s channel enabled", cls.display_name)- except Exception as exc:- self._status.setdefault(name, {})- self._status[name].update(- {- "loaded": False,- "running": False,- "error": f"{type(exc).__name__}: {exc}",- }- )- logger.warning("%s channel not available", name, exc_info=True)self._validate_allow_from()+ def _build_channel(self, name: str, section: dict) -> BaseChannel | None:+ """Build one adapter instance and record its status (``None`` if it cannot be built).++ Args:+ name: Channel name.+ section: The channel's config section.+ """+ if self._status.get(name, {}).get("available") is False:+ logger.warning(+ "%s channel not available: %s",+ name,+ self._status[name].get("error", "unavailable"),+ )+ return None++ try:+ builtins = set(discover_channel_names())+ cls = load_channel_class(name) if name in builtins else discover_plugins({name})[name]+ except Exception as exc: # noqa: BLE001 - status endpoint must explain startup gaps+ self._record_status(+ name,+ available=False,+ loaded=False,+ running=False,+ error=f"{type(exc).__name__}: {exc}",+ )+ logger.warning("%s channel not available: %s", name, exc)+ return None++ try:+ kwargs = self._build_channel_kwargs(name)+ channel = cls(section, self.bus, **kwargs)+ # Resolve global → per-channel boolean overrides+ channel.send_progress = self._resolve_bool_override(+ section, "send_progress", self._global_bool("send_progress", True),+ )+ channel.send_tool_hints = self._resolve_bool_override(+ section, "send_tool_hints", self._global_bool("send_tool_hints", False),+ )+ channel.show_reasoning = self._resolve_bool_override(+ section, "show_reasoning", self._global_bool("show_reasoning", True),+ )+ self._record_status(+ name,+ configured=True,+ enabled=True,+ available=True,+ loaded=True,+ running=channel.is_running,+ display_name=getattr(cls, "display_name", name),+ error="",+ )+ logger.info("%s channel enabled", cls.display_name)+ return channel+ except Exception as exc:+ self._record_status(+ name,+ loaded=False,+ running=False,+ error=f"{type(exc).__name__}: {exc}",+ )+ logger.warning("%s channel not available", name, exc_info=True)+ return None+def _build_channel_kwargs(self, name: str) -> dict[str, Any]:"""Build adapter-specific constructor kwargs for channels that need services."""if name == "websocket":@@ -210,14 +220,19 @@ class ChannelManager:except Exception:logger.exception("Failed to start channel %s", name)+ def _spawn_channel_start(self, name: str, channel: BaseChannel) -> None:+ """Start a channel in the background, keeping a strong task reference."""+ task = asyncio.create_task(self._start_channel(name, channel))+ self._start_tasks.add(task)+ task.add_done_callback(self._start_tasks.discard)+async def start_all(self) -> None:"""Start all channels and the outbound dispatcher."""+ self._dispatch_task = asyncio.create_task(self._dispatch_outbound())if not self.channels:logger.warning("No channels enabled")return- self._dispatch_task = asyncio.create_task(self._dispatch_outbound())-tasks = []for name, channel in self.channels.items():logger.info("Starting %s channel...", name)@@ -236,6 +251,7 @@ class ChannelManager:self._dispatch_task.cancel()with suppress(asyncio.CancelledError):await self._dispatch_task+ self._dispatch_task = Nonefor name, channel in self.channels.items():try:@@ -251,6 +267,79 @@ class ChannelManager:self._status.setdefault(name, {})self._status[name]["running"] = channel.is_running+ async def reload_channel(self, name: str, section: dict | None) -> dict[str, Any]:+ """Hot-swap one channel adapter without restarting the other channels.++ A slow ``stop()`` is bounded and never blocks the replacement.++ Args:+ name: Channel name.+ section: The channel's new config section, or ``None`` when it is+ no longer configured.++ Returns:+ The updated ``_status[name]`` entry.+ """+ old = self.channels.get(name)+ if old is not None:+ try:+ await asyncio.wait_for(old.stop(), timeout=_RELOAD_STOP_TIMEOUT_S)+ except asyncio.TimeoutError:+ logger.warning("Stopping %s timed out; replacing", name)+ except Exception:+ logger.warning("Stopping %s failed; replacing", name, exc_info=True)+ self.channels.pop(name, None)+ self._store_channel_section(name, section)++ if section is None or not self._section_enabled(section):+ return self._record_status(+ name,+ configured=section is not None,+ enabled=False,+ loaded=False,+ running=False,+ )++ channel = self._build_channel(name, section)+ if channel is None:+ return self._record_status(name)+ self.channels[name] = channel+ if self._is_manager_running():+ # start() can be long-running (reconnect loops), so it must not be+ # awaited inline; yield once so adapters that flip is_running early+ # are reflected in the returned status.+ self._spawn_channel_start(name, channel)+ await asyncio.sleep(0)+ self._status[name]["running"] = channel.is_running+ return self._status[name]++ def _record_status(self, name: str, **fields: Any) -> dict[str, Any]:+ """Merge *fields* into the status entry for *name* and return it."""+ self._status.setdefault(name, {})+ self._status[name].update(fields)+ return self._status[name]++ @staticmethod+ def _section_enabled(section: Any) -> bool:+ """Return whether a channel section enables the adapter."""+ if isinstance(section, dict):+ return bool(section.get("enabled", False))+ return bool(getattr(section, "enabled", False))++ def _store_channel_section(self, name: str, section: dict | None) -> None:+ """Keep the manager's config snapshot in step with the reloaded section."""+ if isinstance(self.config, dict):+ if section is None:+ self.config.pop(name, None)+ else:+ self.config[name] = section+ elif section is not None:+ setattr(self.config, name, section)++ def _is_manager_running(self) -> bool:+ """Return whether the outbound dispatcher (``start_all``) is active."""+ return self._dispatch_task is not None and not self._dispatch_task.done()+# --- Outbound dispatch ---@staticmethoddiff --git a/agent/tests/test_channel_manager_reload.py b/agent/tests/test_channel_manager_reload.pynew file mode 100644index 000000000..2e1e394e6--- /dev/null+++ b/agent/tests/test_channel_manager_reload.py@@ -0,0 +1,315 @@+"""Contracts for per-channel hot reload in ``ChannelManager``."""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Iterator+from typing import Any++import pytest++import src.channels.manager as manager_module+from src.channels.bus.queue import MessageBus+from src.channels.manager import ChannelManager+++class FakeChannel:+ """Recording adapter stand-in; no platform SDK is touched."""++ display_name = "Fake"+ send_progress = True+ send_tool_hints = False+ show_reasoning = True++ instances: list["FakeChannel"] = []+ events: list[tuple[str, str]] = []++ def __init__(self, config: dict[str, Any], bus: MessageBus, **kwargs: Any) -> None:+ del kwargs+ if config.get("bad_config"):+ raise ValueError("bad channel config")+ self.config = config+ self.bus = bus+ self.tag = str(config.get("tag", len(FakeChannel.instances)))+ self._running = False+ FakeChannel.instances.append(self)++ @property+ def is_running(self) -> bool:+ return self._running++ async def start(self) -> None:+ if self.config.get("fail_start"):+ raise RuntimeError("start failed")+ self._running = True+ FakeChannel.events.append(("start", self.tag))++ async def stop(self) -> None:+ FakeChannel.events.append(("stop", self.tag))+ if self.config.get("raise_stop"):+ raise TimeoutError("stop timed out")+ if self.config.get("hang_stop"):+ await asyncio.sleep(60)+ self._running = False++ async def send(self, message: Any) -> None:+ """No-op: reload tests never dispatch outbound traffic."""+ del message++[email protected](autouse=True)+def _reset_fake_channel() -> Iterator[None]:+ """Give every test a clean instance/event ledger."""+ FakeChannel.instances = []+ FakeChannel.events = []+ yield+++def _fake_inspect_channels(config: Any) -> dict[str, dict[str, Any]]:+ """``inspect_channels`` stand-in covering the fake names under test."""+ statuses: dict[str, dict[str, Any]] = {}+ if not isinstance(config, dict):+ return statuses+ for name, section in config.items():+ if not isinstance(section, dict):+ continue+ statuses[name] = {+ "name": name,+ "available": True,+ "display_name": name.title(),+ "install_hint": "",+ "error": "",+ "configured": True,+ "enabled": bool(section.get("enabled")),+ "loaded": False,+ "running": False,+ }+ return statuses+++def _build_manager(+ monkeypatch: pytest.MonkeyPatch,+ config: dict[str, Any],+ *,+ names: tuple[str, ...] = ("fakea", "fakeb"),+) -> ChannelManager:+ """Construct a manager whose adapters are :class:`FakeChannel`."""+ monkeypatch.setattr(manager_module, "discover_channel_names", lambda: list(names))+ monkeypatch.setattr(manager_module, "load_channel_class", lambda name: FakeChannel)+ monkeypatch.setattr(manager_module, "inspect_channels", _fake_inspect_channels)+ return ChannelManager(config, MessageBus())+++def test_init_channels_builds_plugin_channels(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(manager_module, "discover_channel_names", lambda: [])+ monkeypatch.setattr(+ manager_module, "discover_plugins", lambda names: {"plugx": FakeChannel}+ )+ monkeypatch.setattr(+ manager_module,+ "load_channel_class",+ lambda name: pytest.fail("built-in path used for a plugin channel"),+ )+ monkeypatch.setattr(manager_module, "inspect_channels", _fake_inspect_channels)++ manager = ChannelManager(+ {"plugx": {"enabled": True, "tag": "plugin"}}, MessageBus()+ )++ assert manager.channels["plugx"].tag == "plugin"+ assert manager.get_status()["plugx"]["loaded"] is True+++def test_reload_enabled_section_builds_but_does_not_start_when_stopped(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def scenario() -> None:+ manager = _build_manager(+ monkeypatch,+ {"fakea": {"enabled": False}, "fakeb": {"enabled": True, "tag": "b"}},+ )+ assert "fakea" not in manager.channels++ status = await manager.reload_channel("fakea", {"enabled": True, "tag": "new"})++ channel = manager.channels["fakea"]+ assert channel.tag == "new"+ assert channel.is_running is False+ assert FakeChannel.events == []+ assert manager.config["fakea"] == {"enabled": True, "tag": "new"}+ assert status["enabled"] is True+ assert status["loaded"] is True+ assert status["running"] is False++ asyncio.run(scenario())+++def test_reload_on_running_manager_stops_old_before_starting_new(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def scenario() -> None:+ manager = _build_manager(+ monkeypatch, {"fakea": {"enabled": True, "tag": "old"}}+ )+ old = manager.channels["fakea"]+ await manager.start_all()+ try:+ status = dict(+ await manager.reload_channel("fakea", {"enabled": True, "tag": "new"})+ )+ new = manager.channels["fakea"]+ new_is_running = new.is_running+ finally:+ await manager.stop_all()++ assert new is not old+ assert old.is_running is False+ assert new_is_running is True+ assert FakeChannel.events == [+ ("start", "old"),+ ("stop", "old"),+ ("start", "new"),+ ("stop", "new"),+ ]+ assert status["enabled"] is True+ assert status["loaded"] is True+ assert status["running"] is True++ asyncio.run(scenario())++[email protected]("section", [None, {"enabled": False}])+def test_reload_disabled_section_removes_only_that_channel(+ monkeypatch: pytest.MonkeyPatch,+ section: dict[str, Any] | None,+) -> None:+ async def scenario() -> None:+ manager = _build_manager(+ monkeypatch,+ {+ "fakea": {"enabled": True, "tag": "a"},+ "fakeb": {"enabled": True, "tag": "b"},+ },+ )+ other = manager.channels["fakeb"]++ status = dict(await manager.reload_channel("fakea", section))++ assert "fakea" not in manager.channels+ assert manager.channels["fakeb"] is other+ assert FakeChannel.events == [("stop", "a")]+ assert status["enabled"] is False+ assert status["loaded"] is False+ assert status["running"] is False+ if section is None:+ assert status["configured"] is False+ assert "fakea" not in manager.config+ else:+ assert status["configured"] is True+ assert manager.config["fakea"] == {"enabled": False}++ asyncio.run(scenario())+++def test_reload_proceeds_when_old_stop_raises_timeout(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ async def scenario() -> None:+ manager = _build_manager(+ monkeypatch,+ {"fakea": {"enabled": True, "tag": "old", "raise_stop": True}},+ )+ with caplog.at_level(logging.WARNING, logger="src.channels.manager"):+ status = dict(+ await manager.reload_channel("fakea", {"enabled": True, "tag": "new"})+ )++ assert manager.channels["fakea"].tag == "new"+ assert FakeChannel.events == [("stop", "old")]+ assert status["loaded"] is True++ asyncio.run(scenario())+ assert "Stopping fakea timed out; replacing" in caplog.text+++def test_reload_bounds_a_wedged_stop(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ async def scenario() -> None:+ monkeypatch.setattr(manager_module, "_RELOAD_STOP_TIMEOUT_S", 0.05)+ manager = _build_manager(+ monkeypatch,+ {"fakea": {"enabled": True, "tag": "old", "hang_stop": True}},+ )+ with caplog.at_level(logging.WARNING, logger="src.channels.manager"):+ status = dict(+ await manager.reload_channel("fakea", {"enabled": True, "tag": "new"})+ )++ assert manager.channels["fakea"].tag == "new"+ assert status["loaded"] is True++ asyncio.run(scenario())+ assert "Stopping fakea timed out; replacing" in caplog.text+++def test_reload_build_failure_records_error_and_leaves_manager_functional(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def scenario() -> None:+ manager = _build_manager(+ monkeypatch,+ {+ "fakea": {"enabled": True, "tag": "old"},+ "fakeb": {"enabled": True, "tag": "b"},+ },+ )+ other = manager.channels["fakeb"]++ status = dict(+ await manager.reload_channel("fakea", {"enabled": True, "bad_config": True})+ )++ assert "fakea" not in manager.channels+ assert manager.channels["fakeb"] is other+ assert status["loaded"] is False+ assert status["running"] is False+ assert status["error"] == "ValueError: bad channel config"++ recovered = dict(+ await manager.reload_channel("fakea", {"enabled": True, "tag": "fixed"})+ )++ assert manager.channels["fakea"].tag == "fixed"+ assert recovered["loaded"] is True+ assert recovered["error"] == ""++ asyncio.run(scenario())+++def test_reload_is_contained_when_replacement_start_fails(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def scenario() -> None:+ manager = _build_manager(+ monkeypatch, {"fakea": {"enabled": True, "tag": "old"}}+ )+ await manager.start_all()+ try:+ status = dict(+ await manager.reload_channel(+ "fakea",+ {"enabled": True, "tag": "new", "fail_start": True},+ )+ )+ finally:+ await manager.stop_all()++ assert manager.channels["fakea"].tag == "new"+ assert status["loaded"] is True+ assert status["running"] is False++ asyncio.run(scenario())diff --git a/agent/tests/test_channel_runtime_reset.py b/agent/tests/test_channel_runtime_reset.pynew file mode 100644index 000000000..1b5243d12--- /dev/null+++ b/agent/tests/test_channel_runtime_reset.py@@ -0,0 +1,117 @@+"""Contracts for resetting the cached IM channel runtime singleton."""++from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest++import api_server+from src.api import state+++class FakeSessionService:+ """SessionService placeholder for channel runtime reset tests."""+++def _stub_channel_runtime_deps(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ config: dict[str, Any],+) -> None:+ """Isolate the runtime singleton from real config files and session stores.++ ``state._get_channel_runtime`` resolves ``load_channels_config`` and+ ``_get_session_service`` in its own module globals, so those are the+ attributes to patch (the ``api_server`` host attrs stay in play as the+ compatibility surface the function also consults).+ """+ import src.channels.config as channel_config+ import src.channels.pairing.store as pairing_store++ del tmp_path # the config loader is stubbed; no file is read+ monkeypatch.setattr(channel_config, "load_channels_config", lambda: dict(config))+ monkeypatch.setattr(+ pairing_store, "_store_path", lambda: Path("unused-pairing.json")+ )++ monkeypatch.setattr(api_server, "_channel_runtime", None)+ monkeypatch.setattr(api_server, "_channel_bus", None)+ monkeypatch.setattr(api_server, "_channel_manager", None)++ monkeypatch.setattr(state, "_channel_runtime", None)+ monkeypatch.setattr(state, "_channel_bus", None)+ monkeypatch.setattr(state, "_channel_manager", None)+ monkeypatch.setattr(state, "_get_session_service", lambda: FakeSessionService())+++def test_reset_channel_runtime_clears_globals_and_host_attrs(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stub_channel_runtime_deps(+ tmp_path,+ monkeypatch,+ {"reply_timeout_s": 600.0, "telegram": {"enabled": False}},+ )++ runtime = state._get_channel_runtime()++ assert runtime is not None+ assert state._channel_runtime is runtime+ assert state._channel_bus is not None+ assert state._channel_manager is not None+ assert api_server._channel_runtime is runtime+ assert api_server._channel_bus is state._channel_bus+ assert api_server._channel_manager is state._channel_manager++ state.reset_channel_runtime()++ assert state._channel_runtime is None+ assert state._channel_bus is None+ assert state._channel_manager is None+ assert api_server._channel_runtime is None+ assert api_server._channel_bus is None+ assert api_server._channel_manager is None+++def test_channel_runtime_rebuilds_from_current_config_after_reset(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ config: dict[str, Any] = {"reply_timeout_s": 600.0, "telegram": {"enabled": False}}+ _stub_channel_runtime_deps(tmp_path, monkeypatch, config)++ first = state._get_channel_runtime()+ assert first.config.reply_timeout_s == 600.0++ state.reset_channel_runtime()++ # The on-disk section changed while the singleton was down.+ config["reply_timeout_s"] = 42.0+ second = state._get_channel_runtime()++ assert second is not first+ assert second.config.reply_timeout_s == 42.0+ assert state._channel_runtime is second+ assert api_server._channel_runtime is second+++def test_reset_channel_runtime_before_any_build_still_allows_a_build(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stub_channel_runtime_deps(+ tmp_path,+ monkeypatch,+ {"reply_timeout_s": 600.0, "telegram": {"enabled": False}},+ )++ state.reset_channel_runtime()++ assert api_server._channel_runtime is None+ runtime = state._get_channel_runtime()++ assert runtime is not None+ assert state._channel_runtime is runtime