Skip to content

The agent that grows with you

fix(gateway): a served profile's reconnect replays the owed restart notice and resumes deferred sessions

John Paul Soliva2e2fd696872a
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index af4adf7c62f..761d535b486 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -788,6 +788,16 @@ class GatewayAdapterLifecycleMixin:
self._sync_voice_mode_state_to_adapter(adapter)
self._bind_voice_input_callback(adapter)
+ def _schedule_planned_restart_replay(self) -> None:
+ """Replay the owed planned-restart notice after a reconnect, in the background: notification delivery
+ must not hold up adapter recovery or other platforms' reconnects."""
+ from gateway.run import _planned_restart_notification_pending
+ if _planned_restart_notification_pending():
+ task = self._retain_background_task(asyncio.create_task(
+ self._replay_pending_planned_restart_notification(),
+ ))
+ task.add_done_callback(self._late_failure_callback("planned-restart notification replay failed"))
+
async def _install_reconnected_adapter(self, platform, adapter) -> None:
"""Publish a freshly reconnected primary adapter and replay what it missed while down."""
self._publish_primary_adapter(platform, adapter)
@@ -806,13 +816,7 @@ class GatewayAdapterLifecycleMixin:
logger.info("⚠ %s reconnected in degraded mode (receive path not yet confirmed)", platform.value)
else:
logger.info("✓ %s reconnected successfully", platform.value)
- # Notification delivery must not hold up adapter recovery or other platforms' reconnects.
- from gateway.run import _planned_restart_notification_pending
- if _planned_restart_notification_pending():
- task = self._retain_background_task(asyncio.create_task(
- self._replay_pending_planned_restart_notification(),
- ))
- task.add_done_callback(self._late_failure_callback("planned-restart notification replay failed"))
+ self._schedule_planned_restart_replay()
# Responses rejected while down are owned by this live process (startup recovery cannot claim them).
with _log_suppressed(
logging.DEBUG, "failed-obligation redelivery after %s reconnect failed",
@@ -1270,6 +1274,14 @@ class GatewayAdapterLifecycleMixin:
await self._redeliver_failed_obligations_for_platform(
platform, profile=profile_name
)
+ # What a primary reconnect replays too: the owed notice spans served profiles' home
+ # channels, and sessions boot skipped for this offline adapter wait for this call.
+ self._schedule_planned_restart_replay()
+ try:
+ self._schedule_resume_pending_sessions(platform=platform)
+ except Exception:
+ logger.debug("resume-pending reschedule after %s reconnect failed (profile: %s)",
+ platform.value, profile_name, exc_info=True)
return
# Not installed (newer reconnect won the slot, shutdown began, or connect failed):
# release partial resources; stop only for a non-retryable fatal.
diff --git a/tests/gateway/test_planned_restart_notice_multiplex.py b/tests/gateway/test_planned_restart_notice_multiplex.py
index 71202f5d1c8..f7b93e4907f 100644
--- a/tests/gateway/test_planned_restart_notice_multiplex.py
+++ b/tests/gateway/test_planned_restart_notice_multiplex.py
@@ -174,3 +174,35 @@ async def test_unserved_profile_config_is_pruned_from_the_fan_out(tmp_path, monk
assert "ghost" not in runner._profile_configs
assert list(runner._served_home_channel_configs()) == [
(None, Platform.DISCORD, runner.config.platforms[Platform.DISCORD])]
+
+
+async def test_a_served_profiles_reconnect_replays_the_owed_notice(multiplex_runner):
+ """A served profile whose bot was down at boot keeps the notice owed "for its reconnect" -- but only
+ the primary reconnect replayed it, so the marker outlived the outage and the notice never went out."""
+ import asyncio
+
+ runner, marker = multiplex_runner
+ runner.adapters[Platform.DISCORD] = _adapter()
+ await runner._replay_pending_planned_restart_notification() # boot: coder's Telegram is down
+ assert marker.exists()
+
+ coder = SimpleNamespace(send_path_degraded=False, has_fatal_error=False, fatal_error_retryable=True,
+ send=AsyncMock(return_value=SendResult(success=True, message_id="n")))
+ runner._running = True
+ runner._background_tasks = set()
+ runner._profile_failed_platforms = {}
+ runner._failed_platforms = {}
+ runner._sync_voice_mode_state_to_adapter = Mock()
+ runner._redeliver_failed_obligations_for_platform = AsyncMock(return_value=0)
+ runner._schedule_resume_pending_sessions = Mock(return_value=0)
+ runner._secondary_reconnect_attempt = AsyncMock(return_value=(coder, True))
+
+ await runner._run_secondary_profile_reconnect("coder", Platform.TELEGRAM)
+ for _ in range(50):
+ await asyncio.sleep(0)
+
+ assert runner._profile_adapters["coder"][Platform.TELEGRAM] is coder
+ coder.send.assert_awaited_once()
+ assert coder.send.await_args.args[:2] == ("coder-home", ONLINE_NOTICE)
+ assert not marker.exists(), "the owed target was reached on reconnect: the obligation is discharged"
diff --git a/tests/gateway/test_restart_resume_pending.py b/tests/gateway/test_restart_resume_pending.py
index 167404aa513..df763532b4b 100644
--- a/tests/gateway/test_restart_resume_pending.py
+++ b/tests/gateway/test_restart_resume_pending.py
@@ -47,6 +47,7 @@ from gateway.run import (
)
from gateway.session import SessionEntry, SessionSource, SessionStore
from tests.gateway.restart_test_helpers import (
+ RestartTestAdapter,
make_restart_runner,
make_restart_source,
)
@@ -665,6 +666,49 @@ async def test_reconnect_reschedule_is_platform_scoped():
assert event.source == tg_source
+async def test_served_profile_reconnect_resumes_what_boot_deferred():
+ """A served profile's session whose own bot is offline at boot is deferred (never answered from the
+ default bot) "for the reconnect watcher" -- which must then resume it through that profile's bot."""
+ runner, primary = make_restart_runner()
+ runner.config.multiplex_profiles = True
+ runner._primary_profile_name = "default"
+ runner._profile_adapters = {"coder": {}}
+ runner._profile_failed_platforms = {}
+ source = SessionSource(
+ platform=Platform.TELEGRAM, chat_id="c1", chat_type="dm", user_id="u1", profile="coder"
+ )
+ entry = SessionEntry(
+ session_key="agent:coder:telegram:dm:c1",
+ session_id="sid-c",
+ created_at=datetime.now(),
+ updated_at=datetime.now(),
+ origin=source,
+ platform=Platform.TELEGRAM,
+ chat_type="dm",
+ resume_pending=True,
+ resume_reason="restart_interrupted",
+ last_resume_marked_at=datetime.now(),
+ transport_profile="coder",
+ )
+ runner.session_store._entries = {entry.session_key: entry}
+ primary.handle_message = AsyncMock()
+ assert runner._schedule_resume_pending_sessions() == 0 # boot: coder's bot is down
+
+ coder = RestartTestAdapter()
+ coder.handle_message = AsyncMock()
+ runner._sync_voice_mode_state_to_adapter = MagicMock()
+ runner._redeliver_failed_obligations_for_platform = AsyncMock(return_value=0)
+ runner._secondary_reconnect_attempt = AsyncMock(return_value=(coder, True))
+ await runner._run_secondary_profile_reconnect("coder", Platform.TELEGRAM)
+ for _ in range(50):
+ await asyncio.sleep(0)
+
+ primary.handle_message.assert_not_called()
+ coder.handle_message.assert_awaited_once()
+ assert coder.handle_message.await_args.args[0].source.profile == "coder"
+
+
@pytest.mark.asyncio
async def test_startup_restore_waits_for_resume_before_draining_inbound():
"""Queued inbound turns replay only after startup resume tasks finish."""