Skip to content

The agent that grows with you

fix(gateway): restart waits on the configured api_server address and treats a slow accept as busy

kshitijk4poor5d48722517b6
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 8227b2b361a..ebc735a2549 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -199,6 +199,19 @@ def _hermes_version() -> str:
# Default settings
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 8642
+
+
+def listen_address(extra: Dict[str, Any]) -> tuple[str, int]:
+ """Host/port the adapter binds: config.yaml ``platforms.api_server`` wins over the env fallbacks.
+
+ Shared with the CLI restart path, which must wait on the SAME address the replacement will
+ bind — an env-only reading missed every config.yaml port (#91547).
+ """
+ host = extra.get("host", os.getenv("API_SERVER_HOST", DEFAULT_HOST))
+ raw_port = extra.get("port")
+ if raw_port is None:
+ raw_port = os.getenv("API_SERVER_PORT", str(DEFAULT_PORT))
+ return host, _coerce_port(raw_port, DEFAULT_PORT)
MAX_STORED_RESPONSES = 100
MAX_REQUEST_BYTES = 10_000_000 # 10 MB — accommodates long agent conversations with tool calls
# Send a comment before remote API clients' common 20-second idle deadline.
@@ -1142,11 +1155,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
def __init__(self, config: PlatformConfig):
super().__init__(config, Platform.API_SERVER)
extra = config.extra or {}
- self._host: str = extra.get("host", os.getenv("API_SERVER_HOST", DEFAULT_HOST))
- raw_port = extra.get("port")
- if raw_port is None:
- raw_port = os.getenv("API_SERVER_PORT", str(DEFAULT_PORT))
- self._port: int = _coerce_port(raw_port, DEFAULT_PORT)
+ self._host, self._port = listen_address(extra)
self._api_key: str = extra.get("key", _get_scoped_secret("API_SERVER_KEY", ""))
self._cors_origins: tuple[str, ...] = self._parse_cors_origins(
extra.get("cors_origins", os.getenv("API_SERVER_CORS_ORIGINS", "")))
@@ -4018,25 +4027,21 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
# while both report success — disable. - Linux: SO_REUSEADDR only permits rebinding past
# TIME_WAIT (a second live listener needs SO_REUSEPORT, never set), so keep the default
# (enabled) for instant restart rebinds.
- self._site = web.TCPSite(
- self._runner, self._host, self._port, reuse_address=False if sys.platform == "darwin" else None)
try:
- last_exc: OSError | None = None
+ # 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):
+ self._site = web.TCPSite(
+ self._runner, self._host, self._port, reuse_address=False if sys.platform == "darwin" else None)
try:
await self._site.start()
- last_exc = None
break
except OSError as exc:
- last_exc = exc
- if (
- getattr(exc, "errno", None) != errno.EADDRINUSE
- or attempt == 4
- ):
- break
+ self._runner._unreg_site(self._site)
+ if getattr(exc, "errno", None) != errno.EADDRINUSE or attempt == 4:
+ raise
await asyncio.sleep(0.2 * (attempt + 1))
- if last_exc is not None:
- raise last_exc
except OSError as exc:
await self._runner.cleanup()
self._runner = None
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 35b479bdd5a..f5c11069d71 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -4328,44 +4328,37 @@ def _wait_for_gateway_exit(timeout: float = 10.0, force_after: float | None = 5.
return True
-def _wait_for_tcp_port_free(
- host: str,
- port: int,
- *,
- timeout: float = 10.0,
- clock=time.monotonic,
- sleeper=time.sleep,
- connect=None,
-) -> bool:
+def _wait_for_tcp_port_free(host: str, port: int, *, timeout: float = 10.0) -> bool:
"""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.
- Connection-refused means the listener is gone.
+ 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
+ listener is gone; a timed-out connect is a live listener with a slow accept queue.
"""
- probe = connect
- if probe is None:
- def probe(target_host: str, target_port: int) -> bool:
- with socket.create_connection((target_host, target_port), timeout=0.2):
- return True
-
- deadline = clock() + timeout
- while clock() < deadline:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
try:
- probe(host, port)
- except OSError:
+ with socket.create_connection((host, port), timeout=0.2):
+ pass
+ except ConnectionRefusedError:
return True
- sleeper(0.1)
+ except OSError:
+ pass
+ time.sleep(0.1)
return False
def _wait_for_api_server_port_free(*, timeout: float = 10.0) -> bool:
- """Wait for the configured api_server listen address to stop accepting."""
- host = os.getenv("API_SERVER_HOST", "127.0.0.1") or "127.0.0.1"
- try:
- port = int(os.getenv("API_SERVER_PORT", "8642"))
- except ValueError:
- port = 8642
+ """Wait for the configured api_server listen address to stop accepting.
+
+ Only when api_server is enabled: with the platform off, a foreign listener on the default
+ port is nobody's race and must not delay the restart."""
+ from gateway.config import Platform
+ from gateway.platforms.api_server import listen_address
+ pconfig = load_gateway_config().platforms.get(Platform.API_SERVER)
+ if pconfig is None or not pconfig.enabled:
+ return True
+ host, port = listen_address(pconfig.extra or {})
freed = _wait_for_tcp_port_free(host, port, timeout=timeout)
if not freed:
print(
diff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.py
index a71506ebea0..50aa0fa2e39 100644
--- a/tests/hermes_cli/test_gateway.py
+++ b/tests/hermes_cli/test_gateway.py
@@ -529,37 +529,42 @@ class TestWaitForGatewayExit:
assert calls == [(22, True)]
-class TestWaitForTcpPortFree:
- def test_returns_true_once_connect_fails(self):
- attempts = {"n": 0}
-
- def connect(_host, _port):
- attempts["n"] += 1
- if attempts["n"] < 3:
- return True
- raise OSError("refused")
-
- times = iter([0.0, 0.0, 0.1, 0.2, 0.3])
- assert gateway._wait_for_tcp_port_free(
- "127.0.0.1",
- 8642,
- timeout=1.0,
- clock=lambda: next(times),
- sleeper=lambda _: None,
- connect=connect,
- )
- assert attempts["n"] == 3
-
- def test_times_out_while_port_stays_busy(self):
- times = iter([0.0, 0.0, 0.5, 1.5])
- assert gateway._wait_for_tcp_port_free(
- "127.0.0.1",
- 8642,
- timeout=1.0,
- clock=lambda: next(times),
- sleeper=lambda _: None,
- connect=lambda _h, _p: True,
- ) is False
+class TestRestartWaitsForApiServerPort:
+ """Regression for #91547: ``hermes gateway restart`` waited only for the old PID; on macOS the
+ replacement then hit EADDRINUSE and ran with no API server."""
+
+ def test_port_is_reported_free_once_the_old_listener_closes(self):
+ import socket
+ import threading
+
+ listener = socket.socket()
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(8)
+ port = listener.getsockname()[1]
+ threading.Timer(0.3, listener.close).start()
+
+ assert gateway._wait_for_tcp_port_free("127.0.0.1", port, timeout=5.0) is True
+
+ def test_wait_targets_the_configured_api_server_port_only_when_enabled(self, monkeypatch):
+ import socket
+
+ from gateway.config import GatewayConfig, Platform, PlatformConfig
+
+ listener = socket.socket()
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(8)
+ port = listener.getsockname()[1]
+ cfg = GatewayConfig()
+ cfg.platforms[Platform.API_SERVER] = PlatformConfig(enabled=True, extra={"port": port})
+ monkeypatch.setattr(gateway, "load_gateway_config", lambda: cfg)
+ monkeypatch.delenv("API_SERVER_PORT", raising=False)
+ try:
+ # config.yaml port wins over the env default: the busy configured port is what we wait on
+ assert gateway._wait_for_api_server_port_free(timeout=0.3) is False
+ cfg.platforms[Platform.API_SERVER].enabled = False
+ assert gateway._wait_for_api_server_port_free(timeout=0.3) is True
+ finally:
+ listener.close()
class TestStopProfileGateway: