Skip to content

The agent that grows with you

fix(serve): emit BACKEND_PORT_IN_USE sentinel + exit 75 on port bind conflict (#93608)

Tekniumde07bd5fab23
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 7444ebf2f06..5f486493c33 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -19254,6 +19254,79 @@ def _demo() -> None:
print("web_server parent-death watchdog self-check: OK")
+# ── Port-conflict sentinel (#93608) ─────────────────────────────────────────
+# When the requested port is already bound, uvicorn's ``bind_socket()``
+# catches the OSError itself and does ``logger.error(exc); sys.exit(1)`` — a
+# bare ERROR line plus the same exit 1 as any real backend crash. The desktop
+# spawn (and any script wrapping ``hermes serve``) cannot tell "port occupied"
+# from "backend broken". So we probe the exact bind before handing the socket
+# to uvicorn and, on conflict, emit ONE machine-readable stdout sentinel plus
+# a human hint, then exit with a distinct code.
+#
+# 75 == BSD ``EX_TEMPFAIL`` (sysexits.h) — the codebase's existing convention
+# for "transient environmental condition, not a code failure" (see
+# gateway/restart.py and kanban_db.py's quota-wall sentinel).
+PORT_IN_USE_EXIT_CODE = 75
+
+# One line, stable format, parsed by machines — mirrors the shape of the
+# HERMES_BACKEND_READY sentinel (which is NOT changed by any of this).
+_PORT_IN_USE_SENTINEL = "BACKEND_PORT_IN_USE port={port}"
+
+
+def _is_addr_in_use_error(exc: OSError) -> bool:
+ """True when ``exc`` is the platform's address-in-use bind failure."""
+ import errno
+
+ codes = {errno.EADDRINUSE, 98, 48, 10048} # POSIX, Linux, macOS, WinSock
+ if exc.errno in codes:
+ return True
+ return getattr(exc, "winerror", None) == 10048 # WSAEADDRINUSE
+
+
+def _port_bind_conflict(host: str, port: int) -> bool:
+ """Probe whether binding ``host:port`` would fail with EADDRINUSE.
+
+ ``port == 0`` (ephemeral) can never conflict — the kernel picks a free
+ port — so the probe is skipped and ``--port 0`` behaves exactly as
+ before. Any probe error other than address-in-use returns ``False`` so
+ uvicorn surfaces it with its normal diagnostics (bad host, EACCES, …).
+ """
+ if not port:
+ return False
+ import socket as _socket
+
+ family = _socket.AF_INET6 if ":" in host else _socket.AF_INET
+ try:
+ probe = _socket.socket(family, _socket.SOCK_STREAM)
+ except OSError:
+ return False
+ try:
+ # Match uvicorn's bind flags (uvicorn/config.py bind_socket) so the
+ # probe conflicts exactly when uvicorn's own bind would: SO_REUSEADDR
+ # lets TIME_WAIT remnants pass while a live LISTEN socket still fails.
+ probe.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
+ probe.bind((host, port))
+ except OSError as exc:
+ return _is_addr_in_use_error(exc)
+ except Exception:
+ return False
+ finally:
+ probe.close()
+ return False
+
+
+def _report_port_in_use(host: str, port: int) -> None:
+ """Print the machine sentinel + a human hint naming likely holders."""
+ print(_PORT_IN_USE_SENTINEL.format(port=port), flush=True)
+ print(
+ f" Port {port} on {host} is already in use — likely another "
+ "'hermes serve' / 'hermes dashboard' backend or the Hermes gateway. "
+ "Stop the other process, or pass --port <other> "
+ "(--port 0 picks a free ephemeral port).",
+ flush=True,
+ )
+
+
def start_server(
host: str = "127.0.0.1",
port: int = 9119,
@@ -19454,9 +19527,9 @@ def start_server(
# (bind port 0 → close → uvicorn rebind): the socket is held by
# uvicorn the entire time, so no other process can steal the port.
#
- # For explicit non-zero ports, if the port is taken uvicorn catches
- # OSError inside create_server() and exits with a clear error — no
- # separate preflight probe needed.
+ # For explicit non-zero ports, a taken port is detected by the #93608
+ # preflight probe below (BACKEND_PORT_IN_USE sentinel + distinct exit
+ # code); uvicorn's own bind error remains the fallback for races.
# Loopback binds are the Desktop case: a single local client, no reverse
# proxy in front. uvicorn's ws keepalive ping runs ON the same event loop
# as agent turns, and a single synchronous GIL-holding call on a worker
@@ -19511,6 +19584,16 @@ def start_server(
)
server = uvicorn.Server(config)
+ # ── #93608: machine-readable port-conflict detection ──────────────
+ # uvicorn's own bind_socket() would catch the EADDRINUSE and exit 1
+ # with a bare ERROR line — indistinguishable from "backend broken".
+ # Probe the exact bind first so a conflict surfaces as the stable
+ # BACKEND_PORT_IN_USE sentinel + a distinct exit code instead.
+ # ``--port 0`` (ephemeral) is skipped by the probe and unaffected.
+ if _port_bind_conflict(host, port):
+ _report_port_in_use(host, port)
+ raise SystemExit(PORT_IN_USE_EXIT_CODE)
+
async def _serve():
# Split startup from main_loop so we can read the bound port
# after the socket is live (ephemeral port discovery).
@@ -19650,6 +19733,15 @@ def start_server(
asyncio.run(_serve())
except KeyboardInterrupt:
return
+ except SystemExit as exc:
+ # Probe-to-bind race (#93608): another process grabbed the port
+ # between our preflight probe and uvicorn's real bind. uvicorn's
+ # bind_socket() exits 1 — re-check the bind and translate a
+ # confirmed conflict into the sentinel + distinct exit code.
+ if exc.code == 1 and _port_bind_conflict(host, port):
+ _report_port_in_use(host, port)
+ raise SystemExit(PORT_IN_USE_EXIT_CODE) from None
+ raise
return
# Windows-only path. Resolve the runner + loop factory FIRST (and fall back
@@ -19684,3 +19776,9 @@ def start_server(
asyncio.run(_serve())
except KeyboardInterrupt:
return
+ except SystemExit as exc:
+ # Same probe-to-bind race translation as the POSIX branch (#93608).
+ if exc.code == 1 and _port_bind_conflict(host, port):
+ _report_port_in_use(host, port)
+ raise SystemExit(PORT_IN_USE_EXIT_CODE) from None
+ raise
diff --git a/tests/hermes_cli/test_serve_port_in_use.py b/tests/hermes_cli/test_serve_port_in_use.py
new file mode 100644
index 00000000000..f800174f2b5
--- /dev/null
+++ b/tests/hermes_cli/test_serve_port_in_use.py
@@ -0,0 +1,203 @@
+"""#93608 — port bind conflict must be machine-readable, not a bare exit 1.
+
+The reporter's repro: something already listens on the serve port (another
+``hermes serve``, the gateway, anything) → ``hermes serve`` printed only
+uvicorn's ``ERROR: [Errno 98/10048] error while attempting to bind on
+address`` and exited 1 — indistinguishable from a broken backend for the
+desktop spawn and for scripts.
+
+Contract under test:
+
+* conflict → single stdout sentinel ``BACKEND_PORT_IN_USE port=<port>`` +
+ a human hint line + exit code 75 (EX_TEMPFAIL, the repo's existing
+ transient-condition convention) — and NO ``HERMES_BACKEND_READY``.
+* free explicit port → boots and announces ``HERMES_BACKEND_READY`` exactly
+ as before (contract untouched).
+* ``--port 0`` (ephemeral) → probe skipped, boots, announces the
+ OS-assigned port.
+"""
+
+import os
+import socket
+import subprocess
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+pytestmark = pytest.mark.skipif(
+ sys.platform == "win32", reason="POSIX serve-runner path under test"
+)
+
+
+# ---------------------------------------------------------------------------
+# Unit: the probe itself
+# ---------------------------------------------------------------------------
+
+
+def test_probe_detects_held_socket():
+ from hermes_cli.web_server import _port_bind_conflict
+
+ holder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ holder.bind(("127.0.0.1", 0))
+ holder.listen(1)
+ port = holder.getsockname()[1]
+ try:
+ assert _port_bind_conflict("127.0.0.1", port) is True
+ finally:
+ holder.close()
+
+
+def test_probe_free_port_is_clean():
+ from hermes_cli.web_server import _port_bind_conflict
+
+ probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ probe.bind(("127.0.0.1", 0))
+ port = probe.getsockname()[1]
+ probe.close()
+ assert _port_bind_conflict("127.0.0.1", port) is False
+
+
+def test_probe_skips_ephemeral_port_zero():
+ from hermes_cli.web_server import _port_bind_conflict
+
+ # port 0 can never conflict — must short-circuit False, never bind.
+ assert _port_bind_conflict("127.0.0.1", 0) is False
+
+
+def test_addr_in_use_error_classification():
+ import errno
+
+ from hermes_cli.web_server import _is_addr_in_use_error
+
+ assert _is_addr_in_use_error(OSError(errno.EADDRINUSE, "in use")) is True
+ assert _is_addr_in_use_error(OSError(98, "linux")) is True
+ assert _is_addr_in_use_error(OSError(10048, "winsock")) is True
+ assert _is_addr_in_use_error(OSError(errno.EACCES, "denied")) is False
+
+
+def test_exit_code_is_distinct_tempfail():
+ from hermes_cli.web_server import PORT_IN_USE_EXIT_CODE
+
+ assert PORT_IN_USE_EXIT_CODE == 75 # EX_TEMPFAIL — repo convention
+ assert PORT_IN_USE_EXIT_CODE != 1
+
+
+# ---------------------------------------------------------------------------
+# E2E: real start_server in a subprocess (temp HERMES_HOME)
+# ---------------------------------------------------------------------------
+
+
+def _spawn_serve(port: int, tmp_path: Path) -> subprocess.Popen:
+ home = tmp_path / "hermes_home"
+ home.mkdir(exist_ok=True)
+ env = dict(os.environ)
+ env.update(
+ HERMES_HOME=str(home),
+ HERMES_SERVE_HEADLESS="1",
+ PYTHONUNBUFFERED="1",
+ )
+ # Ensure a stray desktop-parent env can't arm the watchdog/reaper paths.
+ for k in ("HERMES_DESKTOP", "HERMES_PARENT_PID", "HERMES_PARENT_START_MARKER",
+ "HERMES_PARENT_NONCE"):
+ env.pop(k, None)
+ code = (
+ "from hermes_cli.web_server import start_server\n"
+ f"start_server(host='127.0.0.1', port={port}, open_browser=False, "
+ "headless=True)\n"
+ )
+ return subprocess.Popen(
+ [sys.executable, "-c", code],
+ cwd=str(REPO_ROOT),
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+
+
+def _read_until(proc: subprocess.Popen, token: str, timeout: float = 120.0):
+ """Collect stdout lines until ``token`` appears, process exits, or timeout."""
+ lines: list[str] = []
+ hit = threading.Event()
+
+ def _pump():
+ assert proc.stdout is not None
+ for line in proc.stdout:
+ lines.append(line)
+ if token in line:
+ hit.set()
+ return
+
+ t = threading.Thread(target=_pump, daemon=True)
+ t.start()
+ hit.wait(timeout)
+ return hit.is_set(), lines
+
+
+def test_conflict_emits_sentinel_and_exit_75(tmp_path):
+ """Reporter's exact repro shape: a real held LISTEN socket on the port."""
+ holder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ holder.bind(("127.0.0.1", 0))
+ holder.listen(1)
+ port = holder.getsockname()[1]
+ try:
+ proc = _spawn_serve(port, tmp_path)
+ try:
+ out, _ = proc.communicate(timeout=180)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ out = ""
+ pytest.fail("serve did not exit on a port conflict")
+ finally:
+ holder.close()
+
+ assert proc.returncode == 75, f"exit={proc.returncode}\n{out}"
+ assert f"BACKEND_PORT_IN_USE port={port}" in out
+ assert f"Port {port}" in out # human hint line
+ assert "HERMES_BACKEND_READY" not in out # never claimed ready
+ # exactly one machine sentinel line
+ assert out.count("BACKEND_PORT_IN_USE") == 1
+
+
+def test_free_port_boots_and_announces_ready(tmp_path):
+ probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ probe.bind(("127.0.0.1", 0))
+ port = probe.getsockname()[1]
+ probe.close()
+
+ proc = _spawn_serve(port, tmp_path)
+ try:
+ ready, lines = _read_until(proc, "HERMES_BACKEND_READY")
+ out = "".join(lines)
+ assert ready, f"no READY sentinel; output:\n{out}"
+ assert f"HERMES_BACKEND_READY port={port}" in out
+ assert "BACKEND_PORT_IN_USE" not in out
+ finally:
+ proc.terminate()
+ try:
+ proc.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+
+
+def test_ephemeral_port_zero_unaffected(tmp_path):
+ proc = _spawn_serve(0, tmp_path)
+ try:
+ ready, lines = _read_until(proc, "HERMES_BACKEND_READY")
+ out = "".join(lines)
+ assert ready, f"no READY sentinel; output:\n{out}"
+ # OS-assigned non-zero port announced
+ ready_line = next(l for l in lines if "HERMES_BACKEND_READY" in l)
+ announced = int(ready_line.strip().rsplit("port=", 1)[1])
+ assert announced > 0
+ assert "BACKEND_PORT_IN_USE" not in out
+ finally:
+ proc.terminate()
+ try:
+ proc.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ proc.kill()
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index a75f2a6e917..fe0ca434444 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -1628,6 +1628,8 @@ hermes serve [options]
Start the Hermes **backend server** — the JSON-RPC/WebSocket gateway the [desktop app](/user-guide/desktop) and remote clients connect to. It is the same server `hermes dashboard` runs, but **headless**: it never opens a browser UI. The desktop app launches its own `hermes serve` backend; use this command directly when you want a headless backend on a remote host. Accepts the same `--host` / `--port` / `--insecure` / `--skip-build` / `--stop` / `--status` options as `hermes dashboard` below (a non-loopback bind engages the same auth gate). Requires the `[web]` extra; the embedded Chat socket additionally needs `[pty]` on a POSIX host.
+**Port conflicts:** if the requested port (default `9119`) is already held by another process (e.g. a second `hermes serve` or the gateway), the command prints a machine-readable sentinel line `BACKEND_PORT_IN_USE port=<port>` to stdout, a human hint naming the likely holder, and exits with code **75** (`EX_TEMPFAIL`) instead of a generic error — so scripts and the desktop app can tell "port occupied" apart from "backend broken". Pass `--port 0` to bind a free ephemeral port (the successful boot announces the chosen port via `HERMES_BACKEND_READY port=<port>`).
+
## `hermes dashboard`
```bash