The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): keep profile scope on the standalone fallback pool; desktop ticker stands down for profiles with their own gateway (#100489)
Teknium62a4599f89da
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex d356f815064..d9c72663cc7 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -4005,7 +4005,19 @@ def _deliver_result(job: dict, content: str, adapters=None, loop=None) -> Optiontry:pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)try:- future = pool.submit(asyncio.run, _send_to_platform(platform, pconfig, chat_id, cleaned_delivery_content, thread_id=thread_id, media_files=media_files))+ # The fallback worker is a fresh thread: it does NOT+ # inherit the multiplexed profile ContextVars (home+ # override + secret scope). Run inside a copy of the+ # active context so the standalone sender reads THIS+ # profile's bot token, not the process default's+ # (#100489) — same pattern as the session-db and+ # heartbeat workers in this module.+ _fallback_context = contextvars.copy_context()+ future = pool.submit(+ _fallback_context.run,+ asyncio.run,+ _send_to_platform(platform, pconfig, chat_id, cleaned_delivery_content, thread_id=thread_id, media_files=media_files),+ )result = future.result(timeout=30)finally:pool.shutdown(wait=False)diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.pyindex b6d43d75457..84e51e9824c 100644--- a/cron/scheduler_provider.py+++ b/cron/scheduler_provider.py@@ -560,6 +560,7 @@ class InProcessCronScheduler(CronScheduler):profile_homes=None,profile_adapters=None,default_profile=None,+ profile_gate=None,):import loggingfrom cron.scheduler import CronTickYielded@@ -590,6 +591,7 @@ class InProcessCronScheduler(CronScheduler):can_dispatch=can_dispatch,profile_adapters=profile_adapters,default_profile=default_profile,+ profile_gate=profile_gate,)return@@ -670,6 +672,7 @@ class InProcessCronScheduler(CronScheduler):can_dispatch=None,profile_adapters=None,default_profile=None,+ profile_gate=None,):"""Tick every served profile's cron store when multiplex_profiles is on.@@ -678,6 +681,11 @@ class InProcessCronScheduler(CronScheduler):agent execution to that profile's home — mirroring how``_profile_runtime_scope`` scopes the multiplexed inbound path and``web_server.py`` scopes per-profile cron API calls.++ ``profile_gate(name, home) -> bool``, when given, is consulted every+ cycle; a profile it rejects is neither ticked nor heartbeated that+ cycle (the desktop ticker uses it to stand down for profiles whose+ own gateway is running, #100489)."""import loggingfrom cron.scheduler import tick as cron_tick@@ -734,11 +742,21 @@ class InProcessCronScheduler(CronScheduler):# Worst per-profile failure this cycle (fd exhaustion wins) so the# #87644 backoff/reclaim is applied once per cycle, not per profile._cycle_exc: BaseException | None = None+ cycle_homes = _existing_profile_homes(profile_homes)+ if profile_gate is not None:+ cycle_homes = [+ entry+ for entry in cycle_homes+ if profile_gate(+ entry[0] if isinstance(entry, tuple) else None,+ entry[1] if isinstance(entry, tuple) else entry,+ )+ ]try:if can_dispatch is not None and not can_dispatch():logger.debug("Cron dispatch paused while gateway drains existing work")else:- for entry in _existing_profile_homes(profile_homes):+ for entry in cycle_homes:_pname = entry[0] if isinstance(entry, tuple) else Nonehome = entry[1] if isinstance(entry, tuple) else entryhome_token = set_hermes_home_override(str(home))@@ -803,7 +821,7 @@ class InProcessCronScheduler(CronScheduler):# beat reflects its own outcome, so a yielding profile does not# darken healthy siblings — from an aborted one (exception), where# no profile completed and all beats are unsuccessful (#32612).- for entry in _existing_profile_homes(profile_homes):+ for entry in cycle_homes:home = entry[1] if isinstance(entry, tuple) else entryhome_token = set_hermes_home_override(str(home))try:diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 1a1344c364b..b78cb5fc607 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -303,6 +303,17 @@ def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60profile_homes = list(profiles_to_serve(multiplex=True))if len(profile_homes) > 1:start_kwargs["profile_homes"] = profile_homes+ # Stand down, per tick, for any profile whose OWN gateway is+ # running: that gateway ticks it with live adapters, and the+ # tick-lock race otherwise lets this adapter-less ticker win+ # and deliver the job through the standalone path (#100489).+ # Evaluated every cycle so a gateway starting/stopping later+ # is picked up without a dashboard restart.+ from hermes_cli.profiles import _check_gateway_running++ start_kwargs["profile_gate"] = (+ lambda _name, home: not _check_gateway_running(Path(home))+ )from hermes_logging import enable_profile_log_routingenable_profile_log_routing(profile_homes)diff --git a/tests/cron/test_cron_multiplex_desktop_ticker_scope.py b/tests/cron/test_cron_multiplex_desktop_ticker_scope.pynew file mode 100644index 00000000000..a01aa0ae3cd--- /dev/null+++ b/tests/cron/test_cron_multiplex_desktop_ticker_scope.py@@ -0,0 +1,139 @@+"""Regression tests for #100489 — desktop multiplex ticker must not deliver a+secondary profile's cron output through the default profile's identity.++Two halves:++1. ``_deliver_result``'s standalone fallback pool (taken when the caller has a+ RUNNING event loop — the desktop dashboard shape) spawns a fresh thread that+ did not inherit the profile ContextVars; it must run inside a copy of the+ active context so the sender reads THIS profile's home + secrets.+2. The desktop ticker must stand down, per tick, for a profile whose OWN+ gateway is running — that gateway ticks it with live adapters, and racing it+ on the tick lock lets the adapter-less desktop ticker deliver standalone.+"""+import asyncio+import threading+from unittest.mock import patch++++def test_standalone_fallback_pool_keeps_profile_scope(tmp_path, monkeypatch):+ from agent.secret_scope import (+ get_secret,+ set_multiplex_active,+ set_secret_scope,+ )+ from hermes_constants import get_hermes_home, set_hermes_home_override+ import cron.scheduler as sched+ import tools.send_message_tool as smt++ default_home = tmp_path / "default"+ sec_home = tmp_path / "profiles" / "ops"+ for home in (default_home, sec_home):+ (home / "cron").mkdir(parents=True)+ (home / "config.yaml").write_text("platforms:\n telegram:\n enabled: true\n")+ monkeypatch.setenv("HERMES_HOME", str(default_home))+ monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "DEFAULT-TOKEN")+ set_multiplex_active(True)++ seen = {}++ async def fake_send(platform, pconfig, chat_id, message, **kwargs):+ seen["home"] = str(get_hermes_home())+ seen["token"] = get_secret("TELEGRAM_BOT_TOKEN", None)+ return {"success": True, "message_id": "1"}++ job = {"id": "j1", "name": "probe", "deliver": "telegram:12345", "schedule": {"kind": "cron"}}++ async def _inside_running_loop():+ # Emulate the multiplex ticker's per-profile scope on the caller.+ set_hermes_home_override(str(sec_home))+ set_secret_scope({"TELEGRAM_BOT_TOKEN": "OPS-TOKEN"})+ return sched._deliver_result(job, "hello", adapters={}, loop=None)++ try:+ with patch.object(smt, "_send_to_platform", fake_send):+ err = asyncio.run(_inside_running_loop())+ finally:+ set_multiplex_active(False)++ assert err is None, err+ assert seen["home"] == str(sec_home.resolve())+ assert seen["token"] == "OPS-TOKEN"+++def test_multiplex_ticker_profile_gate_skips_rejected_profile(tmp_path):+ from cron.scheduler_provider import InProcessCronScheduler+ from hermes_constants import get_hermes_home++ own_gateway = tmp_path / "own-gateway"+ orphan = tmp_path / "orphan"+ for home in (own_gateway, orphan):+ (home / "cron").mkdir(parents=True)++ stop = threading.Event()+ ticked: list[str] = []++ def _tick(*args, **kwargs):+ ticked.append(str(get_hermes_home()))+ if len(ticked) >= 3:+ stop.set()+ return 0++ provider = InProcessCronScheduler()+ with patch("cron.scheduler.tick", side_effect=_tick):+ thread = threading.Thread(+ target=provider.start,+ args=(stop,),+ kwargs={+ "interval": 0,+ "profile_homes": [("own-gateway", own_gateway), ("orphan", orphan)],+ "profile_gate": lambda name, home: name != "own-gateway",+ },+ daemon=True,+ )+ thread.start()+ thread.join(timeout=5)+ stop.set()+ thread.join(timeout=5)++ assert not thread.is_alive()+ assert set(ticked) == {str(orphan)}+ # The gated profile gets no tick-loop success marker either: its own+ # gateway owns that status surface.+ assert not (own_gateway / "cron" / "ticker_last_success").exists()+ assert (orphan / "cron" / "ticker_last_success").exists()+++def test_desktop_ticker_gates_on_profile_gateway_running(tmp_path, monkeypatch):+ """The desktop ticker wires the gate to ``_check_gateway_running``."""+ from hermes_cli import web_server++ homes = [("default", tmp_path / "default"), ("ops", tmp_path / "ops")]+ monkeypatch.setattr(+ "hermes_cli.profiles.profiles_to_serve", lambda multiplex=False: list(homes)+ )+ monkeypatch.setattr(+ "hermes_cli.profiles._check_gateway_running", lambda home: home.name == "ops"+ )+ captured = {}++ class _Provider:+ name = "fake"++ def start(self, stop_event, **kwargs):+ captured.update(kwargs)++ from cron import scheduler_provider as sp++ monkeypatch.setattr(web_server, "resolve_cron_scheduler", lambda: _Provider(), raising=False)+ monkeypatch.setattr(sp, "resolve_cron_scheduler", lambda: _Provider())+ monkeypatch.setattr(sp, "InProcessCronScheduler", _Provider)+ monkeypatch.setattr("hermes_logging.enable_profile_log_routing", lambda homes: None)++ web_server._start_desktop_cron_ticker(threading.Event(), interval=0)++ gate = captured.get("profile_gate")+ assert gate is not None, "desktop ticker did not install a profile gate"+ assert gate("default", tmp_path / "default") is True+ assert gate("ops", tmp_path / "ops") is False