The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): pause POSIX gateways before the first checkout move, restart them after deps
Teknium59b5808bc8d2
diff --git a/hermes_cli/source_completion.py b/hermes_cli/source_completion.pyindex a0c417327b1..8d7b4f8c92b 100644--- a/hermes_cli/source_completion.py+++ b/hermes_cli/source_completion.py@@ -37,9 +37,13 @@ def complete_source_checkout(completion_message: str | None = None,announce: str | None = None,followups: list[tuple[str, str]] | None = None,+ before_build=None,) -> bool:"""Publish commands, build the products, then run post-build maintenance.+ ``before_build`` (an update's paused-gateway restart) runs once the launchers are published:+ dependencies are already synced, the long product builds have not started.+Every step runs even when an earlier one failed; each failure is printed as ``⚠``,recorded on the open update receipt and appended to ``followups`` as ``(step, reason)``.Returns True only when every step finished and the SQLite runtime is not unsafe.@@ -70,6 +74,7 @@ def complete_source_checkout(pre_update_snapshot_id=pre_update_snapshot_id,pre_update_version=pre_update_version,completion_message=completion_message, announce=announce, followups=followups,+ before_build=before_build,)finally:lock.release()@@ -86,6 +91,7 @@ def _complete_locked(completion_message: str | None,announce: str | None,followups: list[tuple[str, str]] | None = None,+ before_build=None,) -> bool:"""The completion body; callers hold the update lock already."""from hermes_cli.source_build import build_update_products@@ -115,6 +121,8 @@ def _complete_locked(owed.append((name, reason))step("launchers", lambda: publish_launchers(root))+ if before_build is not None:+ before_build() # never raises: a failed restart stays owed and is retried after the buildstep("build", lambda: build_update_products(root, desktop=desktop))if announce:print(announce)diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 48a98e6039d..a7563760704 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -30,6 +30,7 @@ from hermes_cli import update_receipt as _completion_receipt, update_cmd_configfrom hermes_cli._old_updater import stop_for_relaunchfrom hermes_cli._early_recovery import git_operation_in_progress, interrupted_pull_marker, is_object_idfrom hermes_cli import update_cmd_commit as _commit+from hermes_cli import update_cmd_posix_pause as _posix_pausefrom hermes_cli.update_cmd_pause_gate import _checkout_move, _moves_for # noqa: F401 (re-export)from hermes_cli import update_cmd_check as _check@@ -388,6 +389,9 @@ def _gateway_prompt(prompt_text: str, default: str = "", timeout: float = 300.0)import uuid as _uuidfrom hermes_constants import get_hermes_home+ if _posix_pause.gateways_paused(): # the gateway that would relay it is stopped for the update+ print(f" → {prompt_text} → {default or '(empty)'} (gateways are paused for the update)")+ return defaulthome = get_hermes_home()prompt_path = home / ".update_prompt.json"response_path = home / ".update_response"@@ -1379,7 +1383,9 @@ def _prepare_checkout_for_update(# Keep the running code AND its branch identity for syntax rollback.moved_from_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)rollback_branch = current_branch- # The switch (or its -B fallback) is this update's first tree write: bind both commits first.+ # The switch (or its -B fallback) is this update's first tree write: bind both commits first,+ # on the POSIX pause's baseline (its refusal, sticky, reaches the switch's arm_commit_point).+ _posix_pause.pause_at_commit_point()with _checkout_move(_windows_gateway_resume, *(_resolved_commit(git_cmd, ref) for ref in (f"refs/heads/{branch}", f"origin/{branch}"))):track_result = _switch_branch_at_commit_point(@@ -1764,12 +1770,12 @@ def _cmd_update_impl(args, gateway_mode: bool):_record_pre_update_backup_outcome(args, pre_update_snapshot_id)_record_snapshot_stage(args, pre_update_snapshot_id)- _windows_gateway_resume = _m()._pause_windows_gateways_for_update()+ # Windows pauses here (venv locks); Linux/macOS only arm a pause the commit point performs.+ _windows_gateway_resume = _m()._pause_windows_gateways_for_update() or _posix_pause.arm_pause(+ no_gateway_restart=opts.no_gateway_restart)if _windows_gateway_resume:import atexit as _atexit_atexit.register(_m()._resume_windows_gateways_after_update, _windows_gateway_resume)--desktop_dir = _m().PROJECT_ROOT / "apps" / "desktop"# An installed Hermes.app only this update refreshes counts even with no release/ build# beside it: without one it was never rebuilt, so it never got newer (#52339).diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.pyindex 7b53f0c9e12..cc4abd2e3b6 100644--- a/hermes_cli/update_cmd_commit.py+++ b/hermes_cli/update_cmd_commit.py@@ -180,7 +180,11 @@ def arm_commit_point(git_cmd, root: Path, expected_sha: str, **move) -> str | No``None`` when both are durable; otherwise why not, with the obligations handed back(``disarm_commit_obligations``), and the caller must stop before git writes a file.+ Linux/macOS gateways are paused first: this is every route's first checkout move."""+ from hermes_cli.update_cmd_posix_pause import pause_at_commit_point+ if refused := pause_at_commit_point():+ return refusedtry:arm_commit_obligations(root, expected_sha)arm_tree_move(git_cmd, root, **move)diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex f67dd71e419..86a81c67491 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -921,11 +921,13 @@ def _restart_macos_launchd_gateways(if listing.returncode != 0:failed_or_stale_units.append("launchd (listing failed)")return- _restarted, _failed = _restart_launchd_gateway_after_update(+ from hermes_cli.update_cmd_posix_pause import already_restarted+ current_label = get_launchd_label()+ resumed = already_restarted()["labels"] # paused for the update, restarted on the new code+ _restarted, _failed = ([], []) if current_label in resumed else _restart_launchd_gateway_after_update(supervision_verify=True, self_restart_pending=self_restart_pending)restarted_services.extend(_restarted)failed_or_stale_units.extend(_failed)- current_label = get_launchd_label()derived_labels = launchd_gateway_labels_for_install()# Units labelled before the profile-name suffix scheme (ai.hermes.gateway-<hash>) are invisible@@ -937,7 +939,7 @@ def _restart_macos_launchd_gateways(print(f" ↻ legacy-labelled units of this install join the restart: {', '.join(legacy_labels)}")from hermes_cli.update_fleet_scope import describe_skipped_runtime, launchd_label_foreign_homefor label in derived_labels + legacy_labels:- if label == current_label:+ if label == current_label or label in resumed:continue# Labels are account-global: root B's default profile derives the same bare label root A# installed. A plist pinning a foreign HERMES_HOME is another install's job (#93349).@@ -1390,8 +1392,12 @@ def _restart_systemd_gateway_units("together with: hermes gateway migrate")+ from hermes_cli.update_cmd_posix_pause import already_restartedfor key in keys:scope, scope_cmd, svc_name = targets[key]+ if key in already_restarted()["units"]: # paused for the update, restarted on the new code+ restarted_scoped_units.add(key)+ continue# Scope-qualify before the next unit; ``finally`` so a mid-pass abort keeps settled units._scope_mark = len(restarted_services)try:@@ -1485,7 +1491,9 @@ def _restart_manual_gateways(out: _GatewayRestartOutcome, _drain_budget) -> None_wait_for_gateway_exit,)# Exclude just-restarted service PIDs so we don't kill what systemd/launchd spawned.- service_pids = _get_service_pids(all_profiles=True)+ from hermes_cli.update_cmd_posix_pause import already_restarted+ # Plus the gateways this update paused and already restarted on the new code.+ service_pids = _get_service_pids(all_profiles=True) | already_restarted()["pids"]manual_pids = find_gateway_pids(exclude_pids=service_pids, all_profiles=True)profile_processes = {proc.pid: procdiff --git a/hermes_cli/update_cmd_posix_pause.py b/hermes_cli/update_cmd_posix_pause.pynew file mode 100644index 00000000000..1664e389f23--- /dev/null+++ b/hermes_cli/update_cmd_posix_pause.py@@ -0,0 +1,534 @@+"""Pre-swap gateway pause for ``hermes update`` on Linux and macOS.++Windows pauses its gateways before the fetch (``update_cmd_windows``) because they lock venv+files. On POSIX nothing is locked, but a gateway that keeps running while git rewrites the tree+loads new-tree modules into an old process on its next lazy import. So every gateway running+from this install is stopped at the commit point, immediately before the first checkout move+(``update_cmd_commit.arm_commit_point``), and the same set is restarted once the dependencies+are synced and the launchers published, before the product builds+(``source_completion.complete_source_checkout``'s ``before_build``).++The set rides the Windows pause contract: one token in ``update_pause_record`` (identity = pid++ start time; supervisor unit, or argv + home for bare processes), written before the first stop,+resumed by ``_resume_windows_gateways_after_update`` (which dispatches here on+``platform == "posix"``), adopted by the next ``hermes update`` and resumed by the next launch+when this process dies.++* systemd ``hermes-gateway*`` units and launchd ``ai.hermes.gateway*`` jobs are stopped and+ started through their supervisor, so it cannot respawn them on old code mid-update.+* bare ``gateway run`` processes are drained (planned-stop marker, then the control socket's+ ``pause-for-update``, SIGTERM fallback) and replayed from their recorded argv + home.+* the updater never kills itself: a unit whose cgroup holds this process (``/update`` from+ chat: the update runs in the gateway unit's cgroup, which ``systemctl stop`` kills) is+ stopped only after this process moved into a transient scope of its own. A launchd job+ whose coalition holds it, or any gateway whose stop would take the updater down, is left+ running for the post-commit restart.+"""++from __future__ import annotations++import os+import signal+import subprocess+import sys+import time+from contextlib import suppress+from pathlib import Path++#: This run's token: armed in ``_cmd_update_impl``, filled at the commit point. Same dict object+#: the completion request carries, so the paused set reaches the completion child.+_RUN: dict | None = None+#: Runtimes the early resume already restarted on the new code: the late fleet restart in the+#: same completion process must not restart them a second time.+_RESTARTED: dict = {"units": set(), "labels": set(), "pids": set()}++_STOP_TIMEOUT_S = 120.0+_READY_TIMEOUT_S = 30.0+++class PauseRefused(RuntimeError):+ """The pause could not be completed; everything it stopped was started again."""+++def _empty_token() -> dict:+ return {"platform": "posix", "resume_needed": False, "profiles": {}, "unmapped_pids": [],+ "unmapped": [], "posix_units": []}+++def arm_pause(*, no_gateway_restart: bool) -> dict | None:+ """Arm this run's pause (no stop yet) and adopt any set a killed update left paused.++ ``None`` on Windows (its own pause) and with ``--no-gateway-restart`` (the user manages+ gateways, nothing is stopped). An adopted orphan set is recorded under this process now, so+ even an update that never moves the checkout restarts it at exit."""+ global _RUN+ if sys.platform == "win32" or no_gateway_restart:+ return None+ from hermes_cli import update_pause_record as pause_record+ token = _empty_token()+ try:+ adopted, claims = pause_record.adopt_orphans()+ if adopted is not None:+ token = pause_record.record_pause({**token, "resume_needed": True}, adopted, claims)+ token["platform"] = "posix"+ except Exception as exc: # health: allow BLE001 -- an unreadable record must not block the update; recovery retries it+ print(f" ⚠ Could not adopt gateways an earlier update paused: {exc}")+ _RUN = token+ return token+++def gateways_paused() -> bool:+ """True while this run holds gateways stopped (no gateway can answer a chat prompt)."""+ return bool(_RUN and _RUN.get("posix_stopped") and _RUN.get("resume_needed"))+++# --------------------------------------------------------------------------- discovery++def _unit_cgroup(scope_cmd: list, unit: str) -> str | None:+ from hermes_cli.update_cmd_fleet import _systemctl+ with suppress(OSError, subprocess.TimeoutExpired):+ result = _systemctl(scope_cmd + ["show", unit, "--property=ControlGroup", "--value"], timeout=10)+ if result.returncode == 0 and result.stdout.strip():+ return result.stdout.strip()+ return None+++def _pid_cgroup(pid: int | str = "self") -> str | None:+ """The cgroup-v2 path of *pid* (``None``: not Linux, v1-only, or unreadable)."""+ with suppress(OSError):+ for line in Path(f"/proc/{pid}/cgroup").read_text(encoding="utf-8").splitlines():+ if line.startswith("0::"):+ return line[3:].strip()+ return None+++def _inside(cgroup: str | None, unit_cgroup: str | None) -> bool:+ if not cgroup or not unit_cgroup:+ return False+ return cgroup == unit_cgroup or cgroup.startswith(unit_cgroup.rstrip("/") + "/")+++def _discover_systemd() -> list[dict]:+ """Active ``hermes-gateway*`` units of this install, one per live MainPID."""+ from hermes_cli.gateway import _ensure_user_systemd_env, supports_systemd_services+ from hermes_cli.update_cmd_fleet import (+ _for_each_systemd_gateway_unit, _systemd_gateway_unit_listings, _systemd_unit_owned_by_update,+ _unit_main_pid,+ )+ if not supports_systemd_services():+ return []+ with suppress(Exception):+ _ensure_user_systemd_env()+ units: list[dict] = []+ seen_pids: set[int] = set()+ for scope, scope_cmd, listing in _systemd_gateway_unit_listings():+ names: list[str] = []+ _for_each_systemd_gateway_unit(listing.stdout, process_unit=names.append,+ on_unit_timeout=lambda name, exc: None)+ for name in names:+ if not name.startswith("hermes-gateway"):+ continue # serve/dashboard units are not gateways: the post-commit restart owns them+ pid = _unit_main_pid(scope_cmd, name)+ if pid <= 0 or pid in seen_pids or not _systemd_unit_owned_by_update(scope_cmd, name):+ continue+ seen_pids.add(pid) # a legacy per-profile unit sharing the multiplexer's PID is one process+ units.append({"kind": "systemd", "scope": scope, "unit": name, "pid": pid,+ "cgroup": _unit_cgroup(scope_cmd, name)})+ return units+++def _discover_launchd() -> list[dict]:+ """Loaded ``ai.hermes.gateway*`` jobs of this install with a live process (macOS)."""+ if sys.platform != "darwin":+ return []+ from hermes_cli.gateway import (+ _locate_launchd_gateway_service, get_launchd_plist_path, launchd_gateway_labels_for_install,+ legacy_launchd_labels_for_install,+ )+ from hermes_cli.update_fleet_scope import launchd_label_foreign_home+ derived = launchd_gateway_labels_for_install()+ jobs = []+ for label in derived + legacy_launchd_labels_for_install(exclude=set(derived)):+ if launchd_label_foreign_home(label) is not None:+ continue+ domain, pid = _locate_launchd_gateway_service(label)+ if domain is None or not pid or pid <= 0:+ continue+ plist = get_launchd_plist_path().with_name(f"{label}.plist")+ jobs.append({"kind": "launchd", "label": label, "domain": domain, "plist": str(plist), "pid": int(pid)})+ return jobs+++def _supervisor_markers(pid: int) -> str | None:+ """Why *pid* answers to a supervisor other than a hermes unit/job (it would respawn it on old+ code), or ``None``."""+ from hermes_cli.gateway import _capture_gateway_argv+ if "--external-supervisor" in (_capture_gateway_argv(pid) or []):+ return "--external-supervisor"+ try:+ import psutil # type: ignore+ env = psutil.Process(pid).environ()+ except Exception: # health: allow BLE001 -- unreadable environment: no marker proven+ return None+ if env.get("HERMES_S6_SUPERVISED_CHILD"):+ return "s6"+ if env.get("INVOCATION_ID"):+ return "a systemd unit outside hermes-gateway*"+ if env.get("XPC_SERVICE_NAME", "0") not in ("", "0"):+ return f"launchd job {env['XPC_SERVICE_NAME']}"+ return None+++def _discover_bare(service_pids: set[int]) -> tuple[list[dict], list[str]]:+ """``(bare gateways, notices)``: this install's ``gateway run`` processes outside any unit."""+ from gateway.status import get_process_start_time+ from hermes_cli.gateway import _capture_gateway_argv, _get_service_pids, find_gateway_pids+ from hermes_cli.update_cmd_fleet import _scoped_manual_gateway_pids+ from hermes_cli.update_fleet_scope import gateway_pid_home+ exclude = set(service_pids) | set(_get_service_pids(all_profiles=True))+ pids = _scoped_manual_gateway_pids(find_gateway_pids(exclude_pids=exclude, all_profiles=True))+ bare, notices = [], []+ for pid in pids:+ pid = int(pid)+ marker = _supervisor_markers(pid)+ argv, home = _capture_gateway_argv(pid), gateway_pid_home(pid)+ if marker or not argv or not home:+ why = f"supervised by {marker}" if marker else "its command line could not be read" if not argv \+ else "its Hermes home could not be proved"+ notices.append(f" ↷ gateway PID {pid} keeps running until after the update ({why})")+ continue+ bare.append({"pid": pid, "argv": list(argv), "home": str(home), "ct": get_process_start_time(pid)})+ return bare, notices+++# --------------------------------------------------------------------------- self-preservation++def _ppid(pid: int) -> int:+ with suppress(OSError, ValueError, IndexError):+ stat = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")+ return int(stat.rsplit(")", 1)[1].split()[1])+ return 0+++def _escape_cgroup(unit: dict) -> bool:+ """Move this process (and its ancestors in the same unit, e.g. ``/update``'s bash wrapper)+ into a transient scope so stopping *unit* cannot kill it. True when out (or never in)."""+ if not _inside(_pid_cgroup(), unit.get("cgroup")):+ return True+ from gateway.status import looks_like_gateway_command_line+ pids, pid = [], os.getpid()+ while pid > 1 and pid != unit["pid"] and _inside(_pid_cgroup(pid), unit["cgroup"]):+ with suppress(OSError):+ cmdline = Path(f"/proc/{pid}/cmdline").read_bytes().replace(b"\0", b" ").decode("utf-8", "replace")+ if pid != os.getpid() and looks_like_gateway_command_line(cmdline):+ break+ pids.append(pid)+ pid = _ppid(pid)+ bus = "--user" if unit["scope"] == "user" else "--system"+ cmd = ["busctl", bus, "call", "org.freedesktop.systemd1", "/org/freedesktop/systemd1",+ "org.freedesktop.systemd1.Manager", "StartTransientUnit", "ssa(sv)a(sa(sv))",+ f"hermes-update-{os.getpid()}.scope", "fail", "2", "PIDs", "au", str(len(pids)), *map(str, pids),+ "Description", "s", f"hermes update (outside {unit['unit']} while it is paused)", "0"]+ with suppress(OSError, subprocess.SubprocessError):+ subprocess.run(cmd, capture_output=True, text=True, timeout=15, check=False)+ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline:+ if not _inside(_pid_cgroup(), unit["cgroup"]):+ return True+ time.sleep(0.1)+ return False+++def _left_running(units: list[dict], jobs: list[dict]) -> tuple[list[dict], list[dict], list[str]]:+ """Drop the runtimes whose stop would kill this updater; name each one."""+ from hermes_cli.gateway import _is_pid_ancestor_of_current_process+ keep_units, keep_jobs, notices = [], [], []+ for unit in units:+ if _escape_cgroup(unit):+ keep_units.append(unit)+ else:+ notices.append(f" ↷ {unit['unit']} keeps running until after the update (this update runs "+ "inside its cgroup and could not move out)")+ for job in jobs:+ if (_is_pid_ancestor_of_current_process(job["pid"])+ or os.environ.get("XPC_SERVICE_NAME") == job["label"]):+ notices.append(f" ↷ {job['label']} keeps running until after the update (this update runs "+ "inside its launchd job)")+ else:+ keep_jobs.append(job)+ return keep_units, keep_jobs, notices+++# --------------------------------------------------------------------------- stop / start++def _manage_cmd(scope: str) -> list | None:+ from hermes_cli.update_cmd_fleet import _needs_sudo, _sudo_noninteractive_ok+ cmd = ["systemctl", "--user"] if scope == "user" else ["systemctl"]+ cmd = cmd + ["--no-ask-password"]+ if scope == "system" and _needs_sudo(scope):+ sudo = ["sudo", "-n", *cmd]+ return sudo if _sudo_noninteractive_ok(cmd + ["show", "-p", "Id", "hermes-gateway"]) else None+ return cmd+++def _stop_unit(unit: dict) -> None:+ from hermes_cli.update_cmd_fleet import _systemctl+ cmd = _manage_cmd(unit["scope"])+ if cmd is None:+ raise PauseRefused(f"no privilege to stop system unit {unit['unit']}")+ result = _systemctl(cmd + ["stop", unit["unit"]], timeout=_STOP_TIMEOUT_S)+ if result.returncode != 0:+ raise PauseRefused(f"systemctl stop {unit['unit']} failed: {(result.stderr or '').strip()}")+++def _start_unit(unit: dict) -> int:+ """Start *unit* through systemd; the new MainPID (raises when it does not come up)."""+ from hermes_cli.update_cmd_fleet import _systemctl, _unit_main_pid, _wait_for_service_active+ cmd = _manage_cmd(unit["scope"])+ if cmd is None:+ raise RuntimeError(f"no privilege to start system unit {unit['unit']}")+ _systemctl(cmd + ["reset-failed", unit["unit"]], timeout=10)+ result = _systemctl(cmd + ["start", unit["unit"]], timeout=_STOP_TIMEOUT_S)+ scope_cmd = ["systemctl", "--user"] if unit["scope"] == "user" else ["systemctl"]+ if result.returncode != 0 or not _wait_for_service_active(scope_cmd, unit["unit"], timeout=15.0):+ raise RuntimeError(f"{unit['unit']} did not start: {(result.stderr or '').strip() or 'not active'}")+ return _unit_main_pid(scope_cmd, unit["unit"])+++def _stop_job(job: dict) -> None:+ from hermes_cli.update_cmd_windows import _write_update_planned_stop_marker+ from hermes_cli.update_fleet_scope import gateway_pid_home+ if home := gateway_pid_home(job["pid"]):+ _write_update_planned_stop_marker(Path(home), job["pid"])+ result = subprocess.run(["launchctl", "bootout", f"{job['domain']}/{job['label']}"],+ capture_output=True, text=True, timeout=90, check=False)+ if result.returncode != 0 and _alive(job["pid"], None):+ raise PauseRefused(f"launchctl bootout {job['label']} failed: {(result.stderr or '').strip()}")+ _wait_gone([job["pid"]], 30.0)+++def _start_job(job: dict) -> None:+ from hermes_cli.gateway import _launchctl_bootstrap, _wait_for_launchd_service_pid+ _launchctl_bootstrap(job["domain"], job["plist"], job["label"])+ subprocess.run(["launchctl", "kickstart", f"{job['domain']}/{job['label']}"],+ capture_output=True, text=True, timeout=30, check=False)+ if not _wait_for_launchd_service_pid(job["label"], old_pid=job["pid"], timeout=15.0, domain=job["domain"]):+ raise RuntimeError(f"{job['label']} did not come back under launchd")+++def _alive(pid: int, ct) -> bool:+ from gateway.status import _pid_exists, get_process_start_time+ try:+ if not _pid_exists(int(pid)):+ return False+ except Exception: # health: allow BLE001 -- unknown liveness counts as alive (never relaunch a twin)+ return True+ return ct is None or get_process_start_time(int(pid)) in (None, ct)+++def _wait_gone(pids, timeout: float, born: dict | None = None) -> set[int]:+ deadline = time.monotonic() + timeout+ live = set(pids)+ while live and time.monotonic() < deadline:+ live = {pid for pid in live if _alive(pid, (born or {}).get(pid))}+ if live:+ time.sleep(0.2)+ return live+++def _drain_timeout(acks: list[dict]) -> float:+ from hermes_cli.gateway import _get_restart_drain_timeout+ budget = 30.0+ with suppress(Exception):+ budget = max(float(_get_restart_drain_timeout()), 1.0)+ with suppress(Exception):+ budget = max([budget, *(float(a.get("drain_timeout") or 0) + 10.0 for a in acks)])+ return budget+++def _stop_bare(token: dict, bare: list[dict]) -> None:+ """Drain every bare gateway (marker + socket pause, SIGTERM fallback), then kill survivors of+ the same birth. A stopped bare gateway is never relaunched by anything but this pause."""+ from gateway.control_socket import pause_gateway_for_update+ from hermes_cli import update_pause_record as pause_record+ from hermes_cli.update_cmd_windows import _write_update_planned_stop_marker+ acks, signalled = [], []+ for entry in bare:+ pid, home = entry["pid"], Path(entry["home"])+ _write_update_planned_stop_marker(home, pid)+ ack = None+ with suppress(Exception):+ ack = pause_gateway_for_update(home)+ if ack and (ack.get("pausing") or ack.get("already_stopping")):+ acks.append(ack)+ else:+ with suppress(ProcessLookupError, PermissionError):+ os.kill(pid, signal.SIGTERM)+ signalled.append(pid)+ pause_record.mark_stop_sent(token, pid)+ born = {e["pid"]: e["ct"] for e in bare}+ survivors = _wait_gone(born, _drain_timeout(acks), born)+ for pid in survivors:+ with suppress(ProcessLookupError, PermissionError):+ os.kill(pid, signal.SIGKILL)+ if _wait_gone(survivors, 10.0, born):+ raise PauseRefused("gateway PID(s) " + ", ".join(map(str, sorted(survivors))) + " did not stop")+++def _gateway_on_home(home: str, exclude: set[int]) -> int | None:+ from hermes_cli.gateway import find_gateway_pids+ from hermes_cli.update_fleet_scope import gateway_pid_home+ want = os.path.realpath(home)+ with suppress(Exception):+ for pid in find_gateway_pids(all_profiles=True):+ found = gateway_pid_home(int(pid))+ if int(pid) not in exclude and found and os.path.realpath(found) == want:+ return int(pid)+ return None+++def _relaunch_bare(entry: dict) -> int:+ """Replay a bare gateway from its recorded argv under its recorded home; the new PID once it+ is serving. A gateway already serving that home (an earlier attempt's) is adopted instead."""+ if (existing := _gateway_on_home(entry["home"], {int(entry["pid"])})) is not None:+ return existing+ logs = Path(entry["home"]) / "logs"+ logs.mkdir(parents=True, exist_ok=True)+ env = {**os.environ, "HERMES_HOME": entry["home"]}+ for leaked in ("INVOCATION_ID", "JOURNAL_STREAM", "HERMES_UPDATE_PAUSED"):+ env.pop(leaked, None)+ with open(logs / "gateway-update-resume.log", "ab") as log:+ proc = subprocess.Popen(list(entry["argv"]), env=env, stdin=subprocess.DEVNULL, stdout=log,+ stderr=subprocess.STDOUT, start_new_session=True, close_fds=True)+ deadline = time.monotonic() + _READY_TIMEOUT_S+ while time.monotonic() < deadline:+ if proc.poll() is not None:+ raise RuntimeError(f"replayed gateway for {entry['home']} exited {proc.returncode} "+ f"(see {logs / 'gateway-update-resume.log'})")+ if (pid := _gateway_on_home(entry["home"], {int(entry["pid"])})) is not None:+ return pid+ time.sleep(0.5)+ raise RuntimeError(f"replayed gateway for {entry['home']} did not come up within {int(_READY_TIMEOUT_S)}s")+++def _describe(token: dict) -> str:+ names = [u.get("unit") or u.get("label") for u in token.get("posix_units") or []]+ names += [f"gateway PID {u['pid']}" for u in token.get("unmapped") or [] if u.get("argv")]+ return ", ".join(names)+++# --------------------------------------------------------------------------- the commit point++def pause_at_commit_point() -> str | None:+ """Stop this install's gateways before the first checkout move; once per run.++ Returns a refusal (the caller must not move the checkout) when the pause could not complete;+ by then everything it stopped is running again on the unchanged code. The verdict is sticky:+ every later move of this run gets the same answer."""+ token = _RUN+ if token is None:+ return None+ if "posix_pause_verdict" not in token:+ token["posix_pause_verdict"] = _pause(token)+ return token["posix_pause_verdict"]+++def _pause(token: dict) -> str | None:+ from hermes_cli import update_pause_record as pause_record+ try:+ units, jobs = _discover_systemd(), _discover_launchd()+ units, jobs, notices = _left_running(units, jobs)+ bare, more = _discover_bare({u["pid"] for u in units} | {j["pid"] for j in jobs})+ except Exception as exc: # health: allow BLE001 -- a discovery that cannot finish stops nothing+ return f"could not discover the running gateways before the update ({exc}); nothing was stopped"+ for line in notices + more:+ print(line)+ supervised = units + jobs+ if not supervised and not bare:+ return None+ for entry in supervised + bare:+ entry["ct"] = entry.get("ct") or pause_record.identity(entry["pid"])["ct"]+ token["posix_units"] = [*token.get("posix_units", []), *supervised]+ token["unmapped"] = [*token.get("unmapped", []), *bare]+ token["unmapped_pids"] = [*token.get("unmapped_pids", []), *(e["pid"] for e in bare)]+ token["identities"] = {**token.get("identities", {}), **{str(e["pid"]): e["ct"] for e in supervised + bare}}+ token["resume_needed"] = True+ try:+ from hermes_cli.update_cmd_windows import _planned_stop_marker_path+ pause_record.record_pause(token, None, [])+ pause_record.mark_stop_requested(+ token, [e["pid"] for e in supervised + bare],+ markers={e["pid"]: _planned_stop_marker_path(Path(e["home"])) for e in bare})+ except Exception as exc: # health: allow BLE001 -- no durable record, no stop+ token["resume_needed"] = False+ return f"could not record the gateways this update pauses ({exc}); nothing was stopped"+ # From here a refusal or a crash leaves the set owed: the command's own exit resume (registered+ # in ``_cmd_update_impl`` for this token), else the next launch's recovery, restarts it.+ token["posix_stopped"] = True+ try:+ for entry in supervised:+ (_stop_unit if entry["kind"] == "systemd" else _stop_job)(entry)+ pause_record.mark_stop_sent(token, entry["pid"])+ _stop_bare(token, bare)+ except Exception as exc: # health: allow BLE001 -- roll back: restart the stopped set on the old code+ print(f" ✗ Could not pause every gateway ({exc}); restarting them on the current code")+ try:+ resume_paused_set(token)+ except Exception as again: # health: allow BLE001 -- still owed: the record keeps it for the next launch+ pause_record.sync(token)+ return f"could not pause the gateways ({exc}) and some did not restart ({again}); nothing was changed"+ pause_record.sync(token)+ return f"could not pause the gateways ({exc}); nothing was changed"+ pause_record.sync(token)+ print(f" ⏸ Paused for the update: {_describe(token)} (restarted once the dependencies are synced)")+ return None+++# --------------------------------------------------------------------------- resume++def resume_paused_set(token: dict) -> None:+ """Start every paused runtime again; each leaves *token* only on its own verified start."""+ failures: list[str] = []+ restarted: list[str] = []+ kept_units = []+ for entry in token.get("posix_units") or []:+ try:+ if entry.get("kind") == "launchd":+ _start_job(entry)+ _RESTARTED["labels"].add(entry["label"])+ name = entry["label"]+ else:+ _RESTARTED["pids"].add(_start_unit(entry))+ _RESTARTED["units"].add(f"{entry['scope']}/{entry['unit']}")+ name = entry["unit"]+ restarted.append(name)+ token.setdefault("restarted_services", []).append(name)+ except Exception as exc: # health: allow BLE001 -- one failed unit never keeps the others stopped+ failures.append(str(exc))+ kept_units.append(entry)+ token["posix_units"] = kept_units+ kept_bare = []+ for entry in token.get("unmapped") or []:+ if not entry.get("argv"):+ continue+ try:+ new_pid = _relaunch_bare(entry)+ _RESTARTED["pids"].add(new_pid)+ restarted.append(f"gateway PID {entry['pid']} → {new_pid}")+ except Exception as exc: # health: allow BLE001 -- one failed replay never keeps the others stopped+ failures.append(str(exc))+ kept_bare.append(entry)+ token["unmapped"] = kept_bare+ token["unmapped_pids"] = [e["pid"] for e in kept_bare]+ token["profiles"] = {}+ if restarted:+ print(f" ▶ Restarted paused gateway(s): {', '.join(restarted)}")+ if failures:+ raise RuntimeError("Could not restart every paused gateway: " + "; ".join(failures))+ token["resume_needed"] = False+ token["posix_stopped"] = False+++def already_restarted() -> dict:+ """What the early resume restarted on the new code in this process (for the fleet restart)."""+ return _RESTARTEDdiff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 2fa35f07444..4b9b50c1e82 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -1548,7 +1548,7 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:# ``unregister`` is a no-op when this function was never registered.import atexitatexit.unregister(_resume_windows_gateways_after_update)- if not _m()._is_windows():+ if not _m()._is_windows() and token.get("platform") != "posix":token["resume_needed"] = Falsereturn# Startup recovery runs ahead of an unrelated command whose stdout may be parsed (``--json``):@@ -1582,6 +1582,9 @@ def _resume_paused_set(token: dict) -> None:"""Bring every paused runtime back; each one is retired from *token* only on its own verifiedstart, and one failure (an SCM service, a profile) never keeps the others stopped."""from hermes_cli.update_cmd import _m+ if token.get("platform") == "posix": # Linux/macOS pre-swap pause (update_cmd_posix_pause)+ from hermes_cli.update_cmd_posix_pause import resume_paused_set+ return resume_paused_set(token)# 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_completion.py b/hermes_cli/update_completion.pyindex 587522b7fbe..4801c877f29 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -407,7 +407,7 @@ def _complete_selected(request: dict) -> bool:pre_update_version=request["pre_update_version"],completion_message=request.get("completion_message"),announce=None if request.get("completion_message") else "\n✓ Code updated!",- followups=followups)+ followups=followups, before_build=lambda: _resume_paused_before_build(request))except (Exception, SystemExit) as exc: # health: allow BLE001 -- e.g. the shared update lock refused the tailreason = str(exc) or type(exc).__name__# The tail's steps catch their own failures, so a raise here means the build never ran.@@ -449,6 +449,21 @@ def _complete_selected(request: dict) -> bool:return complete+def _resume_paused_before_build(request: dict) -> None:+ """The one restart point of gateways paused for this update, on every OS: the dependencies are+ synced and the launchers published, the product builds (minutes) have not started. A gateway+ needs nothing later to boot; config migration and maintenance run with it up, as they always+ did on POSIX. A failure stays owed: the post-build resume retries it and records the outcome."""+ token = request.get("windows_resume")+ if not token or not token.get("resume_needed"):+ return+ from hermes_cli.update_cmd_windows import _resume_windows_gateways_after_update+ try:+ _resume_windows_gateways_after_update(token)+ except Exception as exc: # health: allow BLE001 -- retried (and recorded) after the build+ print(f" ⚠ Paused gateway restart incomplete ({exc}); retrying after the build")++class _ForwardedOutput:"""The parent's pipe preserves its terminal's prompt policy and log mirror."""diff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.pyindex 3fb2c4d43d4..06a7d300ffb 100644--- a/hermes_cli/update_pause_record.py+++ b/hermes_cli/update_pause_record.py@@ -894,6 +894,10 @@ def merge_into(token: dict | None, adopted: dict) -> dict:token["cold_start_if_installed"] = Trueif "attested_generation" in adopted:token.setdefault("attested_generation", adopted["attested_generation"])+ if adopted.get("platform"): # a POSIX set (update_cmd_posix_pause): its supervised units ride along+ token["platform"] = adopted["platform"]+ units = token.setdefault("posix_units", [])+ units.extend(u for u in adopted.get("posix_units") or [] if u not in units)services = token.setdefault("services", [])services.extend(s for s in adopted.get("services") or [] if s not in services)if services:@@ -905,7 +909,7 @@ def merge_into(token: dict | None, adopted: dict) -> dict:def _has_work(token: dict) -> bool:return bool(token.get("profiles") or any(u.get("argv") for u in token.get("unmapped") or [])- or token.get("services") or token.get("cold_start_if_installed") or token.get("cold_start_profiles"))+ or token.get("services") or token.get("posix_units") or token.get("cold_start_if_installed") or token.get("cold_start_profiles"))def _resume_claimed(claim_path: Path, body: dict) -> None:diff --git a/tests/e2e/core/upgrade/git/test_hostile_pause.py b/tests/e2e/core/upgrade/git/test_hostile_pause.pynew file mode 100644index 00000000000..a5319754957--- /dev/null+++ b/tests/e2e/core/upgrade/git/test_hostile_pause.py@@ -0,0 +1,406 @@+"""Linux/macOS ``hermes update`` pauses this install's gateways before the first checkout move.++One real HEAD install (``_git_world``: the real ``scripts/install.sh`` over real smart HTTP, every+command in a ``bwrap`` sandbox) is shared by the cells. A credential-free, platform-less (cron-only)+``hermes gateway run`` lives in the same PID namespace as the updater (``handoff._nshost``), as on a+user's machine. What is asserted is what the user sees: which gateway process serves the checkout+(its control-socket ``identify``: pid + ``code_sha``), the update's exit code and transcript, HEAD,+and the durable pause record ``update_pause_record`` keeps in the root hermes home.++(a) a real release: the gateway is gone BEFORE HEAD moves (a 0.1 s timeline of both), and exactly+ one gateway, a new process, serves the new commit once the update returns; the restart line is+ printed after the dependency sync and before the product builds.+(b) no-op update (already current): the same gateway process keeps serving; nothing is stopped.+(c) the fetch fails (origin unreachable): nothing is stopped.+(d) ``--no-gateway-restart``: nothing is stopped before the move (the user manages gateways).+(e) SIGKILL mid-stop: the gateway is SIGSTOPped so the updater blocks in its control-socket pause+ request with the planned-stop request on disk; the whole update tree is SIGKILLed there. The+ next ``hermes`` launch must leave exactly one gateway serving: none lost, none duplicated.+(f) SIGKILL after the commit, before the restart: the release's dependency preparation holds while+ a toggle exists; the update tree is SIGKILLed once HEAD is the release and the gateway is+ paused. The next launch syncs the dependencies and restarts exactly the paused gateway on the+ new commit.+"""++from __future__ import annotations++import contextlib+import json+import os+import re+import shutil+import signal+import tempfile+import threading+import time+from pathlib import Path+from typing import Iterator++import pytest++import hermes_yaml as yaml+from tests.e2e.core.upgrade import _helpers as H+from tests.e2e.core.upgrade.git import _git_world as G+from tests.e2e.core.upgrade import _install_helpers as I+from tests.e2e.core.upgrade.handoff._nshost import NamespaceHost++pytestmark = G.PYTESTMARK++PAUSED = "⏸ Paused for the update"+RESTARTED = "▶ Restarted paused gateway(s)"+SLOW_DEPS = ".e2e-slow-deps-sync"+DEPS_STARTED = ".e2e-deps-sync-started"+UPDATE_TIMEOUT = 1500+_DEPS_MARK = "# e2e (test_hostile_pause): slow dependency sync toggle"+_SLOW_DEPS = f""" {_DEPS_MARK}+ _e2e_home = __import__("os").path.expanduser("~")+ if __import__("os").path.exists(__import__("os").path.join(_e2e_home, "{SLOW_DEPS}")):+ open(__import__("os").path.join(_e2e_home, "{DEPS_STARTED}"), "w").write("started")+ while __import__("os").path.exists(__import__("os").path.join(_e2e_home, "{SLOW_DEPS}")):+ __import__("time").sleep(0.2)+"""++[email protected](scope="module")+def w() -> Iterator[G.World]:+ """A SHORT root: the gateway's AF_UNIX control socket lives under ``$HERMES_HOME``."""+ base = os.environ.get("TMPDIR") or tempfile.gettempdir()+ root = Path(tempfile.mkdtemp(prefix="hz", dir=base))+ try:+ with G.world(root, base=I.head_sha()) as world:+ cfg_path = world.sb.hermes_home / "config.yaml"+ cfg = (yaml.safe_load(cfg_path.read_text(encoding="utf-8")) if cfg_path.is_file() else None) or {}+ cfg["updates"] = {**(cfg.get("updates") or {}), "check": False}+ cfg_path.write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")+ yield world+ finally:+ if not os.environ.get("HERMES_E2E_KEEP_ROOT"):+ shutil.rmtree(root, ignore_errors=True)+++# -- helpers ---------------------------------------------------------------------------------------+++def _read(p: Path) -> str:+ return p.read_text(encoding="utf-8-sig", errors="replace") if p.is_file() else ""+++def _ref_head(w: G.World) -> str:+ """HEAD straight from the ref files (no git process, safe at 10 Hz)."""+ git = w.checkout / ".git"+ head = _read(git / "HEAD").strip()+ if not head.startswith("ref: "):+ return head+ ref = head[5:]+ loose = _read(git / ref).strip()+ if loose:+ return loose+ for line in _read(git / "packed-refs").splitlines():+ if line.endswith(" " + ref):+ return line.split()[0]+ return ""+++def _identify(w: G.World) -> dict | None:+ from gateway.control_socket import identify_gateway++ with contextlib.suppress(Exception):+ return identify_gateway(w.sb.hermes_home, timeout=5.0)+ return None+++def _serving(w: G.World, sha: str) -> dict | None:+ ident = _identify(w)+ return ident if ident and ident.get("code_sha") == sha else None+++def _gateways(host: NamespaceHost) -> list[dict]:+ """``gateway run`` processes in the namespace, by the canonical matcher."""+ from gateway.status import looks_like_gateway_command_line++ return [p for p in host.procs() if p["state"] not in ("Z", "X")+ and looks_like_gateway_command_line(" ".join(p["cmdline"]))]+++def _record(w: G.World) -> list[dict]:+ """Every paused-gateway record (live, orphaned, claimed) in the root hermes home."""+ found = []+ for p in sorted(w.sb.hermes_home.glob(".hermes-update-paused-gateways*.json")):+ with contextlib.suppress(OSError, ValueError):+ found.append({"path": p.name, **json.loads(p.read_text(encoding="utf-8"))})+ return found+++def _namespace(w: G.World) -> Iterator[NamespaceHost]:+ host = NamespaceHost(w.sb.root, w.sb.env)+ try:+ yield host+ finally:+ leaked = host.close()+ (w.sb.hermes_home / "gateway.pid").unlink(missing_ok=True) # names a pid of the dead namespace+ assert not leaked, f"processes outlived the sandbox: {leaked}"+++def _ns_cli(host: NamespaceHost, w: G.World, *args: str, timeout: float = 600):+ cp = host.run([w.sb.hermes, *args], timeout=timeout)+ w.transcripts.append(f"$ hermes {' '.join(args)} -> rc={cp.returncode}\n{(cp.stdout or '')[-6000:]}\n"+ f"{(cp.stderr or '')[-3000:]}")+ return cp+++def _start_gateway(host: NamespaceHost, w: G.World, tag: str) -> dict:+ host.spawn([w.sb.hermes, "gateway", "run"], log=w.sb.root / f"gateway-{tag}.log")+ sha = w.head()+ try:+ return H.wait_for(lambda: _serving(w, sha), timeout=240, interval=1.0, what="the gateway's identify")+ except AssertionError as exc:+ raise AssertionError(f"premise: the gateway never came up: {exc}\n{host.ps_text()}\n"+ f"{_read(w.sb.root / f'gateway-{tag}.log')[-4000:]}") from None+++def _kill_born_after(host: NamespaceHost, before: set[int], keep: set[int] | frozenset[int] = frozenset()) -> list[int]:+ killed: list[int] = []+ for _ in range(10):+ live = [p["pid"] for p in host.procs()+ if p["pid"] not in before and p["pid"] not in keep and p["state"] not in ("Z", "X")]+ if not live:+ break+ for pid in live:+ host.kill(pid, signal.SIGSTOP)+ for pid in live:+ host.kill(pid, signal.SIGKILL) # windows-footgun: ok - linux-only (bwrap) module+ if pid not in killed:+ killed.append(pid)+ time.sleep(0.5)+ return killed+++class _Timeline:+ """10 Hz samples of (gateway pid alive, HEAD) while the update runs."""++ def __init__(self, host: NamespaceHost, w: G.World, pid: int):+ self.host, self.w, self.pid = host, w, pid+ self.rows: list[tuple[float, bool, str]] = []+ self._stop = threading.Event()+ self._t = threading.Thread(target=self._run, daemon=True)++ def _run(self) -> None:+ t0 = time.monotonic()+ while not self._stop.is_set():+ with contextlib.suppress(Exception):+ self.rows.append((time.monotonic() - t0, self.host.alive(self.pid), _ref_head(self.w)))+ time.sleep(0.1)++ def __enter__(self):+ self._t.start()+ return self++ def __exit__(self, *exc):+ self._stop.set()+ self._t.join(timeout=10)++ def first(self, pred) -> float | None:+ return next((t for t, alive, head in self.rows if pred(alive, head)), None)++ def text(self) -> str:+ out, last = [], None+ for t, alive, head in self.rows:+ state = (alive, head[:10])+ if state != last:+ out.append(f" t={t:7.2f}s gateway_pid_alive={alive} HEAD={head[:10]}")+ last = state+ return "\n".join(out)+++def _publish_release(w: G.World, tag: str) -> str:+ """A release that changes a module the gateway imports lazily plus a web build input."""+ return w.publish(f"release: e2e hostile pause {tag}", {+ f"docs/e2e-hostile-pause-{tag}.txt": f"release {tag}\n",+ f"web/e2e-hostile-pause-{tag}.txt": f"web input changed by release {tag}\n",+ })+++def _publish_slow_deps_release(w: G.World, tag: str) -> str:+ text = w.git("show", "HEAD:pm/client.py") + "\n"+ if _DEPS_MARK not in text:+ m = re.search(r"^def ensure_tools_for_sync\(\) -> None:\n \"\"\".*?\"\"\"\n", text, re.S | re.M)+ assert m, "premise: pm/client.py has no ensure_tools_for_sync() with a docstring to inject after"+ text = text[:m.end()] + _SLOW_DEPS + text[m.end():]+ return w.publish(f"release: e2e hostile pause slow deps {tag}", {+ "pm/client.py": text, f"docs/e2e-hostile-pause-{tag}.txt": f"release {tag}\n"})+++def _diag(w: G.World, host: NamespaceHost, cp=None, **extra) -> str:+ parts = [f"{k}={v}" for k, v in extra.items()]+ parts.append("pause records: " + json.dumps(_record(w), default=str)[:3000])+ parts.append("--- sandbox ---\n" + host.ps_text())+ return "\n".join(parts) + "\n" + w.diag(cp)+++# -- cells -----------------------------------------------------------------------------------------+++def test_real_release_pauses_before_the_move_and_restarts_after_deps(w):+ w.reset_clean()+ with _namespace(w) as host:+ before = _start_gateway(host, w, "a")+ old_sha, old_pid = w.head(), int(before["pid"])+ target = _publish_release(w, "a")+ with _Timeline(host, w, old_pid) as tl:+ cp = _ns_cli(host, w, "update", "--yes", "--branch", "main", timeout=UPDATE_TIMEOUT)+ out = G.output(cp)+ after = H.wait_for(lambda: _serving(w, target), timeout=60, interval=1.0, what="a gateway on the release") \+ if cp.returncode == 0 else None+ gws = _gateways(host)+ diag = _diag(w, host, cp, timeline="\n" + tl.text(), before=before, after=after, gateways=gws)++ assert cp.returncode == 0 and w.head() == target, f"premise: the update did not land:\n{diag}"+ gone, moved = tl.first(lambda alive, _h: not alive), tl.first(lambda _a, head: head == target)+ assert gone is not None and moved is not None, f"timeline missed the stop or the move:\n{diag}"+ assert tl.first(lambda alive, head: alive and head == target) is None, \+ f"the OLD gateway process was alive while HEAD named the release:\n{diag}"+ assert gone < moved, f"the gateway stopped only after the checkout moved:\n{diag}"+ assert PAUSED in out and RESTARTED in out, f"the pause/restart lines are missing:\n{diag}"+ assert out.index(PAUSED) < out.index(RESTARTED), f"restart printed before the pause:\n{diag}"+ built = [m.start() for m in re.finditer(r"web UI|Building", out)]+ assert not built or out.index(RESTARTED) < built[0], \+ f"the paused gateway was restarted only after the product builds:\n{diag}"+ assert after and int(after["pid"]) != old_pid, f"no NEW gateway process serves {target[:12]}:\n{diag}"+ assert len(gws) == 1, f"expected exactly one gateway process, found {len(gws)}:\n{diag}"+ assert not [r for r in _record(w) if (r.get("token") or {}).get("resume_needed")], \+ f"a discharged pause left an owed record:\n{diag}"+ assert old_sha != target+++def test_noop_update_stops_nothing(w):+ w.reset_clean()+ with _namespace(w) as host:+ before = _start_gateway(host, w, "b")+ cp = _ns_cli(host, w, "update", "--yes", "--branch", "main", timeout=UPDATE_TIMEOUT)+ ident = _identify(w)+ diag = _diag(w, host, cp, before=before, after=ident)+ assert cp.returncode == 0, f"the no-op update failed:\n{diag}"+ assert PAUSED not in G.output(cp), f"an already-current update paused the gateways:\n{diag}"+ assert ident and ident.get("pid") == before.get("pid"), f"the gateway process changed:\n{diag}"+++def test_failed_fetch_stops_nothing(w):+ w.reset_clean()+ url = w.config("remote.origin.url")+ with _namespace(w) as host:+ before = _start_gateway(host, w, "c")+ _publish_release(w, "c")+ w.git("remote", "set-url", "origin", "http://127.0.0.1:9/unreachable.git")+ try:+ cp = _ns_cli(host, w, "update", "--yes", "--branch", "main", timeout=UPDATE_TIMEOUT)+ finally:+ w.git("remote", "set-url", "origin", url)+ ident = _identify(w)+ diag = _diag(w, host, cp, before=before, after=ident)+ assert cp.returncode != 0, f"premise: the update with an unreachable origin succeeded:\n{diag}"+ assert PAUSED not in G.output(cp), f"a fetch failure paused the gateways:\n{diag}"+ assert ident and ident.get("pid") == before.get("pid"), f"the gateway process changed:\n{diag}"+++def test_no_gateway_restart_stops_nothing_before_the_move(w):+ w.reset_clean()+ with _namespace(w) as host:+ before = _start_gateway(host, w, "d")+ target = _publish_release(w, "d")+ with _Timeline(host, w, int(before["pid"])) as tl:+ cp = _ns_cli(host, w, "update", "--yes", "--branch", "main", "--no-gateway-restart",+ timeout=UPDATE_TIMEOUT)+ diag = _diag(w, host, cp, timeline="\n" + tl.text(), before=before, after=_identify(w))+ assert cp.returncode == 0 and w.head() == target, f"premise: the update did not land:\n{diag}"+ assert PAUSED not in G.output(cp), f"--no-gateway-restart paused the gateways:\n{diag}"+ assert tl.first(lambda alive, _h: not alive) is None, f"--no-gateway-restart stopped the gateway:\n{diag}"+++def test_sigkill_mid_stop_next_launch_restores_exactly_the_set(w):+ w.reset_clean()+ with _namespace(w) as host:+ before = _start_gateway(host, w, "e")+ gw_pid, sha = int(before["pid"]), w.head()+ _publish_release(w, "e")+ marker = w.sb.hermes_home / ".gateway-planned-stop.json"+ procs0 = {p["pid"] for p in host.procs()}+ host.kill(gw_pid, signal.SIGSTOP) # the socket pause request queues; the updater waits on it+ killed: list[int] = []+ try:+ upd = host.spawn([w.sb.hermes, "update", "--yes", "--branch", "main"], log=w.sb.root / "update-e.log")++ def _request_on_disk():+ if not host.alive(upd):+ raise AssertionError("premise: the update exited before its stop request:\n"+ + _read(w.sb.root / "update-e.log")[-6000:])+ with contextlib.suppress(OSError, ValueError):+ return json.loads(marker.read_text(encoding="utf-8")).get("target_pid") == gw_pid+ return False++ H.wait_for(_request_on_disk, timeout=900, interval=0.2, what="the updater's stop request on disk")+ time.sleep(1.0) # inside the socket call now (its timeout is seconds, the drain minutes)+ rec_at_kill = _record(w)+ killed = _kill_born_after(host, procs0, keep={gw_pid})+ finally:+ host.kill(gw_pid, signal.SIGCONT)+ head_at_kill = w.head()+ # The queued request may still drain it: let that settle before the next launch judges.+ with contextlib.suppress(AssertionError):+ H.wait_for(lambda: not host.alive(gw_pid), timeout=120, interval=1.0, what="the old gateway to drain")+ status = _ns_cli(host, w, "status", timeout=600)+ served = None+ with contextlib.suppress(AssertionError):+ served = H.wait_for(lambda: _identify(w), timeout=120, interval=1.0, what="a serving gateway")+ time.sleep(3.0)+ gws = _gateways(host)+ diag = _diag(w, host, None, killed=killed, record_at_kill=rec_at_kill, head_at_kill=head_at_kill,+ served=served, gateways=gws, status=G.output(status)[-3000:],+ update_log=_read(w.sb.root / "update-e.log")[-5000:])+ assert killed, f"premise: nothing was killed:\n{diag}"+ assert rec_at_kill and any((r.get("token") or {}).get("unmapped") for r in rec_at_kill), \+ f"premise: no durable record named the gateway before its stop request:\n{diag}"+ assert head_at_kill == sha, f"premise: the checkout moved before the kill:\n{diag}"+ assert served, f"the next launch left NO gateway serving (lost):\n{diag}"+ assert len(gws) == 1, f"expected exactly one gateway after recovery, found {len(gws)}:\n{diag}"+++def test_sigkill_after_commit_before_restart_next_launch_restarts_on_new_code(w):+ w.reset_clean()+ started, toggle = w.sb.home / DEPS_STARTED, w.sb.home / SLOW_DEPS+ with _namespace(w) as host:+ before = _start_gateway(host, w, "f")+ gw_pid = int(before["pid"])+ target = _publish_slow_deps_release(w, "f")+ procs0 = {p["pid"] for p in host.procs()}+ toggle.write_text("on\n", encoding="utf-8")+ killed: list[int] = []+ try:+ upd = host.spawn([w.sb.hermes, "update", "--yes", "--branch", "main"], log=w.sb.root / "update-f.log")++ def _held_after_commit():+ if not host.alive(upd):+ raise AssertionError("premise: the update exited before the slow dependency sync:\n"+ + _read(w.sb.root / "update-f.log")[-6000:])+ return started.is_file() and _ref_head(w) == target++ H.wait_for(_held_after_commit, timeout=1200, interval=0.5, what="the committed update in its deps sync")+ gw_alive_at_kill = host.alive(gw_pid)+ rec_at_kill = _record(w)+ killed = _kill_born_after(host, procs0, keep={gw_pid})+ finally:+ toggle.unlink(missing_ok=True)+ started.unlink(missing_ok=True)+ status = _ns_cli(host, w, "status", timeout=900)+ served = None+ with contextlib.suppress(AssertionError):+ served = H.wait_for(lambda: _serving(w, target), timeout=180, interval=1.0, what="a gateway on the release")+ time.sleep(3.0)+ gws = _gateways(host)+ diag = _diag(w, host, None, killed=killed, gw_alive_at_kill=gw_alive_at_kill, record_at_kill=rec_at_kill,+ served=served, gateways=gws, status=G.output(status)[-3000:],+ update_log=_read(w.sb.root / "update-f.log")[-5000:])+ assert killed and w.head() == target, f"premise: the kill did not land after the commit:\n{diag}"+ assert not gw_alive_at_kill, f"the gateway still ran old code while HEAD named the release:\n{diag}"+ assert served, f"the next launch did not restart the paused gateway on the release:\n{diag}"+ assert int(served["pid"]) != gw_pid and len(gws) == 1, f"lost or duplicated gateway:\n{diag}"