diff --git a/docs/DEVICES.md b/docs/DEVICES.md index 6218538aa..6f2b81780 100644 --- a/docs/DEVICES.md +++ b/docs/DEVICES.md @@ -498,18 +498,47 @@ For each V1 command: | **Channel Class** | `V1Channel` | `MqttChannel` directly | | **RPC Abstraction** | `RpcChannel` with strategies | Helper functions | | **Strategy Pattern** | ✅ Multi-strategy (Local → MQTT) | ❌ Direct MQTT only | -| **Health Manager** | ✅ Tracks local/MQTT health | ❌ Not needed | +| **MQTT Health Reporting** | ✅ MQTT requests | ✅ A01 requests; ❌ B01 not yet | | **Code Location** | `v1_channel.py` | `a01_channel.py`, `b01_q7_channel.py` | -#### Health Management (V1 Only) +#### Local Connection Recovery (V1 Only) -Each V1 RPC strategy can have a `HealthManager` that tracks success/failure: +`V1Channel` keeps the local connection alive in the background: -- **Exponential Backoff**: After failures, wait before retrying -- **Automatic Recovery**: Periodically attempt to restore failed connections -- **Network Info Refresh**: Refresh local IP addresses after extended periods +- **Exponential Backoff**: After a failed local connection, wait before retrying (1 to 10 minutes) +- **Automatic Recovery**: Check the local connection periodically and reconnect when it drops +- **Network Info Refresh**: Refresh the device's local IP address after 12 hours -A01/B01 devices don't need health management since they only use MQTT (no fallback). +#### MQTT Health Management + +The broker can stop delivering one device's messages while the MQTT connection itself stays up and +other devices on the shared session keep working. The client keepalive can't detect this, so the +outcome of MQTT requests is tracked instead. Subscribing to the device's topic again on the same +connection doesn't bring its messages back; a new connection does. + +The session's `HealthManager` receives the result of every MQTT request through a per-device +`DeviceHealthManager`, and restarts the whole session (a new connection with all subscriptions +re-established) when: + +- **One device fails**: 3 of its requests in a row time out. Only that device's own response resets + its count, so other devices' responses can't hide its timeouts. +- **The session fails**: 3 requests in a row time out across more than one device. A device that + is waiting out its restart interval (see below) may be offline, so its timeouts don't count here. + +Only timeouts on the current connection count: every new connection, whether forced or after the +session reconnected on its own, starts counting from zero. + +Restarts are paced so that a device that is really offline doesn't keep interrupting the others: + +- At most one restart every 30 minutes. +- After a device restarts the session, it may restart it again only after 1 hour, then 2 and + 4 hours, then every 6 hours. The interval is reset when the device responds again. +- Timeouts while the session is already reconnecting don't restart it. +- A forced restart reconnects right away; other disconnects keep the exponential backoff. + +V1 devices answer most requests over the local connection, so their MQTT topic may carry no traffic +for hours. A broken topic is then noticed when the map (only available over MQTT) is requested +again, and the session is restarted after the first few map requests time out. ### Protocol Versions diff --git a/roborock/devices/rpc/v1_channel.py b/roborock/devices/rpc/v1_channel.py index 54355ca53..585d1a6e4 100644 --- a/roborock/devices/rpc/v1_channel.py +++ b/roborock/devices/rpc/v1_channel.py @@ -18,7 +18,7 @@ from roborock.devices.transport.local_channel import LocalChannel, LocalSession, create_local_session from roborock.devices.transport.mqtt_channel import MqttChannel from roborock.exceptions import RoborockException -from roborock.mqtt.health_manager import HealthManager +from roborock.mqtt.health_manager import DeviceHealthManager from roborock.mqtt.session import MqttParams, MqttSession from roborock.protocols.v1_protocol import ( CommandType, @@ -73,7 +73,7 @@ class RpcStrategy: channel: LocalChannel | MqttChannel encoder: Callable[[RequestMessage], RoborockMessage] decoder: Callable[[RoborockMessage], ResponseMessage | MapResponse | None] - health_manager: HealthManager | None = None + health_manager: DeviceHealthManager | None = None class RpcChannel(V1RpcChannel): diff --git a/roborock/devices/transport/mqtt_channel.py b/roborock/devices/transport/mqtt_channel.py index 1a0f81e64..0c5156723 100644 --- a/roborock/devices/transport/mqtt_channel.py +++ b/roborock/devices/transport/mqtt_channel.py @@ -7,7 +7,7 @@ from roborock.callbacks import decoder_callback from roborock.data import HomeDataDevice, RRiot, UserData from roborock.exceptions import RoborockException -from roborock.mqtt.health_manager import HealthManager +from roborock.mqtt.health_manager import DeviceHealthManager from roborock.mqtt.session import MqttParams, MqttQos, MqttSession, MqttSessionException from roborock.protocol import create_mqtt_decoder, create_mqtt_encoder from roborock.roborock_message import RoborockMessage @@ -45,9 +45,9 @@ def is_connected(self) -> bool: return self._mqtt_session.connected @property - def health_manager(self) -> HealthManager: - """Return the health manager for the session.""" - return self._mqtt_session.health_manager + def health_manager(self) -> DeviceHealthManager: + """Return the health manager that reports this device's events to the session.""" + return DeviceHealthManager(self._mqtt_session.health_manager, self._duid) @property def is_local_connected(self) -> bool: diff --git a/roborock/mqtt/health_manager.py b/roborock/mqtt/health_manager.py index 9e5a23ce6..dea75aaa0 100644 --- a/roborock/mqtt/health_manager.py +++ b/roborock/mqtt/health_manager.py @@ -3,11 +3,18 @@ We observe a problem where sometimes the MQTT connection appears to be alive but no messages are being received. To mitigate this, we track consecutive timeouts and restart the connection if too many timeouts occur in succession. + +The broker can also stop delivering a single device's messages while other devices +on the same connection keep working, so consecutive timeouts are also counted per +device. Only a new connection brings the messages back. """ import datetime import logging from collections.abc import Awaitable, Callable +from dataclasses import dataclass + +from roborock.diagnostics import redact_device_uid _LOGGER = logging.getLogger(__name__) @@ -17,44 +24,153 @@ # We won't restart the session more often than this interval. RESTART_COOLDOWN = datetime.timedelta(minutes=30) +# A single failing device may simply be offline, which a restart can't fix. After it +# restarts the session, it may restart it again only after this interval, which doubles +# with each restart up to MAX_DEVICE_RESTART_COOLDOWN until the device responds. +DEVICE_RESTART_COOLDOWN = datetime.timedelta(hours=1) +MAX_DEVICE_RESTART_COOLDOWN = datetime.timedelta(hours=6) + + +@dataclass +class _DeviceHealth: + """The MQTT request state of a single device.""" + + consecutive_timeouts: int = 0 + restart_cooldown_start: datetime.datetime | None = None + restart_cooldown: datetime.timedelta | None = None + + +def _duration(value: datetime.timedelta) -> datetime.timedelta: + """Round a duration to whole seconds for logs.""" + return datetime.timedelta(seconds=round(value.total_seconds())) + class HealthManager: """Manager for monitoring the health of MQTT connections. This tracks communication timeouts and can trigger restarts of the MQTT - session if too many timeouts occur in succession. + session if too many timeouts occur in succession, either for a single + device or across several devices. """ - def __init__(self, restart: Callable[[], Awaitable[None]]) -> None: + def __init__( + self, + restart: Callable[[], Awaitable[None]], + is_connected: Callable[[], bool] = lambda: True, + ) -> None: """Initialize the health manager. Args: restart: A callable to restart the MQTT session. + is_connected: A callable returning whether the session is connected. While it + isn't, the session is already reconnecting, so timeouts don't restart it. """ self._consecutive_timeouts = 0 + self._timed_out_devices: set[str] = set() + self._devices: dict[str, _DeviceHealth] = {} self._restart = restart + self._is_connected = is_connected self._last_restart: datetime.datetime | None = None - async def on_success(self) -> None: - """Record a successful communication event.""" + def _device(self, device_id: str) -> _DeviceHealth: + """Return the state of a device, creating it on first use.""" + return self._devices.setdefault(device_id, _DeviceHealth()) + + def _reset_timeouts(self) -> None: + """Forget the timeouts counted so far.""" self._consecutive_timeouts = 0 + self._timed_out_devices.clear() + for device in self._devices.values(): + device.consecutive_timeouts = 0 - async def on_timeout(self) -> None: - """Record a timeout event. + def on_connected(self) -> None: + """Forget the timeouts counted on a previous connection.""" + self._reset_timeouts() + + async def on_success(self, device_id: str) -> None: + """Record a successful communication event for a device.""" + self._consecutive_timeouts = 0 + self._timed_out_devices.clear() + device = self._device(device_id) + device.consecutive_timeouts = 0 + device.restart_cooldown_start = None + device.restart_cooldown = None + + async def on_timeout(self, device_id: str) -> None: + """Record a timeout event for a device. This may trigger a restart of the MQTT session if too many timeouts have occurred in succession. """ - self._consecutive_timeouts += 1 - if self._consecutive_timeouts >= TIMEOUT_THRESHOLD: - now = datetime.datetime.now(datetime.UTC) - since_last = (now - self._last_restart) if self._last_restart else None - if since_last is None or since_last >= RESTART_COOLDOWN: + now = datetime.datetime.now(datetime.UTC) + device = self._device(device_id) + device.consecutive_timeouts += 1 + cooldown_start, cooldown = device.restart_cooldown_start, device.restart_cooldown + in_cooldown = cooldown_start is not None and cooldown is not None and now - cooldown_start < cooldown + # A device in its restart cooldown may be offline, so its timeouts don't implicate the session. + if not in_cooldown: + self._consecutive_timeouts += 1 + self._timed_out_devices.add(device_id) + + # Only timeouts from several devices implicate the session itself. + session_unhealthy = self._consecutive_timeouts >= TIMEOUT_THRESHOLD and len(self._timed_out_devices) > 1 + if not session_unhealthy and device.consecutive_timeouts < TIMEOUT_THRESHOLD: + return + + device_name = redact_device_uid(device_id) + if not self._is_connected(): + _LOGGER.debug("Not restarting MQTT session for device %s, it is already reconnecting", device_name) + return + + since_last = (now - self._last_restart) if self._last_restart else None + if since_last is not None and since_last < RESTART_COOLDOWN: + _LOGGER.debug( + "Not restarting MQTT session for device %s, last restart was %s ago", device_name, _duration(since_last) + ) + return + + if session_unhealthy: + reason = f"{self._consecutive_timeouts} timeouts in a row across {len(self._timed_out_devices)} devices" + else: + if in_cooldown and cooldown_start is not None and cooldown is not None: _LOGGER.debug( - "Restarting MQTT session after %d consecutive timeouts (duration since last restart %s)", - self._consecutive_timeouts, - since_last, + "Not restarting MQTT session for device %s, it may restart it again in %s", + device_name, + _duration(cooldown_start + cooldown - now), ) - await self._restart() - self._last_restart = now - self._consecutive_timeouts = 0 + return + device.restart_cooldown_start = now + device.restart_cooldown = ( + min(cooldown * 2, MAX_DEVICE_RESTART_COOLDOWN) if cooldown is not None else DEVICE_RESTART_COOLDOWN + ) + reason = ( + f"device {device_name} timed out {device.consecutive_timeouts} times in a row; " + f"it may restart the session again in {device.restart_cooldown} if it keeps failing" + ) + + _LOGGER.info( + "Restarting MQTT session: %s (last restart: %s)", + reason, + f"{_duration(since_last)} ago" if since_last is not None else "never", + ) + # Update the state before awaiting, so timeouts arriving meanwhile don't restart again. + self._last_restart = now + self._reset_timeouts() + await self._restart() + + +class DeviceHealthManager: + """Reports the outcome of a single device's MQTT requests to the session's health manager.""" + + def __init__(self, health_manager: HealthManager, device_id: str) -> None: + """Initialize the device health manager.""" + self._health_manager = health_manager + self._device_id = device_id + + async def on_success(self) -> None: + """Record a successful communication event.""" + await self._health_manager.on_success(self._device_id) + + async def on_timeout(self) -> None: + """Record a timeout event.""" + await self._health_manager.on_timeout(self._device_id) diff --git a/roborock/mqtt/roborock_session.py b/roborock/mqtt/roborock_session.py index ec52d1b36..48cb30ed7 100644 --- a/roborock/mqtt/roborock_session.py +++ b/roborock/mqtt/roborock_session.py @@ -79,10 +79,11 @@ def __init__( self._client_lock = asyncio.Lock() self._listeners: CallbackMap[str, bytes] = CallbackMap(_LOGGER) self._connection_task: asyncio.Task[None] | None = None + self._restart_requested = False self._topic_idle_timeout = topic_idle_timeout self._idle_timers: dict[str, asyncio.Task[None]] = {} self._diagnostics = params.diagnostics - self._health_manager = HealthManager(self.restart) + self._health_manager = HealthManager(self.restart, is_connected=lambda: self._healthy) self._unauthorized_hook = params.unauthorized_hook @property @@ -145,12 +146,15 @@ async def close(self) -> None: async def restart(self) -> None: """Force the session to disconnect and reconnect. - The active connection task will be cancelled and restarted in the background, retried by - the reconnect loop. This is a no-op if there is no active connection. + The active connection task will be cancelled and restarted in the background by the + reconnect loop. If the session was connected, the broker was reachable, so the first + reconnect attempt is made right away instead of after the backoff interval. This is a + no-op if there is no active connection. """ _LOGGER.info("Forcing MQTT session restart") self._diagnostics.increment("restart") - if self._connection_task: + if self._connection_task and not self._connection_task.done(): + self._restart_requested = self._healthy self._connection_task.cancel() else: _LOGGER.debug("No message loop task to cancel") @@ -175,6 +179,7 @@ async def _run_reconnect_loop(self, start_future: asyncio.Future[None] | None) - self._healthy = False start_future = None + restart_requested, self._restart_requested = self._restart_requested, False if self._stop: _LOGGER.debug("MQTT session closed, stopping retry loop") return @@ -188,6 +193,10 @@ async def _run_reconnect_loop(self, start_future: asyncio.Future[None] | None) - return self._backoff = MIN_BACKOFF_INTERVAL continue + if restart_requested: + _LOGGER.info("MQTT session disconnected for a restart, reconnecting now") + self._diagnostics.increment("reconnect_restart") + continue _LOGGER.info("MQTT session disconnected, retrying in %s seconds", self._backoff.total_seconds()) self._diagnostics.increment("reconnect_wait") await asyncio.sleep(self._backoff.total_seconds()) @@ -205,6 +214,7 @@ async def _run_connection(self, start_future: asyncio.Future[None] | None) -> No async with self._mqtt_client(self._params) as client: self._backoff = MIN_BACKOFF_INTERVAL self._healthy = True + self._health_manager.on_connected() _LOGGER.info("MQTT Session connected.") if start_future and not start_future.done(): start_future.set_result(None) diff --git a/roborock/testing/channel.py b/roborock/testing/channel.py index 65a36bc79..3e9f4f7d1 100644 --- a/roborock/testing/channel.py +++ b/roborock/testing/channel.py @@ -11,7 +11,7 @@ from unittest.mock import AsyncMock, MagicMock from roborock.devices.transport.channel import Channel -from roborock.mqtt.health_manager import HealthManager +from roborock.mqtt.health_manager import DeviceHealthManager, HealthManager from roborock.mqtt.session import MqttQos from roborock.protocols.v1_protocol import LocalProtocolVersion from roborock.roborock_message import RoborockMessage @@ -86,7 +86,7 @@ def __init__(self, is_local: bool = False): self.protocol_version = LocalProtocolVersion.V1 self.restart = AsyncMock() - self.health_manager = HealthManager(self.restart) + self.health_manager = DeviceHealthManager(HealthManager(self.restart), "fake-device") async def _connect(self) -> None: self._is_connected = True diff --git a/tests/devices/transport/test_mqtt_channel.py b/tests/devices/transport/test_mqtt_channel.py index 55e7b8bbb..dffde3fd1 100644 --- a/tests/devices/transport/test_mqtt_channel.py +++ b/tests/devices/transport/test_mqtt_channel.py @@ -10,6 +10,7 @@ from roborock.data import HomeData, UserData from roborock.devices.transport.mqtt_channel import MqttChannel +from roborock.mqtt.health_manager import HealthManager from roborock.mqtt.session import MqttParams from roborock.protocol import create_mqtt_decoder, create_mqtt_encoder from roborock.roborock_message import RoborockMessage, RoborockMessageProtocol @@ -268,3 +269,22 @@ def failing_callback(message: RoborockMessage) -> None: # Unsubscribe all remaining subscribers unsub1() unsub2() + + +async def test_health_is_tracked_per_device(mqtt_session: Mock) -> None: + """Test that a working device on the session does not hide a failing device's timeouts.""" + restart = AsyncMock() + mqtt_session.health_manager = HealthManager(restart) + failing, working = ( + MqttChannel( + mqtt_session, duid=duid, local_key=TEST_LOCAL_KEY, rriot=USER_DATA.rriot, mqtt_params=TEST_MQTT_PARAMS + ) + for duid in ("failing", "working") + ) + + for _ in range(3): + restart.assert_not_called() + await working.health_manager.on_success() + await failing.health_manager.on_timeout() + + restart.assert_called_once() diff --git a/tests/mqtt/test_health_manager.py b/tests/mqtt/test_health_manager.py index 94b253b4b..b3ce67386 100644 --- a/tests/mqtt/test_health_manager.py +++ b/tests/mqtt/test_health_manager.py @@ -1,73 +1,298 @@ """Tests for the health manager.""" +import asyncio import datetime -from unittest.mock import AsyncMock, patch +import logging +from collections.abc import Generator +from unittest.mock import AsyncMock, Mock, patch -from roborock.mqtt.health_manager import HealthManager +import pytest + +from roborock.mqtt.health_manager import ( + DEVICE_RESTART_COOLDOWN, + MAX_DEVICE_RESTART_COOLDOWN, + DeviceHealthManager, + HealthManager, +) + +DEVICE_ID = "device-1" +START = datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=datetime.UTC) + + +@pytest.fixture(name="mock_datetime") +def mock_datetime_fixture() -> Generator[Mock, None, None]: + """Freeze the health manager's clock at START.""" + with patch("roborock.mqtt.health_manager.datetime") as mock_datetime: + mock_datetime.timedelta = datetime.timedelta + mock_datetime.UTC = datetime.UTC + mock_datetime.datetime.now.return_value = START + yield mock_datetime + + +async def time_out(device: DeviceHealthManager, times: int = 3) -> None: + """Report several timeouts in a row for a device.""" + for _ in range(times): + await device.on_timeout() async def test_health_manager_restart_called_after_timeouts() -> None: """Test that the health manager calls restart after consecutive timeouts.""" restart = AsyncMock() - health_manager = HealthManager(restart=restart) + health_manager = DeviceHealthManager(HealthManager(restart=restart), DEVICE_ID) - await health_manager.on_timeout() - await health_manager.on_timeout() + await time_out(health_manager, 2) restart.assert_not_called() await health_manager.on_timeout() restart.assert_called_once() -async def test_health_manager_success_resets_counter() -> None: - """Test that a successful message resets the timeout counter.""" +async def test_scattered_timeouts_do_not_restart() -> None: + """Test that timeouts interleaved with the device's own responses don't restart the session.""" + restart = AsyncMock() + health_manager = DeviceHealthManager(HealthManager(restart=restart), DEVICE_ID) + + for _ in range(5): + await time_out(health_manager, 2) + await health_manager.on_success() + + restart.assert_not_called() + + +async def test_other_device_success_does_not_hide_failing_device() -> None: + """Test that one device's timeouts restart the session while another device works.""" restart = AsyncMock() health_manager = HealthManager(restart=restart) + failing = DeviceHealthManager(health_manager, "failing") + working = DeviceHealthManager(health_manager, "working") - await health_manager.on_timeout() - await health_manager.on_timeout() + for _ in range(2): + await failing.on_timeout() + await working.on_success() restart.assert_not_called() - await health_manager.on_success() + await failing.on_timeout() + restart.assert_called_once() - await health_manager.on_timeout() - await health_manager.on_timeout() + +async def test_device_needs_timeouts_of_its_own() -> None: + """Test that timeouts of other devices don't count towards a device's restart.""" + restart = AsyncMock() + health_manager = HealthManager(restart=restart) + device = DeviceHealthManager(health_manager, DEVICE_ID) + other = DeviceHealthManager(health_manager, "other") + + await device.on_timeout() + await other.on_success() + await other.on_timeout() + await other.on_success() + await device.on_timeout() restart.assert_not_called() - await health_manager.on_timeout() + +async def test_timeouts_across_devices_restart_session() -> None: + """Test that timeouts spread across devices still count towards the session.""" + restart = AsyncMock() + health_manager = HealthManager(restart=restart) + + await DeviceHealthManager(health_manager, "device-1").on_timeout() + await DeviceHealthManager(health_manager, "device-2").on_timeout() + restart.assert_not_called() + + await DeviceHealthManager(health_manager, "device-3").on_timeout() restart.assert_called_once() -async def test_cooldown() -> None: - """Test that the health manager respects the restart cooldown.""" +async def test_timeouts_before_a_reconnect_do_not_count() -> None: + """Test that a new connection is not restarted because of the old connection's timeouts.""" restart = AsyncMock() health_manager = HealthManager(restart=restart) + device = DeviceHealthManager(health_manager, DEVICE_ID) - with patch("roborock.mqtt.health_manager.datetime") as mock_datetime: - now = datetime.datetime(2023, 1, 1, 12, 0, 0) - mock_datetime.datetime.now.return_value = now + await time_out(device, 2) + health_manager.on_connected() - # Trigger first restart - await health_manager.on_timeout() - await health_manager.on_timeout() - await health_manager.on_timeout() - restart.assert_called_once() - restart.reset_mock() + await time_out(device, 2) + restart.assert_not_called() - # Advance time but stay within cooldown (30 mins) - mock_datetime.datetime.now.return_value = now + datetime.timedelta(minutes=10) + await device.on_timeout() + restart.assert_called_once() - # Trigger timeouts again - await health_manager.on_timeout() - await health_manager.on_timeout() - await health_manager.on_timeout() - restart.assert_not_called() - # Advance time past cooldown - mock_datetime.datetime.now.return_value = now + datetime.timedelta(minutes=31) +async def test_restart_clears_counters_of_all_devices(mock_datetime: Mock) -> None: + """Test that every device starts counting again after a session restart.""" + restart = AsyncMock() + health_manager = HealthManager(restart=restart) + first = DeviceHealthManager(health_manager, "first") + second = DeviceHealthManager(health_manager, "second") - # Trigger timeouts again - await health_manager.on_timeout() - await health_manager.on_timeout() - await health_manager.on_timeout() + await time_out(second, 2) + await time_out(first) + restart.assert_called_once() + restart.reset_mock() + + # The restart gave "second" a new connection, so its earlier timeouts no longer count. + mock_datetime.datetime.now.return_value = START + datetime.timedelta(minutes=31) + await first.on_success() + await second.on_timeout() + restart.assert_not_called() + + +async def test_cooldown(mock_datetime: Mock) -> None: + """Test that the session is not restarted more often than the restart cooldown.""" + restart = AsyncMock() + health_manager = HealthManager(restart=restart) + first = DeviceHealthManager(health_manager, "first") + second = DeviceHealthManager(health_manager, "second") + + async def time_out_both() -> None: + for device in (first, second, first): + await device.on_timeout() + + await time_out_both() + restart.assert_called_once() + restart.reset_mock() + + mock_datetime.datetime.now.return_value = START + datetime.timedelta(minutes=10) + await time_out_both() + restart.assert_not_called() + + mock_datetime.datetime.now.return_value = START + datetime.timedelta(minutes=31) + await time_out_both() + restart.assert_called_once() + + +async def test_single_failing_device_cooldown_grows(mock_datetime: Mock) -> None: + """Test that a device that stays unreachable restarts a working session less and less often.""" + restart = AsyncMock() + health_manager = HealthManager(restart=restart) + failing = DeviceHealthManager(health_manager, "failing") + working = DeviceHealthManager(health_manager, "working") + + async def time_out_while_session_works() -> None: + for _ in range(3): + await working.on_success() + await failing.on_timeout() + + now = START + await time_out_while_session_works() + restart.assert_called_once() + + # After the first restart the interval doubles from an hour up to the maximum. + for cooldown in ( + DEVICE_RESTART_COOLDOWN, + 2 * DEVICE_RESTART_COOLDOWN, + 4 * DEVICE_RESTART_COOLDOWN, + MAX_DEVICE_RESTART_COOLDOWN, + MAX_DEVICE_RESTART_COOLDOWN, + ): + restart.reset_mock() + mock_datetime.datetime.now.return_value = now + cooldown - datetime.timedelta(minutes=1) + await time_out_while_session_works() + restart.assert_not_called() + + now += cooldown + mock_datetime.datetime.now.return_value = now + await time_out_while_session_works() restart.assert_called_once() + + +async def test_response_resets_device_cooldown(mock_datetime: Mock) -> None: + """Test that a device that responds again may restart the session after the session cooldown.""" + restart = AsyncMock() + device = DeviceHealthManager(HealthManager(restart=restart), DEVICE_ID) + + await time_out(device) + restart.assert_called_once() + restart.reset_mock() + + await device.on_success() + mock_datetime.datetime.now.return_value = START + datetime.timedelta(minutes=31) + await time_out(device) + restart.assert_called_once() + + +async def test_device_in_cooldown_does_not_count_towards_session(mock_datetime: Mock) -> None: + """Test that an offline device in its cooldown and a stray timeout elsewhere don't restart the session.""" + restart = AsyncMock() + health_manager = HealthManager(restart=restart) + offline = DeviceHealthManager(health_manager, "offline") + flaky = DeviceHealthManager(health_manager, "flaky") + + await time_out(offline) + restart.assert_called_once() + restart.reset_mock() + + mock_datetime.datetime.now.return_value = START + datetime.timedelta(minutes=31) + await time_out(offline, 2) + await flaky.on_timeout() + restart.assert_not_called() + + +async def test_timeouts_from_several_devices_bypass_device_cooldown(mock_datetime: Mock) -> None: + """Test that a session failing for other devices restarts during one device's cooldown.""" + restart = AsyncMock() + health_manager = HealthManager(restart=restart) + offline = DeviceHealthManager(health_manager, "offline") + first = DeviceHealthManager(health_manager, "first") + second = DeviceHealthManager(health_manager, "second") + + await time_out(offline) + restart.assert_called_once() + restart.reset_mock() + + mock_datetime.datetime.now.return_value = START + datetime.timedelta(minutes=31) + for device in (first, offline, second): + await device.on_timeout() + restart.assert_not_called() + + await first.on_timeout() + restart.assert_called_once() + + +async def test_no_restart_while_session_reconnects() -> None: + """Test that timeouts while the session is already reconnecting don't restart it.""" + restart = AsyncMock() + connected = False + device = DeviceHealthManager(HealthManager(restart=restart, is_connected=lambda: connected), DEVICE_ID) + + await time_out(device) + restart.assert_not_called() + + connected = True + await device.on_timeout() + restart.assert_called_once() + + +async def test_concurrent_timeouts_restart_once() -> None: + """Test that timeouts arriving while the session is restarting don't restart it again.""" + restarted = asyncio.Event() + calls = 0 + + async def slow_restart() -> None: + nonlocal calls + calls += 1 + await restarted.wait() + + device = DeviceHealthManager(HealthManager(restart=slow_restart), DEVICE_ID) + + await time_out(device, 2) + pending = [asyncio.create_task(device.on_timeout()) for _ in range(5)] + await asyncio.sleep(0) + restarted.set() + await asyncio.gather(*pending) + + assert calls == 1 + + +async def test_restart_is_logged(caplog: pytest.LogCaptureFixture, mock_datetime: Mock) -> None: + """Test that a restart caused by one device is logged with its pacing.""" + caplog.set_level(logging.INFO, logger="roborock.mqtt.health_manager") + device = DeviceHealthManager(HealthManager(restart=AsyncMock()), DEVICE_ID) + + await time_out(device) + + assert [record.getMessage() for record in caplog.records] == [ + "Restarting MQTT session: device ******ice-1 timed out 3 times in a row; " + "it may restart the session again in 1:00:00 if it keeps failing (last restart: never)" + ] diff --git a/tests/mqtt/test_roborock_session.py b/tests/mqtt/test_roborock_session.py index bd8eccf22..879df6eff 100644 --- a/tests/mqtt/test_roborock_session.py +++ b/tests/mqtt/test_roborock_session.py @@ -541,6 +541,159 @@ def succeed_then_fail_unauthorized() -> Any: await session.close() +async def test_restart_reconnects_without_backoff( + mock_aenter_client: AsyncMock, + mqtt_client_lite: AsyncMock, +) -> None: + """Test that a forced restart reconnects right away instead of waiting for the backoff.""" + params = copy.deepcopy(FAKE_PARAMS) + params.diagnostics = Diagnostics() + with patch("roborock.mqtt.roborock_session.MIN_BACKOFF_INTERVAL", datetime.timedelta(hours=1)): + session = await create_mqtt_session(params) + await session.subscribe("topic-1", Subscriber().append) + + try: + await session.restart() + async with asyncio.timeout(1): + while mock_aenter_client.await_count < 2: + await asyncio.sleep(0.01) + assert params.diagnostics.as_dict().get("reconnect_restart") == 1 + assert "reconnect_wait" not in params.diagnostics.as_dict() + finally: + await session.close() + + +async def test_failed_reconnect_after_restart_waits_for_backoff( + mock_aenter_client: AsyncMock, + mqtt_client_lite: AsyncMock, +) -> None: + """Test that only the first reconnect attempt after a forced restart skips the backoff.""" + params = copy.deepcopy(FAKE_PARAMS) + params.diagnostics = Diagnostics() + params.unauthorized_hook = Mock() + mock_aenter_client.side_effect = [mqtt_client_lite, aiomqtt.MqttCodeError(rc=135)] + with patch("roborock.mqtt.roborock_session.MIN_BACKOFF_INTERVAL", datetime.timedelta(hours=1)): + session = await create_mqtt_session(params) + await session.subscribe("topic-1", Subscriber().append) + + try: + await session.restart() + async with asyncio.timeout(1): + while "reconnect_wait" not in params.diagnostics.as_dict(): + await asyncio.sleep(0.01) + assert mock_aenter_client.await_count == 2 + params.unauthorized_hook.assert_called_once() + finally: + await session.close() + + +async def test_restart_while_connecting_waits_for_backoff( + mock_aenter_client: AsyncMock, + mqtt_client_lite: AsyncMock, +) -> None: + """Test that a restart before the connection is established doesn't skip the backoff.""" + params = copy.deepcopy(FAKE_PARAMS) + params.diagnostics = Diagnostics() + connecting = asyncio.Event() + + async def connect_slowly(*args: Any) -> AsyncMock: + if mock_aenter_client.await_count == 2: + connecting.set() + await asyncio.sleep(10) + return mqtt_client_lite + + mock_aenter_client.side_effect = connect_slowly + with patch("roborock.mqtt.roborock_session.MIN_BACKOFF_INTERVAL", datetime.timedelta(hours=1)): + session = await create_mqtt_session(params) + await session.subscribe("topic-1", Subscriber().append) + + try: + await session.restart() + async with asyncio.timeout(1): + await connecting.wait() + await session.restart() + async with asyncio.timeout(1): + while "reconnect_wait" not in params.diagnostics.as_dict(): + await asyncio.sleep(0.01) + assert params.diagnostics.as_dict().get("reconnect_restart") == 1 + finally: + await session.close() + + +async def test_disconnect_waits_for_backoff( + mock_aenter_client: AsyncMock, + message_iterator: FakeAsyncIterator, + mqtt_client_lite: AsyncMock, +) -> None: + """Test that a connection lost without a forced restart still waits before reconnecting.""" + params = copy.deepcopy(FAKE_PARAMS) + params.diagnostics = Diagnostics() + message_iterator.loop = False + with patch("roborock.mqtt.roborock_session.MIN_BACKOFF_INTERVAL", datetime.timedelta(hours=1)): + session = await create_mqtt_session(params) + await session.subscribe("topic-1", Subscriber().append) + + try: + await asyncio.sleep(0.1) + assert mock_aenter_client.await_count == 1 + assert params.diagnostics.as_dict().get("reconnect_wait", 0) >= 1 + assert "reconnect_restart" not in params.diagnostics.as_dict() + finally: + await session.close() + + +async def test_no_health_restart_while_reconnecting( + message_iterator: FakeAsyncIterator, + mqtt_client_lite: AsyncMock, +) -> None: + """Test that timeouts while the session waits to reconnect don't count as a restart.""" + params = copy.deepcopy(FAKE_PARAMS) + params.diagnostics = Diagnostics() + message_iterator.loop = False + with patch("roborock.mqtt.roborock_session.MIN_BACKOFF_INTERVAL", datetime.timedelta(hours=1)): + session = await create_mqtt_session(params) + await session.subscribe("topic-1", Subscriber().append) + + try: + async with asyncio.timeout(1): + while session.connected: + await asyncio.sleep(0.01) + for _ in range(3): + await session.health_manager.on_timeout("device-1") + assert "restart" not in params.diagnostics.as_dict() + finally: + await session.close() + + +async def test_reconnect_resets_health_timeouts( + mock_aenter_client: AsyncMock, + message_iterator: FakeAsyncIterator, + mqtt_client_lite: AsyncMock, +) -> None: + """Test that timeouts counted before a reconnect don't restart the new connection.""" + params = copy.deepcopy(FAKE_PARAMS) + params.diagnostics = Diagnostics() + session = await create_mqtt_session(params) + await session.subscribe("topic-1", Subscriber().append) + health_manager = session.health_manager + + try: + await health_manager.on_timeout("device-1") + await health_manager.on_timeout("device-1") + + # The connection drops and the session reconnects on its own. + message_iterator.loop = False + async with asyncio.timeout(1): + while mock_aenter_client.await_count < 2: + await asyncio.sleep(0.01) + message_iterator.loop = True + + await health_manager.on_timeout("device-1") + assert "restart" not in params.diagnostics.as_dict() + finally: + await session.close() + + async def test_session_defers_reconnect_when_idle( mock_aenter_client: AsyncMock, message_iterator: FakeAsyncIterator,