diff --git a/homeassistant/components/recorder/core.py b/homeassistant/components/recorder/core.py index f0466f59bbf8..7c407ec0e195 100644 --- a/homeassistant/components/recorder/core.py +++ b/homeassistant/components/recorder/core.py @@ -14,7 +14,15 @@ from typing import TYPE_CHECKING, Any, cast, override from propcache.api import cached_property import psutil_home_assistant as ha_psutil -from sqlalchemy import create_engine, event as sqlalchemy_event, exc, select, update +from sqlalchemy import ( + Table, + bindparam, + create_engine, + event as sqlalchemy_event, + exc, + select, + update, +) from sqlalchemy.engine import Engine from sqlalchemy.engine.interfaces import DBAPIConnection from sqlalchemy.exc import SQLAlchemyError @@ -1279,13 +1287,21 @@ class Recorder(threading.Thread): pending_last_reported := self.states_manager.get_pending_last_reported_timestamp() ): + # A plain executemany: a state that has been deleted in the meantime + # has nothing left to update. An ORM bulk update by primary key would + # raise StaleDataError for it and fail the whole commit, and every + # commit after it, since the pending timestamps are only cleared on + # success. + states_table = cast(Table, States.__table__) with session.no_autoflush: session.execute( - update(States), + update(states_table) + .where(states_table.c.state_id == bindparam("b_state_id")) + .values(last_reported_ts=bindparam("b_last_reported_ts")), [ { - "state_id": state_id, - "last_reported_ts": last_reported_timestamp, + "b_state_id": state_id, + "b_last_reported_ts": last_reported_timestamp, } for state_id, last_reported_timestamp in ( pending_last_reported.items() diff --git a/homeassistant/components/recorder/table_managers/states.py b/homeassistant/components/recorder/table_managers/states.py index 82fcadd96a8c..294d662b6270 100644 --- a/homeassistant/components/recorder/table_managers/states.py +++ b/homeassistant/components/recorder/table_managers/states.py @@ -88,6 +88,7 @@ class StatesManager: """ self._last_committed_id.clear() self._pending.clear() + self._last_reported.clear() # _oldest_ts is a database aggregate, not session state. def load_from_db(self, session: Session) -> None: diff --git a/tests/components/recorder/test_last_reported.py b/tests/components/recorder/test_last_reported.py new file mode 100644 index 000000000000..9a84fbf96743 --- /dev/null +++ b/tests/components/recorder/test_last_reported.py @@ -0,0 +1,100 @@ +"""Tests for writing the last reported timestamp of states.""" + +from dataclasses import dataclass +from typing import override + +import pytest +from pytest_homeassistant.components.recorder.common import ( + async_recorder_block_till_done, + async_wait_recording_done, +) +from pytest_homeassistant.typing import RecorderInstanceContextManager +from sqlalchemy import select + +from homeassistant.components.recorder import Recorder, get_instance +from homeassistant.components.recorder.db_schema import States +from homeassistant.components.recorder.table_managers.states import StatesManager +from homeassistant.components.recorder.tasks import CommitTask, RecorderTask +from homeassistant.components.recorder.util import session_scope +from homeassistant.core import HomeAssistant + +MISSING_STATE_ID = 999_999 + + +@pytest.fixture +async def mock_recorder_before_hass( + async_test_recorder: RecorderInstanceContextManager, +) -> None: + """Set up recorder.""" + + +@dataclass(slots=True) +class _QueueLastReportedTask(RecorderTask): + """Queue last reported timestamps as if newer states had been recorded.""" + + timestamps: dict[int, float] + commit_before = False + + @override + def run(self, instance: Recorder) -> None: + for state_id, timestamp in self.timestamps.items(): + instance.states_manager.update_pending_last_reported(state_id, timestamp) + instance._event_session_has_pending_writes = True + + +async def test_last_reported_of_a_deleted_state_is_skipped( + recorder_mock: Recorder, hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: + """A last reported timestamp for a state that is gone must not fail the commit. + + The ORM bulk update by primary key raised StaleDataError for it, which failed + the commit and every commit after it. + """ + hass.states.async_set("sensor.test", "on") + await async_wait_recording_done(hass) + + def _state_id() -> int: + with session_scope(hass=hass, read_only=True) as session: + return session.execute(select(States.state_id)).scalar_one() + + state_id = await get_instance(hass).async_add_executor_job(_state_id) + + instance = get_instance(hass) + instance.queue_task( + _QueueLastReportedTask({state_id: 1234.5, MISSING_STATE_ID: 1234.5}) + ) + instance.queue_task(CommitTask()) + await async_recorder_block_till_done(hass) + + def _last_reported() -> float | None: + with session_scope(hass=hass, read_only=True) as session: + return session.execute( + select(States.last_reported_ts).where(States.state_id == state_id) + ).scalar_one() + + assert await get_instance(hass).async_add_executor_job(_last_reported) == 1234.5 + assert "StaleDataError" not in caplog.text + + # and the recorder keeps recording + hass.states.async_set("sensor.test", "off") + await async_wait_recording_done(hass) + + def _states() -> list[str]: + with session_scope(hass=hass, read_only=True) as session: + return list( + session.execute( + select(States.state).order_by(States.state_id) + ).scalars() + ) + + assert await get_instance(hass).async_add_executor_job(_states) == ["on", "off"] + + +def test_reset_drops_pending_last_reported() -> None: + """Closing the event session drops the timestamps it didn't commit.""" + manager = StatesManager() + manager.update_pending_last_reported(1, 10.0) + + manager.reset() + + assert manager.get_pending_last_reported_timestamp() == {}