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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
feat(alerts): cut the stateful family over to the reducer core
rcourtman5e588c0be1a5
diff --git a/internal/alerts/canonical_lifecycle.go b/internal/alerts/canonical_lifecycle.goindex 26bd5ea622..1c1eb5942b 100644--- a/internal/alerts/canonical_lifecycle.go+++ b/internal/alerts/canonical_lifecycle.go@@ -654,13 +654,7 @@ func (m *Manager) evaluateCanonicalStatefulAlert(params canonicalStatefulAlertPamigratedAlertIdentity = true}- var pendingSince time.Time- if params.PendingTracking != nil {- pendingSince = params.PendingTracking[params.PendingKey]- }-- result, err := alertspecs.Evaluate(params.Spec, statefulPreviousState(params.Spec, existing, pendingSince), params.Evidence)- if err != nil {+ if err := params.Spec.Validate(); err != nil {log.Warn().Err(err).Str("alertID", storageKey).@@ -669,25 +663,105 @@ func (m *Manager) evaluateCanonicalStatefulAlert(params canonicalStatefulAlertPaMsg("Skipping invalid canonical stateful evaluation")return alertspecs.EvaluationResult{}, false}+ if err := alertspecs.ValidateEvidence(params.Spec.Kind, params.Evidence); err != nil {+ log.Warn().+ Err(err).+ Str("alertID", storageKey).+ Str("resourceID", params.ResourceID).+ Str("specID", params.Spec.ID).+ Msg("Skipping invalid canonical stateful evidence")+ return alertspecs.EvaluationResult{}, false+ }++ matched, matchSeverity, matchReason := alertspecs.Match(params.Spec, params.Evidence)++ // An existing alert the core does not know about means it was firing:+ // adopt it, as everywhere else.+ if existing != nil {+ if _, known := m.core.Incident(params.Spec.ResourceID, params.Spec.ID); !known {+ ackAt := time.Time{}+ if existing.AckTime != nil {+ ackAt = *existing.AckTime+ }+ m.core.SeedFiringIncident(params.Spec.ResourceID, params.Spec.ID, shadowSeverityForLevel(existing.Level), existing.StartTime, existing.Acknowledged, existing.AckUser, ackAt)+ }+ }++ severity := reducer.SeverityWarning+ if matchSeverity == alertspecs.AlertSeverityCritical {+ severity = reducer.SeverityCritical+ }+ events := m.core.ApplyDiscrete(reducer.DiscreteSignal{+ ResourceID: params.Spec.ResourceID,+ Key: params.Spec.ID,+ Matched: matched,+ Severity: severity,+ ObservedAt: params.Evidence.ObservedAt,+ }, reducer.DiscreteRule{+ Confirmations: specConfirmationsRequired(params.Spec),+ Disabled: params.Spec.Disabled,+ })+ primary := reducer.EventType("")+ if len(events) > 0 {+ primary = events[0].Type+ }+ incident, hasIncident := m.core.Incident(params.Spec.ResourceID, params.Spec.ID)+ // Legacy pending-since maps stay as read-only mirrors of the core+ // during the transition.if params.PendingTracking != nil {- switch result.State.State {- case alertspecs.AlertStatePending:- if pendingSince.IsZero() {- params.PendingTracking[params.PendingKey] = params.Evidence.ObservedAt+ if hasIncident && incident.State == reducer.StatePending {+ if _, tracked := params.PendingTracking[params.PendingKey]; !tracked {+ params.PendingTracking[params.PendingKey] = incident.PendingSince}- default:+ } else {delete(params.PendingTracking, params.PendingKey)}}- switch result.State.State {- case alertspecs.AlertStatePending:+ result := alertspecs.EvaluationResult{}+ result.State.SpecID = params.Spec.ID+ result.State.LastObservedAt = params.Evidence.ObservedAt+ result.State.Reason = matchReason+ transition := func(kind alertspecs.EvaluationTransitionKind, from, to alertspecs.AlertState) *alertspecs.EvaluationTransition {+ return &alertspecs.EvaluationTransition{+ Kind: kind,+ SpecID: params.Spec.ID,+ ResourceID: params.Spec.ResourceID,+ From: from,+ To: to,+ At: params.Evidence.ObservedAt,+ Severity: matchSeverity,+ Reason: matchReason,+ Evidence: params.Evidence,+ }+ }++ switch {+ case hasIncident && incident.State == reducer.StatePending:+ result.State.State = alertspecs.AlertStatePending+ result.State.Severity = matchSeverity+ result.State.ConsecutiveMatches = incident.Confirmations+ result.State.FirstMatchedAt = incident.PendingSince+ if primary == reducer.EventPending {+ result.Transition = transition(alertspecs.EvaluationTransitionPending, alertspecs.AlertStateClear, alertspecs.AlertStatePending)+ }return result, true- case alertspecs.AlertStateFiring:- level, ok := alertLevelFromCanonicalSeverity(result.State.Severity)- if !ok {- level = AlertLevelWarning+ case hasIncident && incident.State == reducer.StateFiring:+ level := AlertLevelWarning+ if incident.Severity == reducer.SeverityCritical {+ level = AlertLevelCritical+ }+ result.State.State = alertspecs.AlertStateFiring+ result.State.Severity = matchSeverity+ result.State.ConsecutiveMatches = incident.Confirmations+ result.State.FirstMatchedAt = incident.StartedAt+ result.State.ActiveSince = incident.StartedAt+ switch {+ case existing == nil:+ result.Transition = transition(alertspecs.EvaluationTransitionActivated, alertspecs.AlertStatePending, alertspecs.AlertStateFiring)+ case primary == reducer.EventSeverityChanged:+ result.Transition = transition(alertspecs.EvaluationTransitionSeverityChanged, alertspecs.AlertStateFiring, alertspecs.AlertStateFiring)}message := params.Messagevalue := params.Value@@ -695,6 +769,9 @@ func (m *Manager) evaluateCanonicalStatefulAlert(params canonicalStatefulAlertPaif params.MessageBuilder != nil {message, value, threshold = params.MessageBuilder(result)}+ // The stateful family stamps occurrences at the observation (or the+ // caller's override, e.g. a backup timestamp), not the pending run+ // start — preserved from the pre-cutover engine.startTime := params.Evidence.ObservedAtif !params.StartTimeOverride.IsZero() {startTime = params.StartTimeOverride@@ -729,17 +806,16 @@ func (m *Manager) evaluateCanonicalStatefulAlert(params canonicalStatefulAlertPa}if existing == nil {- reactivatedStart, reactivatedAt, reactivated, hadResolvedOccurrence := m.consumeRecentlyResolvedForRefireWithPrimaryLock(storageKey, time.Now())- if reactivated {- if !reactivatedStart.IsZero() {- alert.StartTime = reactivatedStart+ _, _, _, hadResolvedOccurrence := m.consumeRecentlyResolvedForRefireWithPrimaryLock(storageKey, time.Now())+ if primary == reducer.EventRefired {+ if !incident.StartedAt.IsZero() {+ alert.StartTime = incident.StartedAt}if params.AddToHistory {m.historyManager.UpdateAlertLastSeenForAlert(alert, alert.LastSeen)}log.Debug().Str("alertID", storageKey).- Time("resolvedAt", reactivatedAt).Msg("Stateful alert re-fired within cooldown, reactivated without new history entry")if params.RateLimit && !m.checkRateLimit(trackingKey) {return result, true@@ -748,6 +824,7 @@ func (m *Manager) evaluateCanonicalStatefulAlert(params canonicalStatefulAlertPareturn result, true}+ m.recordAlertEvent(eventlog.TypeFired, alert, storageKey, matchReason, message, nil)if params.AddToHistory {if hadResolvedOccurrence {m.historyManager.AddAlertTransition(*alert)@@ -767,7 +844,7 @@ func (m *Manager) evaluateCanonicalStatefulAlert(params canonicalStatefulAlertPareturn result, true}- if result.Transition != nil && result.Transition.Kind == alertspecs.EvaluationTransitionSeverityChanged && params.NotifyOnSeverityChange {+ if primary == reducer.EventSeverityChanged && params.NotifyOnSeverityChange {if params.AddToHistoryOnSeverityChange {m.historyManager.AddAlertTransition(*alert)}@@ -784,9 +861,11 @@ func (m *Manager) evaluateCanonicalStatefulAlert(params canonicalStatefulAlertPam.setActiveAlertNoLock(storageKey, alert)return result, truedefault:+ result.State.State = alertspecs.AlertStateClearif existing == nil {return result, true}+ result.Transition = transition(alertspecs.EvaluationTransitionRecovered, alertspecs.AlertStateFiring, alertspecs.AlertStateClear)m.removeActiveAlertNoLock(storageKey)recoveryEvidence, hasRecoveryEvidence := canonicalAlertEvidenceEnvelope(diff --git a/internal/alerts/canonical_stateful_test.go b/internal/alerts/canonical_stateful_test.goindex 344d63e58d..798615eae0 100644--- a/internal/alerts/canonical_stateful_test.go+++ b/internal/alerts/canonical_stateful_test.go@@ -107,6 +107,10 @@ func TestStatefulAlertReFireCooldown(t *testing.T) {resolved.ResolvedTime = time.Now().Add(-10 * time.Minute)}m.resolvedMutex.Unlock()+ // Age the core's resolved ledger in step with the manager's records.+ m.mu.Lock()+ m.core.ShiftResolved(-10 * time.Minute)+ m.mu.Unlock()m.syncCanonicalHealthAssessmentAlert(params)diff --git a/internal/alerts/core.go b/internal/alerts/core.goindex 110a66bad6..7d05848e1e 100644--- a/internal/alerts/core.go+++ b/internal/alerts/core.go@@ -96,6 +96,6 @@ func (m *Manager) mirrorForgetAlertNoLock(alert *Alert) {return}for _, state := range m.mirrorStatesNoLock() {- state.Forget(alert.ResourceID, alert.CanonicalSpecID)+ state.Forget(alert.ResourceID, alert.CanonicalSpecID, m.policyNow())}}diff --git a/internal/alerts/reducer/reducer.go b/internal/alerts/reducer/reducer.goindex 7a16953496..569c0c284d 100644--- a/internal/alerts/reducer/reducer.go+++ b/internal/alerts/reducer/reducer.go@@ -487,10 +487,20 @@ func (s *State) SeedFiringIncident(resourceID, subKey string, severity Severity,}// Forget drops any incident for the key without emitting events — the-// shadow feed's mirror for manual clears and its divergence resync. Ack-// and resolved records are left to their own retention.-func (s *State) Forget(resourceID, subKey string) {- delete(s.incidents, incidentKey(resourceID, subKey))+// mirror for manual clears and the shadow feed's divergence resync. A+// firing incident is recorded as a resolved occurrence (the manager's+// manual clear adds to recently-resolved the same way), so a quick+// re-fire reactivates it, and its acknowledgement enters the retention+// window.+func (s *State) Forget(resourceID, subKey string, at time.Time) {+ key := incidentKey(resourceID, subKey)+ if incident, ok := s.incidents[key]; ok {+ if incident.State == StateFiring {+ s.recordResolved(key, incident, at)+ s.markAckInactive(key, at)+ }+ delete(s.incidents, key)+ }}// ShiftResolved moves every resolved-occurrence timestamp by deltadiff --git a/internal/alerts/shadow.go b/internal/alerts/shadow.goindex e76152c84b..3d15cf2637 100644--- a/internal/alerts/shadow.go+++ b/internal/alerts/shadow.go@@ -242,7 +242,7 @@ func (m *Manager) shadowCompareNoLock(resourceID, specKey, managerAlertID stringackAt,)} else {- feed.state.Forget(resourceID, specKey)+ feed.state.Forget(resourceID, specKey, observedAt)}key := resourceID + "\x00" + specKey