From d4f666d42fcdaa4532da41b0cade2aa730d051f8 Mon Sep 17 00:00:00 2001 From: Matthias Alphart Date: Tue, 27 Oct 2026 16:17:02 +0100 Subject: [PATCH] Stop the KNX telegram store when the config entry setup fails (#188884) Co-authored-by: Claude Fable 5.1 --- homeassistant/components/knx/knx_module.py | 3 ++ homeassistant/components/knx/telegrams.py | 5 ++- tests/components/knx/test_telegrams.py | 40 ++++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/knx/knx_module.py b/homeassistant/components/knx/knx_module.py index f0679fadfe6a..cb9b06ca4f98 100644 --- a/homeassistant/components/knx/knx_module.py +++ b/homeassistant/components/knx/knx_module.py @@ -127,6 +127,9 @@ class KNXModule: self.entry.async_on_unload( self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.stop) ) + # A setup that fails after the store started initializing in the + # background is not unloaded, so the entry tears the store down itself. + self.entry.async_on_unload(self.telegrams.stop) async def start(self) -> None: """Start XKNX object. Connect to tunneling or Routing device.""" diff --git a/homeassistant/components/knx/telegrams.py b/homeassistant/components/knx/telegrams.py index 3b8c77a99359..10742f993b71 100644 --- a/homeassistant/components/knx/telegrams.py +++ b/homeassistant/components/knx/telegrams.py @@ -306,7 +306,7 @@ class Telegrams: _LOGGER.debug("Evicted %d expired KNX telegrams from storage", deleted) async def stop(self) -> None: - """Stop history store.""" + """Stop history store. Safe to call more than once.""" if self._store_init_task is not None: self._store_init_task.cancel() with contextlib.suppress(asyncio.CancelledError): @@ -327,8 +327,11 @@ class Telegrams: _LOGGER.warning( "Database error stopping KNX telegram storage backend: %s", err ) + return except Exception as err: # noqa: BLE001 _LOGGER.warning("Error stopping KNX telegram storage backend: %s", err) + return + self.store = None def _xknx_telegram_cb(self, telegram: Telegram) -> None: """Handle incoming and outgoing telegrams from xknx.""" diff --git a/tests/components/knx/test_telegrams.py b/tests/components/knx/test_telegrams.py index 5c478a90d551..86f6ce83e89c 100644 --- a/tests/components/knx/test_telegrams.py +++ b/tests/components/knx/test_telegrams.py @@ -21,6 +21,7 @@ from pytest_homeassistant.common import ( async_fire_time_changed, async_load_json_object_fixture, ) +from xknx.exceptions import XKNXException from xknx.telegram import Telegram, TelegramDirection from xknx.telegram.address import GroupAddress, IndividualAddress from xknx.telegram.apci import GroupValueRead @@ -38,7 +39,9 @@ from homeassistant.components.knx.telegrams import ( FLUSH_INTERVAL_SECONDS_POSTGRES, FLUSH_INTERVAL_SECONDS_SQLITE, TelegramDict, + Telegrams, ) +from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from homeassistant.util import dt as dt_util @@ -283,6 +286,43 @@ async def test_stop_cancels_in_flight_store_init( assert telegrams_module._uninitialized_store is None +async def test_failed_setup_stops_the_store_initialization( + hass: HomeAssistant, + knx: KNXTestKit, +) -> None: + """A setup that fails after the store started initializing tears the store down. + + The entry is not unloaded on a failed setup, and the retry builds a new store + on the same database, so the first initialization must not keep running. + """ + handlers: list[Telegrams] = [] + original_async_start = Telegrams.async_start + + def recording_async_start(self: Telegrams) -> None: + handlers.append(self) + original_async_start(self) + + async def hanging_initialize(self: BufferedSqliteStore) -> None: + await asyncio.Event().wait() + + with ( + patch.object(Telegrams, "async_start", recording_async_start), + patch.object(BufferedSqliteStore, "initialize", hanging_initialize), + patch("xknx.xknx.XKNX.start", side_effect=XKNXException("no gateway")), + ): + await knx.setup_integration( + real_telegram_store=True, wait_for_telegram_store=False + ) + + assert knx.mock_config_entry.state is ConfigEntryState.SETUP_RETRY + (telegrams,) = handlers + assert telegrams._store_init_task is None + assert telegrams._uninitialized_store is None + assert telegrams.store is None + # The entry's unload hooks and the module's stop may both run; the second is a no-op. + await telegrams.stop() + + async def test_migrate_telegrams_from_json( hass: HomeAssistant, knx: KNXTestKit,