From 07ba64a6d867fa16df4a76d6ee6620b4f249396c Mon Sep 17 00:00:00 2001 From: Raman Gupta <7243222+raman325@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:01:28 -0500 Subject: [PATCH] Retry recorder startup when schema validation hits a database error (#192615) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/recorder/core.py | 44 +++++++++++++----- tests/components/recorder/test_init.py | 55 ++++++++++++++++++++++- 2 files changed, 86 insertions(+), 13 deletions(-) diff --git a/homeassistant/components/recorder/core.py b/homeassistant/components/recorder/core.py index 7c407ec0e195..1eb01f86bdd2 100644 --- a/homeassistant/components/recorder/core.py +++ b/homeassistant/components/recorder/core.py @@ -778,17 +778,9 @@ class Recorder(threading.Thread): self.thread_id = thread_id self.recorder_and_worker_thread_ids.add(thread_id) - setup_result = self._setup_recorder() - - if not setup_result: - _LOGGER.error("Recorder setup failed, recorder shutting down") - # Give up if we could not connect - return - - schema_status = migration.validate_db_schema(self.hass, self, self.get_session) + schema_status = self._setup_recorder_and_validate_schema() if schema_status is None: - # Give up if we could not validate the schema - _LOGGER.error("Failed to validate schema, recorder shutting down") + _LOGGER.error("Recorder setup failed, recorder shutting down") return if schema_status.current_version > SCHEMA_VERSION: _LOGGER.error( @@ -982,12 +974,40 @@ class Recorder(threading.Thread): def _setup_recorder(self) -> bool: """Create a connection to the database.""" + return self._setup_connection_with_retry(lambda: True) is not None + + def _setup_recorder_and_validate_schema( + self, + ) -> migration.SchemaValidationStatus | None: + """Create a connection to the database and validate its schema.""" + return self._setup_connection_with_retry( + lambda: migration.validate_db_schema(self.hass, self, self.get_session) + ) + + def _setup_connection_with_retry[_T]( + self, after_setup: Callable[[], _T | None] + ) -> _T | None: + """Connect, initialize the database and run after_setup, with retries. + + The whole sequence is retried on a fresh connection, since a database + restarting while we start up can fail any step of it. + """ tries = 1 while tries <= self.db_max_retries: try: self._setup_connection() - return migration.initialize_database(self.get_session) + result = ( + after_setup() + if migration.initialize_database(self.get_session) + else None + ) + if result is not None: + return result + _LOGGER.error( + "Error during database setup: (retrying in %s seconds)", + self.db_retry_wait, + ) except UnsupportedDialect: break except Exception: @@ -1001,7 +1021,7 @@ class Recorder(threading.Thread): self._close_connection() time.sleep(self.db_retry_wait) - return False + return None def _migrate_data_offline( self, schema_status: migration.SchemaValidationStatus diff --git a/tests/components/recorder/test_init.py b/tests/components/recorder/test_init.py index 70a8c29c12f0..81fa574142af 100644 --- a/tests/components/recorder/test_init.py +++ b/tests/components/recorder/test_init.py @@ -1086,7 +1086,7 @@ async def test_recorder_setup_failure(hass: HomeAssistant) -> None: "function_to_patch", ["_get_current_schema_version", "_get_initial_schema_version"] ) async def test_recorder_validate_schema_failure( - hass: HomeAssistant, function_to_patch: str + hass: HomeAssistant, function_to_patch: str, caplog: pytest.LogCaptureFixture ) -> None: """Test some exceptions.""" recorder_helper.async_initialize_recorder(hass) @@ -1102,6 +1102,8 @@ async def test_recorder_validate_schema_failure( rec.start() rec.join() + assert "Recorder setup failed, recorder shutting down" in caplog.text + assert "threw unexpected exception" not in caplog.text hass.stop() @@ -2984,6 +2986,57 @@ async def test_setup_fails_after_downgrade( ) in caplog.text +@pytest.mark.parametrize( + "func_to_patch", + [ + "_initialize_database", + "_get_initial_schema_version", + "non_live_data_migration_needed", + ], +) +async def test_recorder_recovers_from_database_error_during_schema_validation( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture, func_to_patch: str +) -> None: + """Test a transient database error during startup validation is retried.""" + original = getattr(migration, func_to_patch) + calls = 0 + + def _fail_once(*args: Any, **kwargs: Any) -> Any: + nonlocal calls + calls += 1 + if calls == 1: + raise OperationalError( + "SELECT 1", {}, Exception("Lost connection to server during query") + ) + return original(*args, **kwargs) + + with ( + patch.object(migration, func_to_patch, side_effect=_fail_once), + patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True), + ): + if recorder.DOMAIN not in hass.data: + recorder_helper.async_initialize_recorder(hass) + assert await async_setup_component( + hass, + recorder.DOMAIN, + { + recorder.DOMAIN: { + CONF_DB_URL: "sqlite://", + CONF_DB_RETRY_WAIT: 0, + CONF_DB_MAX_RETRIES: 3, + } + }, + ) + await hass.async_block_till_done() + instance = recorder.get_instance(hass) + await async_wait_recording_done(hass) + + assert calls == 2 + assert instance.recording + assert "recorder shutting down" not in caplog.text + await hass.async_stop() + + async def test_events_are_recorded_until_final_write( hass: HomeAssistant, async_setup_recorder_instance: RecorderInstanceGenerator,