The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): recover aborted gateway restart in a fresh process
joaomarcos5609ccbece07
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex be8a823b809..dcba3617abe 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -5082,6 +5082,7 @@ _LAZY_COMMAND_EXPORTS = {"_for_each_systemd_gateway_unit","_format_concurrent_instances_message","_format_time_ago",+ "_gateway_restart_recovery_profiles","_handoff_reapable_backend_pids","_ledger_reapable_backend_pids","_purge_stale_hermes_modules",@@ -5117,6 +5118,7 @@ _LAZY_COMMAND_EXPORTS = {"_refresh_active_memory_provider_dependencies","_refresh_bootstrap_cache_scripts","_refresh_windows_gateway_launchers",+ "_recover_gateway_restart_after_abort","_reload_updated_runtime_modules","_resolve_pre_update_backup_mode","_resolve_stash_selector",diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex de203785149..cddfe4e27f7 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -5588,6 +5588,126 @@ def _surviving_gateway_pids_after_failed_restart():logger.debug("Could not probe for surviving gateways after update: %s", exc)return None++_FRESH_RESTART_SUPERVISORS = frozenset({"systemd", "launchd", "service", "s6"})+++def _gateway_restart_recovery_profiles(+ plan, *, skip_profiles: set[str] | None = None+) -> list[str]:+ """Return supervised gateway profiles that a fresh process may restart.++ The update inventory is captured before the checkout changes. It is the+ only safe source here: re-importing ``hermes_cli.gateway`` in the failing+ interpreter is exactly what can raise the original ``ImportError``. Manual+ gateways are intentionally excluded because no supervisor is available to+ bring them back after a stop.+ """+ profiles: set[str] = set()+ skip_profiles = skip_profiles or set()+ try:+ for runtime in getattr(plan, "runtimes", ()) or ():+ if (+ getattr(runtime, "kind", None) == "gateway"+ and getattr(runtime, "supervisor", None) in _FRESH_RESTART_SUPERVISORS+ ):+ profile = getattr(runtime, "profile", None)+ if isinstance(profile, str) and profile and profile not in skip_profiles:+ profiles.add(profile)+ except Exception as exc:+ logger.debug("Could not prepare fresh gateway restart profiles: %s", exc)+ return sorted(profiles)+++def _recover_gateway_restart_after_abort(+ plan, *, gateway_mode: bool, skip_profiles: set[str] | None = None+) -> bool:+ """Retry supervised gateway restarts from a clean Python process.++ ``hermes update`` normally performs the fleet restart in the interpreter+ that started before ``git pull``. If that phase raises while importing the+ new tree, a warning alone leaves the old gateway alive against new files on+ disk. The recovery boundary launches the existing per-profile+ ``gateway restart`` command through a new interpreter, preserving its+ platform-specific drain and service-manager logic without inheriting the+ stale ``sys.modules`` graph.++ Only profiles classified as supervisor-owned by the pre-update inventory+ are handed off. A manual gateway must remain running and be reported for+ explicit operator action rather than being killed without a relaunch+ authority. Returns True only when the recovery child reports success for+ every handed-off profile.+ """+ profiles = _gateway_restart_recovery_profiles(plan, skip_profiles=skip_profiles)+ if not profiles:+ return False++ command = [+ sys.executable,+ "-m",+ "hermes_cli.update_restart_recovery",+ "--stdin",+ ]+ env = os.environ.copy()+ env["HERMES_UPDATE_RESTART_RECOVERY"] = "1"+ for marker in ("_HERMES_GATEWAY", "HERMES_GATEWAY", "HERMES_GATEWAY_MODE"):+ env.pop(marker, None)++ # A gateway-triggered update may run inside the gateway's systemd cgroup.+ # Put the recovery process in a transient user scope before it asks systemd+ # to restart that gateway, otherwise KillMode can terminate the recovery+ # process together with the old service. If systemd-run is unavailable,+ # fail closed rather than pretending the in-cgroup child is independent.+ if gateway_mode and sys.platform == "linux":+ systemd_run = shutil.which("systemd-run")+ if not systemd_run:+ logger.warning("Cannot isolate fresh gateway recovery from the gateway cgroup")+ return False+ command = [+ systemd_run,+ "--user",+ "--scope",+ "--quiet",+ "--collect",+ "--",+ *command,+ ]++ kwargs = {+ "input": json.dumps({"profiles": profiles}),+ "capture_output": True,+ "text": True,+ "encoding": "utf-8",+ "errors": "replace",+ "check": False,+ "env": env,+ "timeout": max(120, 30 + 90 * len(profiles)),+ }+ if sys.platform == "win32":+ kwargs["creationflags"] = (+ getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)+ | getattr(subprocess, "DETACHED_PROCESS", 0)+ )+ else:+ kwargs["start_new_session"] = True++ try:+ result = subprocess.run(command, **kwargs)+ except (OSError, subprocess.TimeoutExpired) as exc:+ logger.warning("Fresh gateway restart recovery failed: %s", exc)+ return False++ if result.returncode == 0:+ print(+ " ✓ Retried supervised gateway restart(s) in a fresh process: "+ + ", ".join(profiles)+ )+ return True++ logger.warning("Fresh gateway restart recovery exited %s", result.returncode)+ return False++def _warn_gateway_restart_phase_aborted(exc: BaseException, pids) -> None:"""Print a recovery warning when the whole restart phase raised.@@ -7843,6 +7963,13 @@ def _cmd_update_impl(args, gateway_mode: bool):# needed to forward already-restarted units to# ``_finish_dashboard_update_cleanup`` (review on #83595).restarted_services: list = []+ # Keep these restart bookkeeping collections defined even when the+ # phase raises before its platform-specific imports initialize them.+ # The abort recovery and the fleet reconciliation both consume the+ # pre-update plan in that early-failure shape.+ failed_or_stale_units: list = []+ relaunched_profiles: list = []+ externally_supervised_profiles: list = []# Same outside-the-try treatment: the post-restart fleet version# check consults killed_pids to decide whether to wait for# freshly-restarted gateways to settle, and the phase's except@@ -8612,7 +8739,63 @@ def _cmd_update_impl(args, gateway_mode: bool):# its replacement was never verified — the same fail-open contract# this fix closes — so we must still fail closed on ``[]``._surviving = _surviving_gateway_pids_after_failed_restart()- if _restart_phase_failure_is_incomplete(+ _already_restarted_profiles = set(relaunched_profiles)+ _already_restarted_profiles.update(externally_supervised_profiles)+ for runtime in getattr(_pre_update_plan, "runtimes", ()) or ():+ if getattr(runtime, "kind", None) != "gateway":+ continue+ profile = getattr(runtime, "profile", None)+ if not isinstance(profile, str):+ continue+ if any(+ profile in str(service)+ or (profile == "default" and "hermes-gateway" in str(service))+ for service in restarted_services+ ):+ _already_restarted_profiles.add(profile)+ _recovery_profiles = _gateway_restart_recovery_profiles(+ _pre_update_plan,+ skip_profiles=_already_restarted_profiles,+ )+ _recovered = _recover_gateway_restart_after_abort(+ _pre_update_plan,+ gateway_mode=gateway_mode,+ skip_profiles=_already_restarted_profiles,+ )+ if _recovered:+ relaunched_profiles.extend(+ profile+ for profile in _recovery_profiles+ if profile not in relaunched_profiles+ )+ _planned_gateway_runtimes = [+ runtime+ for runtime in getattr(_pre_update_plan, "runtimes", ()) or ()+ if getattr(runtime, "kind", None) == "gateway"+ and isinstance(getattr(runtime, "profile", None), str)+ ]+ _planned_gateway_profiles = {+ runtime.profile for runtime in _planned_gateway_runtimes+ }+ _covered_gateway_profiles = _already_restarted_profiles | set(+ _recovery_profiles+ )+ _all_gateway_profiles_are_safe_to_recover = all(+ runtime.profile in _already_restarted_profiles+ or runtime.supervisor in _FRESH_RESTART_SUPERVISORS+ for runtime in _planned_gateway_runtimes+ )+ _recovery_complete = bool(_planned_gateway_profiles) and (+ _planned_gateway_profiles <= _covered_gateway_profiles+ and _all_gateway_profiles_are_safe_to_recover+ and (not _recovery_profiles or _recovered)+ )+ if _recovery_complete:+ # The fresh child is the recovery terminal result. Leave the+ # final fleet-version matrix below as the authoritative+ # read-back before the update is declared successful.+ gateway_fleet_restart_incomplete = False+ elif _restart_phase_failure_is_incomplete(_surviving, _pre_restart_gateway_pids):gateway_fleet_restart_incomplete = True@@ -8628,6 +8811,10 @@ def _cmd_update_impl(args, gateway_mode: bool):record_gateway_restart(restarted_services=restarted_services,+ relaunched_profiles=relaunched_profiles,+ externally_supervised_profiles=externally_supervised_profiles,+ killed_pids=sorted(killed_pids),+ failed_units=failed_or_stale_units,incomplete=gateway_fleet_restart_incomplete,phase_error=str(e),)diff --git a/hermes_cli/update_restart_recovery.py b/hermes_cli/update_restart_recovery.pynew file mode 100644index 00000000000..560b1bf8153--- /dev/null+++ b/hermes_cli/update_restart_recovery.py@@ -0,0 +1,140 @@+"""Restart supervised gateway profiles from a clean Python generation.++The normal update command keeps executing in the interpreter that started before+``git pull``. This module is deliberately small: it imports no gateway code+itself and launches the regular per-profile gateway command in a new+interpreter. It is used only after the in-process restart phase has raised, so+that the recovery path cannot inherit the stale ``sys.modules`` graph that+caused the failure.+"""++from __future__ import annotations++import argparse+import json+import os+import re+import subprocess+import sys+from collections.abc import Callable, Iterable+from typing import Any++_RECOVERY_ENV = "HERMES_UPDATE_RESTART_RECOVERY"+_GATEWAY_MARKERS = ("_HERMES_GATEWAY", "HERMES_GATEWAY", "HERMES_GATEWAY_MODE")+_PROFILE_RESTART_TIMEOUT = 90+_PROFILE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")+++def _profile_command(profile: str) -> list[str]:+ """Build a parameterized restart command for exactly one profile."""+ return [+ sys.executable,+ "-m",+ "hermes_cli.main",+ "-p",+ profile,+ "gateway",+ "restart",+ ]+++def _child_environment() -> dict[str, str]:+ """Return an environment that cannot self-identify as the gateway owner."""+ env = os.environ.copy()+ for marker in _GATEWAY_MARKERS:+ env.pop(marker, None)+ env[_RECOVERY_ENV] = "1"+ return env+++def _run_profile_restart(+ profile: str,+ *,+ run: Callable[..., Any],+) -> bool:+ """Run one profile restart without inheriting the updater's process state."""+ kwargs: dict[str, Any] = {+ "stdin": subprocess.DEVNULL,+ "capture_output": True,+ "text": True,+ "encoding": "utf-8",+ "errors": "replace",+ "check": False,+ "timeout": _PROFILE_RESTART_TIMEOUT,+ "env": _child_environment(),+ }+ if os.name == "nt":+ kwargs["creationflags"] = (+ getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)+ | getattr(subprocess, "DETACHED_PROCESS", 0)+ )+ else:+ kwargs["start_new_session"] = True++ try:+ result = run(_profile_command(profile), **kwargs)+ except (OSError, subprocess.TimeoutExpired):+ return False+ return getattr(result, "returncode", 1) == 0+++def restart_profiles(+ profiles: Iterable[str], *, run: Callable[..., Any] = subprocess.run+) -> dict[str, list[str]]:+ """Restart the supplied profiles and return per-profile terminal results.++ The caller supplies only profiles whose inventory identified a service+ supervisor. Manual gateways are intentionally excluded before this module+ is called: killing one without a relaunch authority would turn stale code+ into an outage.+ """+ normalized = sorted(+ {profile for profile in profiles if isinstance(profile, str) and profile}+ )+ succeeded: list[str] = []+ failed: list[str] = []+ for profile in normalized:+ if _run_profile_restart(profile, run=run):+ succeeded.append(profile)+ else:+ failed.append(profile)+ return {"succeeded": succeeded, "failed": failed}+++def _parse_payload(stream) -> list[str]:+ payload = json.load(stream)+ profiles = payload.get("profiles") if isinstance(payload, dict) else None+ if not isinstance(profiles, list):+ raise ValueError("recovery payload must contain a profiles list")+ if any(+ not isinstance(profile, str) or not _PROFILE_ID_RE.fullmatch(profile)+ for profile in profiles+ ):+ raise ValueError("recovery profiles contain an invalid profile id")+ return profiles+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--stdin",+ action="store_true",+ help=argparse.SUPPRESS,+ )+ args = parser.parse_args(argv)+ if not args.stdin:+ parser.error("this command is an internal update-recovery entry point")++ try:+ profiles = _parse_payload(sys.stdin)+ result = restart_profiles(profiles)+ except (ValueError, json.JSONDecodeError) as exc:+ print(json.dumps({"error": str(exc), "succeeded": [], "failed": []}))+ return 2++ print(json.dumps(result, sort_keys=True))+ return 0 if not result["failed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/hermes_cli/test_update_restart_recovery.py b/tests/hermes_cli/test_update_restart_recovery.pynew file mode 100644index 00000000000..1723b5be6d7--- /dev/null+++ b/tests/hermes_cli/test_update_restart_recovery.py@@ -0,0 +1,170 @@+"""Regression coverage for fresh-process recovery after an update restart abort.++The updater may have loaded the pre-pull module graph when the checkout changes.+If the in-process gateway restart phase then raises, retrying through the same+interpreter cannot establish a coherent module generation. Recovery must use a+new interpreter and must not invent a restart for manual gateways that have no+supervisor to bring them back.+"""++from __future__ import annotations++import importlib+import io+import json+import subprocess+import sys+from types import SimpleNamespace++from hermes_cli import update_cmd+++class _Completed:+ def __init__(self, returncode: int):+ self.returncode = returncode+ self.stdout = ""+ self.stderr = ""+++def _runtime(profile: str, supervisor: str, kind: str = "gateway"):+ return SimpleNamespace(+ profile=profile,+ supervisor=supervisor,+ kind=kind,+ pid=1234,+ )+++def test_abort_recovery_hands_managed_profiles_to_a_fresh_process(monkeypatch):+ calls = []++ def fake_run(argv, **kwargs):+ calls.append((argv, kwargs))+ return _Completed(0)++ monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)+ plan = SimpleNamespace(+ runtimes=[+ _runtime("default", "systemd"),+ _runtime("coder", "launchd"),+ _runtime("manual-box", "manual"),+ _runtime("desktop", "desktop", kind="serve"),+ ]+ )++ assert update_cmd._recover_gateway_restart_after_abort(plan, gateway_mode=False)++ assert len(calls) == 1+ argv, kwargs = calls[0]+ assert argv[0] == sys.executable+ assert argv[1:4] == ["-m", "hermes_cli.update_restart_recovery", "--stdin"]+ payload = json.loads(kwargs["input"])+ assert payload == {"profiles": ["coder", "default"]}+ assert kwargs["text"] is True+ assert kwargs["capture_output"] is True+ assert kwargs["check"] is False+ assert kwargs["env"]["HERMES_UPDATE_RESTART_RECOVERY"] == "1"+++def test_abort_recovery_does_not_claim_success_when_fresh_process_fails(monkeypatch):+ monkeypatch.setattr(+ update_cmd.subprocess,+ "run",+ lambda *args, **kwargs: _Completed(1),+ )+ plan = SimpleNamespace(runtimes=[_runtime("default", "systemd")])++ assert update_cmd._recover_gateway_restart_after_abort(plan, gateway_mode=False) is False+++def test_abort_recovery_skips_profiles_already_restarted_by_the_phase(monkeypatch):+ calls = []++ def fake_run(argv, **kwargs):+ calls.append((argv, kwargs))+ return _Completed(0)++ monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)+ plan = SimpleNamespace(+ runtimes=[_runtime("default", "systemd"), _runtime("coder", "systemd")]+ )++ assert update_cmd._recover_gateway_restart_after_abort(+ plan,+ gateway_mode=False,+ skip_profiles={"default"},+ )+ assert json.loads(calls[0][1]["input"]) == {"profiles": ["coder"]}+++def test_abort_recovery_does_not_restart_manual_only_fleet(monkeypatch):+ calls = []+ monkeypatch.setattr(+ update_cmd.subprocess,+ "run",+ lambda *args, **kwargs: calls.append((args, kwargs)),+ )+ plan = SimpleNamespace(runtimes=[_runtime("manual-box", "manual")])++ assert update_cmd._recover_gateway_restart_after_abort(plan, gateway_mode=False) is False+ assert calls == []+++def test_recovery_child_restarts_each_profile_with_a_fresh_main(monkeypatch):+ recovery = importlib.import_module("hermes_cli.update_restart_recovery")+ calls = []++ def fake_run(argv, **kwargs):+ calls.append((argv, kwargs))+ return _Completed(0)++ monkeypatch.setenv("_HERMES_GATEWAY", "1")+ result = recovery.restart_profiles(["default", "coder"], run=fake_run)++ assert result == {"succeeded": ["coder", "default"], "failed": []}+ assert [call[0] for call in calls] == [+ [sys.executable, "-m", "hermes_cli.main", "-p", "coder", "gateway", "restart"],+ [sys.executable, "-m", "hermes_cli.main", "-p", "default", "gateway", "restart"],+ ]+ for _, kwargs in calls:+ assert kwargs["stdin"] is subprocess.DEVNULL+ assert kwargs["capture_output"] is True+ assert kwargs["text"] is True+ assert kwargs["check"] is False+ assert kwargs["env"]["HERMES_UPDATE_RESTART_RECOVERY"] == "1"+ assert "_HERMES_GATEWAY" not in kwargs["env"]+++def test_recovery_child_reports_failed_profile_without_losing_successes():+ recovery = importlib.import_module("hermes_cli.update_restart_recovery")+ outcomes = iter((_Completed(1), _Completed(0)))++ result = recovery.restart_profiles(+ ["coder", "default"], run=lambda *args, **kwargs: next(outcomes)+ )++ assert result == {"succeeded": ["default"], "failed": ["coder"]}+++def test_recovery_payload_rejects_path_like_profile_ids():+ recovery = importlib.import_module("hermes_cli.update_restart_recovery")++ try:+ recovery._parse_payload(io.StringIO(json.dumps({"profiles": ["../other"]})))+ except ValueError as exc:+ assert "invalid profile" in str(exc)+ else:+ raise AssertionError("path-like profile id must be rejected")+++def test_recovery_module_empty_payload_is_a_real_clean_process():+ result = subprocess.run(+ [sys.executable, "-m", "hermes_cli.update_restart_recovery", "--stdin"],+ input=json.dumps({"profiles": []}),+ capture_output=True,+ text=True,+ check=False,+ )++ assert result.returncode == 0+ assert json.loads(result.stdout) == {"succeeded": [], "failed": []}diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex fe0ca434444..823b13037b0 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -1751,6 +1751,7 @@ Pulls the latest `hermes-agent` code and reinstalls dependencies in the managedAdditional behavior:- **Gateway restart.** After a successful update, Hermes attempts to restart all running gateway profiles automatically so they pick up the new code. Use `hermes gateway restart` when you want to restart a gateway without applying an update.+- **Restart-phase recovery.** If the in-process restart phase aborts while importing the freshly pulled tree, supervised gateway profiles are retried through a clean Python process. Manual gateways are not killed without a relaunch authority; they remain in the incomplete-update report with the exact restart command.- **Update receipts + fleet version check.** Every run writes a machine-readable receipt to `~/.hermes/logs/update_receipts/` (pre-update fleet plan, steps, skips with reasons, restart outcome; `latest.json` points at the newest). After the restart phase the updater verifies each live gateway's running code against the updated checkout and prints a per-profile version matrix; a gateway still on pre-update code fails the update (exit 1) with the exact restart command.- **Local source changes.** For git installs, dirty tracked files and untracked files are auto-stashed before branch checkout or pull (`git stash push --include-untracked`). Interactive terminal updates ask before restoring the stash. Non-interactive updates restore it by default; set `updates.non_interactive_local_changes: discard` only on managed installs where local source edits should be thrown away after a successful pull. If stash restore conflicts or the pull fails, the stash is left in place for manual recovery.- **npm lockfile churn.** Before stashing or switching branches, Hermes makes a best-effort cleanup of tracked `package-lock.json` diffs produced by npm install/build steps. Commit or manually stash intentional lockfile edits before running `hermes update`.