Skip to content

The agent that grows with you

fix(gateway): a boot that lost a configured platform must not report itself as a normal run

finn763182f623fe50a
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 4686582bb47..af395f13306 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -40,6 +40,11 @@ logger = logging.getLogger("gateway.run")
class GatewayStartupMixin:
"""Startup sequence, resume/restore and handoff methods for GatewayRunner."""
+ # Non-retryable platform failures this boot left the gateway serving WITHOUT: recorded by
+ # ``_start_handle_no_connections`` and consumed when the runtime state is stamped, so a boot that
+ # lost a configured platform never reports itself as a normal run.
+ _startup_parked_platforms: Optional[str] = None
+
async def _run_startup_resume_event(
self, adapter: BasePlatformAdapter, event: MessageEvent, session_key: str,
) -> None:
@@ -1226,9 +1231,27 @@ class GatewayStartupMixin:
self, connected_count: int, enabled_platform_count: int, startup_retryable_errors: list,
startup_nonretryable_errors: list,
) -> bool:
- """Log/degrade when nothing connected; return True when startup must exit."""
+ """Log/degrade when a configured platform failed to start; return True when startup must exit.
+
+ The SHARED gate for every platform, not the api_server path: a configured platform that never
+ came up must leave a loud, observable trace (ERROR + a ``degraded`` runtime state) even while
+ sibling platforms serve normally. One WARNING next to "Gateway running with N platform(s)" let
+ a gateway with no API server at all look healthy for half an hour (api_server lost the bind
+ race against the gateway it was replacing, and nothing retried).
+ """
from gateway.run import _write_runtime_status_quiet
if connected_count != 0:
+ if startup_nonretryable_errors:
+ # Parked fatal failures never heal on their own, so the platforms still serving must
+ # not be reported as a healthy run. Retryable peers are deliberately left alone: the
+ # reconnect watcher recovers them and their platform entry already says "retrying".
+ self._startup_parked_platforms = "; ".join(startup_nonretryable_errors)
+ logger.error(
+ "%d configured platform(s) failed to start and are parked (fix the reported error, "
+ "then `/platform resume <platform>`): %s. The gateway is DEGRADED — it serves the "
+ "remaining platform(s) with those unserved.",
+ len(startup_nonretryable_errors), self._startup_parked_platforms,
+ )
return False
if startup_nonretryable_errors and not startup_retryable_errors:
reason = "; ".join(startup_nonretryable_errors)
@@ -1417,6 +1440,7 @@ class GatewayStartupMixin:
self._start_startup_warmup()
startup_nonretryable_errors: list[str] = []
startup_retryable_errors: list[str] = []
+ self._startup_parked_platforms = None # fresh boot: no platform has failed yet
(
_aborted, enabled_platform_count, _multiplex_skipped_platforms, _pending_connects
) = await self._start_prefilter_platforms()
@@ -1447,7 +1471,10 @@ class GatewayStartupMixin:
self._wire_teams_pipeline_runtime()
self._running = True
self._install_plugin_message_injector()
- self._update_runtime_status("running")
+ # A boot that could not start every configured platform is not a normal run: stamp ``degraded``
+ # so ``gateway status`` / /api/status / the health snapshot surface it, instead of only a log
+ # line next to "Gateway running with N platform(s)".
+ self._update_runtime_status("degraded" if self._startup_parked_platforms else "running")
await self._start_finish_wiring(connected_count)
self._start_spawn_background_watchers()
logger.info("Press Ctrl+C to stop")
diff --git a/tests/gateway/test_startup_failed_platform_reports_degraded.py b/tests/gateway/test_startup_failed_platform_reports_degraded.py
new file mode 100644
index 00000000000..e91688d0c07
--- /dev/null
+++ b/tests/gateway/test_startup_failed_platform_reports_degraded.py
@@ -0,0 +1,153 @@
+"""A configured platform that fails to start must not let the gateway report a normal run.
+
+api_server lost the bind race against the gateway it was replacing (Errno 48 / 10048), logged
+``✗ api_server failed to connect`` at WARNING, and carried on serving its messaging platforms. The
+startup summary said ``Gateway running with 1 platform(s)`` and the runtime state said ``running``:
+status looked healthy, every API client was gone, nothing retried. The startup summary is the SHARED
+gate — every platform, not just api_server — so the same failure on any other platform is reported
+the same way.
+"""
+import logging
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from gateway.platforms.base import BasePlatformAdapter
+from gateway.run import GatewayRunner
+from gateway.status import read_runtime_status
+
+
+class _PortTakenAdapter(BasePlatformAdapter):
+ """Loses the bind race exactly like api_server: fatal AND non-retryable, so it is parked."""
+
+ def __init__(self):
+ super().__init__(PlatformConfig(enabled=True, extra={"port": 8642}), Platform.API_SERVER)
+
+ async def connect(self, *, is_reconnect: bool = False) -> bool:
+ self._set_fatal_error(
+ "api_server_port_in_use",
+ "Port 8642 already in use. Set platforms.api_server.port in config.yaml to a different "
+ "value, then `/platform resume api_server`.",
+ retryable=False,
+ )
+ return False
+
+ async def disconnect(self) -> None:
+ self._mark_disconnected()
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ raise NotImplementedError
+
+ async def get_chat_info(self, chat_id):
+ return {"id": chat_id}
+
+
+class _HealthyAdapter(BasePlatformAdapter):
+ """The messaging platform that keeps the gateway useful — and used to hide the failure."""
+
+ def __init__(self):
+ super().__init__(PlatformConfig(enabled=True, token="***"), Platform.TELEGRAM)
+
+ async def connect(self, *, is_reconnect: bool = False) -> bool:
+ return True
+
+ async def disconnect(self) -> None:
+ self._mark_disconnected()
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ raise NotImplementedError
+
+ async def get_chat_info(self, chat_id):
+ return {"id": chat_id}
+
+
+def _runner_with_one_parked_platform(monkeypatch, tmp_path) -> GatewayRunner:
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ config = GatewayConfig(
+ platforms={
+ Platform.API_SERVER: PlatformConfig(enabled=True, extra={"port": 8642}),
+ Platform.TELEGRAM: PlatformConfig(enabled=True, token="***"),
+ },
+ sessions_dir=tmp_path / "sessions",
+ )
+ runner = GatewayRunner(config)
+ monkeypatch.setattr(
+ runner,
+ "_create_adapter",
+ lambda platform, platform_config: (
+ _PortTakenAdapter() if platform is Platform.API_SERVER else _HealthyAdapter()
+ ),
+ )
+ async def _no_secondary_profiles():
+ return 0
+
+ monkeypatch.setattr(runner, "_start_secondary_profile_adapters", _no_secondary_profiles)
+ return runner
+
+
+async def test_parked_platform_is_reported_at_error_when_others_serve(monkeypatch, tmp_path, caplog):
+ """The failure is logged at ERROR — not only the WARNING that hid it."""
+ runner = _runner_with_one_parked_platform(monkeypatch, tmp_path)
+
+ with caplog.at_level(logging.ERROR):
+ ok = await runner.start()
+ try:
+ assert ok is True, "the working platform keeps the gateway alive; only reporting changes"
+ assert runner.should_exit_cleanly is False
+ assert any(
+ record.levelno >= logging.ERROR and "api_server" in record.getMessage()
+ for record in caplog.records
+ ), "a configured platform that never came up must be reported at ERROR, not only a WARNING"
+ finally:
+ await runner.stop()
+
+
+async def test_parked_platform_is_not_reported_as_a_normal_run(monkeypatch, tmp_path):
+ """The runtime state must not claim a normal run while a configured platform is unserved."""
+ runner = _runner_with_one_parked_platform(monkeypatch, tmp_path)
+
+ ok = await runner.start()
+ try:
+ assert ok is True
+ assert runner.should_exit_cleanly is False
+ state = read_runtime_status()
+ assert state["gateway_state"] == "degraded", (
+ "the gateway is serving with a configured platform missing — it must not claim a normal run"
+ )
+ assert state["platforms"]["api_server"]["state"] == "fatal"
+ assert state["platforms"]["api_server"]["error_code"] == "api_server_port_in_use"
+ assert state["platforms"]["telegram"]["state"] == "connected"
+ finally:
+ await runner.stop()
+
+
+async def test_every_platform_connected_still_reports_a_normal_run(monkeypatch, tmp_path, caplog):
+ """Protection: a clean startup keeps the normal ``running`` state and logs no ERROR."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ config = GatewayConfig(
+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="***")},
+ sessions_dir=tmp_path / "sessions",
+ )
+ runner = GatewayRunner(config)
+ monkeypatch.setattr(runner, "_create_adapter", lambda platform, platform_config: _HealthyAdapter())
+
+ async def _no_secondary_profiles():
+ return 0
+
+ monkeypatch.setattr(runner, "_start_secondary_profile_adapters", _no_secondary_profiles)
+
+ with caplog.at_level(logging.ERROR):
+ ok = await runner.start()
+ try:
+ assert ok is True
+ state = read_runtime_status()
+ assert state["gateway_state"] == "running"
+ assert state["platforms"]["telegram"]["state"] == "connected"
+ assert not [r for r in caplog.records if r.levelno >= logging.ERROR], (
+ "a healthy startup must not log ERROR"
+ )
+ finally:
+ await runner.stop()