The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): count restart-wait cron exclusions per profile-scoped run
unsupportedpastels5bba024d8ddd
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..d01b801babc--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1 @@+Superfly73diff --git a/cron/scheduler.py b/cron/scheduler.pyindex b495ca0ead6..8365a8dc02e 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -631,7 +631,7 @@ _running_worker_pids: dict[tuple, int] = {}# (``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``.+# skips exactly this set — see ``get_restart_wait_cron_counts``._scope_isolated_job_ids: set = set()_running_lock = threading.Lock()@@ -704,14 +704,16 @@ def get_running_job_ids() -> "frozenset[str]":def get_running_job_details() -> list[dict]:- """Per in-flight job: ``{"job_id", "elapsed_s", "worker_pid"}`` (``worker_pid`` None for in-process- runs). The drain wait publishes this so ``hermes update`` can say WHICH job it is waiting on."""+ """Per in-flight job: ``{"job_id", "elapsed_s", "worker_pid", "restart_safe"}`` (``worker_pid``+ None for in-process runs; ``restart_safe`` True when the worker owns its own systemd scope). The+ drain wait publishes this so ``hermes update`` can say WHICH job it is waiting on."""now = time.time()with _running_lock:return [{"job_id": key[1],"elapsed_s": round(now - _running_since[key], 1) if key in _running_since else None,- "worker_pid": _running_worker_pids.get(key)}+ "worker_pid": _running_worker_pids.get(key),+ "restart_safe": key in _scope_isolated_job_ids}for key in sorted(_running_job_ids | _running_fire_owners.keys())]@@ -723,6 +725,11 @@ def get_wedged_job_ids() -> "frozenset[str]":alive (a delivery blocked on a dead transport, #115469), so the gateway restart drain reads this toskip them the way it skips wedged chat turns; restart is their remedy."""+ return frozenset(key[1] for key in _wedged_inflight_keys())+++def _wedged_inflight_keys() -> "frozenset[tuple]":+ """In-flight keys behind :func:`get_wedged_job_ids`, before the projection to bare job IDs."""now = time.time()with _running_lock:ages = {key: now - started for key, started in _running_since.items() if key in _running_job_ids}@@ -752,31 +759,37 @@ def get_wedged_job_ids() -> "frozenset[str]":if key in _running_job_ids: # released meanwhile -> don't resurrect the entry_running_allowance_s[key] = allowancereturn frozenset(- key[1] for key, age in ages.items() if age >= max(allowances[key], floor_seconds))+ key 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.+def get_restart_wait_cron_counts() -> dict:+ """In-flight cron runs split for the gateway restart wait: ``awaitable``, ``wedged`` and+ ``restart_safe`` (scoped external worker, not wedged). The three are disjoint and sum to the+ number of in-flight runs.A ``scoped`` worker runs in a transient user scope outside the gateway cgroup, so a systemdstop/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.+ by whichever gateway is live next. Holding the restart wait for it only keeps the gateway in+ ``draining`` (refusing new turns) for up to ``agent.restart_after_turn_timeout``. A ``degraded``+ worker (external subprocess, no reachable user bus) stays in the gateway cgroup and dies with a+ systemd stop, so it stays awaitable.++ Counted per in-flight KEY, not per bare job ID: one multiplexed gateway can run the same job ID+ in two profiles, and projecting to bare IDs first lets one profile's wedged or scoped run hide+ the other profile's live run, which the restart would then kill (e.g. a scoped ``daily-brief``+ in profile A next to a degraded ``daily-brief`` in profile B)."""+ wedged = _wedged_inflight_keys()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)+ inflight = _running_job_ids | _running_fire_owners.keys()+ restart_safe = (_scope_isolated_job_ids & inflight) - wedged+ wedged = wedged & inflight+ return {+ "awaitable": len(inflight - wedged - restart_safe),+ "wedged": len(wedged),+ "restart_safe": len(restart_safe),+ }def is_job_running(job_id: str, home: Optional[Union[Path, str]] = None) -> bool:diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex f61edc91840..ef0ffe2ef6c 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1531,13 +1531,21 @@ class GatewayShutdownMixin:"""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."""+ def _restart_wait_cron_counts(self) -> dict:+ """``cron.scheduler.get_restart_wait_cron_counts``, counted per profile-scoped run.++ Fail-soft toward waiting: if the split can't be read, every active cron run stays+ awaitable and nothing is excluded.+ """try:- from cron.scheduler import get_wedged_job_ids- return len(get_wedged_job_ids())+ from cron.scheduler import get_restart_wait_cron_counts+ return get_restart_wait_cron_counts()except Exception:- return 0+ return {"awaitable": self._active_cron_job_count(), "wedged": 0, "restart_safe": 0}++ def _wedged_cron_job_count(self) -> int:+ """Cron runs past ``cron.scheduler.get_wedged_job_ids``'s allowance; 0 if cron can't import."""+ return self._restart_wait_cron_counts()["wedged"]def _restart_safe_cron_count(self) -> int:"""Cron runs whose worker owns a restart-safe systemd scope; 0 if cron can't import.@@ -1550,11 +1558,7 @@ class GatewayShutdownMixin:Degraded (no user bus) workers are NOT in this set — they share the cgroup and die with asystemd 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+ return self._restart_wait_cron_counts()["restart_safe"]def _wedged_chat_agent_count(self) -> int:"""Running chat agents with no activity for ``agent.gateway_timeout`` (0 when disabled);@@ -1585,16 +1589,21 @@ class GatewayShutdownMixin:def _awaitable_work_count(self) -> int:"""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.+ Two disjoint exclusions: 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. Cron runs are counted per profile-scoped run by the scheduler, not by+ subtracting from the bare-ID active count: two profiles can run the same job ID, and one+ excluded run must not hide the other."""- return max(- 0,- self._active_work_count()- - self._wedged_agent_count()- - self._restart_safe_cron_count(),+ non_cron = (+ self._running_agent_count()+ + self._active_api_run_count()+ + self._active_deferred_agent_worker_count()+ )+ return (+ max(0, non_cron - self._wedged_chat_agent_count())+ + self._restart_wait_cron_counts()["awaitable"])def _describe_active_work(self) -> list:@@ -1625,18 +1634,13 @@ class GatewayShutdownMixin:unit["idle_s"] = summary.get("seconds_since_activity")units.append(unit)with suppress(Exception):- from cron.scheduler import (- get_restart_safe_external_job_ids,- get_running_job_details,- get_wedged_job_ids,- )+ from cron.scheduler import get_running_job_details, get_wedged_job_idswedged = 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,- "restart_safe": job["job_id"] in restart_safe})+ "restart_safe": bool(job.get("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 unitsdiff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.pyindex cfa8ef7c798..2dc555aeba6 100644--- a/tests/cron/test_restart_safe_worker.py+++ b/tests/cron/test_restart_safe_worker.py@@ -1195,7 +1195,9 @@ 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):+++def test_restart_wait_counts_exclude_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@@ -1214,20 +1216,23 @@ def test_restart_safe_external_job_ids_track_only_scoped_workers(tmp_path, monkescheduler._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"})+ assert scheduler.get_restart_wait_cron_counts() == {+ "awaitable": 1, "wedged": 0, "restart_safe": 2}+ details = {d["job_id"]: d["restart_safe"] for d in scheduler.get_running_job_details()}+ assert details == {"job-scoped": True, "job-degraded": False, "job-scoped-wedged": True}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"})+ # Wedged and scoped: counted once, as wedged.+ assert scheduler.get_restart_wait_cron_counts() == {+ "awaitable": 1, "wedged": 1, "restart_safe": 1}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_idsassert not keys & set(scheduler._running_worker_pids)diff --git a/tests/gateway/test_restart_drain.py b/tests/gateway/test_restart_drain.pyindex f89176e66ed..b6fcbd09e71 100644--- a/tests/gateway/test_restart_drain.py+++ b/tests/gateway/test_restart_drain.py@@ -658,7 +658,7 @@ async def test_request_restart_skips_wait_for_scope_isolated_cron_worker(monkeyprunner.stop.assert_awaited_once()finally:sched.release_running_job("scoped-screening-job")- assert sched.get_restart_safe_external_job_ids() == frozenset()+ assert sched.get_restart_wait_cron_counts()["restart_safe"] == 0@pytest.mark.asyncio@@ -688,3 +688,64 @@ async def test_request_restart_still_waits_for_worker_without_its_own_scope(monkawait asyncio.wait_for(runner._await_active_work_before_restart(), timeout=0.5)finally:sched.release_running_job("degraded-job")+++def _register_in_profile(monkeypatch, sched, home, job_id):+ """Claim ``job_id`` in-flight under profile ``home`` (the multiplexed ticker binds it per tick)."""+ home.mkdir(exist_ok=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ assert sched.try_register_running_job(job_id)+++def test_same_job_id_scoped_in_one_profile_does_not_hide_degraded_in_another(monkeypatch, tmp_path):+ """One gateway ticks every profile, so two profiles can run ``daily-brief`` at once.++ Profile A's run is in its own scope (outlives the restart); profile B's is degraded (shares the+ gateway cgroup, dies with a systemd stop). The wait must still hold for B: counting by bare job+ ID let A's exclusion cancel the single collapsed ``daily-brief`` and restart killed B mid-run.+ """+ import cron.scheduler as sched++ monkeypatch.setattr("cron.jobs.load_jobs", lambda: [])+ runner, _adapter = make_restart_runner()+ home_a, home_b = tmp_path / "profile-a", tmp_path / "profile-b"+ try:+ _register_in_profile(monkeypatch, sched, home_a, "daily-brief")+ sched._record_external_cron_worker("daily-brief", 4321, scope_isolated=True)+ _register_in_profile(monkeypatch, sched, home_b, "daily-brief")+ sched._record_external_cron_worker("daily-brief", 4322, scope_isolated=False)++ assert runner._restart_safe_cron_count() == 1+ assert runner._awaitable_work_count() == 1+ flags = sorted(u["restart_safe"] for u in runner._describe_active_work() if u["kind"] == "cron")+ assert flags == [False, True]++ # B finishes: only the scoped run is left, and it no longer holds the wait.+ sched.release_running_job("daily-brief", home_b)+ assert runner._awaitable_work_count() == 0+ finally:+ sched.release_running_job("daily-brief", home_a)+ sched.release_running_job("daily-brief", home_b)+++def test_same_job_id_wedged_in_one_profile_does_not_hide_live_run_in_another(monkeypatch, tmp_path):+ """Sibling of the scoped case for the wedged exclusion: profile A's ``daily-brief`` is past its+ in-flight allowance, profile B's is a young live run. Only A may be skipped.+ """+ import cron.scheduler as sched++ monkeypatch.delenv("HERMES_AGENT_TIMEOUT", raising=False)+ monkeypatch.setattr("cron.jobs.load_jobs", lambda: [])+ runner, _adapter = make_restart_runner()+ home_a, home_b = tmp_path / "profile-a", tmp_path / "profile-b"+ try:+ _register_in_profile(monkeypatch, sched, home_a, "daily-brief")+ with sched._running_lock:+ sched._running_since[sched._inflight_key("daily-brief")] = time.time() - 702 * 60+ _register_in_profile(monkeypatch, sched, home_b, "daily-brief")++ assert runner._wedged_agent_count() == 1+ assert runner._awaitable_work_count() == 1+ finally:+ sched.release_running_job("daily-brief", home_a)+ sched.release_running_job("daily-brief", home_b)