Skip to content

Home Information - Your home, your data, organized.

Python

Add clear_signature API for persistent-state alarms (#378) (#380)

Tony C73f86a82143b
diff --git a/src/hi/apps/alert/alarm.py b/src/hi/apps/alert/alarm.py
index 2b4110ec..573d8936 100644
--- a/src/hi/apps/alert/alarm.py
+++ b/src/hi/apps/alert/alarm.py
@@ -9,6 +9,24 @@ from hi.apps.sense.transient_models import SensorResponse
from .enums import AlarmLevel, AlarmSource
+@dataclass(frozen=True)
+class AlarmSignature:
+ """Domain identity for a class of alarms that dedupe together.
+
+ Two alarms with the same signature surface as one Alert in the
+ queue. Producers construct an ``AlarmSignature`` to target alerts
+ for clearing on state recovery without having to know the alert
+ module's internal storage representation.
+ """
+
+ alarm_source : AlarmSource
+ alarm_type : str
+ alarm_level : AlarmLevel
+
+ def __str__(self):
+ return f'{self.alarm_source.name}.{self.alarm_type}.{self.alarm_level.name}'
+
+
@dataclass
class Alarm:
@@ -31,14 +49,16 @@ class Alarm:
source_alarm_id : Optional[str] = None
def __post_init__(self):
- # The lifetime field drives ``Alert.end_datetime``; zero or
+ # ``Alert.end_datetime`` is derived from this field; 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
+ # historical failure mode of the previous "0 = until
+ # acknowledged" convention). Raise rather than assert so the
+ # check survives ``python -O``.
+ if self.alarm_lifetime_secs <= 0:
+ raise ValueError(
+ f'alarm_lifetime_secs must be positive, got '
+ f'{self.alarm_lifetime_secs}'
+ )
return
@property
@@ -49,8 +69,12 @@ class Alarm:
return AudioSignal.from_alarm_attributes( self.alarm_level, self.alarm_source, self.alarm_type )
@property
- def signature(self):
- return f'{self.alarm_source}.{self.alarm_type}.{self.alarm_level}'
+ def signature(self) -> AlarmSignature:
+ return AlarmSignature(
+ alarm_source = self.alarm_source,
+ alarm_type = self.alarm_type,
+ alarm_level = self.alarm_level,
+ )
def get_view_url(self) -> str:
"""
diff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.py
index fd85a3d0..e655c175 100644
--- a/src/hi/apps/alert/alert.py
+++ b/src/hi/apps/alert/alert.py
@@ -189,8 +189,13 @@ class Alert:
return len(self.get_all_video_sources())
def to_notification_item(self):
+ # NotificationItem.signature is the notify-side dedup key
+ # (string). AlarmSignature.__str__ produces a stable, unique
+ # encoding -- coerce at the boundary so the notify layer
+ # stays string-typed and does not depend on the alert domain
+ # type.
return NotificationItem(
- signature = self.signature,
+ signature = str( self.signature ),
title = self.title,
source_obj = self,
)
diff --git a/src/hi/apps/alert/alert_manager.py b/src/hi/apps/alert/alert_manager.py
index 3178c98c..ed1b8b75 100644
--- a/src/hi/apps/alert/alert_manager.py
+++ b/src/hi/apps/alert/alert_manager.py
@@ -8,7 +8,7 @@ from hi.apps.notify.notify_mixins import NotificationMixin
from .alert import Alert
from .alert_queue import AlertQueue
-from .alarm import Alarm
+from .alarm import Alarm, AlarmSignature
from .alert_status import AlertStatusData
from .transient_models import AlertMaintenanceResult
@@ -81,6 +81,15 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):
def acknowledge_alert( self, alert_id : str ):
self._alert_queue.acknowledge_alert( alert_id = alert_id )
return
+
+ def clear_alarms( self, signature : AlarmSignature ) -> int:
+ """Drop any alert in the queue whose signature matches, so the
+ next bad-state alarm with the same signature creates a fresh
+ alert rather than being absorbed by a stale dedup anchor.
+ Returns the number of alerts removed; zero is a normal
+ outcome -- producers may call speculatively on every
+ recovery transition."""
+ return self._alert_queue.clear_signature( signature = signature )
async def upsert_alarm_async( self, alarm : Alarm ):
notification_manager = await self.notification_manager_async()
diff --git a/src/hi/apps/alert/alert_queue.py b/src/hi/apps/alert/alert_queue.py
index 132ac9cd..e16f5ea2 100644
--- a/src/hi/apps/alert/alert_queue.py
+++ b/src/hi/apps/alert/alert_queue.py
@@ -4,7 +4,7 @@ import threading
import hi.apps.common.datetimeproxy as datetimeproxy
-from .alarm import Alarm
+from .alarm import Alarm, AlarmSignature
from .alert import Alert
from .enums import AlarmLevel
from .transient_models import AlertQueueCleanupResult
@@ -175,6 +175,30 @@ class AlertQueue:
raise KeyError( f'Alert not found for {alert_id}' )
+ def clear_signature( self, signature : AlarmSignature ) -> int:
+ """Remove any alert -- acked or unacked -- whose signature
+ matches, so the next bad-state alarm with the same signature
+ creates a fresh alert and re-fires notification rather than
+ being absorbed by the stale dedup anchor. Returns the number
+ of alerts removed; zero is a normal outcome."""
+ with self._active_alerts_lock:
+ if len( self._alert_list ) < 1:
+ return 0
+ new_list = list()
+ removed = 0
+ for alert in self._alert_list:
+ if alert.signature == signature:
+ removed += 1
+ continue
+ new_list.append( alert )
+ continue
+ if removed > 0:
+ self._alert_list = new_list
+ self._last_changed_datetime = datetimeproxy.now()
+ logger.debug( f'Cleared {removed} alert(s)'
+ f' with signature "{signature}".' )
+ return removed
+
def remove_expired_alerts(self):
"""Remove alerts whose ``end_datetime`` has passed. Acknowledged
alerts are kept until their natural expiry so they continue to
diff --git a/src/hi/apps/alert/tests/test_alarm.py b/src/hi/apps/alert/tests/test_alarm.py
index 3cdc9965..8c17e1f9 100644
--- a/src/hi/apps/alert/tests/test_alarm.py
+++ b/src/hi/apps/alert/tests/test_alarm.py
@@ -17,6 +17,7 @@ class TestAlarm(BaseTestCase):
def test_alarm_signature_generation(self):
"""Test alarm signature generation - critical for alarm aggregation logic."""
+ from hi.apps.alert.alarm import AlarmSignature
alarm = Alarm(
alarm_source=AlarmSource.EVENT,
alarm_type='test_alarm',
@@ -27,10 +28,20 @@ class TestAlarm(BaseTestCase):
alarm_lifetime_secs=300,
timestamp=datetime.now(),
)
-
- expected_signature = f'{AlarmSource.EVENT}.test_alarm.{AlarmLevel.WARNING}'
+
+ expected_signature = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.WARNING,
+ )
self.assertEqual(alarm.signature, expected_signature)
-
+ # Joined-string form (used in diagnostics) preserves the
+ # dotted ``source.type.level`` shape using readable enum names.
+ self.assertEqual(
+ str(alarm.signature),
+ f'{AlarmSource.EVENT.name}.test_alarm.{AlarmLevel.WARNING.name}',
+ )
+
# Test with different values
critical_alarm = Alarm(
alarm_source=AlarmSource.EVENT,
@@ -42,10 +53,14 @@ class TestAlarm(BaseTestCase):
alarm_lifetime_secs=300,
timestamp=datetime.now(),
)
-
- expected_critical_signature = f'{AlarmSource.EVENT}.critical_test.{AlarmLevel.CRITICAL}'
+
+ expected_critical_signature = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='critical_test',
+ alarm_level=AlarmLevel.CRITICAL,
+ )
self.assertEqual(critical_alarm.signature, expected_critical_signature)
-
+
# Signatures should be different
self.assertNotEqual(alarm.signature, critical_alarm.signature)
return
@@ -101,6 +116,73 @@ class TestAlarm(BaseTestCase):
return
+class TestAlarmSignature(BaseTestCase):
+
+ def test_signatures_with_same_components_are_equal_and_hash_equal(self):
+ """Frozen-dataclass structural equality / hashability is what
+ ``AlertQueue`` relies on for dedup and what producers rely on
+ when constructing a clear target from a different code path."""
+ from hi.apps.alert.alarm import AlarmSignature
+ a = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='shared',
+ alarm_level=AlarmLevel.WARNING,
+ )
+ b = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='shared',
+ alarm_level=AlarmLevel.WARNING,
+ )
+ self.assertEqual(a, b)
+ self.assertEqual(hash(a), hash(b))
+ # Usable as a dict / set key.
+ self.assertEqual(len({a, b}), 1)
+ return
+
+ def test_signatures_differing_in_any_component_are_unequal(self):
+ """All three components participate in identity; changing any
+ one must produce a distinct signature."""
+ from hi.apps.alert.alarm import AlarmSignature
+ base = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='t',
+ alarm_level=AlarmLevel.WARNING,
+ )
+ diff_source = AlarmSignature(
+ alarm_source=AlarmSource.WEATHER,
+ alarm_type='t',
+ alarm_level=AlarmLevel.WARNING,
+ )
+ diff_type = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='other',
+ alarm_level=AlarmLevel.WARNING,
+ )
+ diff_level = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='t',
+ alarm_level=AlarmLevel.CRITICAL,
+ )
+ self.assertNotEqual(base, diff_source)
+ self.assertNotEqual(base, diff_type)
+ self.assertNotEqual(base, diff_level)
+ return
+
+ def test_signature_str_uses_enum_names_for_readable_logs(self):
+ """``__str__`` is the form that surfaces in debug logs (see
+ ``AlertQueue.clear_signature``). It must use enum ``.name`` so
+ log lines read like ``EVENT.foo.CRITICAL`` rather than the
+ verbose default-repr form."""
+ from hi.apps.alert.alarm import AlarmSignature
+ sig = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='foo',
+ alarm_level=AlarmLevel.CRITICAL,
+ )
+ self.assertEqual(str(sig), 'EVENT.foo.CRITICAL')
+ return
+
+
class TestAlarmWithSensorResponse(BaseTestCase):
def test_alarm_with_sensor_response_details(self):
diff --git a/src/hi/apps/alert/tests/test_alert_manager.py b/src/hi/apps/alert/tests/test_alert_manager.py
index dcc72118..aedc806b 100644
--- a/src/hi/apps/alert/tests/test_alert_manager.py
+++ b/src/hi/apps/alert/tests/test_alert_manager.py
@@ -3,7 +3,7 @@ from unittest.mock import patch
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.alert.alert_manager import AlertManager, AlertMaintenanceResult
-from hi.apps.alert.alarm import Alarm
+from hi.apps.alert.alarm import Alarm, AlarmSignature
from hi.apps.alert.enums import AlarmLevel, AlarmSource
from hi.apps.security.enums import SecurityLevel
from hi.testing.async_task_utils import AsyncTaskFastTestCase
@@ -169,6 +169,91 @@ class TestAlertManager(BaseTestCase):
)
return
+ def test_clear_alarms_removes_matching_alert(self):
+ """``AlertManager.clear_alarms`` takes an ``AlarmSignature``
+ the producer constructs from the same fields the original
+ ``Alarm`` carried. The composition (joined-string form, used
+ for diagnostics) stays inside ``AlarmSignature``; the queue
+ compares structurally."""
+ manager = AlertManager()
+ manager._alert_queue._alert_list.clear()
+
+ test_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='clear_alarms_test',
+ alarm_level=AlarmLevel.WARNING,
+ title='Clear-alarms target',
+ sensor_response_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+ manager._alert_queue.add_alarm(test_alarm)
+
+ removed = manager.clear_alarms(
+ signature=AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='clear_alarms_test',
+ alarm_level=AlarmLevel.WARNING,
+ )
+ )
+
+ self.assertEqual(removed, 1)
+ self.assertEqual(len(manager.unacknowledged_alert_list), 0)
+ return
+
+ def test_clear_alarms_returns_zero_when_no_match(self):
+ """``clear_alarms`` returns 0 (not None / not error) when
+ nothing in the queue matches. Producers may call it
+ speculatively on every recovery transition; the no-op outcome
+ must be cheap and silent."""
+ manager = AlertManager()
+ manager._alert_queue._alert_list.clear()
+
+ removed = manager.clear_alarms(
+ signature=AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='nothing.like.this.is.queued',
+ alarm_level=AlarmLevel.WARNING,
+ )
+ )
+
+ self.assertEqual(removed, 0)
+ return
+
+ def test_clear_alarms_matches_alarm_signature(self):
+ """The ``AlarmSignature`` a producer constructs MUST equal the
+ ``Alarm.signature`` of an alarm with the same fields. Pins
+ the contract that ``AlarmSignature`` is the structural
+ identity, not a coincidental string match."""
+ manager = AlertManager()
+ manager._alert_queue._alert_list.clear()
+
+ test_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='roundtrip_test',
+ alarm_level=AlarmLevel.CRITICAL,
+ title='Round-trip target',
+ sensor_response_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+ alert = manager._alert_queue.add_alarm(test_alarm)
+
+ producer_signature = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='roundtrip_test',
+ alarm_level=AlarmLevel.CRITICAL,
+ )
+ # Producer's signature equals the alert's signature -- otherwise
+ # ``clear_alarms`` would silently miss its target.
+ self.assertEqual(producer_signature, alert.signature)
+
+ removed = manager.clear_alarms(signature=producer_signature)
+ self.assertEqual(removed, 1)
+ return
+
def test_alert_manager_alert_queue_integration(self):
"""Test AlertManager integration with AlertQueue - critical system interaction."""
manager = AlertManager()
diff --git a/src/hi/apps/alert/tests/test_alert_queue.py b/src/hi/apps/alert/tests/test_alert_queue.py
index 1f2c3e46..1a8b78ef 100644
--- a/src/hi/apps/alert/tests/test_alert_queue.py
+++ b/src/hi/apps/alert/tests/test_alert_queue.py
@@ -5,7 +5,7 @@ import threading
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.alert.alert_queue import AlertQueue
from hi.apps.alert.alert import Alert
-from hi.apps.alert.alarm import Alarm
+from hi.apps.alert.alarm import Alarm, AlarmSignature
from hi.apps.alert.enums import AlarmLevel, AlarmSource
from hi.apps.security.enums import SecurityLevel
from hi.testing.base_test_case import BaseTestCase
@@ -515,6 +515,167 @@ class TestAlertQueue(BaseTestCase):
datetimeproxy.reset()
return
+ def test_clear_signature_removes_unacked_matching_alert(self):
+ """``clear_signature`` drops an unacknowledged alert with the
+ matching signature -- this is the path producers will use
+ when an external condition resolves before the operator has
+ seen the alert."""
+ alert = self.queue.add_alarm(self.test_alarm)
+ signature = alert.signature
+ self.assertEqual(len(self.queue), 1)
+
+ removed = self.queue.clear_signature(signature)
+
+ self.assertEqual(removed, 1)
+ self.assertEqual(len(self.queue), 0)
+ with self.assertRaises(KeyError):
+ self.queue.get_alert(alert.id)
+ return
+
+ def test_clear_signature_removes_acked_dedup_anchor(self):
+ """The primary use case: an acknowledged alert that was
+ retained as a dedup anchor must be removable by
+ ``clear_signature`` when the producer detects state
+ recovery."""
+ alert = self.queue.add_alarm(self.test_alarm)
+ self.queue.acknowledge_alert(alert.id)
+ signature = alert.signature
+ self.assertEqual(len(self.queue), 1)
+
+ removed = self.queue.clear_signature(signature)
+
+ self.assertEqual(removed, 1)
+ self.assertEqual(len(self.queue), 0)
+ return
+
+ def test_clear_signature_no_op_when_no_match(self):
+ """No matching alert -> returns 0, queue unchanged. Callers
+ must not treat zero as an error."""
+ alert = self.queue.add_alarm(self.test_alarm)
+ before_changed = self.queue._last_changed_datetime
+
+ non_matching = AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='not_in_queue',
+ alarm_level=AlarmLevel.INFO,
+ )
+ removed = self.queue.clear_signature(non_matching)
+
+ self.assertEqual(removed, 0)
+ self.assertEqual(len(self.queue), 1)
+ self.assertEqual(self.queue.get_alert(alert.id), alert)
+ # ``_last_changed_datetime`` must NOT advance when nothing
+ # was removed -- consumers polling on that timestamp would
+ # otherwise see spurious "queue changed" signals.
+ self.assertEqual(self.queue._last_changed_datetime, before_changed)
+ return
+
+ def test_clear_signature_no_op_on_empty_queue(self):
+ """Empty queue: returns 0 without touching state."""
+ self.assertEqual(len(self.queue), 0)
+ before_changed = self.queue._last_changed_datetime
+
+ removed = self.queue.clear_signature(
+ AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='anything',
+ alarm_level=AlarmLevel.INFO,
+ )
+ )
+
+ self.assertEqual(removed, 0)
+ self.assertEqual(self.queue._last_changed_datetime, before_changed)
+ return
+
+ def test_clear_signature_leaves_non_matching_alerts_intact(self):
+ """Only the targeted signature is removed; other alerts
+ survive."""
+ target = self.queue.add_alarm(self.test_alarm)
+ other = self.queue.add_alarm(
+ self._make_alarm('other_type', level=AlarmLevel.CRITICAL),
+ )
+ self.assertEqual(len(self.queue), 2)
+
+ removed = self.queue.clear_signature(target.signature)
+
+ self.assertEqual(removed, 1)
+ self.assertEqual(len(self.queue), 1)
+ self.assertEqual(self.queue.get_alert(other.id), other)
+ return
+
+ def test_clear_signature_updates_last_changed_only_on_removal(self):
+ """The ``_last_changed_datetime`` advances when the call
+ removes alerts but not when it's a no-op. Polling consumers
+ rely on the timestamp to detect state changes."""
+ from datetime import timedelta
+ baseline = datetimeproxy.now()
+ datetimeproxy.set(baseline)
+ try:
+ alert = self.queue.add_alarm(self.test_alarm)
+ insertion_changed = self.queue._last_changed_datetime
+ # Advance the clock and call clear_signature on a
+ # non-matching signature: timestamp must not move.
+ datetimeproxy.set(baseline + timedelta(seconds=10))
+ self.queue.clear_signature(
+ AlarmSignature(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='not_matching',
+ alarm_level=AlarmLevel.INFO,
+ )
+ )
+ self.assertEqual(self.queue._last_changed_datetime, insertion_changed)
+ # Advance further and clear the actual signature: timestamp
+ # must now advance to reflect the change.
+ datetimeproxy.set(baseline + timedelta(seconds=20))
+ self.queue.clear_signature(alert.signature)
+ self.assertGreater(
+ self.queue._last_changed_datetime, insertion_changed
+ )
+ finally:
+ datetimeproxy.reset()
+ return
+
+ def test_clear_signature_removes_all_matching_alerts(self):
+ """``clear_signature`` walks the whole list and removes every
+ match. The normal ``add_alarm`` path aggregates same-signature
+ alarms into a single alert, so two distinct alerts with the
+ same signature don't arise from typical use -- but the method
+ contract is N-matches-N-removed, pinned here by seeding
+ ``_alert_list`` directly."""
+ a1 = self._make_alarm('multi_match')
+ a2 = self._make_alarm('multi_match')
+ alert1 = Alert(first_alarm=a1)
+ alert2 = Alert(first_alarm=a2)
+ with self.queue._active_alerts_lock:
+ self.queue._alert_list = [alert1, alert2]
+ self.assertEqual(alert1.signature, alert2.signature)
+
+ removed = self.queue.clear_signature(alert1.signature)
+
+ self.assertEqual(removed, 2)
+ self.assertEqual(len(self.queue), 0)
+ return
+
+ def test_clear_signature_then_matching_alarm_creates_fresh_alert(self):
+ """Regression check on the design goal: after ``clear_signature``,
+ a subsequent matching alarm produces a NEW alert (not absorbed
+ into a stale anchor), so notification re-fires."""
+ first_alert = self.queue.add_alarm(self.test_alarm)
+ self.queue.acknowledge_alert(first_alert.id)
+ signature = first_alert.signature
+
+ self.queue.clear_signature(signature)
+ # Same signature alarm arrives after recovery -- must NOT
+ # absorb (queue is empty); must create a new alert with a
+ # distinct id.
+ re_alarm = self._make_alarm('test_alarm')
+ re_alert = self.queue.add_alarm(re_alarm)
+
+ self.assertEqual(re_alert.signature, signature)
+ self.assertNotEqual(re_alert.id, first_alert.id)
+ self.assertEqual(len(self.queue.unacknowledged_alert_list), 1)
+ return
+
def test_alert_queue_remove_expired_counts_acknowledged_among_removed(self):
"""``acknowledged_removed`` reports the subset of expired alerts
that had been acknowledged. No longer a removal trigger; just
diff --git a/src/hi/apps/event/event_manager.py b/src/hi/apps/event/event_manager.py
index 219a5724..4cdddbc0 100644
--- a/src/hi/apps/event/event_manager.py
+++ b/src/hi/apps/event/event_manager.py
@@ -26,6 +26,27 @@ logger = logging.getLogger(__name__)
class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):
+ """
+ Routes EntityState transitions through EventDefinition rules,
+ persists matching events to ``EventHistory``, and fires the
+ associated alarms / control actions on the transition-arrival
+ hot path.
+
+ EventDefinition-driven alarms split conceptually into
+ *state-condition* (battery, smoke, connectivity -- persistent bad
+ state) and *event-of-interest* (motion, presence, open/close --
+ discrete occurrence the operator wants to see regardless of
+ subsequent state). Another case exists by trigger shape but not
+ by operator semantics: security/intrusion alarms read as
+ state-condition but must persist in the queue regardless of
+ whether the door is now closed. The engine does not auto-clear
+ on rule-no-longer-matches for any class;
+ ``HiModelHelper.NAG_INTERVAL_SECS`` (24h) bounds the worst-case
+ post-acknowledgement suppression. Enabling auto-clear for any
+ subset of rules requires a per-EventDefinition opt-in flag so
+ intrusion-class rules can stay out of it -- that flag is not yet
+ modeled.
+ """
RECENT_EVENT_CACHE_SIZE = 1000
RECENT_EVENT_CACHE_TTL_SECS = 3600
diff --git a/src/hi/apps/system/health_status_alarm_mapper.py b/src/hi/apps/system/health_status_alarm_mapper.py
index 32563781..8076d415 100644
--- a/src/hi/apps/system/health_status_alarm_mapper.py
+++ b/src/hi/apps/system/health_status_alarm_mapper.py
@@ -2,35 +2,32 @@
Map HealthStatusProvider state transitions to system alarms.
Stateless policy concentrator. Inputs: a HealthStatusTransition plus the
-provider's declared maximum allowed alarm level. Output: an Optional[Alarm]
-that the caller (HealthStatusProvider._dispatch_transition_alarm) hands to
-AlertManager.
+provider's declared maximum allowed alarm level. Output for a degrade
+transition: an Optional[Alarm] the caller hands to AlertManager. Output
+for a recovery transition: an Optional[AlarmSignature] the caller hands
+to AlertManager.clear_alarms so the prior bad-state alert drops from
+the queue.
-Design echoes WeatherAlertAlarmMapper:
-- Single create_alarm() entry point; helper methods are pure.
-- Alarms apply at SecurityLevel.OFF (universal — health affects everyone).
-- Distinct alarm_type strings for error vs recovery so the alert queue
- treats them as separate alerts the user can see and acknowledge
- independently.
+- Single create_alarm() entry point for degrades; helper methods are pure.
+- Alarms apply at SecurityLevel.OFF (universal -- health affects everyone).
Per-provider seriousness is expressed as a maximum alarm level (the
"ceiling"), declared by the provider via HealthStatusProvider.alarm_ceiling.
The mapper picks a "natural" alarm level for the transition class
-(ERROR=CRITICAL, WARNING=WARNING, recovery=INFO) and clamps to the
-provider's ceiling. This lets each provider declare relative importance
-(e.g., HASS/ZM ceiling=CRITICAL, HomeBox ceiling=INFO) without owning the
-full mapping policy.
+(ERROR=CRITICAL, WARNING=WARNING) and clamps to the provider's ceiling.
+The recovery-target helper applies the SAME clamp, so the level it
+returns matches the level the error alarm was queued at.
Transitions involving UNKNOWN or DISABLED on either side are
-suppressed entirely (no alarm fires). UNKNOWN is initialization noise
-with no settled baseline; DISABLED is operator-initiated and the
-operator already knows.
+suppressed entirely (no alarm fires, no recovery target). UNKNOWN is
+initialization noise with no settled baseline; DISABLED is
+operator-initiated and the operator already knows.
"""
from typing import List, Optional
import logging
import hi.apps.common.datetimeproxy as datetimeproxy
-from hi.apps.alert.alarm import Alarm
+from hi.apps.alert.alarm import Alarm, AlarmSignature
from hi.apps.alert.enums import AlarmLevel, AlarmSource
from hi.apps.security.enums import SecurityLevel
from hi.apps.sense.transient_models import SensorResponse
@@ -44,21 +41,15 @@ logger = logging.getLogger(__name__)
class HealthStatusAlarmMapper:
- # Single shared lifetime for both error and recovery alarms. They
- # MUST match: if recovery expired before the error it's resolving,
- # the user would be left looking at a bare error alert from the
- # moment the recovery disappeared until the error finally expired —
- # incorrectly suggesting the integration is still broken.
ALARM_LIFETIME_SECS = 30 * 60
# Natural alarm level for each transition class, BEFORE the
# per-provider ceiling is applied. DISABLED is intentionally
- # omitted — see _ALARM_SUPPRESSED_STATES.
+ # omitted -- see _ALARM_SUPPRESSED_STATES.
NATURAL_LEVEL_FOR_NEW_STATUS = {
HealthStatusType.ERROR : AlarmLevel.CRITICAL,
HealthStatusType.WARNING : AlarmLevel.WARNING,
}
- RECOVERY_NATURAL_LEVEL = AlarmLevel.INFO
# States whose presence on EITHER side of a transition disqualifies
# the transition from alarming:
@@ -73,57 +64,89 @@ class HealthStatusAlarmMapper:
HealthStatusType.DISABLED,
})
+ @staticmethod
+ def _error_alarm_type( provider_id : str ) -> str:
+ # Shared by the degrade (queue) and recovery (clear-target)
+ # paths; recovery clears the alarm an earlier degrade queued,
+ # so the two paths MUST agree on the type string.
+ return f'health_status.{provider_id}.error'
+
def should_create_alarm( self, transition : HealthStatusTransition ) -> bool:
+ # Recovery transitions are handled by the clear-target path.
+ if transition.is_recovery:
+ return False
if ( transition.previous_status in self._ALARM_SUPPRESSED_STATES
or transition.current_status in self._ALARM_SUPPRESSED_STATES ):
return False
-
- # Recovery: HEALTHY from a non-HEALTHY state.
- if transition.is_recovery:
- return True
-
- # Forward transitions into states that warrant an alarm.
if transition.current_status in self.NATURAL_LEVEL_FOR_NEW_STATUS:
return True
return False
+ def _natural_level_for_bad_status(
+ self,
+ status : HealthStatusType,
+ max_level : AlarmLevel ) -> Optional[ AlarmLevel ]:
+ # The clamped alarm level a forward (degrade) transition INTO
+ # ``status`` would fire at -- shared by ``get_alarm_level`` and
+ # ``get_recovery_target_signature`` so the two paths produce
+ # identical levels for the same (status, ceiling) pair.
+ natural = self.NATURAL_LEVEL_FOR_NEW_STATUS.get( status )
+ if natural is None:
+ return None
+ if natural.priority > max_level.priority:
+ return max_level
+ return natural
+
def get_alarm_level( self,
transition : HealthStatusTransition,
max_level : AlarmLevel ) -> Optional[ AlarmLevel ]:
if not self.should_create_alarm( transition ):
return None
+ return self._natural_level_for_bad_status(
+ status = transition.current_status,
+ max_level = max_level,
+ )
- if transition.is_recovery:
- natural = self.RECOVERY_NATURAL_LEVEL
- else:
- natural = self.NATURAL_LEVEL_FOR_NEW_STATUS.get( transition.current_status )
- if natural is None:
+ def get_recovery_target_signature(
+ self,
+ transition : HealthStatusTransition,
+ max_level : AlarmLevel,
+ ) -> Optional[ AlarmSignature ]:
+ """For a recovery transition, return the ``AlarmSignature`` the
+ prior bad-state alarm was queued under. Caller hands this to
+ ``AlertManager.clear_alarms`` to drop that alert from the queue.
+
+ Returns ``None`` for:
+ - Non-recovery transitions (caller has nothing to clear).
+ - Recoveries from a state the mapper would have suppressed
+ (UNKNOWN, DISABLED) -- no prior alarm was issued, so nothing
+ to clear."""
+ if not transition.is_recovery:
return None
-
- # Clamp to the provider's declared ceiling.
- if natural.priority > max_level.priority:
- return max_level
- return natural
+ previous_status = transition.previous_status
+ if previous_status in self._ALARM_SUPPRESSED_STATES:
+ return None
+ level = self._natural_level_for_bad_status(
+ status = previous_status,
+ max_level = max_level,
+ )
+ if level is None:
+ return None
+ return AlarmSignature(
+ alarm_source = AlarmSource.HEALTH_STATUS,
+ alarm_type = self._error_alarm_type( transition.provider_info.provider_id ),
+ alarm_level = level,
+ )
def get_alarm_lifetime_secs( self, transition : HealthStatusTransition ) -> int:
return self.ALARM_LIFETIME_SECS
def get_alarm_type( self, transition : HealthStatusTransition ) -> str:
- # Distinct types so error and recovery produce separate alerts
- # the user can see and acknowledge independently. Includes the
- # provider id so signatures group sensibly when multiple
- # providers are unhealthy at once.
- provider_id = transition.provider_info.provider_id
- if transition.is_recovery:
- return f'health_status.{provider_id}.recovered'
- return f'health_status.{provider_id}.error'
+ return self._error_alarm_type( transition.provider_info.provider_id )
def get_alarm_title( self, transition : HealthStatusTransition ) -> str:
- provider_name = transition.provider_info.provider_name
- if transition.is_recovery:
- return f'{provider_name} recovered'
- return f'{provider_name} unhealthy'
+ return f'{transition.provider_info.provider_name} unhealthy'
def create_sensor_responses( self,
transition : HealthStatusTransition ) -> List[ SensorResponse ]:
diff --git a/src/hi/apps/system/health_status_provider.py b/src/hi/apps/system/health_status_provider.py
index c7236812..0e818edf 100644
--- a/src/hi/apps/system/health_status_provider.py
+++ b/src/hi/apps/system/health_status_provider.py
@@ -176,11 +176,19 @@ class HealthStatusProvider(ABC):
error_count : int,
timestamp ) -> None:
"""
- Map a state transition to an alarm and queue it via AlertManager
+ Map a state transition to an alarm action against AlertManager
when the provider is opted in (alarm_ceiling returns
- non-None). The framework calls into the alert subsystem
- directly — the dependency direction (apps/system -> apps/alert)
- is acceptable since alert is a more general-purpose facility.
+ non-None). Two paths:
+
+ - Degrade (HEALTHY/UNKNOWN -> WARNING/ERROR, and same-level
+ re-degrade): mapper produces an Alarm; we ``upsert_alarm``.
+ - Recovery (anything-bad -> HEALTHY): mapper produces the
+ ``AlarmSignature`` of the prior bad-state alarm; we
+ ``clear_alarms`` to drop it from the queue.
+
+ The framework calls into the alert subsystem directly -- the
+ dependency direction (apps/system -> apps/alert) is acceptable
+ since alert is a more general-purpose facility.
Caller (update_health_status) wraps invocations in a safety
net, so subclass overrides do not need to defend against their
@@ -203,7 +211,19 @@ class HealthStatusProvider(ABC):
error_count = error_count,
timestamp = timestamp,
)
- alarm = HealthStatusAlarmMapper().create_alarm(
+
+ mapper = HealthStatusAlarmMapper()
+ if transition.is_recovery:
+ signature = mapper.get_recovery_target_signature(
+ transition = transition,
+ max_level = max_level,
+ )
+ if signature is None:
+ return
+ AlertManager().clear_alarms( signature = signature )
+ return
+
+ alarm = mapper.create_alarm(
transition = transition,
max_level = max_level,
)
diff --git a/src/hi/apps/system/tests/test_health_status_alarm_mapper.py b/src/hi/apps/system/tests/test_health_status_alarm_mapper.py
index b4038d82..83c876fb 100644
--- a/src/hi/apps/system/tests/test_health_status_alarm_mapper.py
+++ b/src/hi/apps/system/tests/test_health_status_alarm_mapper.py
@@ -81,13 +81,17 @@ class HealthStatusAlarmMapperTest(SimpleTestCase):
t = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)
self.assertTrue(self.mapper.should_create_alarm(t))
- def test_error_to_healthy_recovery_alarms(self):
- t = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)
- self.assertTrue(self.mapper.should_create_alarm(t))
-
- def test_warning_to_healthy_recovery_alarms(self):
- t = _transition(HealthStatusType.WARNING, HealthStatusType.HEALTHY)
- self.assertTrue(self.mapper.should_create_alarm(t))
+ def test_recovery_transitions_do_not_create_alarm(self):
+ """Recovery transitions are handled by the clear-target path
+ (``get_recovery_target_signature`` + ``AlertManager.clear_alarms``),
+ not the create-alarm path. ``should_create_alarm`` must return
+ False so the caller doesn't double-handle the transition."""
+ for prev in (HealthStatusType.ERROR, HealthStatusType.WARNING):
+ t = _transition(prev, HealthStatusType.HEALTHY)
+ self.assertFalse(
+ self.mapper.should_create_alarm(t),
+ f'recovery from {prev} should NOT create an alarm',
+ )
# --- get_alarm_level: natural levels and ceiling clamp ---
@@ -105,11 +109,13 @@ class HealthStatusAlarmMapperTest(SimpleTestCase):
AlarmLevel.WARNING,
)
- def test_recovery_natural_level_is_info(self):
+ def test_recovery_returns_no_alarm_level(self):
+ """Recovery transitions don't fire alarms (cleared via
+ ``clear_alarms`` instead); their ``get_alarm_level`` returns
+ ``None``."""
t = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)
- self.assertEqual(
- self.mapper.get_alarm_level(t, max_level=AlarmLevel.CRITICAL),
- AlarmLevel.INFO,
+ self.assertIsNone(
+ self.mapper.get_alarm_level(t, max_level=AlarmLevel.CRITICAL)
)
def test_error_clamped_down_when_provider_caps_at_info(self):
@@ -140,18 +146,15 @@ class HealthStatusAlarmMapperTest(SimpleTestCase):
# --- alarm types: signature stability ---
- def test_error_and_recovery_have_distinct_types(self):
+ def test_error_alarm_type_includes_provider_id(self):
+ """The error alarm type embeds the provider id so signatures
+ from distinct providers don't collapse together. ``get_alarm_type``
+ is only called from ``create_alarm`` (degrade path); recovery
+ is handled by ``get_recovery_target_signature``."""
t_err = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)
- t_rec = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)
- self.assertNotEqual(
- self.mapper.get_alarm_type(t_err),
- self.mapper.get_alarm_type(t_rec),
- )
- self.assertIn('error', self.mapper.get_alarm_type(t_err))
- self.assertIn('recovered', self.mapper.get_alarm_type(t_rec))
- # Provider id is part of the type so different providers don't
- # collapse into the same alarm.
- self.assertIn('test.provider', self.mapper.get_alarm_type(t_err))
+ alarm_type = self.mapper.get_alarm_type(t_err)
+ self.assertIn('error', alarm_type)
+ self.assertIn('test.provider', alarm_type)
# --- create_alarm end-to-end ---
@@ -168,12 +171,16 @@ class HealthStatusAlarmMapperTest(SimpleTestCase):
self.assertEqual(sr.detail_attrs['Status'], HealthStatusType.ERROR.label)
self.assertEqual(sr.detail_attrs['Message'], 'upstream unreachable')
- def test_create_alarm_full_shape_for_recovery(self):
- t = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)
- alarm = self.mapper.create_alarm(t, max_level=AlarmLevel.CRITICAL)
- self.assertIsNotNone(alarm)
- self.assertEqual(alarm.alarm_level, AlarmLevel.INFO)
- self.assertIn('recovered', alarm.title.lower())
+ def test_create_alarm_returns_none_for_recovery(self):
+ """Recovery transitions no longer fire their own alarm. The
+ caller invokes ``get_recovery_target_signature`` and
+ ``AlertManager.clear_alarms`` instead."""
+ for prev in (HealthStatusType.ERROR, HealthStatusType.WARNING):
+ t = _transition(prev, HealthStatusType.HEALTHY)
+ self.assertIsNone(
+ self.mapper.create_alarm(t, max_level=AlarmLevel.CRITICAL),
+ f'recovery from {prev} should produce no alarm',
+ )
def test_create_alarm_returns_none_for_suppressed_edges(self):
for prev, curr in [
@@ -187,14 +194,87 @@ class HealthStatusAlarmMapperTest(SimpleTestCase):
f'{prev} -> {curr} should produce no alarm',
)
- def test_error_and_recovery_share_lifetime(self):
- # Recovery must not expire before the error it's resolving —
- # otherwise the user sees a bare error alert with no recovery
- # context for the rest of the error's lifetime, suggesting the
- # integration is still broken.
- t_err = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)
- t_rec = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)
- self.assertEqual(
- self.mapper.get_alarm_lifetime_secs(t_err),
- self.mapper.get_alarm_lifetime_secs(t_rec),
+ # --- get_recovery_target_signature ---
+
+ def test_recovery_target_signature_error_to_healthy(self):
+ """Recovery from ERROR clears the CRITICAL-level error alarm
+ the prior degrade transition would have queued."""
+ t = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)
+ signature = self.mapper.get_recovery_target_signature(
+ transition=t, max_level=AlarmLevel.CRITICAL,
+ )
+ self.assertIsNotNone(signature)
+ self.assertEqual(signature.alarm_source, AlarmSource.HEALTH_STATUS)
+ self.assertIn('test.provider', signature.alarm_type)
+ self.assertIn('error', signature.alarm_type)
+ self.assertEqual(signature.alarm_level, AlarmLevel.CRITICAL)
+
+ def test_recovery_target_signature_warning_to_healthy(self):
+ """Recovery from WARNING clears the WARNING-level alarm. Each
+ bad-state level produces its own signature so the clear must
+ target the correct one."""
+ t = _transition(HealthStatusType.WARNING, HealthStatusType.HEALTHY)
+ signature = self.mapper.get_recovery_target_signature(
+ transition=t, max_level=AlarmLevel.CRITICAL,
+ )
+ self.assertIsNotNone(signature)
+ self.assertEqual(signature.alarm_level, AlarmLevel.WARNING)
+
+ def test_recovery_target_signature_uses_clamped_level(self):
+ """The clear-target's level must reflect the SAME ceiling-clamp
+ applied when the original degrade alarm was queued, otherwise
+ the produced signature won't match what's actually in the
+ queue."""
+ t = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)
+ signature = self.mapper.get_recovery_target_signature(
+ transition=t, max_level=AlarmLevel.INFO,
+ )
+ self.assertIsNotNone(signature)
+ # ERROR would naturally fire CRITICAL but is clamped down to
+ # the provider's INFO ceiling. Recovery target must apply the
+ # same clamp so the signatures match.
+ self.assertEqual(signature.alarm_level, AlarmLevel.INFO)
+
+ def test_recovery_target_signature_none_for_non_recovery(self):
+ """Forward (degrade) transitions have nothing to clear."""
+ for prev, curr in [
+ (HealthStatusType.HEALTHY, HealthStatusType.ERROR),
+ (HealthStatusType.HEALTHY, HealthStatusType.WARNING),
+ (HealthStatusType.WARNING, HealthStatusType.ERROR),
+ ]:
+ t = _transition(prev, curr)
+ self.assertIsNone(
+ self.mapper.get_recovery_target_signature(
+ transition=t, max_level=AlarmLevel.CRITICAL,
+ ),
+ f'{prev} -> {curr} is not a recovery; signature should be None',
+ )
+
+ def test_recovery_target_signature_none_for_suppressed_previous(self):
+ """A recovery from a suppressed state (UNKNOWN/DISABLED) had no
+ prior alarm queued, so there's nothing to clear."""
+ for prev in (HealthStatusType.UNKNOWN, HealthStatusType.DISABLED):
+ t = _transition(prev, HealthStatusType.HEALTHY)
+ self.assertIsNone(
+ self.mapper.get_recovery_target_signature(
+ transition=t, max_level=AlarmLevel.CRITICAL,
+ ),
+ f'recovery from suppressed {prev} should produce no signature',
+ )
+
+ def test_recovery_target_signature_matches_prior_degrade_signature(self):
+ """End-to-end contract: the signature a recovery produces equals
+ the signature ``create_alarm`` on the prior degrade transition
+ would have queued. If these ever drift, ``clear_alarms`` would
+ silently miss its target."""
+ max_level = AlarmLevel.CRITICAL
+ t_degrade = _transition(HealthStatusType.HEALTHY, HealthStatusType.ERROR)
+ degrade_alarm = self.mapper.create_alarm(t_degrade, max_level=max_level)
+ self.assertIsNotNone(degrade_alarm)
+
+ t_recover = _transition(HealthStatusType.ERROR, HealthStatusType.HEALTHY)
+ signature = self.mapper.get_recovery_target_signature(
+ transition=t_recover, max_level=max_level,
)
+ self.assertIsNotNone(signature)
+ self.assertEqual(signature, degrade_alarm.signature)
diff --git a/src/hi/apps/system/tests/test_health_status_provider_transitions.py b/src/hi/apps/system/tests/test_health_status_provider_transitions.py
index d0273e99..f1f3c904 100644
--- a/src/hi/apps/system/tests/test_health_status_provider_transitions.py
+++ b/src/hi/apps/system/tests/test_health_status_provider_transitions.py
@@ -92,3 +92,128 @@ class HealthStatusProviderTransitionDispatchTest(SimpleTestCase):
# Status was updated despite the alarm exception.
self.assertEqual(provider.health_status.status, HealthStatusType.ERROR)
+
+
+class HealthStatusProviderRecoveryDispatchTest(SimpleTestCase):
+ """Recovery transitions clear the prior bad-state alert via
+ ``AlertManager.clear_alarms`` instead of producing a second
+ "recovered" alarm. End result: the operator returns to a clean
+ dashboard when the system has recovered while they were away.
+ """
+
+ def test_degrade_then_recover_leaves_no_alerts(self):
+ """Round-trip: HEALTHY -> ERROR -> HEALTHY. After the recovery
+ dispatch fires, the only effect on AlertManager is one
+ ``upsert_alarm`` (for the degrade) followed by one
+ ``clear_alarms`` (for the recovery) -- no second alert is
+ added."""
+ provider = _OptedInProvider()
+ provider.update_health_status(HealthStatusType.HEALTHY, 'init')
+
+ with patch('hi.apps.alert.alert_manager.AlertManager'
+ ) as mock_alert_manager_cls:
+ mock_alert_manager = mock_alert_manager_cls.return_value
+ provider.update_health_status(HealthStatusType.ERROR, 'broken')
+ mock_alert_manager.upsert_alarm.assert_called_once()
+ mock_alert_manager.clear_alarms.assert_not_called()
+
+ mock_alert_manager.reset_mock()
+ mock_alert_manager_cls.reset_mock()
+ provider.update_health_status(HealthStatusType.HEALTHY, 'recovered')
+
+ # Recovery path takes clear_alarms, NOT upsert_alarm.
+ mock_alert_manager.upsert_alarm.assert_not_called()
+ mock_alert_manager.clear_alarms.assert_called_once()
+
+ def test_recovery_from_error_clears_critical_signature(self):
+ """Recovery from ERROR clears the CRITICAL-level error alarm
+ (matching the level the original degrade alarm was queued at)."""
+ provider = _OptedInProvider()
+ provider.update_health_status(HealthStatusType.ERROR, 'broken')
+
+ with patch('hi.apps.alert.alert_manager.AlertManager'
+ ) as mock_alert_manager_cls:
+ mock_alert_manager = mock_alert_manager_cls.return_value
+ provider.update_health_status(HealthStatusType.HEALTHY, 'recovered')
+
+ mock_alert_manager.clear_alarms.assert_called_once()
+ kwargs = mock_alert_manager.clear_alarms.call_args.kwargs
+ self.assertEqual(kwargs['signature'].alarm_level, AlarmLevel.CRITICAL)
+
+ def test_recovery_from_warning_clears_warning_signature(self):
+ """Recovery from WARNING clears the WARNING-level alarm, not
+ the CRITICAL-level one. Distinct levels would queue distinct
+ signatures, so ``clear_alarms`` must target the right one."""
+ provider = _OptedInProvider()
+ provider.update_health_status(HealthStatusType.WARNING, 'flaky')
+
+ with patch('hi.apps.alert.alert_manager.AlertManager'
+ ) as mock_alert_manager_cls:
+ mock_alert_manager = mock_alert_manager_cls.return_value
+ provider.update_health_status(HealthStatusType.HEALTHY, 'recovered')
+
+ mock_alert_manager.clear_alarms.assert_called_once()
+ kwargs = mock_alert_manager.clear_alarms.call_args.kwargs
+ self.assertEqual(kwargs['signature'].alarm_level, AlarmLevel.WARNING)
+
+ def test_recovery_from_suppressed_state_does_not_call_clear_alarms(self):
+ """Recoveries from UNKNOWN or DISABLED had no prior alarm
+ queued, so the dispatch path must be a no-op."""
+ for prev in (HealthStatusType.UNKNOWN, HealthStatusType.DISABLED):
+ provider = _OptedInProvider()
+ # Seed the prior status WITHOUT going through update_health_status
+ # so we don't dispatch the seed transition.
+ provider._ensure_health_status_provider_setup()
+ with provider._health_lock:
+ provider._health_status.status = prev
+
+ with patch('hi.apps.alert.alert_manager.AlertManager'
+ ) as mock_alert_manager_cls:
+ mock_alert_manager = mock_alert_manager_cls.return_value
+ provider.update_health_status(
+ HealthStatusType.HEALTHY, 'recovered',
+ )
+ self.assertFalse(
+ mock_alert_manager.clear_alarms.called,
+ f'recovery from {prev} should not clear anything',
+ )
+ self.assertFalse(
+ mock_alert_manager.upsert_alarm.called,
+ f'recovery from {prev} should not upsert anything',
+ )
+
+ def test_degrade_to_degrade_transition_takes_upsert_path(self):
+ """``is_recovery`` requires ``current_status == HEALTHY``, so
+ any non-HEALTHY destination -- including degrade-to-degrade
+ moves like WARNING->ERROR or partial recovery ERROR->WARNING --
+ takes the upsert path and never the clear path. Operator
+ impact is intentional and accepted: the prior-level alert may
+ coexist with the new-level alert until natural expiry; the
+ operator drills into health-status detail to see the current
+ truth."""
+ for prev, current in [
+ (HealthStatusType.WARNING, HealthStatusType.ERROR),
+ (HealthStatusType.ERROR, HealthStatusType.WARNING),
+ ]:
+ with self.subTest(prev=prev, current=current):
+ provider = _OptedInProvider()
+ provider.update_health_status(prev, 'init-degraded')
+
+ with patch('hi.apps.alert.alert_manager.AlertManager'
+ ) as mock_alert_manager_cls:
+ mock_alert_manager = mock_alert_manager_cls.return_value
+ provider.update_health_status(current, 'still-degraded')
+
+ mock_alert_manager.upsert_alarm.assert_called_once()
+ mock_alert_manager.clear_alarms.assert_not_called()
+
+ def test_opted_out_provider_skips_clear_alarms_too(self):
+ """A provider with no alarm ceiling never queued an alarm to
+ begin with, so the recovery path must also short-circuit."""
+ provider = _OptedOutProvider()
+ provider.update_health_status(HealthStatusType.ERROR, 'broken')
+
+ with patch('hi.apps.alert.alert_manager.AlertManager'
+ ) as mock_alert_manager:
+ provider.update_health_status(HealthStatusType.HEALTHY, 'recovered')
+ mock_alert_manager.assert_not_called()
diff --git a/src/hi/integrations/connector/monitors.py b/src/hi/integrations/connector/monitors.py
index 99ac41b3..d76927ca 100644
--- a/src/hi/integrations/connector/monitors.py
+++ b/src/hi/integrations/connector/monitors.py
@@ -39,7 +39,7 @@ class IntegrationSyncCheckMonitor( PeriodicMonitor ):
MONITOR_ID = 'hi.integrations.sync_check_monitor'
INTERVAL_SECS = IntegrationSyncCheck.INTERVAL_SECS
-
+
def __init__( self ):
super().__init__( id = self.MONITOR_ID )
return
diff --git a/src/hi/integrations/connector/sync_check.py b/src/hi/integrations/connector/sync_check.py
index 6bb518bb..7359b6ad 100644
--- a/src/hi/integrations/connector/sync_check.py
+++ b/src/hi/integrations/connector/sync_check.py
@@ -29,6 +29,8 @@ from typing import Optional, Set
from django.core.cache import cache
+from hi.apps.alert.alarm import AlarmSignature
+from hi.apps.alert.enums import AlarmLevel, AlarmSource
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.enums import LabeledEnum
@@ -109,13 +111,14 @@ class IntegrationSyncCheck:
INTERVAL_SECS = 4 * 60 * 60
- # Alarm lifetime governs the post-acknowledgement nag window
- # (after the AlertQueue dedup-anchor refactor): after a user
- # dismisses the needs-sync alert, the suppression lasts this long
- # before another needs-sync alarm can re-surface. Twenty-four
- # hours strikes a balance between letting the operator defer
- # within their workday and reminding them the next time they
- # sit down at the console.
+ # Ceiling on the post-acknowledgement nag window: once a user
+ # dismisses the needs-sync alert, suppression lasts at most this
+ # long before another needs-sync alarm can re-surface. The
+ # expected case is shorter -- when the integration syncs back to
+ # clean, the producer dispatches ``AlertManager.clear_alarms`` and
+ # the dedup anchor drops immediately. Twenty-four hours balances
+ # letting the operator defer within their workday against
+ # reminding them the next time they sit down at the console.
NAG_INTERVAL_SECS = 24 * 60 * 60
_CACHE_TTL_SECS = INTERVAL_SECS * 2
@@ -190,15 +193,22 @@ class IntegrationSyncCheck:
a lock. The two writers (the framework monitor's probe cycle
and ``record_sync_complete`` via the synchronizer's post-sync
hook) can 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."""
+ overlaps a probe cycle. 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. Opposite-direction races have a small
+ bad window: probe reads ``prior=clean``, computes
+ needs_sync; Refresh writes in_sync and calls
+ ``_clear_needs_sync_alert``; probe then fires the (now-stale)
+ alarm. The resolution path will not re-fire (cache reads
+ in_sync), so the alert sits in the queue until
+ ``NAG_INTERVAL_SECS`` lifetime expiry -- the exact failure
+ mode the producer-side clear is meant to eliminate. The
+ window is small enough and the operator-visible impact (a
+ dismissable nuisance alert that resolves on its own within
+ 24h) light enough that we accept it rather than add a Redis
+ lock that would trade real cache-backend portability risk
+ (LocMemCache in tests) for a marginal UX win."""
if not integration_id:
return
prior = cls.get_state( integration_id )
@@ -227,6 +237,19 @@ class IntegrationSyncCheck:
f'Failed to fire needs-sync alarm for '
f'{integration_id}: {e}'
)
+ elif cls._should_clear_alarm( prior = prior, current = result ):
+ # Drop any pending needs-sync alert immediately on
+ # convergence rather than waiting out the
+ # ``NAG_INTERVAL_SECS`` post-ack suppression window.
+ # Failure here must not mask the cache write -- the next
+ # resolution event will retry.
+ try:
+ cls._clear_needs_sync_alert( integration_id = integration_id )
+ except Exception as e:
+ logger.warning(
+ f'Failed to clear needs-sync alert for '
+ f'{integration_id}: {e}'
+ )
@staticmethod
def _should_alarm( prior : Optional[ SyncCheckResult ],
@@ -236,8 +259,8 @@ class IntegrationSyncCheck:
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."""
+ needs-sync -> in-sync transitions are handled by
+ ``_should_clear_alarm``."""
if not current.needs_sync:
return False
if prior is None:
@@ -245,23 +268,48 @@ class IntegrationSyncCheck:
return not prior.needs_sync
@staticmethod
- def _fire_needs_sync_alarm( integration_id : str,
+ def _should_clear_alarm( prior : Optional[ SyncCheckResult ],
+ current : SyncCheckResult ) -> bool:
+ """Resolution gate. Fires only on the needs-sync -> in-sync
+ transition: prior reported needs-sync, AND current reports
+ in-sync. No-prior -> in-sync needs no clear (no alert was
+ queued). Sustained in-sync (in-sync -> in-sync) is a no-op,
+ as is any transition that ends in needs-sync."""
+ if current.needs_sync:
+ return False
+ if prior is None:
+ return False
+ return prior.needs_sync
+
+ @classmethod
+ def _needs_sync_alarm_signature( cls, integration_id : str ):
+ """Single source of truth for the (source, type, level) identity
+ of the needs-sync alarm, shared by the fire and clear paths so
+ the clear is guaranteed to match what was queued."""
+ return AlarmSignature(
+ alarm_source = AlarmSource.INTEGRATION,
+ alarm_type = f'integrations.needs_sync.{integration_id}',
+ alarm_level = AlarmLevel.INFO,
+ )
+
+ @classmethod
+ def _fire_needs_sync_alarm( cls,
+ 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
+ into the needs-sync state. Per-integration unique signature so
+ two integrations both reporting drift surface as two distinct
alerts. Lifetime is ``NAG_INTERVAL_SECS`` -- the post-ack
- suppression window before a still-out-of-sync integration is
- allowed to re-pop another alert."""
+ suppression ceiling if the operator dismisses and the drift
+ persists."""
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 hi.integrations.transient_models import IntegrationKey
+ signature = cls._needs_sync_alarm_signature( integration_id )
alarm_integration_key = IntegrationKey(
integration_id = 'integrations',
integration_name = f'needs_sync.{integration_id}',
@@ -281,17 +329,26 @@ class IntegrationSyncCheck:
has_event_video_clip = False,
)
alarm = Alarm(
- alarm_source = AlarmSource.INTEGRATION,
- alarm_type = f'integrations.needs_sync.{integration_id}',
- alarm_level = AlarmLevel.INFO,
+ alarm_source = signature.alarm_source,
+ alarm_type = signature.alarm_type,
+ alarm_level = signature.alarm_level,
title = result.summary_message,
sensor_response_list = [ sensor_response ],
security_level = SecurityLevel.OFF,
- alarm_lifetime_secs = IntegrationSyncCheck.NAG_INTERVAL_SECS,
+ alarm_lifetime_secs = cls.NAG_INTERVAL_SECS,
timestamp = datetimeproxy.now(),
)
AlertManager().upsert_alarm( alarm )
+ @classmethod
+ def _clear_needs_sync_alert( cls, integration_id : str ) -> None:
+ """Drop any pending needs-sync alert for this integration so
+ the operator's queue returns to clean immediately on
+ convergence."""
+ from hi.apps.alert.alert_manager import AlertManager
+ signature = cls._needs_sync_alarm_signature( integration_id )
+ AlertManager().clear_alarms( signature = signature )
+
@classmethod
def clear_state( cls, integration_id : str ) -> None:
"""Drop the cached state entirely. Used on integration removal;
diff --git a/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html b/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html
index 46b07301..7230a85f 100644
--- a/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html
+++ b/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html
@@ -22,7 +22,12 @@
style="max-height: 18px; width: auto; margin-right: 6px; flex-shrink: 0;">
{{ item.integration_data.label }}
</span>
- {% with health_status=item.integration_data.integration_gateway.get_health_status_provider.health_status %}
+ {% comment %}
+ ``get_connector`` returns None for integrations without CONNECT
+ capability. Django silently resolves the rest of the chain to
+ empty, and the indicator template no-ops on all-empty inputs.
+ {% endcomment %}
+ {% with health_status=item.integration_data.integration_gateway.get_connector.get_health_status_provider.health_status %}
{% include "integrations/connector/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>
diff --git a/src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.html b/src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.html
index 78f86a16..746aa9be 100644
--- a/src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.html
+++ b/src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.html
@@ -5,34 +5,35 @@ Composes HealthStatus, the integration's is_paused flag, and the
sync-check state into a single attention-grabbing glyph.
Context:
- health_status : HealthStatus instance (required).
+ health_status : HealthStatus instance or None (optional).
is_paused : bool -- integration's is_paused flag (required).
sync_check_result : SyncCheckResult or None (optional) -- sync-check
state for this integration.
Visual priority (worst-of):
ERROR > WARNING > paused > needs-sync
-HEALTHY-and-not-paused-and-in-sync renders nothing.
+HEALTHY-and-not-paused-and-in-sync renders nothing. Each branch reads
+its inputs independently so a missing ``health_status`` does not
+suppress paused or needs-sync indicators (Django silently resolves the
+absent attribute chain to a falsy value).
DISABLED is intentionally not handled -- disabled integrations are
excluded from the tab list upstream.
UNKNOWN is intentionally not handled -- initialization edge, transient.
{% endcomment %}
-{% if health_status %}
-{% with status=health_status.status %}
-{% if status.is_critical %}
+{% if health_status.status.is_critical %}
<span class="hi-integration-indicator hi-integration-indicator-error"
role="img"
- aria-label="{{ status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}"
- title="{{ status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}">
+ aria-label="{{ health_status.status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}"
+ title="{{ health_status.status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}">
{% icon "warning" size="md" %}
</span>
-{% elif status.is_warning %}
+{% elif health_status.status.is_warning %}
<span class="hi-integration-indicator hi-integration-indicator-warning"
role="img"
- aria-label="{{ status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}"
- title="{{ status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}">
+ aria-label="{{ health_status.status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}"
+ title="{{ health_status.status.label }}{% if health_status.last_message %}: {{ health_status.last_message }}{% endif %}">
{% icon "warning" size="sm" %}
</span>
{% elif is_paused %}
@@ -50,5 +51,3 @@ UNKNOWN is intentionally not handled -- initialization edge, transient.
{% icon "sync" size="sm" %}
</span>
{% endif %}
-{% endwith %}
-{% endif %}
diff --git a/src/hi/integrations/tests/test_sync_check.py b/src/hi/integrations/tests/test_sync_check.py
index b4722594..50513e03 100644
--- a/src/hi/integrations/tests/test_sync_check.py
+++ b/src/hi/integrations/tests/test_sync_check.py
@@ -453,7 +453,138 @@ class TransitionAlarmTests(TestCase):
)
# Per-integration unique signature so two integrations
# drifting yield two distinct alerts.
- self.assertIn(self.INTEGRATION_ID, alarm.signature)
+ self.assertIn(self.INTEGRATION_ID, alarm.signature.alarm_type)
+
+ # ---- resolution predicate ----
+
+ def test_should_clear_on_needs_sync_to_in_sync_transition(self):
+ """The resolution direction: drift was reported, current poll
+ is clean. ``_clear_needs_sync_alert`` will be called."""
+ self.assertTrue(IntegrationSyncCheck._should_clear_alarm(
+ prior=self._result(needs_sync=True),
+ current=self._result(needs_sync=False),
+ ))
+
+ def test_should_not_clear_when_no_prior(self):
+ """First-ever probe with no drift: nothing was queued, so
+ nothing to clear."""
+ self.assertFalse(IntegrationSyncCheck._should_clear_alarm(
+ prior=None,
+ current=self._result(needs_sync=False),
+ ))
+
+ def test_should_not_clear_when_drift_persists(self):
+ self.assertFalse(IntegrationSyncCheck._should_clear_alarm(
+ prior=self._result(needs_sync=True),
+ current=self._result(needs_sync=True),
+ ))
+
+ def test_should_not_clear_on_clean_to_drift_transition(self):
+ """A fresh drift detection is the FIRE direction, not the
+ clear direction."""
+ self.assertFalse(IntegrationSyncCheck._should_clear_alarm(
+ prior=self._result(needs_sync=False),
+ current=self._result(needs_sync=True),
+ ))
+
+ def test_should_not_clear_when_both_clean(self):
+ self.assertFalse(IntegrationSyncCheck._should_clear_alarm(
+ prior=self._result(needs_sync=False),
+ current=self._result(needs_sync=False),
+ ))
+
+ # ---- resolution wiring ----
+
+ def test_set_state_clears_alarm_on_drift_to_in_sync_transition(self):
+ """When the cached state shows drift and the new probe finds
+ no drift, ``set_state`` invokes ``_clear_needs_sync_alert``."""
+ # Pre-populate a needs-sync state.
+ IntegrationSyncCheck.set_state(
+ integration_id=self.INTEGRATION_ID,
+ result=self._result(needs_sync=True),
+ )
+ with patch.object(
+ IntegrationSyncCheck, '_clear_needs_sync_alert',
+ ) as mock_clear:
+ IntegrationSyncCheck.set_state(
+ integration_id=self.INTEGRATION_ID,
+ result=self._result(needs_sync=False),
+ )
+ mock_clear.assert_called_once()
+
+ def test_set_state_does_not_clear_on_sustained_in_sync(self):
+ """In-sync -> in-sync is the steady state; no alert was queued,
+ so no clear is needed."""
+ IntegrationSyncCheck.set_state(
+ integration_id=self.INTEGRATION_ID,
+ result=self._result(needs_sync=False),
+ )
+ with patch.object(
+ IntegrationSyncCheck, '_clear_needs_sync_alert',
+ ) as mock_clear:
+ IntegrationSyncCheck.set_state(
+ integration_id=self.INTEGRATION_ID,
+ result=self._result(needs_sync=False),
+ )
+ mock_clear.assert_not_called()
+
+ def test_set_state_does_not_clear_on_first_in_sync(self):
+ """First probe with no drift: nothing was queued, so the clear
+ path must not fire."""
+ with patch.object(
+ IntegrationSyncCheck, '_clear_needs_sync_alert',
+ ) as mock_clear:
+ IntegrationSyncCheck.set_state(
+ integration_id=self.INTEGRATION_ID,
+ result=self._result(needs_sync=False),
+ )
+ mock_clear.assert_not_called()
+
+ def test_clear_failure_does_not_break_set_state(self):
+ """Resolution-side alarm subsystem failure must not propagate;
+ the cache write should already have succeeded."""
+ # Pre-populate a needs-sync state so the next set_state takes
+ # the clear path.
+ IntegrationSyncCheck.set_state(
+ integration_id=self.INTEGRATION_ID,
+ result=self._result(needs_sync=True),
+ )
+ with patch.object(
+ IntegrationSyncCheck, '_clear_needs_sync_alert',
+ side_effect=RuntimeError('alert system down'),
+ ):
+ IntegrationSyncCheck.set_state(
+ integration_id=self.INTEGRATION_ID,
+ result=self._result(needs_sync=False),
+ )
+ # State is recorded despite the clear failure.
+ loaded = IntegrationSyncCheck.get_state(self.INTEGRATION_ID)
+ self.assertIsNotNone(loaded)
+ self.assertFalse(loaded.needs_sync)
+
+ # ---- signature contract ----
+
+ def test_clear_uses_same_signature_as_fire(self):
+ """End-to-end contract: the signature ``_clear_needs_sync_alert``
+ hands to ``AlertManager.clear_alarms`` MUST equal the signature
+ of the alarm ``_fire_needs_sync_alarm`` would have queued.
+ Otherwise the resolution path would silently miss its target."""
+ from hi.apps.alert.alert_manager import AlertManager
+ with patch.object(AlertManager, 'clear_alarms') as mock_clear, \
+ patch.object(AlertManager, 'upsert_alarm') as mock_upsert:
+ IntegrationSyncCheck._fire_needs_sync_alarm(
+ integration_id=self.INTEGRATION_ID,
+ result=self._result(needs_sync=True),
+ )
+ IntegrationSyncCheck._clear_needs_sync_alert(
+ integration_id=self.INTEGRATION_ID,
+ )
+
+ mock_upsert.assert_called_once()
+ mock_clear.assert_called_once()
+ queued_alarm = mock_upsert.call_args.args[0]
+ clear_signature = mock_clear.call_args.kwargs['signature']
+ self.assertEqual(queued_alarm.signature, clear_signature)
class _StubIntegrationData: