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
add storm throttler substrate in FindingsStore.Add
rcourtman8f9ff9270140
diff --git a/internal/ai/findings.go b/internal/ai/findings.goindex 0b413dba99..97a4e83f54 100644--- a/internal/ai/findings.go+++ b/internal/ai/findings.go@@ -731,6 +731,11 @@ type FindingsStore struct {// resource is in a maintenance window. Nil-safe; an unset provider// disables operator-state-driven suppression.resourceOperatorStateProvider ResourceOperatorStateProvider+ // Optional finding-storm throttler — when set, the store invokes it+ // from Add's new-finding branch so a single noisy resource's burst+ // of multi-symptom findings is summarised by one storm finding.+ // Nil-safe; an unset throttler disables storm summarisation.+ stormThrottler *findingStormThrottler}// ResourceOperatorStateMaintenanceWindow describes the maintenance@@ -809,6 +814,16 @@ func (s *FindingsStore) SetResourceOperatorStateProvider(p ResourceOperatorStates.resourceOperatorStateProvider = p}+// SetStormThrottler installs the finding-storm throttler. The store+// consults it from Add's new-finding branch with the store mutex held;+// the throttler must not call back into the store. Pass nil to disable+// storm summarisation (the default).+func (s *FindingsStore) SetStormThrottler(t *findingStormThrottler) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.stormThrottler = t+}+// OperatorStateProjectionFor exposes the operator-state projection for// a resource so callers outside the suppression hot path (e.g. the// patrol investigation runtime, when it's about to hand a finding to@@ -1576,6 +1591,14 @@ func (s *FindingsStore) Add(f *Finding) bool {if f.IsActive() {s.activeCounts[f.Severity]++}+ // Storm throttler hook: still inside the new-finding branch with+ // s.mu held so the observer reads a consistent index. The observer+ // owns its own internal mutex and must not call back into the+ // store; its return is dispatched after s.mu is released below.+ var pendingStormFinding *Finding+ if t := s.stormThrottler; t != nil {+ pendingStormFinding = t.observeLocked(f, time.Now())+ }severity := f.Severitys.mu.Unlock()s.scheduleSave()@@ -1583,6 +1606,13 @@ func (s *FindingsStore) Add(f *Finding) bool {if severity == FindingSeverityWarning || severity == FindingSeverityCritical {_ = s.ForceSave()}+ if pendingStormFinding != nil {+ if pendingStormFinding.ResolvedAt != nil {+ s.ResolveWithReason(pendingStormFinding.ID, stormResolveReason)+ } else {+ s.Add(pendingStormFinding)+ }+ }return true}diff --git a/internal/ai/findings_storm_throttler.go b/internal/ai/findings_storm_throttler.gonew file mode 100644index 0000000000..ec5927714b--- /dev/null+++ b/internal/ai/findings_storm_throttler.go@@ -0,0 +1,242 @@+// findings_storm_throttler.go implements the MVP finding-storm throttler.+//+// The throttler clusters new-finding emissions by ResourceID and, when a+// cluster crosses stormThreshold within stormWindow, emits a single+// meta-finding (FindingCategoryReliability, Source=stormFindingSource)+// that points the operator at the noisy resource instead of letting many+// per-symptom findings drown the surface.+//+// The observer (observeLocked) is called from FindingsStore.Add with the+// store mutex held; it owns its own internal mutex so the throttler does+// not couple to the store's lock-ordering invariants. The observer must+// NOT call back into FindingsStore.++package ai++import (+ "fmt"+ "sort"+ "strings"+ "sync"+ "time"+)++const (+ stormWindow = 60 * time.Second+ stormThreshold = 3+ stormFindingSource = "finding-storm"+ stormFindingIDPrefix = "finding-storm:"+ stormClusterCap = 1024+ stormResolveReason = "finding-storm:rate_dropped_below_threshold"+)++// findingStormCluster carries per-clusterKey state: the sliding window of+// emission timestamps, identity of the storm finding currently emitted for+// the cluster (if any), and the freshest contributor metadata so the storm+// finding's operator-facing pointer tracks the latest symptom.+type findingStormCluster struct {+ emissions []time.Time+ emittedFindingID string+ lastEmittedAt time.Time+ lastTouchedAt time.Time++ lastResourceID string+ lastResourceName string+ lastResourceType string+ lastNode string++ contributorTitles []string+}++// findingStormThrottler clusters new-finding emissions by clusterKey and+// emits a single storm finding per cluster while the cluster is above+// threshold. Safe for concurrent use.+type findingStormThrottler struct {+ mu sync.Mutex+ clusters map[string]*findingStormCluster+ cap int+}++func newFindingStormThrottler() *findingStormThrottler {+ return &findingStormThrottler{+ clusters: make(map[string]*findingStormCluster),+ cap: stormClusterCap,+ }+}++// observeLocked is invoked from FindingsStore.Add with the store mutex+// held. It returns:+// - nil: no action.+// - *Finding with ResolvedAt == nil: a storm finding the caller should+// re-enter through s.Add. Re-entry with the same ID lands in the+// existing-finding branch on subsequent emissions, so the storm+// finding is updated rather than duplicated.+// - *Finding with ResolvedAt != nil: a sentinel; the caller should+// route through s.ResolveWithReason(finding.ID, stormResolveReason).+//+// The "Locked" suffix names the caller's lock state (s.mu held), not this+// method's — the throttler uses its own internal mutex.+func (t *findingStormThrottler) observeLocked(f *Finding, now time.Time) *Finding {+ if t == nil || f == nil {+ return nil+ }+ // Cycle guard: storm findings must not be observed; their own+ // emission re-enters Add and would otherwise recurse.+ if f.Source == stormFindingSource {+ return nil+ }+ clusterKey := strings.TrimSpace(f.ResourceID)+ if clusterKey == "" {+ return nil+ }+ // The synthetic patrol-runtime resource is a single shared bucket+ // for provider-misconfiguration findings; a config loop on Patrol+ // itself must not masquerade as a resource-level storm.+ if clusterKey == patrolRuntimeResourceID {+ return nil+ }++ t.mu.Lock()+ defer t.mu.Unlock()++ cluster, ok := t.clusters[clusterKey]+ if !ok {+ cluster = &findingStormCluster{}+ t.clusters[clusterKey] = cluster+ }+ cluster.lastTouchedAt = now++ cutoff := now.Add(-stormWindow)+ keep := cluster.emissions[:0]+ for _, ts := range cluster.emissions {+ if !ts.Before(cutoff) {+ keep = append(keep, ts)+ }+ }+ cluster.emissions = keep+ cluster.emissions = append(cluster.emissions, now)++ cluster.lastResourceID = f.ResourceID+ cluster.lastResourceName = f.ResourceName+ cluster.lastResourceType = f.ResourceType+ cluster.lastNode = f.Node++ title := strings.TrimSpace(f.Title)+ if title != "" {+ alreadyListed := false+ for _, existing := range cluster.contributorTitles {+ if existing == title {+ alreadyListed = true+ break+ }+ }+ if !alreadyListed {+ if len(cluster.contributorTitles) >= 8 {+ cluster.contributorTitles = cluster.contributorTitles[1:]+ }+ cluster.contributorTitles = append(cluster.contributorTitles, title)+ }+ }++ t.pruneLRULocked(clusterKey)++ count := len(cluster.emissions)+ if count >= stormThreshold {+ stormID := stormFindingIDPrefix + clusterKey+ cluster.emittedFindingID = stormID+ cluster.lastEmittedAt = now+ return t.buildStormFindingLocked(cluster, clusterKey, count, now)+ }++ // Below threshold. If a prior storm emission has aged out (no+ // refresh for at least 2 * stormWindow), signal the caller to+ // resolve it. This is the lazy auto-resolve documented in the+ // brief: it fires the next time any finding lands on the same+ // cluster, not on a separate sweep goroutine.+ if cluster.emittedFindingID != "" && !cluster.lastEmittedAt.IsZero() &&+ now.Sub(cluster.lastEmittedAt) >= 2*stormWindow {+ stormID := cluster.emittedFindingID+ cluster.emittedFindingID = ""+ cluster.lastEmittedAt = time.Time{}+ cluster.contributorTitles = nil+ resolvedAt := now+ return &Finding{+ ID: stormID,+ ResolvedAt: &resolvedAt,+ }+ }++ return nil+}++// pruneLRULocked evicts the least-recently-touched clusters (excluding+// the cluster the caller just touched) until the tracker is at or under+// the cap. Called while t.mu is held.+func (t *findingStormThrottler) pruneLRULocked(protectKey string) {+ if t.cap <= 0 {+ return+ }+ if len(t.clusters) <= t.cap {+ return+ }+ type entry struct {+ key string+ at time.Time+ }+ candidates := make([]entry, 0, len(t.clusters)-1)+ for k, c := range t.clusters {+ if k == protectKey {+ continue+ }+ candidates = append(candidates, entry{key: k, at: c.lastTouchedAt})+ }+ sort.Slice(candidates, func(i, j int) bool {+ return candidates[i].at.Before(candidates[j].at)+ })+ excess := len(t.clusters) - t.cap+ for i := 0; i < excess && i < len(candidates); i++ {+ delete(t.clusters, candidates[i].key)+ }+}++// buildStormFindingLocked constructs the storm finding for a cluster.+// Called while t.mu is held. The finding has a stable ID so subsequent+// emissions on the same cluster dedup through FindingsStore.Add's+// existing-finding branch rather than spawning duplicates.+func (t *findingStormThrottler) buildStormFindingLocked(cluster *findingStormCluster, clusterKey string, count int, now time.Time) *Finding {+ resourceName := cluster.lastResourceName+ if strings.TrimSpace(resourceName) == "" {+ resourceName = clusterKey+ }+ stormID := stormFindingIDPrefix + clusterKey++ var contributorClause string+ if len(cluster.contributorTitles) > 0 {+ contributorClause = " Contributors: " + strings.Join(cluster.contributorTitles, "; ") + "."+ }+ description := fmt.Sprintf(+ "Patrol has emitted %d distinct findings against %s within %s. Inspect this resource directly; the surface is showing several independent symptoms in a tight window.%s",+ count,+ resourceName,+ stormWindow,+ contributorClause,+ )++ return &Finding{+ ID: stormID,+ Key: stormID,+ Severity: FindingSeverityWarning,+ Category: FindingCategoryReliability,+ ResourceID: cluster.lastResourceID,+ ResourceName: resourceName,+ ResourceType: cluster.lastResourceType,+ Node: cluster.lastNode,+ Title: fmt.Sprintf("Multiple findings emitted against %s in %s", resourceName, stormWindow),+ Description: description,+ Recommendation: "Inspect this resource directly; Patrol is surfacing several independent symptoms in a tight window.",+ Evidence: fmt.Sprintf("clusterKey=%s emissions=%d windowSeconds=%d", clusterKey, count, int(stormWindow/time.Second)),+ Source: stormFindingSource,+ DetectedAt: now,+ LastSeenAt: now,+ }+}diff --git a/internal/ai/findings_storm_throttler_test.go b/internal/ai/findings_storm_throttler_test.gonew file mode 100644index 0000000000..9cc253894f--- /dev/null+++ b/internal/ai/findings_storm_throttler_test.go@@ -0,0 +1,234 @@+package ai++import (+ "fmt"+ "strings"+ "testing"+ "time"+)++func newStormFinding(id, resourceID, title string) *Finding {+ return &Finding{+ ID: id,+ ResourceID: resourceID,+ ResourceName: resourceID,+ ResourceType: "vm",+ Title: title,+ Severity: FindingSeverityWarning,+ Category: FindingCategoryReliability,+ }+}++func TestStormThrottler_BelowThresholdReturnsNil(t *testing.T) {+ tr := newFindingStormThrottler()+ base := time.Now()++ if got := tr.observeLocked(newStormFinding("a", "vm/100", "high cpu"), base); got != nil {+ t.Fatalf("first emission below threshold: want nil, got %+v", got)+ }+ if got := tr.observeLocked(newStormFinding("b", "vm/100", "memory swap"), base.Add(5*time.Second)); got != nil {+ t.Fatalf("second emission below threshold: want nil, got %+v", got)+ }+}++func TestStormThrottler_CrossesThresholdEmitsStormFinding(t *testing.T) {+ tr := newFindingStormThrottler()+ base := time.Now()++ tr.observeLocked(newStormFinding("a", "vm/100", "high cpu"), base)+ tr.observeLocked(newStormFinding("b", "vm/100", "memory swap"), base.Add(5*time.Second))+ got := tr.observeLocked(newStormFinding("c", "vm/100", "disk fill"), base.Add(10*time.Second))+ if got == nil {+ t.Fatal("third emission within window: expected storm finding, got nil")+ }+ if got.ID != stormFindingIDPrefix+"vm/100" {+ t.Errorf("storm finding ID: want %q, got %q", stormFindingIDPrefix+"vm/100", got.ID)+ }+ if got.Key != got.ID {+ t.Errorf("storm finding Key: want %q, got %q", got.ID, got.Key)+ }+ if got.Source != stormFindingSource {+ t.Errorf("storm finding Source: want %q, got %q", stormFindingSource, got.Source)+ }+ if got.Category != FindingCategoryReliability {+ t.Errorf("storm finding Category: want %q, got %q", FindingCategoryReliability, got.Category)+ }+ if got.Severity != FindingSeverityWarning {+ t.Errorf("storm finding Severity: want %q, got %q", FindingSeverityWarning, got.Severity)+ }+ if got.ResolvedAt != nil {+ t.Errorf("storm finding ResolvedAt: want nil (emit path), got %v", got.ResolvedAt)+ }+ if !strings.Contains(got.Evidence, "emissions=3") {+ t.Errorf("storm finding Evidence: want emissions=3, got %q", got.Evidence)+ }+ // Title and Description should reference the resource name freshest contributor.+ if !strings.Contains(got.Title, "vm/100") {+ t.Errorf("storm finding Title: want resource name, got %q", got.Title)+ }+ if !strings.Contains(got.Description, "high cpu") || !strings.Contains(got.Description, "disk fill") {+ t.Errorf("storm finding Description: want contributor titles, got %q", got.Description)+ }+}++func TestStormThrottler_FiltersStormFindingSource(t *testing.T) {+ tr := newFindingStormThrottler()+ base := time.Now()+ // Many emissions whose Source is the storm-finding source should NOT+ // count toward threshold — this is the cycle guard.+ for i := 0; i < 10; i++ {+ f := newStormFinding(fmt.Sprintf("s%d", i), "vm/200", "some title")+ f.Source = stormFindingSource+ if got := tr.observeLocked(f, base.Add(time.Duration(i)*time.Second)); got != nil {+ t.Fatalf("storm-source emission %d should be filtered, got %+v", i, got)+ }+ }+}++func TestStormThrottler_FiltersPatrolRuntimeResource(t *testing.T) {+ tr := newFindingStormThrottler()+ base := time.Now()+ for i := 0; i < 10; i++ {+ f := newStormFinding(fmt.Sprintf("p%d", i), patrolRuntimeResourceID, "patrol error")+ if got := tr.observeLocked(f, base.Add(time.Duration(i)*time.Second)); got != nil {+ t.Fatalf("ai-service emission %d should be filtered, got %+v", i, got)+ }+ }+}++func TestStormThrottler_FiltersEmptyResourceID(t *testing.T) {+ tr := newFindingStormThrottler()+ base := time.Now()+ for i := 0; i < 10; i++ {+ f := newStormFinding(fmt.Sprintf("e%d", i), " ", "anon")+ if got := tr.observeLocked(f, base.Add(time.Duration(i)*time.Second)); got != nil {+ t.Fatalf("empty-resource emission %d should be filtered, got %+v", i, got)+ }+ }+}++func TestStormThrottler_WindowEvictionPreventsFalsePositive(t *testing.T) {+ tr := newFindingStormThrottler()+ base := time.Now()+ // Two emissions then a long pause; third emission outside window+ // should NOT trip threshold because the first two have aged out.+ tr.observeLocked(newStormFinding("a", "vm/300", "x"), base)+ tr.observeLocked(newStormFinding("b", "vm/300", "y"), base.Add(2*time.Second))+ got := tr.observeLocked(newStormFinding("c", "vm/300", "z"), base.Add(stormWindow+30*time.Second))+ if got != nil {+ t.Fatalf("emission outside window should not trigger storm: %+v", got)+ }+}++func TestStormThrottler_LRUEvictsOldestClusterAtCap(t *testing.T) {+ tr := newFindingStormThrottler()+ tr.cap = 3+ base := time.Now()+ // Fill cap with three clusters, each touched at increasing times.+ tr.observeLocked(newStormFinding("a", "vm/A", "a"), base)+ tr.observeLocked(newStormFinding("b", "vm/B", "b"), base.Add(1*time.Second))+ tr.observeLocked(newStormFinding("c", "vm/C", "c"), base.Add(2*time.Second))+ // Fourth cluster forces LRU eviction; vm/A is oldest.+ tr.observeLocked(newStormFinding("d", "vm/D", "d"), base.Add(3*time.Second))+ if _, ok := tr.clusters["vm/A"]; ok {+ t.Errorf("LRU eviction: expected oldest cluster vm/A to be evicted; clusters: %v", clusterKeys(tr))+ }+ if _, ok := tr.clusters["vm/D"]; !ok {+ t.Errorf("LRU eviction: expected current cluster vm/D to be present; clusters: %v", clusterKeys(tr))+ }+ if len(tr.clusters) > tr.cap {+ t.Errorf("LRU eviction: cluster count %d exceeds cap %d", len(tr.clusters), tr.cap)+ }+}++func TestStormThrottler_StormFindingPointsAtFreshestContributor(t *testing.T) {+ tr := newFindingStormThrottler()+ base := time.Now()+ a := newStormFinding("a", "vm/400", "cpu pegged")+ a.ResourceName = "vm-name-A"+ a.Node = "pve-01"+ tr.observeLocked(a, base)+ b := newStormFinding("b", "vm/400", "swap pressure")+ b.ResourceName = "vm-name-B"+ b.Node = "pve-01"+ tr.observeLocked(b, base.Add(5*time.Second))+ c := newStormFinding("c", "vm/400", "disk fill")+ c.ResourceName = "vm-name-C"+ c.Node = "pve-02"+ got := tr.observeLocked(c, base.Add(10*time.Second))+ if got == nil {+ t.Fatal("expected storm finding emission")+ }+ if got.ResourceName != "vm-name-C" {+ t.Errorf("freshest resource name: want vm-name-C, got %q", got.ResourceName)+ }+ if got.Node != "pve-02" {+ t.Errorf("freshest node: want pve-02, got %q", got.Node)+ }+}++func TestStormThrottler_ResolveSentinelAfterQuietWindow(t *testing.T) {+ tr := newFindingStormThrottler()+ base := time.Now()+ // Cross threshold so the cluster has an emitted storm finding.+ tr.observeLocked(newStormFinding("a", "vm/500", "x"), base)+ tr.observeLocked(newStormFinding("b", "vm/500", "y"), base.Add(1*time.Second))+ emit := tr.observeLocked(newStormFinding("c", "vm/500", "z"), base.Add(2*time.Second))+ if emit == nil {+ t.Fatal("expected storm finding emission to seed lastEmittedAt")+ }+ // Long pause — well past 2 * stormWindow with no further activity.+ // Next emission within the same cluster should return a resolve+ // sentinel (ResolvedAt non-nil, ID set to the emitted storm finding).+ resolve := tr.observeLocked(newStormFinding("d", "vm/500", "much later"), base.Add(2*stormWindow+30*time.Second))+ if resolve == nil {+ t.Fatal("expected resolve sentinel after quiet window, got nil")+ }+ if resolve.ResolvedAt == nil {+ t.Errorf("resolve sentinel: want ResolvedAt non-nil, got nil")+ }+ if resolve.ID != stormFindingIDPrefix+"vm/500" {+ t.Errorf("resolve sentinel ID: want %q, got %q", stormFindingIDPrefix+"vm/500", resolve.ID)+ }+}++func TestStormThrottler_RefreshesStormFindingWhileAboveThreshold(t *testing.T) {+ tr := newFindingStormThrottler()+ base := time.Now()+ tr.observeLocked(newStormFinding("a", "vm/600", "x"), base)+ tr.observeLocked(newStormFinding("b", "vm/600", "y"), base.Add(1*time.Second))+ first := tr.observeLocked(newStormFinding("c", "vm/600", "z"), base.Add(2*time.Second))+ if first == nil {+ t.Fatal("expected first storm finding emission")+ }+ // 4th distinct emission while still inside the window should also+ // return the storm finding (with incremented count) so the caller+ // can re-enter it through Add — Add dedups on the stable ID.+ second := tr.observeLocked(newStormFinding("d", "vm/600", "w"), base.Add(3*time.Second))+ if second == nil {+ t.Fatal("expected refresh storm finding on 4th emission, got nil")+ }+ if second.ID != first.ID {+ t.Errorf("refresh storm finding: want same ID %q, got %q", first.ID, second.ID)+ }+ if !strings.Contains(second.Evidence, "emissions=4") {+ t.Errorf("refresh storm finding evidence: want emissions=4, got %q", second.Evidence)+ }+}++func TestStormThrottler_NilReceiverNoPanic(t *testing.T) {+ var tr *findingStormThrottler+ if got := tr.observeLocked(newStormFinding("a", "vm/700", "x"), time.Now()); got != nil {+ t.Errorf("nil throttler: want nil result, got %+v", got)+ }+}++func clusterKeys(tr *findingStormThrottler) []string {+ tr.mu.Lock()+ defer tr.mu.Unlock()+ keys := make([]string, 0, len(tr.clusters))+ for k := range tr.clusters {+ keys = append(keys, k)+ }+ return keys+}