Skip to content

The agent that grows with you

fix(update): classify a systemd-owned serve/dashboard as systemd, not manual-serve

kshitijk4poorfb4e9fd22248
diff --git a/hermes_cli/update_abort_recovery.py b/hermes_cli/update_abort_recovery.py
index ef27a838957..7a3ffd6b528 100644
--- a/hermes_cli/update_abort_recovery.py
+++ b/hermes_cli/update_abort_recovery.py
@@ -34,11 +34,16 @@ def _surviving_pre_update_serve_runtimes(plan) -> list[dict]:
if not isinstance(pid, int) or pid <= 0:
continue
detail = getattr(runtime, "detail", None)
+ detail = detail if isinstance(detail, dict) else {}
planned[pid] = {
"pid": pid, "kind": str(getattr(runtime, "kind", "")),
"profile": str(getattr(runtime, "profile", "")),
"supervisor": str(getattr(runtime, "supervisor", "")),
- "_create_time": _numeric(detail.get("create_time") if isinstance(detail, dict) else None)}
+ "_create_time": _numeric(detail.get("create_time"))}
+ if detail.get("systemd_unit"):
+ # The owning unit and scope name the exact restart command (#141021).
+ planned[pid]["systemd_unit"] = str(detail["systemd_unit"])
+ planned[pid]["systemd_scope"] = detail.get("systemd_scope")
except Exception as exc:
logger.debug("Could not read planned serve runtimes: %s", exc)
return []
@@ -234,9 +239,16 @@ def _warn_stale_serve_runtimes(rows) -> None:
print(
f" pid {row.get('pid')} — {row.get('kind')}"
f" (profile {row.get('profile') or 'default'}, {row.get('supervisor') or 'unknown'})")
- print(" Ask their owner to relaunch `hermes serve` / `hermes dashboard`, or reconnect Desktop for an SSH backend.")
- if sys.platform == "linux" and any(row.get("supervisor") == "systemd" for row in rows):
- print(" For unit-managed backends: `systemctl --user restart hermes-serve.service`.")
+ unit_rows = [row for row in rows if row.get("supervisor") == "systemd"]
+ if len(unit_rows) < len(rows):
+ print(" Ask their owner to relaunch `hermes serve` / `hermes dashboard`, or reconnect Desktop for an SSH backend.")
+ # A unit-managed backend restarts through its own unit and scope — never "ask the owner to
+ # relaunch", and never a hardcoded user-scope hermes-serve (#141021).
+ for row in unit_rows:
+ unit = row.get("systemd_unit") or "<unit>"
+ command = {"user": "systemctl --user", "system": "sudo systemctl"}.get(
+ row.get("systemd_scope"), "systemctl [--user]")
+ print(f" pid {row.get('pid')} is managed by systemd: `{command} restart {unit}`")
if sys.platform == "darwin" and any(row.get("supervisor") == "launchd" for row in rows):
print(" For launchd-managed backends: `launchctl kickstart -k gui/$UID/<label>`.")
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index 5c7ea487613..d22ffc8a08f 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -215,9 +215,9 @@ _SUPERVISED_SERVE_BACKENDS = frozenset(
)
# Backends whose supervisor restarts the process without any updater bookkeeping. ``manual-serve``
# is excluded: it owes a durable handoff (``defer_manual_serve``) before it stops counting.
-# ``systemd``/``windows-service``/``service`` mirror ``_SUPERVISED_SERVE_BACKENDS`` for parity only —
-# the inventory writer classifies a serve/dashboard row as exactly launchd, desktop, desktop-ssh or manual-serve
-# (``update_inventory._collect_ledger_runtimes``); those three are set for gateway rows alone.
+# The inventory writer classifies a serve/dashboard row as launchd, desktop, desktop-ssh, systemd (a unit's
+# MainPID, #141021) or manual-serve (``update_inventory._collect_ledger_runtimes``); ``windows-service`` and
+# ``service`` mirror ``_SUPERVISED_SERVE_BACKENDS`` for parity only — they are set for gateway rows alone.
_SUPERVISOR_OWNED_SERVE_BACKENDS = _SUPERVISED_SERVE_BACKENDS - {"manual-serve"}
diff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.py
index 3f65f9db990..d029278a2fe 100644
--- a/hermes_cli/update_inventory.py
+++ b/hermes_cli/update_inventory.py
@@ -259,6 +259,24 @@ def _launchd_owner_for_ledger_entry(entry: dict, pid: int, jobs: list) -> tuple[
return None
+def _systemd_owner_for_ledger_pid(pid: int) -> tuple[str, str | None] | None:
+ """``(unit, scope)`` of the systemd unit whose live ``MainPID`` is *pid*, if any.
+
+ A unit-launched backend sets neither ``HERMES_SPAWN`` nor ``HERMES_PARENT_PID``, so the spawner
+ probe reads ``manual-serve`` and the update tells the user to "ask the owner to relaunch
+ `hermes dashboard`" for a process systemd owns (#141021). Ownership is the unit's MainPID, not
+ cgroup membership (a hand-started dashboard inside some unrelated unit's cgroup is still manual);
+ ``None`` off Linux, when unreadable, or when no unit owns it."""
+ with suppress(Exception):
+ from hermes_cli import main_dashboard as _dash
+
+ unit = _dash._get_systemd_service_for_pid(pid)
+ if unit:
+ cgroup = _dash._get_pid_cgroup_path(pid)
+ return unit, _dash._extract_scope_from_cgroup(cgroup) if cgroup else None
+ return None
+
+
def _is_desktop_ssh_ledger_entry(entry: dict) -> bool:
"""Is this row the backend a (possibly remote) Desktop spawned over SSH? The canonical argv
predicate also classifies rows written before the ledger carried ``isolated``, which is exactly
@@ -277,7 +295,8 @@ def _collect_ledger_runtimes(plan: UpdatePlan, seen: set[int]) -> None:
ledger_entries() live-verifies (pid, create_time) so PID reuse never fabricates a row. Desktop-
supervised backends (spawner still alive) restart via the Desktop's own respawn, not ours.
A backend owned by a loaded launchd job is classified ``launchd`` (kickstart restart, never a
- detached argv respawn) — the spawner probe cannot see that (#116503)."""
+ detached argv respawn) — the spawner probe cannot see that (#116503); one that is a systemd
+ unit's MainPID is ``systemd`` for the same reason (#141021)."""
with _probe("Serve/dashboard ledger inventory"):
from hermes_cli.process_identity import ledger_entries, spawner_is_dead
@@ -300,8 +319,12 @@ def _collect_ledger_runtimes(plan: UpdatePlan, seen: set[int]) -> None:
# No local spawner, so the probe below would read manual-serve and file a reminder
# nobody here can discharge; its token file and owner nonce belong to the client.
supervisor = "desktop-ssh"
+ elif spawner_is_dead(entry) is False:
+ supervisor = "desktop"
+ elif unit := _systemd_owner_for_ledger_pid(pid):
+ supervisor, detail["systemd_unit"], detail["systemd_scope"] = "systemd", unit[0], unit[1]
else:
- supervisor = "desktop" if spawner_is_dead(entry) is False else "manual-serve"
+ supervisor = "manual-serve"
plan.runtimes.append(_runtime(
str(purpose), str(entry.get("profile") or "default"), pid, supervisor, detail=detail,
))
diff --git a/tests/hermes_cli/test_update_system_dashboard_unit.py b/tests/hermes_cli/test_update_system_dashboard_unit.py
index 673ea111a48..fc86d6c3446 100644
--- a/tests/hermes_cli/test_update_system_dashboard_unit.py
+++ b/tests/hermes_cli/test_update_system_dashboard_unit.py
@@ -77,3 +77,41 @@ def test_dashboard_pass_still_restarts_the_unit_when_the_fleet_loop_never_saw_it
_systemd_owned_dashboard(monkeypatch, calls)
dashboard_procs._kill_stale_dashboard_processes(restart_managed=True, already_restarted_units={"hermes-gateway"})
assert ["systemctl", "restart", UNIT] in calls
+
+
+def test_systemd_owned_ledger_dashboard_is_classified_systemd(monkeypatch):
+ calls: list = []
+ _systemd_owned_dashboard(monkeypatch, calls)
+ entry = {"pid": DASH_PID, "create_time": 1000.0, "purpose": "dashboard", "profile": "",
+ "argv": "hermes dashboard --host 0.0.0.0 --port 9119 --no-open", "host": "0.0.0.0", "port": 9119}
+ fake_pi = SimpleNamespace(ledger_entries=lambda **k: [entry], spawner_is_dead=lambda e: None)
+ monkeypatch.setitem(sys.modules, "hermes_cli.process_identity", fake_pi)
+ plan = UpdatePlan()
+ update_inventory._collect_ledger_runtimes(plan, set())
+ (row,) = plan.runtimes
+ assert (row.supervisor, row.restart_via) == ("systemd", "systemd")
+ assert (row.detail["systemd_unit"], row.detail["systemd_scope"]) == (UNIT, "system")
+
+
+def test_hand_started_dashboard_in_a_foreign_cgroup_stays_manual(monkeypatch):
+ """No unit owns the PID as MainPID → still manual-serve (its respawn reminder still applies)."""
+ monkeypatch.setattr(main_dashboard, "_get_systemd_service_for_pid", lambda pid: None)
+ entry = {"pid": 4321, "create_time": 1.0, "purpose": "dashboard", "argv": "hermes dashboard"}
+ monkeypatch.setitem(sys.modules, "hermes_cli.process_identity",
+ SimpleNamespace(ledger_entries=lambda **k: [entry], spawner_is_dead=lambda e: None))
+ plan = UpdatePlan()
+ update_inventory._collect_ledger_runtimes(plan, set())
+ assert plan.runtimes[0].supervisor == "manual-serve"
+
+
+def test_stale_unit_dashboard_hint_names_its_unit_and_scope(monkeypatch, capsys):
+ plan = UpdatePlan(runtimes=[RuntimeRecord(
+ kind="dashboard", profile="default", pid=DASH_PID, supervisor="systemd", restart_via="systemd",
+ detail={"create_time": 1000.0, "systemd_unit": UNIT, "systemd_scope": "system"})])
+ monkeypatch.setitem(sys.modules, "hermes_cli.process_identity", SimpleNamespace(
+ ledger_entries=lambda: [{"pid": DASH_PID, "purpose": "dashboard", "create_time": 1000.0}]))
+ rows = update_cmd._surviving_pre_update_serve_runtimes(plan)
+ update_cmd._warn_stale_serve_runtimes(rows)
+ out = capsys.readouterr().out
+ assert f"`sudo systemctl restart {UNIT}`" in out
+ assert "Ask their owner" not in out and "hermes-serve.service" not in out