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): recovery-confirmation gate in the reducer with composed parity harness
rcourtman07aa2116d148
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 784dcb95dd..6a629a39a0 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@@ -47,7 +47,17 @@ had already fixed this once for unified incidents viawith `lifecycleFirstMatched`, mirroring that precedent, before the parityslice landed.-Remaining for later slices: recovery-confirmation gating-(`offlineRecoveryConfirmations`), re-fire-within-retention start-restoration, ack/snooze lifecycle, intent-policy interaction, and a-shadow-mode runtime feed.+Third slice (2026-08-26): the recovery-confirmation gate — the poll-driven+offline composition where offline polls reset the recovery counter and run+the evaluator while healthy polls skip the evaluator and run+`clearResourceOfflineAlert` (N consecutive healthy polls to resolve,+default 3, storage 2; pending still clears on one healthy poll). The+harness caught a defect in the slice-2 fix itself: callers that reset+confirmation counts directly (bypassing the evaluator path) left a stale+`lifecycleFirstMatched` entry that backdated the next run's alert to the+previous run's first observation. Fixed by re-stamping whenever an+observation starts a new run.++Remaining for later slices: re-fire-within-retention start restoration,+ack/snooze lifecycle, intent-policy interaction, and a shadow-mode+runtime feed.diff --git a/internal/alerts/reducer/discrete.go b/internal/alerts/reducer/discrete.goindex 194158fbe8..189219b343 100644--- a/internal/alerts/reducer/discrete.go+++ b/internal/alerts/reducer/discrete.go@@ -31,9 +31,17 @@ type DiscreteRule struct {// floor. (The manager's spec defaults: connectivity 3, powered-state// 2; callers pass the resolved value.)Confirmations int- // Disabled clears any pending or firing incident, mirroring the- // evaluator's terminal disabled transition and the manager's resolve- // of an existing alert.+ // RecoveryConfirmations is the number of consecutive non-matching+ // observations required before a firing incident resolves. Values+ // <= 1 resolve on the first non-matching observation — the plain+ // evaluator behavior. The manager's poll-driven offline paths compose+ // this gate on top (default 3, storage 2), with any matching+ // observation resetting the run; pending incidents always clear on a+ // single non-matching observation regardless of this setting.+ RecoveryConfirmations int+ // Disabled clears any pending or firing incident immediately —+ // bypassing recovery confirmations, exactly as the manager's disable+ // paths call clearAlert directly.Disabled bool}@@ -54,9 +62,9 @@ func (s *State) ApplyDiscrete(signal DiscreteSignal, rule DiscreteRule) []Event}}- // A non-matching observation and a disabled rule both clear at this- // layer: pending resets entirely, firing resolves.- if rule.Disabled || !signal.Matched {+ // A disabled rule clears immediately: pending resets, firing resolves,+ // recovery confirmations do not apply.+ if rule.Disabled {if incident == nil {return nil}@@ -67,6 +75,32 @@ func (s *State) ApplyDiscrete(signal DiscreteSignal, rule DiscreteRule) []Eventreturn []Event{event(EventPendingCleared, "")}}+ if !signal.Matched {+ if incident == nil {+ return nil+ }+ // Pending always clears on a single non-matching observation.+ if incident.State != StateFiring {+ delete(s.incidents, key)+ return []Event{event(EventPendingCleared, "")}+ }+ // Firing: the recovery gate. Consecutive non-matching observations+ // count toward the requirement; the incident stays firing until it+ // is met.+ requiredRecovery := rule.RecoveryConfirmations+ if requiredRecovery <= 1 {+ delete(s.incidents, key)+ return []Event{event(EventResolved, incident.Severity)}+ }+ incident.RecoveryCount+++ incident.LastObservedAt = signal.ObservedAt+ if incident.RecoveryCount < requiredRecovery {+ return nil+ }+ delete(s.incidents, key)+ return []Event{event(EventResolved, incident.Severity)}+ }+required := rule.Confirmationsif required <= 0 {required = 1@@ -79,6 +113,9 @@ func (s *State) ApplyDiscrete(signal DiscreteSignal, rule DiscreteRule) []Eventprevious := incident.Severityincident.Severity = signal.Severityincident.Confirmations = required+ // A matching observation interrupts any recovery run: recovery+ // confirmations must be consecutive.+ incident.RecoveryCount = 0incident.LastObservedAt = signal.ObservedAtif incident.Severity != previous {return []Event{event(EventSeverityChanged, incident.Severity)}diff --git a/internal/alerts/reducer/discrete_test.go b/internal/alerts/reducer/discrete_test.goindex 9de46925be..82f641accd 100644--- a/internal/alerts/reducer/discrete_test.go+++ b/internal/alerts/reducer/discrete_test.go@@ -134,3 +134,78 @@ func TestDiscreteRefireRequiresFullConfirmations(t *testing.T) {t.Fatalf("events = %+v, want re-fire after full confirmations", events)}}++func TestDiscreteRecoveryGateHoldsUntilConsecutiveConfirmations(t *testing.T) {+ state := NewState()+ rule := DiscreteRule{Confirmations: 1, RecoveryConfirmations: 3}++ state.ApplyDiscrete(discreteSignalAt(true, SeverityCritical, 0), rule)++ // Two healthy observations: still firing.+ if events := state.ApplyDiscrete(discreteSignalAt(false, "", time.Minute), rule); len(events) != 0 {+ t.Fatalf("first healthy emitted %+v", events)+ }+ if events := state.ApplyDiscrete(discreteSignalAt(false, "", 2*time.Minute), rule); len(events) != 0 {+ t.Fatalf("second healthy emitted %+v", events)+ }+ incident, ok := state.Incident("node-1", "connectivity")+ if !ok || incident.State != StateFiring || incident.RecoveryCount != 2 {+ t.Fatalf("incident = %+v, want firing with recovery count 2", incident)+ }++ events := state.ApplyDiscrete(discreteSignalAt(false, "", 3*time.Minute), rule)+ if len(events) != 1 || events[0].Type != EventResolved {+ t.Fatalf("events = %+v, want resolved on third consecutive healthy", events)+ }+ if _, ok := state.Incident("node-1", "connectivity"); ok {+ t.Fatal("incident should be gone after gated resolve")+ }+}++func TestDiscreteMatchedObservationResetsRecoveryRun(t *testing.T) {+ state := NewState()+ rule := DiscreteRule{Confirmations: 1, RecoveryConfirmations: 3}++ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 0), rule)+ state.ApplyDiscrete(discreteSignalAt(false, "", time.Minute), rule)+ state.ApplyDiscrete(discreteSignalAt(false, "", 2*time.Minute), rule)++ // Back offline: recovery run resets.+ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 3*time.Minute), rule)+ incident, _ := state.Incident("node-1", "connectivity")+ if incident.RecoveryCount != 0 {+ t.Fatalf("RecoveryCount = %d, want reset to 0", incident.RecoveryCount)+ }++ // Two healthy observations are again not enough.+ state.ApplyDiscrete(discreteSignalAt(false, "", 4*time.Minute), rule)+ if events := state.ApplyDiscrete(discreteSignalAt(false, "", 5*time.Minute), rule); len(events) != 0 {+ t.Fatalf("post-reset second healthy emitted %+v", events)+ }+ events := state.ApplyDiscrete(discreteSignalAt(false, "", 6*time.Minute), rule)+ if len(events) != 1 || events[0].Type != EventResolved {+ t.Fatalf("events = %+v, want resolved after full recovery run", events)+ }+}++func TestDiscretePendingClearsImmediatelyDespiteRecoveryGate(t *testing.T) {+ state := NewState()+ rule := DiscreteRule{Confirmations: 3, RecoveryConfirmations: 3}++ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 0), rule)+ events := state.ApplyDiscrete(discreteSignalAt(false, "", time.Minute), rule)+ if len(events) != 1 || events[0].Type != EventPendingCleared {+ t.Fatalf("events = %+v, want pending cleared on single healthy observation", events)+ }+}++func TestDiscreteDisableBypassesRecoveryGate(t *testing.T) {+ state := NewState()+ rule := DiscreteRule{Confirmations: 1, RecoveryConfirmations: 3}++ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 0), rule)+ events := state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, time.Minute), DiscreteRule{Confirmations: 1, RecoveryConfirmations: 3, Disabled: true})+ if len(events) != 1 || events[0].Type != EventResolved {+ t.Fatalf("events = %+v, want immediate resolve on disable", events)+ }+}diff --git a/internal/alerts/reducer/reducer.go b/internal/alerts/reducer/reducer.goindex f0f771f478..8e4cc9f6cb 100644--- a/internal/alerts/reducer/reducer.go+++ b/internal/alerts/reducer/reducer.go@@ -75,7 +75,11 @@ type Incident struct {LastValue float64// Confirmations is the consecutive-match count for the confirmation// family; unused by the metric family.- Confirmations int+ Confirmations int+ // RecoveryCount is the consecutive non-matching count while firing,+ // toward DiscreteRule.RecoveryConfirmations; reset by any matching+ // observation. Unused by the metric family.+ RecoveryCount intLastObservedAt time.Time}diff --git a/internal/alerts/reducer_parity_recovery_test.go b/internal/alerts/reducer_parity_recovery_test.gonew file mode 100644index 0000000000..21a7846606--- /dev/null+++ b/internal/alerts/reducer_parity_recovery_test.go@@ -0,0 +1,220 @@+package alerts++import (+ "fmt"+ "testing"+ "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/unifiedresources"+)++// Recovery-gate parity: the manager's poll-driven offline composition —+// an offline poll deletes the recovery counter and runs+// evaluateCanonicalLifecycleAlert with a connectivity spec; a healthy poll+// skips the evaluator and runs clearResourceOfflineAlert instead (the+// pbs.go / node.go / storage.go shape) — diffed against the reducer's+// DiscreteRule.RecoveryConfirmations after every step. Resolve timestamps+// are not asserted (clearResourceOfflineAlert stamps wall-clock time);+// firing state, severity, and first-activation StartTime are.++type recoveryParityStep struct {+ offline bool+ advance time.Duration++ wantFiring bool+ // wantStartOffset asserts the firing alert's StartTime as an offset+ // from the scenario's first observation; -1 skips.+ wantStartOffset time.Duration+}++type recoveryParityScenario struct {+ name string+ confirmations int+ recovery int+ steps []recoveryParityStep+}++const recoveryParityResourceID = "parity-pbs-1"++type managerRecoveryParityEngine struct {+ manager *Manager+ clock time.Time+ conf int+ recovery int+}++func (e *managerRecoveryParityEngine) observe(t *testing.T, step recoveryParityStep) {+ t.Helper()+ e.clock = e.clock.Add(step.advance)++ if !step.offline {+ e.manager.clearResourceOfflineAlert(recoveryParityResourceID, "parity-pbs", "host-1", "PBS", e.recovery)+ return+ }++ e.manager.mu.Lock()+ delete(e.manager.offlineRecoveryConfirmations, canonicalConnectivityStateID(recoveryParityResourceID))+ e.manager.mu.Unlock()++ spec, err := buildCanonicalConnectivitySpec(+ recoveryParityResourceID, "parity-pbs", unifiedresources.ResourceTypePBS,+ AlertLevelCritical, e.conf, false,+ )+ if err != nil {+ t.Fatalf("build spec: %v", err)+ }+ if _, ok := e.manager.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{+ Spec: spec,+ Evidence: alertspecs.AlertEvidence{+ ObservedAt: e.clock,+ Connectivity: &alertspecs.ConnectivityEvidence{Signal: "status", Connected: false},+ },+ Tracking: e.manager.offlineConfirmations,+ TrackingKey: recoveryParityResourceID,+ AlertID: fmt.Sprintf("pbs-offline-%s", recoveryParityResourceID),+ AlertType: "offline",+ ResourceID: recoveryParityResourceID,+ ResourceName: "parity-pbs",+ Node: "host-1",+ Instance: "parity-pbs",+ Message: "parity PBS offline",+ }); !ok {+ t.Fatal("evaluateCanonicalLifecycleAlert rejected the connectivity spec")+ }+}++func (e *managerRecoveryParityEngine) snapshot() (bool, AlertLevel, time.Time) {+ e.manager.mu.Lock()+ defer e.manager.mu.Unlock()+ alert, exists := e.manager.getActiveAlertNoLock(canonicalConnectivityStateID(recoveryParityResourceID))+ if !exists || alert == nil {+ return false, "", time.Time{}+ }+ return true, alert.Level, alert.StartTime+}++func recoveryParityScenarios() []recoveryParityScenario {+ skip := time.Duration(-1)+ return []recoveryParityScenario{+ {+ name: "recovery gate holds until three consecutive healthy polls",+ confirmations: 3, recovery: 3,+ steps: []recoveryParityStep{+ {offline: true, wantFiring: false, wantStartOffset: skip},+ {offline: true, advance: 30 * time.Second, wantFiring: false, wantStartOffset: skip},+ {offline: true, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: false, wantStartOffset: skip},+ },+ },+ {+ name: "an offline poll mid-recovery resets the healthy run",+ confirmations: 1, recovery: 3,+ steps: []recoveryParityStep{+ {offline: true, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: true, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: false, wantStartOffset: skip},+ },+ },+ {+ name: "storage-style two-poll recovery",+ confirmations: 2, recovery: 2,+ steps: []recoveryParityStep{+ {offline: true, wantFiring: false, wantStartOffset: skip},+ {offline: true, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 0},+ {offline: false, advance: 30 * time.Second, wantFiring: false, wantStartOffset: skip},+ },+ },+ {+ name: "healthy poll during pending clears immediately and re-fire re-dates",+ confirmations: 3, recovery: 3,+ steps: []recoveryParityStep{+ {offline: true, wantFiring: false, wantStartOffset: skip},+ {offline: true, advance: 30 * time.Second, wantFiring: false, wantStartOffset: skip},+ {offline: false, advance: 30 * time.Second, wantFiring: false, wantStartOffset: skip},+ {offline: true, advance: 30 * time.Second, wantFiring: false, wantStartOffset: skip},+ {offline: true, advance: 30 * time.Second, wantFiring: false, wantStartOffset: skip},+ {offline: true, advance: 30 * time.Second, wantFiring: true, wantStartOffset: 90 * time.Second},+ },+ },+ }+}++func TestReducerParityWithManagerRecoveryGate(t *testing.T) {+ epoch := time.Date(2026, 8, 26, 12, 0, 0, 0, time.UTC)++ for _, scenario := range recoveryParityScenarios() {+ scenario := scenario+ t.Run(scenario.name, func(t *testing.T) {+ manager := NewManagerWithDataDir(t.TempDir(), WithoutPersistedAlertRestore())+ t.Cleanup(manager.Stop)+ manager.mu.Lock()+ manager.config.Enabled = true+ manager.config.FlappingEnabled = false+ manager.mu.Unlock()++ managerEngine := &managerRecoveryParityEngine{+ manager: manager, clock: epoch,+ conf: scenario.confirmations, recovery: scenario.recovery,+ }+ reducerState := reducer.NewState()+ reducerClock := epoch+ rule := reducer.DiscreteRule{+ Confirmations: scenario.confirmations,+ RecoveryConfirmations: scenario.recovery,+ }++ for i, step := range scenario.steps {+ managerEngine.observe(t, step)+ reducerClock = reducerClock.Add(step.advance)+ reducerState.ApplyDiscrete(reducer.DiscreteSignal{+ ResourceID: recoveryParityResourceID,+ Key: "connectivity",+ Matched: step.offline,+ Severity: reducer.SeverityCritical,+ ObservedAt: reducerClock,+ }, rule)++ managerFiring, managerLevel, managerStart := managerEngine.snapshot()+ incident, ok := reducerState.Incident(recoveryParityResourceID, "connectivity")+ reducerFiring := ok && incident.State == reducer.StateFiring++ label := fmt.Sprintf("step %d (offline=%v advance=%s)", i, step.offline, step.advance)++ if managerFiring != step.wantFiring {+ t.Fatalf("%s: manager firing = %v, scenario expects %v (characterization drift)",+ label, managerFiring, step.wantFiring)+ }+ if managerFiring && step.wantStartOffset >= 0 {+ wantStart := epoch.Add(step.wantStartOffset)+ if !managerStart.Equal(wantStart) {+ t.Fatalf("%s: manager start = %v, scenario expects %v", label, managerStart, wantStart)+ }+ }++ if reducerFiring != managerFiring {+ t.Fatalf("%s: PARITY DIVERGENCE — reducer firing = %v, manager = %v",+ label, reducerFiring, managerFiring)+ }+ if managerFiring {+ if AlertLevel(incident.Severity) != managerLevel {+ t.Fatalf("%s: PARITY DIVERGENCE — reducer severity = %q, manager = %q",+ label, incident.Severity, managerLevel)+ }+ if step.wantStartOffset >= 0 && !incident.StartedAt.Equal(managerStart) {+ t.Fatalf("%s: PARITY DIVERGENCE — reducer start = %v, manager = %v",+ label, incident.StartedAt, managerStart)+ }+ }+ }+ })+ }+}