Skip to content

The agent that grows with you

fix(update): a gateway killed by the restart phase and never replaced now fails the fleet check (DOWN row)

Teknium168487786880
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 62d94198c69..eafe4ef4aa5 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -8129,7 +8129,12 @@ def _cmd_update_impl(args, gateway_mode: bool):
# were running) — nothing to settle.
if restarted_services or killed_pids:
_time.sleep(2.0)
- _fleet_snapshot = collect_fleet_versions()
+ # Pass the pre-restart PID snapshot so a gateway the restart
+ # phase stopped WITHOUT a verified replacement shows as a DOWN
+ # row (exit 1) instead of silently producing no row at all.
+ _fleet_snapshot = collect_fleet_versions(
+ pre_restart_pids=_pre_restart_gateway_pids
+ )
if print_fleet_version_matrix(_fleet_snapshot):
gateway_fleet_restart_incomplete = True
except Exception as _fleet_exc:
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index 135c90e2749..8989bdb3a23 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -277,21 +277,40 @@ def read_latest_receipt() -> Optional[dict[str, Any]]:
# Fleet version verification
# ---------------------------------------------------------------------------
-def collect_fleet_versions() -> list[dict[str, Any]]:
+def collect_fleet_versions(
+ *, pre_restart_pids: Optional[list[int]] = None
+) -> list[dict[str, Any]]:
"""Snapshot every profile's gateway code identity vs. the current tree.
Returns one entry per profile home that has a ``gateway_state.json``
- with a live PID::
+ describing a gateway that is live — or that SHOULD be live::
{"profile": str, "pid": int, "code_sha": str|None,
- "code_version": str|None, "state": "current"|"stale"|"unknown"}
+ "code_version": str|None, "state": "current"|"stale"|"unknown"|"down"}
``stale`` — gateway stamped a code_sha that differs from the updated
checkout's HEAD (it is still serving pre-update modules).
``unknown`` — gateway predates the code-identity stamp (started before
this feature landed) or identity could not be resolved.
+ ``down`` — the gateway was ALIVE when this update started
+ (``pre_restart_pids``), its runtime status still says
+ running, but the PID is dead and no successor rewrote the
+ record: the restart phase stopped it and nothing came
+ back. Without this row a killed-and-never-replaced gateway
+ produced NO entry at all and the matrix passed silently
+ (Phase-1 verification gap, #88848/#74973 class).
+
+ Rollout safety: ``down`` requires membership in ``pre_restart_pids`` —
+ a stale state file from a long-dead gateway (machine reboot, manual
+ kill weeks ago) must NOT fail every future update. Callers that don't
+ have a pre-restart snapshot (``None``/empty) get the historical
+ behavior: dead PIDs are skipped.
Never raises; a probe failure yields an empty list.
"""
+ # Runtime-status states that mean "this record does not describe a
+ # gateway that should be running now" — no down row for these.
+ _NOT_EXPECTED_STATES = {"stopped", "startup_failed"}
+ _pre_restart = {int(p) for p in (pre_restart_pids or []) if isinstance(p, int)}
results: list[dict[str, Any]] = []
try:
from hermes_cli.build_info import get_code_identity
@@ -364,6 +383,28 @@ def collect_fleet_versions() -> list[dict[str, Any]]:
except (TypeError, ValueError):
continue
if not _pid_exists(pid):
+ # Dead PID: a DOWN row only when this exact pid was alive at
+ # update start AND the record still claims a running state —
+ # "the restart phase stopped it and nothing came back."
+ # Everything else (clean stop, startup failure, stale record
+ # from a long-dead gateway) keeps the historical no-row
+ # behavior so the feature's rollout can't false-positive.
+ gw_state = record.get("gateway_state")
+ if (
+ pid in _pre_restart
+ and isinstance(gw_state, str)
+ and gw_state
+ and gw_state not in _NOT_EXPECTED_STATES
+ ):
+ results.append(
+ {
+ "profile": profile,
+ "pid": pid,
+ "code_sha": None,
+ "code_version": record.get("code_version"),
+ "state": "down",
+ }
+ )
continue
code_sha = record.get("code_sha")
if not code_sha or not expected_sha:
@@ -390,15 +431,17 @@ def print_fleet_version_matrix(fleet: list[dict[str, Any]]) -> bool:
"""Print the post-update fleet version matrix.
Returns True when at least one gateway is provably stale (still
- serving pre-update code), so the caller can escalate. ``unknown``
- entries are reported but do NOT fail the update: gateways started
- before the code-identity stamp existed have no sha to compare, and
- failing on them would turn this feature's own rollout into a
+ serving pre-update code) OR provably down (was running, killed by the
+ restart phase, nothing came back), so the caller can escalate.
+ ``unknown`` entries are reported but do NOT fail the update: gateways
+ started before the code-identity stamp existed have no sha to compare,
+ and failing on them would turn this feature's own rollout into a
false-positive storm.
"""
if not fleet:
return False
any_stale = False
+ any_down = False
print()
print("Fleet version check:")
for entry in fleet:
@@ -412,14 +455,23 @@ def print_fleet_version_matrix(fleet: list[dict[str, Any]]) -> bool:
elif state == "stale":
any_stale = True
print(f" ✗ {profile} (pid {pid}) @ {short} — STALE (pre-update code)")
+ elif state == "down":
+ any_down = True
+ print(
+ f" ✗ {profile} — DOWN (gateway was running before the "
+ f"update; pid {pid} is gone and nothing replaced it)"
+ )
else:
print(
f" ? {profile} (pid {pid}) — version unknown "
"(gateway predates version stamping; restart to enable)"
)
- if any_stale:
+ if any_stale or any_down:
print()
- print(" ⚠ Stale gateways keep serving pre-update code until restarted:")
+ if any_stale:
+ print(" ⚠ Stale gateways keep serving pre-update code until restarted:")
+ if any_down:
+ print(" ⚠ Down gateways stopped serving messaging entirely — restart them:")
print(" hermes gateway restart # active profile")
print(" hermes -p <profile> gateway restart # named profile")
- return any_stale
+ return any_stale or any_down
diff --git a/tests/hermes_cli/test_fleet_matrix_down_state.py b/tests/hermes_cli/test_fleet_matrix_down_state.py
new file mode 100644
index 00000000000..b9f8c37c5b9
--- /dev/null
+++ b/tests/hermes_cli/test_fleet_matrix_down_state.py
@@ -0,0 +1,97 @@
+"""Fleet matrix DOWN-state coverage (Phase-1 verification gap, #91277).
+
+A gateway that was ALIVE at update start, got stopped by the restart phase,
+and never came back used to produce NO matrix row at all — the check passed
+silently on a fleet that lost messaging. Now it yields a `down` row and the
+matrix returns True (escalate/exit 1). Rollout safety: `down` requires the
+pid to be in the caller's pre-restart snapshot, so stale state files from
+long-dead gateways never false-positive.
+"""
+
+import json
+import os
+from pathlib import Path
+
+import hermes_cli.update_receipt as ur
+
+
+def _setup(monkeypatch, tmp_path, record: dict):
+ home = tmp_path / ".hermes"
+ home.mkdir(exist_ok=True)
+ monkeypatch.setattr(
+ "hermes_cli.build_info.get_code_identity",
+ lambda refresh=False: {"sha": "HEADSHA", "version": "1.0"},
+ )
+ monkeypatch.setattr("hermes_cli.profiles._get_default_hermes_home", lambda: home)
+ monkeypatch.setattr(
+ "hermes_cli.profiles._get_profiles_root", lambda: tmp_path / "no-profiles"
+ )
+ monkeypatch.setattr("gateway.control_socket.identify_gateway", lambda h, **k: None)
+ (home / "gateway_state.json").write_text(json.dumps(record), encoding="utf-8")
+ return home
+
+
+_DEAD_PID = 999999899 # never a live pid
+
+
+def test_killed_never_replaced_gateway_is_a_down_row(monkeypatch, tmp_path):
+ _setup(
+ monkeypatch,
+ tmp_path,
+ {"pid": _DEAD_PID, "gateway_state": "running", "kind": "hermes-gateway",
+ "code_version": "0.20.5"},
+ )
+ fleet = ur.collect_fleet_versions(pre_restart_pids=[_DEAD_PID])
+ assert len(fleet) == 1
+ assert fleet[0]["state"] == "down"
+ assert fleet[0]["pid"] == _DEAD_PID
+ # and the matrix escalates on it
+ assert ur.print_fleet_version_matrix(fleet) is True
+
+
+def test_dead_pid_not_in_pre_restart_snapshot_keeps_no_row(monkeypatch, tmp_path):
+ """Stale state file from a long-dead gateway: rollout-safe no-row."""
+ _setup(
+ monkeypatch,
+ tmp_path,
+ {"pid": _DEAD_PID, "gateway_state": "running", "kind": "hermes-gateway"},
+ )
+ assert ur.collect_fleet_versions(pre_restart_pids=[12345]) == []
+ assert ur.collect_fleet_versions(pre_restart_pids=None) == []
+ assert ur.collect_fleet_versions() == []
+
+
+def test_cleanly_stopped_gateway_is_not_down(monkeypatch, tmp_path):
+ for benign_state in ("stopped", "startup_failed"):
+ _setup(
+ monkeypatch,
+ tmp_path,
+ {"pid": _DEAD_PID, "gateway_state": benign_state, "kind": "hermes-gateway"},
+ )
+ assert ur.collect_fleet_versions(pre_restart_pids=[_DEAD_PID]) == []
+
+
+def test_live_gateway_rows_unchanged(monkeypatch, tmp_path):
+ """The live-pid path is untouched by the down-state addition."""
+ _setup(
+ monkeypatch,
+ tmp_path,
+ {"pid": os.getpid(), "gateway_state": "running", "code_sha": "HEADSHA",
+ "kind": "hermes-gateway"},
+ )
+ fleet = ur.collect_fleet_versions(pre_restart_pids=[os.getpid()])
+ assert len(fleet) == 1
+ assert fleet[0]["state"] == "current"
+ assert ur.print_fleet_version_matrix(fleet) is False
+
+
+def test_down_and_stale_both_escalate_with_remediation(capsys):
+ fleet = [
+ {"profile": "default", "pid": 1, "code_sha": "OLD", "state": "stale"},
+ {"profile": "coder", "pid": 2, "code_sha": None, "state": "down"},
+ ]
+ assert ur.print_fleet_version_matrix(fleet) is True
+ out = capsys.readouterr().out
+ assert "STALE" in out
+ assert "DOWN" in out
+ assert "hermes gateway restart" in out