Skip to content

The agent that grows with you

fix(cron): stale-code yield reads as an outage in `cron status`; `hermes update` restarts proven-stale gateways

teknium18863b36fd663
diff --git a/cron/scheduler.py b/cron/scheduler.py
index a8a4f28a7d5..c8b20ea9346 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -185,6 +185,22 @@ class CronTickYielded(RuntimeError):
)
+_STALE_YIELD_RE = re.compile(r"stale code: booted on (\S+), disk is at (\S+)\)")
+
+
+def stale_code_yield_labels(recorded_error: str | None) -> tuple[str, str] | None:
+ """``(boot_rev, disk_rev)`` when a persisted ``ticker_last_error`` is a ``CronTickYielded``.
+
+ ``hermes cron status`` runs in another process and only sees the marker text; a yielding
+ ticker still refreshes its heartbeat, so this is the one signal that separates "stale code,
+ firing nothing" from a healthy loop (#117275).
+ """
+ if not recorded_error or not recorded_error.startswith(CronTickYielded.__name__):
+ return None
+ match = _STALE_YIELD_RE.search(recorded_error)
+ return (match.group(1), match.group(2)) if match else None
+
+
# Log the yield at most once per episode (reset when the skew changes) to avoid per-interval spam.
_YIELD_LOG_INTERVAL_SECONDS = 3600.0
_last_yield_log: dict[str, object] = {}
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index a5f1407495b..bf66a72b5f4 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -395,8 +395,10 @@ def _print_ticker_health(pids: list, restart_command: str = "hermes gateway rest
from cron.jobs import (
get_ticker_heartbeat_age, get_ticker_last_error, get_ticker_success_age)
from cron.scheduler import _is_fd_exhaustion_text as _cron_is_fd_exhaustion_text
+ from cron.scheduler import stale_code_yield_labels
hb_age = get_ticker_heartbeat_age()
ok_age = get_ticker_success_age()
+ last_error = get_ticker_last_error()
pid_line = f" PID: {', '.join(map(str, pids))}" if pids else None
def _warn(headline: str) -> None:
@@ -414,10 +416,19 @@ def _print_ticker_health(pids: list, restart_command: str = "hermes gateway rest
_warn("⚠ Gateway is running but the cron ticker looks STALLED — "
f"no heartbeat for {int(hb_age)}s (expected every ~60s).")
print(f" Cron jobs may NOT be firing. Restart: {restart_command}")
- elif ok_age is not None and not _ticker_age_is_fresh(ok_age): # loop alive but every tick fails
+ elif (skew := stale_code_yield_labels(last_error)) is not None:
+ # `hermes update` moved the checkout under a running gateway: its ticker yields every
+ # tick (heartbeat stays fresh, nothing dispatches) until the process is restarted (#117275).
+ _warn("⚠ Gateway is running STALE code — its cron ticker yields every tick and "
+ "fires NOTHING.")
+ print(color(f" Booted on {skew[0]}, checkout is now at {skew[1]} "
+ "(the code was updated under the running gateway).", Colors.RED))
+ print(f" Restart it onto the new code: {restart_command}")
+ elif (ok_age is not None and not _ticker_age_is_fresh(ok_age)) or (ok_age is None and last_error):
+ # Loop alive but every tick fails (or has never succeeded since boot).
_warn("⚠ Gateway and cron ticker are running, but no tick has "
- f"succeeded in {int(ok_age)}s — ticks may be failing.")
- last_error = get_ticker_last_error()
+ f"succeeded {'in ' + str(int(ok_age)) + 's' if ok_age is not None else 'yet'} "
+ "— ticks may be failing.")
if last_error:
# WHY ticks fail: root-rewritten jobs.json (PermissionError) or fd exhaustion.
# Show WHY ticks fail — e.g. a root-rewritten jobs.json (PermissionError) that silently locked
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index 29e78585614..2f2ab605a23 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -1500,6 +1500,15 @@ def _recover_after_restart_phase_abort(
out.record_receipt(phase_error=str(e), fresh_recovery=_recovery_result)
+def _gateway_drain_budget() -> float:
+ """Seconds a drain-first (SIGUSR1) restart may wait for a gateway to exit; 45s floor."""
+ try:
+ from hermes_cli.gateway import _get_restart_exit_wait_budget
+ return max(float(_get_restart_exit_wait_budget()), 45.0)
+ except Exception:
+ return 45.0
+
+
def _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode: bool):
"""Restart every running gateway (systemd, launchd, manual) onto the pulled code.
@@ -1541,11 +1550,7 @@ def _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode: bool):
# Drain budget covers ``restart_after_turn_timeout`` and stop()'s
# ``restart_drain_timeout`` so a gateway waiting on a turn isn't hard-killed;
# units without SIGUSR1 wiring just time out into ``systemctl restart``.
- try:
- from hermes_cli.gateway import _get_restart_exit_wait_budget
- _drain_budget = max(float(_get_restart_exit_wait_budget()), 45.0)
- except Exception:
- _drain_budget = 45.0
+ _drain_budget = _gateway_drain_budget()
# Snapshot before any stop/drain so an empty survivor probe reads as "stopped
# and never came back", not "nothing was running"; None fails closed.
@@ -1725,6 +1730,10 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_re
_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 — fail (partial, exit 1).
diff --git a/hermes_cli/update_cmd_stale_survivors.py b/hermes_cli/update_cmd_stale_survivors.py
new file mode 100644
index 00000000000..e1716ff8143
--- /dev/null
+++ b/hermes_cli/update_cmd_stale_survivors.py
@@ -0,0 +1,65 @@
+"""Post-update escalation for gateways the fleet matrix proved stale.
+
+``_verify_fleet_after_update`` compares every live gateway's stamped ``code_sha`` against the
+fresh checkout. Until now a ``stale`` row only failed the update (exit 1) and left the process
+running pre-update modules: its cron ticker then yields every tick to the "fresh gateway" it
+assumes exists, and nothing ever restarts it (#117275). A proven-stale survivor is now handed to
+the same drain-first ``request_restart`` path (SIGUSR1) the restart phase uses — a supervised
+gateway respawns on the new code, a bare ``gateway run`` stops and is listed for a manual restart.
+"""
+
+from __future__ import annotations
+
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+def stale_fleet_survivor_pids(fleet: list, already_signalled: set) -> list[int]:
+ """Live PIDs the fleet matrix stamped ``stale`` that the restart phase never touched."""
+ pids: list[int] = []
+ for row in fleet or []:
+ pid = row.get("pid") if isinstance(row, dict) else None
+ if row.get("state") == "stale" and isinstance(pid, int) and pid > 0 and pid not in already_signalled:
+ pids.append(pid)
+ return pids
+
+
+def signal_stale_fleet_survivors(fleet: list, restart, drain_budget: float) -> list[int]:
+ """Drain-first restart every proven-stale gateway; returns the PIDs signalled.
+
+ Bookkeeping lands in ``restart.killed_pids`` so the receipt and the survivor sweep see them.
+ Never raises: verification must still finalize the receipt and exit 1.
+ """
+ from hermes_cli.update_cmd_fleet import _drain_or_signal_gateway_for_update
+
+ pids = stale_fleet_survivor_pids(fleet, set(restart.killed_pids))
+ if not pids:
+ return []
+ try:
+ from hermes_cli.gateway import _get_service_pids
+ service_pids = set(_get_service_pids(all_profiles=True))
+ except Exception:
+ service_pids = set()
+ labels = {row.get("pid"): str(row.get("profile") or "gateway") for row in fleet if isinstance(row, dict)}
+ print()
+ print(f" ⚠ {len(pids)} gateway process(es) still run the pre-update code — requesting a restart")
+ signalled: list[int] = []
+ manual: list[int] = []
+ for pid in pids:
+ label = f"{labels.get(pid, 'gateway')} (PID {pid})"
+ try:
+ if _drain_or_signal_gateway_for_update(pid, drain_budget, label):
+ signalled.append(pid)
+ restart.killed_pids.add(pid)
+ if pid not in service_pids:
+ manual.append(pid)
+ except Exception as exc:
+ logger.warning("Could not signal stale gateway PID %s: %s", pid, exc)
+ print(f" ⚠ {label}: could not be signalled ({exc}) — restart it by hand")
+ if manual:
+ print(f" → Stopped {len(manual)} manual gateway process(es) that had no supervisor to respawn them")
+ print(" Restart manually: hermes gateway run")
+ if len(manual) > 1:
+ print(" (or: hermes -p <profile> gateway run for each profile)")
+ return signalled
diff --git a/tests/hermes_cli/test_update_stale_gateway_yield.py b/tests/hermes_cli/test_update_stale_gateway_yield.py
new file mode 100644
index 00000000000..59f01c459b2
--- /dev/null
+++ b/tests/hermes_cli/test_update_stale_gateway_yield.py
@@ -0,0 +1,131 @@
+"""#117275: a stale-code ticker that yields every tick must never read as healthy, and the
+updater must hand a proven-stale survivor to the request_restart path."""
+
+import io
+import contextlib
+import os
+import signal
+import subprocess
+import sys
+import time
+
+import pytest
+
+
+def cron_home(tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ (home / ".hermes").mkdir(parents=True)
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("HERMES_HOME", str(home / ".hermes"))
+ for name in list(sys.modules):
+ if name.split(".")[0] in ("cron", "gateway", "hermes_cli", "hermes_constants"):
+ monkeypatch.delitem(sys.modules, name, raising=False)
+ return home / ".hermes"
+
+
+def _status_block(pids):
+ from hermes_cli.cron import _print_ticker_health
+
+ buf = io.StringIO()
+ with contextlib.redirect_stdout(buf):
+ _print_ticker_health(pids)
+ return buf.getvalue()
+
+
[email protected]("had_success_before_update", [False, True])
+def test_cron_status_reports_stale_code_yield_as_unhealthy(cron_home, had_success_before_update):
+ """Fresh heartbeat + persisted CronTickYielded == outage, whatever the success marker says."""
+ from cron.jobs import _current_cron_store, ensure_dirs, record_ticker_error, record_ticker_heartbeat
+ from cron.scheduler import CronTickYielded
+
+ ensure_dirs()
+ if had_success_before_update:
+ (_current_cron_store().cron_dir / "ticker_last_success").write_text(str(time.time() - 600))
+ exc = CronTickYielded("5eb99eb284", "2ed6387d87")
+ record_ticker_error(f"{type(exc).__name__}: {exc}")
+ record_ticker_heartbeat(success=False)
+
+ out = _status_block([4242])
+
+ assert "cron jobs will fire automatically" not in out
+ assert "STALE code" in out
+ assert "5eb99eb284" in out and "2ed6387d87" in out
+ assert "hermes gateway restart" in out
+
+
+def test_cron_status_still_green_after_a_clean_tick(cron_home):
+ """Control: a ticker whose last cycle succeeded reads healthy."""
+ from cron.jobs import clear_ticker_error, ensure_dirs, record_ticker_heartbeat
+
+ ensure_dirs()
+ record_ticker_heartbeat(success=True)
+ clear_ticker_error()
+
+ assert "cron jobs will fire automatically" in _status_block([4242])
+
+
[email protected](not hasattr(signal, "SIGUSR1"), reason="POSIX drain-first restart signal")
+def test_update_signals_proven_stale_gateway_survivor(cron_home, tmp_path):
+ """A `stale` fleet-matrix row gets SIGUSR1 (request_restart); a `current` row is untouched."""
+ from hermes_cli.update_cmd_fleet import _GatewayRestartOutcome
+ from hermes_cli.update_cmd_stale_survivors import signal_stale_fleet_survivors
+
+ marker = tmp_path / "got_sigusr1"
+ child = subprocess.Popen(
+ [sys.executable, "-c",
+ "import signal, sys, time\n"
+ f"signal.signal(signal.SIGUSR1, lambda *_: (open({str(marker)!r}, 'w').write('x'), sys.exit(75)))\n"
+ "print('ready', flush=True)\n"
+ "time.sleep(120)"],
+ stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True,
+ )
+ try:
+ assert child.stdout.readline().strip() == "ready"
+ restart = _GatewayRestartOutcome(
+ incomplete=True, phase_errors=[], pre_restart_gateway_pids=[child.pid], restarted_services=[],
+ failed_or_stale_units=[], relaunched_profiles=[], externally_supervised_profiles=[], killed_pids=set(),
+ )
+ fleet = [
+ {"profile": "default", "pid": child.pid, "state": "stale", "code_sha": "a" * 40},
+ {"profile": "fresh", "pid": os.getpid(), "state": "current", "code_sha": "b" * 40},
+ ]
+ with contextlib.redirect_stdout(io.StringIO()):
+ signalled = signal_stale_fleet_survivors(fleet, restart, 10.0)
+ assert child.wait(timeout=15) == 75
+ finally:
+ if child.poll() is None:
+ child.kill()
+ child.wait()
+ child.stdout.close()
+
+ assert signalled == [child.pid]
+ assert marker.exists()
+ assert restart.killed_pids == {child.pid}
+
+
+def test_verify_fleet_hands_stale_rows_to_survivor_signalling(monkeypatch):
+ """The wiring: a stale fleet matrix reaches signal_stale_fleet_survivors before exit 1."""
+ import hermes_cli.update_cmd_fleet as fleet_mod
+ 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(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(surv, "signal_stale_fleet_survivors",
+ lambda fleet, restart, budget: seen.setdefault("fleet", fleet) and [])
+ restart = _GatewayRestartOutcome(
+ incomplete=False, phase_errors=[], pre_restart_gateway_pids=[4242], restarted_services=[],
+ failed_or_stale_units=[], relaunched_profiles=[], externally_supervised_profiles=[], killed_pids=set(),
+ )
+ with contextlib.redirect_stdout(io.StringIO()), pytest.raises(SystemExit) as exc:
+ fleet_mod._verify_fleet_after_update(
+ restart, _pre_update_plan=None, _windows_gateway_resume=None, node_failures=[], update_complete=True,
+ )
+ assert exc.value.code == 1
+ assert seen["fleet"] == stale_fleet
diff --git a/website/docs/developer-guide/cron-internals.md b/website/docs/developer-guide/cron-internals.md
index 2cde109ea41..f0d212b859c 100644
--- a/website/docs/developer-guide/cron-internals.md
+++ b/website/docs/developer-guide/cron-internals.md
@@ -382,6 +382,10 @@ Cron-run sessions have the `cronjob` toolset disabled. This prevents:
The scheduler uses cross-process file-based locking (`fcntl.flock` on Unix, `msvcrt.locking` on Windows) to prevent overlapping ticks from executing the same due-job batch twice — even between the gateway's in-process ticker and a standalone `hermes cron` / manual `tick()` call. If the lock cannot be acquired, `tick()` returns 0 immediately.
+### Stale-code yield
+
+Before the tick lock, a gateway whose checkout was updated under it (boot revision ≠ disk revision) yields the tick when another process holds the gateway runtime lock — a fresher gateway's ticker dispatches instead, and the stale one must not race it with mixed `sys.modules`. The yield is raised (`CronTickYielded`) and persisted as the ticker's last error, so `hermes cron status` reports **"Gateway is running STALE code — its cron ticker yields every tick and fires NOTHING"** with both revisions and the restart command, even though the liveness heartbeat keeps refreshing. `hermes update` closes the loop: a gateway the post-update fleet version matrix proves stale is handed to the drain-first `request_restart` path (SIGUSR1) instead of being left running; a supervised gateway respawns on the new code, a bare `gateway run` is stopped and listed under "Restart manually".
+
## CLI Interface
The `hermes cron` CLI provides direct job management: