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
Suppress recovery notifications when the firing never left the queue
rcourtman76dc690840f8
diff --git a/internal/monitoring/monitor_alert_handling_test.go b/internal/monitoring/monitor_alert_handling_test.goindex 9f0cccb027..de3560c7c3 100644--- a/internal/monitoring/monitor_alert_handling_test.go+++ b/internal/monitoring/monitor_alert_handling_test.go@@ -372,6 +372,87 @@ func TestMonitor_HandleAlertResolved_SendsRecoveryForGuestPoweredOffState(t *tes}}+func TestMonitor_HandleAlertResolved_SuppressesRecoveryWhenFiringNeverDelivered(t *testing.T) {+ // Regression test for #1553: an alert that resolves while its firing+ // notification is still waiting in the grouping window must not produce a+ // recovery-only notification.+ t.Setenv("PULSE_DATA_DIR", t.TempDir())+ received := make(chan []byte, 2)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ defer r.Body.Close()+ body, _ := io.ReadAll(r.Body)+ select {+ case received <- body:+ default:+ }+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)++ notifMgr := notifications.NewNotificationManagerWithDataDir("http://pulse.example", t.TempDir())+ if err := notifMgr.UpdateAllowedPrivateCIDRs("127.0.0.1/32,::1/128"); err != nil {+ t.Fatalf("UpdateAllowedPrivateCIDRs: %v", err)+ }+ notifMgr.AddWebhook(notifications.WebhookConfig{+ ID: "test-webhook",+ Name: "test-webhook",+ URL: srv.URL,+ Enabled: true,+ Service: "generic",+ })+ notifMgr.SetNotifyOnResolve(true)+ // Large grouping window keeps the firing notification undelivered until+ // the alert resolves.+ notifMgr.SetGroupingWindow(120)++ alertMgr := alerts.NewManager()+ cfg := alertMgr.GetConfig()+ cfg.Enabled = true+ cfg.ActivationState = alerts.ActivationActive+ cfg.Schedule.QuietHours.Enabled = false+ alertMgr.UpdateConfig(cfg)++ m := &Monitor{+ alertManager: alertMgr,+ notificationMgr: notifMgr,+ }++ vm := models.VM{+ ID: "vm-transient-spike",+ Name: "transient-spike-vm",+ Node: "node-1",+ Instance: "inst-1",+ Status: "stopped",+ }++ // Fire the alert without wiring the async fired-callback, then hand the+ // firing notification to the manager synchronously so it is deterministic+ // that it sits in the grouping window when the alert resolves.+ alertMgr.CheckGuest(vm, vm.Instance)+ alertMgr.CheckGuest(vm, vm.Instance)++ activeAlerts := alertMgr.GetActiveAlerts()+ if len(activeAlerts) != 1 {+ t.Fatalf("expected one active powered-off alert, got %#v", activeAlerts)+ }+ firing := activeAlerts[0]+ notifMgr.SendAlert(&firing)++ vm.Status = "running"+ alertMgr.CheckGuest(vm, vm.Instance)+ if resolved := alertMgr.GetResolvedAlert(firing.ID); resolved == nil {+ t.Fatalf("expected alert %q to be resolved", firing.ID)+ }++ m.handleAlertResolved(firing.ID)++ select {+ case body := <-received:+ t.Fatalf("expected no notification for a firing that never left the grouping window, got %s", string(body))+ case <-time.After(1500 * time.Millisecond):+ }+}+func TestMonitor_HandleAlertEscalated_QuietHoursSuppressesNotification(t *testing.T) {t.Setenv("PULSE_DATA_DIR", t.TempDir())diff --git a/internal/monitoring/monitor_alerts.go b/internal/monitoring/monitor_alerts.goindex b58adfb1a4..4f1ec556a2 100644--- a/internal/monitoring/monitor_alerts.go+++ b/internal/monitoring/monitor_alerts.go@@ -149,13 +149,21 @@ func (m *Monitor) handleAlertResolved(alertID string) {// If the original alert would have been suppressed during quiet hours,// the recovery notification is also suppressed to avoid noise.if m.notificationMgr != nil {- m.notificationMgr.CancelAlert(alertID)+ firingNeverDelivered := m.notificationMgr.CancelAlert(alertID)if m.notificationMgr.GetNotifyOnResolve() {if resolvedAlert == nil {resolvedAlert = m.alertManager.GetResolvedAlert(alertID)}if resolvedAlert != nil && resolvedAlert.Alert != nil {- if m.alertManager.ShouldSuppressResolvedNotification(resolvedAlert.Alert) {+ if firingNeverDelivered {+ // The firing notification was still in the grouping window+ // or waiting in the queue (e.g. quiet-hours replay) when the+ // alert resolved, and CancelAlert just cancelled it. A+ // recovery for an alert the user never saw fire is noise.+ log.Info().+ Str("alertID", alertID).+ Msg("Resolved notification suppressed because the firing notification was cancelled before delivery")+ } else if m.alertManager.ShouldSuppressResolvedNotification(resolvedAlert.Alert) {log.Info().Str("alertID", alertID).Msg("Resolved notification suppressed during quiet hours")diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.goindex b402e1b914..6da4bed668 100644--- a/internal/notifications/notifications.go+++ b/internal/notifications/notifications.go@@ -1154,10 +1154,15 @@ func (n *NotificationManager) SendResolvedAlert(resolved *alerts.ResolvedAlert)}}-// CancelAlert removes pending notifications for a resolved alert-func (n *NotificationManager) CancelAlert(alertID string) {+// CancelAlert removes pending notifications for a resolved alert. It reports+// whether the alert's firing notification was cancelled before any delivery:+// true means the user never received the firing notification (it was still in+// the grouping window or waiting in the queue), so sending a recovery+// notification would reference an alert that was never announced.+func (n *NotificationManager) CancelAlert(alertID string) bool {n.mu.Lock()queue := n.queue+ _, firingDelivered := n.lastNotified[alertID]removed := 0if len(n.pendingAlerts) > 0 {@@ -1192,16 +1197,24 @@ func (n *NotificationManager) CancelAlert(alertID string) {n.mu.Unlock()// Cancel any queued notifications containing this alert+ cancelledPending := 0if queue != nil {- if err := queue.CancelByAlertIdentifiers([]string{alertID}); err != nil {+ var err error+ cancelledPending, err = queue.CancelByAlertIdentifiers([]string{alertID})+ if err != nil {log.Error().Err(err).Str("alertID", alertID).Msg("failed to cancel queued notifications")}}+ firingNeverDelivered := !firingDelivered && (removed > 0 || cancelledPending > 0)+log.Debug().Str("alertID", alertID).Int("remaining", len(n.pendingAlerts)).+ Bool("firingNeverDelivered", firingNeverDelivered).Msg("removed resolved alert from pending notifications and cooldown map")++ return firingNeverDelivered}// sendGroupedAlerts sends all pending alerts as a groupdiff --git a/internal/notifications/notifications_test.go b/internal/notifications/notifications_test.goindex 37ba239d51..7cd6bb6d2f 100644--- a/internal/notifications/notifications_test.go+++ b/internal/notifications/notifications_test.go@@ -579,7 +579,9 @@ func TestCancelAlertClearsCooldownAndQueueWithoutPendingGroup(t *testing.T) {queue: queue,}- nm.CancelAlert(alert.ID)+ if nm.CancelAlert(alert.ID) {+ t.Fatal("expected CancelAlert to report the firing as delivered because a delivery record exists")+ }nm.mu.RLock()_, hasCooldownRecord := nm.lastNotified[alert.ID]@@ -597,6 +599,68 @@ func TestCancelAlertClearsCooldownAndQueueWithoutPendingGroup(t *testing.T) {}}+func TestCancelAlertReportsUndeliveredQueuedFiring(t *testing.T) {+ queue, err := NewNotificationQueue(t.TempDir())+ if err != nil {+ t.Fatalf("failed to create queue: %v", err)+ }+ defer func() { _ = queue.Stop() }()++ alert := &alerts.Alert{+ ID: "alert-undelivered-firing",+ Type: "cpu",+ Level: alerts.AlertLevelWarning,+ StartTime: time.Now().Add(-time.Minute),+ }+ // Far-future NextRetryAt keeps the background processor from delivering+ // the firing notification before CancelAlert runs.+ futureRetry := time.Now().Add(time.Hour)+ if err := queue.Enqueue(&QueuedNotification{+ Type: "webhook",+ Status: QueueStatusPending,+ Alerts: []*alerts.Alert{alert},+ Config: json.RawMessage(`{"enabled":true,"url":"https://hooks.example.test/pulse"}`),+ MaxAttempts: 3,+ NextRetryAt: &futureRetry,+ }); err != nil {+ t.Fatalf("failed to enqueue notification: %v", err)+ }++ nm := &NotificationManager{+ pendingAlerts: []*alerts.Alert{},+ queue: queue,+ }++ if !nm.CancelAlert(alert.ID) {+ t.Fatal("expected CancelAlert to report the queued firing notification was never delivered")+ }++ var status string+ if err := queue.db.QueryRow(`SELECT status FROM notification_queue WHERE type = ?`, "webhook").Scan(&status); err != nil {+ t.Fatalf("failed to read queued notification status: %v", err)+ }+ if status != string(QueueStatusCancelled) {+ t.Fatalf("expected queued firing notification to be cancelled, got %q", status)+ }+}++func TestCancelAlertNothingPendingReportsDelivered(t *testing.T) {+ queue, err := NewNotificationQueue(t.TempDir())+ if err != nil {+ t.Fatalf("failed to create queue: %v", err)+ }+ defer func() { _ = queue.Stop() }()++ nm := &NotificationManager{+ pendingAlerts: []*alerts.Alert{},+ queue: queue,+ }++ if nm.CancelAlert("alert-with-nothing-in-flight") {+ t.Fatal("expected CancelAlert to leave the recovery decision to the notification policy when nothing was cancelled")+ }+}+func TestCancelAlertRemovesPending(t *testing.T) {t.Setenv("PULSE_DATA_DIR", t.TempDir())nm := NewNotificationManager("")@@ -618,7 +682,9 @@ func TestCancelAlertRemovesPending(t *testing.T) {nm.SendAlert(alertA)nm.SendAlert(alertB)- nm.CancelAlert(alertA.ID)+ if !nm.CancelAlert(alertA.ID) {+ t.Fatal("expected CancelAlert to report the firing was never delivered while still in the grouping window")+ }nm.mu.RLock()remaining := make([]string, 0, len(nm.pendingAlerts))diff --git a/internal/notifications/queue.go b/internal/notifications/queue.goindex f8e76a60f7..4ecd74d622 100644--- a/internal/notifications/queue.go+++ b/internal/notifications/queue.go@@ -1033,24 +1033,28 @@ func calculateBackoff(attempt int) time.Duration {}// CancelByAlertIdentifiers suppresses queued firing notifications for resolved-// alerts while preserving unrelated alerts in the same grouped queue row.-func (nq *NotificationQueue) CancelByAlertIdentifiers(alertIdentifiers []string) error {+// alerts while preserving unrelated alerts in the same grouped queue row. It+// returns the number of matched firing-alert entries removed from rows that+// were still waiting for delivery ('pending'). Entries in rows already+// mid-send ('sending') are cancelled best-effort but not counted, because+// their delivery may still complete.+func (nq *NotificationQueue) CancelByAlertIdentifiers(alertIdentifiers []string) (int, error) {if len(alertIdentifiers) == 0 {- return nil+ return 0, nil}nq.mu.Lock()defer nq.mu.Unlock()query := `- SELECT id, type, alerts+ SELECT id, type, status, alertsFROM notification_queueWHERE status IN ('pending', 'sending')`rows, err := nq.db.Query(query)if err != nil {- return fmt.Errorf("failed to query notifications for cancellation: %w", err)+ return 0, fmt.Errorf("failed to query notifications for cancellation: %w", err)}alertIdentifierSet := make(map[string]struct{})@@ -1062,9 +1066,9 @@ func (nq *NotificationQueue) CancelByAlertIdentifiers(alertIdentifiers []string)}if len(alertIdentifierSet) == 0 {if err := rows.Close(); err != nil {- return fmt.Errorf("failed to close cancellation query: %w", err)+ return 0, fmt.Errorf("failed to close cancellation query: %w", err)}- return nil+ return 0, nil}type queuedAlertCancellation struct {@@ -1075,12 +1079,14 @@ func (nq *NotificationQueue) CancelByAlertIdentifiers(alertIdentifiers []string)var toCancelIDs []stringvar toRewrite []queuedAlertCancellationsuppressedAlertCount := 0+ suppressedPendingAlertCount := 0for rows.Next() {var notifID stringvar notifType string+ var notifStatus stringvar alertsJSON []byte- if err := rows.Scan(¬ifID, ¬ifType, &alertsJSON); err != nil {+ if err := rows.Scan(¬ifID, ¬ifType, ¬ifStatus, &alertsJSON); err != nil {log.Error().Err(err).Str("component", "notification_queue").@@ -1121,6 +1127,9 @@ func (nq *NotificationQueue) CancelByAlertIdentifiers(alertIdentifiers []string)}suppressedAlertCount += matchedAlertCount+ if notifStatus == string(QueueStatusPending) {+ suppressedPendingAlertCount += matchedAlertCount+ }if len(remainingAlerts) == 0 {toCancelIDs = append(toCancelIDs, notifID)continue@@ -1134,7 +1143,7 @@ func (nq *NotificationQueue) CancelByAlertIdentifiers(alertIdentifiers []string)rowsErr := rows.Err()rows.Close() // Release connection before executing updatesif rowsErr != nil {- return fmt.Errorf("error iterating notifications for cancellation: %w", rowsErr)+ return 0, fmt.Errorf("error iterating notifications for cancellation: %w", rowsErr)}if len(toRewrite) > 0 {@@ -1146,10 +1155,10 @@ func (nq *NotificationQueue) CancelByAlertIdentifiers(alertIdentifiers []string)for _, rewrite := range toRewrite {alertsJSON, err := json.Marshal(rewrite.remaining)if err != nil {- return fmt.Errorf("failed to marshal remaining alerts for %s: %w", rewrite.notificationID, err)+ return 0, fmt.Errorf("failed to marshal remaining alerts for %s: %w", rewrite.notificationID, err)}if _, err := nq.db.Exec(updateAlertsQuery, string(alertsJSON), rewrite.notificationID); err != nil {- return fmt.Errorf("failed to rewrite queued notification %s after alert resolution: %w", rewrite.notificationID, err)+ return 0, fmt.Errorf("failed to rewrite queued notification %s after alert resolution: %w", rewrite.notificationID, err)}}}@@ -1178,13 +1187,14 @@ func (nq *NotificationQueue) CancelByAlertIdentifiers(alertIdentifiers []string)Str("component", "notification_queue").Str("action", "cancel_alert_identifiers").Int("suppressedAlertCount", suppressedAlertCount).+ Int("suppressedPendingAlertCount", suppressedPendingAlertCount).Int("cancelledRows", len(toCancelIDs)).Int("rewrittenRows", len(toRewrite)).Strs("alertIdentifiers", alertIdentifiers).Msg("suppressed resolved alerts in queued notifications")}- return nil+ return suppressedPendingAlertCount, nil}func queueTypeCancelableOnAlertResolution(notifType string) bool {diff --git a/internal/notifications/queue_observability_test.go b/internal/notifications/queue_observability_test.goindex 4f06f71485..f920ac8683 100644--- a/internal/notifications/queue_observability_test.go+++ b/internal/notifications/queue_observability_test.go@@ -88,7 +88,7 @@ func TestCancelByAlertIdentifiersLogsStructuredContextOnAlertUnmarshalFailure(t}logOutput := captureNotificationQueueLogs(t)- if err := nq.CancelByAlertIdentifiers([]string{"alert-1"}); err != nil {+ if _, err := nq.CancelByAlertIdentifiers([]string{"alert-1"}); err != nil {t.Fatalf("CancelByAlertIdentifiers returned error: %v", err)}diff --git a/internal/notifications/queue_test.go b/internal/notifications/queue_test.goindex ac3d105dad..05c87f24c7 100644--- a/internal/notifications/queue_test.go+++ b/internal/notifications/queue_test.go@@ -361,16 +361,22 @@ func TestCancelByAlertIdentifiers_EmptyInput(t *testing.T) {}// Empty slice should return nil without error- err = nq.CancelByAlertIdentifiers([]string{})+ count, err := nq.CancelByAlertIdentifiers([]string{})if err != nil {t.Errorf("CancelByAlertIdentifiers with empty slice returned error: %v", err)}+ if count != 0 {+ t.Errorf("CancelByAlertIdentifiers with empty slice returned count %d, want 0", count)+ }// Nil slice should also return nil without error- err = nq.CancelByAlertIdentifiers(nil)+ count, err = nq.CancelByAlertIdentifiers(nil)if err != nil {t.Errorf("CancelByAlertIdentifiers with nil slice returned error: %v", err)}+ if count != 0 {+ t.Errorf("CancelByAlertIdentifiers with nil slice returned count %d, want 0", count)+ }}func TestCancelByAlertIdentifiers_NoMatchingNotifications(t *testing.T) {@@ -397,10 +403,13 @@ func TestCancelByAlertIdentifiers_NoMatchingNotifications(t *testing.T) {}// Cancel with non-matching alert ID- err = nq.CancelByAlertIdentifiers([]string{"alert-2"})+ count, err := nq.CancelByAlertIdentifiers([]string{"alert-2"})if err != nil {t.Errorf("CancelByAlertIdentifiers returned error: %v", err)}+ if count != 0 {+ t.Errorf("CancelByAlertIdentifiers returned count %d, want 0", count)+ }// Verify the notification is still pending using GetQueueStatsstats, err := nq.GetQueueStats()@@ -535,10 +544,13 @@ func TestCancelByAlertIdentifiers_MatchingNotificationCancelled(t *testing.T) {}// Cancel with matching alert ID- err = nq.CancelByAlertIdentifiers([]string{"alert-1"})+ count, err := nq.CancelByAlertIdentifiers([]string{"alert-1"})if err != nil {t.Errorf("CancelByAlertIdentifiers returned error: %v", err)}+ if count != 1 {+ t.Errorf("CancelByAlertIdentifiers returned count %d, want 1", count)+ }// Verify the notification is now cancelled using GetQueueStatsstats, err := nq.GetQueueStats()@@ -596,9 +608,13 @@ func TestCancelByAlertIdentifiers_PreservesResolvedNotifications(t *testing.T) {}}- if err := nq.CancelByAlertIdentifiers([]string{"alert-1"}); err != nil {+ count, err := nq.CancelByAlertIdentifiers([]string{"alert-1"})+ if err != nil {t.Fatalf("CancelByAlertIdentifiers returned error: %v", err)}+ if count != 1 {+ t.Fatalf("CancelByAlertIdentifiers returned count %d, want 1 (only the firing entry counts)", count)+ }var statusFiring NotificationQueueStatusif err := nq.db.QueryRow(`SELECT status FROM notification_queue WHERE id = ?`, firing.ID).Scan(&statusFiring); err != nil {@@ -644,10 +660,13 @@ func TestCancelByAlertIdentifiers_MultipleAlertsPartialMatch(t *testing.T) {t.Fatalf("Failed to enqueue: %v", err)}- err = nq.CancelByAlertIdentifiers([]string{"alert-1", "alert-3"})+ count, err := nq.CancelByAlertIdentifiers([]string{"alert-1", "alert-3"})if err != nil {t.Errorf("CancelByAlertIdentifiers returned error: %v", err)}+ if count != 2 {+ t.Errorf("CancelByAlertIdentifiers returned count %d, want 2", count)+ }stats, err := nq.GetQueueStats()if err != nil {@@ -689,6 +708,50 @@ func TestCancelByAlertIdentifiers_MultipleAlertsPartialMatch(t *testing.T) {}}+func TestCancelByAlertIdentifiers_SendingRowsCancelledButNotCounted(t *testing.T) {+ tempDir := t.TempDir()+ nq, err := NewNotificationQueue(tempDir)+ if err != nil {+ t.Fatalf("Failed to create notification queue: %v", err)+ }+ defer func() { _ = nq.Stop() }()++ futureRetry := time.Now().Add(1 * time.Hour)+ notif := &QueuedNotification{+ ID: "notif-sending",+ Type: "webhook",+ Status: QueueStatusPending,+ MaxAttempts: 3,+ Config: []byte(`{}`),+ NextRetryAt: &futureRetry,+ Alerts: []*alerts.Alert{{ID: "alert-1"}},+ }+ if err := nq.Enqueue(notif); err != nil {+ t.Fatalf("Failed to enqueue: %v", err)+ }+ if _, err := nq.db.Exec(`UPDATE notification_queue SET status = 'sending' WHERE id = ?`, notif.ID); err != nil {+ t.Fatalf("Failed to mark notification as sending: %v", err)+ }++ // A mid-send row may still complete delivery, so it must not count as an+ // undelivered firing entry even though the cancellation is still applied.+ count, err := nq.CancelByAlertIdentifiers([]string{"alert-1"})+ if err != nil {+ t.Fatalf("CancelByAlertIdentifiers returned error: %v", err)+ }+ if count != 0 {+ t.Fatalf("CancelByAlertIdentifiers returned count %d, want 0 for a sending row", count)+ }++ var status string+ if err := nq.db.QueryRow(`SELECT status FROM notification_queue WHERE id = ?`, notif.ID).Scan(&status); err != nil {+ t.Fatalf("Failed to query notification status: %v", err)+ }+ if status != string(QueueStatusCancelled) {+ t.Fatalf("status = %q, want %q", status, QueueStatusCancelled)+ }+}+func TestCancelByAlertIdentifiers_SetsCompletedAtAndClearsNextRetry(t *testing.T) {tempDir := t.TempDir()nq, err := NewNotificationQueue(tempDir)@@ -711,7 +774,7 @@ func TestCancelByAlertIdentifiers_SetsCompletedAtAndClearsNextRetry(t *testing.Tt.Fatalf("Failed to enqueue: %v", err)}- if err := nq.CancelByAlertIdentifiers([]string{"alert-1"}); err != nil {+ if _, err := nq.CancelByAlertIdentifiers([]string{"alert-1"}); err != nil {t.Fatalf("CancelByAlertIdentifiers returned error: %v", err)}