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(ai): enhance patrol with dynamic thresholds and stale finding cleanup
rcourtman3eb5cb4f789d
diff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.goindex 9fb46144b9..6a7b0ce4d2 100644--- a/internal/ai/patrol_ai.go+++ b/internal/ai/patrol_ai.go@@ -1017,7 +1017,7 @@ func (p *PatrolService) buildSeedContext(state models.StateSnapshot, scope *Patrsb.WriteString(p.seedBackupAnalysis(state, now))sb.WriteString(p.seedHealthAndAlerts(state, scopedSet, cfg, now))sb.WriteString(p.seedIntelligenceContext(intel, now))- findingsCtx, seededFindingIDs := p.seedFindingsAndContext(scope)+ findingsCtx, seededFindingIDs := p.seedFindingsAndContext(scope, state)sb.WriteString(findingsCtx)if scope != nil {@@ -1852,7 +1852,7 @@ func (p *PatrolService) seedIntelligenceContext(intel seedIntelligence, now time}// seedFindingsAndContext builds the thresholds, active findings, dismissed findings, and user notes sections.-func (p *PatrolService) seedFindingsAndContext(scope *PatrolScope) (string, []string) {+func (p *PatrolService) seedFindingsAndContext(scope *PatrolScope, state models.StateSnapshot) (string, []string) {var sb strings.Builder// --- Alert Thresholds ---@@ -1867,6 +1867,26 @@ func (p *PatrolService) seedFindingsAndContext(scope *PatrolScope) (string, []stsb.WriteString(fmt.Sprintf("- Storage warning: %.0f%%, critical: %.0f%%\n", thresholds.StorageWarning, thresholds.StorageCritical))sb.WriteString("Note: The real-time alerting system monitors these thresholds continuously. Do NOT report findings for threshold breaches — focus on trends, capacity planning, and issues alerts cannot detect.\n\n")+ // Build set of known resource IDs/names for existence checks+ knownResources := make(map[string]bool)+ for _, n := range state.Nodes {+ knownResources[n.ID] = true+ knownResources[n.Name] = true+ }+ for _, vm := range state.VMs {+ knownResources[vm.ID] = true+ knownResources[vm.Name] = true+ }+ for _, ct := range state.Containers {+ knownResources[ct.ID] = true+ knownResources[ct.Name] = true+ }+ for _, s := range state.Storage {+ knownResources[s.ID] = true+ knownResources[s.Name] = true+ }+ stateHasResources := len(knownResources) > 0+// --- Active Findings to Re-check ---activeFindings := p.findings.GetActive(FindingSeverityInfo)var seededFindingIDs []string@@ -1874,6 +1894,25 @@ func (p *PatrolService) seedFindingsAndContext(scope *PatrolScope) (string, []stsb.WriteString("# Active Findings to Re-check\n")sb.WriteString("Verify whether these findings are still valid. Resolve any that are no longer issues.\n\n")for _, f := range activeFindings {+ // Auto-resolve findings for resources that no longer exist+ if stateHasResources && !knownResources[f.ResourceID] && !knownResources[f.ResourceName] {+ if ok := p.findings.ResolveWithReason(f.ID, "Resource no longer exists in infrastructure"); ok {+ // Notify unified store+ p.mu.RLock()+ resolveUnified := p.unifiedFindingResolver+ p.mu.RUnlock()+ if resolveUnified != nil {+ resolveUnified(f.ID)+ }+ log.Info().+ Str("finding_id", f.ID).+ Str("resource_id", f.ResourceID).+ Str("resource_name", f.ResourceName).+ Msg("AI Patrol: Auto-resolved finding for deleted resource")+ }+ continue+ }+sb.WriteString(fmt.Sprintf("- [%s] %s on %s (ID: %s, Severity: %s, Detected: %s)\n",f.ID, f.Title, f.ResourceName, f.ResourceID, f.Severity, f.DetectedAt.Format("2006-01-02 15:04")))if f.UserNote != "" {diff --git a/internal/ai/patrol_findings.go b/internal/ai/patrol_findings.goindex 71b5fe7d8f..dde965b73f 100644--- a/internal/ai/patrol_findings.go+++ b/internal/ai/patrol_findings.go@@ -11,6 +11,7 @@ import ("sync""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline""github.com/rcourtman/pulse-go-rewrite/internal/ai/remediation""github.com/rcourtman/pulse-go-rewrite/internal/ai/tools""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -612,18 +613,77 @@ func (a *patrolFindingCreatorAdapter) CreateFinding(input tools.PatrolFindingInpreturn id, isNew, nil}-// isActionable validates a finding against current metrics (inline version of the old-// validateAIFindings + isActionableFinding logic).-func (a *patrolFindingCreatorAdapter) isActionable(f *Finding) bool {- // Always allow critical findings- if f.Severity == FindingSeverityCritical {- return true+// actionabilityThreshold returns the threshold below which a metric finding is rejected as noise.+// It reads user-configured PatrolThresholds (Watch level = lowest alarm tier) and falls back+// to hardcoded defaults (50/60/70) if the threshold is zero or unset.+// The resourceType parameter selects between node-level and guest-level thresholds where both exist.+func (a *patrolFindingCreatorAdapter) actionabilityThreshold(metric, resourceType string) float64 {+ a.patrol.mu.RLock()+ thresholds := a.patrol.thresholds+ a.patrol.mu.RUnlock()++ isNode := resourceType == "node"++ switch metric {+ case "cpu":+ // Only node-level CPU threshold exists; used for all resource types.+ if thresholds.NodeCPUWatch > 0 {+ return thresholds.NodeCPUWatch+ }+ return 50.0+ case "memory":+ if isNode {+ if thresholds.NodeMemWatch > 0 {+ return thresholds.NodeMemWatch+ }+ } else {+ if thresholds.GuestMemWatch > 0 {+ return thresholds.GuestMemWatch+ }+ }+ return 60.0+ case "disk":+ if thresholds.GuestDiskWatch > 0 {+ return thresholds.GuestDiskWatch+ }+ return 70.0+ case "storage":+ if thresholds.StorageWatch > 0 {+ return thresholds.StorageWatch+ }+ return 70.0+ default:+ return 50.0}- // Always allow backup and reliability findings- if f.Category == FindingCategoryBackup || f.Category == FindingCategoryReliability {- return true+}++// isBaselineAnomaly checks if the given value is anomalously high compared to the learned+// baseline for this resource/metric. Returns true only for upward anomalies (rising above+// baseline), since dropping usage is not concerning. Returns false if baseline data is+// unavailable or insufficient.+func (a *patrolFindingCreatorAdapter) isBaselineAnomaly(resourceID, metric string, value float64) bool {+ a.patrol.mu.RLock()+ store := a.patrol.baselineStore+ a.patrol.mu.RUnlock()++ if store == nil {+ return false}+ severity, _, bl := store.CheckAnomaly(resourceID, metric, value)+ if severity == baseline.AnomalyNone || bl == nil {+ return false+ }++ // Only flag upward anomalies (value above baseline mean)+ return value > bl.Mean+}++// isActionable validates a finding against current metrics (inline version of the old+// validateAIFindings + isActionableFinding logic).+// Uses user-configured thresholds from PatrolThresholds and baseline anomaly detection+// as a second-chance check for findings below the threshold but statistically anomalous.+func (a *patrolFindingCreatorAdapter) isActionable(f *Finding) bool {// Build resource metrics lookup from current stateresourceMetrics := make(map[string]map[string]float64)for _, n := range a.state.Nodes {@@ -653,12 +713,29 @@ func (a *patrolFindingCreatorAdapter) isActionable(f *Finding) bool {resourceMetrics[s.Name] = m}+ // Reject findings for resources that no longer exist in the current infrastructure.+ // Only enforce when we have state data (avoid rejecting during empty/error states).metrics, hasMetrics := resourceMetrics[f.ResourceID]if !hasMetrics {metrics, hasMetrics = resourceMetrics[f.ResourceName]}+ stateHasResources := len(a.state.Nodes) > 0 || len(a.state.VMs) > 0 || len(a.state.Containers) > 0 || len(a.state.Storage) > 0+ if !hasMetrics && stateHasResources {+ // Resource not found — it may have been deleted. Reject the finding.+ return false+ }++ // Allow critical findings without metric threshold checks+ if f.Severity == FindingSeverityCritical {+ return true+ }+ // Allow backup and reliability findings without metric threshold checks+ if f.Category == FindingCategoryBackup || f.Category == FindingCategoryReliability {+ return true+ }+if !hasMetrics {- return true // benefit of doubt+ return true // empty state — benefit of doubt}key := strings.ToLower(f.Key)@@ -666,22 +743,35 @@ func (a *patrolFindingCreatorAdapter) isActionable(f *Finding) bool {// CPU checkif strings.Contains(key, "cpu") || strings.Contains(titleLower, "cpu") {- if cpu, ok := metrics["cpu"]; ok && cpu < 50.0 {+ if cpu, ok := metrics["cpu"]; ok && cpu < a.actionabilityThreshold("cpu", f.ResourceType) {+ // Below threshold — check if anomalous (statistically unusual spike)+ if a.isBaselineAnomaly(f.ResourceID, "cpu", cpu) {+ return true+ }return false}}// Memory checkif strings.Contains(key, "memory") || strings.Contains(key, "mem") || strings.Contains(titleLower, "memory") {- if mem, ok := metrics["memory"]; ok && mem < 60.0 {+ if mem, ok := metrics["memory"]; ok && mem < a.actionabilityThreshold("memory", f.ResourceType) {+ if a.isBaselineAnomaly(f.ResourceID, "memory", mem) {+ return true+ }return false}}// Disk/storage checkif strings.Contains(key, "disk") || strings.Contains(key, "storage") || strings.Contains(titleLower, "disk") {- if disk, ok := metrics["disk"]; ok && disk < 70.0 {+ if disk, ok := metrics["disk"]; ok && disk < a.actionabilityThreshold("disk", f.ResourceType) {+ if a.isBaselineAnomaly(f.ResourceID, "disk", disk) {+ return true+ }return false}- if usage, ok := metrics["usage"]; ok && usage < 70.0 {+ if usage, ok := metrics["usage"]; ok && usage < a.actionabilityThreshold("storage", f.ResourceType) {+ if a.isBaselineAnomaly(f.ResourceID, "storage", usage) {+ return true+ }return false}}@@ -814,6 +904,49 @@ func normalizeFindingKey(key string) string {return strings.Trim(b.String(), "-")}+// recoverStuckInvestigations detects findings stuck in "running" state for longer than+// the investigation timeout and resets them to "failed/timed_out" so they can be retried.+// This handles the case where an investigation goroutine panics or is killed without+// properly updating the finding status.+func (p *PatrolService) recoverStuckInvestigations() {+ if p.findings == nil {+ return+ }+ const stuckThreshold = 15 * time.Minute // investigation timeout is 10min; allow 5min grace+ active := p.findings.GetActive(FindingSeverityWarning)+ recovered := 0+ for _, f := range active {+ if f.InvestigationStatus != string(InvestigationStatusRunning) {+ continue+ }+ if f.LastInvestigatedAt == nil {+ continue+ }+ if time.Since(*f.LastInvestigatedAt) < stuckThreshold {+ continue+ }+ // This finding has been "running" for too long — reset it+ p.findings.UpdateInvestigation(+ f.ID,+ f.InvestigationSessionID,+ string(InvestigationStatusFailed),+ string(InvestigationOutcomeTimedOut),+ f.LastInvestigatedAt,+ f.InvestigationAttempts,+ )+ recovered+++ log.Warn().+ Str("finding_id", f.ID).+ Str("resource", f.ResourceName).+ Time("last_investigated", *f.LastInvestigatedAt).+ Msg("AI Patrol: Recovered stuck investigation (exceeded timeout)")+ }+ if recovered > 0 {+ log.Info().Int("recovered", recovered).+ Msg("AI Patrol: Recovered stuck investigations")+ }+}+// retryTimedOutInvestigations re-triggers investigation for findings that failed due to timeout.// Called at the end of each patrol run to give timed-out investigations another chance// without waiting for the full 1-hour cooldown.@@ -895,11 +1028,24 @@ func (p *PatrolService) MaybeInvestigateFinding(f *Finding) {InvestigationAttempts: f.InvestigationAttempts,}- // Trigger investigation in background with a timeout to prevent indefinite runs+ // Trigger investigation in background with a timeout to prevent indefinite runs.+ // Track with WaitGroup so graceful shutdown can wait for completion.+ p.investigationWg.Add(1)go func() {+ defer p.investigationWg.Done()++ // Re-read autonomy level at execution time to avoid using a stale value+ // captured before the goroutine was scheduled.+ currentCfg := aiService.GetConfig()+ if currentCfg == nil {+ log.Warn().Str("finding_id", f.ID).Msg("AI config unavailable at investigation start, aborting")+ return+ }+ currentAutonomy := currentCfg.GetPatrolAutonomyLevel()+ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)defer cancel()- if err := orchestrator.InvestigateFinding(ctx, invFinding, autonomyLevel); err != nil {+ if err := orchestrator.InvestigateFinding(ctx, invFinding, currentAutonomy); err != nil {log.Error().Err(err).Str("finding_id", f.ID).diff --git a/internal/ai/patrol_findings_additional_test.go b/internal/ai/patrol_findings_additional_test.goindex a55828d6a3..54c10f0b63 100644--- a/internal/ai/patrol_findings_additional_test.go+++ b/internal/ai/patrol_findings_additional_test.go@@ -205,3 +205,281 @@ func TestPatrolService_ForcePatrol_RecordsRun(t *testing.T) {t.Fatalf("expected ForcePatrol to record a run (count stayed at %d)", before)}++// --- Configurable threshold tests ---++func TestActionabilityThreshold_DefaultFallback(t *testing.T) {+ // Zero thresholds → should fall back to old defaults (50/60/70)+ ps := NewPatrolService(nil, nil)+ ps.thresholds = PatrolThresholds{} // all zero++ adapter := newPatrolFindingCreatorAdapter(ps, models.StateSnapshot{})++ if got := adapter.actionabilityThreshold("cpu", "node"); got != 50.0 {+ t.Errorf("cpu threshold = %v, want 50.0", got)+ }+ if got := adapter.actionabilityThreshold("memory", "vm"); got != 60.0 {+ t.Errorf("guest memory threshold = %v, want 60.0", got)+ }+ if got := adapter.actionabilityThreshold("memory", "node"); got != 60.0 {+ t.Errorf("node memory threshold (zero → default) = %v, want 60.0", got)+ }+ if got := adapter.actionabilityThreshold("disk", "vm"); got != 70.0 {+ t.Errorf("disk threshold = %v, want 70.0", got)+ }+ if got := adapter.actionabilityThreshold("storage", "storage"); got != 70.0 {+ t.Errorf("storage threshold = %v, want 70.0", got)+ }+}++func TestActionabilityThreshold_CustomThresholds(t *testing.T) {+ ps := NewPatrolService(nil, nil)+ ps.thresholds = PatrolThresholds{+ NodeCPUWatch: 65,+ NodeMemWatch: 70,+ GuestMemWatch: 72,+ GuestDiskWatch: 80,+ StorageWatch: 75,+ }++ adapter := newPatrolFindingCreatorAdapter(ps, models.StateSnapshot{})++ if got := adapter.actionabilityThreshold("cpu", "node"); got != 65.0 {+ t.Errorf("cpu threshold = %v, want 65.0", got)+ }+ if got := adapter.actionabilityThreshold("memory", "node"); got != 70.0 {+ t.Errorf("node memory threshold = %v, want 70.0", got)+ }+ if got := adapter.actionabilityThreshold("memory", "vm"); got != 72.0 {+ t.Errorf("guest memory threshold = %v, want 72.0", got)+ }+ if got := adapter.actionabilityThreshold("memory", "container"); got != 72.0 {+ t.Errorf("container memory threshold = %v, want 72.0 (guest)", got)+ }+ if got := adapter.actionabilityThreshold("disk", "vm"); got != 80.0 {+ t.Errorf("disk threshold = %v, want 80.0", got)+ }+ if got := adapter.actionabilityThreshold("storage", "storage"); got != 75.0 {+ t.Errorf("storage threshold = %v, want 75.0", got)+ }+}++func TestIsActionable_CustomThresholdsRespected(t *testing.T) {+ // Set a high CPU watch threshold (85%) - value at 60% should be rejected+ ps := NewPatrolService(nil, nil)+ ps.thresholds = PatrolThresholds{NodeCPUWatch: 85}++ state := models.StateSnapshot{+ Nodes: []models.Node{+ {ID: "node-1", Name: "node-1", CPU: 0.60, Memory: models.Memory{Usage: 30}},+ },+ }+ adapter := newPatrolFindingCreatorAdapter(ps, state)++ finding := &Finding{+ Key: "cpu-high",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryPerformance,+ ResourceID: "node-1",+ ResourceType: "node",+ Title: "High CPU usage",+ }++ if adapter.isActionable(finding) {+ t.Fatal("finding at 60% CPU should be rejected with 85% threshold")+ }++ // Now set lower threshold (40%) - same 60% value should pass+ ps.thresholds = PatrolThresholds{NodeCPUWatch: 40}+ adapter2 := newPatrolFindingCreatorAdapter(ps, state)++ if !adapter2.isActionable(finding) {+ t.Fatal("finding at 60% CPU should be accepted with 40% threshold")+ }+}++func TestIsActionable_NodeMemoryUsesNodeThreshold(t *testing.T) {+ // A node at 78% memory should pass with NodeMemWatch=75 but would fail+ // with GuestMemWatch=80. This test verifies the correct threshold is selected.+ ps := NewPatrolService(nil, nil)+ ps.thresholds = PatrolThresholds{+ NodeMemWatch: 75, // node threshold: 75%+ GuestMemWatch: 80, // guest threshold: 80%+ }++ state := models.StateSnapshot{+ Nodes: []models.Node{+ {ID: "node-1", Name: "node-1", CPU: 0.40, Memory: models.Memory{Used: 78, Total: 100}},+ },+ }+ adapter := newPatrolFindingCreatorAdapter(ps, state)++ nodeFinding := &Finding{+ Key: "memory-high",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryPerformance,+ ResourceID: "node-1",+ ResourceType: "node",+ Title: "High memory usage",+ }++ // 78% > NodeMemWatch (75%) → should be actionable+ if !adapter.isActionable(nodeFinding) {+ t.Fatal("node at 78% memory should pass with NodeMemWatch=75")+ }++ // Same memory level on a VM should be rejected (78% < GuestMemWatch 80%)+ vmState := models.StateSnapshot{+ VMs: []models.VM{+ {ID: "vm-1", Name: "vm-1", CPU: 0.40, Memory: models.Memory{Usage: 78}},+ },+ }+ vmAdapter := newPatrolFindingCreatorAdapter(ps, vmState)++ vmFinding := &Finding{+ Key: "memory-high",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryPerformance,+ ResourceID: "vm-1",+ ResourceType: "vm",+ Title: "High memory usage",+ }++ // 78% < GuestMemWatch (80%) → should be rejected+ if vmAdapter.isActionable(vmFinding) {+ t.Fatal("VM at 78% memory should be rejected with GuestMemWatch=80")+ }+}++func TestIsBaselineAnomaly_NoStore(t *testing.T) {+ // No baseline store → always returns false (safe fallback)+ ps := NewPatrolService(nil, nil)+ adapter := newPatrolFindingCreatorAdapter(ps, models.StateSnapshot{})++ if adapter.isBaselineAnomaly("node-1", "cpu", 45.0) {+ t.Fatal("expected false when no baseline store is set")+ }+}++func TestIsActionable_AnomalyBypass(t *testing.T) {+ // Set up a baseline store with learned baselines.+ // CPU at 45% is below the 50% default threshold, but is anomalous+ // relative to a baseline of mean=20, stddev=5 (z-score = 5).+ ps := NewPatrolService(nil, nil)+ ps.thresholds = PatrolThresholds{} // defaults: CPU watch = 0 → fallback 50%++ bsCfg := DefaultBaselineConfig()+ bsCfg.MinSamples = 5 // Lower for test+ bs := NewBaselineStore(bsCfg)++ // Learn a baseline: mean ~20%, stddev ~2.5%+ points := make([]BaselineMetricPoint, 50)+ for i := 0; i < 50; i++ {+ points[i] = BaselineMetricPoint{Value: 18.0 + float64(i%5), Timestamp: time.Now().Add(-time.Duration(i) * time.Hour)}+ }+ _ = bs.Learn("node-1", "node", "cpu", points)+ ps.baselineStore = bs++ state := models.StateSnapshot{+ Nodes: []models.Node{+ {ID: "node-1", Name: "node-1", CPU: 0.45, Memory: models.Memory{Usage: 30}},+ },+ }+ adapter := newPatrolFindingCreatorAdapter(ps, state)++ finding := &Finding{+ Key: "cpu-high",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryPerformance,+ ResourceID: "node-1",+ Title: "High CPU usage",+ }++ // CPU at 45% is below 50% threshold BUT is anomalous (z-score ~5+)+ if !adapter.isActionable(finding) {+ t.Fatal("finding below threshold but anomalous should be allowed through")+ }+}++func TestIsActionable_BelowThresholdNoAnomaly(t *testing.T) {+ // CPU at 45% below 50% threshold, baseline mean is also ~45% → not anomalous → rejected.+ ps := NewPatrolService(nil, nil)+ ps.thresholds = PatrolThresholds{} // defaults++ bsCfg := DefaultBaselineConfig()+ bsCfg.MinSamples = 5+ bs := NewBaselineStore(bsCfg)++ // Learn a baseline: mean ~45%, close to current value+ points := make([]BaselineMetricPoint, 50)+ for i := 0; i < 50; i++ {+ points[i] = BaselineMetricPoint{Value: 43.0 + float64(i%5), Timestamp: time.Now().Add(-time.Duration(i) * time.Hour)}+ }+ _ = bs.Learn("node-1", "node", "cpu", points)+ ps.baselineStore = bs++ state := models.StateSnapshot{+ Nodes: []models.Node{+ {ID: "node-1", Name: "node-1", CPU: 0.45, Memory: models.Memory{Usage: 30}},+ },+ }+ adapter := newPatrolFindingCreatorAdapter(ps, state)++ finding := &Finding{+ Key: "cpu-high",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryPerformance,+ ResourceID: "node-1",+ Title: "High CPU usage",+ }++ if adapter.isActionable(finding) {+ t.Fatal("finding below threshold with no anomaly should be rejected")+ }+}++func TestIsActionable_EscapeHatchesPreserved(t *testing.T) {+ ps := NewPatrolService(nil, nil)+ state := models.StateSnapshot{+ Nodes: []models.Node{+ {ID: "node-1", Name: "node-1", CPU: 0.10, Memory: models.Memory{Usage: 10}},+ },+ }+ adapter := newPatrolFindingCreatorAdapter(ps, state)++ // Critical severity always passes+ critical := &Finding{+ Key: "cpu-high",+ Severity: FindingSeverityCritical,+ Category: FindingCategoryPerformance,+ ResourceID: "node-1",+ Title: "Critical CPU",+ }+ if !adapter.isActionable(critical) {+ t.Fatal("critical finding should always pass")+ }++ // Backup category always passes+ backup := &Finding{+ Key: "backup-missing",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryBackup,+ ResourceID: "node-1",+ Title: "Missing backup",+ }+ if !adapter.isActionable(backup) {+ t.Fatal("backup finding should always pass")+ }++ // Reliability category always passes+ reliability := &Finding{+ Key: "node-offline",+ Severity: FindingSeverityWarning,+ Category: FindingCategoryReliability,+ ResourceID: "node-1",+ Title: "Node offline",+ }+ if !adapter.isActionable(reliability) {+ t.Fatal("reliability finding should always pass")+ }+}