Home Information - Your home, your data, organized.
Python
Issue #283: Periodic 'needs sync' check with user notification (#292)
Tony C5c85893633b1
diff --git a/src/hi/apps/alert/alarm.py b/src/hi/apps/alert/alarm.pyindex 62c09fd6..b75d3bf8 100644--- a/src/hi/apps/alert/alarm.py+++ b/src/hi/apps/alert/alarm.py@@ -11,6 +11,15 @@ from .enums import AlarmLevel, AlarmSource@dataclassclass Alarm:++ # Practical "never expires" lifetime — long enough that the alarm+ # persists until the user acknowledges it under any realistic+ # scenario, while keeping ``end_datetime`` always a valid datetime+ # so consumers do not need a None / special-case branch. Use this+ # value (not zero, not None) when constructing an alarm that+ # should remain visible until acknowledged.+ MAX_LIFETIME_SECS = 365 * 24 * 60 * 60+alarm_source : AlarmSourcealarm_type : stralarm_level : AlarmLevel@@ -20,6 +29,23 @@ class Alarm:alarm_lifetime_secs : inttimestamp : datetime+ def __post_init__(self):+ # The lifetime field drives ``Alert.end_datetime``; zero or+ # negative values produce an already-expired alert (a+ # historical bug with the previous "0 = until acknowledged"+ # convention) and values above MAX exceed the practical+ # "never expires" intent. Enforce the supported range here so+ # mistakes show up at construction, not silently as+ # vanished alarms.+ assert (+ ( self.alarm_lifetime_secs > 0 )+ and ( self.alarm_lifetime_secs <= self.MAX_LIFETIME_SECS )+ ), (+ f'alarm_lifetime_secs out of range: {self.alarm_lifetime_secs}; '+ f'must be in (0, {self.MAX_LIFETIME_SECS}].'+ )+ return+@propertydef audio_signal(self):# Enhanced to support alarm-specific sounds based on level, source, and type.diff --git a/src/hi/apps/alert/enums.py b/src/hi/apps/alert/enums.pyindex 03961f47..c2a83419 100644--- a/src/hi/apps/alert/enums.py+++ b/src/hi/apps/alert/enums.py@@ -7,6 +7,7 @@ class AlarmSource( LabeledEnum ):WEATHER = ( 'Weather' , '' )CONSOLE = ( 'Console' , '' )HEALTH_STATUS = ( 'Health Status' , '' )+ INTEGRATION = ( 'Integration' , '' )class AlarmLevel( LabeledEnum ):diff --git a/src/hi/apps/alert/tests/test_alert_queue.py b/src/hi/apps/alert/tests/test_alert_queue.pyindex 0f07158f..34e7fe03 100644--- a/src/hi/apps/alert/tests/test_alert_queue.py+++ b/src/hi/apps/alert/tests/test_alert_queue.py@@ -345,8 +345,17 @@ class TestAlertQueue(BaseTestCase):returndef test_alert_queue_remove_expired_alerts(self):- """Test remove_expired_or_acknowledged_alerts - critical for cleanup."""- # Create expired alarm (negative lifetime to force expiration)+ """Test remove_expired_or_acknowledged_alerts - critical for cleanup.++ Advances ``datetimeproxy`` past the alarm's expiration rather+ than constructing an alarm with non-positive lifetime+ (``Alarm.__post_init__`` rejects that). The alert system+ consults ``datetimeproxy.now()`` for ``end_datetime``+ comparison, so the simulated clock advance is what makes the+ cleanup observe the alarm as expired.+ """+ from datetime import timedelta+ baseline = datetimeproxy.now()expired_alarm = Alarm(alarm_source=AlarmSource.EVENT,alarm_type='expired_test',@@ -354,30 +363,37 @@ class TestAlertQueue(BaseTestCase):title='Expired Alarm',sensor_response_list=[],security_level=SecurityLevel.LOW,- alarm_lifetime_secs=-1, # Expired immediately- timestamp=datetimeproxy.now(),+ alarm_lifetime_secs=1,+ timestamp=baseline,)# Add expired and active alarmsexpired_alert = self.queue.add_alarm(expired_alarm)active_alert = self.queue.add_alarm(self.test_alarm)-+initial_count = len(self.queue)self.assertEqual(initial_count, 2)-- # Run cleanup- self.queue.remove_expired_or_acknowledged_alerts()-- # Should remove expired alert but keep active one- self.assertEqual(len(self.queue), 1)-- # Should not find expired alert- with self.assertRaises(KeyError):- self.queue.get_alert(expired_alert.id)-- # Should still find active alert- found_alert = self.queue.get_alert(active_alert.id)- self.assertEqual(found_alert, active_alert)++ # Advance the simulated clock past the expired alarm's end+ # but still before the active alarm's. The cleanup pass reads+ # the time via ``datetimeproxy.now()`` so this is sufficient+ # to make it observe the first alarm as expired.+ datetimeproxy.set(baseline + timedelta(seconds=10))+ try:+ self.queue.remove_expired_or_acknowledged_alerts()++ # Should remove expired alert but keep active one+ self.assertEqual(len(self.queue), 1)++ # Should not find expired alert+ with self.assertRaises(KeyError):+ self.queue.get_alert(expired_alert.id)++ # Should still find active alert+ found_alert = self.queue.get_alert(active_alert.id)+ self.assertEqual(found_alert, active_alert)+ finally:+ datetimeproxy.reset()returndef test_alert_queue_remove_acknowledged_alerts(self):diff --git a/src/hi/apps/event/migrations/0007_replace_zero_alarm_lifetime.py b/src/hi/apps/event/migrations/0007_replace_zero_alarm_lifetime.pynew file mode 100644index 00000000..6a6d5be5--- /dev/null+++ b/src/hi/apps/event/migrations/0007_replace_zero_alarm_lifetime.py@@ -0,0 +1,49 @@+"""+Repair existing AlarmAction rows whose ``alarm_lifetime_secs`` was+set to zero by the previous "0 = until acknowledged" convention. The+alarm-queue layer never honored that intent — it treated zero as+"expires immediately", which made connectivity and battery alarms+silently vanish on creation.++The new contract (see ``Alarm.MAX_LIFETIME_SECS`` and+``Alarm.__post_init__``): use the explicit MAX value for+"effectively never expires"; zero is rejected at construction. This+migration normalizes any pre-existing zero rows to the same MAX so+their alarms behave correctly going forward.++Reverse path is intentionally a no-op — once normalized to MAX, the+original zero values are not preserved (they were broken anyway).+"""+from django.db import migrations+++# Inlined to avoid importing from ``hi.apps.alert.alarm`` inside a+# migration: imports of app-level models from migrations are fragile+# during squash / rebuild cycles. This value must stay in sync with+# ``Alarm.MAX_LIFETIME_SECS``.+_MAX_LIFETIME_SECS = 365 * 24 * 60 * 60+++def replace_zero_alarm_lifetime(apps, schema_editor):+ AlarmAction = apps.get_model('event', 'AlarmAction')+ AlarmAction.objects.filter(alarm_lifetime_secs=0).update(+ alarm_lifetime_secs=_MAX_LIFETIME_SECS,+ )+++def noop_reverse(apps, schema_editor):+ return+++class Migration(migrations.Migration):++ dependencies = [+ ('event', '0006_add_previous_integration_identity'),+ ]++ operations = [+ migrations.RunPython(+ replace_zero_alarm_lifetime,+ noop_reverse,+ ),+ ]diff --git a/src/hi/apps/event/models.py b/src/hi/apps/event/models.pyindex 79a0d1dd..c82dd87e 100644--- a/src/hi/apps/event/models.py+++ b/src/hi/apps/event/models.py@@ -135,9 +135,11 @@ class AlarmAction( models.Model ):null = False, blank = False,)- # How long will this alarm be relevant to the user. Alarms exist until- # they expire or are acknowledged. Set this to zero for ann alarm that- # will only be dismissed by a user acknowledgement.+ # How long will this alarm be relevant to the user. Alarms exist+ # until they expire or are acknowledged. Use ``Alarm.MAX_LIFETIME_SECS``+ # for an alarm that should remain visible until the user+ # acknowledges it (zero would expire immediately and is rejected+ # by ``Alarm.__post_init__``).#alarm_lifetime_secs = models.PositiveIntegerField('Lifetime Secs',diff --git a/src/hi/apps/event/tests/test_models.py b/src/hi/apps/event/tests/test_models.pyindex 7ee776e8..7d403243 100644--- a/src/hi/apps/event/tests/test_models.py+++ b/src/hi/apps/event/tests/test_models.py@@ -580,28 +580,6 @@ class TestAlarmActionAdvanced(BaseTestCase):self.assertEqual(alarm_action.alarm_level, AlarmLevel.NONE) # from_name_safe returns default (first enum)return- def test_alarm_action_zero_lifetime_manual_acknowledgment(self):- """Test alarm action with zero lifetime for manual acknowledgment only."""- event_def = EventDefinition.objects.create(- name='Manual Alarm Event',- event_type_str='SECURITY',- event_window_secs=60,- dedupe_window_secs=300,- integration_id='test_id',- integration_name='test_integration'- )-- alarm_action = AlarmAction.objects.create(- event_definition=event_def,- security_level_str='CRITICAL',- alarm_level_str='CRITICAL',- alarm_lifetime_secs=0 # Manual acknowledgment only- )-- # Zero lifetime should indicate manual acknowledgment requirement- self.assertEqual(alarm_action.alarm_lifetime_secs, 0)- return-def test_alarm_action_multiple_per_event_definition(self):"""Test multiple alarm actions for different security levels."""event_def = EventDefinition.objects.create(diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.pyindex 14c69dac..c1068ed7 100644--- a/src/hi/apps/model_helper.py+++ b/src/hi/apps/model_helper.py@@ -1,6 +1,7 @@import jsonfrom typing import Dict+from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevelfrom hi.apps.control.enums import ControllerTypefrom hi.apps.control.models import Controller@@ -32,8 +33,8 @@ class HiModelHelper:DEFAULT_CONNECTIVITY_EVENT_WINDOW_SECS = 180DEFAULT_CONNECTIVITY_DEDUPE_WINDOW_SECS = 300- DEFAULT_CONNECTIVITY_ALARM_LIFETIME_SECS = 0-+ DEFAULT_CONNECTIVITY_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS+DEFAULT_OPEN_CLOSE_EVENT_WINDOW_SECS = 180DEFAULT_OPEN_CLOSE_DEDUPE_WINDOW_SECS = 300DEFAULT_OPEN_CLOSE_ALARM_LIFETIME_SECS = 600@@ -44,7 +45,7 @@ class HiModelHelper:DEFAULT_BATTERY_EVENT_WINDOW_SECS = 180DEFAULT_BATTERY_DEDUPE_WINDOW_SECS = 300- DEFAULT_BATTERY_ALARM_LIFETIME_SECS = 0+ DEFAULT_BATTERY_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS@classmethoddef create_blob_sensor( cls,diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.htmlindex 2e51e5bc..afd9a2dd 100644--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html@@ -34,7 +34,7 @@</div></div><div class="col-6 align-self-center">- <a href="{{ sensor_response.click_url }}" title="See details">+ <a href="{{ sensor_response.click_url }}" title="See details" data-async="true"><div class="{{ sensor_response.css_class }}">{% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}</div>diff --git a/src/hi/apps/system/templates/system/panes/system_info.html b/src/hi/apps/system/templates/system/panes/system_info.htmlindex 5d053db7..427a2087 100644--- a/src/hi/apps/system/templates/system/panes/system_info.html+++ b/src/hi/apps/system/templates/system/panes/system_info.html@@ -48,6 +48,11 @@{% empty %}<div class="col-12 text-secondary"><em>No integrations configured.</em></div>{% endfor %}+ {% for provider in framework_health_providers %}+ <div class="col-lg-6 col-md-12 mb-3">+ {% include "system/panes/health_status_card.html" with health_status_provider=provider %}+ </div>+ {% endfor %}</div><!-- Weather Sources Section -->diff --git a/src/hi/apps/system/views.py b/src/hi/apps/system/views.pyindex e7512c4a..c7f34a2b 100644--- a/src/hi/apps/system/views.py+++ b/src/hi/apps/system/views.py@@ -50,9 +50,14 @@ class SystemInfoView( ConfigPageView ):key = lambda data: data.integration_metadata.label,)]+ framework_health_providers = sorted(+ integration_manager.get_framework_health_status_providers(),+ key = lambda p: p.get_provider_info().provider_name,+ )return {'app_monitor_providers': app_monitor_providers,'integration_health_items': integration_health_items,+ 'framework_health_providers': framework_health_providers,'weather_provider': WeatherSourceManager(),'background_task_provider': AsyncioHealthStatusProvider(),}@@ -76,12 +81,12 @@ class SystemHealthStatusView(HiModalView):if provider_id == 'hi.apps.weather.weather_sources':return WeatherHealthStatusDetailsView().get( request, *args, **kwargs )- if provider_id.startswith( 'hi.services' ):+ if provider_id.startswith( 'hi.services' ) or provider_id.startswith( 'hi.integrations' ):return self.get_integration_status_response(request = request,provider_id = provider_id,)-+if provider_id.startswith( 'hi.apps' ):return self.get_app_monitor_status_response(request = request,diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex 4f3821f5..80bacfd2 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -53,6 +53,11 @@ class IntegrationGateway:(pre-sync confirmation, sync execution, post-sync placement);the synchronizer participates by providing the integration-specific work plus a small amount of peripheral metadata.++ The Issue #283 sync-check probe also rides on the synchronizer+ (see ``IntegrationSynchronizer.check_needs_sync``): integrations+ without a synchronizer naturally opt out of both full sync and+ the periodic drift check."""return Nonediff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.pyindex 1fc085fc..cd383e75 100644--- a/src/hi/integrations/integration_manager.py+++ b/src/hi/integrations/integration_manager.py@@ -47,6 +47,7 @@ class IntegrationManager( Singleton ):def __init_singleton__( self ):self._integration_data_map : Dict[ str, IntegrationData ] = dict()self._monitor_map = dict()+ self._sync_check_monitor = Noneself._initialized = Falseself._data_lock = threading.Lock()self._monitor_event_loop = None@@ -60,6 +61,11 @@ class IntegrationManager( Singleton ):"""self._integration_data_map.clear()self._monitor_map.clear()+ with self._data_lock:+ sync_check_monitor = self._sync_check_monitor+ self._sync_check_monitor = None+ if sync_check_monitor is not None:+ sync_check_monitor.stop()returndef get_integration_data_list( self, enabled_only = False ) -> List[ IntegrationData ]:@@ -103,6 +109,9 @@ class IntegrationManager( Singleton ):if provider.get_provider_info().provider_id == provider_id:return providercontinue+ if ( self._sync_check_monitor is not None+ and self._sync_check_monitor.get_provider_info().provider_id == provider_id ):+ return self._sync_check_monitorraise KeyError( f'Unknown provider id: "{provider_id}".' )def get_health_status_by_monitor_id( self,@@ -112,11 +121,30 @@ class IntegrationManager( Singleton ):if monitor.id == monitor_id:return monitorcontinue+ if ( self._sync_check_monitor is not None+ and self._sync_check_monitor.id == monitor_id ):+ return self._sync_check_monitorraise KeyError( f'Unknown monitor id: "{monitor_id}".' )def get_health_status_providers(self) -> List[HealthStatusProvider]:with self._data_lock:- return list( self._monitor_map.values() )+ providers = list( self._monitor_map.values() )+ if self._sync_check_monitor is not None:+ providers.append( self._sync_check_monitor )+ return providers++ def get_framework_health_status_providers(self) -> List[HealthStatusProvider]:+ """Framework-level monitors owned by ``IntegrationManager`` itself+ rather than by any one integration. These are the integration+ framework's own background workers (currently just the+ Issue #283 sync-check monitor); the System Info page renders+ them alongside the per-integration list so they don't go+ invisible. Returned in a stable order; missing entries simply+ mean those monitors have not been started yet."""+ with self._data_lock:+ if self._sync_check_monitor is None:+ return []+ return [ self._sync_check_monitor ]def get_health_status_provider_map(self) -> Dict[str, HealthStatusProvider]:"""Snapshot of running monitors keyed by integration_id.@@ -142,18 +170,27 @@ class IntegrationManager( Singleton ):self._initialized = Trueself._monitor_event_loop = event_loop-+logger.info("Discovering and starting integration monitors...")await self._load_integration_data()await self._start_all_integration_monitors()+ await self._start_sync_check_monitor()return-+async def shutdown(self) -> None:logger.info("Stopping all integration monitors...")for integration_id, monitor in self._monitor_map.items():logger.debug( f'Stopping integration monitor: {integration_id}' )monitor.stop()continue+ # Snapshot the slot under the lock; release before calling+ # stop() so we don't hold the threading lock across a+ # stop() that just toggles a flag (cheap, but kept clean).+ with self._data_lock:+ sync_check_monitor = self._sync_check_monitor+ if sync_check_monitor is not None:+ logger.debug( 'Stopping sync-check monitor.' )+ sync_check_monitor.stop()returnasync def _load_integration_data(self) -> None:@@ -198,6 +235,41 @@ class IntegrationManager( Singleton ):continuereturn+ async def _start_sync_check_monitor(self) -> None:+ """+ Start the framework-level sync-check monitor (Issue #283). Singular+ across all integrations: iterates enabled+unpaused integrations,+ gets each integration's synchronizer via gateway.get_synchronizer(),+ and dispatches to its check_needs_sync. Sync-check rides on the+ same opt-in surface as full sync — integrations without a+ synchronizer naturally opt out. Started after the per-integration+ health monitors so the integration data map is already populated;+ per-integration probe failures inside the cycle are caught+ individually so a not-yet-ready integration cannot abort the cycle.+ """+ # Local import keeps the module-import-time graph clean — the+ # monitor module imports IntegrationManager lazily inside its+ # do_work, but the manager only needs the class here for+ # construction.+ from .monitors import IntegrationSyncCheckMonitor++ if settings.DEBUG and settings.SUPPRESS_MONITORS:+ logger.debug( 'Skipping sync-check monitor. See SUPPRESS_MONITORS = True' )+ return++ # No explicit lock: ``initialize`` is the sole caller and+ # already holds ``self._data_lock`` for its entire async+ # body. ``_data_lock`` is a non-reentrant ``threading.Lock``,+ # so re-acquiring it here would deadlock the initialization+ # path.+ self._sync_check_monitor = IntegrationSyncCheckMonitor()+ logger.debug( 'Starting sync-check monitor.' )+ asyncio.create_task(+ self._sync_check_monitor.start(),+ name = 'IntegrationSyncCheckMonitor',+ )+ return+def _launch_integration_monitor_task( self, integration_data : IntegrationData ):integration_id = integration_data.integration_iddiff --git a/src/hi/integrations/integration_synchronizer.py b/src/hi/integrations/integration_synchronizer.pyindex d3a2191c..2a46750b 100644--- a/src/hi/integrations/integration_synchronizer.py+++ b/src/hi/integrations/integration_synchronizer.py@@ -25,6 +25,7 @@ from hi.apps.entity.entity_placement import (from hi.apps.entity.models import Entityfrom .entity_operations import EntityIntegrationOperations+from .sync_check import IntegrationSyncCheck, SyncDeltafrom .sync_result import IntegrationSyncResultfrom .transient_models import IntegrationKey, IntegrationMetaData@@ -95,16 +96,45 @@ class IntegrationSynchronizer:try:with ExclusionLockContext(name=self.SYNCHRONIZATION_LOCK_NAME):logger.debug(f'{self.__class__.__name__} sync started.')- return self._sync_impl(is_initial_import=is_initial_import)+ result = self._sync_impl(is_initial_import=is_initial_import)except RuntimeError as e:logger.exception(e)- return IntegrationSyncResult(+ result = IntegrationSyncResult(title=self.get_result_title(is_initial_import=is_initial_import),error_list=[str(e)],)finally:logger.debug(f'{self.__class__.__name__} sync ended.')+ self._record_sync_check_complete_if_successful( result = result )+ return result++ def _record_sync_check_complete_if_successful(+ self, result : IntegrationSyncResult ) -> None:+ """Issue #283: a successful sync brings HI in line with upstream+ as of right now. Write a zero-delta sync-check result with the+ current timestamp so UI surfaces clear immediately and the next+ background probe has a fresh baseline. Cache write failures must+ not propagate — the sync itself succeeded and the caller's+ flow should continue regardless."""+ if result.error_list:+ return+ try:+ metadata = self.get_integration_metadata()+ except NotImplementedError:+ return+ try:+ IntegrationSyncCheck.record_sync_complete(+ integration_id = metadata.integration_id,+ integration_label = metadata.label,+ )+ except Exception as e:+ logger.warning(+ f'Failed to record sync-check completion for '+ f'{metadata.integration_id}: {e}'+ )+ return+def _sync_impl(self, is_initial_import: bool) -> IntegrationSyncResult:"""Integration-specific sync work. Subclasses must override.@@ -112,6 +142,31 @@ class IntegrationSynchronizer:"""raise NotImplementedError('Subclasses must override this method')+ async def check_needs_sync(self) -> Optional[SyncDelta]:+ """Issue #283 — periodic sync-check probe. Return a+ ``SyncDelta`` describing how upstream has drifted from HI's+ current state, or ``None`` to opt out.++ The framework monitor in ``hi.integrations.monitors`` invokes+ this on each enabled+unpaused integration's synchronizer once+ per cycle (default 4 hours). Implementations should do a+ *cheap* upstream fetch — the probe is purely informational and+ runs even when no user action is in progress — and delegate+ the comparison to ``IntegrationSyncCheck.compute_delta``. The+ framework wraps the returned delta into a+ ``SyncCheckResult`` (with timestamp and summary) and caches+ it; subclasses do not touch the cache directly.++ Failures (client unavailable, upstream unreachable) should+ propagate; the framework monitor's per-call try/except+ classifies the cycle as ERROR for that integration and+ continues with the others.++ Default returns ``None`` — opt-out. Sync-check is opt-in even+ among integrations that support full sync.+ """+ return None+def get_integration_metadata(self) -> IntegrationMetaData:"""Subclasses return their integration's ``IntegrationMetaData``diff --git a/src/hi/integrations/monitors.py b/src/hi/integrations/monitors.pynew file mode 100644index 00000000..666c0737--- /dev/null+++ b/src/hi/integrations/monitors.py@@ -0,0 +1,180 @@+"""+Framework-level periodic monitor for the Issue #283 sync-check+feature.++A single ``IntegrationSyncCheckMonitor`` runs at a long cadence+(``IntegrationSyncCheck.INTERVAL_SECS``, currently 4 hours), iterates+the enabled and unpaused integrations, gets each integration's+synchronizer via ``gateway.get_synchronizer()``, and dispatches to+its ``check_needs_sync()``. Sync-check rides on the same opt-in+surface as full sync — an integration without a synchronizer+naturally opts out of the periodic drift check too. Per-integration+calls are wrapped in try/except so one integration's transient+failure does not abort the cycle for the others. Sequential (not+parallel) iteration is deliberate: we hit one upstream at a time+across all integrations, which avoids lock-step CPU bursts when+monitors of multiple integrations would otherwise align at the long+boundary.++Lifecycle: started from ``IntegrationManager`` after the+per-integration health monitors have been launched. Stopped from the+same lifecycle. The first cycle runs immediately on start (the base+``PeriodicMonitor`` semantics) — that gives best-effort cache+population at server boot. Per-integration calls that fail because+their underlying manager / client is not yet ready are reported as+errors for this cycle only and the next cycle catches them.+"""++import logging++from hi.apps.alert.enums import AlarmLevel+from hi.apps.monitor.periodic_monitor import PeriodicMonitor+from hi.apps.system.provider_info import ProviderInfo++from .integration_data import IntegrationData+from .sync_check import IntegrationSyncCheck, SyncCheckOutcome++logger = logging.getLogger(__name__)+++class IntegrationSyncCheckMonitor( PeriodicMonitor ):++ MONITOR_ID = 'hi.integrations.sync_check_monitor'+ INTERVAL_SECS = IntegrationSyncCheck.INTERVAL_SECS++ def __init__( self ):+ super().__init__(+ id = self.MONITOR_ID,+ interval_secs = self.INTERVAL_SECS,+ )+ return++ def alarm_ceiling(self):+ # Drift detection is informational by design — the user always+ # confirms the actual sync. Cap at INFO so probe failures+ # never escalate beyond a notice.+ return AlarmLevel.INFO++ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ return ProviderInfo(+ provider_id = cls.MONITOR_ID,+ provider_name = 'Integration Sync-Check Monitor',+ description = (+ 'Periodic check across integrations for '+ 'changes that would warrant a Refresh.'+ ),+ expected_heartbeat_interval_secs = cls.INTERVAL_SECS,+ )++ async def do_work(self):+ # Imported here to avoid an import cycle: IntegrationManager+ # imports this module to start the monitor on init.+ from .integration_manager import IntegrationManager++ manager = IntegrationManager()+ integration_data_list = manager.get_integration_data_list( enabled_only = True )++ outcome_counts = { outcome: 0 for outcome in SyncCheckOutcome }++ for integration_data in integration_data_list:+ if integration_data.is_paused:+ continue+ outcome = await self._check_one_integration( integration_data )+ outcome_counts[ outcome ] += 1+ continue++ self._record_cycle_health( outcome_counts )+ return++ async def _check_one_integration(+ self,+ integration_data : IntegrationData ) -> SyncCheckOutcome:+ """+ Run the per-integration probe and write the result to the+ cache. Sync-check rides on the same opt-in surface as full+ sync: an integration with no synchronizer+ (``gateway.get_synchronizer() is None``) does not participate.+ Any exception from the synchronizer's check is caught here so+ a single integration cannot abort the cycle.+ """+ integration_id = integration_data.integration_id+ gateway = integration_data.integration_gateway++ synchronizer = gateway.get_synchronizer()+ if synchronizer is None:+ # No synchronizer means no sync support — and therefore+ # no sync-check. Cache state is not touched.+ return SyncCheckOutcome.OPTED_OUT++ try:+ delta = await synchronizer.check_needs_sync()+ except Exception as e:+ logger.warning(+ f'Sync check failed for {integration_id}: {e}',+ exc_info = True,+ )+ return SyncCheckOutcome.ERROR++ if delta is None:+ # Synchronizer exists but opted out of sync-check (the+ # default base-class behavior). Cache state is not+ # touched.+ return SyncCheckOutcome.OPTED_OUT++ result = IntegrationSyncCheck.build_result(+ delta = delta,+ integration_label = integration_data.integration_metadata.label,+ )+ IntegrationSyncCheck.set_state(+ integration_id = integration_id,+ result = result,+ )+ return (+ SyncCheckOutcome.NEEDS_SYNC+ if result.needs_sync+ else SyncCheckOutcome.IN_SYNC+ )++ def _record_cycle_health( self,+ outcome_counts : dict,+ ) -> None:+ """Summarize the cycle into the monitor's own health-status+ surface. The framework monitor's job is "did I iterate and+ dispatch every enabled integration?" — that always succeeds+ when we reach this method (per-integration call failures are+ absorbed by ``_check_one_integration``'s try/except). So+ cycle outcome is reported as HEALTHY regardless of how many+ individual integration probes errored.++ Per-integration upstream errors are owned by each+ integration's own health monitor (which polls the same+ upstream); duplicating an alert here would just repeat the+ same signal. The error count is still surfaced in the+ message for operator visibility, but it does not escalate+ this monitor's status.++ True framework / process failures (cache layer unavailable,+ ``IntegrationManager`` not initialized, etc.) raise out of+ ``do_work`` and are caught by the base class's+ ``run_query``, which records them as ERROR — that is the+ only path that should alert from this monitor.+ """+ checked = (+ outcome_counts[ SyncCheckOutcome.IN_SYNC ]+ + outcome_counts[ SyncCheckOutcome.NEEDS_SYNC ]+ )+ needs_sync = outcome_counts[ SyncCheckOutcome.NEEDS_SYNC ]+ errors = outcome_counts[ SyncCheckOutcome.ERROR ]++ message = (+ f'Sync check completed: {checked} integration(s) checked, '+ f'{needs_sync} need sync.'+ )+ if errors:+ message += (+ f' ({errors} integration probe error(s) — see '+ f'per-integration health.)'+ )+ self.record_healthy( message )+ returndiff --git a/src/hi/integrations/sync_check.py b/src/hi/integrations/sync_check.pynew file mode 100644index 00000000..47265b20--- /dev/null+++ b/src/hi/integrations/sync_check.py@@ -0,0 +1,335 @@+"""+Per-integration sync-check state, and the integration-agnostic delta+primitive used to compute it.++Issue #283: a periodic background probe surfaces a "needs-sync"+signal when an integration's HI representation has drifted from+upstream. The probe never modifies entities — the user always+chooses when to invoke Refresh. Per-integration probe logic lives in+each ``IntegrationSynchronizer.check_needs_sync()`` override, which+returns a ``SyncDelta``; sync-check rides on the same opt-in surface+as full sync (an integration without a synchronizer naturally opts+out of the periodic drift check too). The framework monitor wraps+the returned delta into a ``SyncCheckResult`` (delta + timestamp ++summary) and caches it. The cache entry is the *last known state of+the check*, not a "warning flag" — a successful Refresh records a+zero-delta result with a current timestamp so the UI can show+"verified up to date at HH:MM".++State is stored via ``django.core.cache`` (Redis-backed in+production); no DB model. Frozen dataclasses pickle cleanly through+the cache backend, so no custom serialization is needed; the cache+TTL bounds the impact of any class rename.+"""++import logging+from dataclasses import dataclass, field+from datetime import datetime+from typing import Optional, Set++from django.core.cache import cache++import hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.common.enums import LabeledEnum++from .transient_models import IntegrationKey++logger = logging.getLogger(__name__)+++class SyncCheckOutcome( LabeledEnum ):+ """+ Per-integration result classification used by the framework+ monitor's bookkeeping. Not user-facing — this drives the cycle's+ summary log line and tests, not the UI banner.+ """+ OPTED_OUT = ( 'Opted Out' , 'Integration does not implement sync-check.' )+ IN_SYNC = ( 'In Sync' , 'Upstream and HI match as of this check.' )+ NEEDS_SYNC = ( 'Needs Sync' , 'Upstream has changes not yet imported.' )+ ERROR = ( 'Error' , 'The probe failed; the cycle continues.' )+++@dataclass(frozen=True)+class SyncDelta:+ """+ Result of comparing two integration-key sets — what the+ synchronizer's ``check_needs_sync()`` returns. Integration-+ agnostic; the convention is that ``added`` contains keys upstream+ but not in HI, and ``removed`` contains keys in HI but not+ upstream. Update detection (key-present-on-both-sides but content+ changed) is out of scope for v1.++ Both sets contain ``IntegrationKey`` instances so comparison and+ hashing automatically apply the canonical normalization+ (``IntegrationKey.__post_init__``) — the same canonicalization+ that produced the stored ``entity.integration_key`` values. The+ probe never has to know about the normalization rule.+ """+ added : Set[ IntegrationKey ] = field( default_factory = set )+ removed : Set[ IntegrationKey ] = field( default_factory = set )++ @property+ def added_count(self) -> int:+ return len( self.added )++ @property+ def removed_count(self) -> int:+ return len( self.removed )++ @property+ def needs_sync(self) -> bool:+ return bool( self.added or self.removed )+++@dataclass(frozen=True)+class SyncCheckResult:+ """+ Cached state for one integration: the most recent ``SyncDelta``+ plus when the check ran and a short human-readable summary for+ the UI. Always present after the first cycle (or after a+ successful Refresh) — even when nothing has drifted, the+ zero-delta result records "verified up to date at HH:MM".+ """+ delta : SyncDelta+ last_checked_at : datetime+ summary_message : str++ @property+ def needs_sync(self) -> bool:+ return self.delta.needs_sync+++class IntegrationSyncCheck:+ """+ Namespace for the sync-check primitives: cache access, the+ optional set-comparison helper, and the result builders. Class+ methods rather than module-level functions so call sites carry+ the ``IntegrationSyncCheck.`` prefix and group naturally.+ """++ INTERVAL_SECS = 4 * 60 * 60++ _CACHE_TTL_SECS = INTERVAL_SECS * 2+ _CACHE_KEY_PREFIX = 'integrations:sync_check:'++ @classmethod+ def _cache_key( cls, integration_id : str ) -> str:+ return f'{cls._CACHE_KEY_PREFIX}{integration_id}'++ @staticmethod+ def compute_delta( upstream_keys : Set[ IntegrationKey ],+ current_keys : Set[ IntegrationKey ] ) -> SyncDelta:+ """+ Pure utility for integrations whose check reduces to comparing+ a set of upstream IntegrationKeys against a set of HI+ IntegrationKeys. Most integrations call this from inside+ their ``check_needs_sync()``; integrations with non-set+ semantics can build a ``SyncDelta`` directly.++ Set arithmetic on ``IntegrationKey`` instances picks up the+ canonical normalization automatically (via the dataclass's+ ``__hash__`` / ``__eq__``), so the probe never has to know+ about the normalization rule. Callers feed already-filtered+ sets so the counts match what Refresh would actually act on,+ not what the upstream raw response contains.+ """+ return SyncDelta(+ added = set( upstream_keys ) - set( current_keys ),+ removed = set( current_keys ) - set( upstream_keys ),+ )++ @classmethod+ def get_state( cls, integration_id : str ) -> Optional[ SyncCheckResult ]:+ """Return the most recent cached result, or None if no probe+ has written one (or the entry has expired)."""+ if not integration_id:+ return None+ return cache.get( cls._cache_key( integration_id ) )++ @classmethod+ def set_state( cls,+ integration_id : str,+ result : SyncCheckResult ) -> None:+ """Write a probe result to the cache. The TTL is bounded so a+ stopped monitor cannot leave forever-old state visible. Fires+ a transition alarm when the recorded state moves from+ no-prior / in-sync to needs-sync (see ``_should_alarm``);+ in-progress drift does not re-alarm cycle after cycle.++ Concurrency: this is a read-modify-write on the cache without+ a lock. The two callers — the framework monitor's probe cycle+ and ``record_sync_complete`` via the synchronizer's post-sync+ hook — can theoretically run concurrently if a user-triggered+ Refresh overlaps a probe cycle. By inspection the+ interleavings are benign: duplicate-direction races (both+ writers see prior=clean and call ``_fire_needs_sync_alarm``)+ collapse to a single alert via ``AlertManager``'s+ signature-based dedup, and opposite-direction races worst+ case fire a stale alarm for drift that was just cleared+ — dismissable, rare, no correctness impact. A Redis lock+ would prevent it but trades real cache-backend portability+ risk (LocMemCache in tests) for a marginal UX win, so we+ intentionally do not lock here."""+ if not integration_id:+ return+ prior = cls.get_state( integration_id )+ cache.set(+ cls._cache_key( integration_id ),+ result,+ timeout = cls._CACHE_TTL_SECS,+ )+ logger.debug(+ f'sync-check state recorded for {integration_id}: '+ f'needs_sync={result.needs_sync} '+ f'added={result.delta.added_count} '+ f'removed={result.delta.removed_count}'+ )+ if cls._should_alarm( prior = prior, current = result ):+ # Alarm delivery failures must not break the cache write+ # — the probe state is already persisted; the next+ # clear→set transition will re-attempt notification.+ try:+ cls._fire_needs_sync_alarm(+ integration_id = integration_id,+ result = result,+ )+ except Exception as e:+ logger.warning(+ f'Failed to fire needs-sync alarm for '+ f'{integration_id}: {e}'+ )++ @staticmethod+ def _should_alarm( prior : Optional[ SyncCheckResult ],+ current : SyncCheckResult ) -> bool:+ """Notification gate. Fires only on the clear → needs-sync+ transition: prior was None (first probe / cache expired) or+ in-sync, AND current reports needs-sync. Drift that persists+ across cycles (needs-sync → needs-sync) does not re-alarm —+ the user has already been told. Refresh-induced+ needs-sync → in-sync transitions are not a notification+ direction."""+ if not current.needs_sync:+ return False+ if prior is None:+ return True+ return not prior.needs_sync++ @staticmethod+ def _fire_needs_sync_alarm( integration_id : str,+ result : SyncCheckResult ) -> None:+ """Construct and queue an INFO-level alarm for a transition+ into the needs-sync state. Per-integration unique signature+ (``integrations.needs_sync.<integration_id>``) so two+ integrations both reporting drift surface as two distinct+ alerts. Lifetime is ``Alarm.MAX_LIFETIME_SECS`` — the+ canonical "until acknowledged" value (see+ ``hi/apps/alert/alarm.py``)."""+ from hi.apps.alert.alarm import Alarm+ from hi.apps.alert.alert_manager import AlertManager+ from hi.apps.alert.enums import AlarmLevel, AlarmSource+ from hi.apps.security.enums import SecurityLevel+ from hi.apps.sense.transient_models import SensorResponse++ from .transient_models import IntegrationKey++ alarm_integration_key = IntegrationKey(+ integration_id = 'integrations',+ integration_name = f'needs_sync.{integration_id}',+ )+ sensor_response = SensorResponse(+ integration_key = alarm_integration_key,+ value = 'NEEDS_SYNC',+ timestamp = result.last_checked_at,+ sensor = None,+ detail_attrs = {+ 'Added' : str( result.delta.added_count ),+ 'Removed' : str( result.delta.removed_count ),+ 'Last Checked' : result.last_checked_at.strftime(+ '%Y-%m-%d %H:%M:%S',+ ),+ },+ source_image_url = None,+ has_video_stream = False,+ )+ alarm = Alarm(+ alarm_source = AlarmSource.INTEGRATION,+ alarm_type = f'integrations.needs_sync.{integration_id}',+ alarm_level = AlarmLevel.INFO,+ title = result.summary_message,+ sensor_response_list = [ sensor_response ],+ security_level = SecurityLevel.OFF,+ alarm_lifetime_secs = Alarm.MAX_LIFETIME_SECS,+ timestamp = datetimeproxy.now(),+ )+ AlertManager().add_alarm( alarm )++ @classmethod+ def clear_state( cls, integration_id : str ) -> None:+ """Drop the cached state entirely. Used on integration removal;+ post-Refresh uses ``record_sync_complete`` instead so the UI+ keeps a "verified at HH:MM" indicator rather than going dark.+ """+ if not integration_id:+ return+ cache.delete( cls._cache_key( integration_id ) )+ logger.debug( f'sync-check state cleared for {integration_id}' )++ @classmethod+ def record_sync_complete( cls,+ integration_id : str,+ integration_label : str ) -> None:+ """Called after a successful Refresh: the integration is by+ definition in sync, so we write a zero-delta result with a+ current timestamp. UI surfaces the verified state and the+ next probe cycle naturally re-confirms or detects new drift.+ """+ cls.set_state(+ integration_id = integration_id,+ result = cls.build_result(+ delta = SyncDelta(),+ integration_label = integration_label,+ ),+ )++ @classmethod+ def build_result( cls,+ delta : SyncDelta,+ integration_label : str,+ last_checked_at : Optional[ datetime ] = None,+ ) -> SyncCheckResult:+ """Wrap a ``SyncDelta`` into a ``SyncCheckResult`` with a+ sensible default summary message and timestamp. The framework+ monitor calls this with the delta returned from each+ synchronizer's ``check_needs_sync()``.+ """+ if last_checked_at is None:+ last_checked_at = datetimeproxy.now()+ return SyncCheckResult(+ delta = delta,+ last_checked_at = last_checked_at,+ summary_message = cls._summary_message(+ delta = delta,+ integration_label = integration_label,+ ),+ )++ @staticmethod+ def _summary_message( delta : SyncDelta,+ integration_label : str ) -> str:+ """Pure-information summary of the most recent check. The+ Refresh call-to-action is rendered as a real link by the+ manage-page banner template (so clicking it opens the+ pre-sync modal); it is intentionally not embedded in this+ string. The same string flows into the sidebar tooltip,+ where a "click here" suffix would be misleading."""+ if not delta.needs_sync:+ return f'{integration_label} is up to date.'+ pieces = []+ if delta.added_count:+ noun = 'item' if delta.added_count == 1 else 'items'+ pieces.append( f'{delta.added_count} new {noun} upstream' )+ if delta.removed_count:+ noun = 'item' if delta.removed_count == 1 else 'items'+ pieces.append( f'{delta.removed_count} {noun} removed upstream' )+ return f'{integration_label}: {", ".join(pieces)}.'diff --git a/src/hi/integrations/templates/integrations/pages/integration_manage.html b/src/hi/integrations/templates/integrations/pages/integration_manage.htmlindex c3ba544c..0a441242 100644--- a/src/hi/integrations/templates/integrations/pages/integration_manage.html+++ b/src/hi/integrations/templates/integrations/pages/integration_manage.html@@ -11,19 +11,19 @@{% icon "settings" size="sm" css_class="hi-icon-left" %}INTEGRATIONS</a></div>- {% for integration_data in core.integration_data_list %}- <a class="nav-link hi-vertical-nav-link {% if core.integration_data.integration_id == integration_data.integration_id %}active{% endif %}"- href="{% url 'integrations_manage' integration_id=integration_data.integration_id %}"+ {% for item in core.sidebar_items %}+ <a class="nav-link hi-vertical-nav-link {% if core.integration_data.integration_id == item.integration_data.integration_id %}active{% endif %}"+ href="{% url 'integrations_manage' integration_id=item.integration_data.integration_id %}"data-async="true"><div class="d-flex justify-content-between align-items-center"><span class="d-flex align-items-center" style="white-space: nowrap;">- <img src="{% static integration_data.integration_metadata.logo_static_path %}"- alt="{{ integration_data.label }}"+ <img src="{% static item.integration_data.integration_metadata.logo_static_path %}"+ alt="{{ item.integration_data.label }}"style="max-height: 18px; width: auto; margin-right: 6px; flex-shrink: 0;">- {{ integration_data.label }}+ {{ item.integration_data.label }}</span>- {% with health_status=integration_data.integration_gateway.get_health_status_provider.health_status %}- {% include "integrations/panes/integration_status_indicator.html" with health_status=health_status is_paused=integration_data.integration.is_paused %}+ {% with health_status=item.integration_data.integration_gateway.get_health_status_provider.health_status %}+ {% include "integrations/panes/integration_status_indicator.html" with health_status=health_status is_paused=item.integration_data.integration.is_paused sync_check_result=item.sync_check_result %}{% endwith %}</div></a>@@ -58,6 +58,15 @@{% include "integrations/panes/sync_actions.html" %}</div></div>+ {% if core.sync_check_result and core.sync_check_result.needs_sync %}+ <div class="alert alert-info py-2 mt-2 mb-0" role="status">+ {% icon "sync" size="sm" css_class="hi-icon-left" %}{{ core.sync_check_result.summary_message }}+ Click+ <a href="{% url 'integrations_pre_sync' integration_id=core.integration_data.integration_id %}"+ class="alert-link"+ data-async="modal">REFRESH</a>.+ </div>+ {% endif %}{% include core.manage_view_template_name %}</div>diff --git a/src/hi/integrations/templates/integrations/panes/integration_status_indicator.html b/src/hi/integrations/templates/integrations/panes/integration_status_indicator.htmlindex 5120fe09..cda29756 100644--- a/src/hi/integrations/templates/integrations/panes/integration_status_indicator.html+++ b/src/hi/integrations/templates/integrations/panes/integration_status_indicator.html@@ -1,17 +1,21 @@{% load icons %}{% comment %}Compact integration-status indicator — small icon + tooltip, no label.-Composes HealthStatus and the integration's is_paused flag into a-single attention-grabbing glyph for the sidebar nav-tab.+Composes HealthStatus, the integration's is_paused flag, and the+Issue #283 sync-check state into a single attention-grabbing glyph+for the sidebar nav-tab.Parameters:- health_status : HealthStatus instance (required).- is_paused : bool — integration's is_paused flag (required).+ health_status : HealthStatus instance (required).+ is_paused : bool — integration's is_paused flag (required).+ sync_check_result : SyncCheckResult or None (optional) — Issue #283+ sync-check state for this integration.Visual priority (worst-of):- ERROR > WARNING > paused-HEALTHY-and-not-paused renders nothing — sidebar should be visually-clean when there is nothing to draw the operator's attention to.+ ERROR > WARNING > paused > needs-sync+HEALTHY-and-not-paused-and-in-sync renders nothing — sidebar should+be visually clean when there is nothing to draw the operator's+attention to.DISABLED is intentionally not handled — disabled integrations areexcluded from the sidebar tab list upstream.@@ -41,6 +45,13 @@ UNKNOWN is intentionally not handled — initialization edge, transient.title="Paused — background monitor is suspended">{% icon "pause" size="sm" %}</span>+{% elif sync_check_result.needs_sync %}+ <span class="hi-integration-indicator hi-integration-indicator-needs-sync"+ role="img"+ aria-label="{{ sync_check_result.summary_message }}"+ title="{{ sync_check_result.summary_message }}">+ {% icon "sync" size="sm" %}+ </span>{% endif %}{% endwith %}{% endif %}diff --git a/src/hi/integrations/templates/integrations/panes/sync_actions.html b/src/hi/integrations/templates/integrations/panes/sync_actions.htmlindex 15098313..e6c26dac 100644--- a/src/hi/integrations/templates/integrations/panes/sync_actions.html+++ b/src/hi/integrations/templates/integrations/panes/sync_actions.html@@ -11,10 +11,16 @@Label flips on `core.has_entities`: IMPORT for the first-time path,REFRESH for subsequent re-syncs. The framework manage view computeshas_entities into the `core` context.++ When the Issue #283 sync-check probe has detected upstream drift+ (`core.sync_check_result.needs_sync`), the REFRESH variant+ promotes from outline-secondary to solid btn-primary so it pulls+ the eye. The IMPORT variant is always primary since there is+ nothing to compare against on a first run.{% endcomment %}{% if core.integration_data.is_enabled and core.integration_data.integration_gateway.get_synchronizer %}<a href="{% url 'integrations_pre_sync' integration_id=core.integration_data.integration_id %}"- class="btn {% if core.has_entities %}btn-outline-secondary{% else %}btn-outline-primary{% endif %}"+ class="btn {% if core.has_entities %}{% if core.sync_check_result.needs_sync %}btn-primary{% else %}btn-outline-secondary{% endif %}{% else %}btn-outline-primary{% endif %}"role="button"data-async="modal">{% if core.has_entities %}diff --git a/src/hi/integrations/tests/test_sync_check.py b/src/hi/integrations/tests/test_sync_check.pynew file mode 100644index 00000000..ae7becd1--- /dev/null+++ b/src/hi/integrations/tests/test_sync_check.py@@ -0,0 +1,732 @@+"""+Unit tests for the Issue #283 sync-check primitives, framework+monitor, and post-sync cache hook in ``IntegrationSynchronizer``.++The sync_check module is small and pure (set arithmetic + cache+round-trip + dataclass building); most of the value here is in the+monitor's ``do_work`` iteration semantics — that is where bugs would+hide as more integrations are added.+"""++import asyncio+import logging+from unittest.mock import Mock, patch++from django.core.cache import cache+from django.test import TestCase++from hi.integrations.sync_check import (+ IntegrationSyncCheck,+ SyncCheckOutcome,+ SyncCheckResult,+ SyncDelta,+)+from hi.integrations.monitors import IntegrationSyncCheckMonitor+from hi.integrations.transient_models import IntegrationKey+++def _key(name: str, integration_id: str = 'test') -> IntegrationKey:+ """Concise IntegrationKey builder for test fixtures."""+ return IntegrationKey(integration_id=integration_id, integration_name=name)+++logging.disable(logging.CRITICAL)+++class SyncDeltaTests(TestCase):++ def test_empty_delta_is_not_needs_sync(self):+ delta = SyncDelta()+ self.assertFalse(delta.needs_sync)+ self.assertEqual(delta.added_count, 0)+ self.assertEqual(delta.removed_count, 0)++ def test_added_only(self):+ delta = SyncDelta(added={_key('a'), _key('b')})+ self.assertTrue(delta.needs_sync)+ self.assertEqual(delta.added_count, 2)+ self.assertEqual(delta.removed_count, 0)++ def test_removed_only(self):+ delta = SyncDelta(removed={_key('x')})+ self.assertTrue(delta.needs_sync)+ self.assertEqual(delta.added_count, 0)+ self.assertEqual(delta.removed_count, 1)++ def test_both_sides(self):+ delta = SyncDelta(added={_key('a')}, removed={_key('x'), _key('y')})+ self.assertTrue(delta.needs_sync)+ self.assertEqual(delta.added_count, 1)+ self.assertEqual(delta.removed_count, 2)+++class ComputeDeltaTests(TestCase):++ def test_identical_sets_yield_no_drift(self):+ delta = IntegrationSyncCheck.compute_delta(+ upstream_keys={_key('a'), _key('b'), _key('c')},+ current_keys={_key('a'), _key('b'), _key('c')},+ )+ self.assertFalse(delta.needs_sync)++ def test_disjoint_sets_yield_full_drift_both_sides(self):+ delta = IntegrationSyncCheck.compute_delta(+ upstream_keys={_key('a'), _key('b')},+ current_keys={_key('x'), _key('y')},+ )+ self.assertEqual(delta.added, {_key('a'), _key('b')})+ self.assertEqual(delta.removed, {_key('x'), _key('y')})++ def test_upstream_added(self):+ delta = IntegrationSyncCheck.compute_delta(+ upstream_keys={_key('a'), _key('b'), _key('c')},+ current_keys={_key('a'), _key('b')},+ )+ self.assertEqual(delta.added, {_key('c')})+ self.assertEqual(delta.removed, set())++ def test_upstream_removed(self):+ delta = IntegrationSyncCheck.compute_delta(+ upstream_keys={_key('a')},+ current_keys={_key('a'), _key('b')},+ )+ self.assertEqual(delta.added, set())+ self.assertEqual(delta.removed, {_key('b')})++ def test_both_sides_empty(self):+ delta = IntegrationSyncCheck.compute_delta(+ upstream_keys=set(),+ current_keys=set(),+ )+ self.assertFalse(delta.needs_sync)++ def test_case_mismatch_handled_via_integration_key(self):+ # Regression: stored entity.integration_name values are+ # lowercased by IntegrationKey.__post_init__. A probe whose+ # upstream-key derivation produces mixed-case integration+ # names would false-positive every time without IntegrationKey+ # canonicalization. Set arithmetic on IntegrationKey instances+ # picks up the lowercasing automatically via __hash__/__eq__.+ delta = IntegrationSyncCheck.compute_delta(+ upstream_keys={_key('INSTEON:01.AA.01'), _key('insteon:01.AA.02')},+ current_keys={_key('insteon:01.aa.01'), _key('insteon:01.aa.02')},+ )+ self.assertFalse(delta.needs_sync)+++class BuildResultAndSummaryTests(TestCase):++ def test_in_sync_message_is_concise(self):+ result = IntegrationSyncCheck.build_result(+ delta=SyncDelta(),+ integration_label='HomeBox',+ )+ self.assertFalse(result.needs_sync)+ self.assertIn('up to date', result.summary_message)+ self.assertIn('HomeBox', result.summary_message)++ def test_added_only_message_pluralizes(self):+ result = IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={_key('a'), _key('b'), _key('c')}),+ integration_label='Home Assistant',+ )+ self.assertIn('3 new items upstream', result.summary_message)+ # The Refresh call-to-action is intentionally NOT in the+ # summary string — it is rendered as a real link by the+ # manage-page banner template.+ self.assertNotIn('REFRESH', result.summary_message)++ def test_singular_pluralization(self):+ result = IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={_key('a')}),+ integration_label='HomeBox',+ )+ self.assertIn('1 new item upstream', result.summary_message)++ def test_removed_message(self):+ result = IntegrationSyncCheck.build_result(+ delta=SyncDelta(removed={_key('x'), _key('y')}),+ integration_label='ZoneMinder',+ )+ self.assertIn('2 items removed upstream', result.summary_message)++ def test_both_sides_message(self):+ result = IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={_key('a')}, removed={_key('x')}),+ integration_label='HomeBox',+ )+ self.assertIn('1 new item upstream', result.summary_message)+ self.assertIn('1 item removed upstream', result.summary_message)+++class CacheHelperTests(TestCase):++ INTEGRATION_A = 'integration_a'+ INTEGRATION_B = 'integration_b'++ def setUp(self):+ cache.clear()++ def tearDown(self):+ cache.clear()++ def test_round_trip(self):+ result = IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={_key('k1')}),+ integration_label='Test Integration',+ )+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_A,+ result=result,+ )+ loaded = IntegrationSyncCheck.get_state(self.INTEGRATION_A)+ self.assertIsNotNone(loaded)+ self.assertTrue(loaded.needs_sync)+ self.assertEqual(loaded.delta.added, {_key('k1')})+ self.assertEqual(loaded.summary_message, result.summary_message)++ def test_per_integration_isolation(self):+ result_a = IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={_key('k1')}),+ integration_label='A',+ )+ IntegrationSyncCheck.set_state(self.INTEGRATION_A, result_a)+ # B has no entry — must not surface A's result.+ self.assertIsNone(IntegrationSyncCheck.get_state(self.INTEGRATION_B))+ # Setting B does not perturb A.+ result_b = IntegrationSyncCheck.build_result(+ delta=SyncDelta(removed={_key('k2')}),+ integration_label='B',+ )+ IntegrationSyncCheck.set_state(self.INTEGRATION_B, result_b)+ loaded_a = IntegrationSyncCheck.get_state(self.INTEGRATION_A)+ loaded_b = IntegrationSyncCheck.get_state(self.INTEGRATION_B)+ self.assertEqual(loaded_a.delta.added, {_key('k1')})+ self.assertEqual(loaded_b.delta.removed, {_key('k2')})++ def test_clear_removes_entry(self):+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_A,+ result=IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={_key('x')}),+ integration_label='A',+ ),+ )+ IntegrationSyncCheck.clear_state(self.INTEGRATION_A)+ self.assertIsNone(IntegrationSyncCheck.get_state(self.INTEGRATION_A))++ def test_get_with_no_entry_returns_none(self):+ self.assertIsNone(IntegrationSyncCheck.get_state('never_set'))++ def test_empty_integration_id_is_safe_no_op(self):+ # Defensive: empty / None integration_id must not pollute the+ # cache namespace or raise.+ self.assertIsNone(IntegrationSyncCheck.get_state(''))+ IntegrationSyncCheck.set_state(+ integration_id='',+ result=IntegrationSyncCheck.build_result(+ delta=SyncDelta(),+ integration_label='whatever',+ ),+ )+ IntegrationSyncCheck.clear_state('')+ # No exceptions; nothing to assert beyond reaching here.++ def test_record_sync_complete_writes_zero_delta_with_timestamp(self):+ # Pre-populate a stale "needs sync" state.+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_A,+ result=IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={_key('k1'), _key('k2')}),+ integration_label='A',+ ),+ )+ # Record completion.+ IntegrationSyncCheck.record_sync_complete(+ integration_id=self.INTEGRATION_A,+ integration_label='A',+ )+ loaded = IntegrationSyncCheck.get_state(self.INTEGRATION_A)+ # Cache is now a zero-delta result, not cleared.+ self.assertIsNotNone(loaded)+ self.assertFalse(loaded.needs_sync)+ self.assertEqual(loaded.delta.added, set())+ self.assertEqual(loaded.delta.removed, set())+ self.assertIsNotNone(loaded.last_checked_at)+++class TransitionAlarmTests(TestCase):+ """Phase 4 (Issue #283): clear→needs_sync transition fires a+ fresh alarm; in-progress drift does not re-alarm cycle after+ cycle. The predicate ``_should_alarm`` is the single source of+ truth and is tested directly; the wiring inside ``set_state`` is+ tested by patching ``_fire_needs_sync_alarm`` and asserting call+ counts."""++ INTEGRATION_ID = 'transition_test'++ def setUp(self):+ cache.clear()++ def tearDown(self):+ cache.clear()++ def _result(self, *, needs_sync):+ return IntegrationSyncCheck.build_result(+ delta=(+ SyncDelta(added={_key('x')}) if needs_sync else SyncDelta()+ ),+ integration_label='Transition Test',+ )++ # ---- predicate ----++ def test_should_alarm_when_prior_is_none_and_needs_sync(self):+ self.assertTrue(IntegrationSyncCheck._should_alarm(+ prior=None,+ current=self._result(needs_sync=True),+ ))++ def test_should_alarm_on_clean_to_needs_sync_transition(self):+ self.assertTrue(IntegrationSyncCheck._should_alarm(+ prior=self._result(needs_sync=False),+ current=self._result(needs_sync=True),+ ))++ def test_should_not_alarm_when_drift_persists(self):+ self.assertFalse(IntegrationSyncCheck._should_alarm(+ prior=self._result(needs_sync=True),+ current=self._result(needs_sync=True),+ ))++ def test_should_not_alarm_on_set_to_clear_transition(self):+ # Refresh just succeeded — current is in-sync. Never an+ # alarm direction.+ self.assertFalse(IntegrationSyncCheck._should_alarm(+ prior=self._result(needs_sync=True),+ current=self._result(needs_sync=False),+ ))++ def test_should_not_alarm_when_both_clean(self):+ self.assertFalse(IntegrationSyncCheck._should_alarm(+ prior=self._result(needs_sync=False),+ current=self._result(needs_sync=False),+ ))++ def test_should_not_alarm_when_prior_none_and_current_clean(self):+ # First-ever probe finds no drift — nothing to alarm about.+ self.assertFalse(IntegrationSyncCheck._should_alarm(+ prior=None,+ current=self._result(needs_sync=False),+ ))++ # ---- wiring ----++ def test_set_state_fires_alarm_on_first_drift_detection(self):+ with patch.object(+ IntegrationSyncCheck, '_fire_needs_sync_alarm',+ ) as mock_fire:+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=self._result(needs_sync=True),+ )+ mock_fire.assert_called_once()++ def test_set_state_does_not_re_fire_when_drift_persists(self):+ # First write triggers alarm.+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=self._result(needs_sync=True),+ )+ # Second write with same needs_sync state must NOT re-fire.+ with patch.object(+ IntegrationSyncCheck, '_fire_needs_sync_alarm',+ ) as mock_fire:+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=self._result(needs_sync=True),+ )+ mock_fire.assert_not_called()++ def test_set_state_re_fires_after_refresh_then_drift(self):+ # Initial drift → alarm.+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=self._result(needs_sync=True),+ )+ # Refresh succeeds → zero-delta result; no alarm.+ IntegrationSyncCheck.record_sync_complete(+ integration_id=self.INTEGRATION_ID,+ integration_label='Transition Test',+ )+ # New drift cycle → alarm again (this is the canonical+ # re-fire path: user acted, then upstream changed again).+ with patch.object(+ IntegrationSyncCheck, '_fire_needs_sync_alarm',+ ) as mock_fire:+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=self._result(needs_sync=True),+ )+ mock_fire.assert_called_once()++ def test_record_sync_complete_does_not_fire_alarm(self):+ # Pre-populate a stale needs-sync state.+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=self._result(needs_sync=True),+ )+ with patch.object(+ IntegrationSyncCheck, '_fire_needs_sync_alarm',+ ) as mock_fire:+ IntegrationSyncCheck.record_sync_complete(+ integration_id=self.INTEGRATION_ID,+ integration_label='Transition Test',+ )+ mock_fire.assert_not_called()++ def test_alarm_failure_does_not_break_set_state(self):+ # Alarm subsystem unavailable / raises — cache write should+ # have already succeeded and set_state should not propagate+ # the failure.+ with patch.object(+ IntegrationSyncCheck, '_fire_needs_sync_alarm',+ side_effect=RuntimeError('alert system down'),+ ):+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=self._result(needs_sync=True),+ )+ # State is still recorded despite the alarm failure.+ loaded = IntegrationSyncCheck.get_state(self.INTEGRATION_ID)+ self.assertIsNotNone(loaded)+ self.assertTrue(loaded.needs_sync)++ # ---- alarm shape ----++ def test_fire_needs_sync_alarm_constructs_expected_alarm(self):+ from hi.apps.alert.alarm import Alarm+ from hi.apps.alert.enums import AlarmLevel, AlarmSource+ captured = []++ def capture(alarm):+ captured.append(alarm)++ with patch(+ 'hi.apps.alert.alert_manager.AlertManager',+ ) as mock_manager_class:+ mock_manager_class.return_value.add_alarm = capture+ IntegrationSyncCheck._fire_needs_sync_alarm(+ integration_id=self.INTEGRATION_ID,+ result=self._result(needs_sync=True),+ )++ self.assertEqual(len(captured), 1)+ alarm = captured[0]+ self.assertEqual(alarm.alarm_source, AlarmSource.INTEGRATION)+ self.assertEqual(+ alarm.alarm_type,+ f'integrations.needs_sync.{self.INTEGRATION_ID}',+ )+ self.assertEqual(alarm.alarm_level, AlarmLevel.INFO)+ # Drift alarms should persist until acknowledged, which is+ # expressed in this codebase as ``Alarm.MAX_LIFETIME_SECS``+ # (a sentinel "never expires" value — non-zero so+ # ``end_datetime`` arithmetic remains uniform across all+ # alarm types).+ self.assertEqual(alarm.alarm_lifetime_secs, Alarm.MAX_LIFETIME_SECS)+ # Per-integration unique signature so two integrations+ # drifting yield two distinct alerts.+ self.assertIn(self.INTEGRATION_ID, alarm.signature)+++class _StubIntegrationData:+ """Minimal duck-typed IntegrationData stand-in for the monitor's+ iteration tests. The real IntegrationData is a dataclass over+ Integration model rows; the monitor only reads the gateway, the+ metadata, the integration_id, and the is_paused flag, so a stub+ keeps the tests focused and isolated from DB fixtures."""++ def __init__(self, integration_id, label, gateway, is_paused=False):+ self.integration_id = integration_id+ self.integration_gateway = gateway+ self.integration_metadata = Mock(integration_id=integration_id, label=label)+ self.is_paused = is_paused+++def _stub_gateway_returning(delta_or_exception, has_synchronizer=True):+ """Build a Mock gateway whose ``get_synchronizer()`` returns a+ Mock synchronizer whose ``check_needs_sync`` coroutine returns+ the given SyncDelta (or None) — or raises if an Exception is+ supplied. Pass ``has_synchronizer=False`` to simulate an+ integration that does not support sync at all (gateway returns+ None from get_synchronizer)."""+ gateway = Mock()+ if not has_synchronizer:+ gateway.get_synchronizer = Mock(return_value=None)+ return gateway++ synchronizer = Mock()++ async def check_needs_sync():+ if isinstance(delta_or_exception, BaseException):+ raise delta_or_exception+ return delta_or_exception++ synchronizer.check_needs_sync = check_needs_sync+ gateway.get_synchronizer = Mock(return_value=synchronizer)+ return gateway+++class IntegrationSyncCheckMonitorTests(TestCase):+ """Iteration semantics for the framework monitor's do_work."""++ def setUp(self):+ cache.clear()++ def tearDown(self):+ cache.clear()++ def _run(self, monitor):+ asyncio.run(monitor.do_work())++ def _patch_manager_with(self, integration_data_list):+ """Patch IntegrationManager so do_work sees this fixture set.+ The manager's get_integration_data_list(enabled_only=True) is+ the only accessor do_work calls; mocking it keeps the test+ isolated from singleton state."""+ manager = Mock()+ manager.get_integration_data_list.return_value = integration_data_list+ return patch(+ 'hi.integrations.integration_manager.IntegrationManager',+ return_value=manager,+ )++ def test_writes_cache_when_gateway_returns_delta(self):+ gateway = _stub_gateway_returning(SyncDelta(added={_key('k1')}))+ data = _StubIntegrationData('a', 'A', gateway)++ with self._patch_manager_with([data]):+ self._run(IntegrationSyncCheckMonitor())++ loaded = IntegrationSyncCheck.get_state('a')+ self.assertIsNotNone(loaded)+ self.assertTrue(loaded.needs_sync)+ self.assertEqual(loaded.delta.added, {_key('k1')})++ def test_no_cache_write_when_synchronizer_returns_none(self):+ gateway = _stub_gateway_returning(None)+ data = _StubIntegrationData('a', 'A', gateway)++ with self._patch_manager_with([data]):+ self._run(IntegrationSyncCheckMonitor())++ # Synchronizer present but check returned None: opt-out, no+ # cache entry.+ self.assertIsNone(IntegrationSyncCheck.get_state('a'))++ def test_no_cache_write_when_gateway_has_no_synchronizer(self):+ # Integration that does not support sync at all+ # (get_synchronizer returns None) is naturally opted out of+ # sync-check too — sync-check rides on the same+ # capability.+ gateway = _stub_gateway_returning(None, has_synchronizer=False)+ data = _StubIntegrationData('a', 'A', gateway)++ with self._patch_manager_with([data]):+ self._run(IntegrationSyncCheckMonitor())++ self.assertIsNone(IntegrationSyncCheck.get_state('a'))++ def test_paused_integration_is_skipped(self):+ gateway = _stub_gateway_returning(SyncDelta(added={_key('k1')}))+ data = _StubIntegrationData('a', 'A', gateway, is_paused=True)++ with self._patch_manager_with([data]):+ self._run(IntegrationSyncCheckMonitor())++ # Paused → not invoked, nothing cached.+ self.assertIsNone(IntegrationSyncCheck.get_state('a'))++ def test_one_integration_failure_does_not_abort_cycle(self):+ # First integration raises; second returns a real delta.+ # Without the per-integration try/except, the cycle would+ # abort before reaching B and B's cache entry would never+ # land.+ failing = _StubIntegrationData(+ 'a', 'A', _stub_gateway_returning(RuntimeError('upstream down')),+ )+ ok = _StubIntegrationData(+ 'b', 'B', _stub_gateway_returning(SyncDelta(removed={_key('x')})),+ )++ with self._patch_manager_with([failing, ok]):+ self._run(IntegrationSyncCheckMonitor())++ self.assertIsNone(IntegrationSyncCheck.get_state('a'))+ loaded_b = IntegrationSyncCheck.get_state('b')+ self.assertIsNotNone(loaded_b)+ self.assertTrue(loaded_b.needs_sync)+ self.assertEqual(loaded_b.delta.removed, {_key('x')})++ def test_per_integration_probe_error_does_not_escalate_monitor_status(self):+ # Integration upstream error must NOT bump the framework+ # monitor to WARNING — that would duplicate the alert each+ # integration's own health monitor already raises and+ # mis-blame the framework monitor for an integration-level+ # failure. The cycle stays HEALTHY; the count is surfaced+ # in the message for operator visibility.+ failing = _StubIntegrationData(+ 'a', 'A', _stub_gateway_returning(RuntimeError('upstream down')),+ )++ monitor = IntegrationSyncCheckMonitor()+ with self._patch_manager_with([failing]):+ self._run(monitor)++ from hi.apps.system.enums import HealthStatusType+ self.assertEqual(monitor.health_status.status, HealthStatusType.HEALTHY)+ self.assertIn('1 integration probe error', monitor.health_status.last_message)++ def test_outcome_classification(self):+ # Direct test of _check_one_integration so the enum classifications+ # are pinned independently of do_work bookkeeping.+ monitor = IntegrationSyncCheckMonitor()++ opted_out_data = _StubIntegrationData(+ 'opt', 'Opt', _stub_gateway_returning(None),+ )+ in_sync_data = _StubIntegrationData(+ 'in_sync', 'InSync', _stub_gateway_returning(SyncDelta()),+ )+ needs_sync_data = _StubIntegrationData(+ 'needs', 'Needs', _stub_gateway_returning(SyncDelta(added={_key('k')})),+ )+ error_data = _StubIntegrationData(+ 'err', 'Err', _stub_gateway_returning(RuntimeError('boom')),+ )++ self.assertEqual(+ asyncio.run(monitor._check_one_integration(opted_out_data)),+ SyncCheckOutcome.OPTED_OUT,+ )+ self.assertEqual(+ asyncio.run(monitor._check_one_integration(in_sync_data)),+ SyncCheckOutcome.IN_SYNC,+ )+ self.assertEqual(+ asyncio.run(monitor._check_one_integration(needs_sync_data)),+ SyncCheckOutcome.NEEDS_SYNC,+ )+ self.assertEqual(+ asyncio.run(monitor._check_one_integration(error_data)),+ SyncCheckOutcome.ERROR,+ )+++class IntegrationSynchronizerPostSyncHookTests(TestCase):+ """The post-sync hook clears (writes a zero-delta SyncCheckResult+ with current timestamp) on a successful sync, and leaves the+ cache alone when the sync errored."""++ INTEGRATION_ID = 'sync_post_hook_test'+ INTEGRATION_LABEL = 'Post-Hook Test Integration'++ def setUp(self):+ cache.clear()++ def tearDown(self):+ cache.clear()++ def _make_synchronizer(self, sync_impl_result):+ """Build a concrete IntegrationSynchronizer whose _sync_impl+ returns the given result. We test sync() (the public entry+ point) so the post-hook fires the same way it does in+ production."""+ from hi.integrations.integration_synchronizer import IntegrationSynchronizer+ from hi.integrations.transient_models import IntegrationMetaData++ class _TestSynchronizer(IntegrationSynchronizer):+ SYNCHRONIZATION_LOCK_NAME = 'sync_check_test_lock'++ def get_integration_metadata(self):+ return IntegrationMetaData(+ integration_id=IntegrationSynchronizerPostSyncHookTests.INTEGRATION_ID,+ label=IntegrationSynchronizerPostSyncHookTests.INTEGRATION_LABEL,+ attribute_type=Mock(),+ allow_entity_deletion=True,+ )++ def _sync_impl(self, is_initial_import):+ return sync_impl_result++ return _TestSynchronizer()++ def test_successful_sync_records_zero_delta_completion(self):+ from hi.integrations.sync_result import IntegrationSyncResult++ # Pre-populate a stale "needs sync" state.+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={'a', 'b'}),+ integration_label=self.INTEGRATION_LABEL,+ ),+ )+ synchronizer = self._make_synchronizer(+ sync_impl_result=IntegrationSyncResult(title='Refresh Result'),+ )++ synchronizer.sync(is_initial_import=False)++ loaded = IntegrationSyncCheck.get_state(self.INTEGRATION_ID)+ self.assertIsNotNone(loaded)+ self.assertFalse(loaded.needs_sync)++ def test_failed_sync_leaves_cache_alone(self):+ from hi.integrations.sync_result import IntegrationSyncResult++ # Pre-populate a stale needs-sync state.+ stale = IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={_key('a'), _key('b')}),+ integration_label=self.INTEGRATION_LABEL,+ )+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=stale,+ )+ synchronizer = self._make_synchronizer(+ sync_impl_result=IntegrationSyncResult(+ title='Refresh Result',+ error_list=['something went wrong'],+ ),+ )++ synchronizer.sync(is_initial_import=False)++ loaded = IntegrationSyncCheck.get_state(self.INTEGRATION_ID)+ self.assertIsNotNone(loaded)+ # Stale state still present — failed sync did not clear it.+ self.assertTrue(loaded.needs_sync)+ self.assertEqual(loaded.delta.added, {_key('a'), _key('b')})+++class SyncCheckResultEqualityTests(TestCase):+ """Frozen dataclass equality is the only path tests use to compare+ cache entries; pin it explicitly so a future field change does+ not silently change comparison semantics."""++ def test_two_results_with_same_fields_compare_equal(self):+ from datetime import datetime, timezone+ ts = datetime(2026, 5, 6, 12, 0, tzinfo=timezone.utc)+ a = SyncCheckResult(+ delta=SyncDelta(added={_key('k')}),+ last_checked_at=ts,+ summary_message='msg',+ )+ b = SyncCheckResult(+ delta=SyncDelta(added={_key('k')}),+ last_checked_at=ts,+ summary_message='msg',+ )+ self.assertEqual(a, b)diff --git a/src/hi/integrations/tests/test_views.py b/src/hi/integrations/tests/test_views.pyindex 6d490085..c3d30e3e 100644--- a/src/hi/integrations/tests/test_views.py+++ b/src/hi/integrations/tests/test_views.py@@ -1165,3 +1165,127 @@ class RefineViewTests(SyncViewTestCase):'integrations_refine', kwargs={'location_view_id': 99999},))self.assertEqual(response.status_code, 404)+++class _RenderableManageViewPane:+ """Minimal stand-in for an IntegrationManageViewPane that points+ at an existing empty per-integration template so the manage view+ can render in tests without a real per-integration pane wired+ in. Reuses ``homebox/panes/hb_manage.html`` (a documented empty+ extension-point template) rather than introducing a test-only+ template file."""++ def get_template_name(self):+ return 'homebox/panes/hb_manage.html'++ def get_template_context(self, integration_data):+ return {}+++class _RenderableGateway(_SyncCapableGateway):+ """``_SyncCapableGateway`` plus a real ManageViewPane so the+ full IntegrationManageView render path works."""++ def get_manage_view_pane(self):+ return _RenderableManageViewPane()+++class IntegrationManageViewSyncCheckContextTests(SyncViewTestCase):+ """Issue #283 — wire-up tests for the sync-check state on the+ integration manage page. Pins:+ * banner renders when the active integration's cached+ SyncCheckResult reports needs_sync;+ * banner does NOT render when there is no cache state or+ the cache reports in-sync.+ """++ INTEGRATION_ID = 'sync_check_view_test'++ def setUp(self):+ super().setUp()+ from django.core.cache import cache+ IntegrationManager().reset_for_testing()+ cache.clear()++ self.integration = Integration.objects.create(+ integration_id=self.INTEGRATION_ID,+ is_enabled=True,+ is_paused=False,+ )+ self.gateway = _RenderableGateway(integration_id=self.INTEGRATION_ID)+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(+ integration_gateway=self.gateway,+ integration=self.integration,+ )++ def tearDown(self):+ from django.core.cache import cache+ cache.clear()+ super().tearDown()++ def _url(self):+ return reverse(+ 'integrations_manage',+ kwargs={'integration_id': self.INTEGRATION_ID},+ )++ def test_banner_renders_when_sync_check_reports_drift(self):+ from hi.integrations.sync_check import (+ IntegrationSyncCheck,+ SyncDelta,+ )+ from hi.integrations.transient_models import IntegrationKey+ IntegrationSyncCheck.set_state(+ integration_id=self.INTEGRATION_ID,+ result=IntegrationSyncCheck.build_result(+ delta=SyncDelta(added={+ IntegrationKey(integration_id=self.INTEGRATION_ID,+ integration_name='item-1'),+ }),+ integration_label='Sync View Test Integration',+ ),+ )++ response = self.client.get(self._url())+ self.assertSuccessResponse(response)+ body = response.content.decode()+ self.assertIn('1 new item upstream', body)+ # The "REFRESH" call-to-action is rendered as an inline+ # anchor that links to the pre-sync modal, so the rendered+ # HTML carries both the link text and the URL.+ self.assertIn(+ reverse('integrations_pre_sync',+ kwargs={'integration_id': self.INTEGRATION_ID}),+ body,+ )+ self.assertIn('>REFRESH</a>', body)++ def _refresh_link_url(self):+ return reverse(+ 'integrations_pre_sync',+ kwargs={'integration_id': self.INTEGRATION_ID},+ )++ def test_no_banner_when_no_cache_state(self):+ # Fresh server, probe has not yet run — manage page should+ # render cleanly without the inline-Refresh banner. (The+ # standalone REFRESH button at the page header is unaffected+ # — it is the banner-link variant that should be absent.)+ response = self.client.get(self._url())+ self.assertSuccessResponse(response)+ body = response.content.decode()+ self.assertNotIn('upstream', body)++ def test_no_banner_when_in_sync(self):+ # Probe has run and confirmed in-sync (zero-delta); the+ # banner is gated on needs_sync, so it must not appear.+ from hi.integrations.sync_check import IntegrationSyncCheck+ IntegrationSyncCheck.record_sync_complete(+ integration_id=self.INTEGRATION_ID,+ integration_label='Sync View Test Integration',+ )++ response = self.client.get(self._url())+ self.assertSuccessResponse(response)+ body = response.content.decode()+ self.assertNotIn('upstream', body)diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.pyindex 1451f24a..c28d9cf1 100644--- a/src/hi/integrations/transient_models.py+++ b/src/hi/integrations/transient_models.py@@ -39,10 +39,26 @@ class IntegrationKey:integration_name : str # Name or identifier that is used by the external source.def __post_init__(self):- # Want to make matching more robust, so convert to lowercase- self.integration_id = self.integration_id.lower()- self.integration_name = self.integration_name.lower()+ # Make matching more robust by canonicalizing both fields.+ # The exact rule (currently lowercase) lives in normalize() so+ # external callers comparing raw strings against stored+ # integration_name values can apply the same rule without+ # constructing a full IntegrationKey.+ self.integration_id = self.normalize( self.integration_id )+ self.integration_name = self.normalize( self.integration_name )return++ @staticmethod+ def normalize( value : str ) -> str:+ """Canonical normalization applied to ``integration_id`` and+ ``integration_name``. Exposed so callers that need to compare+ raw strings against stored values can apply exactly the same+ rule without constructing full IntegrationKey instances. Most+ comparisons should go through full ``IntegrationKey`` objects+ and rely on the dataclass's ``__hash__`` / ``__eq__`` (which+ also use this rule); this static is the escape hatch for+ cases where a one-shot string normalization is enough."""+ return value.lower()def __str__(self):return self.integration_key_strdiff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.pyindex 8765312b..d8832086 100644--- a/src/hi/integrations/views.py+++ b/src/hi/integrations/views.py@@ -26,6 +26,7 @@ from .exceptions import IntegrationConnectionErrorfrom .integration_attribute_edit_context import IntegrationAttributeItemEditContextfrom .integration_manager import IntegrationManagerfrom .models import IntegrationAttribute+from .sync_check import IntegrationSyncCheckfrom .view_mixins import IntegrationPlacementViewMixin, IntegrationViewMixinlogger = logging.getLogger(__name__)@@ -634,6 +635,27 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEditintegration_id = integration_data.integration_id,).exists()+ # Issue #283 sync-check state.+ # * sync_check_result drives the banner and the Refresh+ # button emphasis on the active integration's manage+ # page.+ # * sidebar_items pairs each integration with its current+ # sync-check result so the sidebar template iterates one+ # pre-resolved list instead of looking up per-integration+ # state mid-render.+ sync_check_result = IntegrationSyncCheck.get_state(+ integration_data.integration_id,+ )+ sidebar_items = [+ {+ 'integration_data': data,+ 'sync_check_result': IntegrationSyncCheck.get_state(+ data.integration_id,+ ),+ }+ for data in integration_data_list+ ]+template_context.update({# Extra needed on initial view only for tabbed navigation. Not# needed for attribute edit operations.@@ -646,6 +668,8 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit'manage_view_template_name': manage_template_name,'health_status': health_status_provider.health_status,'has_entities': has_entities,+ 'sync_check_result': sync_check_result,+ 'sidebar_items': sidebar_items,},})return template_contextdiff --git a/src/hi/services/hass/hass_sync.py b/src/hi/services/hass/hass_sync.pyindex 74b9fcb1..a39b0e7b 100644--- a/src/hi/services/hass/hass_sync.py+++ b/src/hi/services/hass/hass_sync.py@@ -1,6 +1,7 @@import loggingfrom typing import Dict, List, Optional+from asgiref.sync import sync_to_asyncfrom django.db import transactionfrom hi.apps.entity.models import Entity@@ -12,6 +13,7 @@ from hi.apps.entity.entity_placement import ()from hi.integrations.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.sync_check import IntegrationSyncCheck, SyncDeltafrom hi.integrations.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKey@@ -33,6 +35,56 @@ class HassSynchronizer( IntegrationSynchronizer, HassMixin ):return 'Only items matching your Allowed Item Types setting will be imported.'return 'Only items matching your Allowed Item Types setting are compared.'+ async def check_needs_sync(self) -> Optional[SyncDelta]:+ """Issue #283 — sync-check probe for Home Assistant.++ Fetches the same ``/api/states`` payload the periodic monitor+ uses, applies the configured Allowed Item Types allowlist (so+ the upstream key set matches what Refresh would actually+ import — not what HA exposes raw), then compares against the+ IntegrationKeys of HA-attached HI entities.++ Convention matched to+ ``HassConverter.hass_device_to_integration_key``: each+ aggregated HassDevice maps to one IntegrationKey, which is+ what Refresh stores on the corresponding HI entity. Routing+ the upstream side through the same converter helper means+ the comparison automatically picks up whatever canonicalization+ ``IntegrationKey`` applies. Adds/removes only.+ """+ hass_manager = await self.hass_manager_async()+ if hass_manager is None:+ return None+ hass_entity_id_to_state = await hass_manager.fetch_hass_states_from_api_async(+ verbose = False,+ )+ import_allowlist = hass_manager.import_allowlist+ hass_device_id_to_device = HassConverter.hass_states_to_hass_devices(+ hass_entity_id_to_state = hass_entity_id_to_state,+ import_allowlist = import_allowlist,+ )+ upstream_keys = {+ HassConverter.hass_device_to_integration_key( hass_device )+ for hass_device in hass_device_id_to_device.values()+ }+ current_keys = await sync_to_async( self._get_current_integration_keys )()+ return IntegrationSyncCheck.compute_delta(+ upstream_keys = upstream_keys,+ current_keys = current_keys,+ )++ @staticmethod+ def _get_current_integration_keys() -> set:+ return {+ IntegrationKey(+ integration_id = integration_id,+ integration_name = integration_name,+ )+ for integration_id, integration_name in Entity.objects.filter(+ integration_id = HassMetaData.integration_id,+ ).values_list( 'integration_id', 'integration_name' )+ }+def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:hass_manager = self.hass_manager()result = IntegrationSyncResult(diff --git a/src/hi/services/hass/tests/test_hass_sync.py b/src/hi/services/hass/tests/test_hass_sync.pyindex d3a0cf1c..ce371b2e 100644--- a/src/hi/services/hass/tests/test_hass_sync.py+++ b/src/hi/services/hass/tests/test_hass_sync.py@@ -362,3 +362,131 @@ class TestHassSynchronizerSyncResultGrouping(TestCase):entity = self._entity('Front Camera', 'CAMERA', 'camera.front')placement_input = self.synchronizer.group_entities_for_placement([entity])self.assertEqual(placement_input.groups[0].items[0].key, 'hass:camera.front')+++from hi.testing.async_task_utils import AsyncTaskTestCase+++class TestHassSynchronizerCheckNeedsSync(AsyncTaskTestCase):+ """Issue #283 — sync-check probe shape for Home Assistant.++ Pins the contract that the upstream key set is *post-allowlist*+ (so the count matches what Refresh would actually import) and+ that the comparison is over aggregated HassDevice ids.++ Uses real Entity rows for the HI side so the probe's+ ``Entity.objects.filter(...)`` query path is exercised end-to-end.+ Only the upstream HTTP boundary+ (``fetch_hass_states_from_api_async``) is mocked.+ """++ def _hass_key(self, name: str):+ from hi.integrations.transient_models import IntegrationKey+ from hi.services.hass.hass_metadata import HassMetaData+ return IntegrationKey(+ integration_id=HassMetaData.integration_id,+ integration_name=name,+ )++ def _make_hass_entities(self, integration_names):+ from hi.services.hass.hass_metadata import HassMetaData+ for name in integration_names:+ Entity.objects.create(+ name=f'HASS Device {name}',+ entity_type_str='LIGHT',+ integration_id=HassMetaData.integration_id,+ integration_name=name,+ )++ def _run_check(self, hass_states_payload, allowlist=''):+ synchronizer = HassSynchronizer()+ manager = Mock()+ manager.import_allowlist = allowlist++ async def fetch_states(verbose=True):+ return hass_states_payload++ manager.fetch_hass_states_from_api_async = fetch_states++ async def get_manager():+ return manager++ with patch.object(synchronizer, 'hass_manager_async', side_effect=get_manager):+ return self.run_async(synchronizer.check_needs_sync())++ def _hass_state(self, entity_id):+ """Build a minimal valid HassState via the converter helper."""+ from hi.services.hass.hass_converter import HassConverter+ return HassConverter.create_hass_state({+ 'entity_id': entity_id,+ 'state': 'on',+ 'attributes': {},+ 'last_changed': '2026-05-06T00:00:00+00:00',+ 'last_updated': '2026-05-06T00:00:00+00:00',+ 'last_reported': '2026-05-06T00:00:00+00:00',+ 'context': {'id': '01', 'parent_id': None, 'user_id': None},+ })++ def test_in_sync_when_upstream_devices_match_hi(self):+ self._make_hass_entities(['kitchen', 'hall'])+ states = {+ 'switch.kitchen': self._hass_state('switch.kitchen'),+ 'switch.hall': self._hass_state('switch.hall'),+ }+ delta = self._run_check(+ hass_states_payload=states,+ allowlist='switch',+ )+ self.assertFalse(delta.needs_sync)++ def test_upstream_added_appears_in_delta(self):+ self._make_hass_entities(['kitchen', 'hall'])+ states = {+ 'switch.kitchen': self._hass_state('switch.kitchen'),+ 'switch.hall': self._hass_state('switch.hall'),+ 'switch.garage': self._hass_state('switch.garage'),+ }+ delta = self._run_check(+ hass_states_payload=states,+ allowlist='switch',+ )+ self.assertEqual(delta.added, {self._hass_key('garage')})+ self.assertEqual(delta.removed, set())++ def test_upstream_removed_appears_in_delta(self):+ self._make_hass_entities(['kitchen', 'hall'])+ states = {+ 'switch.kitchen': self._hass_state('switch.kitchen'),+ }+ delta = self._run_check(+ hass_states_payload=states,+ allowlist='switch',+ )+ self.assertEqual(delta.added, set())+ self.assertEqual(delta.removed, {self._hass_key('hall')})++ def test_allowlist_filters_upstream_set(self):+ # HA exposes a switch and a sensor; allowlist only allows+ # switch. The sensor should not appear in the upstream set,+ # so a HI side without 'weather' is still in sync.+ self._make_hass_entities(['kitchen'])+ states = {+ 'switch.kitchen': self._hass_state('switch.kitchen'),+ 'sensor.weather': self._hass_state('sensor.weather'),+ }+ delta = self._run_check(+ hass_states_payload=states,+ allowlist='switch',+ )+ self.assertFalse(delta.needs_sync)++ def test_returns_none_when_manager_not_ready(self):+ synchronizer = HassSynchronizer()++ async def get_manager():+ return None++ with patch.object(synchronizer, 'hass_manager_async', side_effect=get_manager):+ result = self.run_async(synchronizer.check_needs_sync())++ self.assertIsNone(result)diff --git a/src/hi/services/homebox/hb_sync.py b/src/hi/services/homebox/hb_sync.pyindex 1b1f0262..12bd327d 100644--- a/src/hi/services/homebox/hb_sync.py+++ b/src/hi/services/homebox/hb_sync.py@@ -1,11 +1,13 @@import loggingfrom typing import Dict, List, Optional+from asgiref.sync import sync_to_asyncfrom django.db import transactionfrom hi.apps.entity.models import Entity, EntityAttributefrom hi.integrations.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.sync_check import IntegrationSyncCheck, SyncDeltafrom hi.integrations.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKey@@ -28,6 +30,51 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):'each item, not as separate organizational concepts in HI.')+ async def check_needs_sync(self) -> Optional[SyncDelta]:+ """Issue #283 — sync-check probe for HomeBox.++ Uses the lightweight items-summary endpoint (one API call,+ no per-item details) to build the upstream IntegrationKey+ set, compares against the IntegrationKeys of HomeBox-attached+ HI entities, and returns the resulting ``SyncDelta``.+ Convention matched to+ ``HbConverter.hb_item_to_integration_key``: each HomeBox+ item becomes one HI entity whose ``integration_name`` is+ ``str(item.id)``. Adds/removes only — update detection via+ timestamps is deferred.+ """+ hb_manager = await self.hb_manager_async()+ if hb_manager is None:+ # Manager not yet initialized — let the next probe cycle+ # try again. Returning None opts this cycle out cleanly.+ return None+ summary_list = await hb_manager.fetch_hb_items_summary_from_api_async()+ upstream_keys = {+ IntegrationKey(+ integration_id = HbMetaData.integration_id,+ integration_name = str( item['id'] ),+ )+ for item in summary_list+ if item.get('id') is not None+ }+ current_keys = await sync_to_async( self._get_current_integration_keys )()+ return IntegrationSyncCheck.compute_delta(+ upstream_keys = upstream_keys,+ current_keys = current_keys,+ )++ @staticmethod+ def _get_current_integration_keys() -> set:+ return {+ IntegrationKey(+ integration_id = integration_id,+ integration_name = integration_name,+ )+ for integration_id, integration_name in Entity.objects.filter(+ integration_id = HbMetaData.integration_id,+ ).values_list( 'integration_id', 'integration_name' )+ }+def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:hb_manager = self.hb_manager()result = IntegrationSyncResult(diff --git a/src/hi/services/homebox/tests/test_hb_sync.py b/src/hi/services/homebox/tests/test_hb_sync.pyindex 23a22a74..95b7b1cd 100644--- a/src/hi/services/homebox/tests/test_hb_sync.py+++ b/src/hi/services/homebox/tests/test_hb_sync.py@@ -4,10 +4,12 @@ from unittest.mock import ANY, Mock, patchfrom django.test import SimpleTestCase+from hi.apps.entity.models import Entityfrom hi.integrations.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKeyfrom hi.services.homebox.hb_metadata import HbMetaDatafrom hi.services.homebox.hb_sync import HomeBoxSynchronizer+from hi.testing.async_task_utils import AsyncTaskTestCaselogging.disable(logging.CRITICAL)@@ -396,3 +398,102 @@ class TestHomeBoxSynchronizerRebuildIntegrationComponents(SimpleTestCase):hb_item=upstream,entity=existing_entity,)+++class TestHomeBoxSynchronizerCheckNeedsSync(AsyncTaskTestCase):+ """Issue #283 — sync-check probe shape for HomeBox.++ Uses a real DB so the probe's ``Entity.objects.filter(...)``+ query path is exercised end-to-end. Only the upstream HTTP+ boundary is mocked (the manager's+ ``fetch_hb_items_summary_from_api_async`` coroutine), which is+ the appropriate seam — internal accessors like+ ``_get_current_integration_keys`` run for real.++ Inherits ``AsyncTaskTestCase`` (a ``TransactionTestCase``+ subclass with a shared event loop) — required because the+ probe's ``sync_to_async`` DB query runs on a different thread+ than the test's transaction-wrapped writes, which deadlocks+ under SQLite when using a plain ``TestCase``.+ """++ def _hb_key(self, name: str):+ return IntegrationKey(+ integration_id=HbMetaData.integration_id,+ integration_name=name,+ )++ def _make_hb_entities(self, integration_names):+ for name in integration_names:+ Entity.objects.create(+ name=f'HomeBox Item {name}',+ entity_type_str='LIGHT',+ integration_id=HbMetaData.integration_id,+ integration_name=name,+ )++ def _run_check(self, summary_list):+ synchronizer = HomeBoxSynchronizer()+ manager = Mock()++ async def fetch_summary():+ return summary_list++ manager.fetch_hb_items_summary_from_api_async = fetch_summary++ async def get_manager():+ return manager++ with patch.object(synchronizer, 'hb_manager_async', side_effect=get_manager):+ return self.run_async(synchronizer.check_needs_sync())++ def test_in_sync_when_upstream_matches_hi(self):+ self._make_hb_entities(['1', '2'])+ delta = self._run_check(summary_list=[{'id': 1}, {'id': 2}])+ self.assertFalse(delta.needs_sync)++ def test_upstream_added_appears_in_delta(self):+ self._make_hb_entities(['1', '2'])+ delta = self._run_check(summary_list=[{'id': 1}, {'id': 2}, {'id': 3}])+ self.assertEqual(delta.added, {self._hb_key('3')})+ self.assertEqual(delta.removed, set())++ def test_upstream_removed_appears_in_delta(self):+ self._make_hb_entities(['1', '2'])+ delta = self._run_check(summary_list=[{'id': 1}])+ self.assertEqual(delta.added, set())+ self.assertEqual(delta.removed, {self._hb_key('2')})++ def test_summary_items_missing_id_are_skipped(self):+ # Defensive: a HomeBox item with no id (corrupted upstream+ # response) does not crash the probe — it is just dropped+ # from the upstream set.+ self._make_hb_entities(['1', '3'])+ delta = self._run_check(+ summary_list=[{'id': 1}, {'name': 'no-id'}, {'id': 3}],+ )+ self.assertFalse(delta.needs_sync)++ def test_returns_none_when_manager_not_ready(self):+ synchronizer = HomeBoxSynchronizer()++ async def get_manager():+ return None++ with patch.object(synchronizer, 'hb_manager_async', side_effect=get_manager):+ result = self.run_async(synchronizer.check_needs_sync())++ self.assertIsNone(result)++ def test_other_integrations_entities_are_ignored(self):+ # An entity from a different integration must not pollute+ # the HI key set the HomeBox probe compares against.+ self._make_hb_entities(['1'])+ Entity.objects.create(+ name='Other Integration Entity',+ entity_type_str='LIGHT',+ integration_id='hass',+ integration_name='other.entity',+ )+ delta = self._run_check(summary_list=[{'id': 1}])+ self.assertFalse(delta.needs_sync)diff --git a/src/hi/services/zoneminder/tests/test_zm_sync.py b/src/hi/services/zoneminder/tests/test_zm_sync.pyindex 28261523..bc3bd03c 100644--- a/src/hi/services/zoneminder/tests/test_zm_sync.py+++ b/src/hi/services/zoneminder/tests/test_zm_sync.py@@ -1235,3 +1235,112 @@ class EventDefinitionLifecycleCycleTests(TestCase):result=result,)self.assertEqual(self._zm_event_def_count(), 1)+++from hi.testing.async_task_utils import AsyncTaskTestCase+++class TestZoneMinderSynchronizerCheckNeedsSync(AsyncTaskTestCase):+ """Issue #283 — sync-check probe shape for ZoneMinder.++ Pins that upstream keys are built using the same prefix scheme+ as the live sync (``MONITOR.<id>``) and that the HI side filter+ excludes non-monitor entities (the ZM service entity, run-state+ sensors). Uses real Entity rows so the+ ``integration_name__startswith=prefix`` query is exercised — the+ "exclude service entity" claim that lives only in code is the+ load-bearing piece this test class pins.+ """++ def _zm_key(self, name: str):+ return IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=name,+ )++ def _make_zm_monitor_entities(self, monitor_ids):+ for monitor_id in monitor_ids:+ Entity.objects.create(+ name=f'Camera {monitor_id}',+ entity_type_str='CAMERA',+ integration_id=ZmMetaData.integration_id,+ integration_name=f'monitor.{monitor_id}',+ )++ def _make_zm_service_entity(self):+ # The ZM service entity is integration_id='zm' but does NOT+ # carry the 'monitor.' prefix — the probe must exclude it+ # from the comparison.+ Entity.objects.create(+ name='ZoneMinder Service',+ entity_type_str='SERVICE',+ integration_id=ZmMetaData.integration_id,+ integration_name='zoneminder.service',+ )++ def _run_check(self, monitor_ids):+ synchronizer = ZoneMinderSynchronizer()+ manager = Mock()+ manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'++ # Mirror the production zm_manager._to_integration_key+ # builder so the test's upstream side passes through the+ # same IntegrationKey construction the production code uses.+ def to_integration_key(prefix, zm_monitor_id):+ return IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=f'{prefix}.{zm_monitor_id}',+ )+ manager._to_integration_key = to_integration_key++ async def get_monitors(force_load=False):+ return [+ Mock(**{'id.return_value': monitor_id})+ for monitor_id in monitor_ids+ ]++ manager.get_zm_monitors_async = get_monitors++ async def get_manager():+ return manager++ with patch.object(synchronizer, 'zm_manager_async', side_effect=get_manager):+ return self.run_async(synchronizer.check_needs_sync())++ def test_in_sync_when_upstream_monitors_match_hi(self):+ self._make_zm_monitor_entities([1, 2, 3])+ delta = self._run_check(monitor_ids=[1, 2, 3])+ self.assertFalse(delta.needs_sync)++ def test_upstream_added_appears_in_delta(self):+ self._make_zm_monitor_entities([1, 2, 3])+ delta = self._run_check(monitor_ids=[1, 2, 3, 4])+ self.assertEqual(delta.added, {self._zm_key('monitor.4')})+ self.assertEqual(delta.removed, set())++ def test_upstream_removed_appears_in_delta(self):+ self._make_zm_monitor_entities([1, 2])+ delta = self._run_check(monitor_ids=[1])+ self.assertEqual(delta.added, set())+ self.assertEqual(delta.removed, {self._zm_key('monitor.2')})++ def test_zm_service_entity_is_excluded_from_comparison(self):+ # The ZM service entity has integration_id='zm' but no+ # 'monitor.' prefix on integration_name. The probe must+ # exclude it from the HI side, otherwise it would always+ # show up as "removed" (no upstream monitor matches).+ self._make_zm_monitor_entities([1, 2])+ self._make_zm_service_entity()+ delta = self._run_check(monitor_ids=[1, 2])+ self.assertFalse(delta.needs_sync)++ def test_returns_none_when_manager_not_ready(self):+ synchronizer = ZoneMinderSynchronizer()++ async def get_manager():+ return None++ with patch.object(synchronizer, 'zm_manager_async', side_effect=get_manager):+ result = self.run_async(synchronizer.check_needs_sync())++ self.assertIsNone(result)diff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_sync.pyindex a9472091..453f39a8 100644--- a/src/hi/services/zoneminder/zm_sync.py+++ b/src/hi/services/zoneminder/zm_sync.py@@ -2,6 +2,7 @@ import loggingfrom .pyzm_client.helpers.Monitor import Monitor as ZmMonitorfrom typing import Dict, Optional+from asgiref.sync import sync_to_asyncfrom django.db import transactionfrom hi.apps.entity.enums import EntityType@@ -17,6 +18,7 @@ from hi.apps.entity.entity_placement import ()from hi.integrations.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.sync_check import IntegrationSyncCheck, SyncDeltafrom hi.integrations.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKey@@ -48,6 +50,51 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):)return None+ async def check_needs_sync(self) -> Optional[SyncDelta]:+ """Issue #283 — sync-check probe for ZoneMinder.++ Fetches the current monitor list (cheap on a typical install+ — bounded by camera count), builds the upstream+ IntegrationKey set using the same prefix scheme as the live+ sync (``MONITOR.<id>``), and compares against the+ IntegrationKeys of monitor-shaped HI entities. The ZM service+ entity and run-state sensors are excluded from the+ comparison because they are not per-monitor and would+ otherwise look like permanent extras on the HI side.+ """+ zm_manager = await self.zm_manager_async()+ if zm_manager is None:+ return None+ prefix = zm_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX+ zm_monitors = await zm_manager.get_zm_monitors_async( force_load = True )+ upstream_keys = {+ zm_manager._to_integration_key(+ prefix = prefix,+ zm_monitor_id = zm_monitor.id(),+ )+ for zm_monitor in zm_monitors+ }+ current_keys = await sync_to_async( self._get_current_monitor_integration_keys )(+ prefix = prefix,+ )+ return IntegrationSyncCheck.compute_delta(+ upstream_keys = upstream_keys,+ current_keys = current_keys,+ )++ @staticmethod+ def _get_current_monitor_integration_keys( prefix : str ) -> set:+ return {+ IntegrationKey(+ integration_id = integration_id,+ integration_name = integration_name,+ )+ for integration_id, integration_name in Entity.objects.filter(+ integration_id = ZmMetaData.integration_id,+ integration_name__startswith = prefix,+ ).values_list( 'integration_id', 'integration_name' )+ }+def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:result = IntegrationSyncResult(title = self.get_result_title( is_initial_import = is_initial_import ),diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex 5ed80e48..817a0d51 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -1283,6 +1283,9 @@ g[hover] {.hi-integration-indicator-paused {color: var(--muted-color);}+.hi-integration-indicator-needs-sync {+ color: var(--info-color);+}.text-success-custom {color: var(--success-color);