Skip to content

The agent that grows with you

fix(desktop): route the fail-open cron ticker through the shared profile gate

unsupportedpastelsd565acef9ff2
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index cf32178540f..287a341f013 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -77,6 +77,16 @@ from hermes_cli.web_server_lifecycle import ( # noqa: E402
)
+def _gateway_owns_cron(name: str, home) -> bool:
+ """A gateway already ticks this profile's store with live adapters: its OWN process, or the
+ live default multiplexer (a served satellite has no gateway.pid of its own). Winning the
+ tick-lock race here would deliver through the standalone path (#52202, #100489, #107485)."""
+ from hermes_cli.profiles import _check_gateway_running, _served_by_running_multiplexer
+
+ return _check_gateway_running(Path(home)) or (
+ name != "default" and _served_by_running_multiplexer(name))
+
+
def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60) -> None:
"""Tick the cron scheduler from inside the desktop dashboard backend.
@@ -94,14 +104,19 @@ def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60
("tasks on the sleeping profile could be idle" — community report, Aug 2026).
"""
from cron.scheduler_provider import InProcessCronScheduler, resolve_cron_scheduler
+ from hermes_constants import get_hermes_home, profile_name_for_home
provider = resolve_cron_scheduler()
+ own_home = Path(get_hermes_home())
+ own_name = profile_name_for_home(own_home) or "default"
+ # Ownership is re-checked every tick, not once at startup, so Desktop takes over when the
+ # gateway stops (#126822).
+ profile_gate = lambda name, home: not _gateway_owns_cron(name, home)
start_kwargs: dict = {"interval": interval}
if isinstance(provider, InProcessCronScheduler):
try:
- from hermes_cli.profiles import (
- _check_gateway_running, _served_by_running_multiplexer, profiles_to_serve)
+ from hermes_cli.profiles import profiles_to_serve
# Same served set as the multiplexer: default + every live profile under profiles/.
# The ticker re-enumerates this callable every cycle. Passing a
@@ -114,13 +129,7 @@ def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60
# Even one profile needs the per-tick gateway gate; otherwise
# Desktop races its dedicated gateway for the same cron store.
start_kwargs["profile_homes"] = profile_homes
- # Stand down, per tick, for a profile already owned by a gateway — its OWN
- # process, or the live default multiplexer (a served satellite has no gateway.pid
- # of its own). That gateway ticks with live adapters; winning the tick-lock race
- # here would deliver through the standalone path (#100489, #107485).
- start_kwargs["profile_gate"] = lambda name, home: not (
- _check_gateway_running(Path(home))
- or (name != "default" and _served_by_running_multiplexer(name)))
+ start_kwargs["profile_gate"] = profile_gate
from hermes_logging import enable_profile_log_routing
enable_profile_log_routing(initial_profile_homes)
@@ -132,46 +141,31 @@ def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60
except Exception:
# Fail open to the single-store ticker so the active profile keeps firing.
_log.exception("Desktop cron: profile enumeration failed; ticking active profile only")
-
- # A live gateway on THIS backend's HERMES_HOME owns cron delivery with live platform
- # adapters (#52202). The per-tick ``profile_gate`` already stands down while it runs and
- # resumes once it stops (Desktop's own gateway stop, a crash). The fail-open paths (profile
- # enumeration failure, empty served set, external provider) have no profile gate: ungated,
- # their single-store ticker would race the gateway's tick-lock, and when the desktop wins,
- # delivery has no live adapter and the cold send hangs until script_timeout. They re-check
- # the same ownership probe instead of taking it once at startup, so they also take over
- # once that gateway stops (#126822).
- if "profile_gate" not in start_kwargs:
- from hermes_constants import get_hermes_home
- from hermes_cli.profiles import _check_gateway_running
-
- own_home = Path(get_hermes_home())
- probe_failed: list = []
-
- def _gateway_owns_cron() -> bool:
+ if "profile_homes" not in start_kwargs:
+ # Fail open to this backend's own store behind the same gate. A gated-out profile is
+ # neither ticked nor heartbeated, so Desktop never marks the gateway's store healthy.
+ start_kwargs["profile_homes"] = lambda: [(own_name, own_home)]
+ start_kwargs["profile_gate"] = profile_gate
+ else:
+ # External providers take no per-tick gate: defer their start until the gateway is gone.
+ def _owned() -> bool:
try:
- return _check_gateway_running(own_home)
+ return _gateway_owns_cron(own_name, own_home)
except Exception:
- # Start the ticker rather than silently stand down; warn once, not every tick.
- if not probe_failed:
- probe_failed.append(True)
- _log.warning("Desktop cron: gateway-ownership probe failed; starting the ticker", exc_info=True)
+ # Start the ticker rather than silently stand down.
+ _log.warning("Desktop cron: gateway-ownership probe failed; starting the ticker", exc_info=True)
return False
- if isinstance(provider, InProcessCronScheduler):
- # Per-tick gate: a skipped tick leaves due jobs in place for the next allowed one.
- start_kwargs["can_dispatch"] = lambda: not _gateway_owns_cron()
- elif _gateway_owns_cron():
- # External providers take no per-tick gate: defer their start until the gateway is gone.
+ if _owned():
_log.info(
"Desktop cron scheduler waiting: live gateway owns cron on this HERMES_HOME; "
"the gateway ticks with live adapters (re-probing every %ds)", interval,
)
- while _gateway_owns_cron():
+ while True:
if stop_event.wait(interval):
return
- if stop_event.is_set():
- return # shutdown landed during the final probe
+ if not _owned():
+ break
_log.info("Desktop cron scheduler started (provider=%s, interval=%ds)", provider.name, interval)
provider.start(stop_event, **start_kwargs)
diff --git a/tests/hermes_cli/test_desktop_cron_ticker_gateway_standdown.py b/tests/hermes_cli/test_desktop_cron_ticker_gateway_standdown.py
index 9008db35807..e4887e5e76d 100644
--- a/tests/hermes_cli/test_desktop_cron_ticker_gateway_standdown.py
+++ b/tests/hermes_cli/test_desktop_cron_ticker_gateway_standdown.py
@@ -1,16 +1,14 @@
"""Desktop cron ticker yields to a live gateway that owns cron on the same HERMES_HOME (#52202).
-The multiplex path gates each tick through ``profile_gate``. The built-in fail-open paths
-(profile enumeration failure, empty served set) gate each tick through ``can_dispatch`` on
-the same ownership probe, and an external provider defers its start until the gateway is
-gone. Every path takes over once that gateway stops (#126822).
+Every built-in path (multiplex, and the fail-open single-profile fallback) gates each tick
+through ``profile_gate``; an external provider defers its start until the gateway is gone.
+Every path takes over once that gateway stops (#126822).
"""
from __future__ import annotations
import logging
import threading
-from pathlib import Path
import pytest
@@ -35,19 +33,30 @@ def ticker_env(tmp_path, monkeypatch):
return tmp_path, started
-def _set_gateway_running(monkeypatch, running: bool) -> None:
+def gateway(monkeypatch):
+ """Mutable gateway liveness; ``probes`` counts ownership checks."""
import hermes_cli.profiles as profiles
- monkeypatch.setattr(profiles, "_check_gateway_running", lambda home: running)
+ state = {"running": True, "probes": 0}
+
+ def _probe(_home):
+ state["probes"] += 1
+ return state["running"]
+
+ monkeypatch.setattr(profiles, "_check_gateway_running", _probe)
+ return state
-def test_ticker_stands_down_when_gateway_owns_cron(ticker_env, monkeypatch, caplog):
- """An external provider has no per-tick gate: its start waits out the live gateway, and
- happens once that gateway is gone instead of never (#126822)."""
+def _enumeration_fails(**_kw):
+ raise RuntimeError("enumeration failed")
+
+
+def test_external_provider_waits_while_gateway_owns_cron(ticker_env, gateway, caplog):
+ """An external provider has no per-tick gate: it is not started while the gateway owns cron."""
from hermes_cli import web_server
- home, started = ticker_env
- _set_gateway_running(monkeypatch, True)
+ _home, started = ticker_env
stopped = threading.Event()
stopped.set()
@@ -55,23 +64,35 @@ def test_ticker_stands_down_when_gateway_owns_cron(ticker_env, monkeypatch, capl
web_server._start_desktop_cron_ticker(stopped, interval=0)
assert started == {} # backend shut down while the gateway still owned cron
+ assert gateway["probes"] == 1
assert "live gateway owns cron" in caplog.text
- import hermes_cli.profiles as profiles
- probes = iter([True, True, False])
- monkeypatch.setattr(profiles, "_check_gateway_running", lambda _home: next(probes))
+def test_external_provider_starts_once_the_gateway_is_gone(ticker_env, gateway, monkeypatch):
+ """The deferred start happens once that gateway stops instead of never (#126822), with one
+ ownership probe per interval."""
+ from hermes_cli import web_server
- web_server._start_desktop_cron_ticker(threading.Event(), interval=0)
+ _home, started = ticker_env
+ stop = threading.Event()
+
+ def _interval_elapses(_timeout):
+ gateway["running"] = False # the gateway stops during the wait
+ return False
+
+ monkeypatch.setattr(stop, "wait", _interval_elapses)
- assert "kwargs" in started # the gateway stopped: Desktop takes over
+ web_server._start_desktop_cron_ticker(stop, interval=0)
+ assert "kwargs" in started
+ assert gateway["probes"] == 2 # startup probe + one re-probe after the interval
-def test_ticker_starts_when_no_gateway(ticker_env, monkeypatch):
+
+def test_ticker_starts_when_no_gateway(ticker_env, gateway):
from hermes_cli import web_server
- home, started = ticker_env
- _set_gateway_running(monkeypatch, False)
+ _home, started = ticker_env
+ gateway["running"] = False
web_server._start_desktop_cron_ticker(threading.Event(), interval=0)
@@ -81,7 +102,7 @@ def test_ticker_starts_when_no_gateway(ticker_env, monkeypatch):
def test_ticker_fails_open_when_ownership_probe_raises(ticker_env, monkeypatch, caplog):
from hermes_cli import web_server
- home, started = ticker_env
+ _home, started = ticker_env
import hermes_cli.profiles as profiles
@@ -93,11 +114,11 @@ def test_ticker_fails_open_when_ownership_probe_raises(ticker_env, monkeypatch,
with caplog.at_level(logging.WARNING, logger="hermes_cli.web_server"):
web_server._start_desktop_cron_ticker(threading.Event(), interval=0)
- assert "kwargs" in started # per-tick gating fallback, not a silent stand-down
+ assert "kwargs" in started # not a silent stand-down
assert "gateway-ownership probe failed" in caplog.text
-def test_gated_ticker_resumes_after_the_gateway_stops(ticker_env, monkeypatch):
+def test_gated_ticker_resumes_after_the_gateway_stops(ticker_env, gateway, monkeypatch):
"""A gateway live at backend start must not silence Desktop cron for good: the multiplex
ticker still starts, and its per-tick gate stands down only while that gateway runs."""
import cron.scheduler_provider as sp
@@ -111,10 +132,8 @@ def test_gated_ticker_resumes_after_the_gateway_stops(ticker_env, monkeypatch):
def start(self, stop_event, **kwargs):
started["kwargs"] = kwargs
- gateway = {"running": True}
monkeypatch.setattr(sp, "resolve_cron_scheduler", lambda: _InProcess())
monkeypatch.setattr(profiles, "profiles_to_serve", lambda **_kw: [("default", home)])
- monkeypatch.setattr(profiles, "_check_gateway_running", lambda _home: gateway["running"])
monkeypatch.setattr(hermes_logging, "enable_profile_log_routing", lambda _homes: None)
web_server._start_desktop_cron_ticker(threading.Event(), interval=0)
@@ -125,9 +144,10 @@ def test_gated_ticker_resumes_after_the_gateway_stops(ticker_env, monkeypatch):
assert gate("default", home) is True # it stopped: Desktop cron fires again
-def test_fail_open_ticker_gates_every_tick_on_the_gateway(ticker_env, monkeypatch):
- """With no profile gate (enumeration failed), the single-store ticker still starts and stands
- down per tick only while a gateway owns this home, including one that comes back."""
+def test_fail_open_ticker_uses_the_same_profile_gate(ticker_env, gateway, monkeypatch):
+ """With profile enumeration broken, the built-in ticker still ticks this backend's own store
+ through ``profile_gate``, standing down per tick only while a gateway owns it, including one
+ that comes back."""
import cron.scheduler_provider as sp
import hermes_cli.profiles as profiles
from hermes_cli import web_server
@@ -138,19 +158,82 @@ def test_fail_open_ticker_gates_every_tick_on_the_gateway(ticker_env, monkeypatc
def start(self, stop_event, **kwargs):
started["kwargs"] = kwargs
- def _enumeration_fails(**_kw):
- raise RuntimeError("enumeration failed")
-
- gateway = {"running": True}
monkeypatch.setattr(sp, "resolve_cron_scheduler", lambda: _InProcess())
monkeypatch.setattr(profiles, "profiles_to_serve", _enumeration_fails)
- monkeypatch.setattr(profiles, "_check_gateway_running", lambda _home: gateway["running"])
web_server._start_desktop_cron_ticker(threading.Event(), interval=0)
- can_dispatch = started["kwargs"]["can_dispatch"]
- assert can_dispatch() is False # the live gateway ticks with its adapters
+ kwargs = started["kwargs"]
+ assert set(kwargs) == {"interval", "profile_homes", "profile_gate"}
+ [(name, own_home)] = kwargs["profile_homes"]()
+ assert own_home == home
+ gate = kwargs["profile_gate"]
+ assert gate(name, own_home) is False # the live gateway ticks with its adapters
gateway["running"] = False
- assert can_dispatch() is True # it stopped: Desktop cron fires again
+ assert gate(name, own_home) is True # it stopped: Desktop cron fires again
gateway["running"] = True
- assert can_dispatch() is False # a returning gateway is not raced
+ assert gate(name, own_home) is False # a returning gateway is not raced
+
+
+def test_fail_open_ticker_yields_to_the_multiplexer_serving_this_profile(tmp_path, monkeypatch):
+ """A named profile served by the live default multiplexer has no gateway.pid of its own; the
+ fail-open gate must still stand down for it, as the multiplex gate does."""
+ import cron.scheduler_provider as sp
+ import hermes_cli.profiles as profiles
+ import hermes_constants
+ from hermes_cli import web_server
+
+ satellite = tmp_path / "profiles" / "worker"
+ satellite.mkdir(parents=True)
+ monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: tmp_path)
+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: satellite)
+ started = {}
+
+ class _InProcess(sp.InProcessCronScheduler):
+ def start(self, stop_event, **kwargs):
+ started["kwargs"] = kwargs
+
+ multiplexer = {"serves": True}
+ monkeypatch.setattr(sp, "resolve_cron_scheduler", lambda: _InProcess())
+ monkeypatch.setattr(profiles, "profiles_to_serve", _enumeration_fails)
+ monkeypatch.setattr(profiles, "_check_gateway_running", lambda _home: False)
+ monkeypatch.setattr(
+ profiles, "_served_by_running_multiplexer", lambda name: multiplexer["serves"] and name == "worker")
+
+ web_server._start_desktop_cron_ticker(threading.Event(), interval=0)
+
+ [(name, home)] = started["kwargs"]["profile_homes"]()
+ assert (name, home) == ("worker", satellite)
+ gate = started["kwargs"]["profile_gate"]
+ assert gate(name, home) is False
+ multiplexer["serves"] = False
+ assert gate(name, home) is True
+
+
+def test_gated_out_fail_open_tick_leaves_the_gateway_store_status_alone(tmp_path, monkeypatch):
+ """Through the real built-in loop: while the gateway owns the store, the fail-open ticker
+ neither ticks nor records a successful tick or clears the gateway's recorded tick error
+ (#32612, #32895)."""
+ import cron.jobs as jobs
+ import hermes_cli.profiles as profiles
+ import hermes_constants
+ from cron.scheduler_provider import InProcessCronScheduler
+ from hermes_cli import web_server
+
+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: tmp_path)
+ monkeypatch.setattr(profiles, "profiles_to_serve", _enumeration_fails)
+ monkeypatch.setattr(profiles, "_check_gateway_running", lambda _home: True)
+ monkeypatch.setattr("cron.scheduler_provider.resolve_cron_scheduler", InProcessCronScheduler)
+ ticked, beats, cleared = [], [], []
+ monkeypatch.setattr("cron.scheduler.tick", lambda **_kw: ticked.append(True))
+ monkeypatch.setattr(jobs, "record_ticker_heartbeat", lambda success=False: beats.append(success))
+ monkeypatch.setattr(jobs, "clear_ticker_error", lambda: cleared.append(True))
+ stop = threading.Event()
+ # One real scheduler cycle, with no wall-clock wait.
+ monkeypatch.setattr(stop, "wait", lambda _timeout: stop.set())
+
+ web_server._start_desktop_cron_ticker(stop, interval=0)
+
+ assert ticked == []
+ assert True not in beats # at most the startup liveness beat, never a success
+ assert cleared == []
diff --git a/tests/hermes_cli/test_desktop_cron_ticker_profiles.py b/tests/hermes_cli/test_desktop_cron_ticker_profiles.py
index 10a3bc63479..8725d5d02c2 100644
--- a/tests/hermes_cli/test_desktop_cron_ticker_profiles.py
+++ b/tests/hermes_cli/test_desktop_cron_ticker_profiles.py
@@ -114,9 +114,13 @@ def test_enumeration_failure_fails_open(monkeypatch, _providers):
ws._start_desktop_cron_ticker(threading.Event(), interval=11)
- # Single-store fallback (no profile_homes); its gateway gate is covered by the stand-down tests.
+ from hermes_constants import get_hermes_home
+
+ # This backend's own store only, behind the per-tick gateway gate (see the stand-down tests).
+ assert set(builtin.start_kwargs) == {"interval", "profile_homes", "profile_gate"}
assert builtin.start_kwargs["interval"] == 11
- assert "profile_homes" not in builtin.start_kwargs
+ [(_name, home)] = builtin.start_kwargs["profile_homes"]()
+ assert home == Path(get_hermes_home())
def test_external_provider_never_gets_profile_homes(monkeypatch, tmp_path):