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.

emit reliability finding when an alert starts flapping

rcourtman0e0c90da53f5
diff --git a/internal/api/flapping_postmortem.go b/internal/api/flapping_postmortem.go
new file mode 100644
index 0000000000..759780c699
--- /dev/null
+++ b/internal/api/flapping_postmortem.go
@@ -0,0 +1,108 @@
+package api
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai"
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rs/zerolog/log"
+)
+
+// emitFlappingPostmortemFinding writes a reliability finding to the findings
+// store explaining what is flapping and why Pulse suppressed it. The finding
+// ID is derived from the alert's canonical tracking key so re-detection
+// inside the cooldown window updates the existing finding instead of
+// creating a duplicate.
+//
+// This is Path B from the lane brief: emit the finding directly at callback
+// time so it is durable without depending on patrol synthesis. The scoped
+// patrol still runs in parallel to enrich context once it lands.
+func emitFlappingPostmortemFinding(patrol *ai.PatrolService, alertManager *alerts.Manager, alert *alerts.Alert, trackingKey string) {
+ if patrol == nil || alert == nil || trackingKey == "" {
+ return
+ }
+ store := patrol.GetFindings()
+ if store == nil {
+ log.Debug().
+ Str("trackingKey", trackingKey).
+ Msg("Flapping postmortem: findings store unavailable, skipping finding emission")
+ return
+ }
+
+ cfg := alertManager.GetConfig()
+ now := time.Now()
+
+ resourceName := strings.TrimSpace(alert.ResourceName)
+ if resourceName == "" {
+ resourceName = strings.TrimSpace(alert.ResourceID)
+ }
+ if resourceName == "" {
+ resourceName = "resource"
+ }
+ alertType := strings.TrimSpace(alert.Type)
+ if alertType == "" {
+ alertType = "alert"
+ }
+
+ title := fmt.Sprintf("Alert %s on %s is flapping", alertType, resourceName)
+ description := fmt.Sprintf(
+ "Pulse detected this alert switching state %d or more times within %s and suppressed further notifications for %s. Suppression is in effect to avoid alarm-storm noise; the underlying condition has NOT been fixed.",
+ cfg.FlappingThreshold,
+ formatSecondsDuration(cfg.FlappingWindowSeconds),
+ formatMinutesDuration(cfg.FlappingCooldownMinutes),
+ )
+ recommendation := "Consider widening the threshold (so transient blips do not toggle the alert), raising the flapping cooldown, or stabilising the underlying resource. If the resource really is unstable, investigating why it crosses the threshold so often is the durable fix."
+
+ findingID := "alert-flapping:" + trackingKey
+ finding := &ai.Finding{
+ ID: findingID,
+ Key: findingID,
+ Severity: ai.FindingSeverityWarning,
+ Category: ai.FindingCategoryReliability,
+ ResourceID: alert.ResourceID,
+ ResourceName: resourceName,
+ ResourceType: alert.CanonicalKind,
+ Node: alert.Node,
+ Title: title,
+ Description: description,
+ Impact: "Alarm-storm flapping is being silenced. Real problems on this resource may be missed until you tune the alert or fix the instability.",
+ Recommendation: recommendation,
+ Evidence: fmt.Sprintf("trackingKey=%s alertType=%s threshold=%d windowSeconds=%d cooldownMinutes=%d", trackingKey, alertType, cfg.FlappingThreshold, cfg.FlappingWindowSeconds, cfg.FlappingCooldownMinutes),
+ Source: "alert-flapping",
+ DetectedAt: now,
+ LastSeenAt: now,
+ AlertIdentifier: alert.ID,
+ }
+
+ if store.Add(finding) {
+ log.Info().
+ Str("findingID", findingID).
+ Str("trackingKey", trackingKey).
+ Str("resourceID", alert.ResourceID).
+ Str("alertType", alertType).
+ Msg("Emitted flapping postmortem finding")
+ } else {
+ log.Debug().
+ Str("findingID", findingID).
+ Str("trackingKey", trackingKey).
+ Msg("Flapping postmortem finding deduped against existing record")
+ }
+}
+
+func formatSecondsDuration(seconds int) string {
+ if seconds <= 0 {
+ return "the configured window"
+ }
+ d := time.Duration(seconds) * time.Second
+ return d.String()
+}
+
+func formatMinutesDuration(minutes int) string {
+ if minutes <= 0 {
+ return "the configured cooldown"
+ }
+ d := time.Duration(minutes) * time.Minute
+ return d.String()
+}
diff --git a/internal/api/flapping_postmortem_test.go b/internal/api/flapping_postmortem_test.go
new file mode 100644
index 0000000000..82859f401c
--- /dev/null
+++ b/internal/api/flapping_postmortem_test.go
@@ -0,0 +1,118 @@
+package api
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai"
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+// TestEmitFlappingPostmortemFinding_DedupsByTrackingKey verifies the key
+// invariant stated in the lane brief: two flapping transitions for the same
+// trackingKey within the cooldown window must produce exactly one finding.
+// The stable finding ID is derived from trackingKey, so re-emission folds
+// into the existing record via FindingsStore.Add's same-ID branch.
+func TestEmitFlappingPostmortemFinding_DedupsByTrackingKey(t *testing.T) {
+ patrol := ai.NewPatrolService(nil, nil)
+ alertManager := alerts.NewManager()
+ t.Cleanup(func() { alertManager.Stop() })
+
+ store := patrol.GetFindings()
+ if store == nil {
+ t.Fatal("patrol service has nil findings store; cannot run dedup test")
+ }
+
+ alert := &alerts.Alert{
+ ID: "vm-100-cpu-1",
+ Type: "cpu",
+ ResourceID: "vm-100",
+ ResourceName: "testvm",
+ CanonicalKind: "vm",
+ Level: alerts.AlertLevelWarning,
+ }
+ trackingKey := "vm-100/cpu"
+
+ emitFlappingPostmortemFinding(patrol, alertManager, alert, trackingKey)
+ emitFlappingPostmortemFinding(patrol, alertManager, alert, trackingKey)
+
+ got := store.GetByResource("vm-100")
+ flappingCount := 0
+ var found *ai.Finding
+ for _, f := range got {
+ if f == nil {
+ continue
+ }
+ if strings.HasPrefix(f.ID, "alert-flapping:") {
+ flappingCount++
+ found = f
+ }
+ }
+ if flappingCount != 1 {
+ t.Fatalf("expected exactly 1 flapping finding after 2 emits with same trackingKey, got %d", flappingCount)
+ }
+ if found == nil {
+ t.Fatal("flapping finding not present after dedup test")
+ }
+ if found.ID != "alert-flapping:"+trackingKey {
+ t.Errorf("expected stable ID derived from trackingKey, got %q", found.ID)
+ }
+ if found.Category != ai.FindingCategoryReliability {
+ t.Errorf("expected reliability category, got %q", found.Category)
+ }
+ if !strings.Contains(found.Title, "flapping") {
+ t.Errorf("expected title to mention flapping, got %q", found.Title)
+ }
+ if !strings.Contains(found.Description, "Pulse detected") {
+ t.Errorf("expected description to explain detection, got %q", found.Description)
+ }
+ // TimesRaised must increment on re-detection (heartbeat behaviour from
+ // FindingsStore.Add's same-ID branch).
+ if found.TimesRaised < 2 {
+ t.Errorf("expected TimesRaised >= 2 after two emits, got %d", found.TimesRaised)
+ }
+}
+
+// TestEmitFlappingPostmortemFinding_DistinctTrackingKeys verifies that two
+// different trackingKeys produce two distinct findings -- the dedup is
+// per-trackingKey, not global.
+func TestEmitFlappingPostmortemFinding_DistinctTrackingKeys(t *testing.T) {
+ patrol := ai.NewPatrolService(nil, nil)
+ alertManager := alerts.NewManager()
+ t.Cleanup(func() { alertManager.Stop() })
+
+ a1 := &alerts.Alert{
+ ID: "vm-100-cpu", Type: "cpu", ResourceID: "vm-100",
+ ResourceName: "testvm", CanonicalKind: "vm", Level: alerts.AlertLevelWarning,
+ }
+ a2 := &alerts.Alert{
+ ID: "vm-100-memory", Type: "memory", ResourceID: "vm-100",
+ ResourceName: "testvm", CanonicalKind: "vm", Level: alerts.AlertLevelWarning,
+ }
+
+ emitFlappingPostmortemFinding(patrol, alertManager, a1, "vm-100/cpu")
+ emitFlappingPostmortemFinding(patrol, alertManager, a2, "vm-100/memory")
+
+ count := 0
+ for _, f := range patrol.GetFindings().GetByResource("vm-100") {
+ if f != nil && strings.HasPrefix(f.ID, "alert-flapping:") {
+ count++
+ }
+ }
+ if count != 2 {
+ t.Fatalf("expected 2 distinct flapping findings for distinct tracking keys, got %d", count)
+ }
+}
+
+// TestEmitFlappingPostmortemFinding_NilGuards confirms the helper is safe
+// against the nil cases the router lambda might hand it.
+func TestEmitFlappingPostmortemFinding_NilGuards(t *testing.T) {
+ patrol := ai.NewPatrolService(nil, nil)
+ alertManager := alerts.NewManager()
+ t.Cleanup(func() { alertManager.Stop() })
+
+ emitFlappingPostmortemFinding(nil, alertManager, &alerts.Alert{ID: "a"}, "k")
+ emitFlappingPostmortemFinding(patrol, alertManager, nil, "k")
+ emitFlappingPostmortemFinding(patrol, alertManager, &alerts.Alert{ID: "a"}, "")
+ // No panic == pass.
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 0e2157a121..785103b1c6 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -2306,6 +2306,38 @@ func (r *Router) initializeAIIntelligenceServices(ctx context.Context, orgID, da
log.Info().Msg("AI Intelligence: Baseline anomaly callback wired to trigger manager")
}
+ // 11b. Wire alert-flapping callback to the trigger manager and surface
+ // a postmortem finding so the operator sees the diagnosis instead of
+ // silence. The alerts manager fires this callback exactly once per
+ // flapping transition (one-shot for the cooldown window); we both
+ // emit a reliability finding via Path B (direct FindingsStore.Add
+ // with a stable dedup ID derived from trackingKey) AND enqueue a
+ // scoped patrol so the postmortem context can be enriched later.
+ if monitor != nil {
+ if alertManager := monitor.GetAlertManager(); alertManager != nil {
+ alertManager.SetFlappingDetectedCallback(func(alert *alerts.Alert, trackingKey string) {
+ if alert == nil || trackingKey == "" {
+ return
+ }
+ emitFlappingPostmortemFinding(patrol, alertManager, alert, trackingKey)
+ scope := ai.FlappingPostmortemPatrolScope(
+ alert.ID,
+ alert.ResourceID,
+ alert.CanonicalKind,
+ alert.Type,
+ )
+ if triggerManager.TriggerPatrol(scope) {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("trackingKey", trackingKey).
+ Str("alertType", alert.Type).
+ Msg("Flapping-detected triggered postmortem patrol via TriggerManager")
+ }
+ })
+ log.Info().Msg("AI Intelligence: Alert-flapping callback wired to trigger manager")
+ }
+ }
+
log.Info().Msg("AI Intelligence: Event-driven trigger manager initialized and started")
}