Skip to content

The agent that grows with you

fix(update): make the Windows gateway pause durable and never resume onto a torn tree

Tekniumeebfab299178
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index f100a2a2150..b9e14dde54f 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -3562,6 +3562,8 @@ def main():
_warn_pending_fleet_restart_on_startup()
except Exception:
pass
+ from hermes_cli.update_pause_record import recover as _recover_paused_gateways
+ _recover_paused_gateways() # a killed `hermes update` left gateways paused (Windows)
if _first_positional_argv() != "update":
from hermes_cli.boot_bootstrap import maybe_run_boot_bootstrap
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.py
index 21b490525a1..bcef081c67c 100644
--- a/hermes_cli/update_cmd_windows.py
+++ b/hermes_cli/update_cmd_windows.py
@@ -920,6 +920,10 @@ def _pause_windows_gateways_for_update() -> dict | None:
with _abort_on_error("Could not prepare Windows gateway pause for update"):
from gateway.status import get_process_start_time, terminate_pid
from hermes_cli.gateway import _capture_gateway_argv
+ from hermes_cli import update_pause_record as pause_record
+ # A previous update killed mid-pause left its set stopped: bring it back with this run's resume.
+ orphan = pause_record.orphaned_record()
+ adopted = pause_record.drop_never_stopped(dict(orphan["token"])) if orphan else None
profile_processes, service_gateways, service_gateway_pids, running_pids = _discover_windows_gateways()
if not running_pids:
token = _windows_cold_start_plan()
@@ -927,22 +931,44 @@ def _pause_windows_gateways_for_update() -> dict | None:
# (clean exit, autostart not installed): give them a token to ride on.
probe = token if token is not None else {"resume_needed": True, "profiles": {}, "unmapped_pids": [], "unmapped": []}
_record_attested_cold_start_profiles(probe, set())
- return probe if probe.get("cold_start_profiles") else token
- profiles, mapped_pids, socket_acks = _request_socket_pauses(running_pids, profile_processes, service_gateway_pids)
- # Resolve venv-side launchers BEFORE draining: a dead worker's parent cannot be recovered (NoSuchProcess).
- # The launcher keeps ``.pyd`` mapped and would trip the venv-holder guard; it is killed with the survivors.
- launcher_pids = _m()._venv_launcher_ancestors(mapped_pids)
- print("→ Stopping Windows gateway process(es) before updating Hermes...")
- drain_timeout = _gateway_drain_timeout(socket_acks)
- survivors = _m()._wait_for_windows_update_gateway_exit(mapped_pids, timeout=drain_timeout)
+ token = probe if probe.get("cold_start_profiles") else token
+ if adopted is None:
+ return pause_record.stamp_tree(token) if token is not None else None
+ token = pause_record.stamp_tree(pause_record.merge_into(token, adopted))
+ with _abort_on_error("Could not record the adopted paused-gateway set"):
+ pause_record.write(token, owner=pause_record.identity())
+ return token
unmapped_pids = [pid for pid in running_pids if pid not in profile_processes and pid not in service_gateway_pids]
- # Snapshot unmapped gateways' argv *before* force-killing so resume can replay it.
+ # Snapshot unmapped gateways' argv *before* anything stops so resume (or a later launch) can replay it.
# Unmapped = no profile->PID-file mapping (e.g. Scheduled Task ``pythonw.exe -m ...``).
unmapped = [
{"pid": int(pid), "argv": _try_call(lambda p=int(pid): _capture_gateway_argv(p),
"Could not capture argv for unmapped gateway %s: %s", int(pid))}
for pid in unmapped_pids
]
+ # Durable BEFORE the first stop: a killed updater must leave a record the next launch can resume.
+ intended = {
+ "resume_needed": True, "unmapped_pids": unmapped_pids, "unmapped": unmapped,
+ "profiles": {str(profile_processes[pid].profile): int(pid) for pid in running_pids
+ if pid in profile_processes and pid not in service_gateway_pids},
+ "identities": {str(pid): pause_record.identity(pid)["ct"] for pid in running_pids},
+ }
+ if service_gateways:
+ names = [str(s.name) for s in service_gateways]
+ intended.update(services=names, expected_services=list(names), restarted_services=[],
+ service_profiles={str(s.name): str(s.profile) for s in service_gateways})
+ if adopted is not None:
+ pause_record.merge_into(intended, adopted)
+ pause_record.stamp_tree(intended)
+ with _abort_on_error("Could not record the gateways this update pauses"):
+ pause_record.write(intended, owner=pause_record.identity())
+ profiles, mapped_pids, socket_acks = _request_socket_pauses(running_pids, profile_processes, service_gateway_pids)
+ # Resolve venv-side launchers BEFORE draining: a dead worker's parent cannot be recovered (NoSuchProcess).
+ # The launcher keeps ``.pyd`` mapped and would trip the venv-holder guard; it is killed with the survivors.
+ launcher_pids = _m()._venv_launcher_ancestors(mapped_pids)
+ print("→ Stopping Windows gateway process(es) before updating Hermes...")
+ drain_timeout = _gateway_drain_timeout(socket_acks)
+ survivors = _m()._wait_for_windows_update_gateway_exit(mapped_pids, timeout=drain_timeout)
# Tree-kill survivors, unmapped gateways, and pre-drain launchers; a launcher
# already gone with its worker raises ProcessLookupError and is skipped.
force_killed = []
@@ -963,7 +989,17 @@ def _pause_windows_gateways_for_update() -> dict | None:
# socket pause (absent from ``profiles``) but the SCM restart brings them back, not a cold-start.
running_profiles = set(profiles) | {str(p.profile) for p in profile_processes.values()} | {str(s.profile) for s in service_gateways}
_record_attested_cold_start_profiles(token, running_profiles)
- return _pause_windows_gateway_services(service_gateways, token, profiles, unmapped)
+ try:
+ token = _pause_windows_gateway_services(service_gateways, token, profiles, unmapped)
+ except RuntimeError as exc:
+ if "rollback failures" not in str(exc): # everything stopped was restarted in-line
+ pause_record.discharge(intended)
+ raise
+ if adopted is not None:
+ pause_record.merge_into(token, adopted)
+ token.update({key: intended[key] for key in ("pause_id", "pre_sha", "dirty_at_pause", "identities") if key in intended})
+ pause_record.sync(token)
+ return token
def _record_attested_cold_start_profiles(token: dict, running_profiles: set) -> None:
@@ -1299,6 +1335,27 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:
if not _m()._is_windows():
token["resume_needed"] = False
return
+ from hermes_cli import update_pause_record as pause_record
+ if token.get("pause_id"):
+ whole, why = pause_record.tree_is_whole(token)
+ if not whole:
+ # Starting gateways now would boot them on a half-written tree or the pre-sync
+ # dependencies. The durable record keeps the obligation for the next launch, which
+ # runs after the interrupted-pull restore and the dependency sync.
+ print(f" ⚠ Paused gateway(s) left stopped: {why}.\n"
+ " The next `hermes` command (or `hermes update`) restarts them.")
+ token["resume_needed"] = False
+ token["resume_deferred"] = why
+ pause_record.sync(token)
+ return
+ try:
+ _resume_paused_set(token)
+ finally:
+ pause_record.sync(token)
+
+
+def _resume_paused_set(token: dict) -> None:
+ from hermes_cli.update_cmd import _m
# Regenerate launcher scripts before respawning so a legacy pythonw-era
# autostart entry comes back on the current design at next login too.
_m()._refresh_windows_gateway_launchers()
diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.py
index 90b2c0d71bf..dd59b6eb929 100644
--- a/hermes_cli/update_lock.py
+++ b/hermes_cli/update_lock.py
@@ -480,6 +480,41 @@ def _is_ancestor_pid(pid: int) -> bool:
return False
+def _is_runtime_host(cmdline: list[str]) -> bool:
+ """A long-lived Hermes host (``gateway run`` / ``serve`` / ``dashboard``), by the canonical
+ command-line matchers (profile flags, ``hermes_cli/main.py`` paths, inline bootstraps)."""
+ from gateway.status import looks_like_gateway_command_line
+ from hermes_cli.update_cmd_windows import _hermes_holder_subcommand
+ line = " ".join(cmdline)
+ return looks_like_gateway_command_line(line) or _hermes_holder_subcommand(line) in ("serve", "dashboard")
+
+
+def _runtime_host_below(holder_pid: int) -> bool:
+ """True when a Hermes gateway/serve/dashboard sits between us and *holder_pid* (or anywhere
+ above us when the holder is not reached).
+
+ Such a host is relaunched BY an update and outlives its stages; a ``hermes update`` its agent
+ or ``/update`` starts is an independent update that must not run under the first one's claim
+ (cli §7 V9). Unreadable command lines count as not-a-host (the legacy adoption stands).
+ """
+ try:
+ import psutil
+ except ImportError:
+ return False
+ try:
+ proc = psutil.Process().parent()
+ for _ in range(_MAX_ANCESTRY_DEPTH):
+ if proc is None or proc.pid == holder_pid:
+ return False
+ with suppress(psutil.Error):
+ if _is_runtime_host(proc.cmdline()):
+ return True
+ proc = proc.parent()
+ except psutil.Error:
+ return False
+ return False
+
+
# --- the marker --------------------------------------------------------------------------
@@ -1490,7 +1525,7 @@ class UpdateLock:
"""C1 rule 4: a LIVE claim by us, an ancestor or the hand-off partner is run under.
Called inside the marker mutex."""
partners = _live_partners(existing)
- if not any(self._is_partner(p) for p in partners):
+ if not any(self._is_partner(p) and (p == os.getpid() or not _runtime_host_below(p)) for p in partners):
self.holder = UpdateHolder(pid=partners[0], age_seconds=existing.age() if existing.started_at else 0.0)
return False
own = _identity_line()
diff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.py
new file mode 100644
index 00000000000..8fd60dfeb6d
--- /dev/null
+++ b/hermes_cli/update_pause_record.py
@@ -0,0 +1,279 @@
+"""Durable record of the gateways and services ``hermes update`` paused on Windows.
+
+The pause token used to live only in the updater's memory (plus an ``atexit`` resume), so a
+killed updater (console closed, ``taskkill``, power loss) left every paused gateway and SCM
+service stopped with nothing on disk saying so. The record is written under the ROOT Hermes
+home BEFORE anything is stopped, names its owner (pid + creation time, the update-marker
+identity format), is rewritten as the token changes, and is removed only after a verified
+resume. A later launch whose owner check finds the updater dead (and no update live) resumes it.
+
+Resuming is gated on a whole tree: no interrupted-pull marker, no tracked change beyond the ones
+present at pause time, and HEAD still at the pre-update commit or dependencies current for the
+moved HEAD. Otherwise the record stays for the next launch, which runs after the interrupted-pull
+restore and the dependency sync.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import uuid
+from contextlib import suppress
+from pathlib import Path
+
+RECORD_NAME = ".hermes-update-paused-gateways.json"
+# Same tolerance as the update marker's creation-time identity (C1 rule 3).
+_CT_TOLERANCE_S = 2.0
+
+
+def record_path() -> Path:
+ from hermes_constants import get_default_hermes_root
+ return get_default_hermes_root() / RECORD_NAME
+
+
+def install_root() -> Path:
+ return Path(__file__).resolve().parents[1]
+
+
+def _create_time(pid: int) -> float | None:
+ from hermes_cli.process_identity import _process_create_time
+ return _process_create_time(pid)
+
+
+def identity(pid: int | None = None) -> dict:
+ """``{"pid", "ct"}`` with ``ct`` spelled like the update marker's line 3 (``ct:<s.3f>``)."""
+ pid = os.getpid() if pid is None else int(pid)
+ created = _create_time(pid)
+ return {"pid": pid, "ct": None if created is None else f"ct:{created:.3f}"}
+
+
+def identity_is_live(ident: dict | None) -> bool:
+ """Alive (not a zombie) and, when a creation time was recorded, the same incarnation."""
+ from hermes_cli._early_recovery import _pid_is_running
+ try:
+ pid = int((ident or {}).get("pid") or 0)
+ except (TypeError, ValueError):
+ return False
+ if pid <= 0 or not _pid_is_running(pid):
+ return False
+ recorded = str((ident or {}).get("ct") or "")
+ if not recorded.startswith("ct:"):
+ return True
+ actual = _create_time(pid)
+ if actual is None:
+ return True
+ try:
+ return abs(float(recorded[3:]) - actual) <= _CT_TOLERANCE_S
+ except ValueError:
+ return True
+
+
+def _git(root: Path, *args: str) -> subprocess.CompletedProcess | None:
+ try:
+ return subprocess.run(
+ ["git", "-C", str(root), *args], capture_output=True, text=True, encoding="utf-8",
+ errors="replace", stdin=subprocess.DEVNULL, timeout=30, check=False)
+ except (OSError, subprocess.SubprocessError):
+ return None
+
+
+def head_sha(root: Path) -> str | None:
+ result = _git(root, "rev-parse", "--verify", "HEAD")
+ if result is None or result.returncode != 0:
+ return None
+ return result.stdout.strip() or None
+
+
+def tracked_changes(root: Path) -> list[str] | None:
+ """Tracked paths that differ from HEAD (index or worktree); ``None`` when git cannot say."""
+ result = _git(root, "status", "--porcelain=v1", "-z", "--untracked-files=no")
+ if result is None or result.returncode != 0:
+ return None
+ paths = set()
+ entries = result.stdout.split("\0")
+ index = 0
+ while index < len(entries):
+ entry = entries[index]
+ index += 1
+ if len(entry) < 4:
+ continue
+ paths.add(entry[3:])
+ if entry[0] in "RC": # rename/copy: the source path follows as its own entry
+ index += 1
+ return sorted(paths)
+
+
+def stamp_tree(token: dict, root: Path | None = None) -> dict:
+ """Record what "the tree before this update" was, for the whole-tree gate."""
+ root = root or install_root()
+ if (root / ".git").exists():
+ token.setdefault("pre_sha", head_sha(root))
+ token.setdefault("dirty_at_pause", tracked_changes(root))
+ token.setdefault("pause_id", uuid.uuid4().hex)
+ return token
+
+
+def _venv_is_current(root: Path) -> bool:
+ try:
+ import pm
+ return bool(pm.venv_is_current(project_root=root))
+ except Exception:
+ return False
+
+
+def tree_is_whole(token: dict, root: Path | None = None) -> tuple[bool, str]:
+ """May paused gateways start on this checkout now? ``(verdict, reason when not)``."""
+ from hermes_cli._early_recovery import interrupted_pull_marker
+ root = root or install_root()
+ if (root / ".git").exists():
+ if interrupted_pull_marker(root).exists():
+ return False, "the checkout is mid-pull (interrupted-pull marker present)"
+ changes = tracked_changes(root)
+ if changes is None:
+ return False, "git cannot read the checkout state"
+ unexpected = sorted(set(changes) - set(token.get("dirty_at_pause") or []))
+ if unexpected:
+ return False, f"the checkout has {len(unexpected)} file(s) git left half-written (e.g. {unexpected[0]})"
+ head = head_sha(root)
+ if head is None:
+ return False, "the checkout HEAD is unreadable"
+ if head == token.get("pre_sha"):
+ return True, ""
+ if not _venv_is_current(root):
+ return False, "dependencies are not current for the updated code yet"
+ return True, ""
+
+
+def _atomic_write(path: Path, body: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(body, fh, indent=1, sort_keys=True)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(tmp, path)
+
+
+def read(path: Path | None = None) -> dict | None:
+ path = path or record_path()
+ try:
+ body = json.loads(path.read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ return None
+ return body if isinstance(body, dict) and isinstance(body.get("token"), dict) else None
+
+
+def write(token: dict, *, owner: dict | None = None, path: Path | None = None) -> None:
+ """Persist *token*; the owner of an existing record for the same pause is kept."""
+ path = path or record_path()
+ existing = read(path)
+ if owner is None:
+ if existing is not None and existing["token"].get("pause_id") == token.get("pause_id"):
+ owner = existing["owner"]
+ else:
+ owner = identity()
+ _atomic_write(path, {"schema": 1, "owner": owner, "install_root": str(install_root()), "token": token})
+
+
+def discharge(token: dict, path: Path | None = None) -> None:
+ """Compare-and-delete: remove the record only while it still names this pause."""
+ path = path or record_path()
+ existing = read(path)
+ if existing is not None and existing["token"].get("pause_id") == token.get("pause_id"):
+ with suppress(OSError):
+ path.unlink()
+
+
+def sync(token: dict) -> None:
+ """Mirror the token after a resume attempt: done → delete; anything still owed → rewrite."""
+ if not token.get("pause_id"):
+ return
+ try:
+ if token.get("resume_needed") or token.get("resume_deferred"):
+ owed = {**token, "resume_needed": True}
+ owed.pop("resume_deferred", None)
+ write(owed)
+ else:
+ discharge(token)
+ except OSError as exc:
+ print(f" ⚠ Could not update the paused-gateway record {record_path()}: {exc}")
+
+
+def _live_update_elsewhere() -> bool:
+ # TODO(LP-LOCK): switch to update_lock.update_in_progress(install_root) once it lands; the
+ # marker read below is the existing path and misses an orphaned completion child.
+ from hermes_cli.update_lock import read_live_update
+ holder = read_live_update()
+ return holder is not None and holder.pid != os.getpid()
+
+
+def orphaned_record(path: Path | None = None) -> dict | None:
+ """The record when its owner is dead, it belongs to this install and no other update is live."""
+ body = read(path)
+ if body is None or body.get("install_root") != str(install_root()):
+ return None
+ if identity_is_live(body.get("owner")) or _live_update_elsewhere():
+ return None
+ return body
+
+
+def drop_never_stopped(token: dict) -> dict:
+ """Entries whose recorded process is still the same live incarnation were never stopped."""
+ alive = {pid for pid, ct in (token.get("identities") or {}).items()
+ if identity_is_live({"pid": pid, "ct": ct})}
+ token["profiles"] = {p: pid for p, pid in (token.get("profiles") or {}).items() if str(pid) not in alive}
+ token["unmapped"] = [u for u in (token.get("unmapped") or []) if str(u.get("pid")) not in alive]
+ return token
+
+
+def merge_into(token: dict | None, adopted: dict) -> dict:
+ """Fold an orphaned pause into this update's token so its resume brings both sets back."""
+ token = token if token is not None else {"resume_needed": True, "profiles": {}, "unmapped_pids": [], "unmapped": []}
+ token["resume_needed"] = True
+ profiles = token.setdefault("profiles", {})
+ for name, pid in (adopted.get("profiles") or {}).items():
+ profiles.setdefault(name, pid)
+ token.setdefault("unmapped", []).extend(adopted.get("unmapped") or [])
+ services = token.setdefault("services", [])
+ services.extend(s for s in adopted.get("services") or [] if s not in services)
+ if services:
+ token.setdefault("expected_services", []).extend(s for s in services if s not in token["expected_services"])
+ token.setdefault("restarted_services", [])
+ token.setdefault("service_profiles", {}).update(adopted.get("service_profiles") or {})
+ return token
+
+
+def recover(argv: list[str] | None = None) -> None:
+ """Start-of-run recovery: resume an orphaned pause. Never raises."""
+ from hermes_cli._parser import command_argv
+ command = command_argv(list(sys.argv[1:] if argv is None else argv))
+ if command[:1] == ["update"] or command[:2] == ["gateway", "run"]:
+ return # the update adopts it itself; a booting gateway must not block on its siblings
+ try:
+ body = orphaned_record()
+ if body is None:
+ return
+ path = record_path()
+ claim = path.with_name(f"{path.name}.{os.getpid()}.claim")
+ try:
+ os.rename(path, claim) # exactly one concurrent launch wins the record
+ except OSError:
+ return
+ token = drop_never_stopped(dict(body["token"]))
+ token["resume_needed"] = True
+ print("→ Restarting gateway(s) paused by an interrupted `hermes update`...", file=sys.stderr)
+ try:
+ # Its own finally mirrors the outcome: whatever is still owed is re-recorded
+ # under this process, so the next launch retries once we have exited.
+ from hermes_cli.update_cmd_windows import _resume_windows_gateways_after_update
+ _resume_windows_gateways_after_update(token)
+ except Exception as exc:
+ print(f" ⚠ Could not restart every paused gateway: {exc}. Run `hermes update` or "
+ "`hermes gateway start`.", file=sys.stderr)
+ finally:
+ with suppress(OSError):
+ claim.unlink()
+ except Exception as exc: # never brick a launch on recovery
+ print(f" ⚠ Paused-gateway recovery skipped: {exc}", file=sys.stderr)