The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): stop notice reaches every served profile's home channel via its own bot (#118233, salvage #118408)
teknium14b8a57038dcb
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 036ea7ca430..3922b9862ca 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -22,7 +22,7 @@ from gateway.config import Platform, _BUILTIN_PLATFORM_VALUESfrom gateway.platforms.base import BasePlatformAdapter, _mark_notify_metadatafrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.session import SessionEntry, SessionSource-from gateway.run_shutdown import _log_suppressed, _notice_target_key, _send_error, _send_failed+from gateway.run_shutdown import _delivery_target_key, _log_suppressed, _notice_target_key, _send_error, _send_failed# Log-record parity with the origin module.logger = logging.getLogger("gateway.run")@@ -51,16 +51,6 @@ def _served_notice_target_key(profile: Optional[str], platform_value: str, chat_platform_value if profile is None else f"{profile}:{platform_value}", chat_id, thread_id)-def _delivery_target_key(platform_value: str, chat_id, thread_id, *, profile: Optional[str] = None) -> tuple:- """Dedupe shared chats across profiles, but not Telegram bot-private conversations."""- # Telegram private chat IDs identify the user, not the conversation with a particular bot.- # Groups have negative IDs and remain one shared destination across served profiles.- chat = str(chat_id)- if platform_value == "telegram" and chat.isdecimal() and int(chat) > 0:- return _served_notice_target_key(profile, platform_value, chat_id, thread_id)- return _notice_target_key(platform_value, chat_id, thread_id)--def _safe_delivery_transport(platform, config, adapters, *, profile: Optional[str] = None):"""``resolve_delivery_transport`` isolated to one target: ``None`` (logged) on failure.diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex 02d64e65bdc..68134098e96 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -146,6 +146,20 @@ def _notice_target_key(platform_value: str, chat_id, thread_id) -> tuple:return (platform_value, str(chat_id), str(thread_id) if thread_id else None)+def _delivery_target_key(platform_value: str, chat_id, thread_id, *, profile: Optional[str] = None) -> tuple:+ """Dedupe key for one DELIVERED chat: profile-independent, except Telegram private chats.++ Two served profiles can share one home chat (one Telegram group for the whole host) and owe it+ ONE notice per host restart. A positive Telegram chat id names the USER, though: the same id+ under two bot tokens is two conversations, so those stay keyed per served profile (#118233).+ """+ from gateway.delivery import looks_like_telegram_private_chat_id+ if (profile and profile != "default" and platform_value == "telegram"+ and looks_like_telegram_private_chat_id(chat_id)):+ platform_value = f"{profile}:{platform_value}"+ return _notice_target_key(platform_value, chat_id, thread_id)++def _effective_watchdog_leash(runner: object) -> float:"""Thread-watchdog leash for the stop in progress: effective drain + grace, clamped underlaunchd's live ``ExitTimeOut`` minus the dump margin. Lives here (not in gateway.restart)@@ -876,9 +890,12 @@ class GatewayShutdownMixin:platform_cfg = self.config.platforms.get(platform)return platform_cfg is None or bool(platform_cfg.gateway_restart_notification)- def _notice_allowed(self, platform: Platform, what: str) -> bool:- """``_restart_notification_allowed`` with the INFO suppression line for shutdown notices."""- if self._restart_notification_allowed(platform):+ def _notice_allowed(self, platform: Platform, what: str, platform_cfg=None) -> bool:+ """``_restart_notification_allowed`` with the INFO suppression line for shutdown notices.+ ``platform_cfg`` is a SERVED profile's own platform entry; ``self.config`` is the launch profile's."""+ allowed = (self._restart_notification_allowed(platform) if platform_cfg is None+ else bool(platform_cfg.gateway_restart_notification))+ if allowed:return Truelogger.info("Shutdown notification suppressed for %s: %s has gateway_restart_notification=false", what, platform.value,@@ -1034,7 +1051,7 @@ class GatewayShutdownMixin:if target is None:continuesource, platform_str, chat_id, thread_id, profile = target- dedup_key = _notice_target_key(platform_str, chat_id, thread_id)+ dedup_key = _delivery_target_key(platform_str, chat_id, thread_id, profile=profile)if dedup_key in notified:continuetry:@@ -1088,15 +1105,21 @@ class GatewayShutdownMixin:"Home-channel shutdown broadcast suppressed by drain marker (suppress_notification=true)")return- # Snapshot adapters: adapter.send() can hit a fatal path (_handle_fatal) that pops the adapter- # from self.adapters -> ``RuntimeError: dictionary changed size during iteration``.- for platform, adapter in list(self.adapters.items()):- home = self.config.get_home_channel(platform)+ # EVERY served profile's home channel, through that profile's OWN bot: ``self.adapters`` and+ # ``self.config`` are the launch profile's alone, so iterating them left the secondaries'+ # channels silent (#118233). ``list(...)`` snapshots the adapter maps: adapter.send() can hit+ # a fatal path (_handle_fatal) that pops the adapter -> "dictionary changed size during iteration".+ profile_adapters = getattr(self, "_profile_adapters", None) or {}+ for profile, platform, platform_cfg in list(self._served_home_channel_configs()):+ home = platform_cfg.home_channelif not home or not home.chat_id:continue- if not self._notice_allowed(platform, "home channel"):+ adapter = (self.adapters if profile is None else profile_adapters.get(profile) or {}).get(platform)+ if adapter is None:+ continue+ if not self._notice_allowed(platform, "home channel", platform_cfg):continue- dedup_key = _notice_target_key(platform.value, home.chat_id, home.thread_id)+ dedup_key = _delivery_target_key(platform.value, home.chat_id, home.thread_id, profile=profile)if dedup_key in notified:continuetry:@@ -1112,7 +1135,11 @@ class GatewayShutdownMixin:):notified.add(dedup_key)from gateway.warning_notifications import present_notification- await present_notification(_send_home, platform=platform)+ from gateway.run import _async_profile_runtime_scope+ # present_notification reads the ACTIVE profile's display settings: bind the served one's.+ profile_home = (getattr(self, "_served_profile_homes", None) or {}).get(profile) if profile else None+ async with _async_profile_runtime_scope(profile_home) if profile_home else nullcontext():+ await present_notification(_send_home, platform=platform)# Agent finalization / resource cleanup@staticmethoddiff --git a/tests/gateway/test_multiplex_notice_egress_profile_adapter.py b/tests/gateway/test_multiplex_notice_egress_profile_adapter.pyindex 40a93f1efd7..b0d59874602 100644--- a/tests/gateway/test_multiplex_notice_egress_profile_adapter.py+++ b/tests/gateway/test_multiplex_notice_egress_profile_adapter.py@@ -10,7 +10,7 @@ from types import SimpleNamespaceimport pytest-from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.config import GatewayConfig, HomeChannel, Platform, PlatformConfigfrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.run import GatewayRunnerfrom gateway.session import SessionSource@@ -102,3 +102,36 @@ async def test_loop_wakeup_from_secondary_route_fires_through_its_own_bot(monkeyassert r._profile_adapters["sec"][Platform.TELEGRAM].handled == ["tick"]assert r.adapters[Platform.TELEGRAM].handled == []+++def _home_config(platform: Platform, chat_id: str, *, notify: bool = True) -> GatewayConfig:+ return GatewayConfig(platforms={platform: PlatformConfig(+ enabled=True, token="t", gateway_restart_notification=notify,+ home_channel=HomeChannel(platform=platform, chat_id=chat_id, name=chat_id))})+++async def test_shutdown_notice_reaches_every_served_profiles_home_channel(monkeypatch):+ """The home-channel shutdown broadcast covers EVERY served profile, through its own bot.++ ``self.adapters``/``self.config`` are the launch profile's alone, so a served profile's home+ channel never heard the gateway was going down (#118233). Two bots with the same positive+ Telegram id are two private conversations: both are owed a notice. A served profile's own+ ``gateway_restart_notification=false`` opt-out is honoured from ITS config.+ """+ monkeypatch.setattr("gateway.drain_control.drain_notification_suppressed", lambda: False)+ r = _runner()+ r.config = _home_config(Platform.TELEGRAM, "8776018003")+ r._profile_configs = {+ "sec": _home_config(Platform.TELEGRAM, "8776018003"),+ "quiet": _home_config(Platform.DISCORD, "-quiet", notify=False),+ }+ r._profile_adapters = {"sec": {Platform.TELEGRAM: _Adapter()}, "quiet": {Platform.DISCORD: _Adapter()}}+ r._served_profile_homes = {}+ r._snapshot_running_agents = lambda: []++ await r._notify_active_sessions_of_shutdown()++ assert r.adapters[Platform.TELEGRAM].sent == ["8776018003"]+ assert r._profile_adapters["sec"][Platform.TELEGRAM].sent == ["8776018003"], "own bot, own conversation"+ assert r._profile_adapters["quiet"][Platform.DISCORD].sent == [], "served profile's opt-out is its own"diff --git a/tests/gateway/test_planned_restart_notice_multiplex.py b/tests/gateway/test_planned_restart_notice_multiplex.pyindex 0ad5048d4f2..34f591f3c14 100644--- a/tests/gateway/test_planned_restart_notice_multiplex.py+++ b/tests/gateway/test_planned_restart_notice_multiplex.py@@ -96,49 +96,38 @@ async def test_marker_survives_until_a_served_profile_is_reachable(multiplex_run@pytest.mark.asyncio[email protected]("outcome", ["success", "failure", "exception", "disconnected", "disabled", "empty-home"])[email protected]("outcome", ["success", "failure"])async def test_private_home_notices_reach_both_bots(multiplex_runner, outcome):- """Regression for #118233: equal user IDs are distinct bot conversations."""+ """Equal positive Telegram chat ids under two bots are two conversations, not one shared chat.++ A Telegram private chat id names the USER, so the launch bot and a served profile's bot with+ the same home id each owe their own notice; a delivery dedupe that collapses them discharged+ the served profile's obligation without ever sending it (#118233).+ """runner, marker = multiplex_runnerrunner.config = _home_config(Platform.TELEGRAM, "8776018003")launch, coder = _adapter(), _adapter()runner.adapters = {Platform.TELEGRAM: launch}- cfg = _home_config(Platform.TELEGRAM, "8776018003")- runner._profile_configs = {"coder": cfg}+ runner._profile_configs = {"coder": _home_config(Platform.TELEGRAM, "8776018003")}runner._profile_adapters = {"coder": {Platform.TELEGRAM: coder}}if outcome == "failure":coder.send.return_value = SendResult(success=False, error="temporary failure")- elif outcome == "exception":- coder.send.side_effect = RuntimeError("temporary failure")- elif outcome == "disconnected":- runner._profile_adapters["coder"] = {}- elif outcome == "disabled":- cfg.platforms[Platform.TELEGRAM].gateway_restart_notification = False- elif outcome == "empty-home":- cfg.platforms[Platform.TELEGRAM].home_channel = Noneawait runner._replay_pending_planned_restart_notification()launch.send.assert_awaited_once()- if outcome in {"disconnected", "disabled", "empty-home"}:- coder.send.assert_not_awaited()- else:- coder.send.assert_awaited_once()- if outcome in {"failure", "exception", "disconnected"}:- assert marker.exists(), "the second bot conversation is still owed its notice"+ coder.send.assert_awaited_once()+ if outcome == "failure":+ assert marker.exists(), "the second bot's conversation is still owed its notice"recorded = json.loads(marker.read_text(encoding="utf-8"))["delivered_targets"]assert ["telegram", "8776018003", None] in recordedassert ["coder:telegram", "8776018003", None] not in recordedcoder.send.reset_mock()- coder.send.side_effect = Nonecoder.send.return_value = SendResult(success=True, message_id="recovered")- runner._profile_adapters["coder"][Platform.TELEGRAM] = coderawait runner._replay_pending_planned_restart_notification()coder.send.assert_awaited_once()launch.send.assert_awaited_once()assert not marker.exists()- await runner._replay_pending_planned_restart_notification()- launch.send.assert_awaited_once()@pytest.mark.asyncio