diff --git a/homeassistant/components/knx/telegrams.py b/homeassistant/components/knx/telegrams.py index d4c838ee066d..d9bfbc62bf0a 100644 --- a/homeassistant/components/knx/telegrams.py +++ b/homeassistant/components/knx/telegrams.py @@ -61,15 +61,16 @@ FLUSH_INTERVAL_SECONDS_POSTGRES = 1 MAX_BUFFER_TELEGRAMS_SQLITE = FLUSH_INTERVAL_SECONDS_SQLITE * 50 * 4 MAX_BUFFER_TELEGRAMS_POSTGRES = FLUSH_INTERVAL_SECONDS_POSTGRES * 50 * 4 -# Timeout for the migration probe and store initialization, so an unreachable -# database cannot block KNX setup until the driver/OS connection timeout expires. +# Timeout for the migration probe and initialization of a PostgreSQL store, so an +# unreachable database cannot block KNX setup until the driver/OS connection timeout +# expires. SQLite runs unbounded: cancelling a slow startup pass only restarts it. STORE_INIT_TIMEOUT = 10 -# When store initialization times out during startup (busy event loop, cold or large -# database on low-power hardware), the failure is usually transient. Instead of giving -# up until the next reload, retry in the background with a capped backoff. This many -# retries are allowed on top of the initial attempt, i.e. the store is only disabled -# after STORE_INIT_MAX_RETRIES + 1 consecutive timeouts. +# When PostgreSQL store initialization times out during startup (busy event loop, +# slow network), the failure is usually transient. Instead of giving up until the +# next reload, retry in the background with a capped backoff. This many retries +# are allowed on top of the initial attempt, i.e. the store is only disabled after +# STORE_INIT_MAX_RETRIES + 1 consecutive timeouts. STORE_INIT_RETRY_BACKOFF = (15, 30, 60, 120, 300, 300) STORE_INIT_MAX_RETRIES = len(STORE_INIT_RETRY_BACKOFF) @@ -167,7 +168,7 @@ class Telegrams: if self._uninitialized_store is None: return try: - async with asyncio.timeout(STORE_INIT_TIMEOUT): + async with self._store_init_timeout(): needs_migration = await self._uninitialized_store.needs_migration() if needs_migration: _LOGGER.warning( @@ -180,7 +181,7 @@ class Telegrams: "Initializing KNX telegram storage backend '%s'", self.backend, ) - async with asyncio.timeout(STORE_INIT_TIMEOUT): + async with self._store_init_timeout(): await self._uninitialized_store.initialize() _LOGGER.info( "Successfully initialized KNX telegram storage backend '%s'", @@ -268,6 +269,17 @@ class Telegrams: self.last_ga_telegrams[t_dict["destination"]] = t_dict _LOGGER.debug("Hydrated %d unique telegrams from store", len(result)) + def _store_init_timeout(self) -> contextlib.AbstractAsyncContextManager[Any]: + """Bound store initialization for PostgreSQL only. + + A SQLite startup pass that takes longer than the timeout is not helped by + cancelling it: the next attempt starts over, so a large database on slow + hardware would never finish (XKNX/knx-telegram-store#76). + """ + if self.backend == KNX_TELEGRAM_BACKEND_POSTGRES: + return asyncio.timeout(STORE_INIT_TIMEOUT) + return contextlib.nullcontext() + async def _async_retry_load_history(self, now: datetime) -> None: """Retry telegram store initialization after a transient timeout.""" self._store_init_retry_unsub = None diff --git a/tests/components/knx/test_telegrams.py b/tests/components/knx/test_telegrams.py index 4047abfe4ce2..758ce1df7a19 100644 --- a/tests/components/knx/test_telegrams.py +++ b/tests/components/knx/test_telegrams.py @@ -8,7 +8,12 @@ from datetime import datetime from unittest.mock import AsyncMock, patch from freezegun.api import FrozenDateTimeFactory -from knx_telegram_store import KnxTelegramStoreException, StoredTelegram, TelegramQuery +from knx_telegram_store import ( + BufferedSqliteStore, + KnxTelegramStoreException, + StoredTelegram, + TelegramQuery, +) import pytest from xknx.telegram import Telegram, TelegramDirection from xknx.telegram.address import GroupAddress, IndividualAddress @@ -205,33 +210,79 @@ async def test_sqlite_store_is_told_the_configured_timezone( assert store._legacy_timestamp_timezone is dt_util.get_default_time_zone() -async def test_store_telegram_history_needs_migration_timeout( +@pytest.mark.parametrize( + "hanging_method", + [ + pytest.param("needs_migration", id="needs_migration"), + pytest.param("initialize", id="initialize"), + ], +) +async def test_postgres_store_init_timeout( hass: HomeAssistant, knx: KNXTestKit, issue_registry: ir.IssueRegistry, + hanging_method: str, ) -> None: - """Test store init aborts when needs_migration times out and retries are off.""" + """A hanging PostgreSQL store init is cut off by the timeout and aborts when retries are off.""" - async def hanging_probe() -> bool: + async def hang() -> None: await asyncio.Event().wait() - return False + knx.mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + knx.mock_config_entry, + options=knx.mock_config_entry.options + | { + CONF_KNX_TELEGRAM_DB_BACKEND: KNX_TELEGRAM_BACKEND_POSTGRES, + CONF_KNX_TELEGRAM_DB_POSTGRES_DSN: "postgresql://user:secret@db.local:5432/knx", + }, + ) + mock_store = AsyncMock() + mock_store.needs_migration.return_value = False + getattr(mock_store, hanging_method).side_effect = hang with ( patch("homeassistant.components.knx.telegrams.STORE_INIT_TIMEOUT", 0.05), patch("homeassistant.components.knx.telegrams.STORE_INIT_MAX_RETRIES", 0), patch( - "knx_telegram_store.BufferedSqliteStore.needs_migration", - side_effect=hanging_probe, + "homeassistant.components.knx.telegrams.BufferedPostgresStore", + return_value=mock_store, ), + ): + await knx.setup_integration(add_entry_to_hass=False, real_telegram_store=True) + + telegrams_module = hass.data[KNX_MODULE_KEY].telegrams + assert telegrams_module.store is None + assert ( + issue_registry.async_get_issue(DOMAIN, REPAIR_ISSUE_TELEGRAM_BACKEND_ERROR) + is not None + ) + + +async def test_sqlite_store_init_is_not_cut_off_by_timeout( + hass: HomeAssistant, + knx: KNXTestKit, + issue_registry: ir.IssueRegistry, +) -> None: + """A slow SQLite store init runs to completion instead of being cancelled and retried.""" + original_initialize = BufferedSqliteStore.initialize + + async def slow_initialize(self: BufferedSqliteStore) -> None: + await asyncio.sleep(0.2) + await original_initialize(self) + + with ( + patch("homeassistant.components.knx.telegrams.STORE_INIT_TIMEOUT", 0.05), + patch.object(BufferedSqliteStore, "initialize", slow_initialize), ): await knx.setup_integration(real_telegram_store=True) telegrams_module = hass.data[KNX_MODULE_KEY].telegrams - assert telegrams_module.store is None - - # Check that the repair issue was created - issue = issue_registry.async_get_issue(DOMAIN, REPAIR_ISSUE_TELEGRAM_BACKEND_ERROR) - assert issue is not None + assert telegrams_module.store is not None + assert telegrams_module._store_init_retry_unsub is None + assert ( + issue_registry.async_get_issue(DOMAIN, REPAIR_ISSUE_TELEGRAM_BACKEND_ERROR) + is None + ) async def test_store_init_timeout_retries_and_succeeds(