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.

feat(alerts): cut the canonical lifecycle family over to the reducer core

rcourtman6a04dcb84f5e
diff --git a/internal/alerts/active_lifecycle.go b/internal/alerts/active_lifecycle.go
index b0824493ea..d2a2936c32 100644
--- a/internal/alerts/active_lifecycle.go
+++ b/internal/alerts/active_lifecycle.go
@@ -6,6 +6,7 @@ import (
"strings"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"
"github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"
"github.com/rs/zerolog/log"
)
@@ -99,7 +100,7 @@ func (m *Manager) clearAlert(alertID string) {
m.mu.Lock()
alert, exists := m.getActiveAlertNoLock(alertID)
if exists {
- m.shadowForgetAlertNoLock(alert)
+ m.mirrorForgetAlertNoLock(alert)
m.removeActiveAlertNoLock(alertID)
}
m.mu.Unlock()
@@ -150,7 +151,7 @@ func (m *Manager) AcknowledgeAlert(alertID, user string) error {
user: user,
time: now,
})
- m.shadowAcknowledgeNoLock(alert, user, now)
+ m.mirrorAcknowledgeNoLock(alert, user, now)
alertCopy := alert.Clone()
m.mu.Unlock()
@@ -191,7 +192,7 @@ func (m *Manager) UnacknowledgeAlert(alertID string) error {
m.setActiveAlertNoLock(key, alert)
m.deleteAckRecordNoLock(alert, alertID)
- m.shadowUnacknowledgeNoLock(alert)
+ m.mirrorUnacknowledgeNoLock(alert)
alertCopy := alert.Clone()
m.mu.Unlock()
@@ -599,7 +600,8 @@ func (m *Manager) confirmOfflineRecoveryNoLock(alertID string, required int) (in
}
// clearResourceOfflineAlert removes an offline alert when a poll-driven resource
-// stays healthy for enough consecutive polls to confirm recovery.
+// stays healthy for enough consecutive polls to confirm recovery. The
+// reducer core owns the recovery gate.
func (m *Manager) clearResourceOfflineAlert(resourceID, resourceName, host, resourceKind string, requiredRecoveryCount int) {
alertID := canonicalConnectivityStateID(resourceID)
@@ -607,28 +609,65 @@ func (m *Manager) clearResourceOfflineAlert(resourceID, resourceName, host, reso
defer m.mu.Unlock()
defer m.shadowObserveRecoveryNoLock(resourceID, canonicalConnectivitySpecID(resourceID), alertID, requiredRecoveryCount)
- if count, exists := m.offlineConfirmations[resourceID]; exists && count > 0 {
- log.Debug().
- Str(strings.ToLower(resourceKind), resourceName).
- Int("previousCount", count).
- Msg(resourceKind + " is online, resetting offline confirmation count")
- delete(m.offlineConfirmations, resourceID)
+ m.resolveDiscreteRecoveryNoLock(resourceID, canonicalConnectivitySpecID(resourceID), alertID, requiredRecoveryCount, resourceKind, resourceName, host)
+}
+
+// resolveDiscreteRecoveryNoLock feeds one healthy observation for a
+// poll-driven discrete condition to the reducer core and resolves the
+// active alert once the core's recovery gate confirms. Caller holds m.mu.
+func (m *Manager) resolveDiscreteRecoveryNoLock(resourceID, specKey, alertID string, requiredRecoveryCount int, resourceKind, resourceName, host string) {
+ // An existing alert the core does not know about means it was firing:
+ // adopt it before the healthy observation, exactly as the old engine
+ // treated any active alert as previously firing.
+ if adopted, adoptedExists := m.getActiveAlertNoLock(alertID); adoptedExists && adopted != nil {
+ if _, known := m.core.Incident(resourceID, specKey); !known {
+ ackAt := time.Time{}
+ if adopted.AckTime != nil {
+ ackAt = *adopted.AckTime
+ }
+ m.core.SeedFiringIncident(resourceID, specKey, shadowSeverityForLevel(adopted.Level), adopted.StartTime, adopted.Acknowledged, adopted.AckUser, ackAt)
+ }
+ }
+
+ events := m.core.ApplyDiscrete(reducer.DiscreteSignal{
+ ResourceID: resourceID,
+ Key: specKey,
+ Matched: false,
+ ObservedAt: time.Now(),
+ }, reducer.DiscreteRule{RecoveryConfirmations: requiredRecoveryCount})
+
+ // Legacy-map mirrors (read-only during Phase 2; deleted in Phase 3):
+ // a healthy poll clears any confirmation-run mirror and reflects the
+ // core's recovery count.
+ delete(m.offlineConfirmations, resourceID)
+ if incident, tracked := m.core.Incident(resourceID, specKey); tracked && incident.RecoveryCount > 0 {
+ m.offlineRecoveryConfirmations[alertID] = incident.RecoveryCount
+ } else {
+ delete(m.offlineRecoveryConfirmations, alertID)
}
alert, exists := m.getActiveAlertNoLock(alertID)
if !exists {
- delete(m.offlineRecoveryConfirmations, alertID)
return
}
- recoveryCount, confirmed := m.confirmOfflineRecoveryNoLock(alertID, requiredRecoveryCount)
- if !confirmed {
- log.Debug().
- Str(strings.ToLower(resourceKind), resourceName).
- Int("confirmations", recoveryCount).
- Int("required", requiredRecoveryCount).
- Msg(resourceKind + " appears back online, waiting for recovery confirmation")
- return
+ resolved := false
+ for _, event := range events {
+ if event.Type == reducer.EventResolved {
+ resolved = true
+ break
+ }
+ }
+ if !resolved {
+ // Self-heal in the authoritative direction: an alert with no core
+ // incident resolves immediately rather than sticking.
+ if _, hasIncident := m.core.Incident(resourceID, specKey); hasIncident {
+ log.Debug().
+ Str(strings.ToLower(resourceKind), resourceName).
+ Int("required", requiredRecoveryCount).
+ Msg(resourceKind + " appears back online, waiting for recovery confirmation")
+ return
+ }
}
m.removeActiveAlertNoLock(alertID)
@@ -684,7 +723,7 @@ func (m *Manager) clearAlertNoLock(alertID string) {
recordAlertResolved(alert)
}
- m.shadowForgetAlertNoLock(alert)
+ m.mirrorForgetAlertNoLock(alert)
m.removeActiveAlertNoLock(alertID)
resolvedAlert := m.newResolvedAlert(alert, time.Now(), nil)
diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.go
index d7ab30da69..ce5690b258 100644
--- a/internal/alerts/alerts_test.go
+++ b/internal/alerts/alerts_test.go
@@ -8747,7 +8747,6 @@ func TestHandleDockerHostOffline(t *testing.T) {
m := newTestManager(t)
m.mu.Lock()
m.config.Enabled = true
- m.dockerOfflineCount["docker1"] = 2 // Pre-set to trigger on next call
m.mu.Unlock()
host := models.DockerHost{
@@ -8757,6 +8756,10 @@ func TestHandleDockerHostOffline(t *testing.T) {
AgentID: "agent-123",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.HandleDockerHostOffline(host)
+ m.HandleDockerHostOffline(host)
m.HandleDockerHostOffline(host)
m.mu.RLock()
@@ -9601,7 +9604,6 @@ func TestCheckNodeOffline(t *testing.T) {
// t.Parallel()
m := newTestManager(t)
m.mu.Lock()
- m.nodeOfflineCount["node1"] = 2 // Pre-set to trigger on next call
m.mu.Unlock()
node := models.Node{
@@ -9612,6 +9614,10 @@ func TestCheckNodeOffline(t *testing.T) {
ConnectionHealth: "disconnected",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.checkNodeOffline(node)
+ m.checkNodeOffline(node)
m.checkNodeOffline(node)
m.mu.RLock()
@@ -9640,10 +9646,13 @@ func TestCheckNodeOffline(t *testing.T) {
// t.Parallel()
m := newTestManager(t)
m.mu.Lock()
- m.nodeOfflineCount["node1"] = 2
m.mu.Unlock()
node := models.Node{ID: "node1", Name: "Node 1", Instance: "pve1"}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.checkNodeOffline(node)
+ m.checkNodeOffline(node)
m.checkNodeOffline(node)
// Check history
@@ -9737,10 +9746,13 @@ func TestCheckPBSOffline(t *testing.T) {
// t.Parallel()
m := newTestManager(t)
m.mu.Lock()
- m.offlineConfirmations["pbs1"] = 2
m.mu.Unlock()
pbs := models.PBSInstance{ID: "pbs1", Name: "PBS 1", Host: "pbs.local"}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.checkPBSOffline(pbs)
+ m.checkPBSOffline(pbs)
m.checkPBSOffline(pbs)
m.mu.RLock()
@@ -9863,10 +9875,13 @@ func TestCheckPMGOffline(t *testing.T) {
// t.Parallel()
m := newTestManager(t)
m.mu.Lock()
- m.offlineConfirmations["pmg1"] = 2
m.mu.Unlock()
pmg := models.PMGInstance{ID: "pmg1", Name: "PMG 1", Host: "pmg.local"}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.checkPMGOffline(pmg)
+ m.checkPMGOffline(pmg)
m.checkPMGOffline(pmg)
m.mu.RLock()
@@ -14451,7 +14466,6 @@ func TestCheckNode(t *testing.T) {
// Pre-set count to trigger alert on this call
m.mu.Lock()
- m.nodeOfflineCount["node1"] = 2
m.mu.Unlock()
node := models.Node{
@@ -14460,6 +14474,10 @@ func TestCheckNode(t *testing.T) {
Instance: "pve1",
Status: "offline",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckNode(node)
+ m.CheckNode(node)
m.CheckNode(node)
m.mu.RLock()
@@ -14479,7 +14497,6 @@ func TestCheckNode(t *testing.T) {
m := newTestManager(t)
m.mu.Lock()
- m.nodeOfflineCount["node1"] = 2
m.mu.Unlock()
node := models.Node{
@@ -14489,6 +14506,10 @@ func TestCheckNode(t *testing.T) {
Status: "online",
ConnectionHealth: "error",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckNode(node)
+ m.CheckNode(node)
m.CheckNode(node)
m.mu.RLock()
@@ -14505,7 +14526,6 @@ func TestCheckNode(t *testing.T) {
m := newTestManager(t)
m.mu.Lock()
- m.nodeOfflineCount["node1"] = 2
m.mu.Unlock()
node := models.Node{
@@ -14515,6 +14535,10 @@ func TestCheckNode(t *testing.T) {
Status: "online",
ConnectionHealth: "failed",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckNode(node)
+ m.CheckNode(node)
m.CheckNode(node)
m.mu.RLock()
@@ -15073,7 +15097,6 @@ func TestCheckGuest(t *testing.T) {
// Pre-set confirmation count to trigger alert
m.mu.Lock()
- m.offlineConfirmations["vm100"] = 2
m.mu.Unlock()
vm := models.VM{
@@ -15083,6 +15106,10 @@ func TestCheckGuest(t *testing.T) {
Status: "stopped",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckGuest(vm, "pve1")
+ m.CheckGuest(vm, "pve1")
m.CheckGuest(vm, "pve1")
m.mu.RLock()
@@ -16817,7 +16844,6 @@ func TestCheckPBSComprehensive(t *testing.T) {
m.mu.Lock()
// Pre-populate confirmation count to bypass waiting period
- m.offlineConfirmations["pbs1"] = 2
m.mu.Unlock()
pbs := models.PBSInstance{
@@ -16826,6 +16852,10 @@ func TestCheckPBSComprehensive(t *testing.T) {
Status: "offline",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckPBS(pbs)
+ m.CheckPBS(pbs)
m.CheckPBS(pbs)
m.mu.RLock()
@@ -16846,7 +16876,6 @@ func TestCheckPBSComprehensive(t *testing.T) {
m.mu.Lock()
// Pre-populate confirmation count to bypass waiting period
- m.offlineConfirmations["pbs1"] = 2
m.mu.Unlock()
pbs := models.PBSInstance{
@@ -16856,6 +16885,10 @@ func TestCheckPBSComprehensive(t *testing.T) {
ConnectionHealth: "error",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckPBS(pbs)
+ m.CheckPBS(pbs)
m.CheckPBS(pbs)
m.mu.RLock()
@@ -16873,7 +16906,6 @@ func TestCheckPBSComprehensive(t *testing.T) {
m.mu.Lock()
// Pre-populate confirmation count to bypass waiting period
- m.offlineConfirmations["pbs1"] = 2
m.mu.Unlock()
pbs := models.PBSInstance{
@@ -16883,6 +16915,10 @@ func TestCheckPBSComprehensive(t *testing.T) {
ConnectionHealth: "unhealthy",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckPBS(pbs)
+ m.CheckPBS(pbs)
m.CheckPBS(pbs)
m.mu.RLock()
@@ -16902,7 +16938,6 @@ func TestCheckPBSComprehensive(t *testing.T) {
m.config.TimeThresholds = map[string]int{}
m.activeAlerts["pbs1-cpu"] = &Alert{ID: "pbs1-cpu", Type: "cpu"}
m.activeAlerts["pbs1-memory"] = &Alert{ID: "pbs1-memory", Type: "memory"}
- m.offlineConfirmations["pbs1"] = 2 // trigger offline alert immediately
m.mu.Unlock()
pbs := models.PBSInstance{
@@ -16914,6 +16949,10 @@ func TestCheckPBSComprehensive(t *testing.T) {
Memory: 99,
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckPBS(pbs)
+ m.CheckPBS(pbs)
m.CheckPBS(pbs)
m.mu.RLock()
@@ -17164,7 +17203,6 @@ func TestCheckPMGComprehensive(t *testing.T) {
m.mu.Lock()
// Pre-populate confirmation count to bypass waiting period (3 required)
- m.offlineConfirmations["pmg1"] = 2
m.mu.Unlock()
pmg := models.PMGInstance{
@@ -17173,6 +17211,10 @@ func TestCheckPMGComprehensive(t *testing.T) {
Status: "offline",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckPMG(pmg)
+ m.CheckPMG(pmg)
m.CheckPMG(pmg)
m.mu.RLock()
@@ -17193,7 +17235,6 @@ func TestCheckPMGComprehensive(t *testing.T) {
m.mu.Lock()
// Pre-populate confirmation count to bypass waiting period
- m.offlineConfirmations["pmg1"] = 2
m.mu.Unlock()
pmg := models.PMGInstance{
@@ -17203,6 +17244,10 @@ func TestCheckPMGComprehensive(t *testing.T) {
ConnectionHealth: "error",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckPMG(pmg)
+ m.CheckPMG(pmg)
m.CheckPMG(pmg)
m.mu.RLock()
@@ -17220,7 +17265,6 @@ func TestCheckPMGComprehensive(t *testing.T) {
m.mu.Lock()
// Pre-populate confirmation count to bypass waiting period
- m.offlineConfirmations["pmg1"] = 2
m.mu.Unlock()
pmg := models.PMGInstance{
@@ -17230,6 +17274,10 @@ func TestCheckPMGComprehensive(t *testing.T) {
ConnectionHealth: "unhealthy",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckPMG(pmg)
+ m.CheckPMG(pmg)
m.CheckPMG(pmg)
m.mu.RLock()
@@ -17245,7 +17293,6 @@ func TestCheckPMGComprehensive(t *testing.T) {
m := newTestManager(t)
m.mu.Lock()
- m.offlineConfirmations["pmg1"] = 2
m.mu.Unlock()
pmg := models.PMGInstance{
@@ -17255,6 +17302,10 @@ func TestCheckPMGComprehensive(t *testing.T) {
ConnectionHealth: " UNHEALTHY ",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckPMG(pmg)
+ m.CheckPMG(pmg)
m.CheckPMG(pmg)
m.mu.RLock()
@@ -17286,7 +17337,6 @@ func TestCheckPMGComprehensive(t *testing.T) {
Type: "queue-hold",
ResourceID: "pmg1",
}
- m.offlineConfirmations["pmg1"] = 2 // trigger offline alert immediately
m.mu.Unlock()
pmg := models.PMGInstance{
@@ -17296,6 +17346,10 @@ func TestCheckPMGComprehensive(t *testing.T) {
ConnectionHealth: "unhealthy",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckPMG(pmg)
+ m.CheckPMG(pmg)
m.CheckPMG(pmg)
m.mu.RLock()
@@ -17646,7 +17700,6 @@ func TestCheckStorageComprehensive(t *testing.T) {
m.mu.Lock()
// Pre-populate confirmation count (requires 2)
- m.offlineConfirmations["storage1"] = 1
m.mu.Unlock()
storage := models.Storage{
@@ -17655,6 +17708,9 @@ func TestCheckStorageComprehensive(t *testing.T) {
Status: "offline",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckStorage(storage)
m.CheckStorage(storage)
m.mu.RLock()
@@ -17672,7 +17728,6 @@ func TestCheckStorageComprehensive(t *testing.T) {
m.mu.Lock()
// Pre-populate confirmation count (requires 2)
- m.offlineConfirmations["storage1"] = 1
m.mu.Unlock()
storage := models.Storage{
@@ -17681,6 +17736,9 @@ func TestCheckStorageComprehensive(t *testing.T) {
Status: "unavailable",
}
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ m.CheckStorage(storage)
m.CheckStorage(storage)
m.mu.RLock()
diff --git a/internal/alerts/canonical_lifecycle.go b/internal/alerts/canonical_lifecycle.go
index d729f92b5a..1e88876b66 100644
--- a/internal/alerts/canonical_lifecycle.go
+++ b/internal/alerts/canonical_lifecycle.go
@@ -267,44 +267,6 @@ func canonicalAlertSeverity(level AlertLevel) alertspecs.AlertSeverity {
}
}
-func lifecyclePreviousState(spec alertspecs.ResourceAlertSpec, existing *Alert, confirmations int, firstMatched, observedAt time.Time) alertspecs.EvaluatorState {
- if existing != nil {
- required := spec.ConfirmationsRequired
- if confirmations > required {
- required = confirmations
- }
- return alertspecs.EvaluatorState{
- SpecID: spec.ID,
- State: alertspecs.AlertStateFiring,
- Severity: canonicalAlertSeverity(existing.Level),
- ConsecutiveMatches: required,
- FirstMatchedAt: existing.StartTime,
- ActiveSince: existing.StartTime,
- LastObservedAt: existing.LastSeen,
- }
- }
- if confirmations > 0 {
- // Date the reconstructed pending run at its preserved first match so
- // activation stamps StartTime at the first failing observation, not
- // at the final confirming poll.
- matchedAt := firstMatched
- if matchedAt.IsZero() {
- matchedAt = observedAt
- }
- return alertspecs.EvaluatorState{
- SpecID: spec.ID,
- State: alertspecs.AlertStatePending,
- Severity: spec.Severity,
- ConsecutiveMatches: confirmations,
- FirstMatchedAt: matchedAt,
- }
- }
- return alertspecs.EvaluatorState{
- SpecID: spec.ID,
- State: alertspecs.AlertStateClear,
- }
-}
-
func statefulPreviousState(spec alertspecs.ResourceAlertSpec, existing *Alert, pendingSince time.Time) alertspecs.EvaluatorState {
if existing != nil {
return alertspecs.EvaluatorState{
@@ -377,17 +339,9 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlert
migratedAlertIdentity = true
}
- confirmations := 0
- if params.Tracking != nil {
- confirmations = params.Tracking[params.TrackingKey]
- }
- firstMatched := time.Time{}
- if confirmations > 0 {
- firstMatched = m.lifecycleFirstMatched[params.TrackingKey]
- }
-
- result, err := alertspecs.Evaluate(params.Spec, lifecyclePreviousState(params.Spec, existing, confirmations, firstMatched, params.Evidence.ObservedAt), params.Evidence)
- if err != nil {
+ // Validate the spec and evidence exactly as the evaluator did, so
+ // malformed input is skipped rather than misread as a recovery.
+ if err := params.Spec.Validate(); err != nil {
log.Warn().
Err(err).
Str("alertID", storageKey).
@@ -396,38 +350,30 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlert
Msg("Skipping invalid canonical lifecycle evaluation")
return 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.
- if params.Tracking != nil {
- if result.State.ConsecutiveMatches > 0 {
- params.Tracking[params.TrackingKey] = result.State.ConsecutiveMatches
- // Stamp the first-matched time whenever this observation starts
- // a new confirmation run (the pre-evaluation count was zero).
- // Several callers reset the count maps directly without going
- // through this path — clearResourceOfflineAlert among them — so
- // a keep-if-present guard would let a stale entry from a prior
- // run backdate the next run's alert.
- if confirmations == 0 && !result.State.FirstMatchedAt.IsZero() {
- m.lifecycleFirstMatched[params.TrackingKey] = result.State.FirstMatchedAt
- }
- } else {
- delete(params.Tracking, params.TrackingKey)
- delete(m.lifecycleFirstMatched, params.TrackingKey)
- }
+ if err := alertspecs.ValidateEvidence(params.Spec.Kind, params.Evidence); err != nil {
+ log.Warn().
+ Err(err).
+ Str("alertID", storageKey).
+ Str("resourceID", params.ResourceID).
+ Str("specID", params.Spec.ID).
+ Msg("Skipping invalid canonical lifecycle evidence")
+ return alertspecs.EvaluationResult{}, false
}
+ matched, matchSeverity, matchReason := alertspecs.Match(params.Spec, params.Evidence)
+
+ // Intent context resolves before the transition, exactly when the old
+ // engine consulted it: only while no alert is active. Its bookkeeping
+ // (intentPending, preview surfaces) is preserved; the gate itself now
+ // lives in the reducer.
intentSignal := params.IntentSignal
if intentSignal == "" && (params.Spec.Kind == alertspecs.AlertSpecKindConnectivity || params.Spec.Kind == alertspecs.AlertSpecKindPoweredState) {
intentSignal = string(AlertIntentSignalOffline)
}
+ var intent *reducer.DiscreteIntent
if intentSignal != "" && existing == nil {
- conditionActive := result.State.State == alertspecs.AlertStatePending || result.State.State == alertspecs.AlertStateFiring
- decision := m.evaluateIntentNoLock(params.Spec.ResourceID, string(params.Spec.ResourceType), intentSignal, storageKey, params.Evidence.ObservedAt, conditionActive, params.IntentBackup)
- shadowIntent = &reducer.DiscreteIntent{
+ decision := m.evaluateIntentNoLock(params.Spec.ResourceID, string(params.Spec.ResourceType), intentSignal, storageKey, params.Evidence.ObservedAt, matched, params.IntentBackup)
+ intent = &reducer.DiscreteIntent{
Explicit: decision.Effective.Explicit,
GraceSeconds: decision.Effective.GraceSeconds,
// Operator suppression only: the backup-offline deferral is
@@ -437,38 +383,115 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlert
OperatorReason: decision.Reason,
}
if backupOffline := decision.Effective.BackupOffline; backupOffline != nil && backupOffline.Enabled && intentSignal == string(AlertIntentSignalOffline) {
- shadowIntent.BackupEnabled = true
- shadowIntent.BackupActive = params.IntentBackup.Active
- shadowIntent.BackupPostGraceSeconds = backupOffline.PostGraceSeconds
- shadowIntent.BackupMaxDeferralSeconds = backupOffline.MaxDeferralSeconds
+ intent.BackupEnabled = true
+ intent.BackupActive = params.IntentBackup.Active
+ intent.BackupPostGraceSeconds = backupOffline.PostGraceSeconds
+ intent.BackupMaxDeferralSeconds = backupOffline.MaxDeferralSeconds
}
+ shadowIntent = intent
if decision.StateChanged {
m.saveActiveAlertsAsync("lifecycle intent state")
}
- if conditionActive && !decision.ShouldActivate && (decision.Effective.Explicit || decision.Suppressed) {
- result.State.State = alertspecs.AlertStatePending
- result.State.Reason = decision.Reason
- if pending, ok := m.intentPending[storageKey]; ok && !pending.FirstMatchedAt.IsZero() {
- result.State.FirstMatchedAt = pending.FirstMatchedAt
+ }
+
+ severity := reducer.SeverityWarning
+ if matchSeverity == alertspecs.AlertSeverityCritical {
+ severity = reducer.SeverityCritical
+ }
+
+ // An existing alert the core does not know about (guest migration,
+ // direct injection, any unhooked path) means it was firing: adopt it,
+ // exactly as the old engine reconstructed previous state as firing
+ // whenever an active alert existed.
+ if existing != nil {
+ if _, known := m.core.Incident(params.Spec.ResourceID, params.Spec.ID); !known {
+ ackAt := time.Time{}
+ if existing.AckTime != nil {
+ ackAt = *existing.AckTime
}
- return result, true
+ m.core.SeedFiringIncident(
+ params.Spec.ResourceID,
+ params.Spec.ID,
+ shadowSeverityForLevel(existing.Level),
+ existing.StartTime,
+ existing.Acknowledged,
+ existing.AckUser,
+ ackAt,
+ )
+ }
+ }
+
+ events := m.core.ApplyDiscrete(reducer.DiscreteSignal{
+ ResourceID: params.Spec.ResourceID,
+ Key: params.Spec.ID,
+ Matched: matched,
+ Severity: severity,
+ RuntimeTick: m.intentTickNoLock(),
+ RuntimeTickValid: true,
+ ObservedAt: params.Evidence.ObservedAt,
+ }, reducer.DiscreteRule{
+ Confirmations: specConfirmationsRequired(params.Spec),
+ Disabled: params.Spec.Disabled,
+ Intent: intent,
+ })
+ primary := reducer.EventType("")
+ if len(events) > 0 {
+ primary = events[0].Type
+ }
+
+ shadowEligible = true
+
+ incident, hasIncident := m.core.Incident(params.Spec.ResourceID, params.Spec.ID)
+
+ // The legacy count maps are maintained as read-only mirrors of the core
+ // during the Phase 2 transition, for external readers; the engine never
+ // consults them. They are deleted with the Phase 3 cleanup.
+ if params.Tracking != nil {
+ if hasIncident {
+ params.Tracking[params.TrackingKey] = incident.Confirmations
+ } else {
+ delete(params.Tracking, params.TrackingKey)
}
- if decision.Effective.Explicit && result.State.State == alertspecs.AlertStateFiring {
- if pending, ok := m.intentPending[storageKey]; ok && !pending.FirstMatchedAt.IsZero() {
- result.State.FirstMatchedAt = pending.FirstMatchedAt
- }
- m.clearIntentPendingNoLock(storageKey)
- m.saveActiveAlertsAsync("lifecycle intent activated")
+ }
+
+ // Synthesize the evaluator-shaped result the callers consume.
+ result := alertspecs.EvaluationResult{}
+ result.State.SpecID = params.Spec.ID
+ result.State.LastObservedAt = params.Evidence.ObservedAt
+ result.State.Reason = matchReason
+
+ transition := func(kind alertspecs.EvaluationTransitionKind, from, to alertspecs.AlertState) *alertspecs.EvaluationTransition {
+ return &alertspecs.EvaluationTransition{
+ Kind: kind,
+ SpecID: params.Spec.ID,
+ ResourceID: params.Spec.ResourceID,
+ From: from,
+ To: to,
+ At: params.Evidence.ObservedAt,
+ Severity: matchSeverity,
+ Reason: matchReason,
+ Evidence: params.Evidence,
}
}
- switch result.State.State {
- case alertspecs.AlertStatePending:
+ if hasIncident && incident.State == reducer.StatePending {
+ result.State.State = alertspecs.AlertStatePending
+ result.State.Severity = matchSeverity
+ result.State.ConsecutiveMatches = incident.Confirmations
+ result.State.FirstMatchedAt = incident.PendingSince
+ if intent != nil && intent.OperatorReason != "" {
+ result.State.Reason = intent.OperatorReason
+ }
+ if primary == reducer.EventPending {
+ result.Transition = transition(alertspecs.EvaluationTransitionPending, alertspecs.AlertStateClear, alertspecs.AlertStatePending)
+ }
return result, true
- case alertspecs.AlertStateFiring:
- level, ok := alertLevelFromCanonicalSeverity(result.State.Severity)
- if !ok {
- level = AlertLevelWarning
+ }
+
+ if hasIncident && incident.State == reducer.StateFiring {
+ level := AlertLevelWarning
+ if incident.Severity == reducer.SeverityCritical {
+ level = AlertLevelCritical
}
alert := &Alert{
ID: storageKey,
@@ -481,7 +504,7 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlert
Message: params.Message,
Value: 0,
Threshold: 0,
- StartTime: params.Evidence.ObservedAt,
+ StartTime: incident.StartedAt,
LastSeen: params.Evidence.ObservedAt,
Metadata: cloneMetadata(params.Metadata),
}
@@ -492,31 +515,56 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlert
alert.Metadata["resourceType"] = string(params.Spec.ResourceType)
}
applyCanonicalIdentity(alert, params.Spec.ID, string(params.Spec.Kind))
- if !result.State.FirstMatchedAt.IsZero() {
- alert.StartTime = result.State.FirstMatchedAt
- }
applyCanonicalOperationalEvidence(alert, params.Spec, params.Evidence, time.Now())
m.preserveAlertState(storageKey, alert)
+ // The reducer core is authoritative for occurrence start and
+ // acknowledgement restoration.
+ alert.StartTime = incident.StartedAt
+ alert.Acknowledged = incident.Acknowledged
+ alert.AckUser = incident.AckUser
+ if incident.Acknowledged && !incident.AckAt.IsZero() {
+ ackAt := incident.AckAt
+ alert.AckTime = &ackAt
+ } else if !incident.Acknowledged {
+ alert.AckTime = nil
+ alert.AckUser = ""
+ }
m.setActiveAlertNoLock(storageKey, alert)
if params.AddToRecent {
m.recentAlerts[trackingKey] = alert
}
+ result.State.State = alertspecs.AlertStateFiring
+ result.State.Severity = matchSeverity
+ result.State.ConsecutiveMatches = incident.Confirmations
+ result.State.FirstMatchedAt = incident.StartedAt
+ result.State.ActiveSince = incident.StartedAt
+
if existing != nil {
+ if primary == reducer.EventSeverityChanged {
+ result.Transition = transition(alertspecs.EvaluationTransitionSeverityChanged, alertspecs.AlertStateFiring, alertspecs.AlertStateFiring)
+ }
return result, true
}
- reactivatedStart, reactivatedAt, reactivated, hadResolvedOccurrence := m.consumeRecentlyResolvedForRefireWithPrimaryLock(storageKey, time.Now())
- if reactivated {
- if !reactivatedStart.IsZero() {
- alert.StartTime = reactivatedStart
- }
+ // Activation. Intent bookkeeping closes out exactly as before.
+ if intent != nil && intent.Explicit {
+ m.clearIntentPendingNoLock(storageKey)
+ m.saveActiveAlertsAsync("lifecycle intent activated")
+ }
+ result.Transition = transition(alertspecs.EvaluationTransitionActivated, alertspecs.AlertStatePending, alertspecs.AlertStateFiring)
+
+ // Consume the recently-resolved entry for map hygiene and the
+ // new-occurrence history distinction; the reducer already decided
+ // whether this is a reactivation (EventRefired) and restored the
+ // start time.
+ _, _, _, hadResolvedOccurrence := m.consumeRecentlyResolvedForRefireWithPrimaryLock(storageKey, time.Now())
+ if primary == reducer.EventRefired {
if params.AddToHistory {
m.historyManager.UpdateAlertLastSeenForAlert(alert, alert.LastSeen)
}
log.Debug().
Str("alertID", storageKey).
- Time("resolvedAt", reactivatedAt).
Msg("Alert re-fired within cooldown, reactivated without new history entry")
if params.RateLimit && !m.checkRateLimit(trackingKey) {
return result, true
@@ -544,31 +592,34 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlert
m.dispatchAlert(alert, params.DispatchAsync)
return result, true
- default:
- if existing == nil {
- return result, true
- }
+ }
- m.removeActiveAlertNoLock(storageKey)
- recoveryEvidence, hasRecoveryEvidence := canonicalAlertEvidenceEnvelope(
- params.Spec,
- params.Evidence,
- existing.Instance,
- time.Now(),
- )
- var recoveryEvidenceRef *operationaltrust.EvidenceEnvelope
- if hasRecoveryEvidence {
- recoveryEvidenceRef = &recoveryEvidence
- }
- resolvedAlert := m.newResolvedAlert(
- existing,
- params.Evidence.ObservedAt,
- recoveryEvidenceRef,
- )
- m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
- m.safeCallResolvedAlertCallback(existing, storageKey, true)
+ // Clear: the core holds no incident for this key.
+ result.State.State = alertspecs.AlertStateClear
+ if existing == nil {
return result, true
}
+
+ result.Transition = transition(alertspecs.EvaluationTransitionRecovered, alertspecs.AlertStateFiring, alertspecs.AlertStateClear)
+ m.removeActiveAlertNoLock(storageKey)
+ recoveryEvidence, hasRecoveryEvidence := canonicalAlertEvidenceEnvelope(
+ params.Spec,
+ params.Evidence,
+ existing.Instance,
+ time.Now(),
+ )
+ var recoveryEvidenceRef *operationaltrust.EvidenceEnvelope
+ if hasRecoveryEvidence {
+ recoveryEvidenceRef = &recoveryEvidence
+ }
+ resolvedAlert := m.newResolvedAlert(
+ existing,
+ params.Evidence.ObservedAt,
+ recoveryEvidenceRef,
+ )
+ m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
+ m.safeCallResolvedAlertCallback(existing, storageKey, true)
+ return result, true
}
func (m *Manager) evaluateCanonicalStatefulAlert(params canonicalStatefulAlertParams) (alertspecs.EvaluationResult, bool) {
diff --git a/internal/alerts/connection.go b/internal/alerts/connection.go
index 339cb8cc2b..afa7f5062c 100644
--- a/internal/alerts/connection.go
+++ b/internal/alerts/connection.go
@@ -291,44 +291,17 @@ func (m *Manager) CheckConnection(snap ConnectionSnapshot) {
// resolve a real outage. Callers hold no manager locks.
func (m *Manager) clearConnectionDegradedAlert(snap ConnectionSnapshot) {
alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+ specKey := canonicalDiscreteStateSpecID(snap.ID, connectionDegradedStateKey)
m.mu.Lock()
defer m.mu.Unlock()
- defer m.shadowObserveRecoveryNoLock(snap.ID, canonicalDiscreteStateSpecID(snap.ID, connectionDegradedStateKey), alertID, offlineRecoveryConfirmationsDefault)
+ defer m.shadowObserveRecoveryNoLock(snap.ID, specKey, alertID, offlineRecoveryConfirmationsDefault)
+ // Reset the legacy degraded counter; the reducer core owns the
+ // confirmation run itself.
if m.connectionDegradedCount[snap.ID] > 0 {
- log.Debug().
- Str("connection", snap.Name).
- Int("previousCount", m.connectionDegradedCount[snap.ID]).
- Msg("Connection healthy, resetting degraded count")
delete(m.connectionDegradedCount, snap.ID)
}
- alert, exists := m.getActiveAlertNoLock(alertID)
- if !exists {
- delete(m.offlineRecoveryConfirmations, alertID)
- return
- }
-
- recoveryCount, confirmed := m.confirmOfflineRecoveryNoLock(alertID, offlineRecoveryConfirmationsDefault)
- if !confirmed {
- log.Debug().
- Str("connection", snap.Name).
- Int("confirmations", recoveryCount).
- Int("required", offlineRecoveryConfirmationsDefault).
- Msg("Connection appears healthy, waiting for recovery confirmation")
- return
- }
-
- m.removeActiveAlertNoLock(alertID)
-
- resolvedAlert := m.newResolvedAlert(alert, time.Now(), nil)
- m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
- m.safeCallResolvedAlertCallback(alert, alertID, true)
-
- log.Info().
- Str("connection", snap.Name).
- Str("connectionID", snap.ID).
- Dur("downtime", time.Since(alert.StartTime)).
- Msg("Connection back to active")
+ m.resolveDiscreteRecoveryNoLock(snap.ID, specKey, alertID, offlineRecoveryConfirmationsDefault, "Connection", snap.Name, snap.ID)
}
diff --git a/internal/alerts/core.go b/internal/alerts/core.go
new file mode 100644
index 0000000000..110a66bad6
--- /dev/null
+++ b/internal/alerts/core.go
@@ -0,0 +1,101 @@
+package alerts
+
+// Authoritative reducer-core plumbing (docs/ALERT_ENGINE_EVOLUTION.md,
+// Phase 2). The core owns transition state for the canonical lifecycle
+// family; manager mutations that originate outside evaluation — user
+// acknowledgements, manual clears, persisted-alert restore — are mirrored
+// into it (and into the shadow feed when enabled) so both reducers track
+// the same reality. All methods are NoLock: callers hold m.mu.
+
+import (
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"
+)
+
+// seedReducerCoreNoLock installs the currently active canonical alerts as
+// firing incidents so a restart resumes them instead of re-running their
+// confirmations.
+func (m *Manager) seedReducerCoreNoLock() {
+ if m == nil || m.core == nil {
+ return
+ }
+ for _, alert := range m.activeAlerts {
+ if alert == nil {
+ continue
+ }
+ backfillCanonicalIdentity(alert)
+ if alert.ResourceID == "" || alert.CanonicalSpecID == "" {
+ continue
+ }
+ ackAt := time.Time{}
+ if alert.AckTime != nil {
+ ackAt = *alert.AckTime
+ }
+ m.core.SeedFiringIncident(
+ alert.ResourceID,
+ alert.CanonicalSpecID,
+ shadowSeverityForLevel(alert.Level),
+ alert.StartTime,
+ alert.Acknowledged,
+ alert.AckUser,
+ ackAt,
+ )
+ }
+}
+
+// mirrorStatesNoLock returns the reducer states that must observe manager
+// mutations: the authoritative core first, then the shadow when enabled.
+func (m *Manager) mirrorStatesNoLock() []*reducer.State {
+ states := make([]*reducer.State, 0, 2)
+ if m.core != nil {
+ states = append(states, m.core)
+ }
+ if m.shadow != nil {
+ states = append(states, m.shadow.state)
+ }
+ return states
+}
+
+// mirrorAcknowledgeNoLock mirrors a user acknowledgement.
+func (m *Manager) mirrorAcknowledgeNoLock(alert *Alert, user string, at time.Time) {
+ if m == nil || alert == nil {
+ return
+ }
+ backfillCanonicalIdentity(alert)
+ if alert.ResourceID == "" || alert.CanonicalSpecID == "" {
+ return
+ }
+ for _, state := range m.mirrorStatesNoLock() {
+ state.Acknowledge(alert.ResourceID, alert.CanonicalSpecID, user, at)
+ }
+}
+
+// mirrorUnacknowledgeNoLock mirrors an acknowledgement removal.
+func (m *Manager) mirrorUnacknowledgeNoLock(alert *Alert) {
+ if m == nil || alert == nil {
+ return
+ }
+ backfillCanonicalIdentity(alert)
+ if alert.ResourceID == "" || alert.CanonicalSpecID == "" {
+ return
+ }
+ for _, state := range m.mirrorStatesNoLock() {
+ state.Unacknowledge(alert.ResourceID, alert.CanonicalSpecID)
+ }
+}
+
+// mirrorForgetAlertNoLock mirrors a manual clear: the reducers drop the
+// incident without treating it as an evaluated recovery.
+func (m *Manager) mirrorForgetAlertNoLock(alert *Alert) {
+ if m == nil || alert == nil {
+ return
+ }
+ backfillCanonicalIdentity(alert)
+ if alert.ResourceID == "" || alert.CanonicalSpecID == "" {
+ return
+ }
+ for _, state := range m.mirrorStatesNoLock() {
+ state.Forget(alert.ResourceID, alert.CanonicalSpecID)
+ }
+}
diff --git a/internal/alerts/guest.go b/internal/alerts/guest.go
index 4316406afb..d8c93275e8 100644
--- a/internal/alerts/guest.go
+++ b/internal/alerts/guest.go
@@ -5,6 +5,7 @@ import (
"strings"
"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/models"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
@@ -558,6 +559,15 @@ func (m *Manager) clearGuestPoweredOffAlert(guestID, name string) {
if decision := m.evaluateIntentNoLock(guestID, "", string(AlertIntentSignalOffline), alertID, m.policyNow().UTC(), false, BackupIntentContext{}); decision.StateChanged {
m.saveActiveAlertsAsync("guest offline intent cleared")
}
+ // A running guest is a healthy observation for the core's powered-state
+ // run: pending clears, and a firing incident resolves immediately (the
+ // powered-off family has no recovery gate).
+ m.core.ApplyDiscrete(reducer.DiscreteSignal{
+ ResourceID: guestID,
+ Key: canonicalPoweredStateSpecID(guestID),
+ Matched: false,
+ ObservedAt: m.policyNow(),
+ }, reducer.DiscreteRule{})
// Check if powered-off alert exists. A guest that moved nodes may still
// hold the alert under its old node-scoped identity; re-home it so it
diff --git a/internal/alerts/history_recurrence_test.go b/internal/alerts/history_recurrence_test.go
index 527ee4bfed..241fd9d1ae 100644
--- a/internal/alerts/history_recurrence_test.go
+++ b/internal/alerts/history_recurrence_test.go
@@ -4,6 +4,7 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
)
@@ -33,6 +34,11 @@ func TestHistoryNewOccurrenceAfterResolveAppendsRow(t *testing.T) {
m.recentlyResolved[key] = resolved
}
m.resolvedMutex.Unlock()
+ // The reducer core keeps its own resolved ledger for refire decisions;
+ // age it in step with the manager's records.
+ m.mu.Lock()
+ m.core.ShiftResolved(-2 * reducer.RefireRetention)
+ m.mu.Unlock()
fire()
diff --git a/internal/alerts/manager.go b/internal/alerts/manager.go
index 911d8febea..6a5857e527 100644
--- a/internal/alerts/manager.go
+++ b/internal/alerts/manager.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog"
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
"github.com/rs/zerolog/log"
)
@@ -66,13 +67,13 @@ type Manager struct {
connectionDegradedCount map[string]int // Track consecutive degraded counts for platform connections (pve/pbs/pmg/vmware/truenas)
offlineConfirmations map[string]int // Track consecutive offline counts for all resources
offlineRecoveryConfirmations map[string]int // Track consecutive healthy confirmations before clearing poll-driven offline alerts
- // lifecycleFirstMatched preserves when a canonical-lifecycle confirmation
- // run first matched, keyed by tracking key. The confirmation maps hold
- // only counts, so without this the reconstructed pending state dated the
- // run at the current observation and activation stamped StartTime at the
- // final confirming poll — understating outage start by the whole
- // confirmation window. Mirrors unifiedIncidentFirstSeen.
- lifecycleFirstMatched map[string]time.Time
+ // core is the authoritative transition state for the canonical
+ // lifecycle (match-spec) family: the deterministic reducer owns
+ // confirmations, pending runs, first-matched anchoring, recovery
+ // gates, re-fire retention, and ack restoration for alerts that flow
+ // through evaluateCanonicalLifecycleAlert and the poll-driven recovery
+ // paths (docs/ALERT_ENGINE_EVOLUTION.md, Phase 2). Access under m.mu.
+ core *reducer.State
unifiedIncidentConfirmations map[string]int // Track consecutive provider-incident observations before activation
unifiedIncidentFirstSeen map[string]time.Time // Preserve the first confirmed observation as lifecycle start
unifiedIncidentRecoveries map[string]int // Track consecutive healthy observations before provider-incident recovery
@@ -192,7 +193,7 @@ func NewManagerWithDataDir(dataDir string, options ...ManagerOption) *Manager {
connectionDegradedCount: make(map[string]int),
offlineConfirmations: make(map[string]int),
offlineRecoveryConfirmations: make(map[string]int),
- lifecycleFirstMatched: make(map[string]time.Time),
+ core: reducer.NewState(),
unifiedIncidentConfirmations: make(map[string]int),
unifiedIncidentFirstSeen: make(map[string]time.Time),
unifiedIncidentRecoveries: make(map[string]int),
@@ -226,6 +227,10 @@ func NewManagerWithDataDir(dataDir string, options ...ManagerOption) *Manager {
log.Error().Err(err).Msg("failed to load active alerts")
}
+ // Seed the authoritative reducer core from restored alerts so a restart
+ // resumes firing incidents instead of re-running their confirmations.
+ m.seedReducerCoreNoLock()
+
// Start background workers.
m.workerWG.Add(3)
go func() {
diff --git a/internal/alerts/node.go b/internal/alerts/node.go
index 5d9dc710fd..340af773a1 100644
--- a/internal/alerts/node.go
+++ b/internal/alerts/node.go
@@ -293,46 +293,11 @@ func (m *Manager) clearNodeOfflineAlert(node models.Node) {
defer m.mu.Unlock()
defer m.shadowObserveRecoveryNoLock(node.ID, canonicalConnectivitySpecID(node.ID), alertID, offlineRecoveryConfirmationsDefault)
- // Reset offline count when node comes back online
+ // Reset the legacy offline counter; the reducer core owns the
+ // confirmation run itself.
if m.nodeOfflineCount[node.ID] > 0 {
- log.Debug().
- Str("node", node.Name).
- Int("previousCount", m.nodeOfflineCount[node.ID]).
- Msg("Node back online, resetting offline count")
delete(m.nodeOfflineCount, node.ID)
}
- // Check if offline alert exists
- alert, exists := m.getActiveAlertNoLock(alertID)
- if !exists {
- delete(m.offlineRecoveryConfirmations, alertID)
- return
- }
-
- recoveryCount, confirmed := m.confirmOfflineRecoveryNoLock(alertID, offlineRecoveryConfirmationsDefault)
- if !confirmed {
- log.Debug().
- Str("node", node.Name).
- Int("confirmations", recoveryCount).
- Int("required", offlineRecoveryConfirmationsDefault).
- Msg("Node appears back online, waiting for recovery confirmation")
- return
- }
-
- // Remove from active alerts
- m.removeActiveAlertNoLock(alertID)
-
- resolvedAlert := m.newResolvedAlert(alert, time.Now(), nil)
- m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
-
- // Send recovery notification (async to avoid deadlock — callback acquires m.mu.RLock
- // via ShouldSuppressResolvedNotification, and we currently hold m.mu.Lock)
- m.safeCallResolvedAlertCallback(alert, alertID, true)
-
- // Log recovery
- log.Info().
- Str("node", node.Name).
- Str("instance", node.Instance).
- Dur("downtime", time.Since(alert.StartTime)).
- Msg("Node is back online")
+ m.resolveDiscreteRecoveryNoLock(node.ID, canonicalConnectivitySpecID(node.ID), alertID, offlineRecoveryConfirmationsDefault, "Node", node.Name, node.Instance)
}
diff --git a/internal/alerts/reducer/discrete.go b/internal/alerts/reducer/discrete.go
index 2b8f4c1862..28e64029a7 100644
--- a/internal/alerts/reducer/discrete.go
+++ b/internal/alerts/reducer/discrete.go
@@ -18,10 +18,18 @@ import "time"
type DiscreteSignal struct {
ResourceID string
// Key identifies the condition, e.g. "connectivity" or a state key.
- Key string
- Matched bool
- Severity Severity
- ObservedAt time.Time
+ Key string
+ Matched bool
+ Severity Severity
+ // RuntimeTick is an optional monotonic process-runtime reading,
+ // valid when RuntimeTickValid is set (zero is a legitimate reading at
+ // process start). When supplied on matched observations, the intent
+ // gate's grace and backup deferral accrue on it instead of ObservedAt
+ // deltas, preserving the manager's wall-clock immunity (suspend and
+ // NTP jumps neither fire nor starve gated activations).
+ RuntimeTick time.Duration
+ RuntimeTickValid bool
+ ObservedAt time.Time
}
// DiscreteRule is the resolved policy for one discrete condition.
@@ -104,6 +112,9 @@ func intentHoldsActivation(intent *DiscreteIntent, incident *Incident, observedA
return false
}
elapsed := observedAt.Sub(incident.PendingSince)
+ if incident.TicksSupplied {
+ elapsed = incident.GraceElapsed
+ }
eligible := time.Duration(intent.GraceSeconds) * time.Second
if intent.BackupEnabled {
if intent.BackupActive {
@@ -245,13 +256,15 @@ func (s *State) ApplyDiscrete(signal DiscreteSignal, rule DiscreteRule) []Event
entered := false
if incident == nil {
incident = &Incident{
- ResourceID: signal.ResourceID,
- Key: signal.Key,
- State: StatePending,
- Severity: signal.Severity,
- PendingSince: signal.ObservedAt,
- Confirmations: 1,
- LastObservedAt: signal.ObservedAt,
+ ResourceID: signal.ResourceID,
+ Key: signal.Key,
+ State: StatePending,
+ Severity: signal.Severity,
+ PendingSince: signal.ObservedAt,
+ Confirmations: 1,
+ TicksSupplied: signal.RuntimeTickValid,
+ LastRuntimeTick: signal.RuntimeTick,
+ LastObservedAt: signal.ObservedAt,
}
s.incidents[key] = incident
entered = true
@@ -259,6 +272,13 @@ func (s *State) ApplyDiscrete(signal DiscreteSignal, rule DiscreteRule) []Event
incident.Confirmations++
incident.Severity = signal.Severity
incident.LastObservedAt = signal.ObservedAt
+ if signal.RuntimeTickValid {
+ if incident.TicksSupplied && signal.RuntimeTick >= incident.LastRuntimeTick {
+ incident.GraceElapsed += signal.RuntimeTick - incident.LastRuntimeTick
+ }
+ incident.TicksSupplied = true
+ incident.LastRuntimeTick = signal.RuntimeTick
+ }
}
pendingResult := func() []Event {
diff --git a/internal/alerts/reducer/reducer.go b/internal/alerts/reducer/reducer.go
index 60a9ccfbdd..148877acc9 100644
--- a/internal/alerts/reducer/reducer.go
+++ b/internal/alerts/reducer/reducer.go
@@ -88,7 +88,13 @@ type Incident struct {
BackupActive bool
BackupEnded bool
BackupEndedElapsed time.Duration
- LastObservedAt time.Time
+ // GraceElapsed accrues the intent gate's condition-active time from the
+ // signal's monotonic RuntimeTick when supplied, making the gate immune
+ // to wall-clock jumps exactly as the manager's intent machinery is.
+ GraceElapsed time.Duration
+ TicksSupplied bool
+ LastRuntimeTick time.Duration
+ LastObservedAt time.Time
}
// EventType enumerates transition events emitted by Apply.
@@ -409,7 +415,7 @@ func (s *State) ApplyMetric(signal MetricSignal, rule MetricRule) []Event {
// 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) {
+func (s *State) SeedFiringIncident(resourceID, subKey string, severity Severity, startedAt time.Time, acknowledged bool, ackUser string, ackAt time.Time) {
key := incidentKey(resourceID, subKey)
incident := &Incident{
ResourceID: resourceID,
@@ -419,11 +425,16 @@ func (s *State) SeedFiringIncident(resourceID, subKey string, severity Severity,
StartedAt: startedAt,
Confirmations: 1,
Acknowledged: acknowledged,
+ AckUser: ackUser,
+ AckAt: ackAt,
LastObservedAt: startedAt,
}
s.incidents[key] = incident
if acknowledged {
- s.acks[key] = ackRecord{At: startedAt}
+ if ackAt.IsZero() {
+ ackAt = startedAt
+ }
+ s.acks[key] = ackRecord{User: ackUser, At: ackAt}
}
}
@@ -433,3 +444,14 @@ func (s *State) SeedFiringIncident(resourceID, subKey string, severity Severity,
func (s *State) Forget(resourceID, subKey string) {
delete(s.incidents, incidentKey(resourceID, subKey))
}
+
+// ShiftResolved moves every resolved-occurrence timestamp by delta
+// (negative = older). It exists for tests and simulations that age
+// resolved records past RefireRetention; production code has no reason to
+// rewrite history.
+func (s *State) ShiftResolved(delta time.Duration) {
+ for key, record := range s.resolved {
+ record.ResolvedAt = record.ResolvedAt.Add(delta)
+ s.resolved[key] = record
+ }
+}
diff --git a/internal/alerts/shadow.go b/internal/alerts/shadow.go
index 8c9de4ed44..e76152c84b 100644
--- a/internal/alerts/shadow.go
+++ b/internal/alerts/shadow.go
@@ -62,12 +62,18 @@ func (m *Manager) EnableShadowFeed() {
if alert.ResourceID == "" || alert.CanonicalSpecID == "" {
continue
}
+ ackAt := time.Time{}
+ if alert.AckTime != nil {
+ ackAt = *alert.AckTime
+ }
feed.state.SeedFiringIncident(
alert.ResourceID,
alert.CanonicalSpecID,
shadowSeverityForLevel(alert.Level),
alert.StartTime,
alert.Acknowledged,
+ alert.AckUser,
+ ackAt,
)
}
m.shadow = feed
@@ -127,7 +133,7 @@ func shadowSpecSeverity(spec alertspecs.ResourceAlertSpec) reducer.Severity {
return reducer.SeverityWarning
}
-func shadowSpecConfirmations(spec alertspecs.ResourceAlertSpec) int {
+func specConfirmationsRequired(spec alertspecs.ResourceAlertSpec) int {
if spec.ConfirmationsRequired > 0 {
return spec.ConfirmationsRequired
}
@@ -163,13 +169,15 @@ func (m *Manager) shadowObserveLifecycleNoLock(
observedAt = m.policyNow()
}
m.shadow.state.ApplyDiscrete(reducer.DiscreteSignal{
- ResourceID: spec.ResourceID,
- Key: spec.ID,
- Matched: matched,
- Severity: shadowSpecSeverity(spec),
- ObservedAt: observedAt,
+ ResourceID: spec.ResourceID,
+ Key: spec.ID,
+ Matched: matched,
+ Severity: shadowSpecSeverity(spec),
+ RuntimeTick: m.intentTickNoLock(),
+ RuntimeTickValid: true,
+ ObservedAt: observedAt,
}, reducer.DiscreteRule{
- Confirmations: shadowSpecConfirmations(spec),
+ Confirmations: specConfirmationsRequired(spec),
Disabled: spec.Disabled,
Intent: intent,
})
@@ -193,44 +201,6 @@ func (m *Manager) shadowObserveRecoveryNoLock(resourceID, specKey, managerAlertI
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
@@ -259,11 +229,17 @@ func (m *Manager) shadowCompareNoLock(resourceID, specKey, managerAlertID string
// Resync before rate limiting so state converges even when the report
// is suppressed.
if managerFiring {
+ ackAt := time.Time{}
+ if alert.AckTime != nil {
+ ackAt = *alert.AckTime
+ }
feed.state.SeedFiringIncident(
resourceID, specKey,
shadowSeverityForLevel(alert.Level),
alert.StartTime,
alert.Acknowledged,
+ alert.AckUser,
+ ackAt,
)
} else {
feed.state.Forget(resourceID, specKey)
diff --git a/internal/alerts/shadow_feed_test.go b/internal/alerts/shadow_feed_test.go
index b93e59cf2a..3a4324ff30 100644
--- a/internal/alerts/shadow_feed_test.go
+++ b/internal/alerts/shadow_feed_test.go
@@ -115,7 +115,7 @@ func TestShadowFeedRecordsAndResyncsDivergence(t *testing.T) {
manager.mu.Lock()
manager.shadow.state.SeedFiringIncident(
resourceID, canonicalConnectivitySpecID(resourceID),
- reducer.SeverityCritical, time.Now().Add(-time.Minute), false,
+ reducer.SeverityCritical, time.Now().Add(-time.Minute), false, "", time.Time{},
)
manager.mu.Unlock()
diff --git a/internal/alerts/specs/evaluator.go b/internal/alerts/specs/evaluator.go
index 9aba2ec1aa..631ca2b60c 100644
--- a/internal/alerts/specs/evaluator.go
+++ b/internal/alerts/specs/evaluator.go
@@ -432,6 +432,22 @@ func terminalEvaluation(spec ResourceAlertSpec, previous EvaluatorState, evidenc
return result
}
+// ValidateEvidence reports whether the evidence carries the payload the
+// spec kind requires, mirroring Evaluate's up-front check for callers that
+// use Match directly.
+func ValidateEvidence(kind AlertSpecKind, evidence AlertEvidence) error {
+ return evidence.validateForKind(kind)
+}
+
+// Match reports whether one observation matches a spec's trigger
+// condition, with the severity and reason the match carries. It is the
+// spec-domain predicate shared by the evaluator and the reducer-backed
+// lifecycle wrapper: transition logic changes engines, the match
+// predicate does not.
+func Match(spec ResourceAlertSpec, evidence AlertEvidence) (bool, AlertSeverity, string) {
+ return matches(spec, evidence)
+}
+
func matches(spec ResourceAlertSpec, evidence AlertEvidence) (bool, AlertSeverity, string) {
switch spec.Kind {
case AlertSpecKindSeverityThreshold:
diff --git a/internal/alerts/test_helpers_test.go b/internal/alerts/test_helpers_test.go
index 3ebd75ee84..57fec80ce7 100644
--- a/internal/alerts/test_helpers_test.go
+++ b/internal/alerts/test_helpers_test.go
@@ -3,6 +3,9 @@ package alerts
import (
"strings"
"testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"
)
func testNewCanonicalAlert(resourceID, specID, kind, alertType string) (string, *Alert) {
@@ -187,3 +190,49 @@ func testLookupResolvedAlert(t testing.TB, m *Manager, alertID string) (*Resolve
}
return nil, false
}
+
+// testCoreConfirmations reads the reducer core's confirmation count for a
+// key — the post-cutover replacement for asserting the legacy count maps.
+func testCoreConfirmations(m *Manager, resourceID, specID string) int {
+ incident, ok := m.core.Incident(resourceID, specID)
+ if !ok {
+ return 0
+ }
+ return incident.Confirmations
+}
+
+// testCoreRecoveryCount reads the reducer core's consecutive-healthy count
+// for a firing incident.
+func testCoreRecoveryCount(m *Manager, resourceID, specID string) int {
+ incident, ok := m.core.Incident(resourceID, specID)
+ if !ok {
+ return 0
+ }
+ return incident.RecoveryCount
+}
+
+// testCoreHasIncident reports whether the reducer core tracks any incident
+// (pending or firing) for the key.
+func testCoreHasIncident(m *Manager, resourceID, specID string) bool {
+ _, ok := m.core.Incident(resourceID, specID)
+ return ok
+}
+
+// testSeedCoreConfirmations fast-forwards a confirmation run in the
+// reducer core — the post-cutover replacement for pre-seeding the legacy
+// count maps. It applies matched observations directly to the core so the
+// next real observation is the Nth confirmation.
+func testSeedCoreConfirmations(m *Manager, resourceID, specID string, count int, severity reducer.Severity, confirmationsRequired int) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ base := time.Now().Add(-time.Duration(count) * time.Minute)
+ for i := 0; i < count; i++ {
+ m.core.ApplyDiscrete(reducer.DiscreteSignal{
+ ResourceID: resourceID,
+ Key: specID,
+ Matched: true,
+ Severity: severity,
+ ObservedAt: base.Add(time.Duration(i) * time.Minute),
+ }, reducer.DiscreteRule{Confirmations: confirmationsRequired})
+ }
+}
diff --git a/internal/alerts/tracking_cleanup.go b/internal/alerts/tracking_cleanup.go
index 69fa3fea24..ec77ca3bc6 100644
--- a/internal/alerts/tracking_cleanup.go
+++ b/internal/alerts/tracking_cleanup.go
@@ -92,25 +92,6 @@ func (m *Manager) cleanupStaleMaps() {
}
}
- // lifecycleFirstMatched entries share tracking keys with the
- // confirmation-count maps and follow the same retention rule: keep only
- // while a related active alert exists. A leaked entry would otherwise
- // backdate an unrelated future confirmation run for the same key.
- for trackingKey := range m.lifecycleFirstMatched {
- hasRelatedAlert := false
- for storageKey, alert := range m.activeAlerts {
- alertID := effectiveAlertID(alert, storageKey)
- if strings.Contains(alertID, trackingKey) || strings.Contains(trackingKey, alert.ResourceID) {
- hasRelatedAlert = true
- break
- }
- }
- if !hasRelatedAlert {
- delete(m.lifecycleFirstMatched, trackingKey)
- cleaned++
- }
- }
-
for nodeID := range m.nodeOfflineCount {
hasRelatedAlert := false
for storageKey, alert := range m.activeAlerts {
diff --git a/internal/alerts/unified_eval_test.go b/internal/alerts/unified_eval_test.go
index c7d9561a72..4a808e7e54 100644
--- a/internal/alerts/unified_eval_test.go
+++ b/internal/alerts/unified_eval_test.go
@@ -1116,16 +1116,20 @@ func TestCheckNodeOfflineAnnotatesCanonicalSpecMetadata(t *testing.T) {
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.mu.Lock()
- m.nodeOfflineCount["node/pve-1"] = 2
m.mu.Unlock()
- m.CheckNode(models.Node{
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ target := models.Node{
ID: "node/pve-1",
Name: "pve-1",
Instance: "pve1",
Status: "offline",
ConnectionHealth: "failed",
- })
+ }
+ m.CheckNode(target)
+ m.CheckNode(target)
+ m.CheckNode(target)
alert := activeAlert(t, m, buildCanonicalStateID("node/pve-1", "node/pve-1-connectivity"))
if got := alert.Metadata["canonicalAlertKind"]; got != "connectivity" {
@@ -1141,16 +1145,20 @@ func TestCheckPBSOfflineAnnotatesCanonicalSpecMetadata(t *testing.T) {
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.mu.Lock()
- m.offlineConfirmations["pbs-1"] = 2
m.mu.Unlock()
- m.CheckPBS(models.PBSInstance{
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ target := models.PBSInstance{
ID: "pbs-1",
Name: "pbs-main",
Host: "pbs-host",
Status: "online",
ConnectionHealth: "unhealthy",
- })
+ }
+ m.CheckPBS(target)
+ m.CheckPBS(target)
+ m.CheckPBS(target)
alert := activeAlert(t, m, "pbs-offline-pbs-1")
if got := alert.Metadata["canonicalAlertKind"]; got != "connectivity" {
@@ -1166,16 +1174,19 @@ func TestCheckStorageOfflineAnnotatesCanonicalSpecMetadata(t *testing.T) {
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.mu.Lock()
- m.offlineConfirmations["storage-1"] = 1
m.mu.Unlock()
- m.CheckStorage(models.Storage{
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ target := models.Storage{
ID: "storage-1",
Name: "local-lvm",
Node: "pve-1",
Instance: "pve1",
Status: "unavailable",
- })
+ }
+ m.CheckStorage(target)
+ m.CheckStorage(target)
alert := activeAlert(t, m, "storage-offline-storage-1")
if got := alert.Metadata["canonicalAlertKind"]; got != "connectivity" {
@@ -1191,16 +1202,20 @@ func TestCheckPMGOfflineAnnotatesCanonicalSpecMetadata(t *testing.T) {
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.mu.Lock()
- m.offlineConfirmations["pmg-1"] = 2
m.mu.Unlock()
- m.CheckPMG(models.PMGInstance{
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ target := models.PMGInstance{
ID: "pmg-1",
Name: "pmg-main",
Host: "pmg-host",
Status: "online",
ConnectionHealth: "unhealthy",
- })
+ }
+ m.CheckPMG(target)
+ m.CheckPMG(target)
+ m.CheckPMG(target)
alert := activeAlert(t, m, "pmg-offline-pmg-1")
if got := alert.Metadata["canonicalAlertKind"]; got != "connectivity" {
@@ -1216,15 +1231,19 @@ func TestHandleDockerHostOfflineAnnotatesCanonicalSpecMetadata(t *testing.T) {
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.mu.Lock()
- m.dockerOfflineCount["docker1"] = 2
m.mu.Unlock()
- m.HandleDockerHostOffline(models.DockerHost{
+ // Confirmation runs live in the reducer core: drive the
+ // preceding observations for real instead of seeding maps.
+ target := models.DockerHost{
ID: "docker1",
DisplayName: "Docker Host 1",
Hostname: "docker.local",
AgentID: "agent-123",
- })
+ }
+ m.HandleDockerHostOffline(target)
+ m.HandleDockerHostOffline(target)
+ m.HandleDockerHostOffline(target)
alert := activeAlert(t, m, "docker-host-offline-docker1")
if got := alert.Metadata["canonicalAlertKind"]; got != "connectivity" {
diff --git a/internal/alerts/unified_incident_confirmation_test.go b/internal/alerts/unified_incident_confirmation_test.go
index 2151bc8685..aae80fedb4 100644
--- a/internal/alerts/unified_incident_confirmation_test.go
+++ b/internal/alerts/unified_incident_confirmation_test.go
@@ -198,10 +198,10 @@ func TestLifecycleAlertStartTimeIsFirstMatchedObservation(t *testing.T) {
observe("online", epoch.Add(90*time.Second))
manager.mu.Lock()
- _, tracked := manager.lifecycleFirstMatched["conn:node-9"]
+ _, hasIncident := manager.core.Incident("node-9", "node-9-connectivity")
manager.mu.Unlock()
- if tracked {
- t.Fatal("first-matched entry should clear with the confirmation run")
+ if hasIncident {
+ t.Fatal("core incident should clear with the confirmation run")
}
}
@@ -227,12 +227,12 @@ func confirmedProviderIncidentResource(observedAt time.Time) unifiedresources.Re
}
}
-// Regression: several callers reset the confirmation-count maps directly
-// without the evaluator path (clearResourceOfflineAlert among them), which
-// left a stale lifecycleFirstMatched entry that backdated the next run's
-// alert to the previous run's first observation. A new run (pre-evaluation
-// count zero) must re-stamp the first-matched time.
-func TestLifecycleFirstMatchedRestampsAfterDirectCountReset(t *testing.T) {
+// The reducer core owns confirmation runs: resetting the legacy count
+// maps directly (the pre-cutover healthy-poll behavior) no longer
+// disturbs a run in progress — only a genuine non-matching observation
+// resets it. This replaces the pre-cutover restamp regression test, whose
+// premise (reconstructing runs from the count maps) no longer exists.
+func TestLifecycleRunImmuneToLegacyCountResets(t *testing.T) {
manager := NewManagerWithDataDir(t.TempDir(), WithoutPersistedAlertRestore())
t.Cleanup(manager.Stop)
@@ -267,26 +267,35 @@ func TestLifecycleFirstMatchedRestampsAfterDirectCountReset(t *testing.T) {
}
}
- // Two matches begin a run, then the count is reset directly, the way
- // the healthy-poll paths do — leaving lifecycleFirstMatched stale.
+ // Two matches begin a run; a direct legacy count reset is a no-op for
+ // the core-owned run, so the third consecutive match fires with the
+ // run's true first observation as the start.
observe("offline", epoch)
observe("offline", epoch.Add(30*time.Second))
manager.mu.Lock()
delete(manager.offlineConfirmations, "conn:node-9")
manager.mu.Unlock()
-
- restart := epoch.Add(2 * time.Minute)
- observe("offline", restart)
- observe("offline", restart.Add(30*time.Second))
- observe("offline", restart.Add(60*time.Second))
+ observe("offline", epoch.Add(time.Minute))
manager.mu.Lock()
alert, exists := manager.getActiveAlertNoLock(canonicalDiscreteStateStateID("node-9", "connectivity"))
manager.mu.Unlock()
if !exists || alert == nil {
- t.Fatal("expected alert to fire after the second run")
+ t.Fatal("expected alert to fire on the third consecutive match")
}
- if !alert.StartTime.Equal(restart) {
- t.Fatalf("StartTime = %v, want the second run's first observation %v", alert.StartTime, restart)
+ if !alert.StartTime.Equal(epoch) {
+ t.Fatalf("StartTime = %v, want the run's first observation %v", alert.StartTime, epoch)
+ }
+
+ // A genuine non-matching observation does reset the run.
+ observe("online", epoch.Add(90*time.Second))
+ restart := epoch.Add(2 * time.Minute)
+ observe("offline", restart)
+ observe("offline", restart.Add(30*time.Second))
+ manager.mu.Lock()
+ _, midRun := manager.getActiveAlertNoLock(canonicalDiscreteStateStateID("node-9", "connectivity"))
+ manager.mu.Unlock()
+ if midRun {
+ t.Fatal("run must restart after a genuine recovery")
}
}