Skip to content

The agent that grows with you

fix(gateway): a degraded boot stays degraded and still counts as a completed restart

kshitijk4poored8f8498d32e
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index ebc735a2549..2798bf10373 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -199,6 +199,7 @@ def _hermes_version() -> str:
# Default settings
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 8642
+_BIND_ATTEMPTS = 5 # EADDRINUSE retries while a restart's predecessor releases the port (#91547)
def listen_address(extra: Dict[str, Any]) -> tuple[str, int]:
@@ -4028,19 +4029,21 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
# TIME_WAIT (a second live listener needs SO_REUSEPORT, never set), so keep the default
# (enabled) for instant restart rebinds.
try:
- # A restart's predecessor may still hold the port for a moment after its PID is gone;
- # a fresh TCPSite per attempt (a failed one stays registered in the runner) bounds the
- # retry before the conflict is treated as a real config error.
- for attempt in range(5):
+ # A restart's predecessor may still hold the port for a moment after its PID is gone.
+ # aiohttp registers a site with its runner before binding, so a failed start leaves the
+ # site registered: rebuild the runner per attempt rather than reach into its internals.
+ for attempt in range(_BIND_ATTEMPTS):
self._site = web.TCPSite(
self._runner, self._host, self._port, reuse_address=False if sys.platform == "darwin" else None)
try:
await self._site.start()
break
except OSError as exc:
- self._runner._unreg_site(self._site)
- if getattr(exc, "errno", None) != errno.EADDRINUSE or attempt == 4:
+ if exc.errno != errno.EADDRINUSE or attempt == _BIND_ATTEMPTS - 1:
raise
+ await self._runner.cleanup()
+ self._runner = web.AppRunner(self._app)
+ await self._runner.setup()
await asyncio.sleep(0.2 * (attempt + 1))
except OSError as exc:
await self._runner.cleanup()
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index 96fa0fc72de..1483b985c10 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -439,7 +439,7 @@ class GatewayShutdownMixin:
"""
self._last_inbound_at = time.time()
if getattr(self, "_scale_to_zero_cooldown_until", 0.0) > 0:
- self._scale_to_zero_status("running", "scale-to-zero: status restore failed")
+ self._scale_to_zero_status(self._serving_state(), "scale-to-zero: status restore failed")
self._scale_to_zero_cooldown_until = 0.0
def _scale_to_zero_status(self, state: str, fail_msg: str) -> None:
@@ -626,7 +626,7 @@ class GatewayShutdownMixin:
# Same guard as _exit_external_drain: a real shutdown drain must win, so never resurrect
# a stopping gateway to `running`.
if not getattr(self, "_draining", False) and self._running:
- self._scale_to_zero_status("running", "scale-to-zero: status restore failed")
+ self._scale_to_zero_status(self._serving_state(), "scale-to-zero: status restore failed")
# An abort before the cooldown is set would otherwise retry every tick.
self._scale_to_zero_cooldown_until = max(
self._scale_to_zero_cooldown_until, time.time() + 60.0
@@ -676,9 +676,9 @@ class GatewayShutdownMixin:
return
logger.info(
"External drain RELEASED (.drain_request.json removed) — "
- "re-accepting new turns; gateway_state -> running."
+ "re-accepting new turns; gateway_state -> %s.", self._serving_state(),
)
- self._update_runtime_status("running")
+ self._update_runtime_status(self._serving_state())
async def _drain_control_watcher(self, interval: float = 1.0) -> None:
"""Poll ``.drain_request.json`` at 1s: present -> enter drain, absent -> exit; a stale epoch = absent."""
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index af395f13306..a97622aa1c2 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -40,10 +40,12 @@ 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
+ # A configured platform failed non-retryably this boot and is parked: every "we are serving"
+ # status stamp (startup, drain release, scale-to-zero wake) must say ``degraded``, not ``running``.
+ _startup_parked_platforms: bool = False
+
+ def _serving_state(self) -> str:
+ return "degraded" if self._startup_parked_platforms else "running"
async def _run_startup_resume_event(
self, adapter: BasePlatformAdapter, event: MessageEvent, session_key: str,
@@ -1245,12 +1247,12 @@ class GatewayStartupMixin:
# 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)
+ self._startup_parked_platforms = True
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,
+ len(startup_nonretryable_errors), "; ".join(startup_nonretryable_errors),
)
return False
if startup_nonretryable_errors and not startup_retryable_errors:
@@ -1261,6 +1263,7 @@ class GatewayStartupMixin:
if startup_nonretryable_errors:
# Mixed (some fatal, some transient): exiting 78 would take the gateway PERMANENTLY down
# over a blip. Log the fatal side loudly and fall through to the degraded/retry path.
+ self._startup_parked_platforms = True
logger.error(
# WhatsApp enabled but never paired) while others hit merely transient errors (e.g. Telegram
# TimedOut during polling startup). Exiting with GATEWAY_FATAL_CONFIG_EXIT_CODE here is
@@ -1440,7 +1443,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
+ self._startup_parked_platforms = False # fresh boot: no platform has failed yet
(
_aborted, enabled_platform_count, _multiplex_skipped_platforms, _pending_connects
) = await self._start_prefilter_platforms()
@@ -1474,7 +1477,7 @@ class GatewayStartupMixin:
# 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")
+ self._update_runtime_status(self._serving_state())
await self._start_finish_wiring(connected_count)
self._start_spawn_background_watchers()
logger.info("Press Ctrl+C to stop")
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index f5c11069d71..c90580de8dc 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -1223,8 +1223,12 @@ def _wait_for_systemd_service_restart(
if runtime_state and _runtime_state_pid(runtime_state) != new_pid:
runtime_state = None
gateway_state = (runtime_state or {}).get("gateway_state")
- if gateway_state == "running":
+ if gateway_state in ("running", "degraded"):
print(f"✓ {scope_label} service restarted (PID {new_pid})")
+ if gateway_state == "degraded":
+ # Serving, but a configured platform is parked or retrying: a real restart, not a
+ # failure — say so instead of waiting out the timeout and reporting one.
+ print(f"⚠ {scope_label} gateway is DEGRADED — see `hermes gateway status`")
return True
if gateway_state == "startup_failed":
reason = (runtime_state or {}).get("exit_reason") or "startup failed"
@@ -4332,7 +4336,7 @@ def _wait_for_tcp_port_free(host: str, port: int, *, timeout: float = 10.0) -> b
"""Wait until nothing accepts TCP connections on host:port.
PID exit is not enough on macOS: api_server disables SO_REUSEADDR, so a restart that wins
- the race logs EADDRINUSE and keeps running with no API. Only connection-refused means the
+ the race logs EADDRINUSE and keeps running with no API. Connection-refused means the
listener is gone; a timed-out connect is a live listener with a slow accept queue.
"""
deadline = time.monotonic() + timeout
@@ -4342,8 +4346,10 @@ def _wait_for_tcp_port_free(host: str, port: int, *, timeout: float = 10.0) -> b
pass
except ConnectionRefusedError:
return True
+ except TimeoutError:
+ pass # a slow accept queue is still a live listener
except OSError:
- pass
+ return True # unresolvable/unreachable address: nothing to wait for; the bind retry covers it
time.sleep(0.1)
return False
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.py
index 098c5067208..e90b4cb981c 100644
--- a/hermes_cli/gateway_windows.py
+++ b/hermes_cli/gateway_windows.py
@@ -1671,7 +1671,9 @@ def restart() -> None:
"start a duplicate. Investigate stray PIDs before retrying."
)
- time.sleep(1.0) # let Windows release the listening port
+ from hermes_cli.gateway import _wait_for_api_server_port_free # avoid circular init
+
+ _wait_for_api_server_port_free()
start()
if not _wait_for_gateway_ready(timeout_s=15.0):
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index 5bc28e7e3e6..319c3789b7f 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -1115,6 +1115,27 @@ class TestGatewaySystemServiceRouting:
assert result is False
assert replacement_observed == [True]
+ def test_wait_accepts_a_degraded_replacement_as_restarted(self, monkeypatch, capsys):
+ """A replacement serving with a parked platform stamps ``degraded`` for its whole life; the
+ restart verifier must report a restart (with a warning), not wait out the timeout (#91547)."""
+ monkeypatch.setattr(gateway_cli.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(
+ gateway_cli,
+ "_read_systemd_unit_properties",
+ lambda system=False, properties=None: {"ActiveState": "active", "MainPID": "777"},
+ )
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda: 777)
+ monkeypatch.setattr(
+ gateway_cli,
+ "_read_gateway_runtime_status",
+ lambda: {"pid": 777, "gateway_state": "degraded"},
+ )
+
+ result = gateway_cli._wait_for_systemd_service_restart(previous_pid=654, timeout=1.0)
+
+ assert result is True
+ assert "DEGRADED" in capsys.readouterr().out
+
def test_launchd_restart_uses_sigusr1_and_exit_wait_budget(self, monkeypatch, capsys):
"""launchd_restart must take the same graceful path as systemd_restart.