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 live resource metrics fresh

rcourtman6abcac3fdebf
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 6774a286b8..57f318a1d5 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -401,6 +401,12 @@ payloads from the active metrics-target read-state before serialization so
as `/api/resources`; storage resources must not fall back to generated
`Resource.ID` values when the unified resource registry can resolve a
source-owned `storage` target.
+That same broadcast projection owns aggregate resource disk I/O. When the
+canonical unified-resource metrics include `diskRead` or `diskWrite`,
+`internal/monitoring/monitor.go` must project those rates into
+`ResourceFrontend.diskIO` through the shared resource converter, so
+`/api/state` and websocket consumers read disk throughput from the same
+freshness-gated resource metrics contract as CPU, memory, disk, and network.
Unraid ingest must preserve the agent's native disk topology fields through the
monitoring model and read-state projection. `internal/monitoring/monitor_agents.go`
and `internal/monitoring/monitor.go` must carry model, transport, filesystem,
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 451a7c9075..0599f2f588 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -912,6 +912,15 @@ table owners. Proxmox host row version, uptime, temperature, CPU, memory, disk,
network I/O, and disk I/O presentation must derive from canonical resource
facets and the shared `nodeFromResource` adapter; platform pages must not
rebuild resource identity, merge policy, or metric-target inference locally.
+The registry and presentation coalescer also own metric-source freshness. When
+two source facets contribute the same metric, source priority decides only if
+both sources have equivalent freshness. A stale source must not hold CPU,
+memory, disk, network, or disk I/O metrics against a live source, and a stale
+incoming source must not clobber a live metric already attached to the
+canonical resource. This freshness gate belongs in
+`internal/unifiedresources/registry.go` and
+`internal/unifiedresources/presentation_coalesce.go`, not in platform-page
+rendering or frontend fallback code.
`resource_operator_state.go` owns the operator-set per-resource intent
schema. `ResourceOperatorState` carries four narrow operator-intent
diff --git a/internal/models/converters.go b/internal/models/converters.go
index a14d9cfe66..5ed492bd67 100644
--- a/internal/models/converters.go
+++ b/internal/models/converters.go
@@ -1030,6 +1030,9 @@ type ResourceConvertInput struct {
NetworkRX int64
NetworkTX int64
HasNetwork bool
+ DiskReadRate int64
+ DiskWriteRate int64
+ HasDiskIO bool
Temperature *float64
Uptime *int64
Tags []string
@@ -1193,6 +1196,13 @@ func ConvertResourceToFrontend(input ResourceConvertInput) ResourceFrontend {
}
}
+ if input.HasDiskIO {
+ rf.DiskIO = &ResourceDiskIOFrontend{
+ ReadRate: input.DiskReadRate,
+ WriteRate: input.DiskWriteRate,
+ }
+ }
+
// Convert alerts
if len(input.Alerts) > 0 {
rf.Alerts = make([]ResourceAlertFrontend, len(input.Alerts))
diff --git a/internal/models/converters_test.go b/internal/models/converters_test.go
index 8fcc2bf564..050d2469fb 100644
--- a/internal/models/converters_test.go
+++ b/internal/models/converters_test.go
@@ -268,6 +268,30 @@ func TestVMToFrontend_NegativeNetworkValues(t *testing.T) {
}
}
+func TestConvertResourceToFrontendIncludesDiskIO(t *testing.T) {
+ frontend := ConvertResourceToFrontend(ResourceConvertInput{
+ ID: "agent-1",
+ Type: "agent",
+ Name: "tower",
+ DisplayName: "tower",
+ PlatformID: "tower",
+ PlatformType: "agent",
+ SourceType: "agent",
+ Status: "online",
+ LastSeenUnix: time.Now().UnixMilli(),
+ HasDiskIO: true,
+ DiskReadRate: 4096,
+ DiskWriteRate: 8192,
+ })
+
+ if frontend.DiskIO == nil {
+ t.Fatal("expected disk I/O rates to be present")
+ }
+ if frontend.DiskIO.ReadRate != 4096 || frontend.DiskIO.WriteRate != 8192 {
+ t.Fatalf("unexpected disk I/O rates: %+v", frontend.DiskIO)
+ }
+}
+
func TestContainerToFrontend(t *testing.T) {
now := time.Now()
diff --git a/internal/models/models_frontend.go b/internal/models/models_frontend.go
index 6545735a4c..f104915398 100644
--- a/internal/models/models_frontend.go
+++ b/internal/models/models_frontend.go
@@ -971,6 +971,7 @@ type ResourceFrontend struct {
Memory *ResourceMetricFrontend `json:"memory,omitempty"`
Disk *ResourceMetricFrontend `json:"disk,omitempty"`
Network *ResourceNetworkFrontend `json:"network,omitempty"`
+ DiskIO *ResourceDiskIOFrontend `json:"diskIO,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
Uptime *int64 `json:"uptime,omitempty"`
@@ -1052,6 +1053,12 @@ type ResourceNetworkFrontend struct {
TXBytes int64 `json:"txBytes"`
}
+// ResourceDiskIOFrontend represents aggregate disk I/O rates for the frontend.
+type ResourceDiskIOFrontend struct {
+ ReadRate int64 `json:"readRate"`
+ WriteRate int64 `json:"writeRate"`
+}
+
// ResourceAlertFrontend represents an alert on a resource.
type ResourceAlertFrontend struct {
ID string `json:"id"`
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index 7978b84045..7fb6b4d330 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -74,6 +74,19 @@ func TestNoGetStateResourceArrayRegression(t *testing.T) {
}
}
+func TestBroadcastResourceDiskIOUsesUnifiedResourceMetrics(t *testing.T) {
+ hasDiskIO, readRate, writeRate := monitorDiskIOMetricInput(&unifiedresources.ResourceMetrics{
+ DiskRead: &unifiedresources.MetricValue{Value: 4096.4, Unit: "bytes/s", Source: unifiedresources.SourceAgent},
+ DiskWrite: &unifiedresources.MetricValue{Value: 8191.6, Unit: "bytes/s", Source: unifiedresources.SourceAgent},
+ })
+ if !hasDiskIO {
+ t.Fatal("expected disk I/O metrics to be projected")
+ }
+ if readRate != 4096 || writeRate != 8192 {
+ t.Fatalf("unexpected projected disk I/O rates: read=%d write=%d", readRate, writeRate)
+ }
+}
+
func TestStandaloneInactiveDockerSwarmMetadataIsNotCapabilityEvidence(t *testing.T) {
got := convertDockerSwarmInfo(&agentsdocker.SwarmInfo{
NodeRole: "worker",
diff --git a/internal/monitoring/ceph.go b/internal/monitoring/ceph.go
index 4fa97e28f9..068fc9f66b 100644
--- a/internal/monitoring/ceph.go
+++ b/internal/monitoring/ceph.go
@@ -60,8 +60,8 @@ func (m *Monitor) pollCephCluster(ctx context.Context, instanceName string, clie
}
storedClusters := m.state.UpdateCephClustersForInstance(instanceName, []models.CephCluster{cluster})
- for _, storedCluster := range storedClusters {
- m.checkCephPoolStorage(storedCluster)
+ for _, cluster := range storedClusters {
+ m.checkCephPoolStorage(cluster)
}
}
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 0b83c2ba7c..00d1929c8a 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -5090,6 +5090,10 @@ func monitorResourceToConvertInput(resource unifiedresources.Resource) models.Re
input.HasNetwork = hasNetwork
input.NetworkRX = rx
input.NetworkTX = tx
+ hasDiskIO, diskRead, diskWrite := monitorDiskIOMetricInput(resource.Metrics)
+ input.HasDiskIO = hasDiskIO
+ input.DiskReadRate = diskRead
+ input.DiskWriteRate = diskWrite
return input
}
@@ -5460,6 +5464,22 @@ func monitorNetworkMetricInput(metrics *unifiedresources.ResourceMetrics) (bool,
return true, rx, tx
}
+func monitorDiskIOMetricInput(metrics *unifiedresources.ResourceMetrics) (bool, int64, int64) {
+ if metrics == nil || (metrics.DiskRead == nil && metrics.DiskWrite == nil) {
+ return false, 0, 0
+ }
+
+ var read int64
+ var write int64
+ if metrics.DiskRead != nil {
+ read = int64(math.Round(metrics.DiskRead.Value))
+ }
+ if metrics.DiskWrite != nil {
+ write = int64(math.Round(metrics.DiskWrite.Value))
+ }
+ return true, read, write
+}
+
func monitorTemperature(resource unifiedresources.Resource) *float64 {
if resource.Agent != nil && resource.Agent.Temperature != nil {
value := *resource.Agent.Temperature
diff --git a/internal/monitoring/monitor_unified_state_test.go b/internal/monitoring/monitor_unified_state_test.go
index 0fd2d6c024..c9a162133d 100644
--- a/internal/monitoring/monitor_unified_state_test.go
+++ b/internal/monitoring/monitor_unified_state_test.go
@@ -119,6 +119,18 @@ func TestConvertResourcesForBroadcastCoalescesSplitHostResources(t *testing.T) {
Hostname: "delly",
OSName: "Proxmox VE",
},
+ Metrics: &unifiedresources.ResourceMetrics{
+ DiskRead: &unifiedresources.MetricValue{
+ Value: 4096,
+ Unit: "bytes/s",
+ Source: unifiedresources.SourceAgent,
+ },
+ DiskWrite: &unifiedresources.MetricValue{
+ Value: 8192,
+ Unit: "bytes/s",
+ Source: unifiedresources.SourceAgent,
+ },
+ },
},
}
@@ -150,6 +162,12 @@ func TestConvertResourcesForBroadcastCoalescesSplitHostResources(t *testing.T) {
if len(resource.Agent) == 0 {
t.Fatal("expected merged agent facet")
}
+ if resource.DiskIO == nil {
+ t.Fatal("expected aggregate disk I/O rates in broadcast resource")
+ }
+ if resource.DiskIO.ReadRate != 4096 || resource.DiskIO.WriteRate != 8192 {
+ t.Fatalf("unexpected aggregate disk I/O rates: %+v", resource.DiskIO)
+ }
}
func TestConvertResourcesForBroadcastAttachesResolvedStorageMetricsTarget(t *testing.T) {
diff --git a/internal/unifiedresources/presentation_coalesce.go b/internal/unifiedresources/presentation_coalesce.go
index 230f57ccb5..7da2a0453b 100644
--- a/internal/unifiedresources/presentation_coalesce.go
+++ b/internal/unifiedresources/presentation_coalesce.go
@@ -209,7 +209,18 @@ func mergePresentationHostResources(left, right Resource) Resource {
if merged.Metrics == nil {
merged.Metrics = secondary.Metrics
} else if secondary.Metrics != nil {
- merged.Metrics = mergePresentationMetrics(merged.Metrics, secondary.Metrics)
+ now := time.Now().UTC()
+ combinedStatus := make(map[DataSource]SourceStatus, len(primary.SourceStatus)+len(secondary.SourceStatus))
+ for source, status := range secondary.SourceStatus {
+ combinedStatus[source] = status
+ }
+ for source, status := range primary.SourceStatus {
+ combinedStatus[source] = status
+ }
+ stale := func(source DataSource) bool {
+ return presentationSourceStale(now, combinedStatus, source)
+ }
+ merged.Metrics = mergePresentationMetrics(merged.Metrics, secondary.Metrics, stale)
}
if merged.DiscoveryTarget == nil {
merged.DiscoveryTarget = secondary.DiscoveryTarget
@@ -307,35 +318,57 @@ func uniquePresentationStrings(values []string) []string {
return unique
}
-func mergePresentationMetrics(left, right *ResourceMetrics) *ResourceMetrics {
+// presentationSourceStale reports whether a source's most recent report is
+// older than its stale threshold. A zero/unknown last-seen is treated as NOT
+// stale so coalescing never demotes a source on missing information.
+func presentationSourceStale(now time.Time, status map[DataSource]SourceStatus, source DataSource) bool {
+ if status == nil {
+ return false
+ }
+ st, ok := status[source]
+ if !ok || st.LastSeen.IsZero() {
+ return false
+ }
+ threshold, ok := defaultStaleThresholds[source]
+ if !ok {
+ threshold = 60 * time.Second
+ }
+ return now.Sub(st.LastSeen) > threshold
+}
+
+// mergePresentationMetric keeps the primary (left) value, except that a metric
+// from a stale source must never win over a metric from a live one. Without
+// this, a Proxmox node whose Pulse Agent has gone offline shows the agent's
+// last (usually 0) CPU instead of the live PVE value, because the agent is the
+// presentation primary and its 0 reading is non-nil.
+func mergePresentationMetric(left, right *MetricValue, stale func(DataSource) bool) *MetricValue {
if left == nil {
return right
}
if right == nil {
return left
}
- merged := *left
- if merged.CPU == nil {
- merged.CPU = right.CPU
- }
- if merged.Memory == nil {
- merged.Memory = right.Memory
- }
- if merged.Disk == nil {
- merged.Disk = right.Disk
- }
- if merged.NetIn == nil {
- merged.NetIn = right.NetIn
- }
- if merged.NetOut == nil {
- merged.NetOut = right.NetOut
+ if stale(left.Source) && !stale(right.Source) {
+ return right
}
- if merged.DiskRead == nil {
- merged.DiskRead = right.DiskRead
+ return left
+}
+
+func mergePresentationMetrics(left, right *ResourceMetrics, stale func(DataSource) bool) *ResourceMetrics {
+ if left == nil {
+ return right
}
- if merged.DiskWrite == nil {
- merged.DiskWrite = right.DiskWrite
+ if right == nil {
+ return left
}
+ merged := *left
+ merged.CPU = mergePresentationMetric(left.CPU, right.CPU, stale)
+ merged.Memory = mergePresentationMetric(left.Memory, right.Memory, stale)
+ merged.Disk = mergePresentationMetric(left.Disk, right.Disk, stale)
+ merged.NetIn = mergePresentationMetric(left.NetIn, right.NetIn, stale)
+ merged.NetOut = mergePresentationMetric(left.NetOut, right.NetOut, stale)
+ merged.DiskRead = mergePresentationMetric(left.DiskRead, right.DiskRead, stale)
+ merged.DiskWrite = mergePresentationMetric(left.DiskWrite, right.DiskWrite, stale)
return &merged
}
diff --git a/internal/unifiedresources/presentation_coalesce_test.go b/internal/unifiedresources/presentation_coalesce_test.go
index df1d7ffc73..47d9b2db96 100644
--- a/internal/unifiedresources/presentation_coalesce_test.go
+++ b/internal/unifiedresources/presentation_coalesce_test.go
@@ -173,3 +173,102 @@ func TestCoalescePresentationHostResourcesWithExclusionsHonorsManualSplit(t *tes
t.Fatalf("expected manual split exclusion to keep resources separate, got %#v", coalesced)
}
}
+
+// A Proxmox node whose Pulse Agent has gone offline must show the live PVE CPU,
+// not the agent's last (0) reading. The agent is the presentation primary, so
+// without a freshness gate its stale 0 CPU was kept and the live value dropped.
+func TestCoalescePresentationHostResourcesPrefersLiveProxmoxCPUOverOfflineAgent(t *testing.T) {
+ now := time.Now().UTC()
+ resources := []Resource{
+ {
+ ID: "proxmox-delly",
+ Type: ResourceTypeAgent,
+ Name: "delly",
+ Status: StatusOnline,
+ LastSeen: now,
+ Sources: []DataSource{SourceProxmox},
+ SourceStatus: map[DataSource]SourceStatus{
+ SourceProxmox: {Status: "online", LastSeen: now},
+ },
+ Identity: ResourceIdentity{Hostnames: []string{"delly"}},
+ Proxmox: &ProxmoxData{NodeName: "delly", ClusterName: "homelab"},
+ Metrics: &ResourceMetrics{
+ CPU: &MetricValue{Value: 2.88, Percent: 2.88, Unit: "percent", Source: SourceProxmox},
+ },
+ },
+ {
+ ID: "agent-delly",
+ Type: ResourceTypeAgent,
+ Name: "delly",
+ Status: StatusOnline,
+ LastSeen: now.Add(-2 * time.Hour),
+ Sources: []DataSource{SourceAgent},
+ SourceStatus: map[DataSource]SourceStatus{
+ SourceAgent: {Status: "stale", LastSeen: now.Add(-2 * time.Hour)},
+ },
+ Identity: ResourceIdentity{MachineID: "agent-machine-delly", Hostnames: []string{"delly"}},
+ Agent: &AgentData{AgentID: "agent-machine-delly", Hostname: "delly"},
+ Metrics: &ResourceMetrics{
+ CPU: &MetricValue{Value: 0, Percent: 0, Unit: "percent", Source: SourceAgent},
+ },
+ },
+ }
+
+ coalesced := CoalescePresentationHostResources(resources)
+ if len(coalesced) != 1 {
+ t.Fatalf("expected split host resources to coalesce into 1, got %d: %#v", len(coalesced), coalesced)
+ }
+ cpu := coalesced[0].Metrics.CPU
+ if cpu == nil || cpu.Percent != 2.88 {
+ t.Fatalf("expected live Proxmox CPU 2.88 to win over offline agent CPU 0, got %+v", cpu)
+ }
+}
+
+// When the agent is live it stays the preferred CPU source (the presentation
+// primary), so a fresh agent reading is not displaced by the API value.
+func TestCoalescePresentationHostResourcesKeepsLiveAgentCPU(t *testing.T) {
+ now := time.Now().UTC()
+ resources := []Resource{
+ {
+ ID: "proxmox-pi",
+ Type: ResourceTypeAgent,
+ Name: "pi",
+ Status: StatusOnline,
+ LastSeen: now,
+ Sources: []DataSource{SourceProxmox},
+ SourceStatus: map[DataSource]SourceStatus{
+ SourceProxmox: {Status: "online", LastSeen: now},
+ },
+ Identity: ResourceIdentity{Hostnames: []string{"pi"}},
+ Proxmox: &ProxmoxData{NodeName: "pi"},
+ Metrics: &ResourceMetrics{
+ CPU: &MetricValue{Value: 5, Percent: 5, Unit: "percent", Source: SourceProxmox},
+ },
+ },
+ {
+ ID: "agent-pi",
+ Type: ResourceTypeAgent,
+ Name: "pi",
+ Status: StatusOnline,
+ LastSeen: now,
+ Sources: []DataSource{SourceAgent},
+ SourceStatus: map[DataSource]SourceStatus{
+ SourceAgent: {Status: "online", LastSeen: now},
+ },
+ Identity: ResourceIdentity{MachineID: "agent-machine-pi", Hostnames: []string{"pi"}},
+ Agent: &AgentData{AgentID: "agent-machine-pi", Hostname: "pi"},
+ Metrics: &ResourceMetrics{
+ CPU: &MetricValue{Value: 12, Percent: 12, Unit: "percent", Source: SourceAgent},
+ },
+ },
+ }
+
+ coalesced := CoalescePresentationHostResources(resources)
+ if len(coalesced) != 1 {
+ t.Fatalf("expected coalesce into 1, got %d", len(coalesced))
+ }
+ cpu := coalesced[0].Metrics.CPU
+ if cpu == nil || cpu.Percent != 12 {
+ t.Fatalf("expected live agent CPU 12 to be kept, got %+v", cpu)
+ }
+}
diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.go
index db797a2508..66b4195218 100644
--- a/internal/unifiedresources/registry.go
+++ b/internal/unifiedresources/registry.go
@@ -2192,11 +2192,12 @@ func (rr *ResourceRegistry) mergeInto(existing *Resource, incoming Resource, sou
if incoming.LastSeen.After(existing.LastSeen) {
existing.LastSeen = incoming.LastSeen
}
- existing.UpdatedAt = time.Now().UTC()
+ now := time.Now().UTC()
+ existing.UpdatedAt = now
existing.ParentID = rr.resolveCanonicalParentID(existing)
existing.Status = chooseStatus(existing.Status, incoming.Status, source)
- existing.Metrics = mergeMetrics(existing.Metrics, incoming.Metrics, source)
+ existing.Metrics = mergeMetrics(existing.Metrics, incoming.Metrics, source, now, existing.SourceStatus)
// Prefer agent naming when available
if incoming.Name != "" {
@@ -2772,7 +2773,7 @@ func (rr *ResourceRegistry) mergeResourceData(primary *Resource, other *Resource
primary.Ceph = other.Ceph
}
- primary.Metrics = mergeMetrics(primary.Metrics, other.Metrics, SourceAgent)
+ primary.Metrics = mergeMetrics(primary.Metrics, other.Metrics, SourceAgent, time.Now().UTC(), primary.SourceStatus)
primary.Status = aggregateStatus(primary)
}
@@ -3546,7 +3547,7 @@ func addSources(sources []DataSource, more []DataSource) []DataSource {
return out
}
-func mergeMetrics(existing *ResourceMetrics, incoming *ResourceMetrics, source DataSource) *ResourceMetrics {
+func mergeMetrics(existing *ResourceMetrics, incoming *ResourceMetrics, source DataSource, now time.Time, status map[DataSource]SourceStatus) *ResourceMetrics {
if existing == nil {
return incoming
}
@@ -3554,17 +3555,35 @@ func mergeMetrics(existing *ResourceMetrics, incoming *ResourceMetrics, source D
return existing
}
merged := *existing
- merged.CPU = mergeMetric(existing.CPU, incoming.CPU, source)
- merged.Memory = mergeMetric(existing.Memory, incoming.Memory, source)
- merged.Disk = mergeMetric(existing.Disk, incoming.Disk, source)
- merged.NetIn = mergeMetric(existing.NetIn, incoming.NetIn, source)
- merged.NetOut = mergeMetric(existing.NetOut, incoming.NetOut, source)
- merged.DiskRead = mergeMetric(existing.DiskRead, incoming.DiskRead, source)
- merged.DiskWrite = mergeMetric(existing.DiskWrite, incoming.DiskWrite, source)
+ merged.CPU = mergeMetric(existing.CPU, incoming.CPU, source, now, status)
+ merged.Memory = mergeMetric(existing.Memory, incoming.Memory, source, now, status)
+ merged.Disk = mergeMetric(existing.Disk, incoming.Disk, source, now, status)
+ merged.NetIn = mergeMetric(existing.NetIn, incoming.NetIn, source, now, status)
+ merged.NetOut = mergeMetric(existing.NetOut, incoming.NetOut, source, now, status)
+ merged.DiskRead = mergeMetric(existing.DiskRead, incoming.DiskRead, source, now, status)
+ merged.DiskWrite = mergeMetric(existing.DiskWrite, incoming.DiskWrite, source, now, status)
return &merged
}
-func mergeMetric(existing *MetricValue, incoming *MetricValue, source DataSource) *MetricValue {
+// metricSourceStale reports whether a source's most recent report is older than
+// its stale threshold. A zero/unknown last-seen is treated as NOT stale so the
+// merge never demotes a source on missing information.
+func metricSourceStale(now time.Time, status map[DataSource]SourceStatus, source DataSource) bool {
+ if status == nil {
+ return false
+ }
+ st, ok := status[source]
+ if !ok || st.LastSeen.IsZero() {
+ return false
+ }
+ threshold, ok := defaultStaleThresholds[source]
+ if !ok {
+ threshold = 60 * time.Second
+ }
+ return now.Sub(st.LastSeen) > threshold
+}
+
+func mergeMetric(existing *MetricValue, incoming *MetricValue, source DataSource, now time.Time, status map[DataSource]SourceStatus) *MetricValue {
if incoming == nil {
return existing
}
@@ -3573,6 +3592,18 @@ func mergeMetric(existing *MetricValue, incoming *MetricValue, source DataSource
if existing == nil {
return &incomingCopy
}
+ // Freshness gates static source priority: a stale source must never hold a
+ // metric against a live one, and a live source overrides a stale one
+ // regardless of priority. Mirrors the presentation-coalesce rule so the
+ // "live source wins a metric" invariant holds in both metric-merge paths.
+ existingStale := metricSourceStale(now, status, existing.Source)
+ incomingStale := metricSourceStale(now, status, source)
+ if existingStale != incomingStale {
+ if existingStale {
+ return &incomingCopy
+ }
+ return existing
+ }
if sourcePriority(source) >= sourcePriority(existing.Source) {
return &incomingCopy
}
diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.go
index ab94287aca..7f7a186bcb 100644
--- a/internal/unifiedresources/registry_test.go
+++ b/internal/unifiedresources/registry_test.go
@@ -3999,3 +3999,51 @@ func TestRegistryIngestSnapshotPublishesDockerNativeInventory(t *testing.T) {
}
}
}
+
+// A live source must override a metric held by a stale higher-priority source.
+func TestMergeMetric_LiveSourceOverridesStaleHigherPriority(t *testing.T) {
+ now := time.Now().UTC()
+ status := map[DataSource]SourceStatus{
+ SourceAgent: {Status: "stale", LastSeen: now.Add(-2 * time.Hour)},
+ SourceProxmox: {Status: "online", LastSeen: now},
+ }
+ existing := &MetricValue{Value: 0, Percent: 0, Source: SourceAgent}
+ incoming := &MetricValue{Value: 6.2, Percent: 6.2, Source: SourceProxmox}
+
+ got := mergeMetric(existing, incoming, SourceProxmox, now, status)
+ if got == nil || got.Percent != 6.2 || got.Source != SourceProxmox {
+ t.Fatalf("expected live proxmox CPU to override stale agent CPU, got %+v", got)
+ }
+}
+
+// When both sources are fresh, static priority still decides: the agent wins.
+func TestMergeMetric_FreshHigherPriorityStillWins(t *testing.T) {
+ now := time.Now().UTC()
+ status := map[DataSource]SourceStatus{
+ SourceAgent: {Status: "online", LastSeen: now},
+ SourceProxmox: {Status: "online", LastSeen: now},
+ }
+ existing := &MetricValue{Percent: 6.2, Source: SourceProxmox}
+ incoming := &MetricValue{Percent: 12.5, Source: SourceAgent}
+
+ got := mergeMetric(existing, incoming, SourceAgent, now, status)
+ if got == nil || got.Percent != 12.5 || got.Source != SourceAgent {
+ t.Fatalf("expected fresh agent CPU to win by priority, got %+v", got)
+ }
+}
+
+// A stale source must not clobber a metric currently held by a live source.
+func TestMergeMetric_StaleSourceDoesNotClobberLive(t *testing.T) {
+ now := time.Now().UTC()
+ status := map[DataSource]SourceStatus{
+ SourceAgent: {Status: "stale", LastSeen: now.Add(-2 * time.Hour)},
+ SourceProxmox: {Status: "online", LastSeen: now},
+ }
+ existing := &MetricValue{Percent: 6.2, Source: SourceProxmox}
+ incoming := &MetricValue{Percent: 0, Source: SourceAgent}
+
+ got := mergeMetric(existing, incoming, SourceAgent, now, status)
+ if got == nil || got.Percent != 6.2 || got.Source != SourceProxmox {
+ t.Fatalf("expected live proxmox CPU to survive stale agent merge, got %+v", got)
+ }
+}