From f0860263e2fc12bb2103a2865424027faf831082 Mon Sep 17 00:00:00 2001 From: Raman Gupta <7243222+raman325@users.noreply.github.com> Date: Tue, 20 Oct 2026 04:59:56 -0400 Subject: [PATCH] Roll back the session before retrying recorder queries (#178204) Co-authored-by: Claude Fable 5 Co-authored-by: Franck Nijhof --- homeassistant/components/recorder/util.py | 25 +++- homeassistant/helpers/recorder.py | 9 ++ tests/components/recorder/test_util.py | 157 +++++++++++++++++++++- 3 files changed, 189 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/recorder/util.py b/homeassistant/components/recorder/util.py index 1d3f6a02cdf7..c42c2dc98633 100644 --- a/homeassistant/components/recorder/util.py +++ b/homeassistant/components/recorder/util.py @@ -31,7 +31,12 @@ from homeassistant.generated.recorder_database_versions import ( SUPPORTED_DATABASE_VERSIONS, ) from homeassistant.helpers import config_validation as cv, issue_registry as ir -from homeassistant.helpers.recorder import DATA_INSTANCE, get_instance, session_scope # noqa: F401 +from homeassistant.helpers.recorder import ( # noqa: F401 + DATA_INSTANCE, + SESSION_INFO_READ_ONLY, + get_instance, + session_scope, +) from homeassistant.util import dt as dt_util from .const import DEFAULT_MAX_BIND_VARS, DOMAIN, SQLITE_URL_PREFIX, SupportedDialect @@ -148,6 +153,22 @@ SUNDAY_WEEKDAY = 6 DAYS_IN_WEEK = 7 +def _rollback_read_only_session(session: Session) -> None: + """Roll back a read-only session so a retried query can reconnect. + + A query after a lost connection otherwise raises PendingRollbackError. Only a + read-only session is rolled back: it is never committed, so nothing is lost. A + session holding writes is left alone, a rollback would discard them while the + retry succeeds and the caller commits what is left of its unit of work. + """ + if not session.info.get(SESSION_INFO_READ_ONLY): + return + try: + session.rollback() + except SQLAlchemyError as err: + _LOGGER.error("Error rolling back the session: %s", err) + + def execute(qry: Query) -> list[Row]: """Query the database and convert the objects to HA native form. @@ -173,6 +194,7 @@ def execute(qry: Query) -> list[Row]: if tryno == RETRIES - 1: raise + _rollback_read_only_session(qry.session) time.sleep(QUERY_RETRY_WAIT) else: return result @@ -214,6 +236,7 @@ def execute_stmt_lambda_element( _LOGGER.error("Error executing query: %s", err) if tryno == RETRIES - 1: raise + _rollback_read_only_session(session) time.sleep(QUERY_RETRY_WAIT) # Unreachable diff --git a/homeassistant/helpers/recorder.py b/homeassistant/helpers/recorder.py index c954eb6be1e7..1e8ce521ae6b 100644 --- a/homeassistant/helpers/recorder.py +++ b/homeassistant/helpers/recorder.py @@ -18,6 +18,9 @@ if TYPE_CHECKING: _LOGGER = logging.getLogger(__name__) +# Session.info key set while a session is used in a read-only session scope +SESSION_INFO_READ_ONLY = "recorder_read_only" + DATA_RECORDER: HassKey[RecorderData] = HassKey("recorder") DATA_INSTANCE: HassKey[Recorder] = HassKey("recorder_instance") @@ -86,6 +89,10 @@ def session_scope( if session is None: raise RuntimeError("Session required") + if read_only: + # Sessions are reused per thread, so the marker is removed again when the + # scope ends + session.info[SESSION_INFO_READ_ONLY] = True need_rollback = False try: yield session @@ -99,4 +106,6 @@ def session_scope( if not exception_filter or not exception_filter(err): raise finally: + if read_only: + session.info.pop(SESSION_INFO_READ_ONLY, None) session.close() diff --git a/tests/components/recorder/test_util.py b/tests/components/recorder/test_util.py index 334489325ff6..546b7a74ee06 100644 --- a/tests/components/recorder/test_util.py +++ b/tests/components/recorder/test_util.py @@ -1,5 +1,6 @@ """Test util methods.""" +from collections.abc import Callable from contextlib import AbstractContextManager, nullcontext as does_not_raise from datetime import UTC, datetime, timedelta import os @@ -24,6 +25,7 @@ from pytest_homeassistant.typing import ( from sqlalchemy import lambda_stmt, text from sqlalchemy.engine.result import ChunkedIteratorResult from sqlalchemy.exc import OperationalError, SQLAlchemyError +from sqlalchemy.orm import Session from sqlalchemy.sql.elements import TextClause from sqlalchemy.sql.lambdas import StatementLambdaElement @@ -34,7 +36,7 @@ from homeassistant.components.recorder.const import ( SQLITE_URL_PREFIX, SupportedDialect, ) -from homeassistant.components.recorder.db_schema import RecorderRuns +from homeassistant.components.recorder.db_schema import RecorderRuns, StatesMeta from homeassistant.components.recorder.history import _get_single_entity_start_time_stmt from homeassistant.components.recorder.models import ( UnsupportedDialect, @@ -54,6 +56,7 @@ from homeassistant.components.recorder.util import ( from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir +from homeassistant.helpers.recorder import SESSION_INFO_READ_ONLY from homeassistant.util import dt as dt_util @@ -82,6 +85,22 @@ async def test_session_scope_not_setup( pass +async def test_session_scope_read_only_marker_ends_with_scope( + hass: HomeAssistant, + setup_recorder: None, +) -> None: + """Test a session is only marked read-only within a read-only scope. + + Sessions are reused per thread, so a marker left behind would let a failed + query roll back a later session holding writes. + """ + with util.session_scope(hass=hass, read_only=True) as session: + assert session.info[SESSION_INFO_READ_ONLY] is True + with util.session_scope(hass=hass) as reused_session: + assert reused_session is session + assert SESSION_INFO_READ_ONLY not in reused_session.info + + async def test_recorder_bad_execute(hass: HomeAssistant, setup_recorder: None) -> None: """Bad execute, retry 3 times.""" @@ -1173,6 +1192,142 @@ def test_build_mysqldb_conv() -> None: ) +@pytest.mark.parametrize("persistent_database", [True]) +@patch("homeassistant.components.recorder.util.QUERY_RETRY_WAIT", 0) +async def test_execute_recovers_after_lost_connection( + hass: HomeAssistant, + setup_recorder: None, +) -> None: + """Test execute reconnects and returns rows after the connection is lost. + + The database must survive the lost connection, which an in-memory SQLite + database does not. + """ + instance = recorder.get_instance(hass) + hass.states.async_set("sensor.on", "on") + await async_wait_recording_done(hass) + + def _query() -> None: + with session_scope(hass=hass, read_only=True) as session: + query = session.query(StatesMeta).limit(1) + # Simulate a lost connection: the session object stays intact and unaware + session.connection().invalidate() + assert len(util.execute(query)) == 1 + + await instance.async_add_executor_job(_query) + + +@pytest.mark.parametrize("persistent_database", [True]) +@patch("homeassistant.components.recorder.util.QUERY_RETRY_WAIT", 0) +async def test_execute_stmt_lambda_element_recovers_after_lost_connection( + hass: HomeAssistant, + setup_recorder: None, +) -> None: + """Test execute_stmt_lambda_element reconnects after the connection is lost.""" + instance = recorder.get_instance(hass) + hass.states.async_set("sensor.on", "on") + new_state = hass.states.get("sensor.on") + await async_wait_recording_done(hass) + + def _query() -> None: + with session_scope(hass=hass, read_only=True) as session: + metadata_id = instance.states_meta_manager.get("sensor.on", session, True) + start_time_ts = dt_util.utcnow().timestamp() + stmt = lambda_stmt( + lambda: _get_single_entity_start_time_stmt( + start_time_ts, metadata_id, False, False, False + ) + ) + session.connection().invalidate() + + rows = util.execute_stmt_lambda_element(session, stmt) + assert rows[0].state == new_state.state + assert rows[0].metadata_id == metadata_id + + await instance.async_add_executor_job(_query) + + +def _execute_failing_once(session: Session) -> Any: + """Run a query through execute which fails on the first attempt.""" + query = MagicMock(session=session) + query.all.side_effect = [OperationalError("SELECT", {}, Exception()), ["row"]] + return util.execute(query) + + +def _execute_stmt_lambda_element_failing_once(session: Session) -> Any: + """Run a statement through execute_stmt_lambda_element which fails once.""" + result = MagicMock() + result.all.return_value = ["row"] + with patch.object( + session, + "execute", + side_effect=[OperationalError("SELECT", {}, Exception()), result], + ): + return util.execute_stmt_lambda_element(session, MagicMock()) + + +QUERIES_FAILING_ONCE = [ + pytest.param(_execute_failing_once, id="execute"), + pytest.param( + _execute_stmt_lambda_element_failing_once, id="execute_stmt_lambda_element" + ), +] + + +@pytest.mark.parametrize( + ("read_only", "pending_write_kept"), + [ + pytest.param(True, False, id="read_only_session_rolled_back"), + pytest.param(False, True, id="write_session_not_rolled_back"), + ], +) +@pytest.mark.parametrize("run_query", QUERIES_FAILING_ONCE) +@patch("homeassistant.components.recorder.util.QUERY_RETRY_WAIT", 0) +async def test_query_retry_only_rolls_back_read_only_session( + hass: HomeAssistant, + setup_recorder: None, + run_query: Callable[[Session], Any], + read_only: bool, + pending_write_kept: bool, +) -> None: + """Test a failed query only rolls back a read-only session before retrying. + + A read-only session is never committed, so rolling it back loses nothing. A + session holding writes must not be rolled back, as the retry would then succeed + and the caller would go on to commit what is left of its unit of work. + """ + with session_scope(hass=hass, read_only=read_only) as session: + pending_write = RecorderRuns(start=dt_util.utcnow()) + session.add(pending_write) + + run_query(session) + + assert (pending_write in session.new) is pending_write_kept + # Don't commit the pending write when the scope ends + session.expunge_all() + + +@pytest.mark.parametrize("run_query", QUERIES_FAILING_ONCE) +@patch("homeassistant.components.recorder.util.QUERY_RETRY_WAIT", 0) +async def test_query_retry_continues_after_failed_rollback( + hass: HomeAssistant, + setup_recorder: None, + caplog: pytest.LogCaptureFixture, + run_query: Callable[[Session], Any], +) -> None: + """Test a rollback which fails neither replaces the query error nor ends the retries.""" + with ( + session_scope(hass=hass, read_only=True) as session, + patch.object( + session, "rollback", side_effect=SQLAlchemyError("rollback failed") + ), + ): + # The retry after the failed rollback returns the rows + assert run_query(session) == ["row"] + + assert "rollback failed" in caplog.text + + @patch("homeassistant.components.recorder.util.QUERY_RETRY_WAIT", 0) async def test_execute_stmt_lambda_element( hass: HomeAssistant,