fix(host-topology): a createTime-null record is not a live gateway, and the restart we print must run
Review findings on this PR. - `_from_host_record` accepted a record with `createTime: null`: `_same_incarnation` treats a missing create_time as "matches", so `liveness_is_proven()` blessed whatever process happens to own that PID today. A record pointing at an unrelated `sleep 60` made `cron status` print "the host gateway (PID ...) serving profiles default, served". Require a recorded create_time. - `cron status`'s host-record rung printed `hermes gateway restart`, which exits 78 for exactly its audience (a served NAMED profile); use the `--profile default` form both rungs now share. - doctor's WORST state (supervision slots exist, nothing owns the gateway role) emitted a warning but appended no issue, while the strictly less severe LEGACY case did. - Drop three defensive wrappers in `host_topology`: a try/except around an always-importable `normalize_profile_name` that silently degraded to a DIFFERENT normalisation, a blanket except per rung, and a swallowed `get_active_profile_name`. - `get_systemd_unit_path`, `_legacy_unit_search_paths`, the doctor host-unit probe and the profile-delete service cleanup hardcoded `~/.config/systemd/user`, so on a host that moves $XDG_CONFIG_HOME the unit probe false-negatived -- the very bug this PR fixes survived there. One `user_systemd_unit_dir()` helper honours the spec default. Tests: the two "Scheduler host: the host gateway" assertions were prefixes of BOTH rungs, so the rungs were indistinguishable and the host-record rung was never exercised (which is how the restart-command defect shipped green). Both now assert the full line, plus a served-host-record case. Rendezvous isolation uses `tmp_path` instead of a leaked `tempfile.mkdtemp()` and also covers `test_gateway_multiplex_served_record.py`, which read the real host record; the `tests/conftest.py` hook in #118097 supersedes all of them once it lands.
This commit is contained in:
1 parent
f66089174c
commit
ea0c2b820b
10 files changed
+132
-38
No files matched your search
+10
-20
@@ -14,22 +14,17 @@ record. ``default`` is just another served profile here, never a special owner.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _normalized(name: Optional[str]) -> str:
|
||||
if not name:
|
||||
return ""
|
||||
try:
|
||||
from hermes_cli.profiles import normalize_profile_name
|
||||
# Late import: ``hermes_cli.profiles`` imports gateway modules back.
|
||||
from hermes_cli.profiles import normalize_profile_name
|
||||
|
||||
return normalize_profile_name(name)
|
||||
except Exception:
|
||||
return str(name).strip().lower()
|
||||
return normalize_profile_name(name)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -64,8 +59,10 @@ def _from_host_record() -> Optional[HostGatewayTopology]:
|
||||
return None
|
||||
# A record whose (pid, createTime) cannot be POSITIVELY matched is a candidate, never an owner
|
||||
# (``host_rendezvous`` contract): reporting an unprovable record as the live host gateway would
|
||||
# turn a leftover record into a permanent "running" lie on every surface.
|
||||
if not hr.liveness_is_proven(record):
|
||||
# turn a leftover record into a permanent "running" lie on every surface. A record with no
|
||||
# recorded createTime is exactly that — ``_same_incarnation`` treats ``None`` as "matches", so
|
||||
# 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")
|
||||
|
||||
@@ -86,11 +83,7 @@ def _from_served_record() -> Optional[HostGatewayTopology]:
|
||||
def host_gateway_topology() -> Optional[HostGatewayTopology]:
|
||||
"""The one live host gateway and its served profiles, or None when no gateway owns the role."""
|
||||
for rung in (_from_host_record, _from_served_record):
|
||||
try:
|
||||
topology = rung()
|
||||
except Exception:
|
||||
logger.debug("host gateway topology rung %s failed", rung.__name__, exc_info=True)
|
||||
continue
|
||||
topology = rung()
|
||||
if topology is not None:
|
||||
return topology
|
||||
return None
|
||||
@@ -102,10 +95,7 @@ def host_gateway_serving(profile_name: Optional[str] = None) -> Optional[HostGat
|
||||
if topology is None:
|
||||
return None
|
||||
if profile_name is None:
|
||||
try:
|
||||
from hermes_cli.profiles import get_active_profile_name
|
||||
from hermes_cli.profiles import get_active_profile_name
|
||||
|
||||
profile_name = get_active_profile_name()
|
||||
except Exception:
|
||||
return None
|
||||
profile_name = get_active_profile_name()
|
||||
return topology if topology.serves(profile_name) else None
|
||||
+3
-1
@@ -491,7 +491,9 @@ def cron_status():
|
||||
served_by_multiplexer = named_profile_served_by_running_multiplexer()
|
||||
if host is not None:
|
||||
print(f" Scheduler host: {host.describe()}")
|
||||
_print_ticker_health([host.pid], restart_command="hermes gateway restart")
|
||||
# `hermes gateway restart` exits 78 for a served NAMED profile
|
||||
# (_guard_named_profile_under_multiplexer): the one host process is the default's.
|
||||
_print_ticker_health([host.pid], restart_command="hermes --profile default gateway restart")
|
||||
elif pids or gateway_alive_via_lock or served_by_multiplexer:
|
||||
if served_by_multiplexer:
|
||||
print(" Scheduler host: the host gateway (multiplexing this profile)")
|
||||
|
||||
@@ -233,6 +233,8 @@ def _report_host_gateway_slot(mgr, issues: list[str]) -> None:
|
||||
if not slots:
|
||||
return check_info("No gateway registered yet — run `hermes gateway install`")
|
||||
up = [p for p in slots if mgr.is_running(f"gateway-{p}")]
|
||||
issues.append("No host gateway owns the gateway role — start the ONE host multiplexer: "
|
||||
"hermes --profile default gateway start")
|
||||
return check_warn(f"No host gateway owns the gateway role ({len(up)}/{len(slots)} supervision "
|
||||
f"slots up: {', '.join(slots)})", "(nothing is serving these profiles)")
|
||||
check_ok(f"Host gateway: {topology.describe()}")
|
||||
@@ -301,13 +303,14 @@ def _check_gateway_service_linger(issues: list[str]) -> None:
|
||||
"""
|
||||
try:
|
||||
from hermes_cli.gateway import (
|
||||
_SERVICE_BASE, get_systemd_linger_status, get_systemd_unit_path, is_linux)
|
||||
_SERVICE_BASE, get_systemd_linger_status, get_systemd_unit_path, is_linux,
|
||||
user_systemd_unit_dir)
|
||||
from hermes_cli.service_manager import detect_service_manager
|
||||
except Exception as e:
|
||||
return check_warn("Gateway service linger", f"(could not import gateway helpers: {e})")
|
||||
if not is_linux() or detect_service_manager() == "s6":
|
||||
return
|
||||
host_unit = Path.home() / ".config" / "systemd" / "user" / f"{_SERVICE_BASE}.service"
|
||||
host_unit = user_systemd_unit_dir() / f"{_SERVICE_BASE}.service"
|
||||
if not (get_systemd_unit_path().exists() or host_unit.exists()):
|
||||
return
|
||||
_section("Gateway Service")
|
||||
|
||||
+13
-2
@@ -2194,11 +2194,22 @@ def get_service_name() -> str:
|
||||
return f"{_SERVICE_BASE}-{suffix}" if suffix else _SERVICE_BASE
|
||||
|
||||
|
||||
def user_systemd_unit_dir() -> Path:
|
||||
"""``$XDG_CONFIG_HOME/systemd/user`` (``~/.config`` only as the spec's default).
|
||||
|
||||
Hardcoding ``~/.config`` made every unit probe silently false-negative on a host that moves
|
||||
XDG_CONFIG_HOME — doctor then reported no gateway unit while systemd was running ours.
|
||||
"""
|
||||
config_home = os.environ.get("XDG_CONFIG_HOME", "").strip()
|
||||
base = Path(config_home) if config_home else Path.home() / ".config"
|
||||
return base / "systemd" / "user"
|
||||
|
||||
|
||||
def get_systemd_unit_path(system: bool = False) -> Path:
|
||||
name = get_service_name()
|
||||
if system:
|
||||
return _SYSTEM_UNIT_DIR / f"{name}.service"
|
||||
return Path.home() / ".config" / "systemd" / "user" / f"{name}.service"
|
||||
return user_systemd_unit_dir() / f"{name}.service"
|
||||
|
||||
|
||||
class UserSystemdUnavailableError(RuntimeError):
|
||||
@@ -2438,7 +2449,7 @@ _LEGACY_UNIT_EXECSTART_MARKERS: tuple[str, ...] = (
|
||||
|
||||
def _legacy_unit_search_paths() -> list[tuple[bool, Path]]:
|
||||
"""``[(is_system, base_dir), ...]`` to scan for legacy units; factored out so tests can monkeypatch."""
|
||||
return [(False, Path.home() / ".config" / "systemd" / "user"), (True, _SYSTEM_UNIT_DIR)]
|
||||
return [(False, user_systemd_unit_dir()), (True, _SYSTEM_UNIT_DIR)]
|
||||
|
||||
|
||||
def _find_legacy_hermes_units() -> list[tuple[str, Path, bool]]:
|
||||
|
||||
@@ -1665,7 +1665,7 @@ def _cleanup_gateway_service(name: str, profile_dir: Path) -> None:
|
||||
old_home = os.environ.get("HERMES_HOME")
|
||||
try:
|
||||
os.environ["HERMES_HOME"] = str(profile_dir)
|
||||
from hermes_cli.gateway import get_service_name, get_launchd_plist_path
|
||||
from hermes_cli.gateway import get_service_name, get_launchd_plist_path, user_systemd_unit_dir
|
||||
|
||||
def _run(*cmd: str) -> None:
|
||||
subprocess.run(list(cmd), capture_output=True, check=False, timeout=10)
|
||||
@@ -1673,7 +1673,7 @@ def _cleanup_gateway_service(name: str, profile_dir: Path) -> None:
|
||||
system = _platform.system()
|
||||
if system == "Linux":
|
||||
svc_name = get_service_name()
|
||||
svc_file = Path.home() / ".config" / "systemd" / "user" / f"{svc_name}.service"
|
||||
svc_file = user_systemd_unit_dir() / f"{svc_name}.service"
|
||||
if svc_file.exists():
|
||||
_run("systemctl", "--user", "disable", svc_name)
|
||||
_run("systemctl", "--user", "stop", svc_name)
|
||||
|
||||
@@ -50,3 +50,25 @@ def test_unprovable_record_is_a_candidate_not_the_host_gateway(host_gateway, mon
|
||||
monkeypatch.setattr("gateway.host_rendezvous.liveness_is_proven", lambda record: False)
|
||||
monkeypatch.setattr("hermes_cli.gateway_multiplex_served.live_default_gateway_pid", lambda: None)
|
||||
assert host_topology.host_gateway_topology() is None
|
||||
|
||||
|
||||
def test_record_without_createtime_is_never_the_host_gateway(host_gateway, monkeypatch):
|
||||
"""``createTime: null`` is the UNPROVABLE case, not the always-live one.
|
||||
|
||||
``_same_incarnation`` treats a missing create_time as "matches", so liveness_is_proven() says
|
||||
True for whatever process happens to own that PID today — a record pointing at an unrelated
|
||||
`sleep 60` made every surface report a live host gateway."""
|
||||
import json
|
||||
|
||||
from gateway import host_rendezvous as hr
|
||||
from gateway import host_topology
|
||||
|
||||
monkeypatch.setattr("hermes_cli.gateway_multiplex_served.live_default_gateway_pid", lambda: None)
|
||||
path = hr.record_path(hr.ROLE_GATEWAY)
|
||||
record = json.loads(path.read_text())
|
||||
record["createTime"] = None
|
||||
path.write_text(json.dumps(record))
|
||||
|
||||
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
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Tests for hermes_cli.cron command handling."""
|
||||
|
||||
import argparse
|
||||
import tempfile
|
||||
import time
|
||||
from argparse import Namespace
|
||||
from datetime import datetime, timedelta, timezone
|
||||
@@ -610,10 +609,12 @@ class TestStatusSurfacesDeadScheduler:
|
||||
status` / `cron list` must not present the stale timestamp as an upcoming "Next run":
|
||||
flag it as overdue and say when the scheduler last ticked."""
|
||||
|
||||
def _dead_gateway(self, monkeypatch):
|
||||
def _dead_gateway(self, monkeypatch, lock_dir):
|
||||
# No gateway owns the HOST role either: point the rendezvous dir at an empty scratch dir
|
||||
# so an unrelated host record can never make this profile look served.
|
||||
monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", tempfile.mkdtemp(prefix="hermes-locks-"))
|
||||
# so an unrelated host record can never make this profile look served. (Superseded by the
|
||||
# tests/conftest.py hook in #118097 once that lands.)
|
||||
lock_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(lock_dir))
|
||||
monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda: [])
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.gateway.named_profile_served_by_running_multiplexer", lambda: None
|
||||
@@ -629,7 +630,7 @@ class TestStatusSurfacesDeadScheduler:
|
||||
self, tmp_cron_dir, capsys, monkeypatch
|
||||
):
|
||||
job = create_job(prompt="Hourly", schedule="every 60m")
|
||||
self._dead_gateway(monkeypatch)
|
||||
self._dead_gateway(monkeypatch, tmp_cron_dir / "locks")
|
||||
self._park_next_run(job["id"], datetime.now(timezone.utc) - timedelta(hours=7))
|
||||
(tmp_cron_dir / "cron" / "ticker_heartbeat").write_text(str(time.time() - 25 * 3600))
|
||||
|
||||
@@ -650,7 +651,7 @@ class TestStatusSurfacesDeadScheduler:
|
||||
# a few minutes behind the ticker's own cadence is not an outage yet, and status must
|
||||
# not flash OVERDUE while doctor calls the same job healthy.
|
||||
job = create_job(prompt="Hourly", schedule="every 60m")
|
||||
self._dead_gateway(monkeypatch)
|
||||
self._dead_gateway(monkeypatch, tmp_cron_dir / "locks")
|
||||
self._park_next_run(job["id"], datetime.now(timezone.utc) - timedelta(minutes=5))
|
||||
|
||||
cron_command(Namespace(cron_command="status"))
|
||||
|
||||
@@ -57,7 +57,10 @@ def test_status_preserves_profile_health_contract(served_root, capsys, monkeypat
|
||||
|
||||
cron.cron_status()
|
||||
output = capsys.readouterr().out
|
||||
assert ("Scheduler host: the host gateway" in output) == (mode in {"missing", "fresh", "stale"})
|
||||
# This fixture leaves the rendezvous dir EMPTY, so the config-derived multiplexer rung is what
|
||||
# answers here — assert its exact line, never a prefix the host-record rung also prints.
|
||||
assert ("Scheduler host: the host gateway (multiplexing this profile)" in output) == (
|
||||
mode in {"missing", "fresh", "stale"})
|
||||
assert ("will fire automatically" in output) == (mode in {"fresh", "local"})
|
||||
if mode in {"missing", "stale"}:
|
||||
assert "hermes --profile default gateway restart" in output
|
||||
@@ -78,6 +81,29 @@ def test_status_preserves_profile_health_contract(served_root, capsys, monkeypat
|
||||
assert "STALLED" not in output
|
||||
|
||||
|
||||
def test_host_record_rung_names_the_roster_and_a_runnable_restart(served_root, capsys, monkeypatch):
|
||||
"""The OTHER rung: a published host record answers before the config-derived one.
|
||||
|
||||
Both rungs print a "Scheduler host: the host gateway…" line, so they are only distinguishable
|
||||
by their full text — and the remediation they print must actually run for THIS audience:
|
||||
`hermes gateway restart` exits 78 for a served named profile.
|
||||
"""
|
||||
import os
|
||||
|
||||
from gateway import host_rendezvous as hr
|
||||
from hermes_cli import cron
|
||||
|
||||
hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "probe"))
|
||||
|
||||
cron.cron_status()
|
||||
output = capsys.readouterr().out
|
||||
|
||||
assert f"Scheduler host: the host gateway (PID {os.getpid()}) serving profiles default, probe" in output
|
||||
assert "Scheduler host: the host gateway (multiplexing this profile)" not in output
|
||||
assert "hermes --profile default gateway restart" in output
|
||||
assert "\n If heartbeat never appears, restart: hermes gateway restart" not in output
|
||||
|
||||
|
||||
@pytest.mark.parametrize("heartbeat", ["missing", "fresh", "stale"])
|
||||
def test_satellite_list_and_create_require_own_heartbeat(served_root, capsys, monkeypatch, heartbeat):
|
||||
from argparse import Namespace
|
||||
|
||||
@@ -32,6 +32,10 @@ def served_root(tmp_path, monkeypatch):
|
||||
"served_profiles": ["default", "coder"]}))
|
||||
monkeypatch.setenv("HERMES_HOME", str(root / "profiles" / "coder"))
|
||||
monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False)
|
||||
# Never read the developer's / CI's REAL host rendezvous record (superseded by the
|
||||
# tests/conftest.py hook in #118097 once that lands).
|
||||
(tmp_path / "locks").mkdir()
|
||||
monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
|
||||
import hermes_constants
|
||||
import gateway.status as status
|
||||
monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)
|
||||
@@ -184,8 +188,13 @@ def test_satellite_gateway_identity_does_not_imply_cron_health(served_root, monk
|
||||
buf = io.StringIO()
|
||||
with contextlib.redirect_stdout(buf):
|
||||
cr.cron_status()
|
||||
# Multiplex-only: the ONE host gateway is named as the ticker, with the profiles it serves.
|
||||
assert "Scheduler host: the host gateway" in buf.getvalue()
|
||||
# Multiplex-only: the ONE host gateway is named as the ticker, with the profiles it serves —
|
||||
# the FULL line, so this cannot pass on the sibling "(multiplexing this profile)" rung.
|
||||
assert f"Scheduler host: the host gateway (PID {os.getpid()}) serving profiles default, coder" \
|
||||
in buf.getvalue()
|
||||
# The remediation this rung prints must run for a served NAMED profile (`hermes gateway
|
||||
# restart` exits 78 there).
|
||||
assert "restart: hermes --profile default gateway restart" in buf.getvalue()
|
||||
# A live scheduler host alone does not prove this satellite's ticker is healthy.
|
||||
assert "has not reported a heartbeat" in buf.getvalue()
|
||||
assert "will fire automatically" not in buf.getvalue()
|
||||
|
||||
@@ -89,14 +89,44 @@ def test_doctor_reports_the_single_host_gateway_not_per_profile_slots(served_hos
|
||||
assert any("migrate --multiplex" in i for i in issues)
|
||||
|
||||
|
||||
def test_doctor_checks_host_unit_linger_under_a_served_profile(served_host, tmp_path, capsys, monkeypatch):
|
||||
def test_doctor_raises_an_issue_when_nothing_owns_the_gateway_role(served_host, capsys, monkeypatch):
|
||||
"""The WORST state must produce remediation: slots exist, nothing serves them. The strictly
|
||||
less severe LEGACY case already appended an issue, so `doctor` exited 0 with `issues: []`
|
||||
on the outage and non-zero on the mere leftover."""
|
||||
from hermes_cli import doctor_platform
|
||||
|
||||
class _Mgr:
|
||||
def is_running(self, name):
|
||||
return name == "main-hermes"
|
||||
|
||||
def list_profile_gateways(self):
|
||||
return ["default", "served", "legacy"]
|
||||
|
||||
monkeypatch.setattr("gateway.host_topology.host_gateway_topology", lambda: None)
|
||||
monkeypatch.setattr("hermes_cli.service_manager.detect_service_manager", lambda: "s6")
|
||||
monkeypatch.setattr("hermes_cli.service_manager.S6ServiceManager", _Mgr)
|
||||
issues: list[str] = []
|
||||
doctor_platform._check_s6_supervision(issues)
|
||||
|
||||
assert "No host gateway owns the gateway role" in capsys.readouterr().out
|
||||
assert any("gateway start" in i for i in issues), "the outage state produced no remediation"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("xdg", [False, True])
|
||||
def test_doctor_checks_host_unit_linger_under_a_served_profile(served_host, tmp_path, capsys, monkeypatch, xdg):
|
||||
from hermes_cli import doctor_platform
|
||||
|
||||
fake_home = tmp_path / "fakehome"
|
||||
unit_dir = fake_home / ".config" / "systemd" / "user"
|
||||
config_home = (tmp_path / "xdgconfig") if xdg else (fake_home / ".config")
|
||||
unit_dir = config_home / "systemd" / "user"
|
||||
unit_dir.mkdir(parents=True)
|
||||
(unit_dir / "hermes-gateway.service").write_text("[Unit]\n") # the HOST unit; no per-profile unit
|
||||
monkeypatch.setenv("HOME", str(fake_home))
|
||||
# A host that moves XDG_CONFIG_HOME keeps its units there; probing ~/.config false-negatives.
|
||||
if xdg:
|
||||
monkeypatch.setenv("XDG_CONFIG_HOME", str(config_home))
|
||||
else:
|
||||
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
|
||||
monkeypatch.setattr("hermes_cli.gateway.is_linux", lambda: True)
|
||||
monkeypatch.setattr("hermes_cli.service_manager.detect_service_manager", lambda: "systemd")
|
||||
monkeypatch.setattr("hermes_cli.gateway.get_systemd_linger_status", lambda *a, **k: (False, "off"))
|
||||
|
||||
Reference in new issue
Block a user