Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(alerts): stamp confirmation-based lifecycle alerts at the first matched observation

rcourtman7c256cd04c8e
diff --git a/internal/alerts/canonical_lifecycle.go b/internal/alerts/canonical_lifecycle.go
index d1ab109d60..6f94602b71 100644
--- a/internal/alerts/canonical_lifecycle.go
+++ b/internal/alerts/canonical_lifecycle.go
@@ -265,7 +265,7 @@ func canonicalAlertSeverity(level AlertLevel) alertspecs.AlertSeverity {
}
}
-func lifecyclePreviousState(spec alertspecs.ResourceAlertSpec, existing *Alert, confirmations int, observedAt time.Time) alertspecs.EvaluatorState {
+func lifecyclePreviousState(spec alertspecs.ResourceAlertSpec, existing *Alert, confirmations int, firstMatched, observedAt time.Time) alertspecs.EvaluatorState {
if existing != nil {
required := spec.ConfirmationsRequired
if confirmations > required {
@@ -282,12 +282,19 @@ func lifecyclePreviousState(spec alertspecs.ResourceAlertSpec, existing *Alert,
}
}
if confirmations > 0 {
+ // Date the reconstructed pending run at its preserved first match so
+ // activation stamps StartTime at the first failing observation, not
+ // at the final confirming poll.
+ matchedAt := firstMatched
+ if matchedAt.IsZero() {
+ matchedAt = observedAt
+ }
return alertspecs.EvaluatorState{
SpecID: spec.ID,
State: alertspecs.AlertStatePending,
Severity: spec.Severity,
ConsecutiveMatches: confirmations,
- FirstMatchedAt: observedAt,
+ FirstMatchedAt: matchedAt,
}
}
return alertspecs.EvaluatorState{
@@ -361,8 +368,12 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlert
if params.Tracking != nil {
confirmations = params.Tracking[params.TrackingKey]
}
+ firstMatched := time.Time{}
+ if confirmations > 0 {
+ firstMatched = m.lifecycleFirstMatched[params.TrackingKey]
+ }
- result, err := alertspecs.Evaluate(params.Spec, lifecyclePreviousState(params.Spec, existing, confirmations, params.Evidence.ObservedAt), params.Evidence)
+ result, err := alertspecs.Evaluate(params.Spec, lifecyclePreviousState(params.Spec, existing, confirmations, firstMatched, params.Evidence.ObservedAt), params.Evidence)
if err != nil {
log.Warn().
Err(err).
@@ -379,8 +390,12 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlert
if params.Tracking != nil {
if result.State.ConsecutiveMatches > 0 {
params.Tracking[params.TrackingKey] = result.State.ConsecutiveMatches
+ if _, tracked := m.lifecycleFirstMatched[params.TrackingKey]; !tracked && !result.State.FirstMatchedAt.IsZero() {
+ m.lifecycleFirstMatched[params.TrackingKey] = result.State.FirstMatchedAt
+ }
} else {
delete(params.Tracking, params.TrackingKey)
+ delete(m.lifecycleFirstMatched, params.TrackingKey)
}
}
diff --git a/internal/alerts/lifecycle_first_matched_test.go b/internal/alerts/lifecycle_first_matched_test.go
new file mode 100644
index 0000000000..14968b96aa
--- /dev/null
+++ b/internal/alerts/lifecycle_first_matched_test.go
@@ -0,0 +1,74 @@
+package alerts
+
+import (
+ "testing"
+ "time"
+
+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// Regression: the confirmation maps hold only counts, so the reconstructed
+// pending state dated the run at the current observation and a
+// confirmation-based lifecycle alert stamped StartTime at the final
+// confirming poll — understating outage start by the whole confirmation
+// window. lifecycleFirstMatched preserves the first matched observation
+// (mirroring unifiedIncidentFirstSeen) so activation keeps the true start.
+func TestLifecycleAlertStartTimeIsFirstMatchedObservation(t *testing.T) {
+ manager := NewManagerWithDataDir(t.TempDir(), WithoutPersistedAlertRestore())
+ t.Cleanup(manager.Stop)
+
+ manager.mu.Lock()
+ manager.config.Enabled = true
+ manager.mu.Unlock()
+
+ epoch := time.Date(2026, 8, 26, 12, 0, 0, 0, time.UTC)
+ observe := func(observed string, at time.Time) {
+ spec, err := buildCanonicalDiscreteStateSpec(
+ "node-9", "node-9", unifiedresources.ResourceTypeAgent,
+ AlertLevelCritical, 3, false, "connectivity", []string{"offline"},
+ )
+ if err != nil {
+ t.Fatalf("build spec: %v", err)
+ }
+ if _, ok := manager.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{
+ Spec: spec,
+ Evidence: alertspecs.AlertEvidence{
+ ObservedAt: at,
+ DiscreteState: &alertspecs.DiscreteStateEvidence{StateKey: "connectivity", Observed: observed},
+ },
+ Tracking: manager.offlineConfirmations,
+ TrackingKey: "conn:node-9",
+ AlertID: canonicalDiscreteStateStateID("node-9", "connectivity"),
+ AlertType: "connectivity",
+ ResourceID: "node-9",
+ ResourceName: "node-9",
+ Message: "node offline",
+ }); !ok {
+ t.Fatal("evaluation rejected")
+ }
+ }
+
+ observe("offline", epoch)
+ observe("offline", epoch.Add(30*time.Second))
+ observe("offline", epoch.Add(60*time.Second))
+
+ manager.mu.Lock()
+ alert, exists := manager.getActiveAlertNoLock(canonicalDiscreteStateStateID("node-9", "connectivity"))
+ manager.mu.Unlock()
+ if !exists || alert == nil {
+ t.Fatal("expected alert to fire after three confirmations")
+ }
+ if !alert.StartTime.Equal(epoch) {
+ t.Fatalf("StartTime = %v, want first offline observation %v", alert.StartTime, epoch)
+ }
+
+ // Recovery clears the preserved first-match so a later run re-dates.
+ observe("online", epoch.Add(90*time.Second))
+ manager.mu.Lock()
+ _, tracked := manager.lifecycleFirstMatched["conn:node-9"]
+ manager.mu.Unlock()
+ if tracked {
+ t.Fatal("first-matched entry should clear with the confirmation run")
+ }
+}
diff --git a/internal/alerts/manager.go b/internal/alerts/manager.go
index 2f0c8ab799..21c5558a2d 100644
--- a/internal/alerts/manager.go
+++ b/internal/alerts/manager.go
@@ -62,10 +62,17 @@ type Manager struct {
backupIntentResolver BackupIntentContextResolver
resourceIntentResolver ResourceIntentIdentityResolver
// Offline confirmation tracking
- nodeOfflineCount map[string]int // Track consecutive offline counts for nodes (legacy)
- connectionDegradedCount map[string]int // Track consecutive degraded counts for platform connections (pve/pbs/pmg/vmware/truenas)
- offlineConfirmations map[string]int // Track consecutive offline counts for all resources
- offlineRecoveryConfirmations map[string]int // Track consecutive healthy confirmations before clearing poll-driven offline alerts
+ nodeOfflineCount map[string]int // Track consecutive offline counts for nodes (legacy)
+ connectionDegradedCount map[string]int // Track consecutive degraded counts for platform connections (pve/pbs/pmg/vmware/truenas)
+ offlineConfirmations map[string]int // Track consecutive offline counts for all resources
+ offlineRecoveryConfirmations map[string]int // Track consecutive healthy confirmations before clearing poll-driven offline alerts
+ // lifecycleFirstMatched preserves when a canonical-lifecycle confirmation
+ // run first matched, keyed by tracking key. The confirmation maps hold
+ // only counts, so without this the reconstructed pending state dated the
+ // run at the current observation and activation stamped StartTime at the
+ // final confirming poll — understating outage start by the whole
+ // confirmation window. Mirrors unifiedIncidentFirstSeen.
+ lifecycleFirstMatched map[string]time.Time
unifiedIncidentConfirmations map[string]int // Track consecutive provider-incident observations before activation
unifiedIncidentFirstSeen map[string]time.Time // Preserve the first confirmed observation as lifecycle start
unifiedIncidentRecoveries map[string]int // Track consecutive healthy observations before provider-incident recovery
@@ -181,6 +188,7 @@ func NewManagerWithDataDir(dataDir string, options ...ManagerOption) *Manager {
connectionDegradedCount: make(map[string]int),
offlineConfirmations: make(map[string]int),
offlineRecoveryConfirmations: make(map[string]int),
+ lifecycleFirstMatched: make(map[string]time.Time),
unifiedIncidentConfirmations: make(map[string]int),
unifiedIncidentFirstSeen: make(map[string]time.Time),
unifiedIncidentRecoveries: make(map[string]int),
diff --git a/internal/alerts/tracking_cleanup.go b/internal/alerts/tracking_cleanup.go
index ec77ca3bc6..69fa3fea24 100644
--- a/internal/alerts/tracking_cleanup.go
+++ b/internal/alerts/tracking_cleanup.go
@@ -92,6 +92,25 @@ func (m *Manager) cleanupStaleMaps() {
}
}
+ // lifecycleFirstMatched entries share tracking keys with the
+ // confirmation-count maps and follow the same retention rule: keep only
+ // while a related active alert exists. A leaked entry would otherwise
+ // backdate an unrelated future confirmation run for the same key.
+ for trackingKey := range m.lifecycleFirstMatched {
+ hasRelatedAlert := false
+ for storageKey, alert := range m.activeAlerts {
+ alertID := effectiveAlertID(alert, storageKey)
+ if strings.Contains(alertID, trackingKey) || strings.Contains(trackingKey, alert.ResourceID) {
+ hasRelatedAlert = true
+ break
+ }
+ }
+ if !hasRelatedAlert {
+ delete(m.lifecycleFirstMatched, trackingKey)
+ cleaned++
+ }
+ }
+
for nodeID := range m.nodeOfflineCount {
hasRelatedAlert := false
for storageKey, alert := range m.activeAlerts {