From c877b970b72f2932af4b22eedcb902211ee6c8bb Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Fri, 16 Oct 2026 12:10:25 -0400 Subject: [PATCH] Prevent pending writes from restoring removed storage (#186489) --- homeassistant/helpers/storage.py | 6 +++-- tests/helpers/test_storage.py | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/homeassistant/helpers/storage.py b/homeassistant/helpers/storage.py index 504385d0cb5c..f9ab8ad0fc03 100644 --- a/homeassistant/helpers/storage.py +++ b/homeassistant/helpers/storage.py @@ -666,8 +666,10 @@ class Store[_T: Mapping[str, Any] | Sequence[Any]]: async def async_remove(self) -> None: """Remove all data.""" - self._io.async_invalidate_cache() + self._data = None self._async_cleanup_delay_listener() self._async_cleanup_final_write_listener() - await self._io.async_remove() + async with self._write_lock: + self._io.async_invalidate_cache() + await self._io.async_remove() diff --git a/tests/helpers/test_storage.py b/tests/helpers/test_storage.py index 058ec6894789..c97d18661808 100644 --- a/tests/helpers/test_storage.py +++ b/tests/helpers/test_storage.py @@ -93,6 +93,44 @@ async def test_loading(hass: HomeAssistant, store: storage.Store) -> None: assert data == MOCK_DATA +async def test_remove_pending_save(store: storage.Store) -> None: + """Removal discards delayed data instead of returning it on the next load.""" + await store.async_save(MOCK_DATA) + store.async_delay_save(lambda: MOCK_DATA2, 60) + + await store.async_remove() + + assert await store.async_load() is None + + +async def test_remove_during_write( + hass: HomeAssistant, store: storage.Store, hass_storage: dict[str, Any] +) -> None: + """An active write cannot recreate removed storage.""" + write_started = asyncio.Event() + finish_write = asyncio.Event() + async_write = store._io.async_write + + async def blocked_write(mode: str, data: str | bytes) -> None: + write_started.set() + await finish_write.wait() + await async_write(mode, data) + + with patch.object(store._io, "async_write", side_effect=blocked_write): + write_task = hass.async_create_task(store.async_save(MOCK_DATA)) + await write_started.wait() + remove_task = hass.async_create_task(store.async_remove()) + await asyncio.sleep(0) + finish_write.set() + await asyncio.gather(write_task, remove_task) + + assert MOCK_KEY not in hass_storage + assert await store.async_load() is None + + await store.async_save(MOCK_DATA2) + assert await store.async_load() == MOCK_DATA2 + + async def test_custom_encoder(hass: HomeAssistant) -> None: """Test we can save and load data."""