Skip to content

The agent that grows with you

refactor(update): move post-restart fleet verification into update_cmd_fleet_verify

Tekniumf82c0910190b
diff --git a/hermes_cli/AGENTS.md b/hermes_cli/AGENTS.md
index 4fea926e603..23bc568dd04 100644
--- a/hermes_cli/AGENTS.md
+++ b/hermes_cli/AGENTS.md
@@ -184,7 +184,7 @@ target; table-driven `_PREFLIGHT_CHECKS`; manifest `<default>/gateway_migration.
a re-run resumes from it; a named profile's `gateway install|start|run` refuse without `--force` via
`gateway.py::_named_profile_refused_under_multiplexer`, dashboard twin
`web_server_gateway.py::multiplexed_profile_refusal`);
-`update_cmd_fleet._verify_fleet_after_update` calls `maybe_auto_migrate_after_update` on the success
+`update_cmd_fleet_verify._verify_fleet_after_update` calls `maybe_auto_migrate_after_update` on the success
path only; `gateway_migrate_guards.py` holds the auto-path-only refusals (table `_AUTO_MIGRATION_GUARDS`:
other service domain / UNIX user / HERMES_HOME outside `profiles/` — notices for the explicit command,
blockers for the hook) and the `gateway.auto_multiplex_migration` opt-out (#109954). Blockers reuse `GatewayRunner._adapter_credential_fingerprint` and `platform_binds_port`;
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 2d82730d867..38eef9c3092 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -61,11 +61,12 @@ from hermes_cli.update_cmd_fleet import ( # noqa: F401
_restart_systemd_gateway_units,
_run_pending_fleet_restart, _service_restart_sec,
_service_unit_supports_graceful_sigusr1_restart, _surviving_gateway_pids_after_failed_restart,
- _systemctl, _systemctl_reset_and_restart, _verify_fleet_after_update,
+ _systemctl, _systemctl_reset_and_restart,
_wait_for_service_active, _warn_gateway_restart_phase_aborted,
_warn_incomplete_gateway_fleet_restart, _warn_pending_fleet_restart,
_warn_pending_fleet_restart_on_startup, _write_fleet_restart_pending_marker,
_write_gateway_update_exit_code)
+from hermes_cli.update_cmd_fleet_verify import _verify_fleet_after_update # noqa: F401
from hermes_cli.update_cmd_zip import ( # noqa: F401
_ZIP_PRESERVED_TOP_LEVEL, _ZIP_STAGING_ARTIFACT_SUFFIXES, _abort_zip_update_if_dirty_tree,
_atomic_replace_dir, _commit_staged_replacements, _discard_staged,
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index 1ebb1f3089b..aca620b1b52 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -30,11 +30,6 @@ _FLEET_RESTART_PENDING_NAME = "fleet_restart_pending"
_FRESH_RESTART_SUPERVISORS = frozenset({"systemd", "launchd", "service", "s6"})
-# A supervisor can report a restarted unit active before the gateway finishes its
-# bootstrap and publishes ``gateway_state.json``. Keep the readiness poll bounded,
-# but allow the default systemd startup budget plus status-publication slack.
-_FLEET_PROBE_SETTLE_TIMEOUT_SECONDS = 120.0
-
_SYSTEMD_SCOPES = (("user", ["systemctl", "--user"]), ("system", ["systemctl"]))
_LIST_GATEWAY_UNITS = [
"list-units", "hermes-gateway*", "hermes-serve*", "hermes-dashboard*",
@@ -1812,330 +1807,6 @@ def _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode: bool):
return out
-def _print_legacy_units_warning() -> None:
- """Legacy hermes.service fights hermes-gateway.service over the bot token; warn on
- every update until migrated."""
- from hermes_cli.gateway import (has_legacy_hermes_units, _find_legacy_hermes_units, supports_systemd_services)
- if not (supports_systemd_services() and has_legacy_hermes_units()):
- return
- print()
- print("⚠ Legacy Hermes gateway unit(s) detected:")
- for name, path, is_sys in _find_legacy_hermes_units():
- scope = "system" if is_sys else "user"
- print(f" {path} ({scope} scope)")
- print()
- print(" These pre-rename units (hermes.service) fight the current")
- print(" hermes-gateway.service for the bot token and cause SIGTERM")
- print(" flap loops. Remove them with:")
- print()
- print(" hermes gateway migrate-legacy")
- print()
- print(" (add `sudo` if any are in system scope)")
-
-
-def _collect_fleet_snapshot(restart, rows_expected: bool) -> list:
- """Fleet version rows, polled over a bounded settle window when runtimes are expected.
-
- Gateways need time to rewrite gateway_state.json; Windows resumes DETACHED (~10s boot),
- so a single 2s sleep reported "no rows" on healthy resumes. A "down" row may be a
- detached replacement still booting: poll until none remain or the deadline passes.
- Pre-restart PIDs make a gateway stopped WITHOUT verified replacement a DOWN row (owed restart)
- instead of no row at all. An ``unknown`` row whose pid is NOT a pre-restart pid is a successor
- that has not published its code identity yet (a relaunched gateway can sit ~10s between process
- start and its first runtime-status write, #112634) — keep polling; at the deadline it is flagged
- ``identity_pending`` so the matrix does not call it a pre-stamping gateway.
- """
- from hermes_cli.update_receipt import collect_fleet_versions
- pending = getattr(restart, "self_restart_pending_pids", None) or None
- if not rows_expected:
- return collect_fleet_versions(
- pre_restart_pids=restart.pre_restart_gateway_pids, self_restart_pending=pending)
- pre_pids = restart.pre_restart_gateway_pids
- _fleet_deadline = _time.monotonic() + _FLEET_PROBE_SETTLE_TIMEOUT_SECONDS
- while True:
- _time.sleep(2.0)
- snapshot = collect_fleet_versions(pre_restart_pids=pre_pids, self_restart_pending=pending)
- unstamped = [row for row in snapshot if _fleet_row_identity_pending(row, pre_pids)]
- if snapshot and not unstamped and not any(row.get("state") == "down" for row in snapshot):
- return snapshot
- if _time.monotonic() >= _fleet_deadline or _restarted_units_gone(
- getattr(restart, "restarted_scoped_units", ())):
- for row in unstamped:
- row["identity_pending"] = True
- return snapshot
-
-
-def _fleet_row_identity_pending(row: dict, pre_restart_pids) -> bool:
- """An ``unknown`` row with no sha from a pid that did not exist at update start: a relaunched
- gateway still booting, not a gateway that predates version stamping. A surviving pre-restart pid
- (or no pid snapshot at all) is settled as-is — waiting cannot change what it publishes."""
- if row.get("state") != "unknown" or row.get("code_sha"):
- return False
- if pre_restart_pids is None:
- return False
- return row.get("pid") not in {int(p) for p in pre_restart_pids if isinstance(p, int)}
-
-
-def _restarted_units_gone(scoped_units) -> bool:
- """True when every restarted systemd unit is LOADED in its scope and neither active nor
- activating: the successor died, nothing will publish a state stamp, so the settle poll should fail
- closed now instead of at the deadline. Anything inconclusive keeps waiting: no units, systemctl
- missing/slow, or ``LoadState=not-found`` — a unit name asked in a scope that does not own it
- answers ``inactive`` exactly like a dead unit (#112466), so only a loaded unit can prove death."""
- if not scoped_units:
- return False
- scope_cmds = dict(_SYSTEMD_SCOPES)
- for scoped in scoped_units:
- scope, _, name = scoped.partition("/")
- try:
- stdout = _systemctl(scope_cmds[scope] + ["show", "-p", "LoadState,ActiveState", name], timeout=5).stdout
- except (KeyError, FileNotFoundError, subprocess.TimeoutExpired):
- return False
- props = dict(line.split("=", 1) for line in stdout.splitlines() if "=" in line)
- if props.get("LoadState") != "loaded":
- return False
- if props.get("ActiveState") in ("active", "activating", "reloading"):
- return False
- return True
-
-
-def _live_gateway_pids_from_fleet(fleet_rows: list) -> dict:
- """Profile -> gateway PIDs alive after the restart phase, from the fleet snapshot.
-
- Incarnation evidence for gateway reconciliation (``match_runtime_outcomes``'s
- ``live_gateway_pids``): the plan identifies a gateway by the profile it SERVES while the restart
- bookkeeping names the SERVICE, and a service can serve a profile its name does not encode — the
- profile-scoped name matcher then never credits the planned runtime. A ``down`` row reports the
- PRE-restart PID (nothing replaced it), so it is never a successor; rows without a usable
- profile/PID are skipped.
- """
- live: dict = {}
- for row in fleet_rows:
- pid, profile = row.get("pid"), row.get("profile")
- if profile and isinstance(pid, int) and row.get("state") != "down":
- live.setdefault(str(profile), set()).add(pid)
- return live
-
-
-def _record_owed_gateway_inventory(plan) -> None:
- """Name the pre-update gateways on an inventory-less obligation once their restart is owed.
-
- The pull arms the obligation before the restart phase knows what it owes. An inventory-less
- record on a host whose gateway then died at boot is settled by the gateway-less discharge
- (nothing live, nothing named), which would silence the owed-restart warning that replaces a
- failed update under contract C3. A named inventory keeps it until those gateways run HEAD.
- """
- if plan is None:
- return
- armed = _fleet_restart_obligation_armed()
- fields = _obligation_fields() if armed else {}
- if fields is None or fields.get("inventory") not in (None, "", "null"):
- return # unreadable terms stay fail-closed; a recorded inventory is never rewritten
- from dataclasses import asdict
- rows = [
- asdict(runtime) for runtime in getattr(plan, "runtimes", ()) or ()
- if getattr(runtime, "kind", None) == "gateway"
- and isinstance(getattr(runtime, "profile", None), str)
- and runtime.profile.strip() and runtime.profile != "unknown"
- ]
- if rows:
- # Not armed any more (a pre-restart probe settled an inventory-less record): re-arm, the
- # restart is owed. The SHA is the code the fleet must be proven current on.
- sha = fields.get("expected_sha", "") if armed else (_current_checkout_sha() or "")
- _write_fleet_restart_pending_marker(expected_sha=sha, runtimes=rows)
-
-
-def _named_gateways_still_owed() -> bool:
- """True when the armed obligation NAMES gateways (recorded by an earlier owed restart) and the
- live fleet still does not prove them current. An inventory-less record keeps its old rules."""
- if not _fleet_restart_obligation_armed():
- return False
- fields = _obligation_fields()
- if fields is None or fields.get("inventory") in (None, "", "null"):
- return False
- return not _marker_only_restart_obsolete()
-
-
-def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_resume, update_complete):
- """Post-restart verification: legacy-unit warning, dashboard cleanup, stale serve
- probe, fleet version matrix, plan-vs-execution reconciliation, receipt finalize.
-
- Never fails the committed update (contract C3): when any gateway may still be stale it
- records a ``gateway_restart`` follow-up and leaves ``fleet_restart_pending`` armed for the
- next catch-up and the startup warning; otherwise clears the marker.
- """
- from hermes_cli.update_cmd import (
- _m, _surviving_pre_update_serve_runtimes, _warn_stale_serve_runtimes,
- )
- from hermes_cli.update_cmd_maint import _refresh_dashboard_after_update
- with _best_effort('Legacy unit check during update failed: %s'):
- _print_legacy_units_warning()
-
- # Restart a managed dashboard via systemd or stop stale manual ones (raw-killing
- # a systemd-owned PID reads as clean stop and leaves the Cloudflare origin dead).
- # Already-restarted units aren't redone.
- # A dashboard it stopped and could not bring back is a promised restart that did not happen.
- _dashboards_down = _refresh_dashboard_after_update(already_restarted_units=set(restart.restarted_services))
- if _dashboards_down:
- restart.incomplete = True
-
- # Success-path twin of the abort-recovery probe: the restart phase only touches
- # units, so a unit-less `hermes serve` keeps stale sys.modules. Runs AFTER
- # dashboard cleanup so a respawned manual dashboard isn't a survivor. Rows feed
- # reconciliation (survivor → owed restart); ``None`` = probe failed, stays fail-closed.
- # Check if any pre-update serve/dashboard runtimes survived on pre-update code generations (#100479).
- # This is the SUCCESS-path twin of the abort-recovery probe above: the restart phase only restarts
- # units, so an sshd-spawned `serve --isolated` or a manual `hermes serve` (no unit) is left running its
- # pre-update sys.modules graph — and its cron ticker keeps firing agent jobs that ImportError on every
- # symbol added in the pulled range. The rows also feed the plan-vs-execution reconciliation below, so a
- # survivor is escalated (an owed gateway_restart follow-up) instead of merely printed.
- _stale_serve_rows: "list | None" = None
- with _best_effort('Failed to check for surviving serve runtimes: %s'):
- _stale_serve_rows = _surviving_pre_update_serve_runtimes(_pre_update_plan)
- if _stale_serve_rows:
- _warn_stale_serve_runtimes(_stale_serve_rows)
-
- print()
- print("Tip: You can now select a provider and model:")
- print(" hermes model # Select provider and model")
-
- # Compare every live gateway's stamped code_sha against the fresh checkout
- # instead of assuming the restart phase worked.
- # Phase 1 (#91277): post-update fleet version verification.
- _fleet_snapshot: list = []
- with _best_effort('Fleet version verification failed: %s'):
- from hermes_cli.update_receipt import print_fleet_version_matrix
- # Cross-platform "rows expected" signal: (restarted_services or killed_pids)
- # never fires on Windows (pause/resume populates neither), so a healthy
- # resumed gateway yielded zero rows and exit 0.
- # See #93406.
- # A gateway stopped WITHOUT a successor ("Restart manually") publishes no row by design,
- # so it must not count as an expected one — otherwise an update whose only live gateways
- # were unmapped reports "no rows" after correctly stopping them.
- _pre_restart, _killed = restart.fleet_probe_signals()
- _fleet_rows_expected = _m()._fleet_probe_expected_runtimes(
- _pre_update_plan, _pre_restart, _windows_gateway_resume, restart.restarted_services, _killed,
- )
- _fleet_snapshot = _collect_fleet_snapshot(restart, _fleet_rows_expected)
- if print_fleet_version_matrix(_fleet_snapshot):
- restart.incomplete = True
- # A proven-stale survivor must not keep running (its ticker yields every tick and
- # nothing else restarts it, #117275): hand it to the drain-first restart path.
- from hermes_cli.update_cmd_stale_survivors import signal_stale_fleet_survivors
- signal_stale_fleet_survivors(_fleet_snapshot, restart, _gateway_drain_budget())
- elif not _fleet_snapshot and _fleet_rows_expected:
- # collect_fleet_versions() swallows every failure, so zero rows with
- # expected runtimes is indistinguishable from health — keep the restart owed.
- print(
- # Fleet probe returned zero rows even though at least one gateway runtime was (or may have
- # been) live pre-update — POSIX restart bookkeeping, the pre-restart PID snapshot, the
- # pre-update plan inventory, or the Windows pause/resume token all count as that signal.
- # Every failure path inside collect_fleet_versions() is swallowed via logger.debug(), so an
- # empty list is indistinguishable from a healthy fleet in the current output. Treat it as
- # verification failure so the receipt carries a gateway_restart follow-up (#93406).
- "\n⚠ Fleet version check returned no rows even though"
- " gateway runtimes were expected — verification incomplete."
- )
- restart.incomplete = True
-
- # Every runtime the PLAN saw must appear in restart bookkeeping; an
- # unaccounted one is a silent miss and escalates like a STALE/DOWN row.
- with _best_effort('Runtime-outcome reconciliation failed: %s'):
- # An unaccounted runtime is the silent-miss class (a platform branch re-discovered its own targets
- # and skipped one the inventory knew about) — escalate it exactly like a STALE/DOWN fleet row. See
- # #91277.
- if _pre_update_plan is not None and _pre_update_plan.runtimes:
- from hermes_cli.update_inventory import (match_runtime_outcomes, report_unaccounted_runtimes)
- from hermes_cli.update_receipt import row_is_external
- # Gateway incarnation evidence, from the post-restart fleet snapshot collected above: a
- # service can serve a profile its own name does not encode (root-home launchd label +
- # sticky active profile, hashed custom HERMES_HOME), so the bookkeeping's service names
- # alone cannot credit the planned runtime. A profile the probe produced no row for simply
- # has no evidence — that runtime stays on the name-matching path (and logs it).
- _live_gateway_pids = _live_gateway_pids_from_fleet(_fleet_snapshot)
- _runtime_outcomes = match_runtime_outcomes(
- _pre_update_plan,
- restarted_services=restart.restarted_services,
- relaunched_profiles=restart.relaunched_profiles,
- externally_supervised_profiles=restart.externally_supervised_profiles,
- killed_pids=restart.killed_pids,
- failed_units=restart.failed_or_stale_units,
- # Serve/dashboard reconcile by incarnation liveness, not unit names.
- # See #100479.
- stale_serve_pids=(
- {row.get("pid") for row in _stale_serve_rows}
- if _stale_serve_rows is not None
- else None
- ),
- failed_respawn_pids=_dashboards_down,
- # A symlinked profile served by another install's checkout (#120240).
- external_gateway_pids={row.get("pid") for row in _fleet_snapshot if row_is_external(row)},
- live_gateway_pids=_live_gateway_pids,
- )
- from dataclasses import asdict
- from hermes_cli.update_serve_obligations import defer_manual_serve
-
- for runtime, outcome in zip(_pre_update_plan.runtimes, _runtime_outcomes):
- if outcome["outcome"] == "unaccounted" and defer_manual_serve(asdict(runtime), require_alive=True):
- outcome["outcome"] = "deferred"
- if report_unaccounted_runtimes(_runtime_outcomes):
- restart.incomplete = True
- with suppress(Exception):
- import hermes_cli.update_receipt as _ur
- _active = _ur._current.get()
- if _active is not None:
- _active.data["runtime_outcomes"] = _runtime_outcomes
-
- if not restart.incomplete:
- with _best_effort('Owed-gateway check failed: %s'):
- if _named_gateways_still_owed():
- # A gateway a previous run could not restart is still not serving HEAD (nothing
- # live to restart this time): keep owing it rather than clearing the obligation.
- print(" ⚠ A gateway owed a restart by a previous update is still not serving this checkout.")
- restart.incomplete = True
- if getattr(restart, "stopped_unmapped_pids", None):
- # A gateway stopped with no successor is owed a restart, not "accounted for": keep the
- # fleet obligation armed so the startup warning names it until someone restarts it.
- restart.incomplete = True
- if restart.incomplete:
- # Code is committed (contract C3): a gateway that may still run stale modules is a
- # follow-up, never a failed update. The fleet obligation stays armed, every CLI start
- # warns about it, and the next `hermes update` retries the restart.
- from hermes_cli.update_receipt import record_followup
- stopped = sorted(getattr(restart, "stopped_unmapped_pids", None) or ())
- record_followup(
- "gateway_restart",
- "gateways may still run pre-update code or were stopped without a successor"
- + (f" (stopped PIDs {', '.join(map(str, stopped))})" if stopped else "")
- + "; recover with `hermes gateway restart`",
- )
- with _best_effort('Fleet restart inventory not recorded: %s'):
- _record_owed_gateway_inventory(_pre_update_plan)
- with _best_effort('Update receipt finalize failed: %s'):
- from hermes_cli.update_receipt import finalize_update_receipt
- # ``update_complete`` is kept for the historical takeover caller; a False verdict (the
- # SQLite runtime) is reported as a follow-up by the maintenance step, not a failed run.
- _receipt_path = finalize_update_receipt("success", fleet=_fleet_snapshot)
- if _receipt_path is not None:
- logger.info("Update receipt written: %s", _receipt_path)
-
- if restart.incomplete:
- return
- _clear_fleet_restart_pending_marker()
- if not update_complete:
- # Fleet caught up, but the selected runtime's SQLite is unsafe (reported by maintenance):
- # leave the topology alone until the runtime is repaired.
- return
- # Fleet is healthy on the new code: fold per-profile gateways into one multiplexer when nothing
- # blocks it (deterministic; never prompts), else print the blockers and the one-liner to run later.
- try:
- from hermes_cli.gateway_migrate import maybe_auto_migrate_after_update
- maybe_auto_migrate_after_update()
- except (Exception, SystemExit) as exc: # noqa: BLE001 — a SystemExit here must not fail a committed update
- logger.warning('Multiplex auto-migration after update failed: %s', exc)
- print(f" ⚠ Gateway multiplex migration did not finish: {exc} (run `hermes gateway migrate` later)")
-
-
def _restart_phase_failure_is_incomplete(surviving, pre_restart_pids) -> bool:
"""Whether an escaped restart-phase exception must fail the update.
diff --git a/hermes_cli/update_cmd_fleet_verify.py b/hermes_cli/update_cmd_fleet_verify.py
new file mode 100644
index 00000000000..c7be2947416
--- /dev/null
+++ b/hermes_cli/update_cmd_fleet_verify.py
@@ -0,0 +1,350 @@
+"""Post-restart fleet verification for ``hermes update`` (``update_cmd_fleet`` sibling).
+
+After the restart phase: compare every live gateway's stamped code against the checkout, reconcile
+the pre-update plan against what the restart did, keep the restart owed (a ``gateway_restart``
+follow-up, never a failed update — contract C3) or clear the obligation, and finalize the receipt.
+Restart-phase helpers stay in ``update_cmd_fleet`` and are read through it so their patches apply.
+"""
+
+import logging
+import subprocess
+import time as _time
+from contextlib import suppress
+
+from hermes_cli.update_cmd_common import _best_effort
+
+# Log-record parity with the origin module.
+logger = logging.getLogger("hermes_cli.update_cmd")
+
+# A supervisor can report a restarted unit active before the gateway finishes its
+# bootstrap and publishes ``gateway_state.json``. Keep the readiness poll bounded,
+# but allow the default systemd startup budget plus status-publication slack.
+_FLEET_PROBE_SETTLE_TIMEOUT_SECONDS = 120.0
+
+
+def _print_legacy_units_warning() -> None:
+ """Legacy hermes.service fights hermes-gateway.service over the bot token; warn on
+ every update until migrated."""
+ from hermes_cli.gateway import (has_legacy_hermes_units, _find_legacy_hermes_units, supports_systemd_services)
+ if not (supports_systemd_services() and has_legacy_hermes_units()):
+ return
+ print()
+ print("⚠ Legacy Hermes gateway unit(s) detected:")
+ for name, path, is_sys in _find_legacy_hermes_units():
+ scope = "system" if is_sys else "user"
+ print(f" {path} ({scope} scope)")
+ print()
+ print(" These pre-rename units (hermes.service) fight the current")
+ print(" hermes-gateway.service for the bot token and cause SIGTERM")
+ print(" flap loops. Remove them with:")
+ print()
+ print(" hermes gateway migrate-legacy")
+ print()
+ print(" (add `sudo` if any are in system scope)")
+
+
+def _collect_fleet_snapshot(restart, rows_expected: bool) -> list:
+ """Fleet version rows, polled over a bounded settle window when runtimes are expected.
+
+ Gateways need time to rewrite gateway_state.json; Windows resumes DETACHED (~10s boot),
+ so a single 2s sleep reported "no rows" on healthy resumes. A "down" row may be a
+ detached replacement still booting: poll until none remain or the deadline passes.
+ Pre-restart PIDs make a gateway stopped WITHOUT verified replacement a DOWN row (owed restart)
+ instead of no row at all. An ``unknown`` row whose pid is NOT a pre-restart pid is a successor
+ that has not published its code identity yet (a relaunched gateway can sit ~10s between process
+ start and its first runtime-status write, #112634) — keep polling; at the deadline it is flagged
+ ``identity_pending`` so the matrix does not call it a pre-stamping gateway.
+ """
+ from hermes_cli.update_receipt import collect_fleet_versions
+ pending = getattr(restart, "self_restart_pending_pids", None) or None
+ if not rows_expected:
+ return collect_fleet_versions(
+ pre_restart_pids=restart.pre_restart_gateway_pids, self_restart_pending=pending)
+ pre_pids = restart.pre_restart_gateway_pids
+ _fleet_deadline = _time.monotonic() + _FLEET_PROBE_SETTLE_TIMEOUT_SECONDS
+ while True:
+ _time.sleep(2.0)
+ snapshot = collect_fleet_versions(pre_restart_pids=pre_pids, self_restart_pending=pending)
+ unstamped = [row for row in snapshot if _fleet_row_identity_pending(row, pre_pids)]
+ if snapshot and not unstamped and not any(row.get("state") == "down" for row in snapshot):
+ return snapshot
+ if _time.monotonic() >= _fleet_deadline or _restarted_units_gone(
+ getattr(restart, "restarted_scoped_units", ())):
+ for row in unstamped:
+ row["identity_pending"] = True
+ return snapshot
+
+
+def _fleet_row_identity_pending(row: dict, pre_restart_pids) -> bool:
+ """An ``unknown`` row with no sha from a pid that did not exist at update start: a relaunched
+ gateway still booting, not a gateway that predates version stamping. A surviving pre-restart pid
+ (or no pid snapshot at all) is settled as-is — waiting cannot change what it publishes."""
+ if row.get("state") != "unknown" or row.get("code_sha"):
+ return False
+ if pre_restart_pids is None:
+ return False
+ return row.get("pid") not in {int(p) for p in pre_restart_pids if isinstance(p, int)}
+
+
+def _restarted_units_gone(scoped_units) -> bool:
+ """True when every restarted systemd unit is LOADED in its scope and neither active nor
+ activating: the successor died, nothing will publish a state stamp, so the settle poll should fail
+ closed now instead of at the deadline. Anything inconclusive keeps waiting: no units, systemctl
+ missing/slow, or ``LoadState=not-found`` — a unit name asked in a scope that does not own it
+ answers ``inactive`` exactly like a dead unit (#112466), so only a loaded unit can prove death."""
+ from hermes_cli import update_cmd_fleet as fleet
+ if not scoped_units:
+ return False
+ scope_cmds = dict(fleet._SYSTEMD_SCOPES)
+ for scoped in scoped_units:
+ scope, _, name = scoped.partition("/")
+ try:
+ stdout = fleet._systemctl(scope_cmds[scope] + ["show", "-p", "LoadState,ActiveState", name], timeout=5).stdout
+ except (KeyError, FileNotFoundError, subprocess.TimeoutExpired):
+ return False
+ props = dict(line.split("=", 1) for line in stdout.splitlines() if "=" in line)
+ if props.get("LoadState") != "loaded":
+ return False
+ if props.get("ActiveState") in ("active", "activating", "reloading"):
+ return False
+ return True
+
+
+def _live_gateway_pids_from_fleet(fleet_rows: list) -> dict:
+ """Profile -> gateway PIDs alive after the restart phase, from the fleet snapshot.
+
+ Incarnation evidence for gateway reconciliation (``match_runtime_outcomes``'s
+ ``live_gateway_pids``): the plan identifies a gateway by the profile it SERVES while the restart
+ bookkeeping names the SERVICE, and a service can serve a profile its name does not encode — the
+ profile-scoped name matcher then never credits the planned runtime. A ``down`` row reports the
+ PRE-restart PID (nothing replaced it), so it is never a successor; rows without a usable
+ profile/PID are skipped.
+ """
+ live: dict = {}
+ for row in fleet_rows:
+ pid, profile = row.get("pid"), row.get("profile")
+ if profile and isinstance(pid, int) and row.get("state") != "down":
+ live.setdefault(str(profile), set()).add(pid)
+ return live
+
+
+def _record_owed_gateway_inventory(plan) -> None:
+ """Name the pre-update gateways on an inventory-less obligation once their restart is owed.
+
+ The pull arms the obligation before the restart phase knows what it owes. An inventory-less
+ record on a host whose gateway then died at boot is settled by the gateway-less discharge
+ (nothing live, nothing named), which would silence the owed-restart warning that replaces a
+ failed update under contract C3. A named inventory keeps it until those gateways run HEAD.
+ """
+ from hermes_cli import update_cmd_fleet as fleet
+ if plan is None:
+ return
+ armed = fleet._fleet_restart_obligation_armed()
+ fields = fleet._obligation_fields() if armed else {}
+ if fields is None or fields.get("inventory") not in (None, "", "null"):
+ return # unreadable terms stay fail-closed; a recorded inventory is never rewritten
+ from dataclasses import asdict
+ rows = [
+ asdict(runtime) for runtime in getattr(plan, "runtimes", ()) or ()
+ if getattr(runtime, "kind", None) == "gateway"
+ and isinstance(getattr(runtime, "profile", None), str)
+ and runtime.profile.strip() and runtime.profile != "unknown"
+ ]
+ if rows:
+ # Not armed any more (a pre-restart probe settled an inventory-less record): re-arm, the
+ # restart is owed. The SHA is the code the fleet must be proven current on.
+ sha = fields.get("expected_sha", "") if armed else (fleet._current_checkout_sha() or "")
+ fleet._write_fleet_restart_pending_marker(expected_sha=sha, runtimes=rows)
+
+
+def _named_gateways_still_owed() -> bool:
+ """True when the armed obligation NAMES gateways (recorded by an earlier owed restart) and the
+ live fleet still does not prove them current. An inventory-less record keeps its old rules."""
+ from hermes_cli import update_cmd_fleet as fleet
+ if not fleet._fleet_restart_obligation_armed():
+ return False
+ fields = fleet._obligation_fields()
+ if fields is None or fields.get("inventory") in (None, "", "null"):
+ return False
+ return not fleet._marker_only_restart_obsolete()
+
+
+def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_resume, update_complete):
+ """Post-restart verification: legacy-unit warning, dashboard cleanup, stale serve
+ probe, fleet version matrix, plan-vs-execution reconciliation, receipt finalize.
+
+ Never fails the committed update (contract C3): when any gateway may still be stale it
+ records a ``gateway_restart`` follow-up and leaves ``fleet_restart_pending`` armed for the
+ next catch-up and the startup warning; otherwise clears the marker.
+ """
+ from hermes_cli import update_cmd_fleet as fleet
+ from hermes_cli.update_cmd import (
+ _m, _surviving_pre_update_serve_runtimes, _warn_stale_serve_runtimes,
+ )
+ from hermes_cli.update_cmd_maint import _refresh_dashboard_after_update
+ with _best_effort('Legacy unit check during update failed: %s'):
+ _print_legacy_units_warning()
+
+ # Restart a managed dashboard via systemd or stop stale manual ones (raw-killing
+ # a systemd-owned PID reads as clean stop and leaves the Cloudflare origin dead).
+ # Already-restarted units aren't redone.
+ # A dashboard it stopped and could not bring back is a promised restart that did not happen.
+ _dashboards_down = _refresh_dashboard_after_update(already_restarted_units=set(restart.restarted_services))
+ if _dashboards_down:
+ restart.incomplete = True
+
+ # Success-path twin of the abort-recovery probe: the restart phase only touches
+ # units, so a unit-less `hermes serve` keeps stale sys.modules. Runs AFTER
+ # dashboard cleanup so a respawned manual dashboard isn't a survivor. Rows feed
+ # reconciliation (survivor → owed restart); ``None`` = probe failed, stays fail-closed.
+ # Check if any pre-update serve/dashboard runtimes survived on pre-update code generations (#100479).
+ # This is the SUCCESS-path twin of the abort-recovery probe above: the restart phase only restarts
+ # units, so an sshd-spawned `serve --isolated` or a manual `hermes serve` (no unit) is left running its
+ # pre-update sys.modules graph — and its cron ticker keeps firing agent jobs that ImportError on every
+ # symbol added in the pulled range. The rows also feed the plan-vs-execution reconciliation below, so a
+ # survivor is escalated (an owed gateway_restart follow-up) instead of merely printed.
+ _stale_serve_rows: "list | None" = None
+ with _best_effort('Failed to check for surviving serve runtimes: %s'):
+ _stale_serve_rows = _surviving_pre_update_serve_runtimes(_pre_update_plan)
+ if _stale_serve_rows:
+ _warn_stale_serve_runtimes(_stale_serve_rows)
+
+ print()
+ print("Tip: You can now select a provider and model:")
+ print(" hermes model # Select provider and model")
+
+ # Compare every live gateway's stamped code_sha against the fresh checkout
+ # instead of assuming the restart phase worked.
+ # Phase 1 (#91277): post-update fleet version verification.
+ _fleet_snapshot: list = []
+ with _best_effort('Fleet version verification failed: %s'):
+ from hermes_cli.update_receipt import print_fleet_version_matrix
+ # Cross-platform "rows expected" signal: (restarted_services or killed_pids)
+ # never fires on Windows (pause/resume populates neither), so a healthy
+ # resumed gateway yielded zero rows and exit 0.
+ # See #93406.
+ # A gateway stopped WITHOUT a successor ("Restart manually") publishes no row by design,
+ # so it must not count as an expected one — otherwise an update whose only live gateways
+ # were unmapped reports "no rows" after correctly stopping them.
+ _pre_restart, _killed = restart.fleet_probe_signals()
+ _fleet_rows_expected = _m()._fleet_probe_expected_runtimes(
+ _pre_update_plan, _pre_restart, _windows_gateway_resume, restart.restarted_services, _killed,
+ )
+ _fleet_snapshot = _collect_fleet_snapshot(restart, _fleet_rows_expected)
+ if print_fleet_version_matrix(_fleet_snapshot):
+ restart.incomplete = True
+ # A proven-stale survivor must not keep running (its ticker yields every tick and
+ # nothing else restarts it, #117275): hand it to the drain-first restart path.
+ from hermes_cli.update_cmd_stale_survivors import signal_stale_fleet_survivors
+ signal_stale_fleet_survivors(_fleet_snapshot, restart, fleet._gateway_drain_budget())
+ elif not _fleet_snapshot and _fleet_rows_expected:
+ # collect_fleet_versions() swallows every failure, so zero rows with
+ # expected runtimes is indistinguishable from health — keep the restart owed.
+ print(
+ # Fleet probe returned zero rows even though at least one gateway runtime was (or may have
+ # been) live pre-update — POSIX restart bookkeeping, the pre-restart PID snapshot, the
+ # pre-update plan inventory, or the Windows pause/resume token all count as that signal.
+ # Every failure path inside collect_fleet_versions() is swallowed via logger.debug(), so an
+ # empty list is indistinguishable from a healthy fleet in the current output. Treat it as
+ # verification failure so the receipt carries a gateway_restart follow-up (#93406).
+ "\n⚠ Fleet version check returned no rows even though"
+ " gateway runtimes were expected — verification incomplete."
+ )
+ restart.incomplete = True
+
+ # Every runtime the PLAN saw must appear in restart bookkeeping; an
+ # unaccounted one is a silent miss and escalates like a STALE/DOWN row.
+ with _best_effort('Runtime-outcome reconciliation failed: %s'):
+ # An unaccounted runtime is the silent-miss class (a platform branch re-discovered its own targets
+ # and skipped one the inventory knew about) — escalate it exactly like a STALE/DOWN fleet row. See
+ # #91277.
+ if _pre_update_plan is not None and _pre_update_plan.runtimes:
+ from hermes_cli.update_inventory import (match_runtime_outcomes, report_unaccounted_runtimes)
+ from hermes_cli.update_receipt import row_is_external
+ # Gateway incarnation evidence, from the post-restart fleet snapshot collected above: a
+ # service can serve a profile its own name does not encode (root-home launchd label +
+ # sticky active profile, hashed custom HERMES_HOME), so the bookkeeping's service names
+ # alone cannot credit the planned runtime. A profile the probe produced no row for simply
+ # has no evidence — that runtime stays on the name-matching path (and logs it).
+ _live_gateway_pids = _live_gateway_pids_from_fleet(_fleet_snapshot)
+ _runtime_outcomes = match_runtime_outcomes(
+ _pre_update_plan,
+ restarted_services=restart.restarted_services,
+ relaunched_profiles=restart.relaunched_profiles,
+ externally_supervised_profiles=restart.externally_supervised_profiles,
+ killed_pids=restart.killed_pids,
+ failed_units=restart.failed_or_stale_units,
+ # Serve/dashboard reconcile by incarnation liveness, not unit names.
+ # See #100479.
+ stale_serve_pids=(
+ {row.get("pid") for row in _stale_serve_rows}
+ if _stale_serve_rows is not None
+ else None
+ ),
+ failed_respawn_pids=_dashboards_down,
+ # A symlinked profile served by another install's checkout (#120240).
+ external_gateway_pids={row.get("pid") for row in _fleet_snapshot if row_is_external(row)},
+ live_gateway_pids=_live_gateway_pids,
+ )
+ from dataclasses import asdict
+ from hermes_cli.update_serve_obligations import defer_manual_serve
+
+ for runtime, outcome in zip(_pre_update_plan.runtimes, _runtime_outcomes):
+ if outcome["outcome"] == "unaccounted" and defer_manual_serve(asdict(runtime), require_alive=True):
+ outcome["outcome"] = "deferred"
+ if report_unaccounted_runtimes(_runtime_outcomes):
+ restart.incomplete = True
+ with suppress(Exception):
+ import hermes_cli.update_receipt as _ur
+ _active = _ur._current.get()
+ if _active is not None:
+ _active.data["runtime_outcomes"] = _runtime_outcomes
+
+ if not restart.incomplete:
+ with _best_effort('Owed-gateway check failed: %s'):
+ if _named_gateways_still_owed():
+ # A gateway a previous run could not restart is still not serving HEAD (nothing
+ # live to restart this time): keep owing it rather than clearing the obligation.
+ print(" ⚠ A gateway owed a restart by a previous update is still not serving this checkout.")
+ restart.incomplete = True
+ if getattr(restart, "stopped_unmapped_pids", None):
+ # A gateway stopped with no successor is owed a restart, not "accounted for": keep the
+ # fleet obligation armed so the startup warning names it until someone restarts it.
+ restart.incomplete = True
+ if restart.incomplete:
+ # Code is committed (contract C3): a gateway that may still run stale modules is a
+ # follow-up, never a failed update. The fleet obligation stays armed, every CLI start
+ # warns about it, and the next `hermes update` retries the restart.
+ from hermes_cli.update_receipt import record_followup
+ stopped = sorted(getattr(restart, "stopped_unmapped_pids", None) or ())
+ record_followup(
+ "gateway_restart",
+ "gateways may still run pre-update code or were stopped without a successor"
+ + (f" (stopped PIDs {', '.join(map(str, stopped))})" if stopped else "")
+ + "; recover with `hermes gateway restart`",
+ )
+ with _best_effort('Fleet restart inventory not recorded: %s'):
+ _record_owed_gateway_inventory(_pre_update_plan)
+ with _best_effort('Update receipt finalize failed: %s'):
+ from hermes_cli.update_receipt import finalize_update_receipt
+ # ``update_complete`` is kept for the historical takeover caller; a False verdict (the
+ # SQLite runtime) is reported as a follow-up by the maintenance step, not a failed run.
+ _receipt_path = finalize_update_receipt("success", fleet=_fleet_snapshot)
+ if _receipt_path is not None:
+ logger.info("Update receipt written: %s", _receipt_path)
+
+ if restart.incomplete:
+ return
+ fleet._clear_fleet_restart_pending_marker()
+ if not update_complete:
+ # Fleet caught up, but the selected runtime's SQLite is unsafe (reported by maintenance):
+ # leave the topology alone until the runtime is repaired.
+ return
+ # Fleet is healthy on the new code: fold per-profile gateways into one multiplexer when nothing
+ # blocks it (deterministic; never prompts), else print the blockers and the one-liner to run later.
+ try:
+ from hermes_cli.gateway_migrate import maybe_auto_migrate_after_update
+ maybe_auto_migrate_after_update()
+ except (Exception, SystemExit) as exc: # noqa: BLE001 — a SystemExit here must not fail a committed update
+ logger.warning('Multiplex auto-migration after update failed: %s', exc)
+ print(f" ⚠ Gateway multiplex migration did not finish: {exc} (run `hermes gateway migrate` later)")
diff --git a/tests/hermes_cli/test_fleet_matrix_self_restart_pending.py b/tests/hermes_cli/test_fleet_matrix_self_restart_pending.py
index a8b9f92800d..4664dde8b8d 100644
--- a/tests/hermes_cli/test_fleet_matrix_self_restart_pending.py
+++ b/tests/hermes_cli/test_fleet_matrix_self_restart_pending.py
@@ -13,6 +13,7 @@ import os
import pytest
import hermes_cli.update_cmd_fleet as fleet_mod
+import hermes_cli.update_cmd_fleet_verify as fleet_verify
import hermes_cli.update_receipt as ur
OLD = "a" * 40
@@ -77,7 +78,7 @@ def test_restart_phase_records_accepted_self_restart_and_verify_exits_clean(monk
assert pending == {ancestor}
_fleet_homes(monkeypatch, tmp_path, {"default": {"pid": ancestor, "gateway_state": "running", "code_sha": OLD}})
- monkeypatch.setattr(fleet_mod, "_print_legacy_units_warning", lambda: None)
+ monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)
monkeypatch.setattr("hermes_cli.update_cmd_maint._refresh_dashboard_after_update", lambda *a, **k: None)
monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])
monkeypatch.setattr(fleet_mod._time, "sleep", lambda s: None)
@@ -90,7 +91,7 @@ def test_restart_phase_records_accepted_self_restart_and_verify_exits_clean(monk
self_restart_pending_pids=pending,
)
with contextlib.redirect_stdout(io.StringIO()) as out:
- fleet_mod._verify_fleet_after_update(
+ fleet_verify._verify_fleet_after_update(
restart, _pre_update_plan=None, _windows_gateway_resume=None, update_complete=True,
) # a SystemExit(1) here is the #119597 symptom
assert "restart pending" in out.getvalue()
@@ -98,7 +99,7 @@ def test_restart_phase_records_accepted_self_restart_and_verify_exits_clean(monk
assert cleared == [True]
with contextlib.redirect_stdout(io.StringIO()) as out:
restart.self_restart_pending_pids = set() # same fleet, identity not threaded → STALE
- fleet_mod._verify_fleet_after_update(
+ fleet_verify._verify_fleet_after_update(
restart, _pre_update_plan=None, _windows_gateway_resume=None, update_complete=True,
)
# Contract C3: STALE is an owed restart (was SystemExit(1)): flagged, follow-up, marker kept.
diff --git a/tests/hermes_cli/test_manual_serve_deferral.py b/tests/hermes_cli/test_manual_serve_deferral.py
index 5d01d360d72..4de557fd33e 100644
--- a/tests/hermes_cli/test_manual_serve_deferral.py
+++ b/tests/hermes_cli/test_manual_serve_deferral.py
@@ -7,6 +7,7 @@ import pytest
from hermes_cli import process_identity
from hermes_cli import update_cmd_fleet as fleet
+from hermes_cli import update_cmd_fleet_verify as fleet_verify
from hermes_cli import update_receipt
from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan
from hermes_cli.update_serve_obligations import defer_manual_serve, retain_receipt_manual_serves
@@ -20,7 +21,7 @@ def test_manual_deferral_survives_receipt_rotation(monkeypatch, capsys, kind, co
plan = UpdatePlan(runtimes=[runtime])
monkeypatch.setattr(process_identity, "_pid_alive_matches", lambda *a: True)
monkeypatch.setattr(process_identity, "ledger_entries", lambda: [{"pid": 900, "purpose": kind, "create_time": 1000.0}])
- monkeypatch.setattr(fleet, "_print_legacy_units_warning", lambda: None)
+ monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)
monkeypatch.setattr("hermes_cli.update_cmd._finish_dashboard_update_cleanup", lambda *a, **k: None)
monkeypatch.setattr("hermes_cli.gateway_migrate.maybe_auto_migrate_after_update", lambda: None)
monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda **k: [])
@@ -39,7 +40,7 @@ def test_manual_deferral_survives_receipt_rotation(monkeypatch, capsys, kind, co
if condition != "alive":
# Contract C3: a restart that is still owed no longer fails the committed update (was
# SystemExit(1) + "partial") ...
- fleet._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True)
+ fleet_verify._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True)
# ... the obligation stays armed (unchanged) ...
assert fleet._fleet_restart_obligation_armed()
receipt = update_receipt.read_latest_receipt()
@@ -47,7 +48,7 @@ def test_manual_deferral_survives_receipt_rotation(monkeypatch, capsys, kind, co
assert receipt["outcome"] == "success"
assert [f["step"] for f in receipt["followups"]] == ["gateway_restart"]
return
- fleet._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True)
+ fleet_verify._verify_fleet_after_update(restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True)
receipt = update_receipt.read_latest_receipt()
assert receipt["runtime_outcomes"][0]["outcome"] == "deferred"
assert not fleet._fleet_restart_obligation_armed()
diff --git a/tests/hermes_cli/test_update_external_profile_reconciliation.py b/tests/hermes_cli/test_update_external_profile_reconciliation.py
index 2c79bc921bd..32439847d8e 100644
--- a/tests/hermes_cli/test_update_external_profile_reconciliation.py
+++ b/tests/hermes_cli/test_update_external_profile_reconciliation.py
@@ -14,6 +14,7 @@ from types import SimpleNamespace
import pytest
from hermes_cli import update_cmd_fleet as fleet
+from hermes_cli import update_cmd_fleet_verify as fleet_verify
from hermes_cli import update_receipt
from hermes_cli.update_inventory import (
RuntimeRecord,
@@ -61,8 +62,8 @@ def external_profile_host(tmp_path, monkeypatch):
monkeypatch.setattr(update_receipt, "_socket_identity", lambda _home: None)
live = {root.resolve(): 1111, other_home.resolve(): 4242}
monkeypatch.setattr("gateway.status.live_gateway_pid_for_home", lambda home: live.get(Path(home).resolve()))
- monkeypatch.setattr(fleet, "_time", SimpleNamespace(sleep=lambda _s: None, monotonic=time.monotonic))
- monkeypatch.setattr(fleet, "_print_legacy_units_warning", lambda: None)
+ monkeypatch.setattr(fleet_verify, "_time", SimpleNamespace(sleep=lambda _s: None, monotonic=time.monotonic))
+ monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)
monkeypatch.setattr("hermes_cli.update_cmd._finish_dashboard_update_cleanup", lambda *a, **k: None)
monkeypatch.setattr("hermes_cli.gateway_migrate.maybe_auto_migrate_after_update", lambda: None)
return SimpleNamespace(other_checkout=other_checkout)
@@ -79,7 +80,7 @@ def test_symlinked_external_profile_gateway_does_not_fail_update(external_profil
plan = UpdatePlan(runtimes=[_gateway("default", 1111), _gateway("work", 4242)])
update_receipt.begin_update_receipt()
- fleet._verify_fleet_after_update(
+ fleet_verify._verify_fleet_after_update(
_restart_outcome(), _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True,
)
@@ -101,7 +102,7 @@ def test_external_profile_does_not_mask_a_missed_own_gateway(external_profile_ho
update_receipt.begin_update_receipt()
# Contract C3: no longer SystemExit(1); the miss is flagged and owed instead.
- fleet._verify_fleet_after_update(
+ fleet_verify._verify_fleet_after_update(
restart, _pre_update_plan=plan, _windows_gateway_resume=None, update_complete=True,
)
diff --git a/tests/hermes_cli/test_update_finish.py b/tests/hermes_cli/test_update_finish.py
index be9047b7447..a5a9535de10 100644
--- a/tests/hermes_cli/test_update_finish.py
+++ b/tests/hermes_cli/test_update_finish.py
@@ -154,6 +154,7 @@ def completion(tmp_path, monkeypatch):
from hermes_cli import update_cmd as update
from hermes_cli import update_cmd_maint as maint
from hermes_cli import update_cmd_fleet as fleet
+ from hermes_cli import update_cmd_fleet_verify as fleet_verify
from hermes_cli import gateway_migrate
from hermes_cli import macos_tcc_anchor
from hermes_cli import source_build
@@ -196,11 +197,11 @@ def completion(tmp_path, monkeypatch):
maint._print_post_update_notices_and_self_heals = lambda: None
maint._sync_profiles_after_update = lambda: None
maint._print_bundled_skills_sync_report = lambda: None
- fleet._print_legacy_units_warning = lambda: None
+ fleet_verify._print_legacy_units_warning = lambda: None
maint._refresh_dashboard_after_update = lambda **kwargs: None
gateway_migrate.maybe_auto_migrate_after_update = lambda: None
update._surviving_pre_update_serve_runtimes = lambda plan: []
- fleet._collect_fleet_snapshot = lambda *args: []
+ fleet_verify._collect_fleet_snapshot = lambda *args: []
def restart(plan, gateway_mode):
assert isinstance(plan, UpdatePlan)
assert isinstance(plan.runtimes[0], RuntimeRecord)
diff --git a/tests/hermes_cli/test_update_fleet_check_fail_closed.py b/tests/hermes_cli/test_update_fleet_check_fail_closed.py
index f78a39ebf6e..cfdd26d8b6c 100644
--- a/tests/hermes_cli/test_update_fleet_check_fail_closed.py
+++ b/tests/hermes_cli/test_update_fleet_check_fail_closed.py
@@ -39,10 +39,10 @@ class TestCallSiteWiring:
@pytest.mark.parametrize("had_gateway", [False, True], ids=["idle", "plan-saw-gateway"])
def test_empty_probe_settles_and_fails_only_when_rows_expected(self, monkeypatch, tmp_path, capsys, had_gateway):
import json
- from hermes_cli import main, update_cmd, update_cmd_fleet as fleet, update_receipt
+ from hermes_cli import main, update_cmd, update_cmd_fleet as fleet, update_cmd_fleet_verify as fleet_verify, update_receipt
monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr(fleet, "_print_legacy_units_warning", lambda: None)
+ monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)
monkeypatch.setattr("hermes_cli.update_cmd_maint._refresh_dashboard_after_update", lambda **kw: None)
monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])
# Reconciliation is a separate guard; it must not supply this test's failure.
@@ -59,7 +59,7 @@ class TestCallSiteWiring:
events.append("probe")
return []
- monkeypatch.setattr(fleet, "_time", types.SimpleNamespace(monotonic=lambda: now[0], sleep=sleep))
+ monkeypatch.setattr(fleet_verify, "_time", types.SimpleNamespace(monotonic=lambda: now[0], sleep=sleep))
monkeypatch.setattr(update_receipt, "collect_fleet_versions", collect)
restart = fleet._GatewayRestartOutcome(
incomplete=False, phase_errors=[], pre_restart_gateway_pids=[], restarted_services=[],
@@ -69,7 +69,7 @@ class TestCallSiteWiring:
update_receipt.begin_update_receipt()
def verify():
- fleet._verify_fleet_after_update(restart, _pre_update_plan=plan,
+ fleet_verify._verify_fleet_after_update(restart, _pre_update_plan=plan,
_windows_gateway_resume=None, update_complete=True)
cleared = []
@@ -116,10 +116,10 @@ def test_unmapped_stop_keeps_the_restart_owed(monkeypatch, tmp_path):
# (update exit 0, obligation cleared) and stayed down silently. It still predicts no row (the
# test above), but the restart is now OWED: a receipt follow-up and an armed fleet obligation.
import json
- from hermes_cli import main, update_cmd, update_cmd_fleet as fleet, update_receipt
+ from hermes_cli import main, update_cmd, update_cmd_fleet as fleet, update_cmd_fleet_verify as fleet_verify, update_receipt
monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr(fleet, "_print_legacy_units_warning", lambda: None)
+ monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)
monkeypatch.setattr("hermes_cli.update_cmd_maint._refresh_dashboard_after_update", lambda **kw: None)
monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])
monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda **kw: [])
@@ -131,7 +131,7 @@ def test_unmapped_stop_keeps_the_restart_owed(monkeypatch, tmp_path):
killed_pids={101}, stopped_unmapped_pids={101},
)
update_receipt.begin_update_receipt()
- fleet._verify_fleet_after_update(out, _pre_update_plan=_plan([]), _windows_gateway_resume=None,
+ fleet_verify._verify_fleet_after_update(out, _pre_update_plan=_plan([]), _windows_gateway_resume=None,
update_complete=True)
receipt = json.loads((update_cmd.get_hermes_home() / "logs/update_receipts/latest.json").read_text())
assert receipt["outcome"] == "success"
diff --git a/tests/hermes_cli/test_update_fleet_completion.py b/tests/hermes_cli/test_update_fleet_completion.py
index 2a458ff58de..b423756dd22 100644
--- a/tests/hermes_cli/test_update_fleet_completion.py
+++ b/tests/hermes_cli/test_update_fleet_completion.py
@@ -4,7 +4,7 @@ import json
import pytest
-from hermes_cli import update_cmd, update_cmd_fleet, update_cmd_maint, update_receipt
+from hermes_cli import update_cmd, update_cmd_fleet, update_cmd_fleet_verify as fleet_verify, update_cmd_maint, update_receipt
from hermes_constants import get_hermes_home
@@ -22,7 +22,7 @@ def test_fleet_completion_preserves_runtime_verdict_and_restart_obligation(
restarted_services=["hermes-gateway"], failed_or_stale_units=[],
relaunched_profiles=[], externally_supervised_profiles=[], killed_pids=set(),
)
- monkeypatch.setattr(update_cmd_fleet, "_print_legacy_units_warning", lambda: None)
+ monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)
monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])
monkeypatch.setattr(
update_cmd_maint, "_refresh_dashboard_after_update",
@@ -38,14 +38,14 @@ def test_fleet_completion_preserves_runtime_verdict_and_restart_obligation(
assert rows_expected is True
return snapshot
- monkeypatch.setattr(update_cmd_fleet, "_collect_fleet_snapshot", collect)
+ monkeypatch.setattr(fleet_verify, "_collect_fleet_snapshot", collect)
update_cmd_fleet._write_fleet_restart_pending_marker()
assert update_cmd_fleet._fleet_restart_obligation_armed()
healthy = update_complete and state == "current"
with update_receipt.update_receipt_scope():
update_receipt.begin_update_receipt()
# Contract C3: neither verdict fails the committed update any more (was SystemExit(1)).
- update_cmd_fleet._verify_fleet_after_update(
+ fleet_verify._verify_fleet_after_update(
restart, _pre_update_plan=None, _windows_gateway_resume=None,
update_complete=update_complete,
)
diff --git a/tests/hermes_cli/test_update_fleet_snapshot_settle.py b/tests/hermes_cli/test_update_fleet_snapshot_settle.py
index 62b55d3494d..894b152da53 100644
--- a/tests/hermes_cli/test_update_fleet_snapshot_settle.py
+++ b/tests/hermes_cli/test_update_fleet_snapshot_settle.py
@@ -14,6 +14,7 @@ from types import SimpleNamespace
from hermes_cli import update_cmd
import hermes_cli.update_cmd_fleet as update_cmd_fleet
+import hermes_cli.update_cmd_fleet_verify as fleet_verify
from hermes_constants import get_hermes_home
@@ -45,11 +46,11 @@ def test_snapshot_waits_for_late_current_gateway_state(monkeypatch) -> None:
restart = SimpleNamespace(pre_restart_gateway_pids=[101])
- result = update_cmd_fleet._collect_fleet_snapshot(restart, rows_expected=True)
+ result = fleet_verify._collect_fleet_snapshot(restart, rows_expected=True)
assert result == [expected]
assert clock.now > 30.0
- assert clock.now <= update_cmd_fleet._FLEET_PROBE_SETTLE_TIMEOUT_SECONDS
+ assert clock.now <= fleet_verify._FLEET_PROBE_SETTLE_TIMEOUT_SECONDS
def test_snapshot_stops_waiting_once_the_restarted_unit_is_dead(monkeypatch) -> None:
@@ -64,7 +65,7 @@ def test_snapshot_stops_waiting_once_the_restarted_unit_is_dead(monkeypatch) ->
stdout="LoadState=loaded\nActiveState=failed\n", stderr="", returncode=0))
restart = SimpleNamespace(pre_restart_gateway_pids=[101], restarted_scoped_units={"user/hermes-gateway.service"})
- assert update_cmd_fleet._collect_fleet_snapshot(restart, rows_expected=True) == []
+ assert fleet_verify._collect_fleet_snapshot(restart, rows_expected=True) == []
assert clock.now < 30.0
@@ -85,11 +86,11 @@ def test_snapshot_keeps_waiting_when_the_unit_is_unknown_to_the_asked_scope(monk
stderr="", returncode=0)
monkeypatch.setattr(update_cmd_fleet, "_systemctl", systemctl)
- assert update_cmd_fleet._restarted_units_gone(("system/hermes-gateway.service",)) is False
+ assert fleet_verify._restarted_units_gone(("system/hermes-gateway.service",)) is False
restart = SimpleNamespace(pre_restart_gateway_pids=[101], restarted_scoped_units={"system/hermes-gateway.service"})
- assert update_cmd_fleet._collect_fleet_snapshot(restart, rows_expected=True) == []
- assert clock.now >= update_cmd_fleet._FLEET_PROBE_SETTLE_TIMEOUT_SECONDS
+ assert fleet_verify._collect_fleet_snapshot(restart, rows_expected=True) == []
+ assert clock.now >= fleet_verify._FLEET_PROBE_SETTLE_TIMEOUT_SECONDS
def test_snapshot_waits_for_the_relaunched_pid_to_publish_its_identity(monkeypatch) -> None:
@@ -104,20 +105,20 @@ def test_snapshot_waits_for_the_relaunched_pid_to_publish_its_identity(monkeypat
monkeypatch.setattr("hermes_cli.update_receipt.collect_fleet_versions", lambda **_kwargs: next(snapshots))
restart = SimpleNamespace(pre_restart_gateway_pids=[32512], restarted_scoped_units=set())
- assert update_cmd_fleet._collect_fleet_snapshot(restart, rows_expected=True) == [current]
+ assert fleet_verify._collect_fleet_snapshot(restart, rows_expected=True) == [current]
assert clock.now == 12.0
# Control: the same unknown row for a pid that was already running pre-update is settled as-is.
clock.now = 0.0
monkeypatch.setattr("hermes_cli.update_receipt.collect_fleet_versions", lambda **_kwargs: [dict(unknown)])
survivor = SimpleNamespace(pre_restart_gateway_pids=[34516], restarted_scoped_units=set())
- result = update_cmd_fleet._collect_fleet_snapshot(survivor, rows_expected=True)
+ result = fleet_verify._collect_fleet_snapshot(survivor, rows_expected=True)
assert clock.now == 2.0 and "identity_pending" not in result[0]
# Still unknown at the deadline: flagged so the matrix prints restart-aware copy, never "predates".
clock.now = 0.0
- result = update_cmd_fleet._collect_fleet_snapshot(restart, rows_expected=True)
- assert clock.now >= update_cmd_fleet._FLEET_PROBE_SETTLE_TIMEOUT_SECONDS
+ result = fleet_verify._collect_fleet_snapshot(restart, rows_expected=True)
+ assert clock.now >= fleet_verify._FLEET_PROBE_SETTLE_TIMEOUT_SECONDS
assert result[0]["identity_pending"] is True
@@ -139,7 +140,7 @@ def test_verifier_clears_marker_after_late_current_gateway_state(monkeypatch) ->
"hermes_cli.update_receipt.print_fleet_version_matrix",
lambda _fleet: False,
)
- monkeypatch.setattr(update_cmd_fleet, "_print_legacy_units_warning", lambda: None)
+ monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)
monkeypatch.setattr(update_cmd, "_finish_dashboard_update_cleanup", lambda *a, **k: None)
monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda _plan: [])
monkeypatch.setattr(update_cmd, "_warn_stale_serve_runtimes", lambda _rows: None)
@@ -157,7 +158,7 @@ def test_verifier_clears_marker_after_late_current_gateway_state(monkeypatch) ->
fleet_probe_signals=lambda: ([101], set()),
)
- update_cmd_fleet._verify_fleet_after_update(
+ fleet_verify._verify_fleet_after_update(
restart,
_pre_update_plan=None,
_windows_gateway_resume=None,
diff --git a/tests/hermes_cli/test_update_post_commit_followups.py b/tests/hermes_cli/test_update_post_commit_followups.py
index f7fe1f61561..c91576436c5 100644
--- a/tests/hermes_cli/test_update_post_commit_followups.py
+++ b/tests/hermes_cli/test_update_post_commit_followups.py
@@ -142,6 +142,7 @@ def test_owed_restart_names_its_gateways_so_a_dead_fleet_cannot_discharge_it(tmp
# A gateway that died at boot leaves no live row. An inventory-less obligation would be settled
# by the gateway-less discharge, silencing the warning that replaces exit 1 under C3.
from hermes_cli import update_cmd_fleet as fleet
+ from hermes_cli import update_cmd_fleet_verify as fleet_verify
from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -149,7 +150,7 @@ def test_owed_restart_names_its_gateways_so_a_dead_fleet_cannot_discharge_it(tmp
fleet._write_fleet_restart_pending_marker(expected_sha="a" * 40)
plan = UpdatePlan(runtimes=[RuntimeRecord(kind="gateway", profile="default", pid=4242),
RuntimeRecord(kind="dashboard", profile="default", pid=4343)])
- fleet._record_owed_gateway_inventory(plan)
+ fleet_verify._record_owed_gateway_inventory(plan)
inventory = json.loads(fleet._obligation_fields()["inventory"])
assert [(r["kind"], r["profile"]) for r in inventory["runtimes"]] == [("gateway", "default")]
@@ -164,6 +165,7 @@ def test_owed_restart_rearms_a_settled_obligation_and_a_later_run_keeps_owing_it
# A pre-restart probe can settle an inventory-less record; the owed restart must re-arm it, and
# a later verify that finds nothing to restart must keep owing the named gateway.
from hermes_cli import update_cmd_fleet as fleet
+ from hermes_cli import update_cmd_fleet_verify as fleet_verify
from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -171,8 +173,8 @@ def test_owed_restart_rearms_a_settled_obligation_and_a_later_run_keeps_owing_it
monkeypatch.setattr(fleet, "_current_checkout_sha", lambda: "b" * 40)
monkeypatch.setattr("hermes_cli.update_receipt.collect_fleet_versions", lambda: [])
assert not fleet._fleet_restart_obligation_armed()
- fleet._record_owed_gateway_inventory(UpdatePlan(runtimes=[RuntimeRecord(kind="gateway", profile="default")]))
+ fleet_verify._record_owed_gateway_inventory(UpdatePlan(runtimes=[RuntimeRecord(kind="gateway", profile="default")]))
assert fleet._obligation_fields()["expected_sha"] == "b" * 40
# A later verify with nothing live to restart still owes the named gateway (and keeps it armed).
- assert fleet._named_gateways_still_owed()
+ assert fleet_verify._named_gateways_still_owed()
assert fleet._fleet_restart_obligation_armed()
diff --git a/tests/hermes_cli/test_update_stale_gateway_yield.py b/tests/hermes_cli/test_update_stale_gateway_yield.py
index 11b9937fffe..f967d21b157 100644
--- a/tests/hermes_cli/test_update_stale_gateway_yield.py
+++ b/tests/hermes_cli/test_update_stale_gateway_yield.py
@@ -105,16 +105,17 @@ def test_update_signals_proven_stale_gateway_survivor(cron_home, tmp_path):
def test_verify_fleet_hands_stale_rows_to_survivor_signalling(monkeypatch):
"""The wiring: a stale fleet matrix reaches signal_stale_fleet_survivors; the restart stays owed."""
import hermes_cli.update_cmd_fleet as fleet_mod
+ import hermes_cli.update_cmd_fleet_verify as fleet_verify
import hermes_cli.update_cmd_stale_survivors as surv
import hermes_cli.update_cmd as update_cmd
from hermes_cli.update_cmd_fleet import _GatewayRestartOutcome
stale_fleet = [{"profile": "default", "pid": 4242, "state": "stale", "code_sha": "a" * 40}]
seen = {}
- monkeypatch.setattr(fleet_mod, "_print_legacy_units_warning", lambda: None)
+ monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)
monkeypatch.setattr(update_cmd, "_finish_dashboard_update_cleanup", lambda *a, **k: None)
monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])
- monkeypatch.setattr(fleet_mod, "_collect_fleet_snapshot", lambda restart, expected: stale_fleet)
+ monkeypatch.setattr(fleet_verify, "_collect_fleet_snapshot", lambda restart, expected: stale_fleet)
monkeypatch.setattr(surv, "signal_stale_fleet_survivors",
lambda fleet, restart, budget: seen.setdefault("fleet", fleet) and [])
restart = _GatewayRestartOutcome(
@@ -122,7 +123,7 @@ def test_verify_fleet_hands_stale_rows_to_survivor_signalling(monkeypatch):
failed_or_stale_units=[], relaunched_profiles=[], externally_supervised_profiles=[], killed_pids=set(),
)
with contextlib.redirect_stdout(io.StringIO()):
- fleet_mod._verify_fleet_after_update(
+ fleet_verify._verify_fleet_after_update(
restart, _pre_update_plan=None, _windows_gateway_resume=None, update_complete=True,
)
# Contract C3: was SystemExit(1); now flagged incomplete (owed restart, marker kept).
diff --git a/tests/hermes_cli/test_update_zip_completion.py b/tests/hermes_cli/test_update_zip_completion.py
index 2eda523fa2e..6f990d8feef 100644
--- a/tests/hermes_cli/test_update_zip_completion.py
+++ b/tests/hermes_cli/test_update_zip_completion.py
@@ -11,7 +11,7 @@ import zipfile
import pytest
from hermes_cli import main, update_cmd, update_cmd_fleet as fleet, update_cmd_maint as maint
-from hermes_cli import update_cmd_zip, update_receipt
+from hermes_cli import update_cmd_fleet_verify as fleet_verify, update_cmd_zip, update_receipt
from hermes_cli.config_defaults import DEFAULT_CONFIG
from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan
import hermes_yaml
@@ -84,10 +84,10 @@ def zip_update(tmp_path, monkeypatch, isolated_source_completion):
monkeypatch.setattr("hermes_cli.profiles.seed_profile_skills", lambda *a, **kw: {})
monkeypatch.setattr(update_cmd, "_reload_config_modules", lambda: None)
monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None))
- monkeypatch.setattr(fleet, "_print_legacy_units_warning", lambda: None)
+ monkeypatch.setattr(fleet_verify, "_print_legacy_units_warning", lambda: None)
monkeypatch.setattr(maint, "_refresh_dashboard_after_update", lambda **kwargs: None)
monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])
- monkeypatch.setattr(fleet, "_collect_fleet_snapshot", lambda *args: [])
+ monkeypatch.setattr(fleet_verify, "_collect_fleet_snapshot", lambda *args: [])
monkeypatch.setattr("hermes_cli.gateway_migrate.maybe_auto_migrate_after_update", lambda: None)
def resume(received):