Skip to content

The agent that grows with you

fix(gateway): ensure replaces a gateway an older Hermes left running on this home

Teknium14e3689a6283
diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.py
index 99eafe1aa1f..7ae0c28ec05 100644
--- a/hermes_cli/gateway_runtime.py
+++ b/hermes_cli/gateway_runtime.py
@@ -221,9 +221,19 @@ def _update_fenced(homes) -> bool:
return False
+_REPLACE_FAILED_DETAIL = ("an older Hermes gateway owns this profile and is still running after a stop; "
+ "stop it (hermes gateway stop) and retry")
+
+
def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT_ENSURE_TIMEOUT,
idle_exit: bool = False) -> GatewayDiscovery:
- """Ensure once, never install/replace; pending remains pending at deadline.
+ """Ensure once; pending remains pending at deadline.
+
+ Never installs anything. The one owner it replaces is a gateway an older Hermes left running on
+ this install's own home (``incompatible``/``runtime_protocol``, the upgrade case): it is stopped
+ the way ``hermes gateway stop`` stops it, once, and the current one started like any absent
+ owner. Another install's or a newer Hermes's gateway stays refused, with the reason in ``detail``
+ (``hermes_cli.gateway_runtime_replace``).
A successful service command or Popen is not session readiness. After an
owner/start request is observed this invocation never launches another.
@@ -249,6 +259,7 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT
# still held for a moment after its control socket closes, which reads as "starting"), then
# start the replacement this call owes the client.
retiring = False
+ replaced = False
delay = 0.025
try:
while True:
@@ -265,6 +276,20 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT
retiring, requested, child = True, False, None
time.sleep(min(0.1, remaining(deadline)))
continue
+ if observed.state == "incompatible" and observed.reason_code == "runtime_protocol":
+ if replaced:
+ return GatewayDiscovery("incompatible", reason_code="runtime_protocol",
+ detail=_REPLACE_FAILED_DETAIL)
+ from hermes_cli import gateway_runtime_replace as replace
+ replaced = True
+ refusal = replace.replace_incompatible_owner(home, deadline=deadline)
+ if refusal is not None:
+ return GatewayDiscovery("incompatible", reason_code="runtime_protocol",
+ detail=replace.REFUSAL_DETAIL.get(refusal, _REPLACE_FAILED_DETAIL))
+ # Like an idle exit: its lock outlives its socket for a moment ("starting"); wait it
+ # out, then start the current owner this call owes the client.
+ retiring, requested, child = True, False, None
+ continue
if observed.state not in {"absent", "starting"}:
return observed
if status is not None and observed.state == "absent":
diff --git a/hermes_cli/gateway_runtime_replace.py b/hermes_cli/gateway_runtime_replace.py
new file mode 100644
index 00000000000..d0d465f4a05
--- /dev/null
+++ b/hermes_cli/gateway_runtime_replace.py
@@ -0,0 +1,145 @@
+"""Replace a gateway left running by an older Hermes on this install's own home.
+
+After an upgrade the old daemon keeps answering the home's control socket, but its ``identify`` has
+no ``runtime_protocol`` (it predates the session-authority runtime). Every client of this version
+ensures through :func:`hermes_cli.gateway_runtime.ensure_gateway_runtime` (the TUI bootstrap,
+Desktop's ``hermes gateway ensure``, ``hermes chat``), so ensure replaces that owner once, exactly as
+``hermes gateway stop`` would stop it (a planned-stop marker in the owner's home, then SIGTERM; a
+bounded wait; a start-time-guarded force kill), and then starts the current one the normal way.
+
+Refused, never stopped:
+- a gateway that speaks a NEWER runtime protocol than this client (a downgrade must not kill it);
+- a gateway of another install: its home resolves outside this install's root (a profile symlinked
+ into another HERMES root), or the process serves another home than the socket that answered;
+- anything whose ``identify`` cannot be pinned to one live process (pid/start time disagree, our
+ own process, not a gateway).
+"""
+from __future__ import annotations
+
+import os
+import time
+from pathlib import Path
+from typing import Any
+
+# Graceful drain before the guarded force kill; an idle old gateway exits in well under a second.
+_GRACEFUL_STOP_SECONDS = 10.0
+_FORCED_STOP_SECONDS = 5.0
+
+REFUSAL_DETAIL = {
+ "owner_newer": "a gateway from a newer Hermes owns this profile; update this Hermes or stop it "
+ "(hermes gateway stop)",
+ "foreign_install": "the gateway that owns this profile belongs to another Hermes install; stop it "
+ "there (hermes gateway stop)",
+ "owner_unverified": "an older Hermes gateway owns this profile but could not be verified; stop it "
+ "(hermes gateway stop) and retry",
+ "owner_did_not_exit": "an older Hermes gateway owns this profile and did not stop; stop it "
+ "(hermes gateway stop) and retry",
+ "owner_unreachable": "an older Hermes gateway owns this profile; stop it (hermes gateway stop) "
+ "and retry",
+}
+
+
+def _install_root() -> Path:
+ from hermes_constants import get_default_hermes_root
+ return Path(get_default_hermes_root()).resolve()
+
+
+def _identify(home: Path, timeout: float) -> tuple[Path, dict] | None:
+ """``(control_home, identify payload)`` of the process answering for *home*: its own socket, or
+ the default multiplexer's for a served named profile (the same order discovery uses)."""
+ from hermes_cli.gateway_runtime_discovery import query_identify
+ from hermes_cli.gateway_runtime_multiplex import multiplexer_root_for
+ for control in (home, multiplexer_root_for(home)):
+ if control is None:
+ continue
+ try:
+ return control, query_identify(control, timeout=timeout)
+ except (FileNotFoundError, ConnectionRefusedError):
+ continue
+ return None
+
+
+def _same(a: Any, b: Path) -> bool:
+ try:
+ return os.path.normcase(str(Path(a).resolve())) == os.path.normcase(str(b.resolve()))
+ except (OSError, TypeError, ValueError):
+ return False
+
+
+def _within_install(home: Path, root: Path) -> bool:
+ home = home.resolve()
+ return home == root or (home.parent == root / "profiles")
+
+
+def _verified_owner(control: Path, payload: dict) -> tuple[int, Any] | str:
+ from gateway.status import _GATEWAY_KIND, _pid_exists, get_process_start_time, start_time_fingerprints_match
+ protocol = payload.get("runtime_protocol")
+ if type(protocol) is int and protocol > 1:
+ return "owner_newer"
+ if not _within_install(control, _install_root()) or not _same(payload.get("hermes_home"), control):
+ return "foreign_install"
+ pid, recorded = payload.get("pid"), payload.get("start_time")
+ if (payload.get("kind") != _GATEWAY_KIND or type(pid) is not int or pid <= 1
+ or pid in {os.getpid(), os.getppid()} or recorded is None or not _pid_exists(pid)):
+ return "owner_unverified"
+ current = get_process_start_time(pid)
+ try:
+ if current is None or not start_time_fingerprints_match(recorded, current):
+ return "owner_unverified"
+ except (TypeError, ValueError):
+ return "owner_unverified"
+ return pid, current
+
+
+def _write_planned_stop(control: Path, pid: int, start_time: Any) -> None:
+ """The marker ``hermes gateway stop`` writes, in the OWNER's home (it reads its own), so the old
+ gateway exits as a planned stop: clean exit, ``stopped`` persisted, no supervisor revival."""
+ from gateway.status import _PLANNED_STOP_MARKER_FILENAME, _utc_now_iso, _write_marker
+ _write_marker(control / _PLANNED_STOP_MARKER_FILENAME, {
+ "target_pid": pid, "target_start_time": start_time,
+ "stopper_pid": os.getpid(), "written_at": _utc_now_iso(),
+ })
+
+
+def _wait_gone(pid: int, seconds: float) -> bool:
+ from gateway.status import _pid_exists
+ end = time.monotonic() + max(seconds, 0.0)
+ while _pid_exists(pid):
+ if time.monotonic() >= end:
+ return False
+ time.sleep(0.1)
+ return True
+
+
+def replace_incompatible_owner(home: Path, *, deadline: float) -> str | None:
+ """Stop the older-Hermes gateway answering for *home*; None once it is gone, else a refusal code
+ (see :data:`REFUSAL_DETAIL`). Never starts anything: the caller's ensure loop does that."""
+ from gateway.status import terminate_pid
+ budget = deadline - time.monotonic()
+ if budget <= 0:
+ return "owner_unreachable"
+ try:
+ found = _identify(home, timeout=min(2.0, budget))
+ except Exception:
+ return "owner_unreachable"
+ if found is None:
+ return None # it is already gone: nothing to replace
+ control, payload = found
+ verdict = _verified_owner(control, payload)
+ if isinstance(verdict, str):
+ return verdict
+ pid, start_time = verdict
+ _write_planned_stop(control, pid, start_time)
+ graceful = min(_GRACEFUL_STOP_SECONDS, max(deadline - time.monotonic() - _FORCED_STOP_SECONDS, 1.0))
+ try:
+ if os.name != "nt":
+ # Windows has no SIGTERM for an asyncio loop: the marker watcher IS its graceful stop.
+ terminate_pid(pid, expected_start_time=start_time)
+ if _wait_gone(pid, graceful):
+ return None
+ terminate_pid(pid, force=True, expected_start_time=start_time)
+ except ProcessLookupError:
+ return None
+ except (PermissionError, OSError):
+ return "owner_did_not_exit" if not _wait_gone(pid, 0) else None
+ return None if _wait_gone(pid, _FORCED_STOP_SECONDS) else "owner_did_not_exit"
diff --git a/tests/hermes_cli/test_gateway_runtime_replace_incompatible.py b/tests/hermes_cli/test_gateway_runtime_replace_incompatible.py
new file mode 100644
index 00000000000..c91657cb09d
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_runtime_replace_incompatible.py
@@ -0,0 +1,171 @@
+"""An owner from an older Hermes on the SAME home is replaced by ensure, never reported forever.
+
+Upgrade path (Windows Desktop report, TUI "retrying in 30s" forever): the pre-protocol gateway a user
+left running answers ``identify`` without ``runtime_protocol``. Every client of this install ensures
+through ``ensure_gateway_runtime`` (TUI bootstrap, Desktop's ``hermes gateway ensure``), so that is
+where the old owner is stopped the way ``hermes gateway stop`` stops it and the current one started.
+A gateway of another install (a home that resolves outside this install's root) stays refused.
+"""
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli import gateway_runtime as runtime
+from hermes_cli import gateway_runtime_replace as replace
+from hermes_cli.gateway_runtime import GatewayDiscovery, GatewayEndpoint
+
+
+def _ready(home: Path) -> GatewayDiscovery:
+ return GatewayDiscovery("ready", GatewayEndpoint(
+ profile_id=str(home), instance_id="new", authority_epoch=1, runtime_protocol=1,
+ api_origin="http://127.0.0.1:1", supervisor="none", capabilities=frozenset({"session-authority-v1"})))
+
+
+def home(tmp_path, monkeypatch):
+ home = (tmp_path / ".hermes").resolve()
+ home.mkdir()
+ monkeypatch.setattr(runtime, "_update_fenced", lambda homes: False)
+ return home
+
+
+def _script(monkeypatch, verdicts):
+ seen = []
+
+ def discover(h, timeout=2.0):
+ seen.append(h)
+ return verdicts.pop(0) if len(verdicts) > 1 else verdicts[0]
+
+ monkeypatch.setattr(runtime, "discover_gateway_endpoint", discover)
+ return seen
+
+
+def test_ensure_replaces_an_incompatible_owner_of_this_home(home, monkeypatch):
+ stopped = []
+ _script(monkeypatch, [GatewayDiscovery("incompatible", reason_code="runtime_protocol"),
+ GatewayDiscovery("absent"), _ready(home)])
+ monkeypatch.setattr(replace, "replace_incompatible_owner",
+ lambda h, *, deadline: stopped.append(h) or None)
+ from hermes_cli import gateway_runtime_service as service, gateway_runtime_start as start
+ monkeypatch.setattr(service, "discover_existing_gateway_service", lambda h, deadline: None)
+ monkeypatch.setattr(start, "spawn_unmanaged_gateway",
+ lambda h, deadline, idle_exit=False: SimpleNamespace(poll=lambda: None, pid=1))
+ monkeypatch.setattr(start, "stdio_log_size", lambda h: 0)
+
+ result = runtime.ensure_gateway_runtime(home, timeout=5)
+
+ assert result.state == "ready"
+ assert stopped == [home]
+
+
+def test_a_current_protocol_owner_without_session_authority_is_not_replaced(home, monkeypatch):
+ """Only the upgrade leftover (no/old ``runtime_protocol``) is replaced; a current owner that
+ lacks a capability is a configuration verdict, reported as before."""
+ calls = []
+ _script(monkeypatch, [GatewayDiscovery("incompatible", reason_code="session_authority_unavailable")])
+ monkeypatch.setattr(replace, "replace_incompatible_owner",
+ lambda h, *, deadline: calls.append(h) or None)
+ result = runtime.ensure_gateway_runtime(home, timeout=5)
+ assert result.reason_code == "session_authority_unavailable" and calls == []
+
+
+def test_ensure_replaces_at_most_once_then_reports(home, monkeypatch):
+ calls = []
+ _script(monkeypatch, [GatewayDiscovery("incompatible", reason_code="runtime_protocol")])
+ monkeypatch.setattr(replace, "replace_incompatible_owner",
+ lambda h, *, deadline: calls.append(h) or None)
+
+ result = runtime.ensure_gateway_runtime(home, timeout=5)
+
+ assert (result.state, result.reason_code) == ("incompatible", "runtime_protocol")
+ assert calls == [home]
+
+
+def test_a_refused_replacement_is_reported_with_its_reason(home, monkeypatch):
+ _script(monkeypatch, [GatewayDiscovery("incompatible", reason_code="runtime_protocol")])
+ monkeypatch.setattr(replace, "replace_incompatible_owner",
+ lambda h, *, deadline: "foreign_install")
+
+ result = runtime.ensure_gateway_runtime(home, timeout=5)
+
+ assert (result.state, result.reason_code) == ("incompatible", "runtime_protocol")
+ assert result.detail and "another Hermes install" in result.detail
+
+
+# --- the stop itself -------------------------------------------------------------------------------
+
+def _owner_payload(home: Path, pid: int, start_time):
+ # MAIN's identify: no runtime_protocol, kind/pid/start_time/hermes_home from its pid record.
+ return {"protocol": 1, "kind": "hermes-gateway", "pid": pid, "start_time": start_time,
+ "hermes_home": str(home), "supervisor": "manual"}
+
+
+def owner(home, monkeypatch):
+ """A live process standing in for the old daemon; the replacement must SIGTERM exactly it."""
+ import subprocess
+ import sys
+ from gateway.status import get_process_start_time
+ proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ monkeypatch.setattr(replace, "_identify", lambda h, timeout: (home, _owner_payload(
+ home, proc.pid, get_process_start_time(proc.pid))))
+ yield proc
+ if proc.poll() is None:
+ proc.kill()
+ proc.wait()
+
+
+def test_replacement_stops_the_verified_old_owner_with_a_planned_stop(home, owner, monkeypatch):
+ import time
+ monkeypatch.setattr(replace, "_install_root", lambda: home)
+ refusal = replace.replace_incompatible_owner(home, deadline=time.monotonic() + 15)
+ assert refusal is None
+ assert owner.wait(5) is not None
+ marker = home / ".gateway-planned-stop.json"
+ # Written for the old owner's own home, so it exits as a planned stop (no supervisor revival).
+ assert marker.exists() or owner.returncode is not None
+
+
+def test_replacement_refuses_a_recycled_pid(home, owner, monkeypatch):
+ import time
+ monkeypatch.setattr(replace, "_install_root", lambda: home)
+ monkeypatch.setattr(replace, "_identify", lambda h, timeout: (home, _owner_payload(home, owner.pid, 1)))
+ assert replace.replace_incompatible_owner(home, deadline=time.monotonic() + 5) == "owner_unverified"
+ assert owner.poll() is None
+
+
+def test_replacement_refuses_another_installs_owner(tmp_path, home, owner, monkeypatch):
+ """A home that resolves outside this install's root (a profile symlinked into another install)
+ is that install's: its gateway is never stopped from here."""
+ import time
+ other_root = (tmp_path / "other").resolve()
+ other_root.mkdir()
+ monkeypatch.setattr(replace, "_install_root", lambda: other_root)
+ assert replace.replace_incompatible_owner(home, deadline=time.monotonic() + 5) == "foreign_install"
+ assert owner.poll() is None
+
+
+def test_replacement_refuses_an_owner_serving_another_home(tmp_path, home, owner, monkeypatch):
+ import time
+ from gateway.status import get_process_start_time
+ elsewhere = (tmp_path / "elsewhere").resolve()
+ monkeypatch.setattr(replace, "_install_root", lambda: home)
+ monkeypatch.setattr(replace, "_identify", lambda h, timeout: (home, _owner_payload(
+ elsewhere, owner.pid, get_process_start_time(owner.pid))))
+ assert replace.replace_incompatible_owner(home, deadline=time.monotonic() + 5) == "foreign_install"
+ assert owner.poll() is None
+
+
+def test_replacement_never_targets_itself(home, monkeypatch):
+ import time
+ monkeypatch.setattr(replace, "_install_root", lambda: home)
+ monkeypatch.setattr(replace, "_identify", lambda h, timeout: (home, _owner_payload(home, os.getpid(), 1)))
+ assert replace.replace_incompatible_owner(home, deadline=time.monotonic() + 5) == "owner_unverified"