The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): surface multiplex profile failures (OOF-3)
Shannon Sandsf755ed5e90ce
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 242e29f5cdc..d3efafaeb8b 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -3457,7 +3457,15 @@ class BasePlatformAdapter(ABC):"""try:from gateway.status import write_runtime_status- write_runtime_status(platform=self.platform.value, **kwargs)+ # Multiplexed secondary adapters share the process-level runtime+ # status file with the primary adapter. Their runner stamps a+ # namespaced key (``<profile>:<platform>``) so one profile's fatal+ # state cannot overwrite another profile's healthy entry.+ platform_key = (+ getattr(self, "_runtime_status_platform_key", None)+ or self.platform.value+ )+ write_runtime_status(platform=platform_key, **kwargs)except Exception as exc:# Use getattr so object.__new__(...) test harnesses that skip __init__# don't blow up on attribute access.diff --git a/gateway/run.py b/gateway/run.pyindex a4fcde2d499..656cad62650 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -12048,7 +12048,11 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewpasstry:from gateway.status import write_runtime_status- write_runtime_status(gateway_state="starting", exit_reason=None)+ write_runtime_status(+ gateway_state="starting",+ exit_reason=None,+ clear_profile_platforms=True,+ )except Exception:passtry:@@ -14832,6 +14836,11 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewif credential_claim is not None:owner = claimed.get(credential_claim)if owner is not None:+ message = (+ f"Profile '{owner}' and '{profile_name}' both configure "+ f"{platform.value} with the same credential. Give each "+ f"profile its own {platform.value} credential."+ )logger.error("Profile '%s' and '%s' both configure %s with the same ""credential — refusing to start the duplicate (one "@@ -14839,6 +14848,12 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew"its own %s credential.",owner, profile_name, platform.value, platform.value,)+ self._update_platform_runtime_status(+ f"{profile_name}:{platform.value}",+ platform_state="fatal",+ error_code="duplicate_credential",+ error_message=message,+ )# This adapter has not connected and therefore owns no# resources to clean up. Calling disconnect here can mutate# the shared platform state and, for a same-credential Photon@@ -14850,6 +14865,11 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewowner = claimed.get(listener_claim)if owner is not None:bind, port = listener_claim[-2:]+ message = (+ f"Profile '{owner}' and '{profile_name}' both configure "+ f"{platform.value} sidecars on the same listener. Configure "+ f"a distinct listener for profile '{profile_name}'."+ )logger.error("Profile '%s' and '%s' both configure %s sidecars on ""%s:%s — refusing to start the duplicate listener. "@@ -14863,6 +14883,12 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewplatform.value,profile_name,)+ self._update_platform_runtime_status(+ f"{profile_name}:{platform.value}",+ platform_state="fatal",+ error_code="duplicate_listener",+ error_message=message,+ )# Like credential conflicts, this adapter never connected# and owns no resources that should be disconnected.continue@@ -14897,6 +14923,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewplatform: Platform,) -> None:"""Install the profile-scoped handlers shared by startup and reconnect."""+ # Runtime status is process-scoped even while message/config work is+ # profile-scoped. Preserve both dimensions in the key so dashboard+ # and NAS health aggregation can see which secondary profile failed.+ adapter._runtime_status_platform_key = f"{profile_name}:{platform.value}"adapter.set_message_handler(self._make_profile_message_handler(profile_name))adapter.set_fatal_error_handler(self._make_profile_fatal_error_handler(profile_name, platform)diff --git a/gateway/status.py b/gateway/status.pyindex 8f4d5fcad8c..66a56517d29 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -1048,6 +1048,7 @@ def write_runtime_status(needs_attention: Any = _UNSET,retrying_since: Any = _UNSET,served_profiles: Any = _UNSET,+ clear_profile_platforms: bool = False,) -> None:"""Persist gateway runtime health information for diagnostics/status."""path = _get_runtime_status_path()@@ -1055,6 +1056,20 @@ def write_runtime_status(previous_payload = copy.deepcopy(payload)current_record = _build_pid_record()payload.setdefault("platforms", {})+ if clear_profile_platforms:+ # Secondary-profile adapter health is stored in the process-level+ # status file as ``<profile>:<platform>``. A fresh gateway process+ # must not inherit those entries from the prior process: they would+ # otherwise keep /api/status degraded until every old adapter emitted+ # a new state (and removed profiles would remain degraded forever).+ platforms = payload["platforms"]+ if not isinstance(platforms, dict):+ platforms = {}+ payload["platforms"] = {+ key: value+ for key, value in platforms.items()+ if not isinstance(key, str) or ":" not in key+ }payload["kind"] = current_record["kind"]payload["pid"] = current_record["pid"]payload["argv"] = current_record["argv"]diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex dd6df807d0e..71050300f15 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -3287,6 +3287,16 @@ async def get_health():}+_PROFILE_PLATFORM_STATUS_KEY_RE = re.compile(+ r"^[a-z0-9][a-z0-9_-]{0,63}:[a-z][a-z0-9_]{0,63}$"+)+++def _is_profile_platform_status_key(key: object) -> bool:+ """Accept only the runner's public ``<profile>:<platform>`` key grammar."""+ return isinstance(key, str) and bool(_PROFILE_PLATFORM_STATUS_KEY_RE.fullmatch(key))++@app.get("/api/status")async def get_status(profile: Optional[str] = None):status_scope = None@@ -3389,7 +3399,14 @@ async def get_status(profile: Optional[str] = None):gateway_platforms = {key: valuefor key, value in gateway_platforms.items()+ # Namespaced entries are emitted by configured secondary-+ # profile adapters. The config set here belongs to the+ # active/default profile, so suffix-checking against it+ # would incorrectly hide secondary-only platforms. Keep+ # the accepted grammar narrow because this public endpoint+ # is projecting a process-local JSON file.if key in configured_gateway_platforms+ or _is_profile_platform_status_key(key)}gateway_exit_reason = runtime.get("exit_reason")# Contract: gateway_updated_at is RFC3339 string | null, never adiff --git a/tests/gateway/test_multiplex_adapter_registry.py b/tests/gateway/test_multiplex_adapter_registry.pyindex 4b3bbb93ca5..ce05f456dd3 100644--- a/tests/gateway/test_multiplex_adapter_registry.py+++ b/tests/gateway/test_multiplex_adapter_registry.py@@ -96,6 +96,39 @@ class TestProfileMessageHandler:assert seen["profile"] == "coder"+class TestProfileRuntimeStatus:+ def test_base_adapter_uses_namespaced_platform_key(self, monkeypatch):+ from gateway.platforms.base import BasePlatformAdapter++ class _ConcreteAdapter(BasePlatformAdapter):+ async def connect(self):+ return True++ async def disconnect(self):+ return None++ async def send(self, *_args, **_kwargs):+ return None++ async def get_chat_info(self, *_args, **_kwargs):+ return None++ adapter = _ConcreteAdapter.__new__(_ConcreteAdapter)+ adapter.platform = Platform.DISCORD+ adapter._runtime_status_platform_key = "reviewer:discord"+ writes = []+ monkeypatch.setattr(+ "gateway.status.write_runtime_status",+ lambda **kwargs: writes.append(kwargs),+ )++ adapter._write_runtime_status_safe("fatal", platform_state="fatal")++ assert writes == [+ {"platform": "reviewer:discord", "platform_state": "fatal"}+ ]++class _SecondaryRecoveryAdapter:platform = Platform.DISCORD@@ -277,6 +310,98 @@ class TestSecondaryProfileConfigHandling:assert "telegram" not in messageassert "reviewer" not in runner._profile_adapters+ def test_configured_secondary_adapter_namespaces_runtime_status(self):+ runner = _secondary_recovery_runner()+ adapter = _SecondaryRecoveryAdapter()++ runner._configure_profile_adapter(adapter, "reviewer", Platform.DISCORD)++ assert adapter._runtime_status_platform_key == "reviewer:discord"++ @pytest.mark.asyncio+ async def test_duplicate_credential_is_persisted_as_profile_fatal(+ self, monkeypatch+ ):+ runner = _secondary_recovery_runner()+ config = GatewayConfig(+ multiplex_profiles=True,+ platforms={+ Platform.DISCORD: PlatformConfig(+ enabled=True, token="shared-discord-token"+ )+ },+ )+ adapter = _SecondaryRecoveryAdapter()+ adapter.config = config.platforms[Platform.DISCORD]+ writes = []++ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)+ monkeypatch.setattr(runner, "_create_adapter", lambda _p, _c: adapter)+ monkeypatch.setattr(+ runner,+ "_update_platform_runtime_status",+ lambda platform, **kwargs: writes.append((platform, kwargs)),+ )+ claim = runner._adapter_credential_claim(Platform.DISCORD, adapter)++ connected = await runner._start_one_profile_adapters(+ "reviewer", "/tmp/reviewer", {claim: "default"}+ )++ assert connected == 0+ assert writes == [+ (+ "reviewer:discord",+ {+ "platform_state": "fatal",+ "error_code": "duplicate_credential",+ "error_message": (+ "Profile 'default' and 'reviewer' both configure discord "+ "with the same credential. Give each profile its own "+ "discord credential."+ ),+ },+ )+ ]++ @pytest.mark.asyncio+ async def test_duplicate_listener_is_persisted_without_public_bind_details(+ self, monkeypatch+ ):+ class _ListenerAdapter(_SecondaryRecoveryAdapter):+ _sidecar_bind = "127.0.0.1"+ _sidecar_port = 8789++ runner = _secondary_recovery_runner()+ platform = Platform("photon")+ config = GatewayConfig(+ multiplex_profiles=True,+ platforms={platform: PlatformConfig(enabled=True)},+ )+ adapter = _ListenerAdapter()+ adapter.platform = platform+ adapter.config = config.platforms[platform]+ writes = []++ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)+ monkeypatch.setattr(runner, "_create_adapter", lambda _p, _c: adapter)+ monkeypatch.setattr(+ runner,+ "_update_platform_runtime_status",+ lambda key, **kwargs: writes.append((key, kwargs)),+ )+ claim = runner._adapter_listener_claim(platform, adapter)++ connected = await runner._start_one_profile_adapters(+ "reviewer", "/tmp/reviewer", {claim: "default"}+ )++ assert connected == 0+ assert writes[0][0] == "reviewer:photon"+ assert writes[0][1]["error_code"] == "duplicate_listener"+ assert "127.0.0.1" not in writes[0][1]["error_message"]+ assert "8789" not in writes[0][1]["error_message"]+@pytest.mark.asyncioasync def test_multiplexer_skips_bad_profile_and_continues(self, monkeypatch, caplog):from pathlib import Pathdiff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.pyindex 9e5e7f78430..bfca704efc0 100644--- a/tests/gateway/test_status.py+++ b/tests/gateway/test_status.py@@ -171,6 +171,69 @@ class TestGatewayPidState:class TestGatewayRuntimeStatus:+ def test_clear_profile_platforms_preserves_primary_entries(self, tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / "gateway_state.json").write_text(+ json.dumps({+ "platforms": {+ "telegram": {"state": "connected"},+ "reviewer:discord": {+ "state": "fatal",+ "error_code": "duplicate_credential",+ },+ }+ }),+ encoding="utf-8",+ )++ status.write_runtime_status(clear_profile_platforms=True)++ payload = status.read_runtime_status()+ assert payload["platforms"] == {"telegram": {"state": "connected"}}++ def test_clear_profile_platforms_and_write_are_one_atomic_update(+ self, tmp_path, monkeypatch+ ):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / "gateway_state.json").write_text(+ json.dumps({+ "platforms": {+ "old:discord": {"state": "fatal"},+ "telegram": {"state": "connected"},+ }+ }),+ encoding="utf-8",+ )++ status.write_runtime_status(+ platform="reviewer:slack",+ platform_state="connected",+ clear_profile_platforms=True,+ )++ assert status.read_runtime_status()["platforms"] == {+ "telegram": {"state": "connected"},+ "reviewer:slack": {+ "state": "connected",+ "updated_at": status.read_runtime_status()["platforms"][+ "reviewer:slack"+ ]["updated_at"],+ },+ }++ def test_clear_profile_platforms_repairs_malformed_platforms(+ self, tmp_path, monkeypatch+ ):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / "gateway_state.json").write_text(+ json.dumps({"platforms": ["not", "a", "mapping"]}),+ encoding="utf-8",+ )++ status.write_runtime_status(clear_profile_platforms=True)++ assert status.read_runtime_status()["platforms"] == {}+def test_write_runtime_status_overwrites_stale_pid_on_restart(self, tmp_path, monkeypatch):"""Regression: setdefault() preserved stale PID from previous process (#1631)."""diff --git a/tests/hermes_cli/test_web_server_gateway_topology.py b/tests/hermes_cli/test_web_server_gateway_topology.pyindex b5728047cd5..73d18a2d335 100644--- a/tests/hermes_cli/test_web_server_gateway_topology.py+++ b/tests/hermes_cli/test_web_server_gateway_topology.py@@ -131,6 +131,59 @@ class TestStatusEndpointTopology:# The per-gateway detail (host ports) is loopback-only recon.assert data["gateways"] == [{"profile": "default", "ports": {}}]+ def test_status_preserves_secondary_profile_platform_errors(self, monkeypatch):+ monkeypatch.setattr(web_server, "get_running_pid_cached", lambda: 123)+ monkeypatch.setattr(+ web_server,+ "read_runtime_status",+ lambda path=None: {+ "gateway_state": "running",+ "platforms": {+ "telegram": {"state": "connected"},+ "reviewer:discord": {+ "state": "fatal",+ "error_code": "duplicate_credential",+ "error_message": "Profiles configure the same credential",+ },+ },+ },+ )+ monkeypatch.setattr(+ web_server,+ "_load_configured_gateway_platforms",+ lambda: {"telegram"},+ )++ resp = self.client.get("/api/status")++ assert resp.status_code == 200+ platforms = resp.json()["gateway_platforms"]+ assert platforms["telegram"]["state"] == "connected"+ assert platforms["reviewer:discord"]["error_code"] == "duplicate_credential"++ def test_status_rejects_malformed_namespaced_platform_key(self, monkeypatch):+ monkeypatch.setattr(web_server, "get_running_pid_cached", lambda: 123)+ monkeypatch.setattr(+ web_server,+ "read_runtime_status",+ lambda path=None: {+ "gateway_state": "running",+ "platforms": {+ "reviewer:discord:../../secret": {"state": "fatal"},+ },+ },+ )+ monkeypatch.setattr(+ web_server,+ "_load_configured_gateway_platforms",+ lambda: {"telegram"},+ )++ resp = self.client.get("/api/status")++ assert resp.status_code == 200+ assert "reviewer:discord:../../secret" not in resp.json()["gateway_platforms"]+def test_profile_names_and_mode_public_when_auth_gated(self, monkeypatch):# Profile NAMES + gateway_mode are low-sensitivity product surface: the# Hermes Cloud Portal reads /api/status over the network (a gated bind)