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.

Keep node alerts covered through reported agent handovers

pulse-triage[bot]56a5b2dba702
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 8995b77f9d..e409d32d97 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -674,6 +674,7 @@ default construction path still restores.
47a. `internal/alerts/capacity_forecast.go`
47b. `internal/alerts/windowed_metric.go`
48. `internal/alerts/node.go`
+48a. `internal/alerts/host_agent_node_links.go`
49. `internal/alerts/host.go`
50. `internal/alerts/backup_snapshot.go`
51. `internal/alerts/disk_health.go`
@@ -2053,24 +2054,45 @@ clears the incident. `TestStorageUnknownConnectivityDoesNotRecover` and
capacity activation, normalised offline activation and confirmed recovery.
Proxmox node alert evaluation now lives in `internal/alerts/node.go`. That file
owns node metric and temperature projection, node offline lifecycle handling,
-host-agent deduplication bookkeeping, and instance-scoped node display-name
-cache updates; future Proxmox node alert behavior should extend that resource
+and instance-scoped node display-name cache updates; future Proxmox node alert behavior should extend that resource
checker owner rather than expanding the central Manager file.
When a reporting host agent is linked to a node (`LinkedNodeID`, the monitor's
automatic or operator-set identity decision), the agent resource owns each
CPU, memory or disk usage metric it actually evaluates, and `CheckNode` releases
its own copy of those metrics through the disabled-threshold path every cycle:
the pending run is dropped and any node alert still open from before the link is
-resolved, never left frozen until the agent goes offline. `CheckHost` registers
-the link only after evaluation, recording which metrics the agent is configured
-to evaluate (a live CPU or memory threshold; for disk, a live threshold on the
-summary filesystem `models.SummaryDisk` picks, which is also what the linked
-node's disk metric reports), and removes it while agent alerts are disabled.
-Ownership follows configuration, not one report's data, so a missing agent
-reading keeps the agent's alert open instead of handing the metric back to the
-node for a cycle. With several agents linked to one node, a metric is owned when
-any of them evaluates it. A metric no agent evaluates stays with the node, so
-deduplication never leaves a machine unmonitored.
+resolved, never left frozen until the agent goes offline. `CheckHost` applies
+its link outcome after evaluation in per-agent report order. CPU and memory
+ownership requires a live threshold plus a usable, finite observation with a
+ready evaluation window, or a still-open agent alert or reducer run. For disk,
+that evidence must belong to the summary filesystem `models.SummaryDisk` picks,
+which is also what the linked node's disk metric reports. Configuration alone
+is not coverage: an agent with no observation and no open run leaves the node
+responsible. Missing readings keep an existing agent alert, without creating a
+node duplicate; observation-gap interruption and fresh confirmation/recovery
+remain unchanged. Disabling a usage metric releases canonical/shadow pending
+runs and explicit intent grace, even without a reading. A disabled agent or host
+also releases its CPU/memory pending runs. `UpdateConfig` immediately revokes
+unsupported link coverage, and in-flight reports recheck current policy before
+applying their outcome. Newer reports, offline and removal invalidate older
+link updates and removals. Several linked agents contribute the union of their
+coverage; stale alert metadata alone never suppresses a node. The accepted
+short duplicate window remains restart-before-first-report and
+first-offline-before-confirmed-offline; manually linked sibling agents retain
+their own alerts. Explicit host/inherited disk overrides beat `DiskFillByType`,
+as do direct filesystem overrides. A saved direct filesystem disable revokes
+summary disk ownership without a new agent report. Per-type defaults retain
+the existing normalization contract (zero is restored to the type default);
+this repair does not add a per-type Off setting. A nil effective filesystem
+threshold drops its pending run.
+
+A node-side close is an ownership handover, not observed recovery: each released
+metric carries `moved_to_agent` and the identity/name of an agent actually
+covering that metric in the same link snapshot. If several agents cover it,
+the lowest covering agent ID wins deterministically; a sibling covering only
+another metric must not be named. Resolved consumers still receive the close.
+`internal/alerts/host_agent_node_links.go` owns ordered links and per-metric
+successor selection, without persisting stale coverage across restart.
Deduplication keys on that link,
never on a hostname match, so a same-named node in another instance keeps its
alerts, an agent reporting an FQDN still dedups its node, and an operator unlink
@@ -2089,13 +2111,26 @@ instance name in `Instance`.
`TestCheckNodeKeepsTemperatureAlertWhenHostAgentMonitorsNode`,
`TestCheckNodeReleasesOpenMetricAlertWhenHostAgentRegisters`,
`TestCheckNodeMissingTemperatureDoesNotResolveOpenAlert`,
-`TestCheckNodeMissingTemperatureInterruptsTimingRuns` and
-`TestConfigSaveKeepsNodeTemperatureAlertOverTrigger` and
+`TestCheckNodeMissingTemperatureInterruptsTimingRuns`,
+`TestConfigSaveKeepsNodeTemperatureAlertOverTrigger`,
`TestCheckNodeKeepsUsageMetricsTheAgentDoesNotEvaluate`,
-`TestCheckNodeUsageOwnershipFollowsWhatAgentsEvaluate` in
-`internal/alerts/threshold_resolution_shared_test.go`, and
+`TestCheckNodeUsageOwnershipFollowsWhatAgentsEvaluate`,
+`TestCheckNodeKeepsMetricsTheAgentCannotEvaluate`,
+`TestDisabledAgentThresholdReleasesPendingRunWithoutReading`,
+`TestHostAgentNodeLinkFollowsConfigAndReportOrder`,
+`TestCheckNodeTakesBackMetricsWhenAgentUnlinks`,
+`TestHostDiskOverrideBeatsDiskFillByType`,
+`TestReleaseCanonicalMetricAlertClearsIntentPending` in
+`internal/alerts/threshold_resolution_shared_test.go` and
+`TestReportedAlertOwnershipComposition` in
+`internal/alerts/reported_alert_composition_test.go`, plus
`TestHostAgentDeduplicationFollowsNodeLink` in
-`internal/alerts/host_dedup_test.go`, pin these rules.
+`internal/alerts/host_dedup_test.go` and
+`TestCheckMetricReportsWhetherObservationWasUsable` in
+`internal/alerts/windowed_metric_test.go`, pin these rules.
+The real monitor lifecycle/History route is exercised by
+`TestMonitorReportedAgentHandoverUsesActualMetricOwner` in
+`internal/monitoring/monitor_alert_handling_test.go`.
Host-agent alert evaluation now lives in `internal/alerts/host.go`. That file
owns host identity, host-agent metric projection, host disk/SMART/RAID/Unraid
health handling, host cleanup, and host offline lifecycle handling; future host
diff --git a/internal/alerts/canonical_metric.go b/internal/alerts/canonical_metric.go
index b57354b006..8d29198075 100644
--- a/internal/alerts/canonical_metric.go
+++ b/internal/alerts/canonical_metric.go
@@ -86,23 +86,31 @@ func (m *Manager) releaseCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec,
}
storageKey := canonicalTrackingKeyForSpec(spec, spec.ID)
m.mu.Lock()
- m.core.ApplyMetric(reducer.MetricSignal{
- ResourceID: spec.ResourceID,
- Key: spec.ID,
- Metric: spec.MetricThreshold.Metric,
- Value: value,
- ObservedAt: time.Now(),
- }, reducer.MetricRule{})
+ for _, state := range m.mirrorStatesNoLock() {
+ state.ApplyMetric(reducer.MetricSignal{
+ ResourceID: spec.ResourceID,
+ Key: spec.ID,
+ Metric: spec.MetricThreshold.Metric,
+ Value: value,
+ ObservedAt: time.Now(),
+ }, reducer.MetricRule{})
+ }
+ intentChanged := m.clearIntentPendingNoLock(storageKey)
m.mu.Unlock()
+ if intentChanged {
+ m.saveActiveAlertsAsync("canonical metric intent pending state")
+ }
// 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(storageKey, spec.ID, string(spec.Kind), spec.ResourceID, resourceName, node, instance, resourceType)
m.clearAlertWithResolution(storageKey, resolution)
}
-func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec, resourceName, node, instance, resourceType string, value float64, threshold *HysteresisThreshold, opts *metricOptions) {
+// evaluateCanonicalMetricAlert reports whether this observation was usable:
+// a live threshold, finite value and ready window, even if delivery is suppressed.
+func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec, resourceName, node, instance, resourceType string, value float64, threshold *HysteresisThreshold, opts *metricOptions) bool {
if spec.MetricThreshold == nil {
- return
+ return false
}
alertID := spec.ID
@@ -111,14 +119,14 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
metricType := spec.MetricThreshold.Metric
if spec.Disabled || spec.MetricThreshold.Trigger <= 0 {
m.releaseCanonicalMetricAlert(spec, resourceName, node, instance, resourceType, value, nil)
- return
+ return false
}
observedAt := m.policyNow()
windowed := m.evaluateMetricWindow(spec.ResourceID, resourceType, metricType, value, observedAt)
if !windowed.Ready {
m.interruptMetricRun(spec)
- return
+ return false
}
value = windowed.Value
opts = metricWindowOptions(opts, metricType, resourceType, windowed)
@@ -148,7 +156,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
Str("trackingKey", trackingKey).
Time("suppressedUntil", suppressUntil).
Msg("Canonical metric alert suppressed")
- return
+ return true
}
triggered := alertspecsMetricTriggered(spec.MetricThreshold, value)
@@ -175,7 +183,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
time.Since(recent.StartTime) < time.Duration(m.config.SuppressionWindow)*time.Minute &&
abs(recent.Value-value) < m.config.MinimumDelta {
m.suppressedUntil[trackingKey] = time.Now().Add(time.Duration(m.config.SuppressionWindow) * time.Minute)
- return
+ return true
}
}
@@ -244,7 +252,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
switch {
case hasIncident && incident.State == reducer.StatePending:
- return
+ return true
case hasIncident && incident.State == reducer.StateFiring:
if intent != nil && (primary == reducer.EventFired || primary == reducer.EventRefired) {
m.clearIntentPendingNoLock(trackingKey)
@@ -321,7 +329,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
alert.AckUser = ""
}
if !m.setActiveAlertNoLock(storageKey, alert) {
- return
+ return true
}
m.recentAlerts[trackingKey] = alert
m.historyManager.AddAlert(*alert)
@@ -342,7 +350,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
}
if !m.checkRateLimit(trackingKey) {
- return
+ return true
}
if m.getAlertCallback() != nil {
@@ -352,7 +360,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
alert.LastNotified = nil
}
}
- return
+ return true
}
// A hold keeps the last breach's value and message, but what the
@@ -370,7 +378,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
// volatile live status moves, so surfaces can say what the
// reading is now and why the alert has not cleared.
existingAlert.MetricStatus = metricStatus
- return
+ return true
}
oldLevel := existingAlert.Level
@@ -401,7 +409,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
applyCanonicalOperationalEvidence(existingAlert, spec, evidence, time.Now())
if !m.setActiveAlertNoLock(storageKey, existingAlert) {
- return
+ return true
}
shouldRenotify := false
if existingAlert.Acknowledged {
@@ -420,7 +428,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
}
default:
if !exists || existingAlert == nil {
- return
+ return true
}
// Publish the observation that cleared the incident, not the last
@@ -449,6 +457,7 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
m.safeCallResolvedAlertCallback(resolvedAlert, storageKey, true)
}
+ return true
}
func alertspecsMetricTriggered(spec *alertspecs.MetricThresholdSpec, observed float64) bool {
diff --git a/internal/alerts/config_runtime.go b/internal/alerts/config_runtime.go
index 50d8115976..6fe14b53e6 100644
--- a/internal/alerts/config_runtime.go
+++ b/internal/alerts/config_runtime.go
@@ -66,6 +66,7 @@ func (m *Manager) UpdateConfig(config AlertConfig) {
m.config = config
normalizeOverrides(m.config.Overrides)
+ m.reconcileHostAgentNodeLinksNoLock()
// Update cached quiet hours location
if m.config.Schedule.QuietHours.Enabled && m.config.Schedule.QuietHours.Timezone != "" {
diff --git a/internal/alerts/host.go b/internal/alerts/host.go
index 6faf4d3adc..b3f592d6c3 100644
--- a/internal/alerts/host.go
+++ b/internal/alerts/host.go
@@ -262,6 +262,9 @@ func (m *Manager) CheckHost(host models.Host) {
// Fresh telemetry marks the host as online and clears offline tracking.
m.HandleHostOnline(host)
+ // Apply the link outcome in report order, including disabled exits.
+ reportSeq := m.beginHostAgentReport(host.ID)
+
m.mu.RLock()
alertsEnabled := m.config.Enabled
disableAllAgents, _ := m.alertPolicyTypeSwitchesNoLock("agent")
@@ -269,20 +272,22 @@ func (m *Manager) CheckHost(host models.Host) {
// An explicit disk temperature override (host or inherited linked-resource)
// beats the per-type defaults in DiskTempByType.
diskTempOverridden := false
- if override, exists := m.hostThresholdOverrideNoLock(host.ID, host.LinkedNodeID, host.LinkedVMID, host.LinkedContainerID); exists && override.DiskTemperature != nil {
- diskTempOverridden = true
+ diskOverridden := false
+ if override, exists := m.hostThresholdOverrideNoLock(host.ID, host.LinkedNodeID, host.LinkedVMID, host.LinkedContainerID); exists {
+ diskTempOverridden = override.DiskTemperature != nil
+ diskOverridden = override.Disk != nil
}
m.mu.RUnlock()
// While this agent evaluates nothing, its linked node keeps its own usage
// alerts; the link is registered below once the evaluated metrics are known.
if !alertsEnabled {
- m.unregisterHostAgentNodeLink(host.ID)
+ m.applyHostAgentNodeLink(hostAgentNodeLink{agentID: host.ID}, reportSeq)
return
}
if disableAllAgents {
- m.unregisterHostAgentNodeLink(host.ID)
+ m.applyHostAgentNodeLink(hostAgentNodeLink{agentID: host.ID}, reportSeq)
// Clear any existing host alerts when all host alerts are disabled
m.clearHostMetricAlerts(host.ID)
m.clearHostDiskAlerts(host.ID)
@@ -293,7 +298,7 @@ func (m *Manager) CheckHost(host models.Host) {
}
if thresholds.Disabled {
- m.unregisterHostAgentNodeLink(host.ID)
+ m.applyHostAgentNodeLink(hostAgentNodeLink{agentID: host.ID}, reportSeq)
m.clearHostMetricAlerts(host.ID)
m.clearHostDiskAlerts(host.ID)
m.clearHostRAIDAlerts(host.ID)
@@ -333,6 +338,7 @@ func (m *Manager) CheckHost(host models.Host) {
}
m.syncHostCustomSensorAlerts(host, nodeName, instanceName, baseMetadata)
+ cpuEvaluated := false
if thresholds.CPU != nil {
cpuMetadata := cloneMetadata(baseMetadata)
cpuMetadata["metric"] = "cpu"
@@ -348,12 +354,13 @@ func (m *Manager) CheckHost(host models.Host) {
Str("host", resourceName).
Msg("Skipping invalid canonical host CPU metric spec")
} else {
- m.checkMetricWithCanonicalSpec(spec, resourceName, nodeName, instanceName, "agent", host.CPUUsage, thresholds.CPU, &metricOptions{Metadata: cpuMetadata})
+ cpuEvaluated = m.checkMetricWithCanonicalSpec(spec, resourceName, nodeName, instanceName, "agent", host.CPUUsage, thresholds.CPU, &metricOptions{Metadata: cpuMetadata})
}
} else {
- m.clearHostMetricAlerts(host.ID, "cpu")
+ m.releaseHostUsageMetric(resourceID, resourceName, nodeName, instanceName, unifiedresources.ResourceTypeAgent, "agent", "cpu")
}
+ memoryEvaluated := false
if thresholds.Memory != nil {
memMetadata := cloneMetadata(baseMetadata)
memMetadata["metric"] = "memory"
@@ -373,10 +380,10 @@ func (m *Manager) CheckHost(host models.Host) {
} else if !host.Memory.HasKnownUsage() && !spec.Disabled {
m.interruptMetricRun(spec)
} else {
- m.checkMetricWithCanonicalSpec(spec, resourceName, nodeName, instanceName, "agent", host.Memory.Usage, thresholds.Memory, &metricOptions{Metadata: memMetadata})
+ memoryEvaluated = m.checkMetricWithCanonicalSpec(spec, resourceName, nodeName, instanceName, "agent", host.Memory.Usage, thresholds.Memory, &metricOptions{Metadata: memMetadata})
}
} else if thresholds.Memory == nil {
- m.clearHostMetricAlerts(host.ID, "memory")
+ m.releaseHostUsageMetric(resourceID, resourceName, nodeName, instanceName, unifiedresources.ResourceTypeAgent, "agent", "memory")
}
if thresholds.DiskTemperature != nil && thresholds.DiskTemperature.Trigger > 0 {
@@ -441,6 +448,7 @@ func (m *Manager) CheckHost(host models.Host) {
summaryDiskResourceID, _ = hostDiskResourceID(host, summary)
}
evaluatesSummaryDisk := false
+ summaryDiskLive := false
if len(host.Sensors.SMART) > 0 {
for _, disk := range host.Sensors.SMART {
diskResourceID, diskName := hostSMARTDiskResourceID(host, disk)
@@ -468,7 +476,7 @@ func (m *Manager) CheckHost(host models.Host) {
if hasDiskOverride {
// If disk is disabled via override, skip alerting
if diskOverride.Disabled {
- m.clearAlert(canonicalMetricStateID(diskResourceID, "disk"))
+ m.releaseHostUsageMetric(diskResourceID, diskName, nodeName, instanceName, unifiedresources.ResourceType("agent-disk"), "agent-disk", "disk")
continue
}
// Use disk-specific threshold if set
@@ -478,7 +486,7 @@ func (m *Manager) CheckHost(host models.Host) {
}
// Per-type override: consult DiskFillByType if hardware type is inferable
// from the device path and no disk-specific override applied above.
- if effectiveDiskThreshold == nil && thresholds.Disk != nil && thresholds.Disk.Trigger > 0 {
+ if effectiveDiskThreshold == nil && !diskOverridden && thresholds.Disk != nil && thresholds.Disk.Trigger > 0 {
if hwType := inferDiskHardwareType(disk.Device); hwType != "" {
m.mu.RLock()
if th, ok := m.config.DiskFillByType[hwType]; ok {
@@ -496,9 +504,9 @@ func (m *Manager) CheckHost(host models.Host) {
// Skip if no threshold configured (nil)
// We DO NOT skip if Trigger <= 0 because we need to call checkMetric to clear any existing alerts.
if effectiveDiskThreshold == nil {
+ m.releaseHostUsageMetric(diskResourceID, diskName, nodeName, instanceName, unifiedresources.ResourceType("agent-disk"), "agent-disk", "disk")
continue
}
- evaluatesSummaryDisk = evaluatesSummaryDisk || (diskResourceID == summaryDiskResourceID && effectiveDiskThreshold.Trigger > 0)
diskMetadata := hostChildAlertMetadata(baseMetadata, hostDiskAlertResourceType)
diskMetadata["metric"] = "disk"
@@ -522,7 +530,11 @@ func (m *Manager) CheckHost(host models.Host) {
continue
}
- m.checkMetricWithCanonicalSpec(spec, diskName, nodeName, instanceName, "agent-disk", disk.Usage, effectiveDiskThreshold, &metricOptions{Metadata: diskMetadata})
+ evaluated := m.checkMetricWithCanonicalSpec(spec, diskName, nodeName, instanceName, "agent-disk", disk.Usage, effectiveDiskThreshold, &metricOptions{Metadata: diskMetadata})
+ if diskResourceID == summaryDiskResourceID {
+ summaryDiskLive = liveHysteresisThreshold(effectiveDiskThreshold)
+ evaluatesSummaryDisk = evaluated
+ }
}
// Clear all disk alerts if host-level disk alerting is completely disabled and no disk-specific overrides
@@ -546,19 +558,23 @@ func (m *Manager) CheckHost(host models.Host) {
m.cleanupHostDiskAlerts(host, seenDisks)
- // The linked node releases exactly the usage metrics this agent is set up
- // to evaluate and keeps the rest, so deduplication never leaves the machine
- // unmonitored. Ownership follows configuration, not one report's data: a
- // missing memory reading keeps the agent's alert open rather than handing
- // memory back to the node for a cycle.
- m.registerHostAgentNodeLink(hostAgentNodeLink{
- agentID: host.ID,
- agentName: resourceName,
- nodeID: host.LinkedNodeID,
- cpu: thresholds.CPU != nil && thresholds.CPU.Trigger > 0,
- memory: thresholds.Memory != nil && thresholds.Memory.Trigger > 0,
- disk: evaluatesSummaryDisk,
- })
+ // The linked node releases the usage metrics this agent covers and keeps
+ // the rest, so deduplication never leaves the machine unmonitored. A metric
+ // is covered while the current config lets the agent evaluate it and the
+ // agent either evaluated it this report or still holds an alert or run for
+ // it: a missing reading or a warming evaluation window then keeps the
+ // agent's alert as the single source instead of opening a node duplicate,
+ // while an agent with no usable evidence and nothing open hands the metric
+ // to the node.
+ m.applyHostAgentNodeLink(hostAgentNodeLink{
+ agentID: host.ID,
+ agentName: resourceName,
+ nodeID: host.LinkedNodeID,
+ cpu: liveHysteresisThreshold(thresholds.CPU) && (cpuEvaluated || m.hostAgentMetricOpen(resourceID, "cpu")),
+ memory: liveHysteresisThreshold(thresholds.Memory) && (memoryEvaluated || m.hostAgentMetricOpen(resourceID, "memory")),
+ disk: summaryDiskLive && (evaluatesSummaryDisk || m.hostAgentMetricOpen(summaryDiskResourceID, "disk")),
+ summaryDiskResourceID: summaryDiskResourceID,
+ }, reportSeq)
if host.Unraid != nil {
m.syncHostUnraidStorageAlert(host, nodeName, instanceName, resourceName, baseMetadata)
@@ -951,7 +967,7 @@ func (m *Manager) clearHostMetricAlerts(hostID string, metrics ...string) {
}
for _, resourceID := range resourceIDs {
for _, metric := range metrics {
- m.clearAlert(canonicalMetricStateID(resourceID, metric))
+ m.releaseHostUsageMetric(resourceID, "", "", "", unifiedresources.ResourceTypeAgent, "agent", metric)
}
}
}
diff --git a/internal/alerts/host_agent_node_links.go b/internal/alerts/host_agent_node_links.go
new file mode 100644
index 0000000000..681f206446
--- /dev/null
+++ b/internal/alerts/host_agent_node_links.go
@@ -0,0 +1,281 @@
+package alerts
+
+import (
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rs/zerolog/log"
+)
+
+// hostAgentNodeLink is a reporting host agent's link to a Proxmox node and the
+// usage metrics the agent covers for that machine. The link is the monitor's
+// identity decision (automatic or operator-set), so an agent whose hostname
+// merely matches a node name in another instance, or one an operator unlinked,
+// never makes a node release its alerts, and an agent reporting an FQDN still
+// dedups its node.
+type hostAgentNodeLink struct {
+ agentID string
+ agentName string
+ nodeID string
+ cpu bool
+ memory bool
+ disk bool
+ // summaryDiskResourceID is the agent disk resource behind the node's disk
+ // metric, kept so a config change can revoke disk ownership at once.
+ summaryDiskResourceID string
+}
+
+func (l hostAgentNodeLink) ownsAny() bool {
+ return l.cpu || l.memory || l.disk
+}
+
+// beginHostAgentReport numbers a CheckHost run for one agent. Link changes are
+// applied in report order, so a slower, older report can neither re-register
+// nor remove ownership after a newer report or after the agent was
+// unregistered.
+func (m *Manager) beginHostAgentReport(hostID string) uint64 {
+ hostID = strings.TrimSpace(hostID)
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.hostAgentReportSeq[hostID]++
+ return m.hostAgentReportSeq[hostID]
+}
+
+// applyHostAgentNodeLink records the outcome of a report: the link and the
+// usage metrics the agent covers, or no ownership when the link has no node or
+// covers nothing. A stale report is ignored, and the link is checked against
+// the current config so a report evaluated before a config change cannot
+// restore ownership that change revoked.
+func (m *Manager) applyHostAgentNodeLink(link hostAgentNodeLink, reportSeq uint64) {
+ link.agentID = strings.TrimSpace(link.agentID)
+ link.nodeID = strings.TrimSpace(link.nodeID)
+ if link.agentID == "" {
+ return
+ }
+ m.mu.Lock()
+ if reportSeq <= m.hostAgentLinkApplied[link.agentID] {
+ m.mu.Unlock()
+ log.Debug().
+ Str("hostID", link.agentID).
+ Msg("Skipped stale host agent node link update")
+ return
+ }
+ m.hostAgentLinkApplied[link.agentID] = reportSeq
+ if link.nodeID != "" {
+ link = m.revokeUnsupportedOwnershipNoLock(link)
+ }
+ previous, existed := m.hostAgentNodeLinks[link.agentID]
+ if link.nodeID == "" || !link.ownsAny() {
+ delete(m.hostAgentNodeLinks, link.agentID)
+ } else {
+ m.hostAgentNodeLinks[link.agentID] = link
+ }
+ m.mu.Unlock()
+
+ switch {
+ case link.nodeID != "" && link.ownsAny() && (!existed || previous != link):
+ log.Debug().
+ Str("hostID", link.agentID).
+ Str("linkedNodeID", link.nodeID).
+ Bool("cpu", link.cpu).
+ Bool("memory", link.memory).
+ Bool("disk", link.disk).
+ Msg("Updated host agent node link for deduplication")
+ case (link.nodeID == "" || !link.ownsAny()) && existed:
+ log.Debug().
+ Str("hostID", link.agentID).
+ Str("linkedNodeID", previous.nodeID).
+ Msg("Removed host agent node link from deduplication")
+ }
+}
+
+// unregisterHostAgentNodeLink removes a host agent from deduplication tracking,
+// so its linked node evaluates its own usage alerts again, and marks every
+// report already in flight for that agent as stale.
+func (m *Manager) unregisterHostAgentNodeLink(hostID string) {
+ hostID = strings.TrimSpace(hostID)
+ if hostID == "" {
+ return
+ }
+ m.mu.Lock()
+ m.hostAgentLinkApplied[hostID] = m.hostAgentReportSeq[hostID]
+ link, existed := m.hostAgentNodeLinks[hostID]
+ delete(m.hostAgentNodeLinks, hostID)
+ m.mu.Unlock()
+
+ if existed {
+ log.Debug().
+ Str("hostID", hostID).
+ Str("linkedNodeID", link.nodeID).
+ Msg("Removed host agent node link from deduplication")
+ }
+}
+
+// reconcileHostAgentNodeLinksNoLock applies a config change to the recorded
+// links straight away instead of waiting for each agent's next report. It only
+// revokes ownership the new config no longer supports. Caller holds m.mu.
+func (m *Manager) reconcileHostAgentNodeLinksNoLock() {
+ for agentID, link := range m.hostAgentNodeLinks {
+ updated := m.revokeUnsupportedOwnershipNoLock(link)
+ if updated.ownsAny() {
+ m.hostAgentNodeLinks[agentID] = updated
+ } else {
+ delete(m.hostAgentNodeLinks, agentID)
+ }
+ }
+}
+
+// revokeUnsupportedOwnershipNoLock drops the usage metrics the current config
+// does not let the agent evaluate. Caller holds m.mu.
+func (m *Manager) revokeUnsupportedOwnershipNoLock(link hostAgentNodeLink) hostAgentNodeLink {
+ if disableAllAgents, _ := m.alertPolicyTypeSwitchesNoLock("agent"); !m.config.Enabled || disableAllAgents {
+ link.cpu, link.memory, link.disk = false, false, false
+ return link
+ }
+ thresholds := m.resolveHostThresholdsNoLock(link.agentID, link.nodeID, "", "")
+ if thresholds.Disabled {
+ link.cpu, link.memory, link.disk = false, false, false
+ return link
+ }
+ link.cpu = link.cpu && liveHysteresisThreshold(thresholds.CPU)
+ link.memory = link.memory && liveHysteresisThreshold(thresholds.Memory)
+ link.disk = link.disk && m.hostDiskUsageEnabledNoLock(link.summaryDiskResourceID, thresholds)
+ return link
+}
+
+// hostDiskUsageEnabledNoLock reports whether the current direct filesystem
+// override and host policy still allow summary disk evaluation. Per-type
+// defaults remain live after normal config normalization; the next report
+// settles their exact trigger. Caller holds m.mu.
+func (m *Manager) hostDiskUsageEnabledNoLock(diskResourceID string, thresholds ThresholdConfig) bool {
+ if override, ok := m.config.Overrides[diskResourceID]; ok && diskResourceID != "" {
+ if override.Disabled {
+ return false
+ }
+ if override.Disk != nil {
+ return liveHysteresisThreshold(override.Disk)
+ }
+ }
+ return liveHysteresisThreshold(thresholds.Disk)
+}
+
+func liveHysteresisThreshold(threshold *HysteresisThreshold) bool {
+ return threshold != nil && threshold.Trigger > 0
+}
+
+// hostAgentMetricOpen reports whether an agent resource still holds an alert
+// or a pending or firing run for a metric. An agent that cannot evaluate a
+// metric this cycle keeps ownership while it has one, so the node does not
+// open a duplicate during a missing reading.
+func (m *Manager) hostAgentMetricOpen(resourceID, metric string) bool {
+ if strings.TrimSpace(resourceID) == "" {
+ return false
+ }
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ if _, ok := m.core.Incident(resourceID, canonicalMetricSpecID(resourceID, metric)); ok {
+ return true
+ }
+ return m.hasActiveAlertNoLock(canonicalMetricStateID(resourceID, metric))
+}
+
+// Capture ownership and attribution in one read. Different agents can cover
+// different metrics; a handover must name a real owner of the released metric.
+type hostAgentUsageOwners struct {
+ cpu, memory, disk hostAgentNodeLink
+}
+
+func (o hostAgentUsageOwners) forMetric(metric string) hostAgentNodeLink {
+ switch metric {
+ case "cpu":
+ return o.cpu
+ case "memory":
+ return o.memory
+ case "disk":
+ return o.disk
+ default:
+ return hostAgentNodeLink{}
+ }
+}
+
+func (m *Manager) linkedHostAgentsForNode(nodeID string) hostAgentUsageOwners {
+ nodeID = strings.TrimSpace(nodeID)
+ var owners hostAgentUsageOwners
+ if nodeID == "" {
+ return owners
+ }
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ for _, link := range m.hostAgentNodeLinks {
+ if link.nodeID != nodeID {
+ continue
+ }
+ if link.cpu && (owners.cpu.agentID == "" || link.agentID < owners.cpu.agentID) {
+ owners.cpu = link
+ }
+ if link.memory && (owners.memory.agentID == "" || link.agentID < owners.memory.agentID) {
+ owners.memory = link
+ }
+ if link.disk && (owners.disk.agentID == "" || link.agentID < owners.disk.agentID) {
+ owners.disk = link
+ }
+ }
+ return owners
+}
+
+// linkedHostAgentForNode returns the host agent coverage for the given Proxmox
+// node. A usage metric counts as owned when any link to the node covers it, so
+// a second linked agent covering a metric the first does not still keeps the
+// node from alerting twice. The agent identity reported is the lowest agent ID
+// among the linked agents, so the choice is stable. Coverage comes only from
+// links that agent reports keep current; stale evidence such as an old alert's
+// metadata never silences a node.
+func (m *Manager) linkedHostAgentForNode(nodeID string) (hostAgentNodeLink, bool) {
+ nodeID = strings.TrimSpace(nodeID)
+ if nodeID == "" {
+ return hostAgentNodeLink{}, false
+ }
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ var found hostAgentNodeLink
+ ok := false
+ for _, link := range m.hostAgentNodeLinks {
+ if link.nodeID != nodeID {
+ continue
+ }
+ if !ok || link.agentID < found.agentID {
+ found.agentID = link.agentID
+ found.agentName = link.agentName
+ }
+ found.nodeID = nodeID
+ found.cpu = found.cpu || link.cpu
+ found.memory = found.memory || link.memory
+ found.disk = found.disk || link.disk
+ ok = true
+ }
+ return found, ok
+}
+
+// hasHostAgentForNode reports whether a host agent covers at least one of the
+// given Proxmox node's usage metrics.
+func (m *Manager) hasHostAgentForNode(nodeID string) bool {
+ _, ok := m.linkedHostAgentForNode(nodeID)
+ return ok
+}
+
+// releaseHostUsageMetric stops evaluating an agent usage metric the way a
+// disabled threshold does, so a pending run is dropped along with any open
+// alert and its explicit intent state.
+func (m *Manager) releaseHostUsageMetric(resourceID, resourceName, nodeName, instanceName string, specType unifiedresources.ResourceType, resourceType, metric string) {
+ spec, err := buildCanonicalMetricSpec(resourceID, resourceName, specType, metric, nil)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("resourceID", resourceID).
+ Str("metric", metric).
+ Msg("Skipping invalid canonical host metric spec; clearing the alert only")
+ m.clearAlert(canonicalMetricStateID(resourceID, metric))
+ return
+ }
+ m.releaseCanonicalMetricAlert(spec, resourceName, nodeName, instanceName, resourceType, 0, nil)
+}
diff --git a/internal/alerts/host_dedup_test.go b/internal/alerts/host_dedup_test.go
index aee90c38fa..23c8ac1d50 100644
--- a/internal/alerts/host_dedup_test.go
+++ b/internal/alerts/host_dedup_test.go
@@ -47,7 +47,7 @@ func TestHostAgentDeduplicatesNodeAlerts(t *testing.T) {
m.config.NodeDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
// Link a host agent to the node BEFORE checking the node
- m.registerHostAgentNodeLink(agent)
+ testRegisterHostAgentNodeLink(m, agent)
// Verify host agent IS linked
if !m.hasHostAgentForNode("node/pi") {
@@ -80,7 +80,7 @@ func TestHostAgentDeduplicatesNodeAlerts(t *testing.T) {
m.config.NodeDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
// Register and then unregister
- m.registerHostAgentNodeLink(agent)
+ testRegisterHostAgentNodeLink(m, agent)
m.unregisterHostAgentNodeLink(agent.agentID)
// Verify host agent is NOT linked
@@ -169,7 +169,7 @@ func TestHandleHostOfflineUnregistersNodeLink(t *testing.T) {
}
// Register the node link
- m.registerHostAgentNodeLink(hostAgentNodeLink{agentID: host.ID, nodeID: host.LinkedNodeID, cpu: true})
+ testRegisterHostAgentNodeLink(m, hostAgentNodeLink{agentID: host.ID, nodeID: host.LinkedNodeID, cpu: true})
if !m.hasHostAgentForNode("pve-offlinehost") {
t.Error("Expected host agent registered")
@@ -182,3 +182,9 @@ func TestHandleHostOfflineUnregistersNodeLink(t *testing.T) {
t.Error("Expected host agent to be unregistered after HandleHostOffline")
}
}
+
+// testRegisterHostAgentNodeLink applies a link the way CheckHost does, as the
+// agent's newest report.
+func testRegisterHostAgentNodeLink(m *Manager, link hostAgentNodeLink) {
+ m.applyHostAgentNodeLink(link, m.beginHostAgentReport(link.agentID))
+}
diff --git a/internal/alerts/manager.go b/internal/alerts/manager.go
index 27a4e9fab5..a4781899c4 100644
--- a/internal/alerts/manager.go
+++ b/internal/alerts/manager.go
@@ -107,6 +107,9 @@ type Manager struct {
// linked to and the usage metrics the agent evaluates for it. The node
// releases only those metrics and keeps evaluating the rest itself.
hostAgentNodeLinks map[string]hostAgentNodeLink // Host agent ID -> node link
+ // Ordering survives link removal so an older in-flight report cannot restore it.
+ hostAgentReportSeq map[string]uint64
+ hostAgentLinkApplied map[string]uint64
// Node display name caches. Proxmox nodes can share the same raw node name
// across multiple configured instances, so keep instance-scoped entries in
// addition to the legacy raw-name cache used by instance-less resources.
@@ -249,6 +252,8 @@ func NewManagerWithDataDir(dataDir string, options ...ManagerOption) *Manager {
flappingActive: make(map[string]bool),
cleanupStop: make(chan struct{}),
hostAgentNodeLinks: make(map[string]hostAgentNodeLink),
+ hostAgentReportSeq: make(map[string]uint64),
+ hostAgentLinkApplied: make(map[string]uint64),
nodeDisplayNames: make(map[string]string),
instanceNodeDisplayNames: make(map[string]string),
now: time.Now,
diff --git a/internal/alerts/node.go b/internal/alerts/node.go
index 6698bdf64c..302ba1abb4 100644
--- a/internal/alerts/node.go
+++ b/internal/alerts/node.go
@@ -98,7 +98,7 @@ func (m *Manager) CheckNode(node models.Node) {
// the node releases its own copy instead of alerting twice. A metric the
// agent does not evaluate (agent alerts disabled, threshold off, usage
// unknown) stays with the node, so the machine is never left unmonitored.
- link, _ := m.linkedHostAgentForNode(node.ID)
+ owners := m.linkedHostAgentsForNode(node.ID)
input := &UnifiedResourceInput{
ID: node.ID,
Type: "node",
@@ -107,22 +107,22 @@ func (m *Manager) CheckNode(node models.Node) {
Instance: node.Instance,
}
released := make([]string, 0, 3)
- if link.cpu {
+ if owners.cpu.cpu {
released = append(released, "cpu")
} else {
input.CPU = &UnifiedResourceMetric{Percent: node.CPU * 100}
}
- if link.memory {
+ if owners.memory.memory {
released = append(released, "memory")
} else if node.Memory.HasKnownUsage() {
input.Memory = &UnifiedResourceMetric{Percent: node.Memory.Usage}
}
- if link.disk {
+ if owners.disk.disk {
released = append(released, "disk")
} else {
input.Disk = &UnifiedResourceMetric{Percent: node.Disk.Usage}
}
- m.releaseNodeMetricAlerts(node, released...)
+ m.releaseNodeMetricAlerts(node, owners, released...)
m.evaluateUnifiedMetrics(input, thresholds, nil, "temperature") // checkNodeTemperature owns its observation gaps.
// CPU temperature stays with the node even when a host agent runs on it:
@@ -166,9 +166,16 @@ func (m *Manager) checkNodeTemperature(node models.Node, threshold *HysteresisTh
// releaseNodeMetricAlerts stops node-side evaluation of the given metrics the
// same way a disabled threshold does: any pending run is dropped and any open
// node alert is resolved. Without this, a node alert that was open when a host
-// agent registered would stay frozen until the agent went offline.
-func (m *Manager) releaseNodeMetricAlerts(node models.Node, metrics ...string) {
+// agent registered would stay frozen until the agent went offline. Each close
+// names an agent that actually covers that metric, not an arbitrary sibling.
+func (m *Manager) releaseNodeMetricAlerts(node models.Node, owners hostAgentUsageOwners, metrics ...string) {
for _, metric := range metrics {
+ agent := owners.forMetric(metric)
+ resolution := &AlertResolution{
+ Reason: AlertResolutionMovedToAgent,
+ SuccessorResourceID: hostResourceID(agent.agentID),
+ SuccessorName: agent.agentName,
+ }
spec, err := buildCanonicalMetricSpec(node.ID, node.Name, unifiedresources.ResourceType("node"), metric, nil)
if err != nil {
log.Warn().
@@ -179,112 +186,10 @@ func (m *Manager) releaseNodeMetricAlerts(node models.Node, metrics ...string) {
Msg("Skipping invalid canonical node metric spec")
continue
}
- m.checkMetricWithCanonicalSpec(spec, node.Name, node.Name, node.Instance, "node", 0, nil, nil)
- }
-}
-
-// hostAgentNodeLink is a reporting host agent's link to a Proxmox node and the
-// usage metrics the agent evaluates for that machine. The link is the monitor's
-// identity decision (automatic or operator-set), so an agent whose hostname
-// merely matches a node name in another instance, or one an operator unlinked,
-// never makes a node release its alerts, and an agent reporting an FQDN still
-// dedups its node.
-type hostAgentNodeLink struct {
- agentID string
- agentName string
- nodeID string
- cpu bool
- memory bool
- disk bool
-}
-
-// registerHostAgentNodeLink records a host agent's node link after CheckHost
-// has decided which usage metrics it evaluates. A link without a node or
-// without any evaluated metric is removed, so the node keeps all its alerts.
-func (m *Manager) registerHostAgentNodeLink(link hostAgentNodeLink) {
- link.agentID = strings.TrimSpace(link.agentID)
- link.nodeID = strings.TrimSpace(link.nodeID)
- if link.agentID == "" {
- return
- }
- if link.nodeID == "" || !(link.cpu || link.memory || link.disk) {
- m.unregisterHostAgentNodeLink(link.agentID)
- return
- }
- m.mu.Lock()
- previous, existed := m.hostAgentNodeLinks[link.agentID]
- m.hostAgentNodeLinks[link.agentID] = link
- m.mu.Unlock()
-
- if !existed || previous != link {
- log.Debug().
- Str("hostID", link.agentID).
- Str("linkedNodeID", link.nodeID).
- Bool("cpu", link.cpu).
- Bool("memory", link.memory).
- Bool("disk", link.disk).
- Msg("Updated host agent node link for deduplication")
+ m.releaseCanonicalMetricAlert(spec, node.Name, node.Name, node.Instance, "node", 0, resolution)
}
}
-// unregisterHostAgentNodeLink removes a host agent from deduplication tracking,
-// so its linked node evaluates its own usage alerts again.
-func (m *Manager) unregisterHostAgentNodeLink(hostID string) {
- hostID = strings.TrimSpace(hostID)
- if hostID == "" {
- return
- }
- m.mu.Lock()
- link, existed := m.hostAgentNodeLinks[hostID]
- delete(m.hostAgentNodeLinks, hostID)
- m.mu.Unlock()
-
- if existed {
- log.Debug().
- Str("hostID", hostID).
- Str("linkedNodeID", link.nodeID).
- Msg("Removed host agent node link from deduplication")
- }
-}
-
-// linkedHostAgentForNode returns the host agent coverage for the given Proxmox
-// node. A usage metric counts as owned when any agent linked to the node
-// evaluates it, so a second linked agent covering a metric the first does not
-// still keeps the node from alerting twice. The agent identity reported is the
-// lowest agent ID among the linked agents, so the choice is stable.
-func (m *Manager) linkedHostAgentForNode(nodeID string) (hostAgentNodeLink, bool) {
- nodeID = strings.TrimSpace(nodeID)
- if nodeID == "" {
- return hostAgentNodeLink{}, false
- }
- m.mu.RLock()
- defer m.mu.RUnlock()
- var found hostAgentNodeLink
- ok := false
- for _, link := range m.hostAgentNodeLinks {
- if link.nodeID != nodeID {
- continue
- }
- if !ok || link.agentID < found.agentID {
- found.agentID = link.agentID
- found.agentName = link.agentName
- }
- found.nodeID = nodeID
- found.cpu = found.cpu || link.cpu
- found.memory = found.memory || link.memory
- found.disk = found.disk || link.disk
- ok = true
- }
- return found, ok
-}
-
-// hasHostAgentForNode reports whether a reporting host agent is linked to the
-// given Proxmox node and owns at least one of its usage metrics.
-func (m *Manager) hasHostAgentForNode(nodeID string) bool {
- _, ok := m.linkedHostAgentForNode(nodeID)
- return ok
-}
-
// UpdateNodeDisplayName caches the display name for a node/host so alerts
// can resolve it without needing the full model object.
func nodeDisplayNameCacheKey(instance, name string) string {
diff --git a/internal/alerts/reported_alert_composition_test.go b/internal/alerts/reported_alert_composition_test.go
new file mode 100644
index 0000000000..2ead6f1bd5
--- /dev/null
+++ b/internal/alerts/reported_alert_composition_test.go
@@ -0,0 +1,267 @@
+package alerts
+
+import (
+ "math"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+// Exercise the current CheckHost/CheckNode/config entry points, independently
+// of the proposal's new registry helpers, so the same controls run on its parent.
+func TestReportedAlertOwnershipComposition(t *testing.T) {
+ setup := func(t *testing.T) (*Manager, models.Node, models.Host) {
+ t.Helper()
+ m := newTestManager(t)
+ m.mu.Lock()
+ m.config.Enabled = true
+ m.config.TimeThresholds = map[string]int{}
+ m.config.NodeDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.config.NodeDefaults.Memory = &HysteresisThreshold{Trigger: 85, Clear: 80}
+ m.config.NodeDefaults.Disk = &HysteresisThreshold{Trigger: 90, Clear: 85}
+ m.config.AgentDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.config.AgentDefaults.Memory = &HysteresisThreshold{Trigger: 85, Clear: 80}
+ m.config.AgentDefaults.Disk = &HysteresisThreshold{Trigger: 90, Clear: 85}
+ m.mu.Unlock()
+ node, host := testNodeWithHostAgent()
+ node.CPU = 0.9
+ node.Memory = models.Memory{Total: 100, Used: 90, Free: 10, Usage: 90}
+ node.Disk = models.Disk{Total: 100, Used: 95, Free: 5, Usage: 95}
+ host.CPUUsage = 50
+ host.Memory = node.Memory
+ return m, node, host
+ }
+ for _, kind := range []string{"memory-never-observed", "cpu-nan", "cpu-infinite", "window-not-ready", "summary-disk-nan"} {
+ t.Run(kind, func(t *testing.T) {
+ m, node, host := setup(t)
+ metric := "cpu"
+ switch kind {
+ case "memory-never-observed":
+ metric = "memory"
+ host.Memory = models.Memory{Total: 100, UsageUnavailable: true}
+ case "cpu-nan":
+ host.CPUUsage = math.NaN()
+ case "cpu-infinite":
+ host.CPUUsage = math.Inf(1)
+ case "window-not-ready":
+ m.mu.Lock()
+ m.config.MetricEvaluationWindows = map[string]map[string]int{"agent": {"cpu": 300}}
+ m.mu.Unlock()
+ m.SetMetricWindowProvider(func(MetricWindowRequest) ([]MetricWindowPoint, error) { return nil, nil })
+ case "summary-disk-nan":
+ metric = "disk"
+ host.Disks = []models.Disk{{Mountpoint: "/", Device: "/dev/sda1", Total: 100, Usage: math.NaN()}}
+ }
+ m.CheckHost(host)
+ m.CheckNode(node)
+ if !testHasActiveAlert(t, m, canonicalMetricStateID(node.ID, metric)) {
+ t.Fatalf("node %s lost %s to an agent with no evidence or open run", node.ID, metric)
+ }
+ })
+ }
+ t.Run("config-save-without-agent-report", func(t *testing.T) {
+ m, node, host := setup(t)
+ m.CheckHost(host)
+ m.CheckNode(node)
+ cfg := m.GetConfig()
+ cfg.DisableAllAgents = true
+ m.UpdateConfig(cfg)
+ m.CheckNode(node)
+ m.mu.RLock()
+ observed := testCoreHasIncident(m, node.ID, canonicalMetricSpecID(node.ID, "cpu"))
+ m.mu.RUnlock()
+ if !observed {
+ t.Fatal("disabled agent left node CPU unevaluated until another agent report")
+ }
+ })
+ t.Run("direct-disk-disable-without-agent-report", func(t *testing.T) {
+ m, node, host := setup(t)
+ host.Disks = []models.Disk{{Mountpoint: "/", Device: "/dev/nvme0n1p2", Total: 100, Usage: 50}}
+ m.CheckHost(host)
+ m.CheckNode(node)
+ if testHasActiveAlert(t, m, canonicalMetricStateID(node.ID, "disk")) {
+ t.Fatal("control failed to hand summary disk coverage to the agent")
+ }
+ cfg := m.GetConfig()
+ resourceID, _ := hostDiskResourceID(host, host.Disks[0])
+ cfg.Overrides = map[string]ThresholdConfig{resourceID: {Disk: &HysteresisThreshold{Trigger: 0}}}
+ m.UpdateConfig(cfg)
+ m.CheckNode(node)
+ m.mu.RLock()
+ observed := testCoreHasIncident(m, node.ID, canonicalMetricSpecID(node.ID, "disk"))
+ m.mu.RUnlock()
+ if !observed {
+ t.Fatal("saved direct disk disable left node disk unevaluated until another agent report")
+ }
+ })
+ t.Run("nil-disk-threshold-releases-pending", func(t *testing.T) {
+ m, _, host := setup(t)
+ host.Disks = []models.Disk{{Mountpoint: "/", Device: "/dev/sda1", Total: 100, Usage: 92}}
+ m.mu.Lock()
+ m.config.MetricTimeThresholds = map[string]map[string]int{"agent-disk": {"disk": 300}}
+ m.mu.Unlock()
+ m.CheckHost(host)
+ resourceID, _ := hostDiskResourceID(host, host.Disks[0])
+ specID := canonicalMetricSpecID(resourceID, "disk")
+ m.mu.Lock()
+ if !testCoreIsPending(m, resourceID, specID) {
+ m.mu.Unlock()
+ t.Fatal("control did not create a pending disk run")
+ }
+ m.config.AgentDefaults.Disk = nil
+ m.mu.Unlock()
+ m.CheckHost(host)
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ if testCoreHasIncident(m, resourceID, specID) {
+ t.Fatal("nil disk threshold retained a pending disk run")
+ }
+ })
+ for _, policy := range []string{"global", "host", "threshold"} {
+ t.Run("pending-release-"+policy, func(t *testing.T) {
+ m, _, host := setup(t)
+ m.EnableShadowFeed()
+ host.Memory = models.Memory{Total: 100, Used: 90, Free: 10, Usage: 90}
+ m.mu.Lock()
+ m.config.MetricTimeThresholds = map[string]map[string]int{"agent": {"memory": 300}}
+ m.mu.Unlock()
+ m.CheckHost(host)
+ resourceID := hostResourceID(host.ID)
+ specID := canonicalMetricSpecID(resourceID, "memory")
+ m.mu.Lock()
+ if !testCoreIsPending(m, resourceID, specID) {
+ m.mu.Unlock()
+ t.Fatal("control did not create a pending canonical memory run")
+ }
+ // Canonical metrics do not feed diagnostic shadow evaluation.
+ // Seed the matching diagnostic run explicitly to pin release mirroring.
+ m.shadow.state.ApplyMetric(reducer.MetricSignal{ResourceID: resourceID, Key: specID, Value: 90, ObservedAt: time.Now()}, reducer.MetricRule{Trigger: 85, Clear: 80, DelaySeconds: 300})
+ for _, state := range m.mirrorStatesNoLock() {
+ if incident, ok := state.Incident(resourceID, specID); !ok || string(incident.State) != "pending" {
+ m.mu.Unlock()
+ t.Fatal("control did not create a pending canonical/shadow memory run")
+ }
+ }
+ switch policy {
+ case "global":
+ m.config.DisableAllAgents = true
+ case "host":
+ m.config.Overrides = map[string]ThresholdConfig{host.ID: {Disabled: true}}
+ case "threshold":
+ m.config.AgentDefaults.Memory = &HysteresisThreshold{Trigger: 0}
+ }
+ m.mu.Unlock()
+ host.Memory = models.Memory{Total: 100, UsageUnavailable: true}
+ m.CheckHost(host)
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ for _, state := range m.mirrorStatesNoLock() {
+ if _, ok := state.Incident(resourceID, specID); ok {
+ t.Fatal("disabled interval retained a pending canonical/shadow memory run")
+ }
+ }
+ })
+ }
+ for _, scenario := range []string{"newer-unlink", "newer-cover", "offline", "removed", "config-disabled"} {
+ t.Run("in-flight-"+scenario, func(t *testing.T) {
+ m, node, host := setup(t)
+ m.mu.Lock()
+ m.config.MetricEvaluationWindows = map[string]map[string]int{"agent": {"cpu": 60}}
+ m.mu.Unlock()
+ entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
+ var calls atomic.Int32
+ var once sync.Once
+ defer once.Do(func() { close(release) })
+ m.SetMetricWindowProvider(func(r MetricWindowRequest) ([]MetricWindowPoint, error) {
+ if r.ResourceID == hostResourceID(host.ID) && r.Metric == "cpu" && calls.Add(1) == 1 {
+ close(entered)
+ <-release
+ }
+ return []MetricWindowPoint{{Timestamp: r.Start, Value: 50}, {Timestamp: r.Start.Add(30 * time.Second), Value: 50}}, nil
+ })
+ older := host
+ if scenario == "newer-cover" {
+ older.LinkedNodeID = ""
+ }
+ go func() { defer close(done); m.CheckHost(older) }()
+ select {
+ case <-entered:
+ case <-time.After(3 * time.Second):
+ t.Fatal("older report did not reach its evaluation window")
+ }
+ wantCover := false
+ switch scenario {
+ case "newer-unlink":
+ newer := host
+ newer.LinkedNodeID = ""
+ m.CheckHost(newer)
+ case "newer-cover":
+ m.CheckHost(host)
+ wantCover = true
+ case "offline":
+ m.HandleHostOffline(host)
+ case "removed":
+ m.HandleHostRemoved(host)
+ case "config-disabled":
+ cfg := m.GetConfig()
+ cfg.DisableAllAgents = true
+ m.UpdateConfig(cfg)
+ }
+ once.Do(func() { close(release) })
+ select {
+ case <-done:
+ case <-time.After(3 * time.Second):
+ t.Fatal("older report did not finish")
+ }
+ if got := m.hasHostAgentForNode(node.ID); got != wantCover {
+ t.Fatalf("coverage after %s = %v, want %v", scenario, got, wantCover)
+ }
+ })
+ }
+ t.Run("handover-names-metric-owner", func(t *testing.T) {
+ m, node, host := setup(t)
+ m.CheckNode(node)
+ var closed []*ResolvedAlert
+ m.SetResolvedAlertCallback(func(a *ResolvedAlert) { closed = append(closed, a) })
+ a := host
+ a.ID = "agent-a"
+ a.DisplayName = "CPU reader"
+ a.CPUUsage = 50
+ b := host
+ b.ID = "agent-b"
+ b.DisplayName = "Memory reader"
+ m.mu.Lock()
+ m.config.Overrides = map[string]ThresholdConfig{
+ a.ID: {Memory: &HysteresisThreshold{Trigger: 0}, Disk: &HysteresisThreshold{Trigger: 0}},
+ b.ID: {CPU: &HysteresisThreshold{Trigger: 0}, Disk: &HysteresisThreshold{Trigger: 0}},
+ }
+ m.mu.Unlock()
+ m.CheckHost(a)
+ m.CheckHost(b)
+ m.CheckNode(node)
+ seen := map[string]bool{}
+ for _, a := range closed {
+ if a.Alert.ResourceID != node.ID {
+ continue
+ }
+ expected := "agent:agent-a"
+ if a.Alert.Type == "memory" {
+ expected = "agent:agent-b"
+ }
+ if a.Alert.Resolution == nil || a.Alert.Resolution.Reason != AlertResolutionMovedToAgent || a.Alert.Resolution.SuccessorResourceID != expected {
+ t.Fatalf("%s close named wrong successor: %+v", a.Alert.Type, a.Alert.Resolution)
+ }
+ seen[a.Alert.Type] = true
+ }
+ if !seen["cpu"] || !seen["memory"] {
+ t.Fatalf("missing node handover callbacks: %v", seen)
+ }
+ if !testHasActiveAlert(t, m, canonicalMetricStateID(node.ID, "disk")) {
+ t.Fatal("node disk lost coverage even though neither agent owns a summary filesystem")
+ }
+ })
+}
diff --git a/internal/alerts/threshold_resolution_shared_test.go b/internal/alerts/threshold_resolution_shared_test.go
index 673a1bab50..53aaa6e226 100644
--- a/internal/alerts/threshold_resolution_shared_test.go
+++ b/internal/alerts/threshold_resolution_shared_test.go
@@ -1,6 +1,7 @@
package alerts
import (
+ "math"
"testing"
"time"
@@ -1445,3 +1446,258 @@ func TestDiskTemperatureThresholdMatchesCheckHostPolicy(t *testing.T) {
t.Fatalf("nil manager threshold = %+v, want the factory nvme 70", got)
}
}
+
+// An agent owns a usage metric only with usable evidence: it evaluated the
+// metric this report, or it still holds an alert or run for it. Configuration
+// alone is not coverage.
+func TestCheckNodeKeepsMetricsTheAgentCannotEvaluate(t *testing.T) {
+ setup := func(t *testing.T) (*Manager, models.Node, models.Host) {
+ m := newTestManager(t)
+ m.mu.Lock()
+ m.config.Enabled = true
+ m.config.TimeThresholds = map[string]int{}
+ m.config.NodeDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.config.NodeDefaults.Memory = &HysteresisThreshold{Trigger: 85, Clear: 80}
+ m.config.AgentDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.config.AgentDefaults.Memory = &HysteresisThreshold{Trigger: 85, Clear: 80}
+ m.mu.Unlock()
+ node, host := testNodeWithHostAgent()
+ node.CPU = 0.95
+ node.Memory = models.Memory{Total: 100, Used: 95, Free: 5, Usage: 95}
+ return m, node, host
+ }
+
+ t.Run("memory_unknown_from_the_start", func(t *testing.T) {
+ m, node, host := setup(t)
+ host.Memory = models.Memory{Total: 100, UsageUnavailable: true}
+ m.CheckHost(host)
+ m.CheckNode(node)
+ if !testHasActiveAlert(t, m, canonicalMetricStateID(node.ID, "memory")) {
+ t.Fatalf("expected the node to alert on memory while the agent has no memory reading")
+ }
+ })
+
+ t.Run("non_finite_cpu", func(t *testing.T) {
+ m, node, host := setup(t)
+ host.CPUUsage = math.NaN()
+ m.CheckHost(host)
+ m.CheckNode(node)
+ if !testHasActiveAlert(t, m, canonicalMetricStateID(node.ID, "cpu")) {
+ t.Fatalf("expected the node to alert on CPU while the agent reports no usable CPU value")
+ }
+ })
+}
+
+// Turning an agent threshold off releases its pending run even when the agent
+// reports no reading for that metric, so the old run cannot keep ownership and
+// leave the node silent.
+func TestDisabledAgentThresholdReleasesPendingRunWithoutReading(t *testing.T) {
+ m := newTestManager(t)
+ m.mu.Lock()
+ m.config.Enabled = true
+ m.config.TimeThresholds = map[string]int{}
+ m.config.MetricTimeThresholds = map[string]map[string]int{"agent": {"memory": 300}}
+ m.config.NodeDefaults.Memory = &HysteresisThreshold{Trigger: 85, Clear: 80}
+ m.config.AgentDefaults.Memory = &HysteresisThreshold{Trigger: 85, Clear: 80}
+ m.mu.Unlock()
+ node, host := testNodeWithHostAgent()
+ // 90% stays below the 95% critical level, which would bypass the delay.
+ node.Memory = models.Memory{Total: 100, Used: 90, Free: 10, Usage: 90}
+ host.Memory = node.Memory
+ agentResourceID := hostResourceID(host.ID)
+ agentMemorySpec := canonicalMetricSpecID(agentResourceID, "memory")
+
+ m.CheckHost(host)
+ m.mu.RLock()
+ pending := testCoreIsPending(m, agentResourceID, agentMemorySpec)
+ m.mu.RUnlock()
+ if !pending {
+ t.Fatalf("expected a pending agent memory run")
+ }
+
+ m.mu.Lock()
+ m.config.AgentDefaults.Memory = &HysteresisThreshold{Trigger: 0, Clear: 0}
+ m.mu.Unlock()
+ host.Memory = models.Memory{Total: 100, UsageUnavailable: true}
+ m.CheckHost(host)
+ m.CheckNode(node)
+
+ m.mu.RLock()
+ agentIncident := testCoreHasIncident(m, agentResourceID, agentMemorySpec)
+ nodeIncident := testCoreHasIncident(m, node.ID, canonicalMetricSpecID(node.ID, "memory"))
+ m.mu.RUnlock()
+ if agentIncident {
+ t.Fatalf("expected the disabled agent memory threshold to release its pending run")
+ }
+ if !nodeIncident {
+ t.Fatalf("expected the node to evaluate memory once the agent no longer covers it")
+ }
+}
+
+// Ownership follows the config at once and link updates apply in report order:
+// a config change revokes what it no longer supports without waiting for the
+// agent's next report, an older report can neither restore revoked ownership
+// nor remove a newer report's link, and a report started before the agent went
+// offline is stale.
+func TestHostAgentNodeLinkFollowsConfigAndReportOrder(t *testing.T) {
+ m := newTestManager(t)
+ m.mu.Lock()
+ m.config.Enabled = true
+ m.config.TimeThresholds = map[string]int{}
+ m.config.NodeDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.config.AgentDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.mu.Unlock()
+ node, host := testNodeWithHostAgent()
+ node.CPU = 0.95
+ host.CPUUsage = 50
+
+ m.CheckHost(host)
+ m.CheckNode(node)
+ nodeCPUSpec := canonicalMetricSpecID(node.ID, "cpu")
+ m.mu.RLock()
+ evaluatedBefore := testCoreHasIncident(m, node.ID, nodeCPUSpec)
+ m.mu.RUnlock()
+ if evaluatedBefore {
+ t.Fatalf("expected the agent to own CPU before the config change")
+ }
+
+ // A report already in flight when agent alerts are disabled must not
+ // restore ownership once it lands.
+ inFlight := m.beginHostAgentReport(host.ID)
+
+ // No agent report follows the config change; the node must evaluate CPU on
+ // its very next check. (UpdateConfig restores the default activation delay,
+ // so the run is pending rather than firing.)
+ config := m.GetConfig()
+ config.DisableAllAgents = true
+ m.UpdateConfig(config)
+ m.CheckNode(node)
+ m.mu.RLock()
+ evaluatedAfter := testCoreHasIncident(m, node.ID, nodeCPUSpec)
+ m.mu.RUnlock()
+ if !evaluatedAfter {
+ t.Fatalf("expected the node to evaluate CPU right after agent alerts were disabled")
+ }
+
+ covering := hostAgentNodeLink{agentID: host.ID, nodeID: node.ID, cpu: true}
+ m.applyHostAgentNodeLink(covering, inFlight)
+ if m.hasHostAgentForNode(node.ID) {
+ t.Fatalf("expected a report evaluated before agent alerts were disabled not to restore ownership")
+ }
+
+ config.DisableAllAgents = false
+ m.UpdateConfig(config)
+ older := m.beginHostAgentReport(host.ID)
+ newer := m.beginHostAgentReport(host.ID)
+ m.applyHostAgentNodeLink(covering, newer)
+ m.applyHostAgentNodeLink(hostAgentNodeLink{agentID: host.ID, nodeID: node.ID}, older)
+ if !m.hasHostAgentForNode(node.ID) {
+ t.Fatalf("expected an older report not to remove the newer report's link")
+ }
+
+ olderCovering := m.beginHostAgentReport(host.ID)
+ newerRemoving := m.beginHostAgentReport(host.ID)
+ m.applyHostAgentNodeLink(hostAgentNodeLink{agentID: host.ID, nodeID: node.ID}, newerRemoving)
+ m.applyHostAgentNodeLink(covering, olderCovering)
+ if m.hasHostAgentForNode(node.ID) {
+ t.Fatalf("expected an older report not to restore ownership a newer report removed")
+ }
+
+ beforeOffline := m.beginHostAgentReport(host.ID)
+ m.HandleHostOffline(host)
+ m.applyHostAgentNodeLink(covering, beforeOffline)
+ if m.hasHostAgentForNode(node.ID) {
+ t.Fatalf("expected a report started before the agent went offline not to re-register")
+ }
+}
+
+// An agent that reports unlinked hands its former node the usage metrics back
+// on the node's next check, even while the agent's own alert is still firing.
+func TestCheckNodeTakesBackMetricsWhenAgentUnlinks(t *testing.T) {
+ m := newTestManager(t)
+ m.mu.Lock()
+ m.config.Enabled = true
+ m.config.TimeThresholds = map[string]int{}
+ m.config.NodeDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.config.AgentDefaults.CPU = &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.mu.Unlock()
+ node, host := testNodeWithHostAgent()
+ node.CPU = 0.95
+ host.CPUUsage = 95
+
+ m.CheckHost(host)
+ m.CheckNode(node)
+ nodeCPU := canonicalMetricStateID(node.ID, "cpu")
+ if testHasActiveAlert(t, m, nodeCPU) {
+ t.Fatalf("expected the linked agent to own CPU")
+ }
+
+ host.LinkedNodeID = ""
+ m.CheckHost(host)
+ m.CheckNode(node)
+ if !testHasActiveAlert(t, m, nodeCPU) {
+ t.Fatalf("expected the node to alert on CPU once its agent reports unlinked")
+ }
+}
+
+// An explicit disk override, including one inherited from the linked node,
+// beats the per-type DiskFillByType default; otherwise the node released its
+// disk alert to an agent applying a looser per-type threshold.
+func TestHostDiskOverrideBeatsDiskFillByType(t *testing.T) {
+ for _, overrideOn := range []string{"linked node", "agent"} {
+ t.Run(overrideOn, func(t *testing.T) {
+ m := newTestManager(t)
+ node, host := testNodeWithHostAgent()
+ overrideID := node.ID
+ if overrideOn == "agent" {
+ overrideID = host.ID
+ }
+ m.mu.Lock()
+ m.config.Enabled = true
+ m.config.TimeThresholds = map[string]int{}
+ m.config.AgentDefaults.Disk = &HysteresisThreshold{Trigger: 90, Clear: 85}
+ m.config.DiskFillByType = map[string]HysteresisThreshold{"nvme": {Trigger: 92, Clear: 88}}
+ m.config.Overrides = map[string]ThresholdConfig{
+ overrideID: {Disk: &HysteresisThreshold{Trigger: 80, Clear: 75}},
+ }
+ m.mu.Unlock()
+ root := models.Disk{Mountpoint: "/", Device: "/dev/nvme0n1p2", Total: 100, Used: 85, Free: 15, Usage: 85}
+ host.Disks = []models.Disk{root}
+
+ m.CheckHost(host)
+ rootResourceID, _ := hostDiskResourceID(host, root)
+ if !testHasActiveAlert(t, m, canonicalMetricStateID(rootResourceID, "disk")) {
+ t.Fatalf("expected the 80%% %s disk override to raise the agent's root disk alert at 85%%", overrideOn)
+ }
+ })
+ }
+}
+
+// Releasing a metric drops its explicit intent grace run too, so a later
+// resume does not activate at once on time counted while nothing evaluated.
+func TestReleaseCanonicalMetricAlertClearsIntentPending(t *testing.T) {
+ m := newTestManager(t)
+ spec, err := buildCanonicalMetricSpec("homelab-delly2", "delly2", "node", "cpu", nil)
+ if err != nil {
+ t.Fatalf("spec: %v", err)
+ }
+ trackingKey := canonicalTrackingKeyForSpec(spec, spec.ID)
+ m.mu.Lock()
+ m.intentPending[trackingKey] = IntentPendingState{
+ TrackingKey: trackingKey,
+ ResourceID: spec.ResourceID,
+ Signal: MetricAlertIntentSignal("cpu"),
+ FirstMatchedAt: time.Now().Add(-10 * time.Minute),
+ LastObservedAt: time.Now().Add(-9 * time.Minute),
+ }
+ m.mu.Unlock()
+
+ m.releaseCanonicalMetricAlert(spec, "delly2", "delly2", "homelab", "node", 0, nil)
+
+ m.mu.RLock()
+ _, stillPending := m.intentPending[trackingKey]
+ m.mu.RUnlock()
+ if stillPending {
+ t.Fatalf("expected releasing the metric to clear its intent pending state")
+ }
+}
diff --git a/internal/alerts/unified_eval.go b/internal/alerts/unified_eval.go
index 74796bd896..b108596bcf 100644
--- a/internal/alerts/unified_eval.go
+++ b/internal/alerts/unified_eval.go
@@ -500,11 +500,11 @@ func buildCanonicalMetricSpec(resourceID, title string, resourceType unifiedreso
return spec, spec.Validate()
}
-func (m *Manager) checkMetricWithCanonicalSpec(spec alertspecs.ResourceAlertSpec, resourceName, node, instance, resourceType string, value float64, threshold *HysteresisThreshold, opts *metricOptions) {
+func (m *Manager) checkMetricWithCanonicalSpec(spec alertspecs.ResourceAlertSpec, resourceName, node, instance, resourceType string, value float64, threshold *HysteresisThreshold, opts *metricOptions) bool {
if spec.MetricThreshold == nil {
- return
+ return false
}
- m.evaluateCanonicalMetricAlert(spec, resourceName, node, instance, resourceType, value, threshold, opts)
+ return m.evaluateCanonicalMetricAlert(spec, resourceName, node, instance, resourceType, value, threshold, opts)
}
func unifiedMetricResourceType(typeKey string) (unifiedresources.ResourceType, bool) {
diff --git a/internal/alerts/windowed_metric_test.go b/internal/alerts/windowed_metric_test.go
index fc216db290..528e5b22e3 100644
--- a/internal/alerts/windowed_metric_test.go
+++ b/internal/alerts/windowed_metric_test.go
@@ -428,3 +428,44 @@ func TestUnknownMetricObservationDropsDurableIntentCheckpoint(t *testing.T) {
})
}
}
+
+// The evaluator reports whether an observation was usable evidence; host-agent
+// deduplication hands a node metric to an agent only on that evidence (or an
+// incident the agent still holds), never on configuration alone.
+func TestCheckMetricReportsWhetherObservationWasUsable(t *testing.T) {
+ live := &HysteresisThreshold{Trigger: 80, Clear: 75}
+ cases := []struct {
+ name string
+ threshold *HysteresisThreshold
+ value float64
+ window int
+ provider bool
+ want bool
+ }{
+ {name: "live threshold, instant evaluation", threshold: live, value: 50, want: true},
+ {name: "disabled threshold", threshold: &HysteresisThreshold{Trigger: 0}, value: 50, want: false},
+ {name: "non-finite value", threshold: live, value: math.NaN(), want: false},
+ {name: "evaluation window without history", threshold: live, value: 50, window: 300, provider: true, want: false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ m := NewManagerWithDataDir(t.TempDir(), WithoutPersistedAlertRestore())
+ t.Cleanup(m.Stop)
+ m.mu.Lock()
+ m.config.MetricEvaluationWindows = map[string]map[string]int{"all": {"cpu": tc.window}}
+ m.mu.Unlock()
+ if tc.provider {
+ m.SetMetricWindowProvider(func(MetricWindowRequest) ([]MetricWindowPoint, error) {
+ return nil, nil
+ })
+ }
+ spec, err := buildCanonicalMetricSpec("vm-1", "web-1", unifiedresources.ResourceTypeVM, "cpu", tc.threshold)
+ if err != nil {
+ t.Fatalf("spec: %v", err)
+ }
+ if got := m.checkMetricWithCanonicalSpec(spec, "web-1", "node-1", "pve-1", "vm", tc.value, tc.threshold, nil); got != tc.want {
+ t.Fatalf("usable evidence = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/monitoring/monitor_alert_handling_test.go b/internal/monitoring/monitor_alert_handling_test.go
index 3a5b27f43f..7a903f669f 100644
--- a/internal/monitoring/monitor_alert_handling_test.go
+++ b/internal/monitoring/monitor_alert_handling_test.go
@@ -1771,3 +1771,74 @@ func TestSilentLinkedAgentStopsRefreshingNodeTemperatureAlert(t *testing.T) {
require.NotNil(t, poll())
require.True(t, temperatureAlert().LastSeen.After(held.LastSeen), "a fresh agent reading is evaluated")
}
+
+// Drive the actual node/agent evaluators into the monitor's lifecycle handler,
+// rather than fabricating a pre-stamped handover event.
+func TestMonitorReportedAgentHandoverUsesActualMetricOwner(t *testing.T) {
+ manager := alerts.NewManagerWithDataDir(t.TempDir(), alerts.WithoutPersistedAlertRestore())
+ t.Cleanup(manager.Stop)
+ cfg := manager.GetConfig()
+ cfg.Enabled = true
+ cfg.ActivationState = alerts.ActivationPending
+ cfg.TimeThresholds = map[string]int{}
+ cfg.SuppressionWindow = 0
+ cfg.NodeDefaults.CPU = &alerts.HysteresisThreshold{Trigger: 80, Clear: 75}
+ cfg.NodeDefaults.Memory = &alerts.HysteresisThreshold{Trigger: 85, Clear: 80}
+ cfg.AgentDefaults.CPU = &alerts.HysteresisThreshold{Trigger: 80, Clear: 75}
+ cfg.AgentDefaults.Memory = &alerts.HysteresisThreshold{Trigger: 85, Clear: 80}
+ cfg.Overrides = map[string]alerts.ThresholdConfig{
+ "agent-a": {Memory: &alerts.HysteresisThreshold{Trigger: 0}},
+ "agent-b": {CPU: &alerts.HysteresisThreshold{Trigger: 0}},
+ }
+ manager.UpdateConfig(cfg)
+ store := unifiedresources.NewMemoryStore()
+ incidentStore := memory.NewIncidentStore(memory.IncidentStoreConfig{})
+ m := &Monitor{alertManager: manager, incidentStore: incidentStore, resourceStore: unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store))}
+ incidentStore.SetResourceTimelineStore(m.resourceStore.(memory.IncidentTimelineStore))
+ manager.SubscribeLifecycleCallback(m.handleAlertLifecycleEvent)
+ node := models.Node{ID: "instance/node", Name: "node", Instance: "instance", Status: "online", ConnectionHealth: "healthy", CPU: 0.99, Memory: models.Memory{Total: 100, Used: 99, Free: 1, Usage: 99}}
+ manager.CheckNode(node)
+ opened := manager.GetActiveAlerts()
+ require.Len(t, opened, 2)
+ cpuAgent := models.Host{ID: "agent-a", Hostname: "node", DisplayName: "CPU reader", Status: "online", LinkedNodeID: node.ID, CPUUsage: 50}
+ memoryAgent := models.Host{ID: "agent-b", Hostname: "node", DisplayName: "Memory reader", Status: "online", LinkedNodeID: node.ID, Memory: node.Memory}
+ manager.CheckHost(cpuAgent)
+ manager.CheckHost(memoryAgent)
+ manager.CheckNode(node)
+ for _, a := range opened {
+ timeline := incidentStore.GetTimelineByAlertAt(a.ID, a.StartTime)
+ require.NotNil(t, timeline)
+ require.Len(t, timeline.Events, 2)
+ wantName := "CPU reader"
+ wantID := "agent:agent-a"
+ if a.Type == "memory" {
+ wantName = "Memory reader"
+ wantID = "agent:agent-b"
+ }
+ summary := "Alert moved to " + wantName + ". This is not a recovery: check the agent for the current reading."
+ require.Equal(t, summary, timeline.Events[1].Summary)
+ events, err := manager.AlertEvents(eventlog.Filter{AlertID: a.ID, Types: []string{eventlog.TypeResolved}})
+ require.NoError(t, err)
+ require.Len(t, events, 1)
+ require.Equal(t, "moved_to_agent", events[0].Reason)
+ require.Equal(t, summary, events[0].Message)
+ found := false
+ for _, row := range manager.GetAlertHistory(10) {
+ if row.ID == a.ID && row.Resolution != nil {
+ found = true
+ require.NotNil(t, row.Resolution)
+ require.Equal(t, wantID, row.Resolution.SuccessorResourceID)
+ }
+ }
+ require.True(t, found, "no resolved History row for %s", a.ID)
+ }
+ changes, err := store.GetRecentChanges(node.ID, time.Time{}, 10)
+ require.NoError(t, err)
+ require.Len(t, changes, 4)
+ for _, c := range changes {
+ if c.Kind == unifiedresources.ChangeAlertResolved {
+ require.Equal(t, "moved_to_agent", c.Metadata[unifiedresources.MetadataAlertResolution])
+ require.Contains(t, c.Reason, "This is not a recovery")
+ }
+ }
+}