HASS.Agent-Integration icon indicating copy to clipboard operation
HASS.Agent-Integration copied to clipboard

Device registry update called from thread outside event loop (causes RuntimeError in Home Assistant 2024.6+)

Open KotsAO opened this issue 4 months ago • 2 comments

When HASS.Agent Integration receives a devices MQTT message (topic: hass.agent/devices/...), it tries to update the Home Assistant device registry from a non-main thread (not the event loop).

Starting with Home Assistant 2024.6, such calls raise a RuntimeError:

RuntimeError: Detected code that calls device_registry.async_update_device from a thread other than the event loop, which may cause Home Assistant to crash or data to corrupt.

This happens specifically in: File "/config/custom_components/hass_agent/init.py", line 144, in updated update_device_info(hass, entry, payload)

This is caused by calling device_registry.async_get_or_create or device_registry.async_update_device from inside an MQTT message callback, which runs outside the main thread.

Related Home Assistant documentation: https://developers.home-assistant.io/docs/asyncio_thread_safety/#device_registryasync_update_device

Steps to reproduce:

  1. Enable devices MQTT publishing in HASS.Agent.
  2. Send a devices payload to Home Assistant via MQTT.
  3. Observe the RuntimeError in the logs.

Why it matters: This issue may cause crashes or corruption of the Home Assistant device registry. It also floods the logs every time a devices MQTT message is received.

Suggested solution: Use hass.add_job or asyncio.run_coroutine_threadsafe to ensure the registry update runs inside the event loop.

KotsAO avatar Jul 08 '25 05:07 KotsAO