Skip to content

Home Information - Your home, your data, organized.

Python

Fixed cache-invalidation bug on intergration syncs.

Anthony Cassandra4109d5ed3cb6
diff --git a/src/hi/apps/control/controller_manager.py b/src/hi/apps/control/controller_manager.py
index ec2b3988..05435dc0 100644
--- a/src/hi/apps/control/controller_manager.py
+++ b/src/hi/apps/control/controller_manager.py
@@ -42,7 +42,7 @@ class ControllerManager( Singleton ):
if settings.DEBUG and settings.DEBUG_TRACE_STATE:
DevOverrideManager.trace_state(
'hi.control.out',
- ha_entity_id = integration_details.key.integration_name,
+ integration_name = integration_details.key.integration_name,
hi_entity_state_id = controller.entity_state.id,
hi_value = control_value,
)
diff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.py
index 7189413b..7a559c9e 100644
--- a/src/hi/apps/monitor/status_display_manager.py
+++ b/src/hi/apps/monitor/status_display_manager.py
@@ -46,7 +46,7 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
latest = status_display_data.sensor_response_list[ 0 ]
DevOverrideManager.trace_state(
'hi.ui_poll.entity_state.out',
- ha_entity_id = latest.integration_key.integration_name,
+ integration_name = latest.integration_key.integration_name,
hi_entity_state_id = status_display_data.entity_state.id,
hi_value = latest.value,
row = status_map[ state_id_key ],
diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.py
index 0bc80822..024bfc22 100644
--- a/src/hi/apps/sense/sensor_response_manager.py
+++ b/src/hi/apps/sense/sensor_response_manager.py
@@ -85,6 +85,31 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
# Any future heavyweight initializations go here (e.g., any DB operations).
self._was_initialized = True
return
+
+ def invalidate_local_sensor_cache(self):
+ """Drop the in-process IntegrationKey → Sensor lookup cache
+ and mark the in-memory latest-responses map stale. Leaves
+ the Redis-backed sensor response data untouched (its keys
+ are integration_key strings, which are stable across
+ re-import).
+
+ Called by the integration framework after any operation that
+ creates, refreshes, or removes Sensors with integration_keys
+ (sync, disable). Symmetric with
+ ``IntegrationMetadataCache.invalidate()``.
+
+ Necessary because ``_sensor_cache`` holds Python ``Sensor``
+ model instances keyed by integration_key. After re-import
+ the integration_key is reused (it's derived from the
+ external ID, which doesn't change) but the underlying DB
+ row has a new PK and a new ``entity_state`` link. Without
+ invalidation, the polling read path returns the stale
+ Sensor object, the status map is keyed by the deleted
+ EntityState's PK, and the client's DOM (rendered with new
+ PKs) silently fails to update for up to the 300s TTL."""
+ self._sensor_cache.clear()
+ self._latest_sensor_data_dirty = True
+ return
async def update_with_latest_sensor_responses(
self,
@@ -119,7 +144,7 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
sensor = latest_sensor_response.sensor
DevOverrideManager.trace_state(
'hi.sensor.skip',
- ha_entity_id = integration_key.integration_name,
+ integration_name = integration_key.integration_name,
hi_entity_state_id = sensor.entity_state.id if sensor else None,
hi_value = latest_sensor_response.value,
)
@@ -136,7 +161,7 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
sensor = latest_sensor_response.sensor
DevOverrideManager.trace_state(
'hi.sensor.commit',
- ha_entity_id = integration_key.integration_name,
+ integration_name = integration_key.integration_name,
hi_entity_state_id = sensor.entity_state.id if sensor else None,
hi_value = f'{previous_sensor_response.value} -> {latest_sensor_response.value}',
)
@@ -145,7 +170,7 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
sensor = latest_sensor_response.sensor
DevOverrideManager.trace_state(
'hi.sensor.first',
- ha_entity_id = integration_key.integration_name,
+ integration_name = integration_key.integration_name,
hi_entity_state_id = sensor.entity_state.id if sensor else None,
hi_value = latest_sensor_response.value,
)
diff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.py
index c6d5cc18..8e92818b 100644
--- a/src/hi/integrations/views.py
+++ b/src/hi/integrations/views.py
@@ -19,6 +19,7 @@ from hi.apps.config.views import ConfigPageView
from hi.apps.entity.entity_placement import EntityPlacementService
from hi.apps.entity.models import Entity
from hi.apps.location.models import LocationView
+from hi.apps.sense.sensor_response_manager import SensorResponseManager
from .placement_request import PlacementFormParser, PlacementUrlParams
from .entity_operations import EntityIntegrationOperations
@@ -218,6 +219,13 @@ class IntegrationSyncView( HiModalView, IntegrationViewMixin ):
# in the UI until the server restarts. ``finally`` so a
# partial-commit failure during sync also flushes.
IntegrationMetadataCache().invalidate()
+ # Drop the in-process Sensor lookup cache so subsequent
+ # polling reads pick up the new Sensor rows. Re-imported
+ # entities reuse their integration_keys but get new DB
+ # PKs and new EntityState links; without this, the
+ # polling status map keys responses by stale (deleted)
+ # EntityState PKs and the UI silently fails to update.
+ SensorResponseManager().invalidate_local_sensor_cache()
# Scope the placement to just the entities this sync created.
# Without scoping, the placement's GET endpoint queries every
@@ -578,6 +586,7 @@ class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
# don't return stale entries that reference deleted
# rows. Symmetric with the post-sync invalidation.
IntegrationMetadataCache().invalidate()
+ SensorResponseManager().invalidate_local_sensor_cache()
redirect_url = reverse( 'integrations_home' )
return self.redirect_response( request, redirect_url )
diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.py
index 9be8bf2e..9ea4ce77 100644
--- a/src/hi/services/hass/monitors.py
+++ b/src/hi/services/hass/monitors.py
@@ -110,8 +110,8 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):
if settings.DEBUG and settings.DEBUG_TRACE_STATE:
DevOverrideManager.trace_state(
'hi.ha_poll.in',
- ha_entity_id = hass_state.entity_id,
- ha_value = hass_state.state_value,
+ integration_name = hass_state.entity_id,
+ integration_value = hass_state.state_value,
device_class = hass_state.device_class,
value_map = { str(k): v for k, v in value_map.items() },
)
diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.py
index 2d897d16..08d3c472 100644
--- a/src/hi/services/zoneminder/monitors.py
+++ b/src/hi/services/zoneminder/monitors.py
@@ -3,6 +3,8 @@ from datetime import datetime
import logging
from .pyzm_client.helpers.Monitor import Monitor as ZmMonitor
+from django.conf import settings
+
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.alert.enums import AlarmLevel
from hi.apps.entity.enums import EntityStateValue
@@ -11,6 +13,7 @@ from hi.apps.sense.sensor_response_manager import SensorResponseMixin
from hi.apps.sense.transient_models import SensorResponse
from hi.apps.sense.enums import CorrelationRole
from hi.apps.system.provider_info import ProviderInfo
+from hi.testing.dev_overrides import DevOverrideManager
from .constants import ZmDetailKeys, ZmTimeouts
from .zm_models import ZmEvent, AggregatedMonitorState
@@ -196,6 +199,14 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
timestamp = current_poll_datetime,
)
sensor_response_map[idle_sensor_response.integration_key] = idle_sensor_response
+
+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:
+ DevOverrideManager.trace_state(
+ 'hi.zm_poll.no_events',
+ integration_name = idle_sensor_response.integration_key.integration_name,
+ integration_value = idle_sensor_response.value,
+ monitor_id = zm_monitor.id(),
+ )
continue
if open_zm_event_list:
@@ -293,11 +304,23 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
sensor_response = self._create_movement_active_sensor_response(state.canonical_event)
else: # state.is_idle
sensor_response = self._create_movement_idle_sensor_response(state.canonical_event)
-
+
# Use our calculated effective timestamp
sensor_response.timestamp = state.effective_timestamp
-
+
sensor_response_map[sensor_response.integration_key] = sensor_response
+
+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:
+ DevOverrideManager.trace_state(
+ 'hi.zm_poll.events',
+ integration_name = sensor_response.integration_key.integration_name,
+ integration_value = sensor_response.value,
+ monitor_id = monitor_id,
+ event_count = len( state.all_events ),
+ canonical_event_id = (
+ state.canonical_event.event_id if state.canonical_event else None
+ ),
+ )
# Update event processing caches to avoid reprocessing from ZM API
for zm_event in state.all_events:
@@ -320,10 +343,18 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
timestamp = current_poll_datetime,
)
sensor_response_map[function_sensor_response.integration_key] = function_sensor_response
+
+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:
+ DevOverrideManager.trace_state(
+ 'hi.zm_poll.function',
+ integration_name = function_sensor_response.integration_key.integration_name,
+ integration_value = str( zm_monitor.function() ),
+ monitor_id = zm_monitor.id(),
+ )
continue
-
+
return sensor_response_map
-
+
async def _process_states(self):
current_poll_datetime = datetimeproxy.now()
sensor_response_map = dict()
@@ -342,7 +373,14 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
timestamp = current_poll_datetime,
)
sensor_response_map[run_state_sensor_response.integration_key] = run_state_sensor_response
-
+
+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:
+ DevOverrideManager.trace_state(
+ 'hi.zm_poll.run_state',
+ integration_name = run_state_sensor_response.integration_key.integration_name,
+ integration_value = active_run_state_name,
+ )
+
return sensor_response_map
def _has_video_stream_capability(self, detail_attrs: dict = None) -> bool:
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index 90f8480c..0a06421c 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -415,16 +415,16 @@ DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE = False
# For testing UI error display of the various attribute editing form errors.
DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS = False
-# Per-state tracing for debugging value flow across the HA
-# integration and the simulator. The master switch is
-# ``DEBUG_TRACE_STATE``; main-code call sites short-circuit on
+# Per-state tracing for debugging value flow across any
+# integration (HA, ZM, etc.) and the simulator. The master switch
+# is ``DEBUG_TRACE_STATE``; main-code call sites short-circuit on
# it for zero overhead when off. When on, the trace dispatcher
-# consults ``DEBUG_TRACE_HA_ENTITY_IDS`` (HA entity_ids; matched
-# against the integration_name with any ``~suffix`` stripped, so
-# a single entry like ``cover.x`` catches its substate variants)
-# and ``DEBUG_TRACE_HI_ENTITY_STATE_IDS`` (HI EntityState PKs)
-# for granularity. ``settings.DEBUG`` must also be True. See
+# consults ``DEBUG_TRACE_INTEGRATION_NAMES`` (matched against
+# the integration_name with any ``~suffix`` stripped, so a single
+# entry like ``cover.x`` catches its substate variants) and
+# ``DEBUG_TRACE_HI_ENTITY_STATE_IDS`` (HI EntityState PKs) for
+# granularity. ``settings.DEBUG`` must also be True. See
# ``hi.testing.dev_overrides.StateTraceManager``.
DEBUG_TRACE_STATE = False
-DEBUG_TRACE_HA_ENTITY_IDS = [ ] # strings / integration_key.name
+DEBUG_TRACE_INTEGRATION_NAMES = [ ] # strings / integration_key.name
DEBUG_TRACE_HI_ENTITY_STATE_IDS = [ ] # ints / EntityState database ids
diff --git a/src/hi/settings/development.py b/src/hi/settings/development.py
index 35133672..cd684483 100644
--- a/src/hi/settings/development.py
+++ b/src/hi/settings/development.py
@@ -164,8 +164,8 @@ DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS = False
# Per-state tracing for debugging value flow. Set
# ``DEBUG_TRACE_STATE = True`` and populate one or both id lists
-# with the specific HA entity_ids and/or HI EntityState PKs to
-# instrument.
+# with the specific integration_names and/or HI EntityState PKs
+# to instrument.
DEBUG_TRACE_STATE = False
-DEBUG_TRACE_HA_ENTITY_IDS = [] # strings / integration_key.name
-DEBUG_TRACE_HI_ENTITY_STATE_IDS = [] # ints / EntityState database ids
+DEBUG_TRACE_INTEGRATION_NAMES = [ ] # strings / integration_key.name
+DEBUG_TRACE_HI_ENTITY_STATE_IDS = [ ] # ints / EntityState database ids
diff --git a/src/hi/testing/dev_overrides.py b/src/hi/testing/dev_overrides.py
index 74f7b1eb..51eb547a 100644
--- a/src/hi/testing/dev_overrides.py
+++ b/src/hi/testing/dev_overrides.py
@@ -102,20 +102,20 @@ class DevOverrideManager:
@classmethod
def trace_state( cls,
label : str,
- ha_entity_id : Optional[ str ] = None,
+ integration_name : Optional[ str ] = None,
hi_entity_state_id : Optional[ int ] = None,
- ha_value : Any = None,
+ integration_value : Any = None,
hi_value : Any = None,
**kwargs : Any ) -> None:
if not StateTraceManager.is_traced(
- ha_entity_id = ha_entity_id,
+ integration_name = integration_name,
hi_entity_state_id = hi_entity_state_id ):
return
StateTraceManager.emit(
label = label,
- ha_entity_id = ha_entity_id,
+ integration_name = integration_name,
hi_entity_state_id = hi_entity_state_id,
- ha_value = ha_value,
+ integration_value = integration_value,
hi_value = hi_value,
**kwargs,
)
@@ -123,18 +123,18 @@ class DevOverrideManager:
class StateTraceManager:
"""
- Per-state tracing for debugging value flow across the HA
- integration and the simulator.
+ Per-state tracing for debugging value flow across any
+ integration (HA, ZM, etc.) and the simulator.
Reached from main code only via ``DevOverrideManager.trace_state``;
main-code sites short-circuit on
``settings.DEBUG and settings.DEBUG_TRACE_STATE`` so this class
is only consulted when tracing is on.
- Granularity is set by ``DEBUG_TRACE_HA_ENTITY_IDS`` (HA
- entity_ids; the matcher strips any ``~suffix`` so a single
- entry like ``'cover.x'`` catches its substate variants) and
- ``DEBUG_TRACE_HI_ENTITY_STATE_IDS`` (HI EntityState PKs).
+ Granularity is set by ``DEBUG_TRACE_INTEGRATION_NAMES``
+ (integration_names; the matcher strips any ``~suffix`` so a
+ single entry like ``'cover.x'`` catches its substate variants)
+ and ``DEBUG_TRACE_HI_ENTITY_STATE_IDS`` (HI EntityState PKs).
Output goes to the dedicated ``hi.state_trace`` logger at
INFO so verbosity can be scoped independently of other
loggers.
@@ -142,11 +142,11 @@ class StateTraceManager:
@classmethod
def is_traced( cls,
- ha_entity_id : Optional[ str ] = None,
+ integration_name : Optional[ str ] = None,
hi_entity_state_id : Optional[ int ] = None ) -> bool:
- if ha_entity_id:
- target = ha_entity_id.split( '~', 1 )[ 0 ]
- if target in settings.DEBUG_TRACE_HA_ENTITY_IDS:
+ if integration_name:
+ target = integration_name.split( '~', 1 )[ 0 ]
+ if target in settings.DEBUG_TRACE_INTEGRATION_NAMES:
return True
if hi_entity_state_id is not None:
if hi_entity_state_id in settings.DEBUG_TRACE_HI_ENTITY_STATE_IDS:
@@ -156,29 +156,29 @@ class StateTraceManager:
# Tabular column widths. Generous so common values fit without
# disrupting alignment; long values overflow the slot and
# disrupt only their own row, not subsequent ones.
- LABEL_W = 28
- HA_ID_W = 42
- HA_VAL_W = 14
- HI_ID_W = 6
- HI_VAL_W = 26
+ LABEL_W = 28
+ INTEGRATION_NAME_W = 42
+ INTEGRATION_VAL_W = 14
+ HI_ID_W = 6
+ HI_VAL_W = 26
@classmethod
def emit( cls,
label : str,
- ha_entity_id : Optional[ str ] = None,
+ integration_name : Optional[ str ] = None,
hi_entity_state_id : Optional[ int ] = None,
- ha_value : Any = None,
+ integration_value : Any = None,
hi_value : Any = None,
**kwargs : Any ) -> None:
- ha_id_str = ha_entity_id or ''
- hi_id_str = '' if hi_entity_state_id is None else str( hi_entity_state_id )
- ha_val_str = '' if ha_value is None else str( ha_value )
- hi_val_str = '' if hi_value is None else str( hi_value )
- extras_str = ' '.join( f'{k}={v}' for k, v in kwargs.items() )
+ int_name_str = integration_name or ''
+ hi_id_str = '' if hi_entity_state_id is None else str( hi_entity_state_id )
+ int_val_str = '' if integration_value is None else str( integration_value )
+ hi_val_str = '' if hi_value is None else str( hi_value )
+ extras_str = ' '.join( f'{k}={v}' for k, v in kwargs.items() )
line = (
f'{label:<{cls.LABEL_W}} | '
- f'{ha_id_str:<{cls.HA_ID_W}} | '
- f'{ha_val_str:<{cls.HA_VAL_W}} | '
+ f'{int_name_str:<{cls.INTEGRATION_NAME_W}} | '
+ f'{int_val_str:<{cls.INTEGRATION_VAL_W}} | '
f'{hi_id_str:<{cls.HI_ID_W}} | '
f'{hi_val_str:<{cls.HI_VAL_W}} | '
f'{extras_str}'