From c7980bda823fd402885ae858931f5abf3929ee0e Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 5 Feb 2023 21:12:41 -0600 Subject: [PATCH] Fix recorder run history during schema migration and startup (#87492) Fix recorder run history during schema migration RunHistory.get and RunHistory.current can be called before RunHistory.start. We need to return a RecorderRuns object with the recording_start time that will be used when start it called to ensure history queries still work as expected. fixes #87112 --- homeassistant/components/recorder/run_history.py | 9 +++++++-- tests/components/recorder/test_run_history.py | 11 +++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/recorder/run_history.py b/homeassistant/components/recorder/run_history.py index fb87d9a1fa2..02b2df066bd 100644 --- a/homeassistant/components/recorder/run_history.py +++ b/homeassistant/components/recorder/run_history.py @@ -64,8 +64,13 @@ class RunHistory: @property def current(self) -> RecorderRuns: """Get the current run.""" - assert self._current_run_info is not None - return self._current_run_info + # If start has not been called yet because the recorder is + # still starting up we want history to use the current time + # as the created time to ensure we can still return results + # and we do not try to pull data from the previous run. + return self._current_run_info or RecorderRuns( + start=self.recording_start, created=dt_util.utcnow() + ) def get(self, start: datetime) -> RecorderRuns | None: """Return the recorder run that started before or at start. diff --git a/tests/components/recorder/test_run_history.py b/tests/components/recorder/test_run_history.py index 7504404f779..3b5bd7dda6b 100644 --- a/tests/components/recorder/test_run_history.py +++ b/tests/components/recorder/test_run_history.py @@ -45,3 +45,14 @@ async def test_run_history(recorder_mock, hass): process_timestamp(instance.run_history.get(now).start) == instance.run_history.recording_start ) + + +async def test_run_history_during_schema_migration(recorder_mock, hass): + """Test the run history during schema migration.""" + instance = recorder.get_instance(hass) + run_history = instance.run_history + assert run_history.current.start == run_history.recording_start + with instance.get_session() as session: + run_history.start(session) + assert run_history.current.start == run_history.recording_start + assert run_history.current.created >= run_history.recording_start