Skip to content

The agent that grows with you

fix(gateway): keep the host's own record whole on unscoped /api/status

unsupportedpastelse6ec18fba62a
diff --git a/gateway/status.py b/gateway/status.py
index a489555698f..068c84d554d 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -1258,8 +1258,8 @@ def derive_gateway_drainable(*, gateway_running: bool, gateway_state: Any) -> bo
@dataclass(frozen=True)
class GatewayLiveness:
"""Resolved gateway liveness for one dashboard surface. ``source``: which ladder rung answered
- (logging/tests only -- never branch product behavior on it). ``probe_error``: a rung raised;
- lets fail-open callers tell "down" from "unknown"."""
+ (logging/tests; product code reads it only via ``status_served.local_liveness_pid``).
+ ``probe_error``: a rung raised; lets fail-open callers tell "down" from "unknown"."""
running: bool
pid: Optional[int]
diff --git a/gateway/status_served.py b/gateway/status_served.py
new file mode 100644
index 00000000000..1225a0b1e8a
--- /dev/null
+++ b/gateway/status_served.py
@@ -0,0 +1,47 @@
+"""Which runtime record describes a profile the host multiplexer may serve.
+
+One rule for ``/api/status`` and the messaging card so the two surfaces never pick different records
+for the same profile. Read-only: it selects and projects existing ``gateway_state.json`` records and
+writes nothing. ``gateway.status`` is resolved at call time so its test seams
+(``monkeypatch.setattr(gateway.status, ...)``) still intercept.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Optional
+
+
+def local_liveness_pid(liveness: Any) -> Optional[int]:
+ """``liveness.pid`` when it was proven on THIS host; None for a health-probe answer, whose PID
+ belongs to the remote container and may collide with an unrelated local one."""
+ return None if liveness.source == "health" else liveness.pid
+
+
+def served_profile_runtime(
+ home: Path, own_runtime: Optional[dict[str, Any]], *, gateway_pid: Optional[int] = None
+) -> Optional[dict[str, Any]]:
+ """The multiplexer's record projected onto ``home``'s profile (bare platform keys, the shape a
+ standalone gateway writes) when it is that profile's live runtime record, else None.
+
+ - ``own_runtime`` wins whenever it proves a live gateway of ``home`` -- an own ``--force`` one, or
+ the host's own record on the host itself, which must stay whole so other profiles'
+ ``<profile>:<platform>`` failures remain visible there;
+ - a missing/unreadable multiplexer record (``(pid, {})``) is no record;
+ - ``gateway_pid`` (a PID the caller proved on this host) must BE the multiplexer, so a gateway of
+ the profile's own holding its lock keeps its record.
+ """
+ from gateway import status
+
+ if own_runtime is not None and status.get_runtime_status_running_pid(own_runtime, expected_home=home) is not None:
+ return None
+ served = status.multiplexer_liveness_for_profile(home)
+ if served is None or not served[1]:
+ return None
+ mux_pid, record = served
+ if gateway_pid is not None and mux_pid != gateway_pid:
+ return None
+ # Fold on the profile NAME, never ``home.name``: the default root's basename is ``.hermes`` (or
+ # any custom HERMES_HOME), so its flat keys never matched (#123088).
+ name = status.profile_name_for_home(home) or "default"
+ return {**record, "platforms": status.profile_platforms_from_multiplexer(record, name)}
diff --git a/hermes_cli/web_routers/messaging.py b/hermes_cli/web_routers/messaging.py
index 00c4475baf0..f146f692045 100644
--- a/hermes_cli/web_routers/messaging.py
+++ b/hermes_cli/web_routers/messaging.py
@@ -21,9 +21,7 @@ from typing import Any, Optional
from fastapi import APIRouter, HTTPException
-from gateway.status import (
- multiplexer_liveness_for_profile, profile_name_for_home, profile_platforms_from_multiplexer,
- resolve_gateway_liveness, retained_gateway_state)
+from gateway.status import resolve_gateway_liveness, retained_gateway_state
from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_cli.config import OPTIONAL_ENV_VARS, get_env_path
from hermes_constants import get_process_hermes_home
@@ -61,6 +59,7 @@ _gateway_subcommand = late("_gateway_subcommand", "hermes_cli.web_server_gateway
_probe_gateway_health = late("_probe_gateway_health", "hermes_cli.web_server_gateway")
get_running_pid_cached = late("get_running_pid_cached", "gateway.status")
get_runtime_status_running_pid = late("get_runtime_status_running_pid", "gateway.status")
+served_profile_runtime = late("served_profile_runtime", "gateway.status_served")
_GATEWAY_HEALTH_URL = LateState("_GATEWAY_HEALTH_URL")
# Display labels for env vars not in OPTIONAL_ENV_VARS (bridge toggles, Twilio, Email, ...)
# so the UI can still render a friendly label. Rows: (key, description, prompt, extra flags).
@@ -303,16 +302,7 @@ def _platform_payloads(scoped_dir: Optional[Path], entries) -> list[dict[str, An
# so the two surfaces cannot disagree. Unscoped, the profile is the process's own home (a pooled
# ``hermes --profile X serve``).
own_home = scoped_dir if scoped_dir is not None else get_process_hermes_home()
- if (
- runtime is None
- or get_runtime_status_running_pid(runtime, expected_home=own_home) is None
- ):
- served = multiplexer_liveness_for_profile(own_home)
- if served is not None:
- # Fold on the profile NAME, not ``own_home.name``: the default root's basename is
- # ``.hermes`` (or any custom HERMES_HOME), so its flat keys never matched (#123088).
- served_name = profile_name_for_home(own_home) or "default"
- runtime = {**served[1], "platforms": profile_platforms_from_multiplexer(served[1], served_name)}
+ runtime = served_profile_runtime(own_home, runtime) or runtime
return [_messaging_platform_payload(entry, env_on_disk, runtime, scoped=scoped_dir is not None, profile_home=scoped_dir)
for entry in entries]
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index ae72114b93a..3315ff62ec0 100644
--- a/hermes_cli/web_routers/status.py
+++ b/hermes_cli/web_routers/status.py
@@ -20,9 +20,10 @@ from starlette.concurrency import run_in_threadpool
from fastapi import HTTPException, Request
from gateway.status import (
derive_gateway_busy, derive_gateway_drainable, normalize_updated_at, parse_active_agents,
- multiplexer_liveness_for_profile, profile_platforms_from_multiplexer, resolve_gateway_liveness,
+ profile_platforms_from_multiplexer, resolve_gateway_liveness,
retained_gateway_state,
runtime_status_heartbeat_age_s, runtime_status_is_stale)
+from gateway.status_served import local_liveness_pid
from hermes_cli import __release_date__
from hermes_cli.config import get_config_path, get_env_path
from hermes_cli.version_info import get_version_info
@@ -55,6 +56,7 @@ _profile_cli_args = late("_profile_cli_args", "hermes_cli.web_server_profiles")
get_install_id = late("get_install_id")
get_running_pid_cached = late("get_running_pid_cached", "gateway.status")
get_runtime_status_running_pid = late("get_runtime_status_running_pid", "gateway.status")
+served_profile_runtime = late("served_profile_runtime", "gateway.status_served")
load_config = late("load_config", "hermes_cli.config")
read_runtime_status = late("read_runtime_status", "gateway.status")
_open_session_db_for_profile = late("_open_session_db_for_profile", "hermes_cli.web_server_sessions")
@@ -311,33 +313,28 @@ async def _resolve_gateway_status(profile_dir: Optional[Path], health_url) -> di
runtime = local_runtime
if runtime is None and remote_health_body and remote_health_body.get("gateway_state"):
runtime = remote_health_body
- mux_runtime = liveness.runtime
- if mux_runtime is None and gateway_running:
+ # Unscoped, the profile is the process's own home (a pooled ``hermes --profile X serve``).
+ own_home = profile_dir or get_process_hermes_home()
+ if liveness.runtime is not None:
+ # Served by the multiplexer: its record is this profile's runtime, with the profile's own
+ # adapters under ``<profile>:<platform>`` re-keyed to the standalone shape.
+ # Fold on the profile NAME, never ``profile_dir.name``: ``?profile=default`` resolves the
+ # root itself, whose basename (``.hermes``) matched nothing and read as a named id (#123088).
+ served_name = profile_name_for_home(own_home)
+ runtime = {**liveness.runtime,
+ "platforms": profile_platforms_from_multiplexer(liveness.runtime, served_name or "")}
+ elif local_liveness_pid(liveness) is not None:
# The PID rung answers before the multiplexer rung, and a served profile's gateway.lock is
# held by the multiplexer itself, so the ladder returns without its record while the
- # profile's own gateway_state.json may be a retired standalone gateway's (#139080). When the
- # lock holder IS the multiplexer serving this profile, its record is the live one; a
- # profile's own (--force) gateway holds the lock under a different PID and keeps its record.
+ # profile's own gateway_state.json may be a retired standalone gateway's (#139080). The
+ # shared rule (also the messaging card's) picks the multiplexer record only when the lock
+ # holder IS the multiplexer and the profile's own record proves no live gateway.
try:
- # Unscoped, the profile is the process's own home (a named `hermes -p X serve`).
- served = await run_in_threadpool(multiplexer_liveness_for_profile,
- profile_dir or get_process_hermes_home())
+ runtime = await run_in_threadpool(
+ served_profile_runtime, own_home, local_runtime, gateway_pid=local_liveness_pid(liveness)) or runtime
except Exception: # health: allow BLE001 -- status route must never 500; traceback is logged
- # A failed lookup keeps the profile's own record. A missing multiplexer record does
- # not raise: the helper returns (pid, {}), which still replaces it on a PID match.
+ # A failed lookup keeps the profile's own record.
_log.warning("/api/status multiplexer record lookup failed", exc_info=True)
- served = None
- if served is not None and served[0] == liveness.pid:
- mux_runtime = served[1]
- if mux_runtime is not None:
- # Served by the multiplexer: its record is this profile's runtime, with the profile's own
- # adapters under ``<profile>:<platform>`` re-keyed to the standalone shape. Unscoped, the
- # profile is the process's own home (a pooled ``hermes --profile X serve``).
- # Fold on the profile NAME, never ``profile_dir.name``: ``?profile=default`` resolves the
- # root itself, whose basename (``.hermes``) matched nothing and read as a named id (#123088).
- served_name = profile_name_for_home(profile_dir or get_process_hermes_home())
- runtime = {**mux_runtime,
- "platforms": profile_platforms_from_multiplexer(mux_runtime, served_name or "")}
gateway_state = None
gateway_platforms: dict = {}
@@ -372,15 +369,15 @@ async def _resolve_gateway_status(profile_dir: Optional[Path], health_url) -> di
if gateway_running and gateway_state is None and remote_health_body is not None:
gateway_state = "running"
- # ``mux_runtime`` is set only when the shared multiplexer answered for a served profile: its
- # gateway IS that process, so name every bot a restart would blip ("default, alpha, beta").
- served = (mux_runtime or {}).get("served_profiles")
+ # A live multiplexer's record (the host's own, or the one serving this profile) names every
+ # profile a restart would blip ("default, alpha, beta"); a standalone gateway's names none.
+ shared_with = (runtime or {}).get("served_profiles") if gateway_running else None
return {
"runtime": runtime, "gateway_running": gateway_running, "gateway_pid": liveness.pid,
"gateway_state": gateway_state, "gateway_platforms": gateway_platforms,
"gateway_exit_reason": gateway_exit_reason, "gateway_updated_at": gateway_updated_at,
"gateway_heartbeat_stale_s": gateway_heartbeat_stale_s,
- "gateway_shared_with": [str(p) for p in served] if isinstance(served, list) else None}
+ "gateway_shared_with": [str(p) for p in shared_with] if isinstance(shared_with, list) else None}
def _auth_gate_status() -> dict[str, Any]:
diff --git a/tests/hermes_cli/test_served_profile_mirror_platforms.py b/tests/hermes_cli/test_served_profile_mirror_platforms.py
index e10c9327ee9..d1c6bda27b3 100644
--- a/tests/hermes_cli/test_served_profile_mirror_platforms.py
+++ b/tests/hermes_cli/test_served_profile_mirror_platforms.py
@@ -116,7 +116,7 @@ def test_messaging_card_for_the_default_home_rekeys_by_the_profile_not_the_dirna
# A launch-service gateway's record fails the own-rung argv check (inline ``-c``), so the card
# falls through to the multiplexer rung — mirrored here by an absent own record.
monkeypatch.setattr(messaging, "read_runtime_status", lambda *a, **k: None)
- monkeypatch.setattr(messaging, "multiplexer_liveness_for_profile", lambda home: (os.getpid(), record))
+ monkeypatch.setattr(status, "multiplexer_liveness_for_profile", lambda home: (os.getpid(), record))
monkeypatch.setattr(status, "_read_process_cmdline", lambda pid: "hermes gateway run")
monkeypatch.setattr(messaging, "_platform_enablement", lambda *a, **k: (True, True, None))
entry = {"id": "telegram", "name": "Telegram", "description": "", "docs_url": "", "env_vars": [],
diff --git a/tests/hermes_cli/test_web_server_gateway_topology.py b/tests/hermes_cli/test_web_server_gateway_topology.py
index 366ecc1133c..c052bed0631 100644
--- a/tests/hermes_cli/test_web_server_gateway_topology.py
+++ b/tests/hermes_cli/test_web_server_gateway_topology.py
@@ -460,10 +460,10 @@ class TestStatusEndpointTopology:
status_router, "resolve_gateway_liveness",
lambda **kwargs: GatewayLiveness(running=True, pid=lock_pid, source="pid"),
)
- monkeypatch.setattr(
- status_router, "multiplexer_liveness_for_profile",
- lambda home: (mux_pid, mux_runtime) if home == profile else None,
- )
+ def _lookup(home):
+ return (mux_pid, mux_runtime) if home == profile else None
+
+ monkeypatch.setattr(_gw_status, "multiplexer_liveness_for_profile", _lookup)
monkeypatch.setattr(_web_server_gateway, "_load_configured_gateway_platforms", lambda: {"telegram"})
def test_profile_scoped_status_uses_multiplexer_record_when_lock_names_it(self, monkeypatch, tmp_path):
@@ -550,8 +550,6 @@ class TestStatusEndpointTopology:
def test_profile_scoped_status_keeps_own_record_when_multiplexer_lookup_raises(self, monkeypatch, tmp_path):
# The multiplexer lookup is optional: a failure there must not 500 the status route or
# drop the record the ladder already selected.
- import hermes_cli.web_routers.status as status_router
-
self._scope_to_served_profile(
monkeypatch, tmp_path,
own_runtime={"gateway_state": "running", "platforms": {"telegram": {"state": "connected"}}},
@@ -561,7 +559,7 @@ class TestStatusEndpointTopology:
def _boom(home):
raise OSError("unreadable multiplexer record")
- monkeypatch.setattr(status_router, "multiplexer_liveness_for_profile", _boom)
+ monkeypatch.setattr(_gw_status, "multiplexer_liveness_for_profile", _boom)
resp = self.client.get("/api/status", params={"profile": "coder"})
@@ -571,6 +569,110 @@ class TestStatusEndpointTopology:
assert data["gateway_platforms"]["telegram"]["state"] == "connected"
assert data["gateway_shared_with"] is None
+ def test_profile_scoped_status_keeps_own_record_when_multiplexer_record_is_missing(self, monkeypatch, tmp_path):
+ # A missing/unreadable multiplexer gateway_state.json comes back as (pid, {}): that is no
+ # record, so it must not replace the profile's own one with an empty platform map.
+ self._scope_to_served_profile(
+ monkeypatch, tmp_path,
+ own_runtime={"gateway_state": "running", "platforms": {"telegram": {"state": "connected"}}},
+ lock_pid=4242, mux_pid=4242, mux_runtime={},
+ )
+
+ resp = self.client.get("/api/status", params={"profile": "coder"})
+
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["gateway_platforms"]["telegram"]["state"] == "connected"
+ assert data["gateway_shared_with"] is None
+
+ def test_remote_health_liveness_never_borrows_the_local_multiplexer_record(self, monkeypatch, tmp_path):
+ # A health-probe answer carries the REMOTE container's PID, which can equal an unrelated
+ # local host-record PID; only a PID proven on this host may select the local record.
+ from gateway.status import GatewayLiveness
+ import hermes_cli.web_routers.status as status_router
+
+ mux_runtime = {
+ "gateway_state": "running", "served_profiles": ["default", "coder"],
+ "platforms": {"coder:telegram": {"state": "disconnected"}},
+ }
+ self._scope_to_served_profile(
+ monkeypatch, tmp_path,
+ own_runtime={"gateway_state": "running", "platforms": {"telegram": {"state": "connected"}}},
+ lock_pid=4242, mux_pid=4242, mux_runtime=mux_runtime,
+ )
+ monkeypatch.setattr(
+ status_router, "resolve_gateway_liveness",
+ lambda **kwargs: GatewayLiveness(running=True, pid=4242, source="health",
+ health_body={"gateway_state": "running", "pid": 4242}),
+ )
+ calls = []
+
+ def _lookup(home):
+ calls.append(home)
+ return 4242, mux_runtime
+
+ monkeypatch.setattr(_gw_status, "multiplexer_liveness_for_profile", _lookup)
+
+ resp = self.client.get("/api/status", params={"profile": "coder"})
+
+ assert resp.status_code == 200
+ data = resp.json()
+ assert calls == []
+ assert data["gateway_platforms"]["telegram"]["state"] == "connected"
+ assert data["gateway_shared_with"] is None
+
+ def _status_on_the_host(self, monkeypatch, record):
+ # The default profile's own backend on the host: its gateway_state.json is the live
+ # multiplexer's record, and the real lookup (host record + default root) resolves to it.
+ from gateway import host_topology
+ from gateway.status import GatewayLiveness
+ import hermes_cli.web_routers.status as status_router
+ from hermes_constants import get_process_hermes_home
+
+ monkeypatch.setattr(_gw_status, "read_runtime_status", lambda path=None: record)
+ monkeypatch.setattr(_gw_status, "get_runtime_status_running_pid",
+ lambda runtime=None, *, expected_home=None: (runtime or {}).get("pid"))
+ monkeypatch.setattr(host_topology, "host_gateway_topology", lambda: host_topology.HostGatewayTopology(
+ pid=4242, profiles=("default", "reviewer"), source="host_record"))
+ monkeypatch.setattr(status_router, "resolve_gateway_liveness",
+ lambda **kwargs: GatewayLiveness(running=True, pid=4242, source="pid"))
+ monkeypatch.setattr(_web_server_gateway, "_load_configured_gateway_platforms", lambda: {"telegram"})
+ monkeypatch.setattr(_web_server_gateway, "_collect_profile_gateway_topology", lambda: {
+ "profiles": ["default", "reviewer"], "gateway_mode": "multiplex", "gateways": [],
+ "profile_platforms": {}})
+ # The lookup genuinely succeeds here (no zero-arg PID-probe trap making it raise).
+ assert _gw_status.multiplexer_liveness_for_profile(get_process_hermes_home()) == (4242, record)
+ resp = self.client.get("/api/status")
+ assert resp.status_code == 200
+ return resp.json()
+
+ def test_status_on_the_host_keeps_other_profiles_platform_errors(self, monkeypatch):
+ # The host's own record proves the live gateway, so it is read whole: folding it through
+ # the default profile's projection dropped every ``<profile>:<platform>`` entry and the
+ # platforms component read ok over another profile's fatal adapter.
+ data = self._status_on_the_host(monkeypatch, {
+ "pid": 4242, "gateway_state": "running", "served_profiles": ["default", "reviewer"],
+ "platforms": {
+ "telegram": {"state": "connected"},
+ "reviewer:discord": {"state": "fatal", "error_code": "duplicate_credential",
+ "error_message": "Profiles configure the same credential"},
+ },
+ })
+
+ assert data["gateway_platforms"]["reviewer:discord"]["error_code"] == "duplicate_credential"
+ assert data["gateway_platforms"]["telegram"]["state"] == "connected"
+ assert data["components"]["platforms"]["status"] != "ok"
+
+ def test_status_on_the_host_names_the_profiles_it_serves(self, monkeypatch):
+ # A restart of the host gateway blips every profile it serves, so its own unscoped
+ # readout names them just as a served profile's does.
+ data = self._status_on_the_host(monkeypatch, {
+ "pid": 4242, "gateway_state": "running", "served_profiles": ["default", "reviewer"],
+ "platforms": {"telegram": {"state": "connected"}},
+ })
+
+ assert data["gateway_shared_with"] == ["default", "reviewer"]
+
def test_status_rejects_malformed_namespaced_platform_key(self, monkeypatch):
monkeypatch.setattr(_gw_status, "get_running_pid_cached", lambda: 123)
monkeypatch.setattr(