Skip to content

The agent that grows with you

fix: post-update fleet settle poll no longer ends early on inconclusive signals

teknium1f079458401fb
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index 6687b942a83..88eb0b4e61b 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -1429,36 +1429,59 @@ def _collect_fleet_snapshot(restart, rows_expected: bool) -> list:
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 (exit 1)
- instead of no row at all.
+ 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
if not rows_expected:
return collect_fleet_versions(pre_restart_pids=restart.pre_restart_gateway_pids)
+ 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=restart.pre_restart_gateway_pids)
- if snapshot and not any(row.get("state") == "down" for row in snapshot):
+ snapshot = collect_fleet_versions(pre_restart_pids=pre_pids)
+ pending = [row for row in snapshot if _fleet_row_identity_pending(row, pre_pids)]
+ if snapshot and not pending 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 pending:
+ 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 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. Unknown (no units, systemctl missing/slow) keeps waiting."""
+ """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:
- state = _systemctl(scope_cmds[scope] + ["is-active", name], timeout=5).stdout.strip()
+ stdout = _systemctl(scope_cmds[scope] + ["show", "-p", "LoadState,ActiveState", name], timeout=5).stdout
except (KeyError, FileNotFoundError, subprocess.TimeoutExpired):
return False
- if state in ("active", "activating", "reloading"):
+ 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
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index dc7cec31d52..eacc5e6e173 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -365,6 +365,12 @@ _FLEET_ROW_LINES = {
"down": " ✗ {profile} — DOWN (gateway was running before the update; pid {pid} is gone and nothing replaced it)",
}
_FLEET_ROW_UNKNOWN = " ? {profile} (pid {pid}) — version unknown (gateway predates version stamping; restart to enable)"
+# A gateway this update relaunched that had not published its code identity when the settle window
+# closed (#112634): it was just restarted on the new code, so "restart to enable" would be wrong.
+_FLEET_ROW_IDENTITY_PENDING = (
+ " ? {profile} (pid {pid}) — restarted by this update, code identity not published yet"
+ " — re-check with `hermes gateway status`"
+)
def print_fleet_version_matrix(fleet: list[dict[str, Any]]) -> bool:
@@ -384,7 +390,8 @@ def print_fleet_version_matrix(fleet: list[dict[str, Any]]) -> bool:
for entry in fleet:
sha = entry.get("code_sha")
states.add(entry.get("state"))
- print(_FLEET_ROW_LINES.get(entry.get("state"), _FLEET_ROW_UNKNOWN).format(
+ fallback = _FLEET_ROW_IDENTITY_PENDING if entry.get("identity_pending") else _FLEET_ROW_UNKNOWN
+ print(_FLEET_ROW_LINES.get(entry.get("state"), fallback).format(
profile=entry.get("profile"), pid=entry.get("pid"), short=sha[:8] if isinstance(sha, str) and sha else "?",
))
stale_or_down = sum(1 for entry in fleet if entry.get("state") in ("stale", "down"))
diff --git a/tests/hermes_cli/test_update_fleet_snapshot_settle.py b/tests/hermes_cli/test_update_fleet_snapshot_settle.py
index 835b57eb9ea..a64f2a7ff99 100644
--- a/tests/hermes_cli/test_update_fleet_snapshot_settle.py
+++ b/tests/hermes_cli/test_update_fleet_snapshot_settle.py
@@ -60,13 +60,67 @@ def test_snapshot_stops_waiting_once_the_restarted_unit_is_dead(monkeypatch) ->
monkeypatch.setattr("hermes_cli.update_receipt.collect_fleet_versions", lambda **_kwargs: [])
monkeypatch.setattr(
update_cmd_fleet, "_systemctl",
- lambda cmd, *, timeout: SimpleNamespace(stdout="failed\n", stderr="", returncode=3))
+ lambda cmd, *, timeout: SimpleNamespace(
+ 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 clock.now < 30.0
+def test_snapshot_keeps_waiting_when_the_unit_is_unknown_to_the_asked_scope(monkeypatch) -> None:
+ """#112466: a user unit recorded as ``system/<name>`` answers ``LoadState=not-found`` in the
+ system scope — inconclusive, not a dead successor, so the settle poll runs to its deadline."""
+ clock = _FakeClock()
+ monkeypatch.setattr(update_cmd_fleet._time, "monotonic", clock.monotonic)
+ monkeypatch.setattr(update_cmd_fleet._time, "sleep", clock.sleep)
+ monkeypatch.setattr("hermes_cli.update_receipt.collect_fleet_versions", lambda **_kwargs: [])
+
+ def systemctl(cmd, *, timeout):
+ # Real systemctl shape: the owning (user) scope has the unit loaded and active; the system
+ # scope does not know it at all (``is-active`` there would print ``inactive`` rc 4).
+ loaded = "--user" in cmd
+ return SimpleNamespace(
+ stdout=f"LoadState={'loaded' if loaded else 'not-found'}\nActiveState={'active' if loaded else 'inactive'}\n",
+ stderr="", returncode=0)
+
+ monkeypatch.setattr(update_cmd_fleet, "_systemctl", systemctl)
+ assert update_cmd_fleet._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
+
+
+def test_snapshot_waits_for_the_relaunched_pid_to_publish_its_identity(monkeypatch) -> None:
+ """#112634: an ``unknown`` row from a pid that did not exist at update start is a successor still
+ booting — keep polling until it turns ``current``; a surviving pre-restart pid settles at once."""
+ clock = _FakeClock()
+ monkeypatch.setattr(update_cmd_fleet._time, "monotonic", clock.monotonic)
+ monkeypatch.setattr(update_cmd_fleet._time, "sleep", clock.sleep)
+ unknown = {"profile": "default", "pid": 34516, "code_sha": None, "code_version": None, "state": "unknown"}
+ current = {**unknown, "code_sha": "new", "code_version": "0.21.3", "state": "current"}
+ snapshots = iter([[dict(unknown)]] * 5 + [[current]])
+ 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 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)
+ 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
+ assert result[0]["identity_pending"] is True
+
+
def test_verifier_clears_marker_after_late_current_gateway_state(monkeypatch) -> None:
"""A late current row reaches the normal success-only marker cleanup."""
clock = _FakeClock()
diff --git a/tests/hermes_cli/test_update_receipt.py b/tests/hermes_cli/test_update_receipt.py
index e5969a96d7a..17e00efdd5d 100644
--- a/tests/hermes_cli/test_update_receipt.py
+++ b/tests/hermes_cli/test_update_receipt.py
@@ -426,6 +426,17 @@ class TestFleetClassification:
assert ok is False
assert "version unknown" in capsys.readouterr().out
+ def test_identity_pending_row_gets_restart_aware_copy(self, capsys):
+ """#112634: a gateway this update relaunched that has not stamped yet must not be told to
+ restart — it was just restarted on the new code. Still non-fatal."""
+ ok = ur.print_fleet_version_matrix(
+ [{"profile": "default", "pid": 34516, "code_sha": None, "state": "unknown", "identity_pending": True}]
+ )
+ assert ok is False
+ out = capsys.readouterr().out
+ assert "code identity not published yet" in out and "hermes gateway status" in out
+ assert "predates version stamping" not in out
+
class TestGatewayStatusStamping:
def test_runtime_status_record_carries_code_identity(self, monkeypatch):