From 941ac635b978773743d44af8fb59de4edcaac053 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Tue, 20 Oct 2026 19:48:44 +0100 Subject: [PATCH] Fix race in entity condition history priming (#187604) --- .../helpers/condition/entity_condition.py | 25 +++-- tests/helpers/test_condition.py | 95 +++++++++++++++++++ 2 files changed, 112 insertions(+), 8 deletions(-) diff --git a/homeassistant/helpers/condition/entity_condition.py b/homeassistant/helpers/condition/entity_condition.py index e1e7199ecd3e..699ada0cb56d 100644 --- a/homeassistant/helpers/condition/entity_condition.py +++ b/homeassistant/helpers/condition/entity_condition.py @@ -126,8 +126,10 @@ class EntityConditionBase(Condition): # Entities whose `for:` anchor is currently being resolved from recorder # history. While an entity is here the live listener leaves its anchor to # 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() + # the in-flight history is stale and live tracking takes over). Mapped to + # a token of the priming pass that owns the entity: when passes for an + # entity overlap, only the most recent one applies its result. + self._priming: dict[str, object] = {} def entity_filter(self, entities: set[str]) -> set[str]: """Filter entities matching any of the domain specs.""" @@ -180,7 +182,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. - self._priming.discard(entity_id) + self._priming.pop(entity_id, None) self._valid_since.pop(entity_id, None) @property @@ -283,7 +285,7 @@ class EntityConditionBase(Condition): changes. """ for entity_id in removed: - self._priming.discard(entity_id) + self._priming.pop(entity_id, None) self._valid_since.pop(entity_id, None) await self._async_prime_valid_since(added) @@ -303,7 +305,10 @@ class EntityConditionBase(Condition): While loading, an entity is held in `_priming`. A live change that keeps it valid is ignored (the run is unbroken, history is accurate), but an invalidation removes it from `_priming` so that we do not apply now-stale - history over the live tracking that observed the break. + history over the live tracking that observed the break. If a later pass + takes over the entity, e.g. because it left the target and came back + while this one loaded, this pass leaves the entity to the later one: its + history may predate a break that went unobserved while untracked. """ # Conservative anchor from the live state for each currently-valid entity. anchors = { @@ -316,7 +321,8 @@ class EntityConditionBase(Condition): if not anchors: return - self._priming.update(anchors) + token = object() + self._priming.update(dict.fromkeys(anchors, token)) try: if "recorder" in self._hass.config.components: await self._async_refine_anchors_from_history(anchors) @@ -324,10 +330,13 @@ class EntityConditionBase(Condition): # 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 in self._priming: + # Also skip those a later pass took over. + if self._priming.get(entity_id) is token: self._valid_since[entity_id] = anchor finally: - self._priming.difference_update(anchors) + for entity_id in anchors: + if self._priming.get(entity_id) is token: + del self._priming[entity_id] async def _async_refine_anchors_from_history( self, anchors: dict[str, datetime] diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index bd5e17bee83c..7b421dc98b67 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -5880,6 +5880,101 @@ async def test_state_condition_attr_duration_invalidation_during_load_discards_h assert test.async_check() is False +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_overlapping_loads_latest_wins( + recorder_mock: Recorder, hass: HomeAssistant +) -> None: + """When loads for an entity overlap, only the most recent one applies. + + The entity leaves the target and comes back while its history loads. Its run + breaks while it is not tracked, which the first load's history predates, so + only the second load's result is accurate. + """ + label_reg = lr.async_get(hass) + label = label_reg.async_create("Overlapping Loads") + entity_reg = er.async_get(hass) + entry = entity_reg.async_get_or_create( + domain="test", platform="test", unique_id="overlapping_loads" + ) + entity_id = entry.entity_id + instance = get_instance(hass) + + start = dt_util.utcnow() + with freeze_time(start) as freezer: + # Valid since t=0. + hass.states.async_set(entity_id, STATE_ON, {"test_attr": True}) + await hass.async_block_till_done() + await async_wait_recording_done(hass) + stale_history = await instance.async_add_executor_job( + _read_attr_history, hass, start - timedelta(minutes=1), entity_id + ) + + freezer.move_to(start + timedelta(seconds=10)) + test = await _setup_attr_state_condition_with_target( + hass, + target={ATTR_LABEL_ID: label.label_id}, + states={True}, + condition_options={CONF_FOR: {"seconds": 5}}, + ) + + real_query = history.get_significant_states + stale_reads = 1 + + def _read(*args: Any, **kwargs: Any) -> Any: + # The first load's read predates the dip. + nonlocal stale_reads + if not stale_reads: + return real_query(*args, **kwargs) + stale_reads -= 1 + return stale_history + + gate: asyncio.Future[None] = hass.loop.create_future() + with ( + patch.object(instance, "async_get_commit_future", return_value=gate), + patch( + "homeassistant.components.recorder.history.get_significant_states", + side_effect=_read, + ), + ): + # The first load blocks on the held flush. + entity_reg.async_update_entity(entity_id, labels={label.label_id}) + await hass.async_block_till_done() + + # Untracked, the entity is invalid at t=11 and valid again at t=12. + entity_reg.async_update_entity(entity_id, labels=set()) + await hass.async_block_till_done() + 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() + await async_wait_recording_done(hass) + + # Tracked again: a second load starts while the first is in flight. + entity_reg.async_update_entity(entity_id, labels={label.label_id}) + await hass.async_block_till_done() + + gate.set_result(None) + await hass.async_block_till_done(wait_background_tasks=True) + + # Valid only since t=12, not since t=0 as the first load's history says. + freezer.move_to(start + timedelta(seconds=15)) + assert test.async_check() is False + + async def test_state_condition_attr_duration_history_flushes_before_query( recorder_mock: Recorder, hass: HomeAssistant ) -> None: