Skip to content

The agent that grows with you

fix(gateway): read a standalone host's refusal like `gateway status` does, once per ensure pass

Teknium3a99ad6b67e1
diff --git a/hermes_cli/gateway_multiplex_mode.py b/hermes_cli/gateway_multiplex_mode.py
index 885369f374f..8362563c801 100644
--- a/hermes_cli/gateway_multiplex_mode.py
+++ b/hermes_cli/gateway_multiplex_mode.py
@@ -358,21 +358,30 @@ def standalone_warning_lines(decision: MultiplexDecision, unserved: Optional[lis
return _box(body)
-def recorded_standalone_warning_lines() -> list[str]:
- """Same box, rebuilt from the live gateway's ``gateway_state.json`` for processes that did not
- make the decision (``hermes update``'s summary, ``hermes gateway status``)."""
+def recorded_standalone_reason(state_path: Path | None = None) -> str | None:
+ """The guard refusal a LIVE standalone gateway published in its ``gateway_state.json`` (this
+ home's, or *state_path*), else ``None``. A stopped, failed or dead record's reason is history."""
try:
from gateway.status import read_runtime_status, runtime_status_pid_is_live
- record = read_runtime_status() or {}
+ record = read_runtime_status(state_path) or {}
if record.get("gateway_state") in (None, "stopped", "startup_failed"):
- return []
+ return None
# Liveness is the state + a live PID, never the heartbeat: a paused or wedged gateway is
# still the standalone process the box warns about (#120991).
if not runtime_status_pid_is_live(record):
- return []
+ return None
reason = record.get("multiplex_standalone_reason")
- except Exception:
- return []
+ # The readers already absorb a missing/garbled file; what is left is a hostile record shape
+ # (a non-object, a PID too large for the OS) or a liveness probe's OS error.
+ except (OSError, ValueError, TypeError, AttributeError, OverflowError):
+ return None
+ return str(reason) if isinstance(reason, str) and reason else None
+
+
+def recorded_standalone_warning_lines() -> list[str]:
+ """Same box, rebuilt from the live gateway's ``gateway_state.json`` for processes that did not
+ make the decision (``hermes update``'s summary, ``hermes gateway status``)."""
+ reason = recorded_standalone_reason()
if not reason:
return []
- return standalone_warning_lines(MultiplexDecision(False, "guard", str(reason)))
+ return standalone_warning_lines(MultiplexDecision(False, "guard", reason))
diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.py
index f54cb472a68..77081dcc5dd 100644
--- a/hermes_cli/gateway_runtime.py
+++ b/hermes_cli/gateway_runtime.py
@@ -129,35 +129,28 @@ def control_home_for(home: Path, endpoint: GatewayEndpoint | None) -> Path:
return home
-def _multiplexer_starting(home: Path) -> bool:
- """The root's reservation is pending AND that root's boot policy would serve *home*. A
- ``gateway.standalone: true`` secondary is never served by it, so a reserved (or ready) root
- must not make its client wait out the deadline instead of starting the profile's own owner."""
+def _starting_multiplexer_root(home: Path) -> Path | None:
+ """The root whose reservation is pending AND whose boot policy would serve *home*, else None.
+ A ``gateway.standalone: true`` secondary is never served by it, so a reserved (or ready) root
+ must not make its client wait out the deadline instead of starting the profile's own owner.
+ One uncached config parse plus a lock probe: call it once per ensure iteration."""
from hermes_cli.gateway_runtime_discovery import missing_owner_state
from hermes_cli.gateway_runtime_multiplex import implied_host_root
root = implied_host_root(home)
- return root is not None and missing_owner_state(root) == "starting"
+ return root if root is not None and missing_owner_state(root) == "starting" else None
-def _standalone_multiplexer_reason(home: Path) -> str | None:
- """Return a live host's reason for not serving *home*, if it has one.
+def _standalone_multiplexer_reason(root: Path) -> str | None:
+ """A live host's reason for not serving its named profiles, if it published one.
A held root lock ordinarily means that a named profile should wait for its
multiplexer. A host which published a guard refusal is different: it is a
- standalone gateway and can never add the named profile during that boot.
+ standalone gateway and can never add the named profile during that boot. Read
+ with the same liveness rules as ``hermes gateway status``'s standalone box.
"""
- from hermes_cli.gateway_runtime_discovery import missing_owner_state
- from hermes_cli.gateway_runtime_multiplex import implied_host_root
-
- root = implied_host_root(home)
- if root is None or missing_owner_state(root) != "starting":
- return None
- from gateway.status import read_runtime_status, runtime_status_pid_is_live
- record = read_runtime_status(root / "gateway_state.json")
- if not runtime_status_pid_is_live(record):
- return None
- reason = record.get("multiplex_standalone_reason") if isinstance(record, dict) else None
- return str(reason)[:500] if isinstance(reason, str) and reason else None
+ from hermes_cli.gateway_multiplex_mode import recorded_standalone_reason
+ reason = recorded_standalone_reason(root / "gateway_state.json")
+ return reason[:500] if reason else None
def _parked_by_multiplexer(payload: dict, home: Path) -> GatewayDiscovery | None:
@@ -347,11 +340,12 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT
requested = True
if observed.state == "absent":
retiring = False
- if observed.state == "absent" and not requested and (reason := _standalone_multiplexer_reason(home)):
+ reserved = _starting_multiplexer_root(home) if observed.state == "absent" and not requested else None
+ if reserved is not None and (reason := _standalone_multiplexer_reason(reserved)):
return GatewayDiscovery("inaccessible", reason_code="profile_parked", detail=reason)
# A default multiplexer that is still starting will serve this named profile; never
# spawn a competing per-profile daemon while its reservation is pending.
- if observed.state == "absent" and not requested and _multiplexer_starting(home):
+ if reserved is not None:
requested = True
if observed.state == "absent" and not requested:
# A named profile the default multiplexer serves has no daemon of its own: start
diff --git a/tests/hermes_cli/test_gateway_runtime_ensure.py b/tests/hermes_cli/test_gateway_runtime_ensure.py
index f3716295923..8eefb2f03f6 100644
--- a/tests/hermes_cli/test_gateway_runtime_ensure.py
+++ b/tests/hermes_cli/test_gateway_runtime_ensure.py
@@ -437,28 +437,61 @@ def test_reserved_root_never_suppresses_a_standalone_profile_start(tmp_path, mon
assert spawned == [home.resolve()]
-def test_ensure_reports_a_standalone_host_reason_for_an_unserved_named_profile(tmp_path, monkeypatch):
- """A live standalone host cannot later add this profile, so do not wait on its root lock."""
- from gateway import status
+def _standalone_host(tmp_path, monkeypatch, record):
+ """A named profile whose root holds its gateway lock and has written *record* (or nothing)
+ to the root's real gateway_state.json; returns (home, spawned targets)."""
from hermes_cli import gateway_runtime as runtime, gateway_runtime_discovery as discovery
+ from hermes_cli import gateway_runtime_service as service, gateway_runtime_start as start
root = tmp_path / ".hermes"
home = root / "profiles" / "alpha"
home.mkdir(parents=True, mode=0o700)
+ if record is not None:
+ (root / "gateway_state.json").write_text(json.dumps(record), encoding="utf-8")
+ spawned = []
monkeypatch.setattr(runtime, "_update_fenced", lambda homes: False)
monkeypatch.setattr(runtime, "discover_gateway_endpoint", lambda *a, **k: runtime.GatewayDiscovery("absent"))
- monkeypatch.setattr(discovery, "missing_owner_state", lambda path: "starting")
- monkeypatch.setattr(status, "read_runtime_status", lambda path: {
- "gateway_state": "running",
- "served_profiles": [],
- "multiplex_standalone_reason": "duplicate Telegram token; run hermes gateway migrate --multiplex",
- })
- monkeypatch.setattr(status, "runtime_status_pid_is_live", lambda record: True)
+ monkeypatch.setattr(discovery, "missing_owner_state", lambda path: "starting" if Path(path).resolve() == root.resolve() else "absent")
+ monkeypatch.setattr(service, "discover_existing_gateway_service", lambda *a, **k: None)
+ monkeypatch.setattr(start, "spawn_unmanaged_gateway", lambda target, **k: spawned.append(Path(target)))
+ return home, spawned
+
+
+_REASON = "duplicate Telegram token; run hermes gateway migrate --multiplex"
+
+
+def test_ensure_reports_a_standalone_host_reason_for_an_unserved_named_profile(tmp_path, monkeypatch):
+ """A live standalone host cannot later add this profile, so do not wait on its root lock: its
+ reason is read from the root's real gateway_state.json (path and key included)."""
+ from hermes_cli import gateway_runtime as runtime
+
+ home, spawned = _standalone_host(tmp_path, monkeypatch, {
+ "gateway_state": "running", "pid": os.getpid(), "served_profiles": [],
+ "multiplex_standalone_reason": _REASON})
result = runtime.ensure_gateway_runtime(home, timeout=1)
- assert (result.state, result.reason_code) == ("inaccessible", "profile_parked")
- assert result.detail == "duplicate Telegram token; run hermes gateway migrate --multiplex"
+ assert (result.state, result.reason_code, result.detail) == ("inaccessible", "profile_parked", _REASON)
+ assert spawned == []
+
+
[email protected]("record", [
+ None, # the host has not written its state yet
+ {"gateway_state": "running", "pid": os.getpid()}, # a multiplexer: no refusal
+ {"gateway_state": "stopped", "pid": os.getpid(), "multiplex_standalone_reason": _REASON},
+ {"gateway_state": "running", "pid": 999_999_999, "multiplex_standalone_reason": _REASON},
+], ids=["no-state", "no-reason", "stopped", "dead-pid"])
+def test_a_reserved_root_without_a_live_refusal_is_still_awaited(tmp_path, monkeypatch, record):
+ """A held root lock with no LIVE standalone refusal is a multiplexer still starting: the named
+ profile waits for it (never parked on a stale reason, never a competing per-profile spawn)."""
+ from hermes_cli import gateway_runtime as runtime
+
+ home, spawned = _standalone_host(tmp_path, monkeypatch, record)
+
+ result = runtime.ensure_gateway_runtime(home, timeout=0.5)
+
+ assert (result.state, result.reason_code) == ("starting", "deadline")
+ assert spawned == []
@pytest.mark.platforms("linux", "macos")