Skip to content

The agent that grows with you

fix(review): a second tenant's host gateway never attaches, refuses, or reports as ours (#121352)

teknium1304cf75bbd72
diff --git a/gateway/host_attach.py b/gateway/host_attach.py
index faf2bf87f15..fa449ad5aea 100644
--- a/gateway/host_attach.py
+++ b/gateway/host_attach.py
@@ -105,7 +105,7 @@ class HostGateway:
return f"PID {self.pid} (launched by profile '{self.profile_label}'; serves: {served})"
-def _record_home(record) -> Path:
+def record_home(record) -> Path:
"""Home the owner was launched from. Records written before the field existed fall back to the
default root — the home every pre-record multiplexer ran under."""
from hermes_constants import get_default_hermes_root
@@ -113,6 +113,23 @@ def _record_home(record) -> Path:
return Path(record.home) if getattr(record, "home", "") else Path(get_default_hermes_root())
+def launched_by_other_tenant(owner_home: Path | str, our_home: Path | str) -> bool:
+ """Was the owner launched from ANOTHER Hermes root (a second tenant on this host)?
+
+ The host record and lock are per OS user, and two tenants (separate ``HERMES_HOME`` roots)
+ each expose a profile named ``default``: tenant A's multiplexer "serving default" is a name
+ collision for tenant B, never coverage, so it is not this tenant's host gateway (#121352).
+ A legacy record with no ``home`` proves nothing and counts as ours.
+ """
+ if not str(owner_home or ""):
+ return False
+ from gateway.status import _same_hermes_home
+ from hermes_constants import get_default_hermes_root
+
+ return not _same_hermes_home(get_default_hermes_root(home=owner_home),
+ get_default_hermes_root(home=our_home))
+
+
def _identify(home: Path) -> Optional[dict]:
try:
from gateway.control_socket import identify_gateway
@@ -174,7 +191,7 @@ def _probe_host_gateway(wait_for_channel: float) -> Optional[HostGateway]:
# address it chose; proving the PID first is also what keeps a stale record from naming a peer.
if not hr.liveness_is_proven(record):
return None
- home = _record_home(record)
+ home = record_home(record)
deadline = time.monotonic() + max(0.0, wait_for_channel)
while True:
identity = _identify(home)
@@ -340,7 +357,7 @@ def decide(our_home: Path, *, replace: bool = False) -> HostAttachDecision:
except Exception:
logger.debug("host gateway probe failed; starting as before", exc_info=True)
return HostAttachDecision(START, "")
- if gateway is None or gateway.pid == os.getpid():
+ if gateway is None or gateway.pid == os.getpid() or launched_by_other_tenant(gateway.home, our_home):
return standalone_attach_decision(our_home, None) or HostAttachDecision(START, "")
if replace and (gateway.serves(profile) or not gateway.served_known):
# An owner known not to serve us is another profile's gateway: replacing it is always refused
diff --git a/gateway/host_topology.py b/gateway/host_topology.py
index 224f3bc3b2d..9cfeb82f1f8 100644
--- a/gateway/host_topology.py
+++ b/gateway/host_topology.py
@@ -15,6 +15,7 @@ record. ``default`` is just another served profile here, never a special owner.
from __future__ import annotations
from dataclasses import dataclass
+from pathlib import Path
from typing import Optional
@@ -38,6 +39,9 @@ class HostGatewayTopology:
pid: int
profiles: tuple[str, ...]
source: str
+ #: Home the process was launched from (its ``gateway_state.json`` lives there); None when the
+ #: rung cannot tell, which readers resolve to the default root.
+ home: Optional[Path] = None
def serves(self, profile_name: Optional[str]) -> bool:
"""True when this host process ticks/serves ``profile_name`` (``default`` included)."""
@@ -64,7 +68,14 @@ def _from_host_record() -> Optional[HostGatewayTopology]:
# liveness_is_proven() would bless ANY process that happens to hold the recorded PID today.
if record.create_time is None or not hr.liveness_is_proven(record):
return None
- return HostGatewayTopology(pid=int(record.pid), profiles=tuple(record.profiles), source="host_record")
+ from gateway.host_attach import launched_by_other_tenant, record_home
+ from hermes_constants import get_hermes_home
+
+ # Another tenant root's gateway is a name collision, not this tenant's host process (#121352).
+ if launched_by_other_tenant(record.home, get_hermes_home()):
+ return None
+ return HostGatewayTopology(pid=int(record.pid), profiles=tuple(record.profiles), source="host_record",
+ home=record_home(record))
def _from_served_record() -> Optional[HostGatewayTopology]:
diff --git a/gateway/run.py b/gateway/run.py
index 76765f35173..4b9158675d3 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -5465,9 +5465,16 @@ def _claim_host_gateway_role(force: bool = False) -> None:
hr.describe(owner) if owner else "another process")
return
from gateway.host_attach import (
- ATTACH_CHANNEL_WAIT_S, START, host_gateway, standalone_attach_decision,
+ ATTACH_CHANNEL_WAIT_S, START, host_gateway, launched_by_other_tenant, standalone_attach_decision,
)
from hermes_cli.profiles import profile_is_standalone
+ if owner is not None and launched_by_other_tenant(owner.home, get_hermes_home()):
+ # The lock is per OS user, so a second tenant root can never win it against the first:
+ # refusing 75 here would retry forever and its gateway would never start (#121352).
+ logger.warning(
+ "Another Hermes home's gateway owns this host (%s); starting this home's gateway beside it.",
+ hr.describe(owner))
+ return
if profile_is_standalone(get_hermes_home()):
# Recheck after losing the atomic lock: the pre-lock served set may be stale.
live_owner = host_gateway(wait_for_channel=ATTACH_CHANNEL_WAIT_S)
diff --git a/gateway/status.py b/gateway/status.py
index dfd41a3a8f2..51d01e9e706 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -1449,8 +1449,12 @@ def multiplexer_liveness_for_profile(profile_dir: Path) -> Optional[tuple[int, d
if name != "default" and not _same_hermes_home(profile_dir, get_default_hermes_root() / "profiles" / name):
return None
topology = host_gateway_topology()
+ # The multiplexer's record lives in the home that LAUNCHED it; a named-hosted multiplexer leaves
+ # a possibly stale standalone record at the default root, which must not be projected.
+ launch_home = get_default_hermes_root()
if topology is not None and topology.serves(name):
pid: Optional[int] = topology.pid
+ launch_home = topology.home or launch_home
elif name != "default" and named_profile_served_by_running_multiplexer(name):
# Config-derived fallback for a record that predates ``served_profiles``.
pid = live_default_gateway_pid()
@@ -1458,7 +1462,7 @@ def multiplexer_liveness_for_profile(profile_dir: Path) -> Optional[tuple[int, d
return None
if pid is None:
return None
- return pid, read_runtime_status(get_default_hermes_root() / "gateway_state.json") or {}
+ return pid, read_runtime_status(launch_home / "gateway_state.json") or {}
def shared_listener_mirror_platforms(runtime: Optional[dict[str, Any]], profile: str) -> dict[str, Any]:
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index c9732dc5164..4765be78549 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -4134,13 +4134,10 @@ def host_multiplexer_serving(profile_name: str | None = None):
gateway = host_gateway_serving(name or "default")
if gateway is None:
return None
- # The host record is HOST-wide, and two Hermes tenants on one host (separate HERMES_HOMEs)
- # each expose a profile named 'default': a same-named profile under ANOTHER tenant root is a
- # collision, not coverage. decide() / _claim_host_gateway_role already start beside such an
- # owner; the CLI guards read this probe and refused with exit 78 instead (#121352).
- from hermes_constants import get_default_hermes_root
- from gateway.status import _same_hermes_home
- if not _same_hermes_home(get_default_hermes_root(home=gateway.home), get_default_hermes_root()):
+ # Same predicate as decide() / _claim_host_gateway_role: another tenant's multiplexer
+ # "serving default" is a name collision, and the CLI guards refused on it with exit 78 (#121352).
+ from gateway.host_attach import launched_by_other_tenant
+ if launched_by_other_tenant(gateway.home, get_hermes_home()):
logger.debug("Host gateway %s belongs to another Hermes home; not ours", gateway.describe())
return None
return gateway
diff --git a/hermes_cli/gateway_multiplex_mode.py b/hermes_cli/gateway_multiplex_mode.py
index 5f00f4b2b3e..3237ca168a8 100644
--- a/hermes_cli/gateway_multiplex_mode.py
+++ b/hermes_cli/gateway_multiplex_mode.py
@@ -326,15 +326,13 @@ 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``)."""
try:
- from gateway.status import (
- read_runtime_status,
- runtime_status_is_stale,
- runtime_status_pid_is_live,
- )
+ from gateway.status import read_runtime_status, runtime_status_pid_is_live
record = read_runtime_status() or {}
if record.get("gateway_state") in (None, "stopped", "startup_failed"):
return []
- if not runtime_status_pid_is_live(record) or runtime_status_is_stale(record):
+ # 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 []
reason = record.get("multiplex_standalone_reason")
except Exception:
diff --git a/tests/gateway/test_host_attach_lifecycle.py b/tests/gateway/test_host_attach_lifecycle.py
index 9bd65d77355..5773d50bd93 100644
--- a/tests/gateway/test_host_attach_lifecycle.py
+++ b/tests/gateway/test_host_attach_lifecycle.py
@@ -293,3 +293,23 @@ def test_the_default_profile_arriving_second_starts_beside_a_standalone_named_ow
assert host_attach.profile_name_for_home(root) == "default"
assert decision.outcome == host_attach.START
assert asyncio.run(gateway_run._host_attach_or_none(replace=False)) is None
+
+
+def test_another_tenants_host_gateway_never_yields_attach_or_the_lock_refusal(tmp_path, monkeypatch, owner_pid):
+ """#121352: two Hermes roots on one host (one OS user) each expose a profile named ``default``.
+ Tenant A's live multiplexer serves A's ``default`` + ``coder``; tenant B's ``default`` must START,
+ not ATTACH (exit 0 with nothing running), and losing the per-OS-user host lock to A must not
+ refuse 75 (a race B can never win, so its gateway would never start)."""
+ root_a, root_b = tmp_path / "hermes-a", tmp_path / "hermes-b"
+ _publish(owner_pid, root_a, ("default", "coder"))
+ _answer_identify(monkeypatch, owner_pid, root_a, ["default", "coder"])
+ monkeypatch.setattr(gateway_run, "get_hermes_home", lambda: root_b)
+
+ assert host_attach.host_gateway_serving("default") is not None # A's record is live and names default
+ assert host_attach.decide(root_b).outcome == host_attach.START
+ assert host_attach.decide(root_a / "profiles" / "coder").outcome == host_attach.ATTACH # control: A's own
+
+ monkeypatch.setattr(hr, "claim_host_lock", lambda role: (hr.HostLockOutcome.HELD_BY_OTHER, None))
+ monkeypatch.setattr("gateway.control_socket.rescan_gateway_profiles",
+ lambda *a, **k: pytest.fail("B must not ask A's gateway to rescan"))
+ gateway_run._claim_host_gateway_role() # no SystemExit(75)
diff --git a/tests/gateway/test_host_gateway_lock_refusal.py b/tests/gateway/test_host_gateway_lock_refusal.py
index e56f53fc1fc..8ecb1a1472d 100644
--- a/tests/gateway/test_host_gateway_lock_refusal.py
+++ b/tests/gateway/test_host_gateway_lock_refusal.py
@@ -10,6 +10,8 @@ import sys
import pytest
+from hermes_constants import get_hermes_home
+
@pytest.fixture
def host_lock_dir(tmp_path, monkeypatch):
@@ -43,7 +45,7 @@ def test_second_host_gateway_is_refused_with_75_naming_the_owner_and_the_migrate
from gateway.run import _claim_host_gateway_role
from hermes_cli.gateway_migrate import MIGRATE_COMMAND
- hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "coder"), home=str(host_lock_dir))
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "coder"), home=str(get_hermes_home()))
owner = hr.read_record(hr.ROLE_GATEWAY, include_stale=True)
assert owner is not None
handle = _hold_host_lock_from_another_description(hr)
@@ -71,7 +73,7 @@ def test_force_still_starts_a_second_gateway_and_an_unusable_lock_dir_is_not_a_r
from gateway import host_rendezvous as hr
from gateway.run import _claim_host_gateway_role
- hr.publish_record(hr.ROLE_GATEWAY, profiles=(), home=str(host_lock_dir))
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=(), home=str(get_hermes_home()))
handle = _hold_host_lock_from_another_description(hr)
try:
_claim_host_gateway_role(force=True) # no SystemExit
@@ -104,7 +106,7 @@ def test_an_unmigrated_standalone_fleet_starts_beside_the_owner_instead_of_spinn
from gateway import host_rendezvous as hr
from gateway.run import _claim_host_gateway_role
- hr.publish_record(hr.ROLE_GATEWAY, profiles=("default",), home=str(host_lock_dir))
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=("default",), home=str(get_hermes_home()))
owner = hr.read_record(hr.ROLE_GATEWAY, include_stale=True)
assert owner is not None
# The owner answers the rescan the way a STANDALONE gateway does: "I do not multiplex."
@@ -139,7 +141,7 @@ def test_a_multiplexing_owner_is_still_refused(host_lock_dir, monkeypatch):
from gateway.restart import GATEWAY_SERVICE_RESTART_EXIT_CODE
from gateway.run import _claim_host_gateway_role
- hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "coder"), home=str(host_lock_dir))
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "coder"), home=str(get_hermes_home()))
owner = hr.read_record(hr.ROLE_GATEWAY, include_stale=True)
assert owner is not None
# Another process holds the record (our own pid would short-circuit _owner_is_standalone before
@@ -203,7 +205,7 @@ async def test_a_replace_unit_that_replaced_nothing_is_still_refused_when_it_los
# patch this used to carry was unreachable (_owner_is_standalone short-circuits on our own pid).
monkeypatch.setattr("gateway.run._owner_is_standalone", lambda: False)
- hr.publish_record(hr.ROLE_GATEWAY, profiles=("default",), home=str(host_lock_dir))
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=("default",), home=str(get_hermes_home()))
handle = _hold_host_lock_from_another_description(hr)
try:
with pytest.raises(SystemExit) as exc:
diff --git a/tests/gateway/test_host_topology.py b/tests/gateway/test_host_topology.py
index fcd8640858d..b3fb8b70ba4 100644
--- a/tests/gateway/test_host_topology.py
+++ b/tests/gateway/test_host_topology.py
@@ -72,3 +72,37 @@ def test_record_without_createtime_is_never_the_host_gateway(host_gateway, monke
parsed = hr.read_record(hr.ROLE_GATEWAY)
assert parsed is not None and parsed.create_time is None # the record itself still parses
assert host_topology.host_gateway_topology() is None
+
+
+def test_topology_ignores_another_tenants_record_and_reads_the_launch_homes_state(tmp_path, monkeypatch):
+ """#121352 reporting half: a record from ANOTHER Hermes root is not this tenant's host gateway
+ (doctor / cron status / the dashboard ladder), and a NAMED-hosted multiplexer's platforms are read
+ from the home that launched it, not from a stale standalone record at the default root."""
+ import json
+ import os
+
+ from gateway import host_rendezvous as hr
+ from gateway import host_topology, status
+
+ root_a, root_b = tmp_path / "hermes-a", tmp_path / "hermes-b"
+ argus = root_b / "profiles" / "argus"
+ argus.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
+ monkeypatch.setenv("HERMES_HOME", str(root_b))
+ monkeypatch.setattr("hermes_constants._default_hermes_root_memo", None)
+
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "coder"), home=str(root_a))
+ assert host_topology.host_gateway_topology() is None
+
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "argus"), home=str(argus))
+ (argus / "gateway_state.json").write_text(json.dumps(
+ {"pid": os.getpid(), "gateway_state": "running", "platforms": {"telegram": {"state": "connected"}}}),
+ encoding="utf-8")
+ (root_b / "gateway_state.json").write_text(json.dumps(
+ {"pid": 1, "gateway_state": "stopped", "platforms": {"discord": {"state": "disconnected"}}}),
+ encoding="utf-8")
+ topology = host_topology.host_gateway_topology()
+ assert topology is not None and topology.home == argus
+ resolved = status.multiplexer_liveness_for_profile(root_b)
+ assert resolved is not None and resolved[0] == os.getpid()
+ assert set(resolved[1]["platforms"]) == {"telegram"}
diff --git a/tests/hermes_cli/test_gateway_multiplex_mode.py b/tests/hermes_cli/test_gateway_multiplex_mode.py
index 89e59071c13..82bfddaeb82 100644
--- a/tests/hermes_cli/test_gateway_multiplex_mode.py
+++ b/tests/hermes_cli/test_gateway_multiplex_mode.py
@@ -217,15 +217,16 @@ def test_recorded_standalone_warning_lines_suppressed_for_dead_or_stale_record(t
monkeypatch.setattr(gw_status, "runtime_status_pid_is_live", lambda r: False)
assert mode.recorded_standalone_warning_lines() == []
- # 3. Stale heartbeat
+ # 3. Stale heartbeat but LIVE PID: a paused/wedged standalone gateway still warns (the
+ # heartbeat is a health signal, not liveness).
state_file.write_text(json.dumps({
"gateway_state": "running",
"pid": os.getpid(),
"updated_at": "2020-01-01T00:00:00Z",
- "multiplex_standalone_reason": "orphan reason",
+ "multiplex_standalone_reason": "wedged reason",
}), encoding="utf-8")
monkeypatch.setattr(gw_status, "runtime_status_pid_is_live", lambda r: True)
- assert mode.recorded_standalone_warning_lines() == []
+ assert any("wedged reason" in line for line in mode.recorded_standalone_warning_lines())
# 4. Live and fresh record emits warning
state_file.write_text(json.dumps({
diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.md
index 127ba7bc8f8..96e1b7a7ca3 100644
--- a/website/docs/user-guide/multi-profile-gateways.md
+++ b/website/docs/user-guide/multi-profile-gateways.md
@@ -210,6 +210,9 @@ Parking does not delete the profile, its sessions, or its scheduled jobs.
Without a running host it removes the marker and follows the normal start
path; start the host from the default profile if prompted. `restart` unserves
and serves the profile without writing a parked marker, re-reading its config.
+On a **parked** profile with no live per-profile gateway, `restart` behaves as
+`start`: it removes the marker and hot-serves the profile (a gateway started
+with `--force` beside the marker keeps its own restart instead).
These operations do not terminate work already dispatched by a cron tick.
The host also rescans every 30 seconds: adding the marker by hand unserves the