Skip to content

The agent that grows with you

fix(gateway): gate per-profile watcher ticks on actual work in the profile's store

Andre2e6247fb3e25
diff --git a/gateway/run.py b/gateway/run.py
index 0eac13a0e5f..b4fcad130ac 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -1788,6 +1788,24 @@ async def _async_profile_runtime_scope(profile_home: "Path"):
yield
+def _profile_session_db_probe(profile_home: "Path"):
+ """The goals-cached SessionDB for *profile_home* with ONLY the HERMES_HOME contextvar
+ installed — no config parse, no secret hydration, no terminal policy. Idle-path gates
+ ("is there any work for this profile at all?") use it before paying for a full
+ ``_profile_runtime_scope`` entry on every watcher tick. None when unavailable."""
+ from hermes_cli.goals import _get_session_db
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ token = set_hermes_home_override(str(profile_home))
+ try:
+ return _get_session_db()
+ except Exception:
+ logger.debug("session-db probe failed for %s", profile_home, exc_info=True)
+ return None
+ finally:
+ reset_hermes_home_override(token)
+
+
def load_gateway_config_for_runner() -> "GatewayConfig":
"""Load gateway config for the process-level GatewayRunner. An UNSET ``multiplex_profiles`` is
settled first by ``resolve_multiplex_mode`` (the default is on; the boot guard keeps a fleet that
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index ca506335d79..390ee51ed06 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -35,6 +35,27 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
logger = logging.getLogger("gateway.run")
+async def _watcher_has_pending_handoffs(runner: object, profile_home: "Path") -> bool:
+ """Idle gate for the handoff watcher's per-profile ticks: True when the profile's store
+ holds a pending handoff — or when the probe can't prove otherwise (fail OPEN: a probe
+ error must never suppress a dispatch). The SessionDB read goes through the runner's
+ executor hop (off the loop thread); runners without one (bare test stand-ins) skip the
+ gate entirely and keep the historical always-enter behavior."""
+
+ def _probe() -> bool:
+ try:
+ from gateway.run import _profile_session_db_probe
+ db = _profile_session_db_probe(profile_home)
+ return True if db is None else db.has_pending_handoffs()
+ except Exception:
+ return True
+
+ offload = getattr(runner, "_run_in_executor_with_context", None)
+ if not callable(offload):
+ return True
+ return bool(await offload(_probe))
+
+
class GatewayAdapterLifecycleMixin:
"""Adapter lifecycle: connect/teardown, fatal recovery, reconnect watcher, multiplex profiles."""
@@ -524,6 +545,12 @@ class GatewayAdapterLifecycleMixin:
while self._running:
try:
for profile_name, profile_home in _handoff_watch_scopes(self):
+ # Idle gate: the scope entry re-parses the profile's config/secrets,
+ # so only pay it when the profile's store actually holds a pending
+ # handoff. The root poll (None) is unscoped and stays cheap.
+ if profile_home is not None and not await _watcher_has_pending_handoffs(
+ self, profile_home):
+ continue
async with _scope(profile_home):
await _tick(profile_name)
except asyncio.CancelledError:
diff --git a/gateway/run_goals.py b/gateway/run_goals.py
index 14479dd8c8b..c79c4a75414 100644
--- a/gateway/run_goals.py
+++ b/gateway/run_goals.py
@@ -24,6 +24,30 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
logger = logging.getLogger("gateway.run")
+async def _watcher_has_active_loops(runner: object, profile_home) -> bool:
+ """Idle gate for the loop wakeup watcher's per-profile scans: True when the profile's
+ store holds an ACTIVE ``loop:*`` row — or when the probe can't prove otherwise (fail
+ OPEN: a probe error must never skip a due loop). The scan's SessionDB read goes through
+ the runner's executor hop (off the loop thread, #92413); runners without one (bare test
+ stand-ins) skip the gate entirely and keep the historical always-enter behavior."""
+
+ def _probe() -> bool:
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ token = set_hermes_home_override(str(profile_home))
+ try:
+ from hermes_cli.loops import list_active_loops
+ return bool(list_active_loops())
+ except Exception:
+ return True
+ finally:
+ reset_hermes_home_override(token)
+
+ offload = getattr(runner, "_run_in_executor_with_context", None)
+ if not callable(offload):
+ return True
+ return bool(await offload(_probe))
+
+
class GatewayGoalsMixin:
"""Goal/heartbeat continuation, post-turn hooks and loop-wakeup watcher methods for GatewayRunner."""
@@ -483,6 +507,12 @@ class GatewayGoalsMixin:
while self._running:
try:
for profile_name, profile_home in _handoff_watch_scopes(self):
+ # Idle gate: the scope entry re-parses the profile's config/secrets, so
+ # only pay it when the profile's store actually holds an active loop.
+ # The root scan (None) is unscoped and stays cheap.
+ if profile_home is not None and not await _watcher_has_active_loops(
+ self, profile_home):
+ continue
async with _scope(profile_home):
await _scan_one_store(profile_name)
except Exception as exc:
diff --git a/gateway/run_heartbeat_restore.py b/gateway/run_heartbeat_restore.py
index 80d1f0949c7..fa44303ea69 100644
--- a/gateway/run_heartbeat_restore.py
+++ b/gateway/run_heartbeat_restore.py
@@ -9,21 +9,18 @@ logger = logging.getLogger("gateway.run")
def _profile_has_heartbeat_keys(profile_home) -> bool:
"""Indexed ``heartbeat:*`` probe on one profile's SessionDB — no config/secret parsing.
- Only the HERMES_HOME override (a contextvar) is installed; the expensive secret/terminal
- scopes are skipped. Fails OPEN: a probe error must not suppress the restore sweep.
+ Fails OPEN: a probe error or unavailable DB must not suppress the restore sweep.
"""
- from hermes_cli.goals import _get_session_db
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from gateway.run import _profile_session_db_probe
- token = set_hermes_home_override(str(profile_home))
+ db = _profile_session_db_probe(profile_home)
+ if db is None:
+ return True
try:
- db = _get_session_db()
- return bool(db is not None and db.list_meta_prefix("heartbeat:"))
+ return bool(db.list_meta_prefix("heartbeat:"))
except Exception:
logger.debug("heartbeat probe failed for %s; running full sweep", profile_home, exc_info=True)
return True
- finally:
- reset_hermes_home_override(token)
def _served_profile_homes(runner, default_home):
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py
index 40f75bedf4d..788003d54c5 100644
--- a/hermes_state_gateway.py
+++ b/hermes_state_gateway.py
@@ -836,6 +836,15 @@ class SessionGatewayMixin:
(session_id,),
) > 0
+ def has_pending_handoffs(self) -> bool:
+ """Cheap existence probe for the handoff watcher's idle gate. Fails OPEN: a probe
+ error answers True so a broken store never silently disables handoff dispatch."""
+ try:
+ return self._read_one(
+ "SELECT 1 AS found FROM sessions WHERE handoff_state = 'pending' LIMIT 1") is not None
+ except Exception:
+ return True
+
def complete_handoff(self, session_id: str) -> None:
"""Mark a handoff as completed."""
self._write_sql(
diff --git a/tests/gateway/test_handoff_watcher_multiprofile.py b/tests/gateway/test_handoff_watcher_multiprofile.py
index 54a1904d139..c61deb449e9 100644
--- a/tests/gateway/test_handoff_watcher_multiprofile.py
+++ b/tests/gateway/test_handoff_watcher_multiprofile.py
@@ -89,6 +89,98 @@ class _RecordingDB:
return []
+class _ProbeDB:
+ """Probe-side store stub for the idle gate (goals SessionDB cache)."""
+
+ def __init__(self, pending):
+ self._pending = pending
+
+ def has_pending_handoffs(self):
+ return self._pending
+
+
+async def test_watcher_gates_profile_scope_on_pending_handoffs(monkeypatch):
+ """Idle profiles must not pay the scope entry (config/secret re-parse) every tick.
+
+ The gate probes the profile's store off-loop; only a store WITH a pending handoff gets
+ its scope entered by the tick. Both directions are the contract: no work → no scope
+ entry; work present → scope entered and the store polled. The startup reclaim is
+ exempt (once per boot, and it must also see 'running' leftovers)."""
+ scopes = [
+ (None, None),
+ ("bala", Path("/h/profiles/bala")),
+ ("medicina", Path("/h/profiles/medicina")),
+ ]
+ monkeypatch.setattr(run, "_handoff_watch_scopes", lambda _r: scopes)
+
+ from hermes_cli import goals
+
+ entered = []
+
+ class _SpyScope:
+ def __init__(self, home):
+ self.home = home
+
+ async def __aenter__(self):
+ entered.append(self.home)
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ monkeypatch.setattr(run, "_async_profile_runtime_scope", _SpyScope)
+
+ async def _no_sleep(_seconds):
+ return None
+
+ monkeypatch.setattr(run.asyncio, "sleep", _no_sleep)
+
+ homes = [h for _n, h in scopes[1:]]
+
+ async def _run_once(pending_by_home):
+ monkeypatch.setattr(
+ goals, "_DB_CACHE",
+ {str(h): _ProbeDB(pending_by_home[h]) for h in homes})
+ entered.clear()
+ db = _RecordingDB()
+ states = iter([True, False])
+
+ class _Running:
+ def __bool__(_self):
+ try:
+ return next(states)
+ except StopIteration:
+ return False
+
+ fake = types.SimpleNamespace()
+ fake._session_db = db
+ fake._running = _Running()
+ fake._run_in_executor_with_context = asyncio.to_thread
+
+ async def _process_handoff(row, profile_name=None):
+ return None
+
+ fake._process_handoff = _process_handoff
+ coro = run.GatewayRunner._handoff_watcher(fake, interval=0.0)
+ await asyncio.wait_for(coro, timeout=5)
+ return db
+
+ # Idle: nothing pending anywhere → the tick skips both named scopes (only the
+ # startup reclaim enters them, once each); the unscoped root poll still runs.
+ db = await _run_once({h: False for h in homes})
+ assert entered == homes, (
+ f"only the startup reclaim may enter idle profile scopes; got {entered}")
+ assert db.polls == 1, "only the root store is polled when no profile has work"
+
+ # Work in one profile → the tick enters THAT profile's scope (reclaim + tick),
+ # while the still-idle profile is entered only by the reclaim.
+ db = await _run_once({homes[0]: True, homes[1]: False})
+ assert entered == [homes[0], homes[1], homes[0]], (
+ f"tick must enter exactly the profile with pending work; got {entered}")
+ assert db.polls == 2, "root + the busy profile are polled"
+
+
@pytest.mark.asyncio
async def test_watcher_enters_profile_scope_for_each_home(monkeypatch):
"""Each non-root home is polled INSIDE ``_profile_runtime_scope``.
diff --git a/tests/gateway/test_loop_command.py b/tests/gateway/test_loop_command.py
index f52a0bfb603..35da8716b2a 100644
--- a/tests/gateway/test_loop_command.py
+++ b/tests/gateway/test_loop_command.py
@@ -402,3 +402,71 @@ async def test_loop_wakeup_watcher_runs_every_sessiondb_call_off_loop_thread(loo
assert on_loop_calls == [], f"SessionDB calls ran on the event-loop thread: {on_loop_calls}"
# complete_tick ran (slash-command loops complete immediately).
assert loops.load_loop("sid-gateway-loop").ticks_fired == 1
+
+
+async def test_loop_wakeup_watcher_gates_profile_scope_on_active_loops(loop_env, monkeypatch, tmp_path):
+ """A secondary profile with no ACTIVE loop must not get its runtime scope entered on
+ every tick (each entry re-parses the profile's config/secrets — the dominant idle-CPU
+ cost on multiplex gateways); a profile holding an active loop must still be scanned."""
+ from hermes_state import SessionDB
+
+ work_home = tmp_path / "profiles" / "work"
+ work_home.mkdir(parents=True)
+ work_db = SessionDB(db_path=work_home / "state.db")
+ goals._DB_CACHE[str(work_home)] = work_db
+
+ scopes = [(None, None), ("work", work_home)]
+ monkeypatch.setattr("gateway.run._handoff_watch_scopes", lambda _r: scopes)
+
+ entered = []
+
+ class _SpyScope:
+ def __init__(self, home):
+ self.home = home
+
+ async def __aenter__(self):
+ entered.append(self.home)
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ monkeypatch.setattr("gateway.run._async_profile_runtime_scope", _SpyScope)
+
+ runner = _make_runner()
+ runner._running_agents = {}
+ runner.adapters = {}
+
+ orig_sleep = asyncio.sleep
+
+ async def _run_one_tick():
+ runner._running = True
+ calls = {"n": 0}
+
+ async def _one_pass_sleep(delay):
+ calls["n"] += 1
+ if calls["n"] >= 2: # 5s connect grace, then exactly one scan pass
+ runner._running = False
+ return await orig_sleep(0)
+
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(asyncio, "sleep", _one_pass_sleep)
+ await asyncio.wait_for(
+ GatewayRunner._loop_wakeup_watcher(runner, interval=0), timeout=5)
+
+ try:
+ # Idle: no loop rows in the work profile's store → its scope is never entered.
+ await _run_one_tick()
+ assert entered == [], f"idle profile scope must not be entered; got {entered}"
+
+ # An ACTIVE loop row in the work profile's store opens the gate.
+ await GatewayRunner._handle_loop_command(runner, _make_event("/loop 5m poll CI"))
+ raw = loops._get_session_db().get_meta("loop:sid-gateway-loop")
+ assert raw
+ work_db.set_meta("loop:sid-work-loop", raw)
+ await _run_one_tick()
+ assert entered == [work_home], (
+ f"profile with an active loop must still be scanned; got {entered}")
+ finally:
+ work_db.close()