Skip to content

The agent that grows with you

fix(update): tighten hermes-serve unit gate, dedupe fleet/cleanup restarts

chelsealong0b42cae068b8
diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.py
index 3ee58ff2667..7f8d722facf 100644
--- a/hermes_cli/dashboard_procs.py
+++ b/hermes_cli/dashboard_procs.py
@@ -296,6 +296,7 @@ def _kill_stale_dashboard_processes(
reason: str = "the running backend no longer matches the updated frontend",
*,
restart_managed: bool = False,
+ already_restarted_units: "set[str] | None" = None,
) -> dict[str, list]:
"""Kill running ``hermes dashboard`` / ``hermes serve`` processes.
@@ -319,6 +320,14 @@ def _kill_stale_dashboard_processes(
e.g. a remote backend's ``hermes-serve.service``) has its owning unit
restarted after the kill, because systemd treats our SIGTERM as a clean
stop and ``Restart=on-failure`` would never fire (#68934).
+
+ *already_restarted_units* names units (no ``.service`` suffix) the
+ caller already restarted directly — e.g. ``hermes update``'s systemd
+ fleet-restart loop, which restarts ``hermes-serve*`` units before this
+ function runs. Without excluding them, a Serve-only install's freshly
+ restarted process is found again here and restarted a second time for
+ no benefit (review on #83595). PIDs owned by one of these units are
+ left untouched.
"""
if restart_managed and _m()._restart_managed_dashboard_service(reason):
return {"matched": [], "killed": [], "failed": []}
@@ -347,9 +356,6 @@ def _kill_stale_dashboard_processes(
if not pids:
return {"matched": [], "killed": [], "failed": []}
- print()
- print(f"⟲ Stopping {len(pids)} dashboard process(es) ({reason})")
-
# Before killing, snapshot systemd cgroup info for each PID so we can
# restart supervised services after the kill (the cgroup disappears
# along with the process). Only meaningful on Linux, and only when the
@@ -374,6 +380,22 @@ def _kill_stale_dashboard_processes(
pid_cmdline[pid] = cmdline
pid_home[pid] = _hermes_home_for_pid(pid)
+ if already_restarted_units:
+ # Already handled directly by the caller (e.g. hermes update's
+ # systemd fleet-restart loop) — leave these alone instead of
+ # killing and re-restarting a process that's already fresh.
+ pids = [
+ pid
+ for pid in pids
+ if (pid_service.get(pid) or "").removesuffix(".service")
+ not in already_restarted_units
+ ]
+ if not pids:
+ return {"matched": [], "killed": [], "failed": []}
+
+ print()
+ print(f"⟲ Stopping {len(pids)} dashboard process(es) ({reason})")
+
killed: list[int] = []
failed: list[tuple[int, str]] = []
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 4705aa8b13b..bfc56a1ef95 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -669,8 +669,16 @@ def _reload_process_scan_modules() -> None:
)
-def _finish_dashboard_update_cleanup(node_failures: list[str]) -> None:
- """Refresh managed dashboards or stop stale manual ones after an update."""
+def _finish_dashboard_update_cleanup(
+ node_failures: list[str], already_restarted_units: "set[str] | None" = None
+) -> None:
+ """Refresh managed dashboards or stop stale manual ones after an update.
+
+ *already_restarted_units* forwards the systemd unit names (no
+ ``.service`` suffix) that the fleet-restart loop already restarted
+ directly, so a Serve-only install's freshly restarted process isn't
+ found and restarted a second time here (review on #83595).
+ """
if node_failures:
print()
print(" ℹ Leaving running dashboard process(es) untouched because the")
@@ -681,7 +689,9 @@ def _finish_dashboard_update_cleanup(node_failures: list[str]) -> None:
# both modules reflect the freshly-updated source before touching them.
_reload_process_scan_modules()
- stop_result = _m()._kill_stale_dashboard_processes(restart_managed=True)
+ stop_result = _m()._kill_stale_dashboard_processes(
+ restart_managed=True, already_restarted_units=already_restarted_units
+ )
if not stop_result.get("unrecovered"):
return
@@ -3883,7 +3893,14 @@ def _for_each_systemd_gateway_unit(
continue
# list-units is already pattern-filtered, but keep the name gate so a
# stray non-gateway/serve line cannot enter the restart path.
- if not (unit.startswith("hermes-gateway") or unit.startswith("hermes-serve")):
+ # ``unit.startswith("hermes-serve")`` alone would also accept the
+ # unrelated ``hermes-server.service`` — require the exact base unit
+ # or the hyphenated profile family instead (review on #83595).
+ if not (
+ unit.startswith("hermes-gateway")
+ or unit == "hermes-serve.service"
+ or unit.startswith("hermes-serve-")
+ ):
continue
svc_name = unit.removesuffix(".service")
try:
@@ -5679,6 +5696,12 @@ def _cmd_update_impl(args, gateway_mode: bool):
# discovered gateway lets the handler fail closed on an empty survivor
# probe rather than reporting a clean update (#78574).
_pre_restart_gateway_pids: list | None = []
+ # Declared outside the restart try/except below (and never reset
+ # to None) so it's always safe to read afterwards even if that
+ # block raises before reaching its own restart bookkeeping —
+ # needed to forward already-restarted units to
+ # ``_finish_dashboard_update_cleanup`` (review on #83595).
+ restarted_services: list = []
# Auto-restart ALL gateways after update.
# The code update (git pull) is shared across all profiles, so every
@@ -5852,7 +5875,6 @@ def _cmd_update_impl(args, gateway_mode: bool):
except Exception:
_drain_budget = 45.0
- restarted_services = []
failed_or_stale_units = []
killed_pids = set()
relaunched_profiles = []
@@ -6466,7 +6488,13 @@ def _cmd_update_impl(args, gateway_mode: bool):
# systemd treat it as a clean stop, leaving the Cloudflare origin dead.
# Preserve the safety rule above: a failed Node refresh leaves the
# currently running dashboard untouched.
- _finish_dashboard_update_cleanup(node_failures)
+ #
+ # Forward the systemd units restarted above (includes hermes-serve*,
+ # #83438) so a Serve-only install's freshly restarted process isn't
+ # found and restarted again below (review on #83595).
+ _finish_dashboard_update_cleanup(
+ node_failures, already_restarted_units=set(restarted_services)
+ )
print()
print("Tip: You can now select a provider and model:")
diff --git a/tests/hermes_cli/test_update_fleet_restart_timeout.py b/tests/hermes_cli/test_update_fleet_restart_timeout.py
index 210a768095a..67866be8105 100644
--- a/tests/hermes_cli/test_update_fleet_restart_timeout.py
+++ b/tests/hermes_cli/test_update_fleet_restart_timeout.py
@@ -112,6 +112,20 @@ class TestFleetRestartTimeoutIsolation:
assert seen == ["hermes-serve", "hermes-serve-work", "hermes-gateway"]
+ def test_hermes_server_near_prefix_is_rejected(self):
+ # Review on #83595: a bare ``startswith("hermes-serve")`` gate also
+ # accepts the unrelated ``hermes-server.service``. Only the exact
+ # base unit or the hyphenated profile family should pass.
+ seen: list[str] = []
+
+ _for_each_systemd_gateway_unit(
+ _list_units_stdout(["hermes-server"]),
+ process_unit=seen.append,
+ on_unit_timeout=lambda *_: pytest.fail("unexpected timeout"),
+ )
+
+ assert seen == []
+
class TestGracefulSigusr1Eligibility:
def test_gateway_units_are_eligible(self):
diff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.py
index b6dde9bcfe4..1c8bb0f9d85 100644
--- a/tests/hermes_cli/test_update_stale_dashboard.py
+++ b/tests/hermes_cli/test_update_stale_dashboard.py
@@ -338,6 +338,30 @@ class TestSupervisedBackendRestart:
# Supervised restart succeeded — no manual hint.
assert "when you're ready" not in out
+ def test_already_restarted_unit_is_left_untouched(self):
+ """Review on #83595: hermes update's systemd fleet-restart loop may
+ already have restarted this PID's owning unit directly (e.g. a
+ Serve-only install). Passing it via already_restarted_units must
+ skip killing/restarting it again here."""
+ live = self._live()
+
+ with patch.object(live, "_restart_managed_dashboard_service", return_value=False), \
+ patch.object(live, "_find_stale_dashboard_pids", return_value=[4321]), \
+ patch.object(live, "_get_pid_cgroup_path",
+ return_value="/system.slice/hermes-serve.service"), \
+ patch.object(live, "_get_systemd_service_for_pid",
+ return_value="hermes-serve.service"), \
+ patch.object(live, "_try_restart_systemd_service") as restart, \
+ patch("os.kill") as kill, \
+ patch("time.sleep"):
+ result = _kill_stale_dashboard_processes(
+ restart_managed=True, already_restarted_units={"hermes-serve"}
+ )
+
+ kill.assert_not_called()
+ restart.assert_not_called()
+ assert result == {"matched": [], "killed": [], "failed": []}
+
class TestManualBackendRespawn:
"""Manually-started dashboards/serves have their argv captured before the