From 6597cc48125a6bf98e1ecd59520b58a06f38d024 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Tue, 20 Oct 2026 17:16:57 +0100 Subject: [PATCH] Revert "Fix deadlock when priming conditions relying on recorder history" (#187564) --- .../helpers/condition/entity_condition.py | 148 +----- tests/helpers/test_condition.py | 442 +----------------- 2 files changed, 31 insertions(+), 559 deletions(-) diff --git a/homeassistant/helpers/condition/entity_condition.py b/homeassistant/helpers/condition/entity_condition.py index 60c6fd694680..e1e7199ecd3e 100644 --- a/homeassistant/helpers/condition/entity_condition.py +++ b/homeassistant/helpers/condition/entity_condition.py @@ -4,7 +4,6 @@ import abc import asyncio from collections.abc import Callable, Coroutine, Mapping from datetime import datetime, timedelta -from enum import Enum, auto import functools as ft import logging from typing import TYPE_CHECKING, Any, ClassVar, Final, Unpack, cast, override @@ -58,7 +57,6 @@ if TYPE_CHECKING: from homeassistant.components.recorder import Recorder from .models import Condition, ConditionCheckParams, ConditionConfig -from .tracing import condition_trace_update_result _LOGGER = logging.getLogger(__name__) @@ -72,16 +70,6 @@ HISTORY_PRIMING_TIMEOUT = 10 # such conditions may only become true once enough time has elapsed since setup. MAX_HISTORY_PRIMING_LOOKBACK = timedelta(hours=6) - -class _HistoryPriming(Enum): - """Outcome of refining `for:` anchors from recorder history.""" - - COMPLETE = auto() - # History was read, or skipped, before the recorder processed its queue. - PENDING = auto() - FAILED = auto() - - ATTR_BEHAVIOR: Final = "behavior" BEHAVIOR_ANY: Final = "any" BEHAVIOR_ALL: Final = "all" @@ -140,13 +128,6 @@ class EntityConditionBase(Condition): # the priming, except that an invalidation removes it (the run broke, so # the in-flight history is stale and live tracking takes over). self._priming: set[str] = set() - # Entities whose `for:` anchor was resolved without complete recorder - # history. They are reported in the condition trace, and re-primed once - # the recorder processes its queue if that is what was missing. Mapped to - # the live anchor: the entity has been valid since, as live tracking saw. - self._incomplete_history: dict[str, datetime] = {} - self._unsub_recorder_ready: CALLBACK_TYPE | None = None - self._prime_tasks: set[asyncio.Task[None]] = set() def entity_filter(self, entities: set[str]) -> set[str]: """Filter entities matching any of the domain specs.""" @@ -199,9 +180,7 @@ class EntityConditionBase(Condition): else: # An invalidation breaks the run, so any history being loaded for the # entity is now stale; stop priming it and let live tracking own it. - # Live tracking observed the break, so its next anchor is exact. self._priming.discard(entity_id) - self._incomplete_history.pop(entity_id, None) self._valid_since.pop(entity_id, None) @property @@ -305,7 +284,6 @@ class EntityConditionBase(Condition): """ for entity_id in removed: self._priming.discard(entity_id) - self._incomplete_history.pop(entity_id, None) self._valid_since.pop(entity_id, None) await self._async_prime_valid_since(added) @@ -317,10 +295,7 @@ class EntityConditionBase(Condition): `MAX_HISTORY_PRIMING_LOOKBACK`). The earlier of that and the current state's own anchor wins, so a run that began before the lookback window is not cut short. When the recorder is unavailable or the read fails, - the current state's anchor is used alone. Before the recorder processes - its queue the history lacks queued changes, so the anchor may be too - generous; such entities are flagged in `_incomplete_history` and primed - again once the recorder is ready. An entity is added to + the current state's anchor is used alone. An entity is added to `_valid_since` only once this resolves, so a newly tracked entity does not participate in the condition until its anchor is known — rather than briefly using a conservative anchor that then changes. @@ -331,77 +306,37 @@ class EntityConditionBase(Condition): history over the live tracking that observed the break. """ # Conservative anchor from the live state for each currently-valid entity. - live_anchors: dict[str, datetime] = {} - for entity_id in entity_ids: - if ( - (_state := self._hass.states.get(entity_id)) is None - or not self._should_include(_state) - or not self.is_valid_state(_state) - ): - continue - live_anchor = self._state_valid_since(_state) - # When priming again, live tracking has seen the entity stay valid - # since the earlier anchor; a later update must not cut that short. - if (earlier := self._incomplete_history.get(entity_id)) is not None: - live_anchor = min(live_anchor, earlier) - live_anchors[entity_id] = live_anchor - if not live_anchors: + anchors = { + entity_id: self._state_valid_since(_state) + for entity_id in entity_ids + if (_state := self._hass.states.get(entity_id)) is not None + and self._should_include(_state) + and self.is_valid_state(_state) + } + if not anchors: return - anchors = dict(live_anchors) self._priming.update(anchors) try: - priming = _HistoryPriming.COMPLETE if "recorder" in self._hass.config.components: - priming = await self._async_refine_anchors_from_history(anchors) + await self._async_refine_anchors_from_history(anchors) for entity_id, anchor in anchors.items(): # Skip entities a live change invalidated mid-load: they were # removed from `_priming`, the run broke, and live tracking (which # saw the break) owns them — applying this history would be stale. - if entity_id not in self._priming: - continue - self._valid_since[entity_id] = anchor - if priming is _HistoryPriming.COMPLETE: - self._incomplete_history.pop(entity_id, None) - else: - self._incomplete_history[entity_id] = live_anchors[entity_id] + if entity_id in self._priming: + self._valid_since[entity_id] = anchor finally: self._priming.difference_update(anchors) - if ( - priming is _HistoryPriming.PENDING - and self._incomplete_history - and self._unsub_recorder_ready is None - ): - manager = self._hass.data[DATA_HISTORY_PRIMING_MANAGER] - self._unsub_recorder_ready = manager.async_on_recorder_ready( - self._async_prime_incomplete_history - ) - - @callback - def _async_prime_incomplete_history(self) -> None: - """Prime entities again now that the recorder processes its queue.""" - self._unsub_recorder_ready = None - # Tracked so it can be cancelled on unload. - task = self._hass.async_create_background_task( - self._async_prime_valid_since(set(self._incomplete_history)), - "condition history priming", - ) - self._prime_tasks.add(task) - task.add_done_callback(self._prime_tasks.discard) - async def _async_refine_anchors_from_history( self, anchors: dict[str, datetime] - ) -> _HistoryPriming: + ) -> None: """Move each anchor in `anchors` back to the true start of its run. For each entity the anchor becomes the earlier of the recorded run start and the existing (live) anchor; entities with no usable history keep their existing anchor. Mutates `anchors` in place. - - The recorder only processes its queue once Home Assistant has started - and any live schema migration is done, so the queue is not flushed - before that. """ from sqlalchemy.exc import SQLAlchemyError # noqa: PLC0415 @@ -415,8 +350,8 @@ class EntityConditionBase(Condition): async def _read_history( instance: Recorder, ) -> dict[str, list[State | dict[str, Any]]]: - # The history query only sees committed rows; once the recorder is - # ready the priming manager flushes its queue before running this. + # The history query only sees committed rows; the priming manager + # flushes the recorder queue before running this. return await instance.async_add_executor_job( ft.partial( history.get_significant_states, @@ -433,19 +368,16 @@ class EntityConditionBase(Condition): ) manager = self._hass.data[DATA_HISTORY_PRIMING_MANAGER] - recorder_ready = get_instance(self._hass).async_recorder_ready.is_set() try: # The timeout also covers waiting for our turn, so under a flood of # primings a condition falls back to its conservative anchor rather # than blocking on the queue indefinitely. async with asyncio.timeout(HISTORY_PRIMING_TIMEOUT): - historical_states = await manager.async_prime( - _read_history, flush=recorder_ready - ) + historical_states = await manager.async_prime(_read_history) except (SQLAlchemyError, TimeoutError) as err: # Best effort: keep the conservative anchors rather than failing. _LOGGER.debug("Error priming condition durations from history: %s", err) - return _HistoryPriming.FAILED if recorder_ready else _HistoryPriming.PENDING + return for entity_id, rows in historical_states.items(): valid_since = self._valid_since_from_history( @@ -453,7 +385,6 @@ class EntityConditionBase(Condition): ) if valid_since is not None: anchors[entity_id] = min(valid_since, anchors[entity_id]) - return _HistoryPriming.COMPLETE if recorder_ready else _HistoryPriming.PENDING def _valid_since_from_history( self, entity_id: str, rows: list[State] @@ -485,11 +416,6 @@ class EntityConditionBase(Condition): for cb in self._on_unload: cb() self._on_unload.clear() - if self._unsub_recorder_ready is not None: - self._unsub_recorder_ready() - self._unsub_recorder_ready = None - for task in self._prime_tasks: - task.cancel() def _should_include(self, _state: State) -> bool: """Check if an entity should participate in any/all checks. @@ -560,11 +486,6 @@ class EntityConditionBase(Condition): if (_state := self._hass.states.get(entity_id)) and self._should_include(_state) ] - if self._incomplete_history and ( - incomplete_history := self._incomplete_history.keys() - & {_state.entity_id for _state in entity_states} - ): - condition_trace_update_result(incomplete_history=sorted(incomplete_history)) return self._matcher(entity_states) @@ -920,46 +841,15 @@ class HistoryPrimingManager: self._flushing = False self._flush_ok = False self._query_lock = asyncio.Lock() - self._recorder_ready_jobs: set[Callable[[], None]] = set() - self._recorder_ready_task: asyncio.Task[None] | None = None async def async_prime[_T]( - self, job: Callable[[Recorder], Coroutine[Any, Any, _T]], *, flush: bool + self, job: Callable[[Recorder], Coroutine[Any, Any, _T]] ) -> _T: """Flush the recorder, then run `job`, coordinated with other primings.""" - if flush: - await self._async_flush() + await self._async_flush() async with self._query_lock: return await job(get_instance(self._hass)) - @callback - def async_on_recorder_ready(self, job: Callable[[], None]) -> CALLBACK_TYPE: - """Call `job` once the recorder processes its queue.""" - self._recorder_ready_jobs.add(job) - if self._recorder_ready_task is None: - # Not eager: if the recorder is already ready, an eager task would - # finish, and reset the attribute, before it is assigned here. - self._recorder_ready_task = self._hass.async_create_background_task( - self._async_run_recorder_ready_jobs(), - "condition history priming recorder ready", - eager_start=False, - ) - - @callback - def _unsub() -> None: - self._recorder_ready_jobs.discard(job) - - return _unsub - - async def _async_run_recorder_ready_jobs(self) -> None: - """Wait for the recorder to be ready, then call the registered jobs.""" - await get_instance(self._hass).async_recorder_ready.wait() - jobs = self._recorder_ready_jobs - self._recorder_ready_jobs = set() - self._recorder_ready_task = None - for job in jobs: - job() - async def _async_flush(self) -> None: """Return once a recorder flush that began no earlier than this call ends. diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index 31d343ade413..bd5e17bee83c 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -7,7 +7,6 @@ from dataclasses import dataclass, field from datetime import datetime, timedelta import io import logging -import threading from typing import Any from unittest.mock import AsyncMock, Mock, patch @@ -21,11 +20,7 @@ from pytest_homeassistant.common import ( mock_integration, mock_platform, ) -from pytest_homeassistant.components.recorder.common import ( - async_wait_recorder, - async_wait_recording_done, -) -from pytest_homeassistant.typing import RecorderInstanceGenerator +from pytest_homeassistant.components.recorder.common import async_wait_recording_done from pytest_unordered import unordered from sqlalchemy.exc import SQLAlchemyError @@ -49,7 +44,6 @@ from homeassistant.const import ( CONF_FOR, CONF_OPTIONS, CONF_TARGET, - EVENT_HOMEASSISTANT_STARTED, STATE_OFF, STATE_ON, STATE_UNAVAILABLE, @@ -57,7 +51,7 @@ from homeassistant.const import ( EntityCategory, UnitOfTemperature, ) -from homeassistant.core import CoreState, HomeAssistant, State +from homeassistant.core import HomeAssistant, State from homeassistant.exceptions import ConditionError, HomeAssistantError from homeassistant.helpers import ( area_registry as ar, @@ -65,7 +59,6 @@ from homeassistant.helpers import ( config_validation as cv, entity_registry as er, label_registry as lr, - recorder as recorder_helper, trace, ) from homeassistant.helpers.automation import ( @@ -5601,10 +5594,6 @@ async def test_state_condition_attr_duration_history_error_falls_back( # Fell back to the conservative anchor (last_updated bumped at t=8), # so the 5s `for:` is not satisfied 2s later. assert test.async_check() is False - # The trace shows that the anchor lacks history. - assert_condition_trace( - {"": [{"result": {"result": False, "incomplete_history": [entity_id]}}]} - ) async def test_state_condition_attr_duration_history_lookback_capped( @@ -5935,411 +5924,6 @@ async def test_state_condition_attr_duration_history_flushes_before_query( assert call_order == ["flush", "query"] -async def test_state_condition_attr_duration_primes_before_recorder_started( - async_setup_recorder_instance: RecorderInstanceGenerator, - hass: HomeAssistant, -) -> None: - """Priming at startup does not wait for the recorder to process its queue. - - The recorder only processes its queue once Home Assistant has started, so - waiting for a flush during setup would block condition setup — and with it - startup — until the priming timeout. Instead the condition is set up with the - committed history only, reports that in its trace, and is primed again once - the recorder is ready. - """ - hass.set_state(CoreState.not_running) - recorder_helper.async_initialize_recorder(hass) - hass.async_create_task(async_setup_recorder_instance(hass)) - await async_wait_recorder(hass) - instance = get_instance(hass) - await instance.async_db_ready - assert not instance.async_recorder_ready.is_set() - - entity_id = "test.entity_1" - start = dt_util.utcnow() - with freeze_time(start) as freezer: - # Valid since t=0; the main-state change at t=8 keeps the attribute valid. - # Both writes stay queued in the recorder until Home Assistant has started. - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - freezer.move_to(start + timedelta(seconds=8)) - hass.states.async_set(entity_id, STATE_OFF, {"test_attr": True}) - await hass.async_block_till_done() - - freezer.move_to(start + timedelta(seconds=10)) - with patch.object( - instance, - "async_get_commit_future", - side_effect=AssertionError("flushed before the recorder was ready"), - ): - test = await _setup_attr_state_condition( - hass, - entity_ids=entity_id, - states={True}, - condition_options={CONF_FOR: {"seconds": 5}}, - ) - - # Nothing is committed, so only the live anchor (t=8) is known. - assert test.async_check() is False - assert_condition_trace( - {"": [{"result": {"result": False, "incomplete_history": [entity_id]}}]} - ) - - hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) - await async_wait_recording_done(hass) - await hass.async_block_till_done(wait_background_tasks=True) - assert instance.async_recorder_ready.is_set() - - # Primed again with the now committed history: valid since t=0. - assert test.async_check() is True - assert_condition_trace({"": [{"result": {"result": True}}]}) - - -def _read_attr_history( - hass: HomeAssistant, start_time: datetime, entity_id: str -) -> dict[str, list[State | dict[str, Any]]]: - """Read history the way condition priming does.""" - return history.get_significant_states( - hass, - start_time, - entity_ids=[entity_id], - include_start_time_state=True, - significant_changes_only=False, - minimal_response=False, - ) - - -async def test_state_condition_attr_duration_incomplete_history_reprimed( - recorder_mock: Recorder, hass: HomeAssistant -) -> None: - """A too generous anchor from incomplete history is replaced once ready. - - Before the recorder is ready the history read is not preceded by a flush, so - it misses changes still queued in the recorder. Here that hides a dip, and - the condition is wrongly met; the trace reports the incomplete history. Once - the recorder is ready the condition is primed again, and the complete history - replaces the too generous anchor rather than only moving it earlier. - """ - entity_id = "test.entity_1" - instance = get_instance(hass) - start = dt_util.utcnow() - with freeze_time(start) as freezer: - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - await hass.async_block_till_done() - await async_wait_recording_done(hass) - # History as committed before the dip. - stale_history = await instance.async_add_executor_job( - _read_attr_history, hass, start - timedelta(minutes=1), entity_id - ) - - # Invalid at t=6, valid again at t=7. - freezer.move_to(start + timedelta(seconds=6)) - hass.states.async_set(entity_id, STATE_ON, {"test_attr": False}) - freezer.move_to(start + timedelta(seconds=7)) - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - await hass.async_block_till_done() - await async_wait_recording_done(hass) - - freezer.move_to(start + timedelta(seconds=10)) - instance.async_recorder_ready.clear() - with ( - patch.object( - instance, - "async_get_commit_future", - side_effect=AssertionError("flushed before the recorder was ready"), - ), - patch( - "homeassistant.components.recorder.history.get_significant_states", - return_value=stale_history, - ), - ): - test = await _setup_attr_state_condition( - hass, - entity_ids=entity_id, - states={True}, - condition_options={CONF_FOR: {"seconds": 5}}, - ) - - # The read missed the dip: anchored at t=0 instead of t=7. - assert test.async_check() is True - assert_condition_trace( - {"": [{"result": {"result": True, "incomplete_history": [entity_id]}}]} - ) - - instance.async_recorder_ready.set() - await hass.async_block_till_done(wait_background_tasks=True) - - # Primed again with complete history: valid only since t=7. - assert test.async_check() is False - assert_condition_trace({"": [{"result": {"result": False}}]}) - - -async def test_state_condition_attr_duration_invalidation_clears_incomplete_history( - recorder_mock: Recorder, hass: HomeAssistant -) -> None: - """Live tracking takes over an entity with incomplete history it saw break. - - After observing the run break, the live anchor is exact, so the entity is no - longer reported as having incomplete history, and priming it again once the - recorder is ready leaves it alone. - """ - entity_id = "test.entity_1" - instance = get_instance(hass) - start = dt_util.utcnow() - with freeze_time(start) as freezer: - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - await hass.async_block_till_done() - await async_wait_recording_done(hass) - - freezer.move_to(start + timedelta(seconds=10)) - instance.async_recorder_ready.clear() - test = await _setup_attr_state_condition( - hass, - entity_ids=entity_id, - states={True}, - condition_options={CONF_FOR: {"seconds": 5}}, - ) - assert test.async_check() is True - assert_condition_trace( - {"": [{"result": {"result": True, "incomplete_history": [entity_id]}}]} - ) - - # Invalid at t=11, valid again at t=12. - freezer.move_to(start + timedelta(seconds=11)) - hass.states.async_set(entity_id, STATE_ON, {"test_attr": False}) - freezer.move_to(start + timedelta(seconds=12)) - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - await hass.async_block_till_done() - assert test.async_check() is False - assert_condition_trace({"": [{"result": {"result": False}}]}) - - with patch( - "homeassistant.components.recorder.history.get_significant_states", - return_value={}, - ) as get_significant_states: - instance.async_recorder_ready.set() - await hass.async_block_till_done(wait_background_tasks=True) - get_significant_states.assert_not_called() - - freezer.move_to(start + timedelta(seconds=17)) - assert test.async_check() is True - assert_condition_trace({"": [{"result": {"result": True}}]}) - - -async def test_state_condition_attr_duration_unload_before_recorder_ready( - recorder_mock: Recorder, hass: HomeAssistant -) -> None: - """A condition unloaded before the recorder is ready is not primed again.""" - entity_id = "test.entity_1" - instance = get_instance(hass) - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - await hass.async_block_till_done() - await async_wait_recording_done(hass) - - instance.async_recorder_ready.clear() - test = await _setup_attr_state_condition( - hass, - entity_ids=entity_id, - states={True}, - condition_options={CONF_FOR: {"seconds": 5}}, - ) - test.async_unload() - - with patch( - "homeassistant.components.recorder.history.get_significant_states", - return_value={}, - ) as get_significant_states: - instance.async_recorder_ready.set() - await hass.async_block_till_done(wait_background_tasks=True) - get_significant_states.assert_not_called() - - -async def test_state_condition_attr_duration_reprime_keeps_live_anchor( - recorder_mock: Recorder, hass: HomeAssistant -) -> None: - """Priming again keeps the run live tracking saw, even without history. - - The entity has no usable history, e.g. it is excluded from recording. Live - tracking sees it stay valid across an unrelated update after setup; priming - again once the recorder is ready must not restart the run at that update. - """ - entity_id = "test.entity_1" - instance = get_instance(hass) - start = dt_util.utcnow() - with ( - freeze_time(start) as freezer, - patch( - "homeassistant.components.recorder.history.get_significant_states", - return_value={}, - ), - ): - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - await hass.async_block_till_done() - - instance.async_recorder_ready.clear() - test = await _setup_attr_state_condition( - hass, - entity_ids=entity_id, - states={True}, - condition_options={CONF_FOR: {"seconds": 5}}, - ) - - # Unrelated update at t=8: still valid, so the run continues. - freezer.move_to(start + timedelta(seconds=8)) - hass.states.async_set(entity_id, STATE_OFF, {"test_attr": True}) - await hass.async_block_till_done() - - freezer.move_to(start + timedelta(seconds=10)) - assert test.async_check() is True - assert_condition_trace( - {"": [{"result": {"result": True, "incomplete_history": [entity_id]}}]} - ) - - instance.async_recorder_ready.set() - await hass.async_block_till_done(wait_background_tasks=True) - - # Still valid since t=0, not since the update at t=8. - assert test.async_check() is True - assert_condition_trace({"": [{"result": {"result": True}}]}) - - -async def test_state_condition_attr_duration_unload_cancels_reprime( - recorder_mock: Recorder, hass: HomeAssistant -) -> None: - """Unloading a condition cancels its in-flight re-prime.""" - entity_id = "test.entity_1" - instance = get_instance(hass) - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - await hass.async_block_till_done() - await async_wait_recording_done(hass) - - instance.async_recorder_ready.clear() - test = await _setup_attr_state_condition( - hass, - entity_ids=entity_id, - states={True}, - condition_options={CONF_FOR: {"seconds": 5}}, - ) - - gate: asyncio.Future[None] = hass.loop.create_future() - with ( - # Shielded, so cancelling the waiting re-prime leaves the gate releasable. - patch.object( - instance, - "async_get_commit_future", - side_effect=lambda: asyncio.shield(gate), - ) as commit_future, - patch( - "homeassistant.components.recorder.history.get_significant_states", - return_value={}, - ) as get_significant_states, - ): - instance.async_recorder_ready.set() - # The re-prime blocks on the held flush. - await _advance_until(lambda: commit_future.called) - test.async_unload() - - gate.set_result(None) - await hass.async_block_till_done(wait_background_tasks=True) - get_significant_states.assert_not_called() - - -async def test_state_condition_attr_duration_reprimed_when_ready_during_read( - recorder_mock: Recorder, hass: HomeAssistant -) -> None: - """Conditions whose read spans the recorder becoming ready are primed again. - - They read without a flush, so the result is incomplete, but they only - register to be primed again once the recorder is already ready. Each of them - must still be primed again, not just the first. - """ - entity_id = "test.entity_1" - instance = get_instance(hass) - start = dt_util.utcnow() - with freeze_time(start) as freezer: - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - await hass.async_block_till_done() - await async_wait_recording_done(hass) - # History as committed before the dip. - stale_history = await instance.async_add_executor_job( - _read_attr_history, hass, start - timedelta(minutes=1), entity_id - ) - - # Invalid at t=6, valid again at t=7. - freezer.move_to(start + timedelta(seconds=6)) - hass.states.async_set(entity_id, STATE_ON, {"test_attr": False}) - freezer.move_to(start + timedelta(seconds=7)) - hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) - await hass.async_block_till_done() - await async_wait_recording_done(hass) - - freezer.move_to(start + timedelta(seconds=10)) - real_query = history.get_significant_states - stale_reads = 2 - read_started = threading.Event() - release_read = threading.Event() - - def _read(*args: Any, **kwargs: Any) -> Any: - # The reads are serialized by the priming manager. - nonlocal stale_reads - if not stale_reads: - return real_query(*args, **kwargs) - stale_reads -= 1 - read_started.set() - release_read.wait(10) - return stale_history - - instance.async_recorder_ready.clear() - with patch( - "homeassistant.components.recorder.history.get_significant_states", - side_effect=_read, - ): - setups = [ - hass.async_create_task( - _setup_attr_state_condition( - hass, - entity_ids=entity_id, - states={True}, - condition_options={CONF_FOR: {"seconds": 5}}, - ) - ) - for _ in range(2) - ] - # The second read waits for the first, which the recorder becoming - # ready interrupts. - assert await hass.async_add_executor_job(read_started.wait, 10) - instance.async_recorder_ready.set() - release_read.set() - tests = await asyncio.gather(*setups) - await hass.async_block_till_done(wait_background_tasks=True) - - # Both were primed again with complete history: valid only since t=7. - for test in tests: - assert test.async_check() is False - assert_condition_trace({"": [{"result": {"result": False}}]}) - - -async def test_history_priming_manager_recorder_ready_jobs( - recorder_mock: Recorder, hass: HomeAssistant -) -> None: - """Jobs are called once the recorder is ready, never before registering returns. - - Callers store the returned callback before their job may clear it, also when - the recorder is already ready; and every registration is served. - """ - manager = HistoryPrimingManager(hass) - calls: list[int] = [] - - manager.async_on_recorder_ready(lambda: calls.append(1)) - assert calls == [] - await hass.async_block_till_done(wait_background_tasks=True) - assert calls == [1] - - manager.async_on_recorder_ready(lambda: calls.append(2)) - assert calls == [1] - await hass.async_block_till_done(wait_background_tasks=True) - assert calls == [1, 2] - - async def test_async_setup_creates_history_priming_manager( hass: HomeAssistant, ) -> None: @@ -6372,9 +5956,7 @@ async def test_history_priming_manager_serializes_queries( # No pending commit, so flushing is instant and only query serialization # is exercised. with patch.object(instance, "async_get_commit_future", return_value=None): - tasks = [ - asyncio.create_task(manager.async_prime(_job, flush=True)) for _ in range(5) - ] + tasks = [asyncio.create_task(manager.async_prime(_job)) for _ in range(5)] # The first job holds the query lock; the rest must queue behind it. await started.wait() await asyncio.sleep(0) @@ -6426,12 +6008,12 @@ async def test_history_priming_manager_does_not_ride_in_flight_flush( with patch.object(instance, "async_get_commit_future", _spy_commit_future): # C0 claims the flush and is mid-flush (its commit future is pending). - c0 = asyncio.create_task(manager.async_prime(_job, flush=True)) + c0 = asyncio.create_task(manager.async_prime(_job)) await _advance_until(lambda: len(flush_futures) == 1) # Two conditions arrive while C0's flush runs; they must not ride it. - c1 = asyncio.create_task(manager.async_prime(_job, flush=True)) - c2 = asyncio.create_task(manager.async_prime(_job, flush=True)) + c1 = asyncio.create_task(manager.async_prime(_job)) + c2 = asyncio.create_task(manager.async_prime(_job)) # C0's flush completes; C1 then performs a fresh flush and C2 rides it. flush_futures[0].set_result(None) @@ -6471,10 +6053,10 @@ async def test_history_priming_manager_retries_after_cancelled_flush( with patch.object(instance, "async_get_commit_future", _spy_commit_future): # C0 takes the lobby so c1 and c2 form one generation behind it. - c0 = asyncio.create_task(manager.async_prime(_job, flush=True)) + c0 = asyncio.create_task(manager.async_prime(_job)) await _advance_until(lambda: len(flush_futures) == 1) - c1 = asyncio.create_task(manager.async_prime(_job, flush=True)) - c2 = asyncio.create_task(manager.async_prime(_job, flush=True)) + c1 = asyncio.create_task(manager.async_prime(_job)) + c2 = asyncio.create_task(manager.async_prime(_job)) flush_futures[0].set_result(None) assert await c0 == "done" @@ -6514,11 +6096,11 @@ async def test_history_priming_manager_cancelled_lobby_waiter( return "done" with patch.object(instance, "async_get_commit_future", _spy_commit_future): - c0 = asyncio.create_task(manager.async_prime(_job, flush=True)) + c0 = asyncio.create_task(manager.async_prime(_job)) await _advance_until(lambda: len(flush_futures) == 1) # A second priming parks in the lobby (reached in one step, as its lock # acquire is uncontended), then its timeout cancels it. - waiter = asyncio.create_task(manager.async_prime(_job, flush=True)) + waiter = asyncio.create_task(manager.async_prime(_job)) await asyncio.sleep(0) waiter.cancel() with pytest.raises(asyncio.CancelledError): @@ -6527,7 +6109,7 @@ async def test_history_priming_manager_cancelled_lobby_waiter( # C0 finishes; a later priming still flushes and completes normally. flush_futures[0].set_result(None) assert await c0 == "done" - later = asyncio.create_task(manager.async_prime(_job, flush=True)) + later = asyncio.create_task(manager.async_prime(_job)) await _advance_until(lambda: len(flush_futures) == 2) flush_futures[1].set_result(None) assert await later == "done"