Skip to content

The agent that grows with you

fix(gateway): keep a reconnecting satellite off the primary bot

unsupportedpastelsf18ef0a15c1d
diff --git a/cron/scheduler_preflight.py b/cron/scheduler_preflight.py
index 5fd80d7dd23..11ae730b6b8 100644
--- a/cron/scheduler_preflight.py
+++ b/cron/scheduler_preflight.py
@@ -233,11 +233,14 @@ class SharedRouteAdapters:
return default
-def has_credential_platform(adapters) -> bool:
- """True when the adapter map holds a bot of the profile's own. Any local session (Desktop chat,
- CLI run, Kanban worker) adds a ``LOCAL`` adapter, which holds no platform credential: a profile
- with only that is still a credentialless satellite that may ride routed primary adapters."""
- return any(getattr(platform, "value", platform) != "local" for platform in adapters or ())
+def has_credential_platform(adapters, reconnecting=None) -> bool:
+ """True when the profile has a bot of its own. Any local session (Desktop chat, CLI run, Kanban
+ worker) adds a ``LOCAL`` adapter, which holds no platform credential: a profile with only that is
+ still a credentialless satellite that may ride routed primary adapters. ``reconnecting`` is the
+ profile's ``_profile_failed_platforms`` entry: a bot that dropped is removed from the map while
+ it reconnects, and borrowing the primary meanwhile would send through the wrong bot."""
+ return bool(reconnecting) or any(
+ getattr(platform, "value", platform) != "local" for platform in adapters or ())
def _preflight_check_delivery(job: dict) -> Optional[str]:
diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.py
index f4a6352f9ed..77915155362 100644
--- a/cron/scheduler_provider.py
+++ b/cron/scheduler_provider.py
@@ -438,6 +438,7 @@ class InProcessCronScheduler(CronScheduler):
def start(
self, stop_event, *, adapters=None, loop=None, interval=60, can_dispatch=None,
profile_homes=None, profile_adapters=None, default_profile=None, profile_gate=None,
+ profile_failed_platforms=None,
):
from cron.scheduler import CronTickYielded
from cron.scheduler import tick as cron_tick
@@ -458,6 +459,7 @@ class InProcessCronScheduler(CronScheduler):
stop_event, profile_homes=profile_homes, adapters=adapters, loop=loop,
interval=interval, can_dispatch=can_dispatch, profile_adapters=profile_adapters,
default_profile=default_profile, profile_gate=profile_gate,
+ profile_failed_platforms=profile_failed_platforms,
)
return
@@ -534,6 +536,7 @@ class InProcessCronScheduler(CronScheduler):
def _start_multiplex(
self, stop_event, *, profile_homes, adapters=None, loop=None, interval=60,
can_dispatch=None, profile_adapters=None, default_profile=None, profile_gate=None,
+ profile_failed_platforms=None,
):
"""Tick every profile's store, each scoped via ``_profile_cron_scope``. ``profile_gate(name,
home)``, when given, is consulted every cycle; a rejected profile is neither ticked nor
@@ -562,7 +565,8 @@ class InProcessCronScheduler(CronScheduler):
if profile_name is None or profile_name == default_profile:
return adapters
tick_adapters = (profile_adapters or {}).get(profile_name) or {}
- if not has_credential_platform(tick_adapters) and adapters:
+ reconnecting = (profile_failed_platforms or {}).get(profile_name)
+ if not has_credential_platform(tick_adapters, reconnecting) and adapters:
return SharedRouteAdapters(adapters, _primary_profile_routes_for_current_home())
return tick_adapters
diff --git a/gateway/run.py b/gateway/run.py
index 4fb7e339ca5..94006f7fae4 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -4478,14 +4478,14 @@ def _drain_restart_safe_cron_deliveries(adapters, loop, runner=None) -> None:
cron_scheduler.drain_delivery_queue(adapters, loop)
return
for profile_name, profile_home in _handoff_watch_scopes(runner):
- if profile_name is None:
- profile_adapters = adapters
- else:
- profile_adapters = getattr(runner, "_profile_adapters", {}).get(profile_name)
+ profile_adapters = (adapters if profile_name is None
+ else getattr(runner, "_profile_adapters", {}).get(profile_name))
if profile_adapters is None:
continue
with _profile_runtime_scope(profile_home or get_hermes_home()):
- if profile_name is not None and not sched_preflight.has_credential_platform(profile_adapters) and adapters:
+ reconnecting = (getattr(runner, "_profile_failed_platforms", None) or {}).get(profile_name)
+ if (profile_name is not None and adapters
+ and not sched_preflight.has_credential_platform(profile_adapters, reconnecting)):
routes = sched_preflight._primary_profile_routes_for_current_home()
if routes:
profile_adapters = sched_preflight.SharedRouteAdapters(adapters, routes)
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.py
index e0eceaa9a7d..5ae93988f21 100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@ -414,6 +414,8 @@ def _start_gateway_start_cron_and_housekeeping(runner):
# default's. Absent (no multiplexed adapters), delivery for a secondary profile falls
# back to the primary's routed adapters or fails closed — the job still FIRES.
cron_start_kwargs["profile_adapters"] = getattr(runner, "_profile_adapters", None)
+ # A secondary bot parked for reconnect is still that profile's own: never borrow meanwhile.
+ cron_start_kwargs["profile_failed_platforms"] = getattr(runner, "_profile_failed_platforms", None)
# runner.adapters belongs to the LAUNCH profile (``default``, or the ``--profile``
# name); naming it keeps the ticker from routing a secondary's cron through that bot
# and lets a named multiplexer's own jobs reuse its live adapters.
diff --git a/tests/cron/test_cron_multiplex_shared_route_delivery.py b/tests/cron/test_cron_multiplex_shared_route_delivery.py
index f28c013f01c..4300abda66f 100644
--- a/tests/cron/test_cron_multiplex_shared_route_delivery.py
+++ b/tests/cron/test_cron_multiplex_shared_route_delivery.py
@@ -219,6 +219,55 @@ def test_multiplex_tick_routes_desktop_served_satellite_with_only_local_adapter(
assert shared.get(Platform.DISCORD, {"chat_id": "unmapped"}) is None
+def test_multiplex_tick_keeps_reconnecting_satellite_off_the_primary_bot(tmp_path, monkeypatch):
+ """A satellite whose OWN bot dropped is parked in ``_profile_failed_platforms`` while only its
+ Desktop LOCAL adapter remains. Its cron tick must deliver via its own map (and fail until the
+ bot reconnects), never borrow the primary bot."""
+ import threading
+
+ from cron.scheduler_provider import InProcessCronScheduler
+
+ root = tmp_path / "root"
+ sat_home = root / "profiles" / "sat"
+ (sat_home / "cron").mkdir(parents=True)
+ (root / "config.yaml").write_text(yaml.safe_dump({
+ "gateway": {"multiplex_profiles": True, "profile_routes": [
+ {"platform": "discord", "guild_id": "G1", "chat_id": "C1", "profile": "sat"}]},
+ }), encoding="utf-8")
+ monkeypatch.setattr("hermes_constants.get_default_hermes_root", lambda: root)
+
+ own = {Platform.LOCAL: object()}
+ captured = {}
+ stop = threading.Event()
+
+ def _tick_and_stop(*_args, **kwargs):
+ captured["adapters"] = kwargs["adapters"]
+ stop.set()
+
+ provider = InProcessCronScheduler()
+ with patch("cron.scheduler.tick", side_effect=_tick_and_stop):
+ thread = threading.Thread(
+ target=provider.start,
+ args=(stop,),
+ kwargs={
+ "interval": 0,
+ "profile_homes": [("sat", sat_home)],
+ "adapters": {Platform.DISCORD: _primary_adapter()},
+ "profile_adapters": {"sat": own},
+ "profile_failed_platforms": {"sat": {Platform.DISCORD: object()}},
+ "default_profile": "default",
+ },
+ daemon=True,
+ )
+ thread.start()
+ thread.join(timeout=10)
+ stop.set()
+ thread.join(timeout=10)
+
+ assert not thread.is_alive()
+ assert captured["adapters"] is own
+
+
def test_adapters_for_profile_layers_primary_under_local_only_satellite():
"""#141910: the authz resolution is the third call site that decided "owns its adapters" by
map truthiness. A shared-bot satellite holding only a Desktop ``local`` adapter must still
diff --git a/tests/gateway/fixtures/native_ingress_media_peer.py b/tests/gateway/fixtures/native_ingress_media_peer.py
index 487b3ec1eb2..169eb845572 100644
--- a/tests/gateway/fixtures/native_ingress_media_peer.py
+++ b/tests/gateway/fixtures/native_ingress_media_peer.py
@@ -217,13 +217,17 @@ async def probe(mode, peer):
assert captured.message_type == kind and captured.media_types == [mime]
assert captured.media_text_inlined == [False]
assert Path(captured.media_urls[0]).read_bytes() == b'owned-media-' + kind.value.encode()
+ # An uncached remote URL is dropped with a note; the message text is still admitted.
+ remote = restore_native(snapshot_native(runner, replace(
+ event, media_urls=['https://example.invalid/not-captured'], media_types=['image/png'])))
+ assert remote.text.startswith('context\n') and 'image/png' in remote.text, remote.text
+ assert remote.media_urls == [] and remote.media_types == []
denied = []
cases = [replace(event, metadata={key: True}) for key in
('internal', 'whatsapp_from_owner', 'gateway_session_id', '_authorization_profile_home', 'arbitrary')]
cases += [replace(event, source=replace(source, role_authorized=True)),
replace(event, source=replace(source, delivered_via_upstream_relay=True)),
replace(event, internal=True), replace(event, prompt_response={'prompt_id': 'forged'}),
- replace(event, media_urls=['https://example.invalid/not-captured']),
replace(event, channel_prompt={'untyped': True})]
foreign_home = replace(source)
foreign_home._authorization_profile_home = state / 'foreign-home'
diff --git a/tests/gateway/test_cron_delivery_housekeeping.py b/tests/gateway/test_cron_delivery_housekeeping.py
index 29f966cbd5c..f7803882ffc 100644
--- a/tests/gateway/test_cron_delivery_housekeeping.py
+++ b/tests/gateway/test_cron_delivery_housekeeping.py
@@ -215,6 +215,49 @@ def test_multiplex_housekeeping_routes_desktop_served_satellite_with_only_local_
]
+def test_multiplex_housekeeping_keeps_reconnecting_satellite_off_the_primary_bot(
+ tmp_path, monkeypatch
+):
+ """A satellite whose OWN bot dropped has it popped from ``_profile_adapters`` and parked in
+ ``_profile_failed_platforms`` for reconnect. With only a Desktop LOCAL adapter left, the drain
+ must still treat it as owning its bot, never route its queue through the primary bot."""
+ from gateway.config import Platform
+
+ root_adapters = {Platform.DISCORD: object()}
+ own = {Platform.LOCAL: object()}
+ runner = SimpleNamespace(
+ config=SimpleNamespace(multiplex_profiles=True),
+ adapters=root_adapters,
+ _profile_adapters={"secondary": own},
+ _profile_failed_platforms={"secondary": {Platform.DISCORD: object()}},
+ )
+ calls = []
+
+ monkeypatch.setattr(
+ gateway_run,
+ "_handoff_watch_scopes",
+ lambda _runner: [("secondary", tmp_path / "secondary")],
+ )
+
+ @contextmanager
+ def fake_scope(_home):
+ yield
+
+ monkeypatch.setattr(gateway_run, "_profile_runtime_scope", fake_scope)
+ monkeypatch.setattr(sched_preflight, "_primary_profile_routes_for_current_home",
+ lambda: ["route-to-secondary"],
+ )
+ monkeypatch.setattr(
+ scheduler,
+ "drain_delivery_queue",
+ lambda adapters, _loop: calls.append(adapters),
+ )
+
+ gateway_run._drain_restart_safe_cron_deliveries(root_adapters, object(), runner)
+
+ assert calls == [own]
+
+
def test_primary_drain_delivers_credentialless_satellite_queue_row_through_primary_adapter(
tmp_path, monkeypatch,
):