The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): the restart drain skips a cron run wedged past its in-flight allowance
teknium169266ecb4241
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex b015f539ab1..c51d24de848 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -602,6 +602,32 @@ def get_running_job_details() -> list[dict]:]+def get_wedged_job_ids() -> "frozenset[str]":+ """In-flight job IDs older than their stale-inflight allowance (``max(2 * interval,+ cron.inflight_max_minutes)``) — the scheduler's own definition of a claim that can no longer be+ making progress. ``sweep_stale_inflight`` cannot release these while the worker thread is still+ alive (a delivery blocked on a dead transport, #115469), so the gateway restart drain reads this to+ skip them the way it skips wedged chat turns; restart is their remedy.+ """+ now = time.time()+ with _running_lock:+ ages = {jid: now - started for jid, started in _running_since.items() if jid in _running_job_ids}+ if not ages:+ return frozenset()+ floor_seconds = _inflight_min_allowance_minutes() * 60.0+ wedged = set()+ for job_id, age in ages.items():+ allowance = floor_seconds+ with contextlib.suppress(Exception):+ from cron.jobs import get_job+ interval_minutes = _job_interval_minutes(get_job(job_id) or {})+ if interval_minutes:+ allowance = max(allowance, 2.0 * interval_minutes * 60.0)+ if age >= allowance:+ wedged.add(job_id)+ return frozenset(wedged)++def try_register_running_job(job_id: str) -> bool:"""Atomically add ``job_id`` to the in-flight set; False (caller must skip) if already mid-run.Single dedupe owner for ticker + manual runs (the fire claim's 300s TTL is outlived by realdiff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex 58e20a4edf1..a4f8bca84fc 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1448,9 +1448,23 @@ class GatewayShutdownMixin:)def _wedged_agent_count(self) -> int:- """Running chat agents with no activity for ``agent.gateway_timeout`` (0 when disabled).+ """Work units the restart wait may skip: chat agents idle past ``agent.gateway_timeout`` and+ cron runs older than the scheduler's stale-inflight allowance (#115469).- Cron/API work has no activity clock and pending sentinels are brand-new, so neither counts;+ API work has no activity clock and pending sentinels are brand-new, so neither counts.+ """+ return self._wedged_chat_agent_count() + self._wedged_cron_job_count()++ def _wedged_cron_job_count(self) -> int:+ """Cron runs past ``cron.scheduler.get_wedged_job_ids``'s allowance; 0 if cron can't import."""+ try:+ from cron.scheduler import get_wedged_job_ids+ return len(get_wedged_job_ids())+ except Exception:+ return 0++ def _wedged_chat_agent_count(self) -> int:+ """Running chat agents with no activity for ``agent.gateway_timeout`` (0 when disabled);an unreadable activity summary means "not wedged"."""from gateway.run import _AGENT_PENDING_SENTINEL, _float_env@@ -1507,10 +1521,12 @@ class GatewayShutdownMixin:unit["idle_s"] = summary.get("seconds_since_activity")units.append(unit)with suppress(Exception):- from cron.scheduler import get_running_job_details+ from cron.scheduler import get_running_job_details, get_wedged_job_ids+ wedged = get_wedged_job_ids()for job in get_running_job_details():units.append({"kind": "cron", "job_id": job["job_id"], "elapsed_s": job["elapsed_s"],- "pid": job["worker_pid"] or os.getpid(), "external": bool(job["worker_pid"])})+ "pid": job["worker_pid"] or os.getpid(), "external": bool(job["worker_pid"]),+ "wedged": job["job_id"] in wedged})for kind, count in (("api", self._active_api_run_count()), ("deferred", self._active_deferred_agent_worker_count())):units.extend({"kind": kind, "pid": os.getpid()} for _ in range(count))return unitsdiff --git a/tests/gateway/test_restart_drain.py b/tests/gateway/test_restart_drain.pyindex 765badb4b96..e1fc0ae9136 100644--- a/tests/gateway/test_restart_drain.py+++ b/tests/gateway/test_restart_drain.py@@ -1,6 +1,7 @@import asyncioimport shutilimport subprocess+import timefrom datetime import datetimefrom unittest.mock import AsyncMock, MagicMock@@ -513,3 +514,54 @@ def test_wedged_agent_count_ignores_sentinels_and_bad_summaries(monkeypatch):})assert runner._wedged_agent_count() == 1+++async def test_request_restart_skips_wait_for_cron_run_past_inflight_allowance(monkeypatch, tmp_path):+ """A cron run older than the scheduler's stale-inflight allowance is wedged: the restart proceeds.++ #115469 Defect B: a no-agent job whose delivery hung pinned ``hermes update`` in "draining" for the+ full ``restart_after_turn_timeout`` because ``_wedged_agent_count`` only ever looked at chat agents,+ so the cron unit was structurally un-skippable ("0 wedged and excluded").+ """+ import cron.scheduler as sched++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.delenv("HERMES_AGENT_TIMEOUT", raising=False)+ monkeypatch.setattr("cron.jobs.get_job", lambda job_id: None)+ runner, _adapter = make_restart_runner()+ runner.stop = AsyncMock()+ runner._restart_after_turn_timeout = 300.0 # would hang the test without the wedge bypass+ assert sched.try_register_running_job("hung-delivery-job")+ try:+ with sched._running_lock:+ sched._running_since["hung-delivery-job"] = time.time() - 702 * 60+ assert runner._wedged_agent_count() == 1 and runner._awaitable_work_count() == 0+ cron_units = [u for u in runner._describe_active_work() if u["kind"] == "cron"]+ assert cron_units[0]["job_id"] == "hung-delivery-job" and cron_units[0]["wedged"] is True++ assert runner.request_restart(detached=False, via_service=True) is True+ await asyncio.wait_for(runner._restart_task, timeout=5.0)+ runner.stop.assert_awaited_once()+ finally:+ sched.release_running_job("hung-delivery-job")+++def test_wedged_cron_allowance_honours_young_runs_and_job_interval(monkeypatch, tmp_path):+ """Control: a run inside ``max(2 * interval, cron.inflight_max_minutes)`` is live work, not wedged."""+ import cron.scheduler as sched++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr("cron.jobs.get_job", lambda job_id: {"id": job_id, "schedule": {"kind": "interval", "minutes": 360}})+ runner, _adapter = make_restart_runner()+ assert sched.try_register_running_job("six-hourly-job")+ try:+ assert runner._wedged_agent_count() == 0 and runner._awaitable_work_count() == 1+ with sched._running_lock:+ sched._running_since["six-hourly-job"] = time.time() - 11 * 3600 # past the 30m floor, inside 2 * 6h+ assert runner._wedged_agent_count() == 0+ with sched._running_lock:+ sched._running_since["six-hourly-job"] = time.time() - 13 * 3600+ assert runner._wedged_agent_count() == 1 and runner._awaitable_work_count() == 0+ finally:+ sched.release_running_job("six-hourly-job")diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex 86420bf94ae..e139618b18b 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -58,6 +58,8 @@ The restart is drain-first: the running gateway refuses new turns, then waits foChat turns show their session key, model and current tool; cron jobs show the job id, name and the process running them (an external restart-safe worker on systemd installs, otherwise the gateway itself). `hermes gateway status` lists the same units while the gateway is draining. To stop waiting, finish or kill the listed work, or lower `agent.restart_after_turn_timeout` in `config.yaml` (`0` enters the forced drain immediately).+Wedged work does not hold the restart: a chat turn idle past `agent.gateway_timeout`, or a cron run older than the scheduler's in-flight allowance (`max(2 × the job's interval, cron.inflight_max_minutes)`, 30 minutes by default), is excluded from the wait and interrupted by the restart instead.+### Missing Windows updater filesIf the maintained updater script is missing (for example after antivirus quarantine), the legacy update forwarder fails instead of reporting a successful hand-off. Repair the installation and review the security software's quarantine report before retrying; do not disable antivirus protection. Before reporting success, the maintained updater checks the CLI import, Windows executable header, ASAR header and packaged main entry, readable renderer HTML with a local module entry, initial module files, and current build stamp. These are minimum artifact checks, not a full dependency audit or an application/backend launch test. Missing Python is reported before waiting for Desktop shutdown; dependency repair is still allowed to run as part of the update. Electron checks maintained handoff prerequisites before stopping backends when that layout is present; genuine legacy-flat updater layouts remain supported, so not every missing updater file is detected before backend shutdown.