The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): skip cron runs in their own restart-safe scope in the restart wait
Superfly73336b557bec9b
diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 8fefa9aa667..558add85e2d 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -1237,6 +1237,8 @@ agent:# begins. /restart and SIGUSR1 refuse new work, then wait up to this cap for# in-flight agent, cron and API runs to complete so the requesting turn is# not cut off by restart_drain_timeout. 0 = enter stop()/drain immediately.+ # Excluded from the wait: wedged runs, and cron runs already handed to a+ # worker in its own restart-safe systemd scope (they outlive the restart).# The default (30 min) is a safety valve for wedged agents, not a target# latency; raise it for long unattended turns. Env: HERMES_RESTART_AFTER_TURN_TIMEOUT.# restart_after_turn_timeout: 1800diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 3deb53e654e..b495ca0ead6 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -627,6 +627,12 @@ _restart_safe_waiter_job_ids: set = set()# in-flight key -> pid of the restart-safe external worker executing it (absent for in-process# runs), so a drain observer can name the process holding the gateway open._running_worker_pids: dict[tuple, int] = {}+# In-flight keys whose external worker runs in its OWN transient systemd scope+# (``GatewayChildDispatch.mode == "scoped"``). Only that worker outlives a gateway restart: a+# systemd stop kills the service cgroup, so a ``degraded`` direct subprocess (no reachable user+# bus) dies with the gateway even though it is external. The gateway's restart after-turn wait+# skips exactly this set — see ``get_restart_safe_external_job_ids``.+_scope_isolated_job_ids: set = set()_running_lock = threading.Lock()# Per in-flight id: time.time() claim instant + the future owning its release (``_FUTURE_PENDING``@@ -749,6 +755,30 @@ def get_wedged_job_ids() -> "frozenset[str]":key[1] for key, age in ages.items() if age >= max(allowances[key], floor_seconds))+def get_restart_safe_external_job_ids() -> "frozenset[str]":+ """In-flight job IDs executing in a restart-safe external worker of its OWN systemd scope.++ A ``scoped`` worker runs in a transient user scope outside the gateway cgroup, so a systemd+ stop/restart cannot reach it: the shutdown drain deliberately leaves it unmarked+ (``mark_running_jobs_interrupted``) and its final send rides the durable delivery queue, drained+ by whichever gateway is live next. The gateway restart after-turn wait reads this to skip those+ runs — holding for work that provably outlives the process only keeps the gateway in+ ``draining`` (refusing new turns) for up to ``agent.restart_after_turn_timeout`` while the+ worker keeps going regardless.++ A ``degraded`` worker (external subprocess, no reachable user bus) is deliberately NOT listed:+ it stays in the gateway cgroup and dies with a systemd stop, so the wait must still hold for it.+ Runs already reported as wedged by :func:`get_wedged_job_ids` are excluded here as well — the+ gateway subtracts both counts, and a run in both sets would be subtracted twice.+ """+ with _running_lock:+ keys = set(_scope_isolated_job_ids)+ if not keys:+ return frozenset()+ wedged = get_wedged_job_ids()+ return frozenset(key[1] for key in keys if key[1] not in wedged)++def is_job_running(job_id: str, home: Optional[Union[Path, str]] = None) -> bool:"""True when THIS process has an in-flight run of ``job_id`` FOR ``home`` (default: the activecron scope's home).@@ -763,6 +793,24 @@ def is_job_running(job_id: str, home: Optional[Union[Path, str]] = None) -> boolreturn key in _running_job_ids or key in _running_fire_owners+def _record_external_cron_worker(job_id: str, pid: Any, *, scope_isolated: bool) -> None:+ """Record the external worker holding *job_id* so a drain observer can name it, and whether+ its scope isolates it from this process.++ ``scope_isolated`` is the strong form of restart-safety: only a ``scoped`` dispatch+ (``GatewayChildDispatch``) puts the worker in its own transient systemd scope, outside the+ gateway cgroup. A ``degraded`` worker is still external but shares the cgroup and dies with a+ systemd stop, so it must NOT be listed as restart-safe. Called once per accepted handoff;+ both maps are cleared by ``release_running_job`` and by the worker waiter's ``finally``.+ """+ key = _inflight_key(job_id)+ with _running_lock:+ with contextlib.suppress(TypeError, ValueError):+ _running_worker_pids[key] = int(pid)+ if scope_isolated:+ _scope_isolated_job_ids.add(key)++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 real@@ -805,6 +853,7 @@ def release_running_job(job_id: str, home: Optional[Union[Path, str]] = None) ->_running_allowance_s.pop(key, None)_running_futures.pop(key, None)_running_worker_pids.pop(key, None)+ _scope_isolated_job_ids.discard(key)def _inflight_min_allowance_minutes() -> float:@@ -3536,8 +3585,10 @@ def _wait_for_external_cron_worker(raise _ExternalWorkerPostHandoffError(str(wait_error)) from wait_errorfinally:if job_id is not None:+ _key = _inflight_key(job_id)with _running_lock:- _restart_safe_waiter_job_ids.discard(_inflight_key(job_id))+ _restart_safe_waiter_job_ids.discard(_key)+ _scope_isolated_job_ids.discard(_key)# The execution is terminal or its worker is dead: nobody will read a# payload or acknowledgement left behind by a late/unread handoff.for stale in handoff_files:@@ -3731,14 +3782,17 @@ def _launch_external_cron_worker(job: dict) -> bool:stderr_path=stderr_path,)logger.info(- "Cron job '%s' handed to restart-safe worker pid=%s execution=%s",+ "Cron job '%s' handed to restart-safe worker pid=%s execution=%s dispatch=%s",job_id,acknowledgement.get("pid"),execution_id,+ dispatch.mode,+ )+ _record_external_cron_worker(+ job_id,+ acknowledgement.get("pid") or process.pid,+ scope_isolated=dispatch.mode == "scoped",)- with _running_lock, contextlib.suppress(TypeError, ValueError):- _running_worker_pids[_inflight_key(job_id)] = int(- acknowledgement.get("pid") or process.pid)return _wait_for_external_cron_worker(process,execution_id=execution_id,diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex 04f83b100c2..f61edc91840 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1539,6 +1539,23 @@ class GatewayShutdownMixin:except Exception:return 0+ def _restart_safe_cron_count(self) -> int:+ """Cron runs whose worker owns a restart-safe systemd scope; 0 if cron can't import.++ Such a worker runs outside the gateway cgroup, so neither the tool-process sweep nor+ ``mark_running_jobs_interrupted`` reaches it, and its final send rides the durable delivery+ queue for whichever gateway is live next. The restart after-turn wait must therefore not+ hold the gateway in ``draining`` for it: waiting buys the run nothing and refuses new turns+ for up to the whole cap (observed live: a 100-minute job held the gateway ~30 minutes).+ Degraded (no user bus) workers are NOT in this set — they share the cgroup and die with a+ systemd stop, so they keep holding the wait.+ """+ try:+ from cron.scheduler import get_restart_safe_external_job_ids+ return len(get_restart_safe_external_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".@@ -1566,8 +1583,19 @@ class GatewayShutdownMixin:)def _awaitable_work_count(self) -> int:- """Active work minus wedged turns — what the restart wait waits on."""- return max(0, self._active_work_count() - self._wedged_agent_count())+ """Active work minus the units the restart wait must not hold for.++ Two disjoint exclusions, both subtracted here so a unit in both sets is never dropped+ twice: wedged turns (idle past ``agent.gateway_timeout`` / past the cron in-flight+ allowance — restart is their remedy, #115469) and cron runs executing in a restart-safe+ external worker (``_restart_safe_cron_count``), which outlives this process either way.+ """+ return max(+ 0,+ self._active_work_count()+ - self._wedged_agent_count()+ - self._restart_safe_cron_count(),+ )def _describe_active_work(self) -> list:"""One dict per in-flight work unit the restart wait is holding for, so an observer@@ -1597,12 +1625,18 @@ class GatewayShutdownMixin:unit["idle_s"] = summary.get("seconds_since_activity")units.append(unit)with suppress(Exception):- from cron.scheduler import get_running_job_details, get_wedged_job_ids+ from cron.scheduler import (+ get_restart_safe_external_job_ids,+ get_running_job_details,+ get_wedged_job_ids,+ )wedged = get_wedged_job_ids()+ restart_safe = get_restart_safe_external_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"]),- "wedged": job["job_id"] in wedged})+ "wedged": job["job_id"] in wedged,+ "restart_safe": job["job_id"] in restart_safe})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 units@@ -1618,9 +1652,11 @@ class GatewayShutdownMixin:return Trueif self._awaitable_work_count() <= 0:logger.warning(- "Restart requested with %d active work unit(s), all wedged "- "past the inactivity timeout; skipping the after-turn wait "- "and proceeding to stop()/drain which will interrupt them", active,+ "Restart requested with %d active work unit(s), none awaitable "+ "(%d wedged past the inactivity timeout, %d in restart-safe external cron "+ "workers that outlive this process); skipping the after-turn wait and "+ "proceeding to stop()/drain", active,+ self._wedged_agent_count(), self._restart_safe_cron_count(),)return Falsetimeout = float(getattr(self, "_restart_after_turn_timeout", 0.0) or 0.0)@@ -1651,8 +1687,10 @@ class GatewayShutdownMixin:if (now - last_status_at) >= 30.0:logger.info("Restart deferred: waiting on %d active work unit(s) "- "(%d wedged and excluded; %.0fs remaining before force drain): %s",- self._awaitable_work_count(), self._wedged_agent_count(), deadline - now,+ "(%d wedged and excluded, %d restart-safe and excluded; "+ "%.0fs remaining before force drain): %s",+ self._awaitable_work_count(), self._wedged_agent_count(),+ self._restart_safe_cron_count(), deadline - now,self._describe_active_work(),)self._scale_to_zero_status("draining", "restart wait: status mark failed")@@ -1660,8 +1698,10 @@ class GatewayShutdownMixin:await asyncio.sleep(0.1)if self._active_work_count() > 0:logger.warning(- "Restart deferred wait: %d wedged work unit(s) remain; "- "proceeding to stop()/drain which will interrupt them", self._active_work_count(),+ "Restart deferred wait: %d excluded work unit(s) remain "+ "(%d wedged, %d restart-safe external cron); proceeding to stop()/drain",+ self._active_work_count(), self._wedged_agent_count(),+ self._restart_safe_cron_count(),)return Falselogger.info("Restart deferred wait complete — active work drained; proceeding to stop()")diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.pyindex c61eb0233ab..cfa8ef7c798 100644--- a/tests/cron/test_restart_safe_worker.py+++ b/tests/cron/test_restart_safe_worker.py@@ -1195,3 +1195,39 @@ def test_post_handoff_waiter_failure_records_bookkeeping_without_alert(assert len(marks) == 1 and marks[0][0][1] is Falseassert marks[0][0][2].startswith("Restart-safe cron worker failed after handoff: ")assert execution_ledger.get_execution(record["id"])["status"] == "failed"+def test_restart_safe_external_job_ids_track_only_scoped_workers(tmp_path, monkeypatch):+ """Only a worker in its OWN scope may be skipped by the gateway restart wait.++ A ``degraded`` dispatch is still an external subprocess but stays in the gateway cgroup, so a+ systemd stop kills it mid-run and the restart wait must keep holding for it. A run the scheduler+ already reports as wedged is excluded too: the gateway subtracts both counts, and a run in both+ sets would be subtracted twice.+ """+ import cron.scheduler as scheduler++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr("cron.jobs.load_jobs", lambda: [])+ jobs = ("job-scoped", "job-degraded", "job-scoped-wedged")+ for job_id in jobs:+ assert scheduler.try_register_running_job(job_id)+ try:+ scheduler._record_external_cron_worker("job-scoped", 4321, scope_isolated=True)+ scheduler._record_external_cron_worker("job-degraded", 4322, scope_isolated=False)+ scheduler._record_external_cron_worker("job-scoped-wedged", 4323, scope_isolated=True)+ assert scheduler.get_restart_safe_external_job_ids() == frozenset(+ {"job-scoped", "job-scoped-wedged"})++ with scheduler._running_lock:+ scheduler._running_since[scheduler._inflight_key("job-scoped-wedged")] = (+ time.time() - 702 * 60)+ assert scheduler.get_wedged_job_ids() == frozenset({"job-scoped-wedged"})+ assert scheduler.get_restart_safe_external_job_ids() == frozenset({"job-scoped"})+ finally:+ for job_id in jobs:+ scheduler.release_running_job(job_id)+ # Scoped to THIS test's claims: the module keeps other runs' entries (a launch that never went+ # through a claim, e.g. a stubbed worker in a sibling test, is not this test's to assert on).+ keys = {scheduler._inflight_key(job_id) for job_id in jobs}+ assert scheduler.get_restart_safe_external_job_ids() == frozenset()+ assert not keys & scheduler._scope_isolated_job_ids+ assert not keys & set(scheduler._running_worker_pids)diff --git a/tests/gateway/test_restart_drain.py b/tests/gateway/test_restart_drain.pyindex 6d2b28cb156..f89176e66ed 100644--- a/tests/gateway/test_restart_drain.py+++ b/tests/gateway/test_restart_drain.py@@ -623,3 +623,68 @@ def test_wedged_cron_check_parses_jobs_once_per_run(monkeypatch, tmp_path):for jid in ("job-a", "job-b", "job-c"):sched.release_running_job(jid)assert not sched._running_allowance_s+++async def test_request_restart_skips_wait_for_scope_isolated_cron_worker(monkeypatch, tmp_path):+ """A cron run in its own restart-safe systemd scope outlives the restart: the wait must skip it.++ Its worker lives outside the gateway cgroup, so the shutdown drain deliberately leaves it+ unmarked (``mark_running_jobs_interrupted``) and its final send rides the durable delivery queue+ for the next gateway. Holding the after-turn wait for it therefore only kept the gateway in+ "draining" — refusing new turns for up to the whole ``agent.restart_after_turn_timeout`` — while+ the worker kept running (observed live: a 100-minute job held the gateway ~30 minutes).+ """+ import cron.scheduler as sched++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr("cron.jobs.load_jobs", lambda: [])+ runner, _adapter = make_restart_runner()+ runner.stop = AsyncMock()+ runner._restart_after_turn_timeout = 300.0 # would hang the test without the scope bypass+ assert sched.try_register_running_job("scoped-screening-job")+ try:+ sched._record_external_cron_worker("scoped-screening-job", 4321, scope_isolated=True)+ # Counted as work (the drain still sees it), but not awaited.+ assert runner._active_work_count() == 1+ assert runner._restart_safe_cron_count() == 1+ assert 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"] == "scoped-screening-job"+ assert cron_units[0]["external"] is True and cron_units[0]["restart_safe"] 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("scoped-screening-job")+ assert sched.get_restart_safe_external_job_ids() == frozenset()+++async def test_request_restart_still_waits_for_worker_without_its_own_scope(monkeypatch, tmp_path):+ """Control: an external worker WITHOUT its own scope dies with the gateway, so the wait holds.++ A ``degraded`` dispatch (no reachable user D-Bus) is still an external subprocess but stays in+ the gateway cgroup — a systemd stop kills it mid-run. The fix must not degrade into "never wait+ for a cron worker".+ """+ import cron.scheduler as sched++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr("cron.jobs.load_jobs", lambda: [])+ runner, _adapter = make_restart_runner()+ runner._restart_after_turn_timeout = 300.0+ runner._scale_to_zero_status = MagicMock()+ assert sched.try_register_running_job("degraded-job")+ try:+ sched._record_external_cron_worker("degraded-job", 4322, scope_isolated=False)+ assert runner._restart_safe_cron_count() == 0+ assert runner._awaitable_work_count() == 1+ cron_units = [u for u in runner._describe_active_work() if u["kind"] == "cron"]+ assert cron_units[0]["external"] is True and cron_units[0]["restart_safe"] is False+ # Still awaited: the wait does not return while this run is in flight.+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(runner._await_active_work_before_restart(), timeout=0.5)+ finally:+ sched.release_running_job("degraded-job")diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex cbd089c531b..26690d8f633 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -158,6 +158,8 @@ Chat turns show their session key, model and current tool; cron jobs show the joWedged 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.+Work that outlives the gateway does not hold the restart either: a cron run already handed to a worker in its own systemd scope (`systemd-run --user --scope`, the normal case on a systemd install) keeps running when the gateway stops, and its result is delivered from the durable queue by whichever gateway comes up next — so the restart proceeds instead of waiting up to the full cap. A worker that could not get its own scope (no reachable user D-Bus session, see `cron.require_restart_safe_scope`) stays in the gateway's cgroup and is still awaited, because the restart would kill it mid-run.+### 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.