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 metric-threshold family over to the reducer core, emit lifecycle fired events

rcourtmanb1b35bf09327
diff --git a/internal/alerts/canonical_lifecycle.go b/internal/alerts/canonical_lifecycle.go
index 1e88876b66..26bd5ea622 100644
--- a/internal/alerts/canonical_lifecycle.go
+++ b/internal/alerts/canonical_lifecycle.go
@@ -4,6 +4,7 @@ import (
"strings"
"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/operationaltrust"
@@ -554,6 +555,12 @@ func (m *Manager) evaluateCanonicalLifecycleAlert(params canonicalLifecycleAlert
}
result.Transition = transition(alertspecs.EvaluationTransitionActivated, alertspecs.AlertStatePending, alertspecs.AlertStateFiring)
+ firedType := eventlog.TypeFired
+ if primary == reducer.EventRefired {
+ firedType = eventlog.TypeRefired
+ }
+ m.recordAlertEvent(firedType, alert, storageKey, matchReason, params.Message, nil)
+
// 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
diff --git a/internal/alerts/eventlog/eventlog.go b/internal/alerts/eventlog/eventlog.go
index 66a78d1878..558d14a59e 100644
--- a/internal/alerts/eventlog/eventlog.go
+++ b/internal/alerts/eventlog/eventlog.go
@@ -24,11 +24,14 @@ import (
_ "modernc.org/sqlite"
)
-// Event types recorded by the alert manager. Lifecycle "fired" is
-// deliberately absent: the active-alert store funnel also runs on persisted
-// restore, so firing cannot be recorded there without misreporting restarts.
-// It arrives with the explicit activation seam in a later phase.
+// Event types recorded by the alert manager.
const (
+ // TypeFired marks a new occurrence activating; TypeRefired marks a
+ // reactivation that resumed a recently resolved occurrence. Both come
+ // from the reducer core's explicit activation events, so persisted
+ // restores are never misreported as firings.
+ TypeFired = "fired"
+ TypeRefired = "refired"
TypeResolved = "resolved"
TypeAcknowledged = "acknowledged"
TypeUnacknowledged = "unacknowledged"
diff --git a/internal/alerts/metric_runtime.go b/internal/alerts/metric_runtime.go
index 5b369242d1..8bd479d53a 100644
--- a/internal/alerts/metric_runtime.go
+++ b/internal/alerts/metric_runtime.go
@@ -5,6 +5,8 @@ import (
"strings"
"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/rs/zerolog/log"
)
@@ -179,20 +181,20 @@ func (m *Manager) checkMetric(resourceID, resourceName, node, instance, resource
// A guest that moved nodes may hold this alert under its old node-scoped
// identity; re-home it first so the clear below can resolve it.
m.rehomeStrandedGuestAlert(canonicalStateID, canonicalSpecID, string(alertspecs.AlertSpecKindMetricThreshold), resourceID, resourceName, node, instance, resourceType)
+ m.mu.Lock()
+ m.core.ApplyMetric(reducer.MetricSignal{
+ ResourceID: resourceID,
+ Key: canonicalSpecID,
+ Metric: metricType,
+ Value: value,
+ ObservedAt: time.Now(),
+ }, reducer.MetricRule{})
+ m.mu.Unlock()
m.clearAlert(canonicalStateID)
m.clearAlert(alertID)
return
}
- log.Debug().
- Str("resource", resourceName).
- Str("metric", metricType).
- Float64("value", value).
- Float64("trigger", threshold.Trigger).
- Float64("clear", threshold.Clear).
- Bool("exceeds", value >= threshold.Trigger).
- Msg("Checking metric threshold")
-
m.mu.Lock()
migratedAlertIdentity := false
defer func() {
@@ -229,208 +231,102 @@ func (m *Manager) checkMetric(resourceID, resourceName, node, instance, resource
return
}
- if value >= threshold.Trigger {
- // Threshold exceeded
- if !exists {
- alertStartTime := time.Now()
-
- effectiveIntent := m.resolveEffectiveIntentPolicyNoLock(resourceID, resourceType, MetricAlertIntentSignal(metricType))
- if effectiveIntent.Explicit {
- decision := m.evaluateIntentNoLock(resourceID, resourceType, MetricAlertIntentSignal(metricType), trackingKey, alertStartTime, true, BackupIntentContext{})
- if pending, ok := m.intentPending[trackingKey]; ok && !pending.FirstMatchedAt.IsZero() {
- alertStartTime = pending.FirstMatchedAt
- }
- if decision.StateChanged {
- m.saveActiveAlertsAsync("metric intent pending state")
- }
- if !decision.ShouldActivate {
- return
- }
- m.clearIntentPendingNoLock(trackingKey)
- m.saveActiveAlertsAsync("metric intent activated")
- } else if timeThreshold := m.getTimeThreshold(resourceID, resourceType, metricType); timeThreshold > 0 {
- // Check if this threshold was already pending
- if pendingTime, isPending := m.pendingAlerts[trackingKey]; isPending {
- // Check if enough time has passed
- if time.Since(pendingTime) >= time.Duration(timeThreshold)*time.Second {
- // Time threshold met, proceed with alert
- delete(m.pendingAlerts, trackingKey)
- if !pendingTime.IsZero() {
- alertStartTime = pendingTime
- }
- log.Debug().
- Str("alertID", alertID).
- Int("timeThreshold", timeThreshold).
- Dur("elapsed", time.Since(pendingTime)).
- Msg("Time threshold met, triggering alert")
- } else {
- // Still waiting for time threshold
- log.Debug().
- Str("alertID", alertID).
- Int("timeThreshold", timeThreshold).
- Dur("elapsed", time.Since(pendingTime)).
- Msg("Threshold exceeded but waiting for time threshold")
- return
- }
- } else {
- // First time exceeding threshold, start tracking
- m.pendingAlerts[trackingKey] = alertStartTime
- log.Debug().
- Str("alertID", alertID).
- Str("trackingKey", trackingKey).
- Int("timeThreshold", timeThreshold).
- Msg("Threshold exceeded, starting time threshold tracking")
- return
- }
- }
-
- // Check for recent similar alert to prevent spam
- if recent, hasRecent := m.recentAlerts[trackingKey]; hasRecent {
- // Check minimum delta
- if m.config.MinimumDelta > 0 &&
- time.Since(recent.StartTime) < time.Duration(m.config.SuppressionWindow)*time.Minute &&
- abs(recent.Value-value) < m.config.MinimumDelta {
- log.Debug().
- Str("alertID", alertID).
- Float64("recentValue", recent.Value).
- Float64("currentValue", value).
- Float64("delta", abs(recent.Value-value)).
- Float64("minimumDelta", m.config.MinimumDelta).
- Msg("Alert suppressed due to minimum delta")
-
- // Set suppression window
- m.suppressedUntil[trackingKey] = time.Now().Add(time.Duration(m.config.SuppressionWindow) * time.Minute)
- return
- }
- }
-
- // New alert
- message := ""
- var unit string
- if opts != nil && opts.Message != "" {
- message = opts.Message
- } else {
- switch metricType {
- case "usage":
- message = fmt.Sprintf("%s at %.1f%%", resourceType, value)
- case "diskRead", "diskWrite", "networkIn", "networkOut":
- message = fmt.Sprintf("%s %s at %.1f MB/s", resourceType, metricType, value)
- unit = "MB/s"
- case "temperature", "disk_temperature", "diskTemperature":
- message = fmt.Sprintf("%s %s at %.1f°C", resourceType, metricType, value)
- unit = "°C"
- default:
- message = fmt.Sprintf("%s %s at %.1f%%", resourceType, metricType, value)
- }
+ // An existing alert the core does not know about (guest migration,
+ // direct injection) means it was firing: adopt it.
+ if exists && existingAlert != nil {
+ if _, known := m.core.Incident(resourceID, canonicalSpecID); !known {
+ ackAt := time.Time{}
+ if existingAlert.AckTime != nil {
+ ackAt = *existingAlert.AckTime
}
+ m.core.SeedFiringIncident(resourceID, canonicalSpecID, shadowSeverityForLevel(existingAlert.Level), existingAlert.StartTime, existingAlert.Acknowledged, existingAlert.AckUser, ackAt)
+ }
+ }
- alertMetadata := map[string]interface{}{
- "resourceType": resourceType,
- "clearThreshold": threshold.Clear,
- }
- if unit != "" {
- alertMetadata["unit"] = unit
- }
- if opts != nil && opts.Metadata != nil {
- for k, v := range opts.Metadata {
- alertMetadata[k] = v
- }
- }
- alertMetadata["monitorOnly"] = monitorOnly
-
- alert := &Alert{
- ID: alertID,
- Type: metricType,
- Level: AlertLevelWarning,
- ResourceID: resourceID,
- ResourceName: resourceName,
- Node: node,
- NodeDisplayName: m.resolveNodeDisplayName(instance, node),
- Instance: instance,
- Message: message,
- Value: value,
- Threshold: threshold.Trigger,
- StartTime: alertStartTime,
- LastSeen: time.Now(),
- Metadata: alertMetadata,
+ // Suppress a would-be new occurrence when it is within the minimum
+ // delta of a recent one (spam guard), before it reaches the core.
+ coreIncidentBefore, hadCoreIncident := m.core.Incident(resourceID, canonicalSpecID)
+ wouldBeNew := !hadCoreIncident || coreIncidentBefore.State != reducer.StateFiring
+ if wouldBeNew && value >= threshold.Trigger {
+ if recent, hasRecent := m.recentAlerts[trackingKey]; hasRecent {
+ if m.config.MinimumDelta > 0 &&
+ time.Since(recent.StartTime) < time.Duration(m.config.SuppressionWindow)*time.Minute &&
+ abs(recent.Value-value) < m.config.MinimumDelta {
+ log.Debug().
+ Str("alertID", alertID).
+ Float64("recentValue", recent.Value).
+ Float64("currentValue", value).
+ Float64("minimumDelta", m.config.MinimumDelta).
+ Msg("Alert suppressed due to minimum delta")
+ m.suppressedUntil[trackingKey] = time.Now().Add(time.Duration(m.config.SuppressionWindow) * time.Minute)
+ return
}
- applyCanonicalIdentity(alert, canonicalSpecID, string(alertspecs.AlertSpecKindMetricThreshold))
+ }
+ }
- // Set level based on how much over threshold
- if value >= computeCriticalThreshold(threshold.Trigger, metricType) {
- alert.Level = AlertLevelCritical
- }
+ // Intent context: explicit metric policies replace the legacy
+ // time-threshold delay; the gate itself lives in the reducer.
+ conditionActive := value >= threshold.Trigger
+ effectiveIntent := m.resolveEffectiveIntentPolicyNoLock(resourceID, resourceType, MetricAlertIntentSignal(metricType))
+ var intent *reducer.DiscreteIntent
+ delaySeconds := 0
+ if effectiveIntent.Explicit {
+ decision := m.evaluateIntentNoLock(resourceID, resourceType, MetricAlertIntentSignal(metricType), trackingKey, time.Now(), conditionActive, BackupIntentContext{})
+ if decision.StateChanged {
+ m.saveActiveAlertsAsync("metric intent pending state")
+ }
+ intent = &reducer.DiscreteIntent{
+ Explicit: decision.Effective.Explicit,
+ GraceSeconds: decision.Effective.GraceSeconds,
+ OperatorSuppressed: decision.Suppressed && strings.HasPrefix(decision.Reason, "operator_"),
+ OperatorReason: decision.Reason,
+ }
+ } else if conditionActive {
+ delaySeconds = m.getTimeThreshold(resourceID, resourceType, metricType)
+ }
- log.Debug().
- Str("alertID", alertID).
- Time("alertStartTime", alertStartTime).
- Time("now", time.Now()).
- Dur("initialDuration", time.Since(alertStartTime)).
- Msg("Creating new alert with start time")
+ events := m.core.ApplyMetric(reducer.MetricSignal{
+ ResourceID: resourceID,
+ Key: canonicalSpecID,
+ Metric: metricType,
+ Value: value,
+ RuntimeTick: m.intentTickNoLock(),
+ RuntimeTickValid: true,
+ ObservedAt: time.Now(),
+ }, reducer.MetricRule{
+ Trigger: threshold.Trigger,
+ Clear: threshold.Clear,
+ DelaySeconds: delaySeconds,
+ Intent: intent,
+ })
+ primary := reducer.EventType("")
+ if len(events) > 0 {
+ primary = events[0].Type
+ }
- m.preserveAlertState(canonicalStateID, alert)
- trackingKey = canonicalTrackingKeyOrFallback(alert, canonicalStateID)
- m.setActiveAlertNoLock(canonicalStateID, alert)
- m.recentAlerts[trackingKey] = alert
- m.historyManager.AddAlert(*alert)
+ incident, hasIncident := m.core.Incident(resourceID, canonicalSpecID)
- m.saveActiveAlertsAsync("metric create")
+ if hasIncident && incident.State == reducer.StatePending {
+ return
+ }
- log.Warn().
- Str("alertID", alertID).
- Str("resource", resourceName).
- Str("metric", metricType).
- Float64("value", value).
- Float64("trigger", threshold.Trigger).
- Float64("clear", threshold.Clear).
- Int("activeAlerts", len(m.activeAlerts)).
- Msg("Alert triggered")
-
- // Trigger AI analysis callback unconditionally (bypasses notification suppression)
- if callbacks := m.getAlertForAICallbacks(); len(callbacks) > 0 {
- alertCopy := cloneAlertForOutput(alert)
- go func(a *Alert, fns []func(*Alert)) {
- defer func() {
- if r := recover(); r != nil {
- log.Error().Interface("panic", r).Str("alertID", a.ID).Msg("panic in AI alert callback")
- }
- }()
- for _, callback := range fns {
- callback(a)
- }
- }(alertCopy, callbacks)
- }
+ if hasIncident && incident.State == reducer.StateFiring {
+ if intent != nil && intent.Explicit && (primary == reducer.EventFired || primary == reducer.EventRefired) {
+ m.clearIntentPendingNoLock(trackingKey)
+ m.saveActiveAlertsAsync("metric intent activated")
+ }
- // Check rate limit (but don't remove alert from tracking)
- if !m.checkRateLimit(trackingKey) {
- log.Debug().
- Str("alertID", alertID).
- Str("trackingKey", trackingKey).
- Int("maxPerHour", m.config.Schedule.MaxAlertsHour).
- Msg("Alert notification suppressed due to rate limit")
- // Don't delete the alert, just suppress notifications
- return
- }
+ level := AlertLevelWarning
+ if incident.Severity == reducer.SeverityCritical {
+ level = AlertLevelCritical
+ }
- // Notify callback (may be suppressed by quiet hours)
- if len(m.getAlertCallbacks()) > 0 {
- now := time.Now()
- alert.LastNotified = &now
- if m.dispatchAlert(alert, true) {
- log.Info().Str("alertID", alertID).Msg("calling onAlert callback")
- } else {
- alert.LastNotified = nil
- }
- } else {
- log.Warn().Msg("no onAlert callback set!")
- }
- } else {
+ if exists && existingAlert != nil {
// Update existing alert
applyCanonicalIdentity(existingAlert, canonicalSpecID, string(alertspecs.AlertSpecKindMetricThreshold))
m.setActiveAlertNoLock(canonicalStateID, existingAlert)
existingAlert.LastSeen = time.Now()
existingAlert.Value = value
- // Keep display name current (handles upgrades and renames).
if dn := m.resolveNodeDisplayName(existingAlert.Instance, existingAlert.Node); dn != "" {
existingAlert.NodeDisplayName = dn
}
@@ -451,13 +347,8 @@ func (m *Manager) checkMetric(resourceID, resourceName, node, instance, resource
}
}
- // Update level if needed
oldLevel := existingAlert.Level
- if value >= computeCriticalThreshold(threshold.Trigger, metricType) {
- existingAlert.Level = AlertLevelCritical
- } else {
- existingAlert.Level = AlertLevelWarning
- }
+ existingAlert.Level = level
// Check if we should re-notify based on cooldown period
// Never re-notify acknowledged alerts (user has already seen it)
@@ -468,27 +359,14 @@ func (m *Manager) checkMetric(resourceID, resourceName, node, instance, resource
Msg("Alert is acknowledged, skipping re-notification")
} else if m.shouldNotifyAfterCooldown(existingAlert) {
shouldRenotify = m.allowNotificationByRateLimit(trackingKey, existingAlert, "cooldown")
- if shouldRenotify {
- log.Debug().
- Str("alertID", alertID).
- Dur("cooldown", time.Duration(m.config.Schedule.Cooldown)*time.Minute).
- Msg("Cooldown period has passed, will re-notify")
- }
} else if oldLevel != existingAlert.Level && existingAlert.Level == AlertLevelCritical {
// Always re-notify if alert escalated to critical
shouldRenotify = m.allowNotificationByRateLimit(trackingKey, existingAlert, "critical-escalation")
- if shouldRenotify {
- log.Debug().
- Str("alertID", alertID).
- Msg("Alert escalated to critical, will re-notify despite cooldown")
- }
}
- // Send re-notification if appropriate (may be suppressed by quiet hours)
if shouldRenotify && len(m.getAlertCallbacks()) > 0 {
now := time.Now()
existingAlert.LastNotified = &now
- // Dispatch asynchronously so callback I/O cannot block alert evaluation.
if m.dispatchAlert(existingAlert, true) {
log.Info().
Str("alertID", alertID).
@@ -498,61 +376,147 @@ func (m *Manager) checkMetric(resourceID, resourceName, node, instance, resource
existingAlert.LastNotified = nil
}
}
- }
- } else {
- // Value is below trigger threshold
- intentDecision := m.evaluateIntentNoLock(resourceID, resourceType, MetricAlertIntentSignal(metricType), trackingKey, time.Now(), false, BackupIntentContext{})
- if intentDecision.StateChanged {
- m.saveActiveAlertsAsync("metric intent cleared")
- }
- // Clear any pending alert for this metric
- if _, isPending := m.pendingAlerts[trackingKey]; isPending {
- delete(m.pendingAlerts, trackingKey)
- log.Debug().
- Str("alertID", alertID).
- Str("trackingKey", trackingKey).
- Msg("Value dropped below threshold, clearing pending alert")
+ return
}
- if exists {
- // Use hysteresis for resolution - only resolve if below clear threshold
- clearThreshold := threshold.Clear
- if clearThreshold <= 0 {
- clearThreshold = threshold.Trigger // Fallback to trigger if clear not set
+ // New occurrence.
+ message := ""
+ var unit string
+ if opts != nil && opts.Message != "" {
+ message = opts.Message
+ } else {
+ switch metricType {
+ case "usage":
+ message = fmt.Sprintf("%s at %.1f%%", resourceType, value)
+ case "diskRead", "diskWrite", "networkIn", "networkOut":
+ message = fmt.Sprintf("%s %s at %.1f MB/s", resourceType, metricType, value)
+ unit = "MB/s"
+ case "temperature", "disk_temperature", "diskTemperature":
+ message = fmt.Sprintf("%s %s at %.1f°C", resourceType, metricType, value)
+ unit = "°C"
+ default:
+ message = fmt.Sprintf("%s %s at %.1f%%", resourceType, metricType, value)
}
+ }
- if value <= clearThreshold {
- // Threshold cleared with hysteresis - auto resolve
- resolvedAlert := m.newResolvedAlert(existingAlert, time.Now(), nil)
-
- // Remove from active alerts by the key it is actually stored
- // under. Canonical-identity alerts are keyed by canonical
- // state, and the legacy alertID is not registered as an
- // alias, so removing by alertID silently no-ops and leaves a
- // stale active alert that re-resolves on every poll.
- m.removeActiveAlertNoLock(activeAlertStorageKey(existingAlert, alertID))
-
- m.saveActiveAlertsAsync("metric resolution")
+ alertMetadata := map[string]interface{}{
+ "resourceType": resourceType,
+ "clearThreshold": threshold.Clear,
+ }
+ if unit != "" {
+ alertMetadata["unit"] = unit
+ }
+ if opts != nil && opts.Metadata != nil {
+ for k, v := range opts.Metadata {
+ alertMetadata[k] = v
+ }
+ }
+ alertMetadata["monitorOnly"] = monitorOnly
+
+ alert := &Alert{
+ ID: alertID,
+ Type: metricType,
+ Level: level,
+ ResourceID: resourceID,
+ ResourceName: resourceName,
+ Node: node,
+ NodeDisplayName: m.resolveNodeDisplayName(instance, node),
+ Instance: instance,
+ Message: message,
+ Value: value,
+ Threshold: threshold.Trigger,
+ StartTime: incident.StartedAt,
+ LastSeen: time.Now(),
+ Metadata: alertMetadata,
+ }
+ applyCanonicalIdentity(alert, canonicalSpecID, string(alertspecs.AlertSpecKindMetricThreshold))
+
+ m.preserveAlertState(canonicalStateID, 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 = ""
+ }
+ trackingKey = canonicalTrackingKeyOrFallback(alert, canonicalStateID)
+ m.setActiveAlertNoLock(canonicalStateID, alert)
+ m.recentAlerts[trackingKey] = alert
+ m.historyManager.AddAlert(*alert)
+ m.recordAlertEvent(eventlog.TypeFired, alert, canonicalStateID, "metric-threshold", message, nil)
- // Add to recently resolved while preventing lock-order inversions
- m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
+ m.saveActiveAlertsAsync("metric create")
- log.Info().
- Str("alertID", alertID).
- Msg("Added alert to recently resolved")
+ log.Warn().
+ Str("alertID", alertID).
+ Str("resource", resourceName).
+ Str("metric", metricType).
+ Float64("value", value).
+ Float64("trigger", threshold.Trigger).
+ Float64("clear", threshold.Clear).
+ Int("activeAlerts", len(m.activeAlerts)).
+ Msg("Alert triggered")
+
+ // Trigger AI analysis callback unconditionally (bypasses notification suppression)
+ if callbacks := m.getAlertForAICallbacks(); len(callbacks) > 0 {
+ alertCopy := cloneAlertForOutput(alert)
+ go func(a *Alert, fns []func(*Alert)) {
+ defer func() {
+ if r := recover(); r != nil {
+ log.Error().Interface("panic", r).Str("alertID", a.ID).Msg("panic in AI alert callback")
+ }
+ }()
+ for _, callback := range fns {
+ callback(a)
+ }
+ }(alertCopy, callbacks)
+ }
- log.Info().
- Str("resource", resourceName).
- Str("metric", metricType).
- Float64("value", value).
- Float64("clearThreshold", clearThreshold).
- Bool("wasAcknowledged", existingAlert.Acknowledged).
- Msg("Alert resolved with hysteresis")
+ // Check rate limit (but don't remove alert from tracking)
+ if !m.checkRateLimit(trackingKey) {
+ log.Debug().
+ Str("alertID", alertID).
+ Str("trackingKey", trackingKey).
+ Int("maxPerHour", m.config.Schedule.MaxAlertsHour).
+ Msg("Alert notification suppressed due to rate limit")
+ return
+ }
- m.safeCallResolvedAlertCallback(existingAlert, alertID, true)
+ // Notify callback (may be suppressed by quiet hours)
+ if len(m.getAlertCallbacks()) > 0 {
+ now := time.Now()
+ alert.LastNotified = &now
+ if m.dispatchAlert(alert, true) {
+ log.Info().Str("alertID", alertID).Msg("calling onAlert callback")
+ } else {
+ alert.LastNotified = nil
}
+ } else {
+ log.Warn().Msg("no onAlert callback set!")
}
+ return
}
+
+ // Clear: the core holds no incident.
+ if !exists || existingAlert == nil {
+ return
+ }
+ resolvedAlert := m.newResolvedAlert(existingAlert, time.Now(), nil)
+ m.removeActiveAlertNoLock(activeAlertStorageKey(existingAlert, alertID))
+ m.saveActiveAlertsAsync("metric resolution")
+ m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
+ log.Info().
+ Str("resource", resourceName).
+ Str("metric", metricType).
+ Float64("value", value).
+ Bool("wasAcknowledged", existingAlert.Acknowledged).
+ Msg("Alert resolved with hysteresis")
+ m.safeCallResolvedAlertCallback(existingAlert, alertID, true)
}
func sanitizeAlertKey(label string) string {
diff --git a/internal/alerts/reducer/reducer.go b/internal/alerts/reducer/reducer.go
index 148877acc9..8c7518c49b 100644
--- a/internal/alerts/reducer/reducer.go
+++ b/internal/alerts/reducer/reducer.go
@@ -24,9 +24,24 @@ import (
// MetricSignal is one observation of one metric on one resource.
type MetricSignal struct {
ResourceID string
- Metric string
- Value float64
- ObservedAt time.Time
+ // Key is the incident sub-key (the canonical metric spec ID). When
+ // empty it falls back to Metric, which older callers and tests use.
+ Key string
+ // Metric is the metric name, used for percentage classification.
+ Metric string
+ Value float64
+ // RuntimeTick mirrors DiscreteSignal: a monotonic reading (valid when
+ // RuntimeTickValid) that the intent gate accrues grace on.
+ RuntimeTick time.Duration
+ RuntimeTickValid bool
+ ObservedAt time.Time
+}
+
+func (s MetricSignal) subKey() string {
+ if s.Key != "" {
+ return s.Key
+ }
+ return s.Metric
}
// MetricRule is the resolved threshold policy for one resource+metric.
@@ -38,8 +53,13 @@ type MetricRule struct {
// Trigger, exactly as the manager does.
Clear float64
// DelaySeconds is the sustained-above-trigger duration required before
- // firing. Zero fires on the first exceeding observation.
+ // firing. Zero fires on the first exceeding observation. Ignored when
+ // an explicit Intent gate is supplied — the manager's explicit intent
+ // policies replace the legacy time-threshold delay.
DelaySeconds int
+ // Intent is the resolved intent-policy context for this observation
+ // (metric.<name> signals); nil means no gate.
+ Intent *DiscreteIntent
}
// Severity mirrors the manager's two-level model.
@@ -294,14 +314,14 @@ func severityFor(value, trigger float64, metric string) Severity {
// and returns the transition events, in order. It is deterministic: the
// same state, signal, and rule always produce the same result.
func (s *State) ApplyMetric(signal MetricSignal, rule MetricRule) []Event {
- key := incidentKey(signal.ResourceID, signal.Metric)
+ key := incidentKey(signal.ResourceID, signal.subKey())
incident := s.incidents[key]
event := func(eventType EventType, severity Severity) Event {
return Event{
Type: eventType,
ResourceID: signal.ResourceID,
- Key: signal.Metric,
+ Key: signal.subKey(),
Severity: severity,
Value: signal.Value,
At: signal.ObservedAt,
@@ -337,49 +357,60 @@ func (s *State) ApplyMetric(signal MetricSignal, rule MetricRule) []Event {
return nil
}
- // Sustained-for delay: enter pending on the first exceeding
- // observation, fire once the delay has elapsed. StartedAt is the
- // pending entry time, matching the manager's use of the pending
- // timestamp as the alert start time.
- if rule.DelaySeconds > 0 {
- if incident == nil {
- s.incidents[key] = &Incident{
- ResourceID: signal.ResourceID,
- Key: signal.Metric,
- State: StatePending,
- PendingSince: signal.ObservedAt,
- LastValue: signal.Value,
- LastObservedAt: signal.ObservedAt,
+ // The run enters or advances pending, then attempts activation.
+ // An explicit Intent gate replaces the legacy sustained-for delay,
+ // exactly as the manager's explicit intent policies replace the
+ // time-threshold branch. StartedAt is the pending entry time,
+ // matching the manager's use of the pending timestamp as the alert
+ // start time.
+ entered := false
+ if incident == nil {
+ incident = &Incident{
+ ResourceID: signal.ResourceID,
+ Key: signal.subKey(),
+ State: StatePending,
+ PendingSince: signal.ObservedAt,
+ LastValue: signal.Value,
+ TicksSupplied: signal.RuntimeTickValid,
+ LastRuntimeTick: signal.RuntimeTick,
+ LastObservedAt: signal.ObservedAt,
+ }
+ s.incidents[key] = incident
+ entered = true
+ } else {
+ incident.LastValue = signal.Value
+ 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 {
+ if entered {
return []Event{event(EventPending, "")}
}
+ return nil
+ }
+
+ if rule.Intent != nil {
+ if intentHoldsActivation(rule.Intent, incident, signal.ObservedAt) {
+ return pendingResult()
+ }
+ } else if rule.DelaySeconds > 0 {
if signal.ObservedAt.Sub(incident.PendingSince) < time.Duration(rule.DelaySeconds)*time.Second {
- incident.LastValue = signal.Value
- incident.LastObservedAt = signal.ObservedAt
- return nil
+ return pendingResult()
}
- severity := severityFor(signal.Value, rule.Trigger, signal.Metric)
- incident.State = StateFiring
- incident.Severity = severity
- incident.StartedAt = incident.PendingSince
- incident.LastValue = signal.Value
- incident.LastObservedAt = signal.ObservedAt
- s.restoreAck(key, incident, signal.ObservedAt)
- return []Event{event(EventFired, severity)}
}
severity := severityFor(signal.Value, rule.Trigger, signal.Metric)
- created := &Incident{
- ResourceID: signal.ResourceID,
- Key: signal.Metric,
- State: StateFiring,
- Severity: severity,
- StartedAt: signal.ObservedAt,
- LastValue: signal.Value,
- LastObservedAt: signal.ObservedAt,
- }
- s.incidents[key] = created
- s.restoreAck(key, created, signal.ObservedAt)
+ incident.State = StateFiring
+ incident.Severity = severity
+ incident.StartedAt = incident.PendingSince
+ s.restoreAck(key, incident, signal.ObservedAt)
return []Event{event(EventFired, severity)}
}
@@ -455,3 +486,14 @@ func (s *State) ShiftResolved(delta time.Duration) {
s.resolved[key] = record
}
}
+
+// ShiftPending moves every pending run's start (and observation anchor) by
+// delta (negative = older), for tests that simulate elapsed sustained-for
+// time without waiting.
+func (s *State) ShiftPending(delta time.Duration) {
+ for _, incident := range s.incidents {
+ if incident.State == StatePending {
+ incident.PendingSince = incident.PendingSince.Add(delta)
+ }
+ }
+}
diff --git a/internal/alerts/reducer_parity_test.go b/internal/alerts/reducer_parity_test.go
index 0e845d7373..ce5a03b418 100644
--- a/internal/alerts/reducer_parity_test.go
+++ b/internal/alerts/reducer_parity_test.go
@@ -78,11 +78,9 @@ func newManagerParityEngine(t *testing.T, scenario parityScenario) *managerParit
func (e *managerParityEngine) observe(step parityStep) {
if step.advance > 0 {
- // Simulate elapsed time for the wall-clock delay tracker.
+ // Simulate elapsed time for the core's sustained-for delay.
e.manager.mu.Lock()
- for key, since := range e.manager.pendingAlerts {
- e.manager.pendingAlerts[key] = since.Add(-step.advance)
- }
+ e.manager.core.ShiftPending(-step.advance)
e.manager.mu.Unlock()
}
diff --git a/internal/alerts/time_threshold_test.go b/internal/alerts/time_threshold_test.go
index 36fea6dc55..2396e78611 100644
--- a/internal/alerts/time_threshold_test.go
+++ b/internal/alerts/time_threshold_test.go
@@ -3,6 +3,8 @@ package alerts
import (
"testing"
"time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"
)
func TestGetTimeThresholdMappings(t *testing.T) {
@@ -101,13 +103,16 @@ func TestCheckMetricUsesPendingStartTime(t *testing.T) {
t.Fatalf("expected no active alerts after initial exceedance")
}
- if _, ok := manager.pendingAlerts[buildCanonicalStateID("guest-123", "metric-threshold:cpu")]; !ok {
+ incident, pending := manager.core.Incident("guest-123", "metric-threshold:cpu")
+ if !pending || incident.State != reducer.StatePending {
manager.mu.Unlock()
- t.Fatalf("expected pending alert tracking to be started")
+ t.Fatalf("expected core pending run to be started")
}
- forcedStart := time.Now().Add(-3 * time.Second)
- manager.pendingAlerts[buildCanonicalStateID("guest-123", "metric-threshold:cpu")] = forcedStart
+ // Age the core's pending run past the delay.
+ manager.core.ShiftPending(-3 * time.Second)
+ forcedIncident, _ := manager.core.Incident("guest-123", "metric-threshold:cpu")
+ forcedStart := forcedIncident.PendingSince
manager.mu.Unlock()
// Second exceedance should trigger the alert using the pending start time.