Skip to content

The agent that grows with you

fix(gateway): scoped PID queries validate against the probed home (#106406)

liuhao1024a23319d0f788
diff --git a/gateway/status.py b/gateway/status.py
index b356a938b69..63c069390d4 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -450,6 +450,15 @@ def _pid_record_belongs_to_current_profile(record: Optional[dict[str, Any]]) ->
return not record_home or _same_hermes_home(record_home, _get_process_hermes_home())
+def _pid_record_matches_home(record: Optional[dict[str, Any]], expected_home: Path) -> bool:
+ """True when the record's ``hermes_home`` matches ``expected_home`` (legacy records: True).
+ Scoped queries validate against the probed home, not the serve process's."""
+ if not isinstance(record, dict):
+ return False
+ record_home = record.get("hermes_home")
+ return not record_home or _same_hermes_home(record_home, expected_home)
+
+
def _build_runtime_status_record() -> dict[str, Any]:
return {
**_build_pid_record(), "gateway_state": "starting", "exit_reason": None,
@@ -1444,20 +1453,37 @@ def planned_stop_marker_targets_self() -> bool:
def get_running_pid(
pid_path: Optional[Path] = None, *, cleanup_stale: bool = True
) -> Optional[int]:
- """PID of a running gateway (lock + PID file verified against the live process), or None."""
+ """PID of a running gateway (lock + PID file verified against the live process), or None.
+ An explicit ``pid_path`` is a scoped query into that home's identity files: records are
+ validated against the probed home (not the serve process's), and a live record is never
+ cleanup-unlinked, so polling another profile must not delete its gateway.pid/gateway.lock
+ (#106406)."""
resolved_pid_path = pid_path or _get_pid_path()
resolved_lock_path = _get_gateway_lock_path(resolved_pid_path)
if is_gateway_runtime_lock_active(resolved_lock_path):
records = (
_read_pid_record(resolved_pid_path), _read_gateway_lock_record(resolved_lock_path),
)
+ expected_home = pid_path.parent if pid_path is not None else None
+ saw_live_pid = False
for record in records:
pid = _live_pid_from_record(record)
- if pid is None or not _pid_record_belongs_to_current_profile(record):
+ if pid is None:
continue
- if _record_matches_live_gateway_pid(record, pid):
+ home_ok = (
+ _pid_record_belongs_to_current_profile(record) if expected_home is None
+ else _pid_record_matches_home(record, expected_home)
+ )
+ if home_ok and _record_matches_live_gateway_pid(
+ record, pid, expected_home=expected_home
+ ):
return pid
- _cleanup_invalid_pid_path(resolved_pid_path, cleanup_stale=cleanup_stale)
+ # A live record we could not adopt may still be a real gateway: unlinking its
+ # identity files would break that home's double-run protection while the PID
+ # is alive, so leave cleanup to a poll after it dies.
+ saw_live_pid = True
+ if not saw_live_pid:
+ _cleanup_invalid_pid_path(resolved_pid_path, cleanup_stale=cleanup_stale)
return get_runtime_status_running_pid() if pid_path is None else None
# Lock inactive: the runtime-status fallback runs BEFORE cleanup here.
runtime_pid = get_runtime_status_running_pid() if pid_path is None else None
diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.py
index d17e47fa86b..3afa8219781 100644
--- a/tests/gateway/test_status.py
+++ b/tests/gateway/test_status.py
@@ -170,6 +170,70 @@ class TestGatewayPidState:
(process_home / "gateway.pid").unlink(missing_ok=True)
+class TestScopedGatewayPidQuery:
+ """get_running_pid(pid_path) is a scoped query into another home's identity files (#106406):
+ records are validated against the probed home (not the serve process's) and a live record is
+ never cleanup-unlinked, so a scoped status poll must not delete a live foreign gateway's
+ gateway.pid/gateway.lock."""
+
+ def _write_scoped_profile(self, tmp_path):
+ profile_dir = tmp_path / "profiles" / "wiki"
+ profile_dir.mkdir(parents=True)
+ record = {
+ "pid": 4242,
+ "kind": "hermes-gateway",
+ "argv": ["python", "-m", "hermes_cli.main", "gateway", "--profile", "wiki"],
+ "start_time": 123,
+ "hermes_home": str(profile_dir.resolve()),
+ }
+ pid_path = profile_dir / "gateway.pid"
+ pid_path.write_text(json.dumps(record))
+ (profile_dir / "gateway.lock").write_text(json.dumps(record))
+ return profile_dir, pid_path, record
+
+ def test_scoped_query_reports_live_foreign_profile_pid(self, tmp_path, monkeypatch):
+ # The serve process polls from the DEFAULT home; the live wiki record must still count.
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "default-home"))
+ profile_dir, pid_path, _ = self._write_scoped_profile(tmp_path)
+ monkeypatch.setattr(status, "is_gateway_runtime_lock_active", lambda lock: True)
+ monkeypatch.setattr(status, "_pid_exists", lambda pid: True)
+ monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 123)
+ monkeypatch.setattr(
+ status, "_read_process_cmdline",
+ lambda pid: "python -m hermes_cli.main gateway --profile wiki",
+ )
+ assert status.get_running_pid(pid_path) == 4242
+ assert pid_path.exists()
+ assert (profile_dir / "gateway.lock").exists()
+
+ def test_scoped_query_never_unlinks_live_foreign_identity(self, tmp_path, monkeypatch):
+ # Live PID whose record claims a THIRD home: not adoptable, but its identity files must
+ # survive the poll (double-run/takeover protection).
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "default-home"))
+ profile_dir, pid_path, record = self._write_scoped_profile(tmp_path)
+ # Both identity files migrate together in the real world; repoint both homes.
+ record["hermes_home"] = str((tmp_path / "elsewhere").resolve())
+ pid_path.write_text(json.dumps(record))
+ (profile_dir / "gateway.lock").write_text(json.dumps(record))
+ monkeypatch.setattr(status, "is_gateway_runtime_lock_active", lambda lock: True)
+ monkeypatch.setattr(status, "_pid_exists", lambda pid: True)
+ monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 123)
+ monkeypatch.setattr(status, "_read_process_cmdline", lambda pid: None)
+ assert status.get_running_pid(pid_path) is None
+ assert pid_path.exists()
+ assert (profile_dir / "gateway.lock").exists()
+
+ def test_scoped_query_still_cleans_dead_pid_record(self, tmp_path, monkeypatch):
+ # A dead PID's stale record is still cleanup-unlinked, scoped or not.
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "default-home"))
+ profile_dir, pid_path, _ = self._write_scoped_profile(tmp_path)
+ monkeypatch.setattr(status, "is_gateway_runtime_lock_active", lambda lock: True)
+ monkeypatch.setattr(status, "_pid_exists", lambda pid: False)
+ assert status.get_running_pid(pid_path) is None
+ assert not pid_path.exists()
+ assert not (profile_dir / "gateway.lock").exists()
+
+
class TestGatewayRuntimeStatus:
def test_clear_profile_platforms_preserves_primary_entries(self, tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))