The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): recover hermes-serve units after an aborted restart phase
joaomarcosf9fec169b569
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 2254fb42df6..05f47b0d810 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -6933,11 +6933,19 @@ def _gateway_recovery_partition(Returns ``(candidates, skipped)`` where ``candidates`` maps profile →supervisor for supervised gateway runtimes the fresh process may restart,and ``skipped`` lists every other inventoried runtime the recovery pass- deliberately does NOT touch, each with an explicit reason. Nothing from- the spawn ledger may vanish from the recovery pass silently: manual- gateways have no relaunch authority, and serve/dashboard runtimes (the- ``update_inventory`` serve collector) are owned by the Desktop app or a- human terminal, not by this recovery boundary.+ deliberately does NOT touch *through a profile command*, each with an+ explicit reason. Nothing from the spawn ledger may vanish silently:+ manual gateways have no relaunch authority, and serve/dashboard runtimes+ (the ``update_inventory`` serve collector) have no per-profile relaunch+ command at all.++ A ``skipped`` serve/dashboard entry is NOT a statement that the runtime is+ unrecoverable. The fresh child runs a separate ``hermes-serve*`` systemd+ pass that enumerates units from systemd rather than from this inventory,+ precisely because the ledger collector cannot classify a systemd-launched+ ``hermes serve``: it records no spawner, so it reads as ``manual-serve``.+ Whatever that unit pass does not reconcile is caught afterwards by+ :func:`_surviving_pre_update_serve_runtimes` (#92145)."""skip_profiles = skip_profiles or set()candidates: dict[str, str] = {}@@ -6975,10 +6983,21 @@ def _gateway_recovery_partition(" its supervisor")else:+ # NOT a claim that no supervisor exists. The ledger+ # collector derives serve/dashboard supervisors from+ # spawner liveness alone, and a systemd-launched+ # `hermes serve` sets neither HERMES_SPAWN nor+ # HERMES_PARENT_PID, so it lands here as "manual-serve".+ # Unit-backed serve runtimes are recovered by the+ # fresh child's systemd pass, which enumerates+ # `hermes-serve*` from systemd instead of trusting this+ # classification; survivors are reported afterwards by+ # _surviving_pre_update_serve_runtimes (#92145).reason = (- "manually launched serve/dashboard has no relaunch"- " authority; left running for explicit operator"- " restart"+ "no per-profile relaunch command reaches a serve/"+ "dashboard runtime; recovered by the fresh systemd"+ " unit pass when it owns a hermes-serve* unit, else"+ " left running for explicit operator restart")skipped.append({@@ -7001,8 +7020,66 @@ def _gateway_restart_recovery_profiles(return sorted(candidates)+def _serve_unit_recovery_available() -> bool:+ """Can a fresh process restart ``hermes-serve*`` units on this host?"""+ return sys.platform == "linux" and bool(shutil.which("systemctl"))+++def _surviving_pre_update_serve_runtimes(plan) -> list[dict]:+ """Pre-update serve/dashboard runtimes that are STILL the same process.++ ``ledger_entries()`` re-verifies ``(pid, create_time)`` on every read and+ prunes anything that is gone, so an entry that still matches a pre-update+ PID is the original process — not a PID-reuse look-alike, and not a+ successor (a restarted serve re-registers under a new PID).++ Anything still here after the recovery pass is a live runtime on the+ pre-update code generation, which is precisely the unsafe state #92145+ reports. Fail closed: if the ledger cannot be read, every inventoried+ runtime counts as surviving, because we cannot prove otherwise.+ """+ planned: dict[int, dict] = {}+ try:+ for runtime in getattr(plan, "runtimes", ()) or ():+ if getattr(runtime, "kind", None) not in ("serve", "dashboard"):+ continue+ pid = getattr(runtime, "pid", None)+ if not isinstance(pid, int) or pid <= 0:+ continue+ planned[pid] = {+ "pid": pid,+ "kind": str(getattr(runtime, "kind", "")),+ "profile": str(getattr(runtime, "profile", "")),+ "supervisor": str(getattr(runtime, "supervisor", "")),+ }+ except Exception as exc:+ logger.debug("Could not read planned serve runtimes: %s", exc)+ return []+ if not planned:+ return []+ try:+ from hermes_cli.process_identity import ledger_entries++ live_pids = {+ entry.get("pid")+ for entry in ledger_entries()+ if entry.get("purpose") in ("serve", "dashboard")+ }+ except Exception as exc:+ logger.debug("Serve/dashboard survivor probe failed: %s", exc)+ return sorted(planned.values(), key=lambda row: row["pid"])+ return sorted(+ (row for pid, row in planned.items() if pid in live_pids),+ key=lambda row: row["pid"],+ )++def _recover_gateway_restart_after_abort(- plan, *, gateway_mode: bool, skip_profiles: set[str] | None = None+ plan,+ *,+ gateway_mode: bool,+ skip_profiles: set[str] | None = None,+ skip_units: set[str] | None = None,) -> dict[str, list]:"""Retry supervised gateway restarts from a clean Python process.@@ -7022,6 +7099,12 @@ def _recover_gateway_restart_after_abort(The returned protocol is persisted in the update receipt so operators candistinguish a spawn failure from a per-profile failure.+ The same child additionally restarts active ``hermes-serve*`` systemd+ units (#92145). ``hermes serve`` hosts ``tui_gateway.server`` and is+ restarted by the in-process phase alongside the gateway units, but no+ per-profile ``gateway restart`` command reaches it — so an abort used to+ leave it holding the pre-pull module graph with nothing left to notice.+Outcome honesty: ``verified`` means the fresh child independently observedthe profile's systemd unit active after the relaunch. A zero exit from``gateway restart`` alone is NOT observed proof that the new code@@ -7032,13 +7115,16 @@ def _recover_gateway_restart_after_abort(plan, skip_profiles=skip_profiles)profiles = sorted(candidates)- if not profiles:+ recover_serve = _serve_unit_recovery_available()+ _empty_serve: dict[str, list] = {"verified": [], "failed": []}+ if not profiles and not recover_serve:return {"requested": [],"verified": [],"relaunch_attempted": [],"failed": [],"skipped": skipped,+ "serve_units": dict(_empty_serve),}def _all_failed() -> dict[str, list]:@@ -7048,6 +7134,7 @@ def _recover_gateway_restart_after_abort("relaunch_attempted": [],"failed": profiles,"skipped": skipped,+ "serve_units": dict(_empty_serve),}command = [@@ -7082,14 +7169,26 @@ def _recover_gateway_restart_after_abort(]kwargs = {- "input": json.dumps({"profiles": profiles, "supervisors": candidates}),+ "input": json.dumps(+ {+ "profiles": profiles,+ "supervisors": candidates,+ "serve_units": {+ "recover": recover_serve,+ "skip": sorted(skip_units or set()),+ },+ }+ ),"capture_output": True,"text": True,"encoding": "utf-8","errors": "replace","check": False,"env": env,- "timeout": max(120, 30 + 90 * len(profiles)),+ # Gateway profiles run sequentially at up to 90s each; the serve pass+ # adds its own restart + settle budget on top, so give the child room+ # for both rather than killing a recovery that was working.+ "timeout": max(180, 30 + 90 * len(profiles) + (150 if recover_serve else 0)),}if sys.platform == "win32":kwargs["creationflags"] = (@@ -7114,10 +7213,32 @@ def _recover_gateway_restart_after_abort(verified = recovery_result.get("verified")relaunch_attempted = recovery_result.get("relaunch_attempted")failed = recovery_result.get("failed")+ raw_serve = recovery_result.get("serve_units") or dict(_empty_serve)except (AttributeError, TypeError, ValueError):logger.warning("Fresh gateway restart recovery returned invalid JSON")return _all_failed()+ serve_units = dict(_empty_serve)+ if (+ isinstance(raw_serve, dict)+ and isinstance(raw_serve.get("verified"), list)+ and isinstance(raw_serve.get("failed"), list)+ and all(+ isinstance(unit, str)+ for unit in (*raw_serve["verified"], *raw_serve["failed"])+ )+ ):+ serve_units = {+ "verified": sorted(raw_serve["verified"]),+ "failed": sorted(raw_serve["failed"]),+ }+ elif recover_serve:+ # An unreadable serve block cannot be read as "nothing to do": the+ # units it describes are exactly the ones that host tui_gateway and+ # may still be serving the pre-update generation.+ logger.warning("Fresh recovery returned an invalid serve-unit result")+ serve_units = {"verified": [], "failed": ["<unreadable>"]}+buckets = (verified, relaunch_attempted, failed)reported: list[str] = []if all(isinstance(bucket, list) for bucket in buckets):@@ -7142,15 +7263,56 @@ def _recover_gateway_restart_after_abort(" supervisor-verified (check these gateways manually): "+ ", ".join(sorted(relaunch_attempted)))+ if serve_units["verified"]:+ print(+ " ✓ Restarted serve unit(s) in a fresh process"+ " (new main PID observed): "+ + ", ".join(serve_units["verified"])+ )+ if serve_units["failed"]:+ print(+ " ⚠ Could not verify a replacement for serve unit(s): "+ + ", ".join(serve_units["failed"])+ )return {"requested": profiles,"verified": sorted(verified),"relaunch_attempted": sorted(relaunch_attempted),"failed": sorted(failed),"skipped": skipped,+ "serve_units": serve_units,}+def _warn_stale_serve_runtimes(rows) -> None:+ """Name the serve/dashboard processes that survived on pre-update code.++ The original #92145 report is a user watching every chat turn fail with an+ ``ImportError`` for a symbol that imports fine on disk, with nothing in the+ terminal naming the responsible process. ``hermes serve`` hosts+ ``tui_gateway.server``; when its unit was never restarted it keeps the+ pre-pull ``sys.modules`` graph and there is no gateway row anywhere that+ reveals it. Print the PIDs and the exact command that fixes it.+ """+ if not rows:+ return+ print(+ " ⚠ These serve/dashboard processes still run pre-update code"+ " (they started before the checkout changed):"+ )+ for row in rows:+ supervisor = row.get("supervisor") or "unknown"+ print(+ f" pid {row.get('pid')} — {row.get('kind')}"+ f" (profile {row.get('profile') or 'default'}, {supervisor})"+ )+ print(+ " Restart them before using Hermes again, e.g."+ " `systemctl --user restart hermes-serve.service`"+ " or by relaunching `hermes serve` / the Desktop app."+ )++def _warn_gateway_restart_phase_aborted(exc: BaseException, pids) -> None:"""Print a recovery warning when the whole restart phase raised.@@ -10357,7 +10519,26 @@ def _cmd_update_impl(args, gateway_mode: bool):_pre_update_plan,gateway_mode=gateway_mode,skip_profiles=_already_restarted_profiles,+ skip_units=set(restarted_services),)+ _recovery_serve_units = _recovery_result.get("serve_units") or {}+ _serve_units_failed = list(_recovery_serve_units.get("failed") or [])+ # Deliberately NOT merged into ``restarted_services``: that list is+ # the gateway phase's own vocabulary and feeds the fleet-probe+ # expectation. Serve coverage lives in the recovery result and the+ # receipt, where it can be read without changing gateway semantics.+ # A serve/dashboard runtime that is still the SAME process the+ # pre-update inventory saw is a live runtime on the pre-update+ # code generation — the exact unsafe state of #92145, and the one+ # the reporter hit through tui_gateway (hosted by `hermes serve`,+ # which is not a gateway profile and which no `gateway restart`+ # command can reach). Recovery may not report success while one+ # is still there, and it must never kill one: a manual or+ # Desktop-owned serve has no relaunch authority.+ _stale_runtime_rows = _surviving_pre_update_serve_runtimes(+ _pre_update_plan+ )+ _recovery_result["stale_runtimes"] = _stale_runtime_rows# Only systemd-VERIFIED outcomes may claim supervisor coverage.# A relaunch that merely exited 0 ("relaunch_attempted") was never# observed by the code and must not clear the incomplete flag.@@ -10380,21 +10561,27 @@ def _cmd_update_impl(args, gateway_mode: bool):_covered_gateway_profiles = (_already_restarted_profiles | _recovery_verified)- _recovery_complete = bool(_planned_gateway_profiles) and (- _planned_gateway_profiles <= _covered_gateway_profiles- and not _recovery_result.get("failed")- and not _recovery_result.get("relaunch_attempted")+ _recovery_complete = _abort_recovery_is_complete(+ planned_gateway_profiles=_planned_gateway_profiles,+ covered_gateway_profiles=_covered_gateway_profiles,+ recovery_result=_recovery_result,+ stale_runtime_rows=_stale_runtime_rows,)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+ elif (+ _restart_phase_failure_is_incomplete(+ _surviving, _pre_restart_gateway_pids+ )+ or _stale_runtime_rows+ or _serve_units_failed):gateway_fleet_restart_incomplete = True_warn_gateway_restart_phase_aborted(e, _surviving)+ _warn_stale_serve_runtimes(_stale_runtime_rows)if gateway_mode:_exit_code_path = get_hermes_home() / ".update_exit_code"try:@@ -10741,6 +10928,50 @@ def _restart_phase_failure_is_incomplete(surviving, pre_restart_pids) -> bool:return pre_restart_pids is None or bool(pre_restart_pids)+def _abort_recovery_is_complete(+ *,+ planned_gateway_profiles,+ covered_gateway_profiles,+ recovery_result,+ stale_runtime_rows,+) -> bool:+ """May a fresh-process recovery clear the incomplete flag?++ Only when EVERY inventoried runtime family is accounted for. The gateway+ leg alone is not enough (#92145): the post-update read-back+ (``collect_fleet_versions``) is gateway-only — it reads each profile's+ ``gateway_state.json`` / control socket — so a ``hermes serve`` still+ holding the pre-update ``sys.modules`` graph is invisible to both the+ recovery pass and the verification that follows it. Clearing the flag on+ gateway coverage alone is exactly how an update reported success while+ every chat turn kept failing with an ``ImportError`` for a symbol that+ imports fine on disk.++ Fail closed on each leg:++ * every planned gateway profile is covered, with nothing failed and+ nothing merely ``relaunch_attempted`` (rc 0 is not observed coverage);+ * no ``hermes-serve*`` unit failed to produce a verified replacement; and+ * no serve/dashboard process from the pre-update inventory is still the+ same process (``stale_runtime_rows``).++ ``planned_gateway_profiles`` being empty is deliberately NOT completeness:+ with no gateway leg to prove, the caller's own fail-closed contract+ (``_restart_phase_failure_is_incomplete``) plus the stale-runtime rows+ decide the outcome.+ """+ if not planned_gateway_profiles:+ return False+ if not set(planned_gateway_profiles) <= set(covered_gateway_profiles):+ return False+ result = recovery_result or {}+ if result.get("failed") or result.get("relaunch_attempted"):+ return False+ if (result.get("serve_units") or {}).get("failed"):+ return False+ return not stale_runtime_rows++def _fleet_probe_expected_runtimes(pre_update_plan,pre_restart_pids,diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex f3df91da406..11d8d218404 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -132,6 +132,27 @@ class UpdateReceipt:for entry in fresh_recovery.get("skipped", [])if isinstance(entry, dict)]+ # Serve/dashboard coverage (#92145). ``hermes serve`` hosts+ # tui_gateway and is not a gateway profile, so neither the+ # per-profile buckets above nor the fleet-version matrix can+ # describe it. Persist its unit outcomes and any process that+ # survived on the pre-update generation, or the receipt keeps+ # claiming a clean recovery the operator's box contradicts.+ serve_units = fresh_recovery.get("serve_units") or {}+ persisted["serve_units"] = {+ key: [str(unit) for unit in (serve_units.get(key) or [])]+ for key in ("verified", "failed")+ }+ persisted["stale_runtimes"] = [+ {+ "pid": int(entry.get("pid", 0) or 0),+ "kind": str(entry.get("kind", "")),+ "profile": str(entry.get("profile", "")),+ "supervisor": str(entry.get("supervisor", "")),+ }+ for entry in fresh_recovery.get("stale_runtimes", [])+ if isinstance(entry, dict)+ ]result["fresh_recovery"] = persistedself.data["gateway_restart"] = resultdiff --git a/hermes_cli/update_restart_recovery.py b/hermes_cli/update_restart_recovery.pyindex 6124bfd4411..deed59fd537 100644--- a/hermes_cli/update_restart_recovery.py+++ b/hermes_cli/update_restart_recovery.py@@ -19,6 +19,20 @@ Outcome vocabulary (deliberately conservative):so this outcome must never be treated as verified coverage.- ``failed`` — the relaunch command errored, timed out, or exitednon-zero.++The pass covers two runtime families, because the in-process restart phase+covers both and an abort can strand either one (#92145):++- **gateway profiles**, relaunched through the existing per-profile+ ``hermes_cli.main -p <profile> gateway restart`` command; and+- **``hermes-serve*`` systemd units**, restarted directly through+ ``systemctl``. ``hermes serve`` is not a gateway profile and has no+ per-profile relaunch command, but it is the runtime that hosts+ ``tui_gateway.server``: the process the original report saw answering every+ chat turn with an ``ImportError`` for a symbol that existed on disk. The+ unit family is enumerated from systemd itself rather than from the update+ inventory, so a manually launched or Desktop-owned ``hermes serve`` — which+ has no relaunch authority — can never enter this path."""from __future__ import annotations@@ -30,6 +44,7 @@ import reimport shutilimport subprocessimport sys+import timefrom collections.abc import Callable, Iterable, Mappingfrom typing import Any@@ -39,6 +54,11 @@ _PROFILE_RESTART_TIMEOUT = 90_VERIFY_TIMEOUT = 15_PROFILE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")_SUPERVISOR_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$")+_UNIT_RE = re.compile(r"^hermes-serve(-[a-z0-9][a-z0-9_-]{0,63})?\.service$")+_SERVE_UNIT_PATTERN = "hermes-serve*"+_UNIT_RESTART_TIMEOUT = 60+_UNIT_SETTLE_ATTEMPTS = 10+_UNIT_SETTLE_DELAY = 1.0def _profile_command(profile: str) -> list[str]:@@ -183,7 +203,208 @@ def restart_profiles(}-def _parse_payload(stream) -> tuple[list[str], dict[str, str]]:+def _systemctl_scopes() -> list[list[str]]:+ """``systemctl`` invocations for the user and system scopes, or nothing.++ Mirrors the scope pair the in-process restart phase walks. ``systemctl``+ is resolved through ``shutil.which`` so this module never has to import+ any Hermes platform helper — importing the freshly pulled tree is exactly+ what aborted the phase that called us.+ """+ systemctl = shutil.which("systemctl")+ if not systemctl or sys.platform != "linux":+ return []+ return [[systemctl, "--user"], [systemctl]]+++def _listed_serve_units(scope: list[str], *, run: Callable[..., Any]) -> list[str]:+ """Serve units systemd knows about in one scope, validated by name."""+ try:+ result = run(+ scope+ + [+ "list-units",+ _SERVE_UNIT_PATTERN,+ "--plain",+ "--no-legend",+ "--no-pager",+ ],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ check=False,+ timeout=_VERIFY_TIMEOUT,+ )+ except (OSError, subprocess.TimeoutExpired):+ return []+ units: list[str] = []+ for line in (getattr(result, "stdout", "") or "").splitlines():+ parts = line.split()+ if not parts:+ continue+ # The glob is a systemd pattern, not a name gate: `hermes-serve*` also+ # matches the unrelated `hermes-server.service`. Require the exact+ # base unit or the hyphenated profile family, same shape as the+ # in-process phase's own name gate.+ if _UNIT_RE.fullmatch(parts[0]) and parts[0] not in units:+ units.append(parts[0])+ return units+++def _unit_property(+ scope: list[str], unit: str, prop: str, *, run: Callable[..., Any]+) -> str | None:+ """One ``systemctl show`` property, or ``None`` when it cannot be read."""+ try:+ result = run(+ scope + ["show", unit, f"--property={prop}", "--value"],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ check=False,+ timeout=_VERIFY_TIMEOUT,+ )+ except (OSError, subprocess.TimeoutExpired):+ return None+ if getattr(result, "returncode", 1) != 0:+ return None+ return (getattr(result, "stdout", "") or "").strip()+++def _unit_main_pid(scope: list[str], unit: str, *, run: Callable[..., Any]) -> int:+ """The unit's ``MainPID``; ``0`` when absent or unreadable."""+ raw = _unit_property(scope, unit, "MainPID", run=run)+ try:+ return int(raw or 0)+ except ValueError:+ return 0+++def _unit_is_active(scope: list[str], unit: str, *, run: Callable[..., Any]) -> bool:+ try:+ result = run(+ scope + ["is-active", unit],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ check=False,+ timeout=_VERIFY_TIMEOUT,+ )+ except (OSError, subprocess.TimeoutExpired):+ return False+ return (getattr(result, "stdout", "") or "").strip() == "active"+++def _serve_unit_replaced(+ scope: list[str],+ unit: str,+ previous_pid: int,+ *,+ run: Callable[..., Any],+ sleep: Callable[[float], Any],+) -> bool:+ """Did the unit come back on a NEW main process?++ ``restart`` returning 0 is not evidence: the whole point of #92145 is that+ a live process can keep serving the pre-update generation while every+ status command reports success. A changed ``MainPID`` on an ``active``+ unit is the observation that the old interpreter — and its stale+ ``sys.modules`` — is gone.+ """+ for attempt in range(_UNIT_SETTLE_ATTEMPTS):+ if attempt:+ sleep(_UNIT_SETTLE_DELAY)+ if not _unit_is_active(scope, unit, run=run):+ continue+ current = _unit_main_pid(scope, unit, run=run)+ if current > 0 and current != previous_pid:+ return True+ return False+++def restart_serve_units(+ *,+ skip_units: Iterable[str] = (),+ run: Callable[..., Any] = subprocess.run,+ sleep: Callable[[float], Any] = time.sleep,+) -> dict[str, list[str]]:+ """Restart every active ``hermes-serve*`` systemd unit from this process.++ ``hermes serve`` hosts ``tui_gateway.server`` and is restarted by the+ in-process phase alongside the gateway units, but it is not a gateway+ profile: no ``gateway restart`` command reaches it. When the phase aborts+ part-way — systemd lists ``hermes-gateway.service`` before+ ``hermes-serve.service``, so the gateway is typically already done — the+ serve unit is the one left holding generation-N modules over a+ generation-N+1 checkout.++ Units are enumerated from systemd, never from the update inventory. That+ keeps the relaunch authority requirement structural: a manually launched+ or Desktop-owned ``hermes serve`` owns no unit and therefore cannot be+ touched here.++ Returns ``{"verified": [...], "failed": [...]}`` keyed by base unit name+ (no ``.service`` suffix), matching the vocabulary the restart phase+ already uses for ``restarted_services``.+ """+ skipped = {str(name).removesuffix(".service") for name in skip_units}+ # base unit name -> replaced? A unit name can exist in BOTH the user and+ # the system scope; each is a separate process and each must be proven.+ # Worst outcome wins, so one unprovable scope cannot be masked by the+ # other reporting success.+ outcomes: dict[str, bool] = {}+ seen: set[tuple[str, str]] = set()+ for scope in _systemctl_scopes():+ scope_key = " ".join(scope)+ for unit in _listed_serve_units(scope, run=run):+ base = unit.removesuffix(".service")+ if (scope_key, base) in seen or base in skipped:+ continue+ seen.add((scope_key, base))+ if not _unit_is_active(scope, unit, run=run):+ # Not running: nothing is serving a stale generation from it.+ continue+ previous_pid = _unit_main_pid(scope, unit, run=run)+ if previous_pid <= 0:+ # Active with no readable main process: a replacement cannot+ # be observed, so it cannot be claimed. Restarting blind and+ # reporting success is the failure mode this module exists to+ # remove.+ outcomes[base] = False+ continue+ try:+ result = run(+ scope + ["--no-ask-password", "restart", unit],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ check=False,+ timeout=_UNIT_RESTART_TIMEOUT,+ )+ except (OSError, subprocess.TimeoutExpired):+ outcomes[base] = False+ continue+ if getattr(result, "returncode", 1) != 0:+ # Includes the unprivileged system-scope case. We do not probe+ # for sudo here: an unverifiable unit must read as failed so+ # the update stays explicitly incomplete.+ outcomes[base] = False+ continue+ replaced = _serve_unit_replaced(+ scope, unit, previous_pid, run=run, sleep=sleep+ )+ outcomes[base] = outcomes.get(base, True) and replaced+ return {+ "verified": sorted(base for base, ok in outcomes.items() if ok),+ "failed": sorted(base for base, ok in outcomes.items() if not ok),+ }+++def _parse_payload(stream) -> tuple[list[str], dict[str, str], bool, list[str]]:payload = json.load(stream)profiles = payload.get("profiles") if isinstance(payload, dict) else Noneif not isinstance(profiles, list):@@ -205,7 +426,26 @@ def _parse_payload(stream) -> tuple[list[str], dict[str, str]]:):raise ValueError("recovery supervisors map is invalid")supervisors = dict(raw_supervisors)- return profiles, supervisors+ raw_serve = payload.get("serve_units") if isinstance(payload, dict) else None+ recover_serve = False+ skip_units: list[str] = []+ if raw_serve is not None:+ if not isinstance(raw_serve, dict):+ raise ValueError("recovery serve_units block is invalid")+ recover_serve = bool(raw_serve.get("recover"))+ raw_skip = raw_serve.get("skip") or []+ if not isinstance(raw_skip, list) or any(+ not isinstance(unit, str) for unit in raw_skip+ ):+ raise ValueError("recovery serve_units skip list is invalid")+ # Only the shapes systemd can actually produce for this family; a+ # skip entry is a name filter, never a command argument.+ skip_units = [+ unit+ for unit in raw_skip+ if _UNIT_RE.fullmatch(unit if unit.endswith(".service") else f"{unit}.service")+ ]+ return profiles, supervisors, recover_serve, skip_unitsdef main(argv: list[str] | None = None) -> int:@@ -220,8 +460,13 @@ def main(argv: list[str] | None = None) -> int:parser.error("this command is an internal update-recovery entry point")try:- profiles, supervisors = _parse_payload(sys.stdin)+ profiles, supervisors, recover_serve, skip_units = _parse_payload(sys.stdin)result = restart_profiles(profiles, supervisors=supervisors)+ result["serve_units"] = (+ restart_serve_units(skip_units=skip_units)+ if recover_serve+ else {"verified": [], "failed": []}+ )except (ValueError, json.JSONDecodeError) as exc:print(json.dumps(@@ -230,13 +475,16 @@ def main(argv: list[str] | None = None) -> int:"verified": [],"relaunch_attempted": [],"failed": [],+ "serve_units": {"verified": [], "failed": []},}))return 2print(json.dumps(result, sort_keys=True))- return 0 if not result["failed"] else 1+ if result["failed"] or result["serve_units"]["failed"]:+ return 1+ return 0if __name__ == "__main__":diff --git a/tests/hermes_cli/test_update_receipt.py b/tests/hermes_cli/test_update_receipt.pyindex cb7634fd0b1..01b38914b68 100644--- a/tests/hermes_cli/test_update_receipt.py+++ b/tests/hermes_cli/test_update_receipt.py@@ -93,7 +93,12 @@ class TestReceiptLifecycle:payload = json.loads(path.read_text(encoding="utf-8"))persisted = payload["gateway_restart"]["fresh_recovery"]- assert persisted == recovery+ assert {key: persisted[key] for key in recovery} == recovery+ # Serve coverage is always persisted, even when the pass had nothing+ # to report, so a reader can tell "no serve runtime" from "the field+ # predates #92145".+ assert persisted["serve_units"] == {"verified": [], "failed": []}+ assert persisted["stale_runtimes"] == []# The conservative vocabulary is the persisted contract: no bucket may# rebrand an unverified relaunch as supervisor-backed success.assert "succeeded" not in persisteddiff --git a/tests/hermes_cli/test_update_restart_recovery.py b/tests/hermes_cli/test_update_restart_recovery.pyindex f5054bce643..f7bce47ab14 100644--- a/tests/hermes_cli/test_update_restart_recovery.py+++ b/tests/hermes_cli/test_update_restart_recovery.py@@ -86,10 +86,11 @@ def test_abort_recovery_hands_managed_profiles_to_a_fresh_process(monkeypatch):assert argv[0] == sys.executableassert argv[1:4] == ["-m", "hermes_cli.update_restart_recovery", "--stdin"]payload = json.loads(kwargs["input"])- assert payload == {- "profiles": ["coder", "default"],- "supervisors": {"coder": "launchd", "default": "systemd"},- }+ assert payload["profiles"] == ["coder", "default"]+ assert payload["supervisors"] == {"coder": "launchd", "default": "systemd"}+ # Serve units travel in the same payload so one fresh child covers both+ # runtime families (#92145).+ assert set(payload["serve_units"]) == {"recover", "skip"}assert kwargs["text"] is Trueassert kwargs["capture_output"] is Trueassert kwargs["check"] is False@@ -224,7 +225,7 @@ def test_abort_recovery_records_serve_runtimes_as_skipped_with_reason(monkeypatcassert set(by_kind) == {"serve", "dashboard"}assert "desktop app" in by_kind["serve"]["reason"]assert by_kind["dashboard"]["profile"] == "ops"- assert "relaunch authority" in by_kind["dashboard"]["reason"]+ assert "relaunch" in by_kind["dashboard"]["reason"]def test_service_matching_is_exact_for_overlapping_profile_names():@@ -375,6 +376,7 @@ def test_recovery_module_empty_payload_is_a_real_clean_process():"failed": [],"relaunch_attempted": [],"verified": [],+ "serve_units": {"verified": [], "failed": []},}@@ -455,6 +457,7 @@ def test_recovery_module_end_to_end_in_a_real_fresh_process(tmp_path):"failed": [],"relaunch_attempted": ["coder"],"verified": ["default"],+ "serve_units": {"verified": [], "failed": []},}restarts = [json.loads(line) for line in ledger.read_text().splitlines()]assert [argv[argv.index("-p") + 1] for argv in restarts] == ["coder", "default"]diff --git a/tests/hermes_cli/test_update_serve_generation_recovery.py b/tests/hermes_cli/test_update_serve_generation_recovery.pynew file mode 100644index 00000000000..85c9d281588--- /dev/null+++ b/tests/hermes_cli/test_update_serve_generation_recovery.py@@ -0,0 +1,895 @@+"""Regression coverage for stale ``hermes serve`` generations after an abort.++Issue #92145: ``hermes update`` moves the checkout from generation N to N+1+while the updater still holds the pre-pull module graph. When the in-process+restart phase raises, a fresh process retries the *gateway* profiles — but+``hermes serve`` is not a gateway profile. It hosts ``tui_gateway.server``,+systemd lists ``hermes-gateway.service`` before ``hermes-serve.service`` (so+the serve unit is the one an abort typically never reaches), and the final+read-back (``collect_fleet_versions``) only inspects gateway state. A serve+process left on generation N is therefore invisible to every check, and the+update reports a clean recovery while every chat turn fails with an+``ImportError`` for a symbol that imports fine on disk.++These tests pin the closure predicate: no runtime from the pre-update+inventory may still be the same process once recovery reports success, and+nothing without a verified relaunch authority may be killed to get there.+"""++from __future__ import annotations++import io+import json+import subprocess+import sys+from types import SimpleNamespace++import pytest++from hermes_cli import update_cmd+from hermes_cli import update_restart_recovery as recovery+++class _Completed:+ def __init__(self, returncode: int, stdout: str = "", stderr: str = ""):+ self.returncode = returncode+ self.stdout = stdout+ self.stderr = stderr+++def _runtime(kind: str, profile: str, supervisor: str, pid):+ return SimpleNamespace(kind=kind, profile=profile, supervisor=supervisor, pid=pid)+++def _plan(*runtimes):+ return SimpleNamespace(runtimes=list(runtimes))+++def _identity_module():+ return __import__("hermes_cli.process_identity", fromlist=["ledger_entries"])+++# ---------------------------------------------------------------------------+# The closure predicate itself+# ---------------------------------------------------------------------------+++def _gateway_only_success():+ return {+ "requested": ["default"],+ "verified": ["default"],+ "relaunch_attempted": [],+ "failed": [],+ "skipped": [],+ "serve_units": {"verified": [], "failed": []},+ }+++def test_full_gateway_recovery_does_not_clear_the_flag_while_serve_is_stale():+ """The reported bug as a predicate: gateway green, serve still generation N."""+ assert (+ update_cmd._abort_recovery_is_complete(+ planned_gateway_profiles={"default"},+ covered_gateway_profiles={"default"},+ recovery_result=_gateway_only_success(),+ stale_runtime_rows=[+ {+ "pid": 4242,+ "kind": "serve",+ "profile": "default",+ "supervisor": "manual-serve",+ }+ ],+ )+ is False+ )+++def test_recovery_is_complete_when_no_runtime_survived():+ assert (+ update_cmd._abort_recovery_is_complete(+ planned_gateway_profiles={"default"},+ covered_gateway_profiles={"default"},+ recovery_result=_gateway_only_success(),+ stale_runtime_rows=[],+ )+ is True+ )+++def test_failed_serve_unit_blocks_completion():+ result = _gateway_only_success()+ result["serve_units"] = {"verified": [], "failed": ["hermes-serve"]}+ assert (+ update_cmd._abort_recovery_is_complete(+ planned_gateway_profiles={"default"},+ covered_gateway_profiles={"default"},+ recovery_result=result,+ stale_runtime_rows=[],+ )+ is False+ )++[email protected]("blocking", ["failed", "relaunch_attempted"])+def test_unverified_gateway_outcomes_still_block_completion(blocking):+ result = _gateway_only_success()+ result[blocking] = ["default"]+ assert (+ update_cmd._abort_recovery_is_complete(+ planned_gateway_profiles={"default"},+ covered_gateway_profiles={"default"},+ recovery_result=result,+ stale_runtime_rows=[],+ )+ is False+ )+++def test_uncovered_gateway_profile_blocks_completion():+ assert (+ update_cmd._abort_recovery_is_complete(+ planned_gateway_profiles={"default", "coder"},+ covered_gateway_profiles={"default"},+ recovery_result=_gateway_only_success(),+ stale_runtime_rows=[],+ )+ is False+ )+++def test_no_planned_gateway_leg_is_not_completeness():+ """A serve-only fleet must fall through to the caller's fail-closed path."""+ assert (+ update_cmd._abort_recovery_is_complete(+ planned_gateway_profiles=set(),+ covered_gateway_profiles=set(),+ recovery_result=_gateway_only_success(),+ stale_runtime_rows=[],+ )+ is False+ )+++def test_legacy_recovery_result_without_serve_key_still_evaluates():+ """Forward/backward compatibility: a pre-#92145 shape must not crash."""+ legacy = {+ "requested": ["default"],+ "verified": ["default"],+ "relaunch_attempted": [],+ "failed": [],+ "skipped": [],+ }+ assert (+ update_cmd._abort_recovery_is_complete(+ planned_gateway_profiles={"default"},+ covered_gateway_profiles={"default"},+ recovery_result=legacy,+ stale_runtime_rows=[],+ )+ is True+ )+++# ---------------------------------------------------------------------------+# Survivor probe — identity, not PID guessing+# ---------------------------------------------------------------------------+++def test_serve_process_that_never_restarted_is_reported_as_stale(monkeypatch):+ monkeypatch.setattr(+ _identity_module(),+ "ledger_entries",+ lambda *a, **k: [{"pid": 4242, "purpose": "serve"}],+ )+ rows = update_cmd._surviving_pre_update_serve_runtimes(+ _plan(_runtime("serve", "default", "manual-serve", 4242))+ )+ assert rows == [+ {+ "pid": 4242,+ "kind": "serve",+ "profile": "default",+ "supervisor": "manual-serve",+ }+ ]+++def test_restarted_serve_leaves_no_survivor(monkeypatch):+ """A restarted unit re-registers under a NEW pid; the old row is pruned."""+ monkeypatch.setattr(+ _identity_module(),+ "ledger_entries",+ lambda *a, **k: [{"pid": 9999, "purpose": "serve"}],+ )+ assert (+ update_cmd._surviving_pre_update_serve_runtimes(+ _plan(_runtime("serve", "default", "manual-serve", 4242))+ )+ == []+ )+++def test_gateway_runtimes_are_not_counted_as_serve_survivors(monkeypatch):+ monkeypatch.setattr(+ _identity_module(),+ "ledger_entries",+ lambda *a, **k: [{"pid": 4242, "purpose": "gateway"}],+ )+ assert (+ update_cmd._surviving_pre_update_serve_runtimes(+ _plan(_runtime("gateway", "default", "systemd", 4242))+ )+ == []+ )+++def test_dashboard_survivors_count_too(monkeypatch):+ monkeypatch.setattr(+ _identity_module(),+ "ledger_entries",+ lambda *a, **k: [{"pid": 77, "purpose": "dashboard"}],+ )+ rows = update_cmd._surviving_pre_update_serve_runtimes(+ _plan(_runtime("dashboard", "default", "manual-serve", 77))+ )+ assert [row["kind"] for row in rows] == ["dashboard"]+++def test_unreadable_ledger_fails_closed(monkeypatch):+ """Unprovable state is unsafe state — never a silent all-clear."""++ def boom(*a, **k):+ raise OSError("ledger unreadable")++ monkeypatch.setattr(_identity_module(), "ledger_entries", boom)+ rows = update_cmd._surviving_pre_update_serve_runtimes(+ _plan(_runtime("serve", "default", "manual-serve", 4242))+ )+ assert [row["pid"] for row in rows] == [4242]+++def test_no_inventoried_serve_runtime_is_a_clean_no_op(monkeypatch):+ def boom(*a, **k): # must not even be consulted+ raise AssertionError("ledger probed with nothing to check")++ monkeypatch.setattr(_identity_module(), "ledger_entries", boom)+ assert (+ update_cmd._surviving_pre_update_serve_runtimes(+ _plan(_runtime("gateway", "default", "systemd", 111))+ )+ == []+ )+++def test_runtimes_without_a_usable_pid_are_ignored(monkeypatch):+ def boom(*a, **k):+ raise AssertionError("ledger probed with nothing to check")++ monkeypatch.setattr(_identity_module(), "ledger_entries", boom)+ assert (+ update_cmd._surviving_pre_update_serve_runtimes(+ _plan(+ _runtime("serve", "default", "manual-serve", 0),+ _runtime("serve", "other", "manual-serve", None),+ )+ )+ == []+ )+++# ---------------------------------------------------------------------------+# restart_serve_units — what may claim "verified"+# ---------------------------------------------------------------------------+++class _Systemctl:+ """Scriptable systemctl double: unit table + MainPID progression."""++ def __init__(self, listed, active, main_pids, restart_rc=0):+ self.listed = listed+ self.active = dict(active)+ self.main_pids = dict(main_pids)+ self.restart_rc = restart_rc+ self.restarted: list[str] = []++ def __call__(self, argv, **kwargs):+ if "list-units" in argv:+ if "--user" not in argv:+ return _Completed(0, stdout="")+ body = "\n".join(+ f"{unit} loaded active running Hermes" for unit in self.listed+ )+ return _Completed(0, stdout=body)+ if "is-active" in argv:+ unit = argv[-1]+ return _Completed(+ 0, stdout="active" if self.active.get(unit) else "inactive"+ )+ if "show" in argv:+ unit = argv[argv.index("show") + 1]+ return _Completed(0, stdout=str(self.main_pids.get(unit, 0)))+ if "restart" in argv:+ unit = argv[-1]+ self.restarted.append(unit)+ if self.restart_rc == 0:+ self.main_pids[unit] = self.main_pids.get(unit, 0) + 1000+ return _Completed(self.restart_rc)+ raise AssertionError(f"unexpected systemctl call: {argv}")+++def linux_systemctl(monkeypatch):+ monkeypatch.setattr(recovery.sys, "platform", "linux")+ monkeypatch.setattr(recovery.shutil, "which", lambda name: "/usr/bin/systemctl")+++def test_serve_unit_verified_when_main_pid_changes(linux_systemctl):+ fake = _Systemctl(+ listed=["hermes-serve.service"],+ active={"hermes-serve.service": True},+ main_pids={"hermes-serve.service": 4242},+ )+ out = recovery.restart_serve_units(run=fake, sleep=lambda _: None)+ assert out == {"verified": ["hermes-serve"], "failed": []}+ assert fake.restarted == ["hermes-serve.service"]+++def test_unchanged_main_pid_is_not_verified(linux_systemctl):+ """rc 0 with the same main process means the stale interpreter survived."""+ fake = _Systemctl(+ listed=["hermes-serve.service"],+ active={"hermes-serve.service": True},+ main_pids={"hermes-serve.service": 4242},+ )+ original_call = fake.__call__++ def frozen(argv, **kwargs):+ if "restart" in argv:+ fake.restarted.append(argv[-1])+ return _Completed(0) # rc 0, MainPID deliberately untouched+ return original_call(argv, **kwargs)++ out = recovery.restart_serve_units(run=frozen, sleep=lambda _: None)+ assert out == {"verified": [], "failed": ["hermes-serve"]}+++def test_unit_that_does_not_come_back_active_is_failed(linux_systemctl):+ fake = _Systemctl(+ listed=["hermes-serve.service"],+ active={"hermes-serve.service": True},+ main_pids={"hermes-serve.service": 4242},+ )+ original_call = fake.__call__++ def dies(argv, **kwargs):+ if "restart" in argv:+ fake.restarted.append(argv[-1])+ fake.active["hermes-serve.service"] = False+ return _Completed(0)+ return original_call(argv, **kwargs)++ out = recovery.restart_serve_units(run=dies, sleep=lambda _: None)+ assert out == {"verified": [], "failed": ["hermes-serve"]}+++def test_nonzero_restart_is_failed_not_silently_skipped(linux_systemctl):+ """The unprivileged system-scope case must read as failure, not absence."""+ fake = _Systemctl(+ listed=["hermes-serve.service"],+ active={"hermes-serve.service": True},+ main_pids={"hermes-serve.service": 4242},+ restart_rc=1,+ )+ out = recovery.restart_serve_units(run=fake, sleep=lambda _: None)+ assert out == {"verified": [], "failed": ["hermes-serve"]}+++def test_restart_timeout_is_failed(linux_systemctl):+ fake = _Systemctl(+ listed=["hermes-serve.service"],+ active={"hermes-serve.service": True},+ main_pids={"hermes-serve.service": 4242},+ )+ original_call = fake.__call__++ def timing_out(argv, **kwargs):+ if "restart" in argv:+ raise subprocess.TimeoutExpired(cmd=argv, timeout=60)+ return original_call(argv, **kwargs)++ out = recovery.restart_serve_units(run=timing_out, sleep=lambda _: None)+ assert out == {"verified": [], "failed": ["hermes-serve"]}+++def test_inactive_serve_unit_is_left_alone(linux_systemctl):+ """Nothing inactive can be serving a stale generation."""+ fake = _Systemctl(+ listed=["hermes-serve.service"],+ active={"hermes-serve.service": False},+ main_pids={"hermes-serve.service": 0},+ )+ out = recovery.restart_serve_units(run=fake, sleep=lambda _: None)+ assert out == {"verified": [], "failed": []}+ assert fake.restarted == []+++def test_units_already_restarted_by_the_phase_are_skipped(linux_systemctl):+ fake = _Systemctl(+ listed=["hermes-serve.service", "hermes-serve-work.service"],+ active={"hermes-serve.service": True, "hermes-serve-work.service": True},+ main_pids={"hermes-serve.service": 1, "hermes-serve-work.service": 2},+ )+ out = recovery.restart_serve_units(+ skip_units=["hermes-serve"], run=fake, sleep=lambda _: None+ )+ assert fake.restarted == ["hermes-serve-work.service"]+ assert out == {"verified": ["hermes-serve-work"], "failed": []}+++def test_unrelated_hermes_server_service_is_never_touched(linux_systemctl):+ """``hermes-serve*`` is a systemd glob, not a name gate (review on #83595)."""+ fake = _Systemctl(+ listed=["hermes-server.service", "hermes-serve.service"],+ active={"hermes-server.service": True, "hermes-serve.service": True},+ main_pids={"hermes-server.service": 7, "hermes-serve.service": 8},+ )+ out = recovery.restart_serve_units(run=fake, sleep=lambda _: None)+ assert fake.restarted == ["hermes-serve.service"]+ assert out["verified"] == ["hermes-serve"]+++def test_gateway_units_are_not_restarted_by_the_serve_pass(linux_systemctl):+ """Gateway profiles have their own per-profile relaunch command."""+ fake = _Systemctl(+ listed=["hermes-gateway.service"],+ active={"hermes-gateway.service": True},+ main_pids={"hermes-gateway.service": 5},+ )+ out = recovery.restart_serve_units(run=fake, sleep=lambda _: None)+ assert fake.restarted == []+ assert out == {"verified": [], "failed": []}+++def test_no_systemctl_means_no_serve_pass(monkeypatch):+ monkeypatch.setattr(recovery.shutil, "which", lambda name: None)++ def unreachable(*a, **k):+ raise AssertionError("systemctl invoked without a systemctl binary")++ assert recovery.restart_serve_units(run=unreachable) == {+ "verified": [],+ "failed": [],+ }+++def test_non_linux_hosts_do_not_run_the_serve_pass(monkeypatch):+ monkeypatch.setattr(recovery.sys, "platform", "win32")+ monkeypatch.setattr(recovery.shutil, "which", lambda name: "systemctl")++ def unreachable(*a, **k):+ raise AssertionError("serve unit pass ran off Linux")++ assert recovery.restart_serve_units(run=unreachable) == {+ "verified": [],+ "failed": [],+ }+++def test_active_unit_with_no_readable_main_pid_is_failed(linux_systemctl):+ """No observable main process means no observable replacement."""+ fake = _Systemctl(+ listed=["hermes-serve.service"],+ active={"hermes-serve.service": True},+ main_pids={"hermes-serve.service": 0},+ )+ out = recovery.restart_serve_units(run=fake, sleep=lambda _: None)+ assert out == {"verified": [], "failed": ["hermes-serve"]}+ assert fake.restarted == []+++def test_same_unit_name_in_both_scopes_is_proven_in_both(linux_systemctl):+ """User and system scope are two different processes, not one."""+ calls: list[tuple[str, list]] = []++ def dual_scope(argv, **kwargs):+ scope = "user" if "--user" in argv else "system"+ calls.append((scope, list(argv)))+ if "list-units" in argv:+ return _Completed(0, stdout="hermes-serve.service loaded active running x")+ if "is-active" in argv:+ return _Completed(0, stdout="active")+ if "show" in argv:+ return _Completed(0, stdout="10" if scope == "user" else "20")+ if "restart" in argv:+ # The user scope relaunches cleanly; the system scope is refused+ # (no privilege) and must not be masked by the user-scope success.+ return _Completed(0 if scope == "user" else 1)+ raise AssertionError(argv)++ out = recovery.restart_serve_units(run=dual_scope, sleep=lambda _: None)+ restarts = [scope for scope, argv in calls if "restart" in argv]+ assert restarts == ["user", "system"]+ assert out == {"verified": [], "failed": ["hermes-serve"]}+++def test_restart_is_invoked_without_an_interactive_auth_prompt(linux_systemctl):+ """A polkit prompt inside a captured subprocess hangs the whole update."""+ seen = []+ fake = _Systemctl(+ listed=["hermes-serve.service"],+ active={"hermes-serve.service": True},+ main_pids={"hermes-serve.service": 4242},+ )+ original_call = fake.__call__++ def recording(argv, **kwargs):+ if "restart" in argv:+ seen.append(list(argv))+ return original_call(argv, **kwargs)++ recovery.restart_serve_units(run=recording, sleep=lambda _: None)+ assert seen and "--no-ask-password" in seen[0]+++# ---------------------------------------------------------------------------+# Payload boundary+# ---------------------------------------------------------------------------+++def test_skip_unit_names_are_filtered_to_the_serve_family():+ _, _, recover_serve, skip = recovery._parse_payload(+ io.StringIO(+ json.dumps(+ {+ "profiles": [],+ "serve_units": {+ "recover": True,+ "skip": [+ "hermes-serve",+ "hermes-serve-work.service",+ "hermes-server",+ "../../etc/systemd/evil",+ "hermes-serve; rm -rf /",+ "hermes-gateway",+ ],+ },+ }+ )+ )+ )+ assert recover_serve is True+ assert skip == ["hermes-serve", "hermes-serve-work.service"]+++def test_malformed_serve_block_is_rejected():+ with pytest.raises(ValueError, match="serve_units"):+ recovery._parse_payload(+ io.StringIO(json.dumps({"profiles": [], "serve_units": ["nope"]}))+ )+++def test_non_string_skip_entries_are_rejected():+ with pytest.raises(ValueError, match="skip list"):+ recovery._parse_payload(+ io.StringIO(+ json.dumps(+ {"profiles": [], "serve_units": {"recover": True, "skip": [7]}}+ )+ )+ )+++def test_absent_serve_block_defaults_to_no_serve_recovery():+ _, _, recover_serve, skip = recovery._parse_payload(+ io.StringIO(json.dumps({"profiles": []}))+ )+ assert recover_serve is False+ assert skip == []+++# ---------------------------------------------------------------------------+# Driver: the fresh child is still launched for a serve-only fleet+# ---------------------------------------------------------------------------+++def test_serve_only_fleet_still_spawns_the_recovery_child(monkeypatch):+ """Before #92145 the driver returned early whenever no gateway profile was+ supervised, so a stale serve unit was never even attempted."""+ monkeypatch.setattr(update_cmd, "_serve_unit_recovery_available", lambda: True)+ calls = []++ def fake_run(argv, **kwargs):+ calls.append((argv, kwargs))+ return _Completed(+ 0,+ stdout=json.dumps(+ {+ "verified": [],+ "relaunch_attempted": [],+ "failed": [],+ "serve_units": {"verified": ["hermes-serve"], "failed": []},+ }+ ),+ )++ monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)+ result = update_cmd._recover_gateway_restart_after_abort(+ _plan(_runtime("serve", "default", "manual-serve", 4242)),+ gateway_mode=False,+ )+ assert len(calls) == 1+ payload = json.loads(calls[0][1]["input"])+ assert payload["profiles"] == []+ assert payload["serve_units"]["recover"] is True+ assert result["serve_units"] == {"verified": ["hermes-serve"], "failed": []}+++def test_child_timeout_budget_covers_the_serve_pass(monkeypatch):+ """A serve-only recovery must not be killed before its settle window."""+ monkeypatch.setattr(update_cmd, "_serve_unit_recovery_available", lambda: True)+ captured = {}++ def fake_run(argv, **kwargs):+ captured["timeout"] = kwargs["timeout"]+ return _Completed(+ 0,+ stdout=json.dumps(+ {+ "verified": [],+ "relaunch_attempted": [],+ "failed": [],+ "serve_units": {"verified": [], "failed": []},+ }+ ),+ )++ monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)+ update_cmd._recover_gateway_restart_after_abort(+ _plan(_runtime("serve", "default", "manual-serve", 4242)),+ gateway_mode=False,+ )+ assert captured["timeout"] >= 180+++def test_verified_serve_units_do_not_enter_gateway_restart_vocabulary(monkeypatch):+ """Serve coverage must not silently widen the gateway fleet-probe gate."""+ monkeypatch.setattr(update_cmd, "_serve_unit_recovery_available", lambda: True)++ def fake_run(argv, **kwargs):+ return _Completed(+ 0,+ stdout=json.dumps(+ {+ "verified": ["default"],+ "relaunch_attempted": [],+ "failed": [],+ "serve_units": {"verified": ["hermes-serve"], "failed": []},+ }+ ),+ )++ monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)+ result = update_cmd._recover_gateway_restart_after_abort(+ _plan(_runtime("gateway", "default", "systemd", 111)),+ gateway_mode=False,+ )+ assert result["verified"] == ["default"]+ assert "hermes-serve" not in result["verified"]+++def test_no_serve_authority_and_no_gateway_profile_spawns_nothing(monkeypatch):+ monkeypatch.setattr(update_cmd, "_serve_unit_recovery_available", lambda: False)++ def unreachable(*a, **k):+ raise AssertionError("recovery child spawned with nothing to recover")++ monkeypatch.setattr(update_cmd.subprocess, "run", unreachable)+ result = update_cmd._recover_gateway_restart_after_abort(+ _plan(_runtime("serve", "default", "manual-serve", 4242)),+ gateway_mode=False,+ )+ assert result["requested"] == []+ assert result["serve_units"] == {"verified": [], "failed": []}+++def test_already_restarted_units_are_forwarded_as_skips(monkeypatch):+ monkeypatch.setattr(update_cmd, "_serve_unit_recovery_available", lambda: True)+ captured = {}++ def fake_run(argv, **kwargs):+ captured["payload"] = json.loads(kwargs["input"])+ return _Completed(+ 0,+ stdout=json.dumps(+ {+ "verified": ["default"],+ "relaunch_attempted": [],+ "failed": [],+ "serve_units": {"verified": [], "failed": []},+ }+ ),+ )++ monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)+ update_cmd._recover_gateway_restart_after_abort(+ _plan(_runtime("gateway", "default", "systemd", 111)),+ gateway_mode=False,+ skip_units={"hermes-serve"},+ )+ assert captured["payload"]["serve_units"]["skip"] == ["hermes-serve"]+++def test_unreadable_serve_block_from_the_child_reads_as_failure(monkeypatch):+ """A child that answers with a broken serve block has proven nothing."""+ monkeypatch.setattr(update_cmd, "_serve_unit_recovery_available", lambda: True)++ def fake_run(argv, **kwargs):+ return _Completed(+ 0,+ stdout=json.dumps(+ {+ "verified": ["default"],+ "relaunch_attempted": [],+ "failed": [],+ "serve_units": {"verified": "not-a-list", "failed": []},+ }+ ),+ )++ monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)+ result = update_cmd._recover_gateway_restart_after_abort(+ _plan(_runtime("gateway", "default", "systemd", 111)),+ gateway_mode=False,+ )+ assert result["serve_units"]["failed"] == ["<unreadable>"]+ assert (+ update_cmd._abort_recovery_is_complete(+ planned_gateway_profiles={"default"},+ covered_gateway_profiles={"default"},+ recovery_result=result,+ stale_runtime_rows=[],+ )+ is False+ )+++def test_missing_serve_block_off_linux_is_not_a_failure(monkeypatch):+ """Hosts with no serve authority must not manufacture a phantom failure."""+ monkeypatch.setattr(update_cmd, "_serve_unit_recovery_available", lambda: False)++ def fake_run(argv, **kwargs):+ return _Completed(+ 0,+ stdout=json.dumps(+ {+ "verified": ["default"],+ "relaunch_attempted": [],+ "failed": [],+ }+ ),+ )++ monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)+ result = update_cmd._recover_gateway_restart_after_abort(+ _plan(_runtime("gateway", "default", "systemd", 111)),+ gateway_mode=False,+ )+ assert result["serve_units"] == {"verified": [], "failed": []}+++def test_spawn_failure_reports_empty_serve_coverage(monkeypatch):+ monkeypatch.setattr(update_cmd, "_serve_unit_recovery_available", lambda: True)++ def boom(*a, **k):+ raise OSError("no fork available")++ monkeypatch.setattr(update_cmd.subprocess, "run", boom)+ result = update_cmd._recover_gateway_restart_after_abort(+ _plan(_runtime("gateway", "default", "systemd", 111)),+ gateway_mode=False,+ )+ assert result["failed"] == ["default"]+ assert result["serve_units"] == {"verified": [], "failed": []}+++# ---------------------------------------------------------------------------+# Receipt persistence+# ---------------------------------------------------------------------------+++def test_serve_coverage_reaches_the_persisted_receipt(tmp_path, monkeypatch):+ from hermes_cli import update_receipt++ monkeypatch.setattr(update_receipt, "_receipt_dir", lambda: tmp_path)+ update_receipt.begin_update_receipt()+ update_receipt.record_gateway_restart(+ restarted_services=[],+ incomplete=True,+ phase_error="cannot import name 'line_input' from 'hermes_cli.cli_output'",+ fresh_recovery={+ "requested": ["default"],+ "verified": ["default"],+ "relaunch_attempted": [],+ "failed": [],+ "skipped": [],+ "serve_units": {+ "verified": ["hermes-serve"],+ "failed": ["hermes-serve-work"],+ },+ "stale_runtimes": [+ {+ "pid": 4242,+ "kind": "serve",+ "profile": "default",+ "supervisor": "manual-serve",+ }+ ],+ },+ )+ path = update_receipt.finalize_update_receipt("partial")+ assert path is not None+ persisted = json.loads(path.read_text(encoding="utf-8"))["gateway_restart"][+ "fresh_recovery"+ ]+ assert persisted["serve_units"] == {+ "verified": ["hermes-serve"],+ "failed": ["hermes-serve-work"],+ }+ assert persisted["stale_runtimes"] == [+ {+ "pid": 4242,+ "kind": "serve",+ "profile": "default",+ "supervisor": "manual-serve",+ }+ ]+++# ---------------------------------------------------------------------------+# Operator-facing output+# ---------------------------------------------------------------------------+++def test_stale_serve_warning_names_the_process_and_the_fix(capsys):+ update_cmd._warn_stale_serve_runtimes(+ [+ {+ "pid": 4242,+ "kind": "serve",+ "profile": "default",+ "supervisor": "manual-serve",+ }+ ]+ )+ out = capsys.readouterr().out+ assert "4242" in out+ assert "serve" in out+ assert "systemctl --user restart hermes-serve.service" in out+++def test_no_survivors_prints_nothing(capsys):+ update_cmd._warn_stale_serve_runtimes([])+ assert capsys.readouterr().out == ""+++# ---------------------------------------------------------------------------+# Real fresh interpreter+# ---------------------------------------------------------------------------+++def test_recovery_module_reports_serve_units_in_a_real_process():+ """The protocol survives a genuine subprocess round-trip."""+ result = subprocess.run(+ [sys.executable, "-m", "hermes_cli.update_restart_recovery", "--stdin"],+ input=json.dumps(+ {"profiles": [], "serve_units": {"recover": True, "skip": []}}+ ),+ capture_output=True,+ text=True,+ check=False,+ timeout=120,+ )+ assert result.returncode == 0, result.stderr+ payload = json.loads(result.stdout)+ assert set(payload["serve_units"]) == {"verified", "failed"}