diff --git a/homeassistant/components/recorder/migration.py b/homeassistant/components/recorder/migration.py index 2e2b22ac3da..1d2b56fb434 100644 --- a/homeassistant/components/recorder/migration.py +++ b/homeassistant/components/recorder/migration.py @@ -1481,6 +1481,7 @@ def migrate_event_type_ids(instance: Recorder) -> bool: event_type_to_id[ db_event_type.event_type ] = db_event_type.event_type_id + event_type_manager.clear_non_existent(db_event_type.event_type) session.execute( update(Events), diff --git a/homeassistant/components/recorder/table_managers/event_types.py b/homeassistant/components/recorder/table_managers/event_types.py index 465e8608661..d5541c547d5 100644 --- a/homeassistant/components/recorder/table_managers/event_types.py +++ b/homeassistant/components/recorder/table_managers/event_types.py @@ -120,9 +120,17 @@ class EventTypeManager(BaseLRUTableManager[EventTypes]): """ for event_type, db_event_types in self._pending.items(): self._id_map[event_type] = db_event_types.event_type_id - self._non_existent_event_types.pop(event_type, None) + self.clear_non_existent(event_type) self._pending.clear() + def clear_non_existent(self, event_type: str) -> None: + """Clear a non-existent event type from the cache. + + This call is not thread-safe and must be called from the + recorder thread. + """ + self._non_existent_event_types.pop(event_type, None) + def evict_purged(self, event_types: Iterable[str]) -> None: """Evict purged event_types from the cache when they are no longer used. diff --git a/tests/components/recorder/test_migration_from_schema_32.py b/tests/components/recorder/test_migration_from_schema_32.py index f76cf318008..2ae32018213 100644 --- a/tests/components/recorder/test_migration_from_schema_32.py +++ b/tests/components/recorder/test_migration_from_schema_32.py @@ -553,6 +553,16 @@ async def test_migrate_event_type_ids( assert len(events_by_type["event_type_one"]) == 2 assert len(events_by_type["event_type_two"]) == 1 + def _get_many(): + with session_scope(hass=hass, read_only=True) as session: + return instance.event_type_manager.get_many( + ("event_type_one", "event_type_two"), session + ) + + mapped = await instance.async_add_executor_job(_get_many) + assert mapped["event_type_one"] is not None + assert mapped["event_type_two"] is not None + @pytest.mark.parametrize("enable_migrate_entity_ids", [True]) async def test_migrate_entity_ids(