The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): publish degraded status when polling dies mid-session, via a public seam
kshitijk4poor60ee3790e00b
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 9a30b74b408..b2067bef404 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -3669,26 +3669,40 @@ class BasePlatformAdapter(ABC):def set_fatal_error_handler(self, handler: Callable[["BasePlatformAdapter"], Awaitable[None] | None]) -> None:self._fatal_error_handler = handler- def _mark_connected(self, *, degraded: bool = False) -> None:+ #: Published when an adapter is installed and running but its receive+ #: path is not yet confirmed (e.g. Telegram polling has not proven a+ #: getUpdates round-trip). Same ``retrying`` platform_state the runner+ #: uses for queued reconnects, so readers see "not delivering" (#101391).+ DEGRADED_STATUS_MESSAGE = "connected but not yet confirmed active; recovering in background"++ @property+ def send_path_degraded(self) -> bool:+ """True while connect() succeeded but delivery is not confirmed.++ Adapters with a separately-proven receive path override this; the+ default adapter is either connected or not.+ """+ return False++ def _mark_connected(self) -> None:self._running = Trueself._fatal_error_code = Noneself._fatal_error_message = Noneself._fatal_error_retryable = True- if degraded:- # connect() succeeded but the adapter knows its send/receive path- # is not actually confirmed active yet (e.g. Telegram polling- # never proved a first getUpdates round-trip). Publishing- # "connected" here would be indistinguishable from a healthy- # adapter to anything reading gateway_state.json (#101391).- self._write_runtime_status_safe(- "connected_degraded",- platform_state="retrying",- error_code=None,- error_message="connected but not yet confirmed active; recovering in background",- )+ if self.send_path_degraded:+ self._mark_degraded()else:self._write_runtime_status_safe("connected", platform_state="connected", error_code=None, error_message=None)+ def _mark_degraded(self) -> None:+ """Publish ``retrying`` for a running adapter whose delivery path is unproven."""+ self._write_runtime_status_safe(+ "connected_degraded",+ platform_state="retrying",+ error_code=None,+ error_message=self.DEGRADED_STATUS_MESSAGE,+ )+def _mark_disconnected(self) -> None:self._running = Falseif self.has_fatal_error:diff --git a/gateway/run.py b/gateway/run.pyindex 182ebf40ebd..b249e855cde 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -14439,10 +14439,14 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# transcription is forwarded without requiring /voice join.self._bind_voice_input_callback(adapter)connected_count += 1+ _degraded = adapter.send_path_degradedself._update_platform_runtime_status(- platform.value, platform_state="connected", error_code=None, error_message=None,+ platform.value,+ platform_state="retrying" if _degraded else "connected",+ error_code=None,+ error_message=adapter.DEGRADED_STATUS_MESSAGE if _degraded else None,)- logger.info("\u2713 %s connected", platform.value)+ logger.info("\u2713 %s connected%s", platform.value, " (degraded)" if _degraded else "")else: # outcome == "failed"logger.warning("\u2717 %s failed to connect", platform.value)# Defensive cleanup: a failed connect() may have allocated resources@@ -16204,30 +16208,23 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewself.delivery_router.adapters = self.adaptersdel self._failed_platforms[platform]# connect() returning True does not mean the adapter's- # send/receive path is actually confirmed active --- # Telegram's degraded-polling reconnect intentionally- # returns True so the gateway stays up while its own- # background ladder retries. Stamping "connected"- # unconditionally here would silently undo the- # adapter's own accurate status write (#101391).- _degraded = getattr(adapter, "_send_path_degraded", False)+ # receive path is confirmed -- Telegram's degraded+ # reconnect returns True so the gateway stays up while+ # its own ladder retries. Stamping "connected" here+ # would undo the adapter's accurate status (#101391).+ _degraded = adapter.send_path_degradedself._update_platform_runtime_status(platform.value,platform_state="retrying" if _degraded else "connected",error_code=None,- error_message=(- "connected but not yet confirmed active; recovering in background"- if _degraded else None- ),+ error_message=adapter.DEGRADED_STATUS_MESSAGE if _degraded else None,needs_attention=False,retrying_since=None,)- logger.info(- "%s %s reconnected%s",- "⚠" if _degraded else "✓",- platform.value,- " in degraded mode (send/receive path not yet confirmed)" if _degraded else " successfully",- )+ if _degraded:+ logger.info("⚠ %s reconnected in degraded mode (receive path not yet confirmed)", platform.value)+ else:+ logger.info("✓ %s reconnected successfully", platform.value)# Final responses rejected while this adapter was down# are still owned by this live process, so startupdiff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex fc2920dc707..d50f631c272 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -900,13 +900,16 @@ class TelegramAdapter(BasePlatformAdapter):# blow the gateway's connect timeout (#46298).self._post_connect_task: Optional[asyncio.Task] = None+ @property+ def send_path_degraded(self) -> bool:+ # True from polling-generation start until the first getUpdates+ # round-trip is proven (_record_polling_progress), and again at every+ # polling-death site. getattr: tests build adapters via object.__new__().+ return bool(getattr(self, "_send_path_degraded", False))+def _mark_connected(self) -> None:self._drop_delayed_deliveries = False- # _send_path_degraded is already true whenever this connect's- # polling generation has not proven a first getUpdates round-trip- # (set at generation start, cleared in _record_polling_progress) —- # publish that instead of an unconditional "connected" (#101391).- super()._mark_connected(degraded=getattr(self, "_send_path_degraded", False))+ super()._mark_connected()# Drain anything held while we were down. PTB will not redeliver —# these events exist only in our hold queue now.self._schedule_held_inbound_redispatch()@@ -2698,12 +2701,9 @@ class TelegramAdapter(BasePlatformAdapter):self._polling_conflict_recovery_generation = Noneelse:self._polling_conflict_count = 0- # If connect() already published "connected" while polling was- # confirmed degraded (or the reconnect watcher stamped that state- # once connect() returned), gateway_state.json is still showing the- # pre-recovery status. This is the first proof getUpdates is- # actually flowing again, so flip it back now instead of leaving it- # wedged at "retrying" until the next disconnect/reconnect (#101391).+ # First proof getUpdates is flowing for this generation: flip a+ # published "retrying" (degraded connect, reconnect stamp, or the+ # mid-session recovery below) back to "connected" (#101391).if self._send_path_degraded and getattr(self, "_running", False) and not self.has_fatal_error:self._write_runtime_status_safe("connected", platform_state="connected", error_code=None, error_message=None,@@ -2926,6 +2926,11 @@ class TelegramAdapter(BasePlatformAdapter):)returnself._send_path_degraded = True+ # Polling died mid-session on an adapter that published "connected"+ # at connect time. Without this, gateway_state.json keeps saying+ # connected for as long as the recovery ladder runs (#101391: 11 h).+ if getattr(self, "_running", False):+ self._mark_degraded()logger.warning("[%s] Telegram polling degraded (%s); gateway stays alive and will retry. Error: %s",self.name, reason, _redact_telegram_error_text(error),diff --git a/tests/gateway/test_platform_reconnect.py b/tests/gateway/test_platform_reconnect.pyindex 75029072c8c..e923fac8092 100644--- a/tests/gateway/test_platform_reconnect.py+++ b/tests/gateway/test_platform_reconnect.py@@ -199,6 +199,55 @@ class TestPlatformReconnectWatcher:)assert Platform.TELEGRAM in runner.adapters+ @pytest.mark.asyncio+ @pytest.mark.parametrize("degraded", [False, True])+ async def test_reconnect_stamp_honours_adapter_send_path_degraded(self, degraded):+ """connect() returning True is not proof the receive path is live:+ Telegram's degraded reconnect returns True while its own ladder+ retries. The watcher's status stamp must publish what the adapter+ reports, not an unconditional "connected" (#101391)."""+ runner = _make_runner()+ runner._sync_voice_mode_state_to_adapter = MagicMock()+ runner._update_platform_runtime_status = MagicMock()+ runner._failed_platforms[Platform.TELEGRAM] = {+ "config": PlatformConfig(enabled=True, token="test"),+ "attempts": 1,+ "next_retry": time.monotonic() - 1,+ }++ class _DegradableAdapter(StubAdapter):+ @property+ def send_path_degraded(self) -> bool:+ return degraded++ adapter = _DegradableAdapter(succeed=True)+ real_sleep = asyncio.sleep++ with patch.object(runner, "_create_adapter", return_value=adapter):+ with patch("gateway.run.build_channel_directory", create=True):+ runner._running = True+ call_count = 0++ async def fake_sleep(n):+ nonlocal call_count+ call_count += 1+ if call_count > 1:+ runner._running = False+ await real_sleep(0)++ with patch("asyncio.sleep", side_effect=fake_sleep):+ await runner._platform_reconnect_watcher()++ stamps = [+ c.kwargs for c in runner._update_platform_runtime_status.call_args_list+ if c.args and c.args[0] == Platform.TELEGRAM.value+ ]+ assert stamps, "watcher never stamped telegram"+ final = stamps[-1]+ assert final["platform_state"] == ("retrying" if degraded else "connected")+ assert final["error_message"] == (adapter.DEGRADED_STATUS_MESSAGE if degraded else None)+ assert final["retrying_since"] is None+@pytest.mark.asyncioasync def test_cold_connect_defaults_to_is_reconnect_false(self):"""The cold-start connect path (_connect_adapter_with_timeout with nodiff --git a/tests/gateway/test_telegram_send_path_health.py b/tests/gateway/test_telegram_send_path_health.pyindex 0e50312e974..91e0a01123f 100644--- a/tests/gateway/test_telegram_send_path_health.py+++ b/tests/gateway/test_telegram_send_path_health.py@@ -122,3 +122,64 @@ def test_record_polling_progress_republishes_connected_after_degraded_connect():_, kwargs = write_status.call_argsassert kwargs["platform_state"] == "connected"assert adapter._send_path_degraded is False+++def test_mid_session_polling_death_publishes_retrying_while_running():+ """#101391's measured incident: a HEALTHY connect published "connected",+ then getUpdates silently died mid-session and nothing republished for 11h.+ The recovery ladder's entry point must flip the file to "retrying"."""+ adapter = _make_adapter()+ adapter._running = True+ adapter._send_path_degraded = False+ adapter._polling_error_task = None++ class _Loop:+ def create_task(self, coro):+ coro.close()+ return MagicMock(done=lambda: False)++ with patch.object(adapter, "_write_runtime_status_safe") as write_status, \+ patch("asyncio.get_running_loop", return_value=_Loop()):+ adapter._schedule_polling_recovery(RuntimeError("boom"), reason="heartbeat probe")++ assert adapter._send_path_degraded is True+ write_status.assert_called_once()+ _, kwargs = write_status.call_args+ assert kwargs["platform_state"] == "retrying"+ assert kwargs["error_message"] == TelegramAdapter.DEGRADED_STATUS_MESSAGE+++def test_polling_death_before_connect_does_not_publish():+ """Not yet running (cold connect still in progress): connect()'s own+ _mark_connected publishes; the recovery path must not write early."""+ adapter = _make_adapter()+ adapter._running = False+ adapter._polling_error_task = None++ class _Loop:+ def create_task(self, coro):+ coro.close()+ return MagicMock(done=lambda: False)++ with patch.object(adapter, "_write_runtime_status_safe") as write_status, \+ patch("asyncio.get_running_loop", return_value=_Loop()):+ adapter._schedule_polling_recovery(RuntimeError("boom"), reason="polling bootstrap")++ write_status.assert_not_called()++[email protected]("running, fatal", [(False, False), (True, True)])+def test_record_polling_progress_does_not_flip_when_not_running_or_fatal(running, fatal):+ """Cold connect: progress arrives while _running is still False -- the+ connect path publishes, not the flip. Fatal: never overwrite "fatal"."""+ adapter = _make_adapter()+ generation, _event = adapter._begin_polling_generation()+ adapter._running = running+ if fatal:+ adapter._fatal_error_message = "dead"++ with patch.object(adapter, "_write_runtime_status_safe") as write_status:+ adapter._record_polling_progress(generation)++ write_status.assert_not_called()+ assert adapter._send_path_degraded is False