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): shadow-mode reducer feed with always-on divergence telemetry
rcourtmanbfc1a81867e4
diff --git a/docs/release-control/v6/internal/records/alert-lifecycle-contract-coverage-2026-08-26.md b/docs/release-control/v6/internal/records/alert-lifecycle-contract-coverage-2026-08-26.mdindex 4ea7e70b61..39bf6f9cea 100644--- a/docs/release-control/v6/internal/records/alert-lifecycle-contract-coverage-2026-08-26.md+++ b/docs/release-control/v6/internal/records/alert-lifecycle-contract-coverage-2026-08-26.md@@ -93,5 +93,19 @@ StartTime parity additionally exercises the lifecycleFirstMatched fix incomposition. Deferred: the backup-offline deferral sub-policy(MaxDeferralSeconds / PostGraceSeconds).-Remaining for later slices: the backup-offline deferral sub-policy and a-shadow-mode runtime feed.+Capstone (2026-08-26): the shadow-mode runtime feed. The reducer now runs+continuously inside the live manager against the same production+observations — the canonical lifecycle path (connectivity, powered-state,+discrete-state kinds), the poll-driven recovery paths, manual+acknowledge/unacknowledge/clear, with persisted-alert seeding at enable —+and every state disagreement is counted (Manager.ShadowDivergences) and+recorded in the alert event log as a shadow_divergence event+(rate-limited per key; the reducer resyncs to the manager after each+report so one divergence yields one event, including divergences from+unhooked mutations). Enabled by the monitoring bootstrap next to the+event log. The divergence rate is the go/no-go evidence for each Phase 2+family cutover.++Remaining: the backup-offline deferral sub-policy (the shadow feed maps+its hold to operator suppression, which is behavior-equivalent while+uncharacterized), and Phase 2 itself.diff --git a/internal/alerts/active_lifecycle.go b/internal/alerts/active_lifecycle.goindex 23e61016a5..b0824493ea 100644--- a/internal/alerts/active_lifecycle.go+++ b/internal/alerts/active_lifecycle.go@@ -99,6 +99,7 @@ func (m *Manager) clearAlert(alertID string) {m.mu.Lock()alert, exists := m.getActiveAlertNoLock(alertID)if exists {+ m.shadowForgetAlertNoLock(alert)m.removeActiveAlertNoLock(alertID)}m.mu.Unlock()@@ -149,6 +150,7 @@ func (m *Manager) AcknowledgeAlert(alertID, user string) error {user: user,time: now,})+ m.shadowAcknowledgeNoLock(alert, user, now)alertCopy := alert.Clone()m.mu.Unlock()@@ -189,6 +191,7 @@ func (m *Manager) UnacknowledgeAlert(alertID string) error {m.setActiveAlertNoLock(key, alert)m.deleteAckRecordNoLock(alert, alertID)+ m.shadowUnacknowledgeNoLock(alert)alertCopy := alert.Clone()m.mu.Unlock()@@ -602,6 +605,7 @@ func (m *Manager) clearResourceOfflineAlert(resourceID, resourceName, host, resom.mu.Lock()defer m.mu.Unlock()+ defer m.shadowObserveRecoveryNoLock(resourceID, canonicalConnectivitySpecID(resourceID), alertID, requiredRecoveryCount)if count, exists := m.offlineConfirmations[resourceID]; exists && count > 0 {log.Debug().@@ -680,6 +684,7 @@ func (m *Manager) clearAlertNoLock(alertID string) {recordAlertResolved(alert)}+ m.shadowForgetAlertNoLock(alert)m.removeActiveAlertNoLock(alertID)resolvedAlert := m.newResolvedAlert(alert, time.Now(), nil)diff --git a/internal/alerts/canonical_lifecycle.go b/internal/alerts/canonical_lifecycle.goindex be86323da0..b6a59743bf 100644--- a/internal/alerts/canonical_lifecycle.go+++ b/internal/alerts/canonical_lifecycle.go@@ -3,6 +3,7 @@ package alertsimport ("time"+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs""github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"@@ -356,6 +357,17 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlertstorageKey := canonicalTrackingKeyForSpec(params.Spec, params.AlertID)trackingKey := storageKey+ // Shadow feed: after this evaluation settles (any exit), replay the same+ // observation through the shadow reducer and compare outcomes. Runs+ // before the deferred unlock (LIFO), so it still holds m.mu.+ var shadowIntent *reducer.DiscreteIntent+ shadowEligible := false+ defer func() {+ if shadowEligible {+ m.shadowObserveLifecycleNoLock(params.Spec, params.Evidence, shadowIntent, storageKey)+ }+ }()+var existing *Alertif current, ok := m.getActiveAlertNoLock(storageKey); ok {existing = current@@ -384,6 +396,8 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlertreturn alertspecs.EvaluationResult{}, false}+ shadowEligible = true+// Persist the canonical confirmation state before applying intent policy.// Grace and operator context are an additional gate; they must not prevent// the underlying evaluator from reaching its configured confirmation count.@@ -412,6 +426,12 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlertif intentSignal != "" && existing == nil {conditionActive := result.State.State == alertspecs.AlertStatePending || result.State.State == alertspecs.AlertStateFiringdecision := m.evaluateIntentNoLock(params.Spec.ResourceID, string(params.Spec.ResourceType), intentSignal, storageKey, params.Evidence.ObservedAt, conditionActive, params.IntentBackup)+ shadowIntent = &reducer.DiscreteIntent{+ Explicit: decision.Effective.Explicit,+ GraceSeconds: decision.Effective.GraceSeconds,+ OperatorSuppressed: decision.Suppressed,+ OperatorReason: decision.Reason,+ }if decision.StateChanged {m.saveActiveAlertsAsync("lifecycle intent state")}diff --git a/internal/alerts/connection.go b/internal/alerts/connection.goindex a0ff31c25b..339cb8cc2b 100644--- a/internal/alerts/connection.go+++ b/internal/alerts/connection.go@@ -294,6 +294,7 @@ func (m *Manager) clearConnectionDegradedAlert(snap ConnectionSnapshot) {m.mu.Lock()defer m.mu.Unlock()+ defer m.shadowObserveRecoveryNoLock(snap.ID, canonicalDiscreteStateSpecID(snap.ID, connectionDegradedStateKey), alertID, offlineRecoveryConfirmationsDefault)if m.connectionDegradedCount[snap.ID] > 0 {log.Debug().diff --git a/internal/alerts/eventlog/eventlog.go b/internal/alerts/eventlog/eventlog.goindex 57d9b06a5c..66a78d1878 100644--- a/internal/alerts/eventlog/eventlog.go+++ b/internal/alerts/eventlog/eventlog.go@@ -37,6 +37,10 @@ const (TypeNotificationDispatched = "notification_dispatched"TypeNotificationDeferred = "notification_deferred"TypeNotificationSuppressed = "notification_suppressed"+ // TypeShadowDivergence records the shadow reducer disagreeing with the+ // live manager on an alert's state — the always-on parity signal+ // (docs/ALERT_ENGINE_EVOLUTION.md, Phase 1).+ TypeShadowDivergence = "shadow_divergence")// Event is one immutable alert event.diff --git a/internal/alerts/manager.go b/internal/alerts/manager.goindex 21c5558a2d..911d8febea 100644--- a/internal/alerts/manager.go+++ b/internal/alerts/manager.go@@ -112,6 +112,10 @@ type Manager struct {// Nil until EnableEventLog/SetEventLog; recording is then a no-op.eventLog atomic.Pointer[eventlog.Store]+ // Shadow-mode reducer feed (Phase 1 capstone). Nil until+ // EnableShadowFeed; all access is under m.mu.+ shadow *shadowFeed+// Cached timezone for quiet hoursquietHoursLoc *time.Locationnow func() time.Timediff --git a/internal/alerts/node.go b/internal/alerts/node.goindex 24d2c664ff..5d9dc710fd 100644--- a/internal/alerts/node.go+++ b/internal/alerts/node.go@@ -291,6 +291,7 @@ func (m *Manager) clearNodeOfflineAlert(node models.Node) {m.mu.Lock()defer m.mu.Unlock()+ defer m.shadowObserveRecoveryNoLock(node.ID, canonicalConnectivitySpecID(node.ID), alertID, offlineRecoveryConfirmationsDefault)// Reset offline count when node comes back onlineif m.nodeOfflineCount[node.ID] > 0 {diff --git a/internal/alerts/reducer/reducer.go b/internal/alerts/reducer/reducer.goindex 27480c8dd1..83849b2928 100644--- a/internal/alerts/reducer/reducer.go+++ b/internal/alerts/reducer/reducer.go@@ -399,3 +399,32 @@ func (s *State) ApplyMetric(signal MetricSignal, rule MetricRule) []Event {// reducer mirrors that so parity diffs stay exact.return nil}++// SeedFiringIncident installs a firing incident directly, bypassing the+// transition functions. Shadow mode uses it to align the reducer with+// pre-existing manager state (persisted-alert restore, divergence resync);+// it is not part of normal evaluation.+func (s *State) SeedFiringIncident(resourceID, subKey string, severity Severity, startedAt time.Time, acknowledged bool) {+ key := incidentKey(resourceID, subKey)+ incident := &Incident{+ ResourceID: resourceID,+ Key: subKey,+ State: StateFiring,+ Severity: severity,+ StartedAt: startedAt,+ Confirmations: 1,+ Acknowledged: acknowledged,+ LastObservedAt: startedAt,+ }+ s.incidents[key] = incident+ if acknowledged {+ s.acks[key] = ackRecord{At: startedAt}+ }+}++// 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))+}diff --git a/internal/alerts/shadow.go b/internal/alerts/shadow.gonew file mode 100644index 0000000000..8c9de4ed44--- /dev/null+++ b/internal/alerts/shadow.go@@ -0,0 +1,297 @@+package alerts++// Shadow-mode runtime feed (docs/ALERT_ENGINE_EVOLUTION.md, Phase 1+// capstone): the deterministic reducer runs continuously against the same+// production observations the live manager evaluates, and every+// disagreement on an alert's state is counted and recorded in the alert+// event log as a shadow_divergence event. This converts the parity+// harness's test-time guarantee into an always-on invariant, and its+// divergence rate is the go/no-go evidence for each Phase 2 family+// cutover.+//+// Scope: the discrete confirmation family (connectivity, powered-state,+// discrete-state kinds) through evaluateCanonicalLifecycleAlert, the+// poll-driven recovery paths, manual acknowledge/unacknowledge/clear, and+// persisted-alert seeding. After reporting a divergence the reducer is+// resynced to the manager's state for that key, so one divergence+// produces one event rather than a stream — including divergences caused+// by manager mutations the feed does not observe.+//+// All shadow methods are NoLock: callers hold m.mu.++import (+ "fmt"+ "strings"+ "sync/atomic"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog"+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"+)++// shadowReportMinInterval rate-limits divergence events per key; the+// counter still counts every divergence.+const shadowReportMinInterval = 10 * time.Minute++type shadowFeed struct {+ state *reducer.State+ divergences atomic.Int64+ lastReported map[string]time.Time+}++// EnableShadowFeed starts the shadow reducer, seeded from the currently+// active canonical alerts so a restart does not read as mass divergence.+// The monitoring bootstrap calls this once per manager, after+// EnableEventLog.+func (m *Manager) EnableShadowFeed() {+ if m == nil {+ return+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ feed := &shadowFeed{+ state: reducer.NewState(),+ lastReported: make(map[string]time.Time),+ }+ for _, alert := range m.activeAlerts {+ if alert == nil {+ continue+ }+ backfillCanonicalIdentity(alert)+ if alert.ResourceID == "" || alert.CanonicalSpecID == "" {+ continue+ }+ feed.state.SeedFiringIncident(+ alert.ResourceID,+ alert.CanonicalSpecID,+ shadowSeverityForLevel(alert.Level),+ alert.StartTime,+ alert.Acknowledged,+ )+ }+ m.shadow = feed+}++// ShadowDivergences reports how many shadow divergences have been observed+// since the feed was enabled.+func (m *Manager) ShadowDivergences() int64 {+ if m == nil || m.shadow == nil {+ return 0+ }+ return m.shadow.divergences.Load()+}++// shadowDiscreteObservation derives the reducer observation for the kinds+// the shadow feed covers. The match predicates mirror the spec evaluator's+// matches() for those kinds.+func shadowDiscreteObservation(spec alertspecs.ResourceAlertSpec, evidence alertspecs.AlertEvidence) (bool, bool) {+ switch spec.Kind {+ case alertspecs.AlertSpecKindConnectivity:+ if evidence.Connectivity == nil {+ return false, false+ }+ return !evidence.Connectivity.Connected, true+ case alertspecs.AlertSpecKindPoweredState:+ if evidence.PoweredState == nil {+ return false, false+ }+ return evidence.PoweredState.Observed != evidence.PoweredState.Expected, true+ case alertspecs.AlertSpecKindDiscreteState:+ if evidence.DiscreteState == nil || spec.DiscreteState == nil {+ return false, false+ }+ observed := strings.TrimSpace(evidence.DiscreteState.Observed)+ for _, trigger := range spec.DiscreteState.TriggerStates {+ if strings.TrimSpace(trigger) == observed {+ return true, true+ }+ }+ return false, true+ default:+ return false, false+ }+}++func shadowSeverityForLevel(level AlertLevel) reducer.Severity {+ if level == AlertLevelCritical {+ return reducer.SeverityCritical+ }+ return reducer.SeverityWarning+}++func shadowSpecSeverity(spec alertspecs.ResourceAlertSpec) reducer.Severity {+ if spec.Severity == alertspecs.AlertSeverityCritical {+ return reducer.SeverityCritical+ }+ return reducer.SeverityWarning+}++func shadowSpecConfirmations(spec alertspecs.ResourceAlertSpec) int {+ if spec.ConfirmationsRequired > 0 {+ return spec.ConfirmationsRequired+ }+ switch spec.Kind {+ case alertspecs.AlertSpecKindConnectivity:+ return 3+ case alertspecs.AlertSpecKindPoweredState:+ return 2+ default:+ return 1+ }+}++// shadowObserveLifecycleNoLock feeds one canonical lifecycle observation to+// the shadow reducer and compares the outcome against the manager's state+// for the same key. intent carries the resolved intent context when the+// manager evaluated it this observation (nil otherwise).+func (m *Manager) shadowObserveLifecycleNoLock(+ spec alertspecs.ResourceAlertSpec,+ evidence alertspecs.AlertEvidence,+ intent *reducer.DiscreteIntent,+ managerAlertID string,+) {+ if m == nil || m.shadow == nil {+ return+ }+ matched, supported := shadowDiscreteObservation(spec, evidence)+ if !supported {+ return+ }+ observedAt := evidence.ObservedAt+ if observedAt.IsZero() {+ observedAt = m.policyNow()+ }+ m.shadow.state.ApplyDiscrete(reducer.DiscreteSignal{+ ResourceID: spec.ResourceID,+ Key: spec.ID,+ Matched: matched,+ Severity: shadowSpecSeverity(spec),+ ObservedAt: observedAt,+ }, reducer.DiscreteRule{+ Confirmations: shadowSpecConfirmations(spec),+ Disabled: spec.Disabled,+ Intent: intent,+ })+ m.shadowCompareNoLock(spec.ResourceID, spec.ID, managerAlertID, observedAt)+}++// shadowObserveRecoveryNoLock feeds one healthy poll from the poll-driven+// offline recovery paths (which never reach the evaluator) to the shadow+// reducer.+func (m *Manager) shadowObserveRecoveryNoLock(resourceID, specKey, managerAlertID string, requiredRecovery int) {+ if m == nil || m.shadow == nil || resourceID == "" || specKey == "" {+ return+ }+ observedAt := m.policyNow()+ m.shadow.state.ApplyDiscrete(reducer.DiscreteSignal{+ ResourceID: resourceID,+ Key: specKey,+ Matched: false,+ ObservedAt: observedAt,+ }, reducer.DiscreteRule{RecoveryConfirmations: requiredRecovery})+ m.shadowCompareNoLock(resourceID, specKey, managerAlertID, observedAt)+}++// shadowAcknowledgeNoLock mirrors a user acknowledgement into the shadow+// reducer.+func (m *Manager) shadowAcknowledgeNoLock(alert *Alert, user string, at time.Time) {+ if m == nil || m.shadow == nil || alert == nil {+ return+ }+ backfillCanonicalIdentity(alert)+ if alert.ResourceID == "" || alert.CanonicalSpecID == "" {+ return+ }+ m.shadow.state.Acknowledge(alert.ResourceID, alert.CanonicalSpecID, user, at)+}++// shadowUnacknowledgeNoLock mirrors an acknowledgement removal.+func (m *Manager) shadowUnacknowledgeNoLock(alert *Alert) {+ if m == nil || m.shadow == nil || alert == nil {+ return+ }+ backfillCanonicalIdentity(alert)+ if alert.ResourceID == "" || alert.CanonicalSpecID == "" {+ return+ }+ m.shadow.state.Unacknowledge(alert.ResourceID, alert.CanonicalSpecID)+}++// shadowForgetAlertNoLock mirrors a manual clear: the reducer drops the+// incident without treating it as an evaluated recovery.+func (m *Manager) shadowForgetAlertNoLock(alert *Alert) {+ if m == nil || m.shadow == nil || alert == nil {+ return+ }+ backfillCanonicalIdentity(alert)+ if alert.ResourceID == "" || alert.CanonicalSpecID == "" {+ return+ }+ m.shadow.state.Forget(alert.ResourceID, alert.CanonicalSpecID)+}++// shadowCompareNoLock diffs the reducer's incident for a key against the+// manager's alert, records a divergence when they disagree, and resyncs+// the reducer to the manager so a single divergence produces a single+// event.+func (m *Manager) shadowCompareNoLock(resourceID, specKey, managerAlertID string, observedAt time.Time) {+ feed := m.shadow+ if feed == nil {+ return+ }++ alert, exists := m.getActiveAlertNoLock(managerAlertID)+ managerFiring := exists && alert != nil+ incident, ok := feed.state.Incident(resourceID, specKey)+ reducerFiring := ok && incident.State == reducer.StateFiring++ severityAgrees := true+ if managerFiring && reducerFiring {+ severityAgrees = shadowSeverityForLevel(alert.Level) == incident.Severity+ }+ if managerFiring == reducerFiring && severityAgrees {+ return+ }++ feed.divergences.Add(1)++ // Resync before rate limiting so state converges even when the report+ // is suppressed.+ if managerFiring {+ feed.state.SeedFiringIncident(+ resourceID, specKey,+ shadowSeverityForLevel(alert.Level),+ alert.StartTime,+ alert.Acknowledged,+ )+ } else {+ feed.state.Forget(resourceID, specKey)+ }++ key := resourceID + "\x00" + specKey+ if last, reported := feed.lastReported[key]; reported && observedAt.Sub(last) < shadowReportMinInterval {+ return+ }+ feed.lastReported[key] = observedAt++ details := map[string]string{+ "specKey": specKey,+ "managerFiring": fmt.Sprintf("%t", managerFiring),+ "reducerFiring": fmt.Sprintf("%t", reducerFiring),+ }+ if managerFiring {+ details["managerSeverity"] = string(alert.Level)+ }+ if reducerFiring {+ details["reducerSeverity"] = string(incident.Severity)+ }+ m.recordAlertEvent(+ eventlog.TypeShadowDivergence,+ alert,+ managerAlertID,+ "shadow_divergence",+ fmt.Sprintf("Shadow reducer disagreed with the live manager (manager firing=%t, reducer firing=%t).", managerFiring, reducerFiring),+ details,+ )+}diff --git a/internal/alerts/shadow_feed_test.go b/internal/alerts/shadow_feed_test.gonew file mode 100644index 0000000000..b93e59cf2a--- /dev/null+++ b/internal/alerts/shadow_feed_test.go@@ -0,0 +1,171 @@+package alerts++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog"+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++func newShadowFeedManager(t *testing.T) *Manager {+ t.Helper()+ manager := NewManagerWithDataDir(t.TempDir(), WithoutPersistedAlertRestore())+ t.Cleanup(manager.Stop)++ store, err := eventlog.OpenInMemory()+ if err != nil {+ t.Fatalf("open in-memory event log: %v", err)+ }+ manager.SetEventLog(store)++ manager.mu.Lock()+ manager.config.Enabled = true+ manager.config.FlappingEnabled = false+ manager.mu.Unlock()+ manager.EnableShadowFeed()+ return manager+}++func shadowObserveConnectivity(t *testing.T, manager *Manager, resourceID string, connected bool, at time.Time) {+ t.Helper()+ spec, err := buildCanonicalConnectivitySpec(+ resourceID, resourceID, unifiedresources.ResourceTypePBS,+ AlertLevelCritical, 3, false,+ )+ if err != nil {+ t.Fatalf("build spec: %v", err)+ }+ if _, ok := manager.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{+ Spec: spec,+ Evidence: alertspecs.AlertEvidence{+ ObservedAt: at,+ Connectivity: &alertspecs.ConnectivityEvidence{Signal: "status", Connected: connected},+ },+ Tracking: manager.offlineConfirmations,+ TrackingKey: resourceID,+ AlertID: canonicalConnectivityStateID(resourceID),+ AlertType: "offline",+ ResourceID: resourceID,+ ResourceName: resourceID,+ Message: "shadow feed test offline",+ }); !ok {+ t.Fatal("evaluateCanonicalLifecycleAlert rejected the spec")+ }+}++func shadowDivergenceEvents(t *testing.T, manager *Manager) []eventlog.Event {+ t.Helper()+ events, err := manager.AlertEvents(eventlog.Filter{Types: []string{eventlog.TypeShadowDivergence}})+ if err != nil {+ t.Fatalf("AlertEvents: %v", err)+ }+ return events+}++// The full production cycle — confirmation-based activation, ack, unack,+// recovery-gated resolve, and re-fire — must produce zero divergences: the+// shadow reducer tracks the live manager exactly through the hooked paths.+func TestShadowFeedNoDivergenceThroughFullCycle(t *testing.T) {+ manager := newShadowFeedManager(t)+ epoch := time.Date(2026, 8, 26, 12, 0, 0, 0, time.UTC)+ resourceID := "shadow-pbs-1"++ // Fire after three offline confirmations.+ shadowObserveConnectivity(t, manager, resourceID, false, epoch)+ shadowObserveConnectivity(t, manager, resourceID, false, epoch.Add(30*time.Second))+ shadowObserveConnectivity(t, manager, resourceID, false, epoch.Add(time.Minute))++ // Ack, then unack.+ alertID := canonicalConnectivityStateID(resourceID)+ if err := manager.AcknowledgeAlert(alertID, "richard"); err != nil {+ t.Fatalf("AcknowledgeAlert: %v", err)+ }+ if err := manager.UnacknowledgeAlert(alertID); err != nil {+ t.Fatalf("UnacknowledgeAlert: %v", err)+ }++ // Recovery-gated resolve: three healthy polls.+ for i := 0; i < 3; i++ {+ manager.clearResourceOfflineAlert(resourceID, resourceID, "host", "PBS", offlineRecoveryConfirmationsDefault)+ }++ // Re-fire.+ shadowObserveConnectivity(t, manager, resourceID, false, epoch.Add(2*time.Minute))+ shadowObserveConnectivity(t, manager, resourceID, false, epoch.Add(150*time.Second))+ shadowObserveConnectivity(t, manager, resourceID, false, epoch.Add(3*time.Minute))++ if divergences := manager.ShadowDivergences(); divergences != 0 {+ t.Fatalf("ShadowDivergences = %d, want 0; events: %+v", divergences, shadowDivergenceEvents(t, manager))+ }+ if events := shadowDivergenceEvents(t, manager); len(events) != 0 {+ t.Fatalf("divergence events = %+v, want none", events)+ }+}++// A reducer/manager disagreement — simulated by seeding a bogus shadow+// incident the manager knows nothing about — is counted, recorded once,+// and resynced so the next observation is clean.+func TestShadowFeedRecordsAndResyncsDivergence(t *testing.T) {+ manager := newShadowFeedManager(t)+ resourceID := "shadow-bogus-1"++ manager.mu.Lock()+ manager.shadow.state.SeedFiringIncident(+ resourceID, canonicalConnectivitySpecID(resourceID),+ reducer.SeverityCritical, time.Now().Add(-time.Minute), false,+ )+ manager.mu.Unlock()++ // A healthy poll with a 3-poll recovery gate: the reducer holds firing,+ // the manager has no alert — divergence, then resync (Forget).+ manager.clearResourceOfflineAlert(resourceID, resourceID, "host", "PBS", offlineRecoveryConfirmationsDefault)++ if divergences := manager.ShadowDivergences(); divergences != 1 {+ t.Fatalf("ShadowDivergences = %d, want 1", divergences)+ }+ events := shadowDivergenceEvents(t, manager)+ if len(events) != 1 {+ t.Fatalf("divergence events = %d, want 1", len(events))+ }+ if events[0].Details["managerFiring"] != "false" || events[0].Details["reducerFiring"] != "true" {+ t.Fatalf("event details = %+v, want manager=false reducer=true", events[0].Details)+ }++ // After resync the next healthy poll agrees.+ manager.clearResourceOfflineAlert(resourceID, resourceID, "host", "PBS", offlineRecoveryConfirmationsDefault)+ if divergences := manager.ShadowDivergences(); divergences != 1 {+ t.Fatalf("ShadowDivergences after resync = %d, want still 1", divergences)+ }+}++// Enabling the feed on a manager with existing alerts seeds the reducer so+// restored state does not read as mass divergence.+func TestShadowFeedSeedsFromActiveAlerts(t *testing.T) {+ manager := NewManagerWithDataDir(t.TempDir(), WithoutPersistedAlertRestore())+ t.Cleanup(manager.Stop)+ manager.mu.Lock()+ manager.config.Enabled = true+ manager.mu.Unlock()++ epoch := time.Date(2026, 8, 26, 12, 0, 0, 0, time.UTC)+ resourceID := "shadow-seeded-1"++ // Fire before the feed exists (simulating restored state).+ shadowObserveConnectivity(t, manager, resourceID, false, epoch)+ shadowObserveConnectivity(t, manager, resourceID, false, epoch.Add(30*time.Second))+ shadowObserveConnectivity(t, manager, resourceID, false, epoch.Add(time.Minute))++ manager.EnableShadowFeed()++ // Continued offline observations and a full recovery agree throughout.+ shadowObserveConnectivity(t, manager, resourceID, false, epoch.Add(90*time.Second))+ for i := 0; i < 3; i++ {+ manager.clearResourceOfflineAlert(resourceID, resourceID, "host", "PBS", offlineRecoveryConfirmationsDefault)+ }+ if divergences := manager.ShadowDivergences(); divergences != 0 {+ t.Fatalf("ShadowDivergences = %d, want 0", divergences)+ }+}diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex a0fee44d7d..5b278478d3 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1759,6 +1759,7 @@ func New(cfg *config.Config) (*Monitor, error) {m.hydrateRemovedHostAgents(time.Now().UTC())m.alertManager.SetBackupIntentContextResolver(m.resolveBackupIntentContext)m.alertManager.EnableEventLog()+ m.alertManager.EnableShadowFeed()m.registerBuiltInPollProviders()m.buildInstanceInfoCache(cfg)