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.

Stop recording metrics for grace-period guests

rcourtman2f4e9957a558
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index c5423a709d..46910f9b59 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -734,6 +734,23 @@ must never prevent the remaining configured hosts from being suppressed.
coverage: `TestPoolTopologyStaysDiscriminatorAcrossVDevLayouts` in
`internal/truenas/provider_pool_health_contract_test.go`.
+12. Guest metric history records only guests the current poll actually
+ observed. A guest preserved while its node sits in the grace period
+ carries the `LastSeen` of the cycle that saw it, so every metric
+ recording loop gates on `guestObservedInCycle` before writing a
+ sample. Recording a carried-forward guest fabricates a reading: the
+ projection has no counters, so it writes CPU, disk and network zeroes
+ for a guest Pulse cannot currently see and the history shows a
+ collapse to zero rather than a gap. The guard fails open on an absent
+ `LastSeen`, because losing a real sample is the worse error and the
+ harder one to notice. Regression coverage:
+ `TestRecordGuestMetricsSkipsGracePeriodGuestsButKeepsObservedOnes` and
+ `TestGuestObservedInCycleFailsOpenWithoutEvidence` in
+ `internal/monitoring/monitor_additional_test.go`, and
+ `TestGracePeriodGuestContributesNoMemorySample` in
+ `internal/monitoring/memory_trust_characterization_test.go`.
+
+
## Current State
### PBS health is one completed-poll outcome
diff --git a/internal/monitoring/memory_trust_characterization_test.go b/internal/monitoring/memory_trust_characterization_test.go
index e3947e1c16..1d54a76657 100644
--- a/internal/monitoring/memory_trust_characterization_test.go
+++ b/internal/monitoring/memory_trust_characterization_test.go
@@ -1250,3 +1250,36 @@ func TestPollContainersWithNodesMemoryTrustCharacterization(t *testing.T) {
})
}
}
+
+// TestGracePeriodGuestContributesNoMemorySample extends the memory-trust
+// boundary to carried-forward guests. A guest preserved while its node sits in
+// the grace period has no fresh observation behind it, so recording one writes
+// a memory reading Pulse did not take. Before the cycle guard this was hidden
+// only by accident: the carried-forward projection leaves Memory without known
+// usage, so historyMemoryUsage returned the -1 sentinel rather than a
+// fabricated percentage. That is a coincidence of the projection, not a
+// guarantee, and it would break the moment preservation started carrying
+// memory forward.
+func TestGracePeriodGuestContributesNoMemorySample(t *testing.T) {
+ history := NewMetricsHistory(32, time.Hour)
+ monitor := &Monitor{metricsHistory: history}
+
+ cycleStart := time.Now().UTC()
+
+ monitor.recordGuestMetrics(
+ []models.VM{{
+ ID: "vm-grace",
+ Status: "running",
+ CPU: 0,
+ CPUs: 4,
+ LastSeen: cycleStart.Add(-2 * time.Minute),
+ Memory: models.Memory{Total: 8 << 30, Used: 4 << 30, Usage: 50},
+ }},
+ nil,
+ cycleStart,
+ )
+
+ if got := history.GetGuestMetrics("vm-grace", "memory", time.Hour); len(got) != 0 {
+ t.Fatalf("grace-period guest recorded %d memory sample(s): %+v", len(got), got)
+ }
+}
diff --git a/internal/monitoring/monitor_additional_test.go b/internal/monitoring/monitor_additional_test.go
index 2f1459b10f..dded09cf97 100644
--- a/internal/monitoring/monitor_additional_test.go
+++ b/internal/monitoring/monitor_additional_test.go
@@ -336,3 +336,71 @@ func TestBuildClusterEndpointsForInit_RespectsDiscoveryPolicy(t *testing.T) {
t.Fatalf("expected only the discovery-allowed member as failover, got %#v", endpoints)
}
}
+
+// TestGuestObservedInCycleFailsOpenWithoutEvidence pins the direction of the
+// guard. Dropping a legitimate sample is worse than recording a fabricated one,
+// so a guest with no LastSeen evidence is recorded rather than skipped.
+func TestGuestObservedInCycleFailsOpenWithoutEvidence(t *testing.T) {
+ cycleStart := time.Date(2026, 7, 24, 12, 0, 0, 0, time.UTC)
+
+ for _, tc := range []struct {
+ name string
+ lastSeen time.Time
+ want bool
+ }{
+ {name: "observed this cycle", lastSeen: cycleStart.Add(2 * time.Second), want: true},
+ {name: "observed exactly at cycle start", lastSeen: cycleStart, want: true},
+ {name: "carried forward from an earlier cycle", lastSeen: cycleStart.Add(-30 * time.Second), want: false},
+ {name: "no evidence either way", lastSeen: time.Time{}, want: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := guestObservedInCycle(tc.lastSeen, cycleStart); got != tc.want {
+ t.Fatalf("guestObservedInCycle(%v) = %v, want %v", tc.lastSeen, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestRecordGuestMetricsSkipsGracePeriodGuestsButKeepsObservedOnes is the
+// regression guard for the fabricated-zero defect. ac0fb263c made preserved
+// guests carry their real runtime status ("running") instead of the stringified
+// aggregate status ("online"), so they started passing recordGuestMetrics'
+// status filter. The carried-forward projection has no counters, so every cycle
+// a node spent in its grace period wrote CPU, disk and network zeroes into the
+// persistent store, showing a collapse to zero rather than a gap.
+//
+// Both directions matter: the observed guest must still be recorded, because
+// silently losing real samples would be a worse regression than the one being
+// fixed.
+func TestRecordGuestMetricsSkipsGracePeriodGuestsButKeepsObservedOnes(t *testing.T) {
+ history := NewMetricsHistory(32, time.Hour)
+ monitor := &Monitor{metricsHistory: history}
+
+ cycleStart := time.Now().UTC()
+ observedAt := cycleStart.Add(time.Second)
+ carriedForward := cycleStart.Add(-2 * time.Minute)
+
+ monitor.recordGuestMetrics(
+ []models.VM{
+ {ID: "vm-observed", Status: "running", CPU: 0.42, CPUs: 4, LastSeen: observedAt},
+ {ID: "vm-preserved", Status: "running", CPU: 0, CPUs: 4, LastSeen: carriedForward},
+ },
+ []models.Container{
+ {ID: "ct-observed", Status: "running", Type: "lxc", CPU: 0.25, CPUs: 1, LastSeen: observedAt},
+ {ID: "ct-preserved", Status: "running", Type: "lxc", CPU: 0, CPUs: 1, LastSeen: carriedForward},
+ },
+ cycleStart,
+ )
+
+ for _, id := range []string{"vm-observed", "ct-observed"} {
+ if got := history.GetGuestMetrics(id, "cpu", time.Hour); len(got) == 0 {
+ t.Fatalf("%s: observed guest lost its sample entirely", id)
+ }
+ }
+
+ for _, id := range []string{"vm-preserved", "ct-preserved"} {
+ if got := history.GetGuestMetrics(id, "cpu", time.Hour); len(got) != 0 {
+ t.Fatalf("%s: grace-period guest recorded %d fabricated sample(s): %+v", id, len(got), got)
+ }
+ }
+}
diff --git a/internal/monitoring/monitor_polling_containers.go b/internal/monitoring/monitor_polling_containers.go
index 19cb2047b0..a5fbe9c431 100644
--- a/internal/monitoring/monitor_polling_containers.go
+++ b/internal/monitoring/monitor_polling_containers.go
@@ -367,6 +367,9 @@ func (m *Monitor) collectContainersWithNodes(ctx context.Context, instanceName s
if !shouldSkipNativeMockStateMetricWrites() {
now := time.Now()
for _, ct := range allContainers {
+ if !guestObservedInCycle(ct.LastSeen, startTime) {
+ continue
+ }
if ct.Status != "running" {
continue
}
diff --git a/internal/monitoring/monitor_polling_vm.go b/internal/monitoring/monitor_polling_vm.go
index 12f2ba9b68..1df126cedf 100644
--- a/internal/monitoring/monitor_polling_vm.go
+++ b/internal/monitoring/monitor_polling_vm.go
@@ -123,6 +123,9 @@ func (m *Monitor) collectVMsWithNodes(ctx context.Context, instanceName string,
if !shouldSkipNativeMockStateMetricWrites() {
now := time.Now()
for _, vm := range allVMs {
+ if !guestObservedInCycle(vm.LastSeen, startTime) {
+ continue
+ }
if vm.Status != "running" {
continue
}
diff --git a/internal/monitoring/monitor_pve_guest_cpu_authority_test.go b/internal/monitoring/monitor_pve_guest_cpu_authority_test.go
index 589f44bda9..5bcfd84f05 100644
--- a/internal/monitoring/monitor_pve_guest_cpu_authority_test.go
+++ b/internal/monitoring/monitor_pve_guest_cpu_authority_test.go
@@ -35,6 +35,7 @@ func TestRecordGuestMetricsKeepsLiveAndHistoricalProxmoxCPUUnitsAligned(t *testi
metricsHistory: history,
metricsStore: store,
}
+ cycleStart := time.Now().UTC().Add(-time.Second)
monitor.recordGuestMetrics(
[]models.VM{{
ID: "cluster-a-node-1-301",
@@ -51,6 +52,7 @@ func TestRecordGuestMetricsKeepsLiveAndHistoricalProxmoxCPUUnitsAligned(t *testi
CPUs: 1,
LastSeen: time.Now().UTC(),
}},
+ cycleStart,
)
store.Flush()
diff --git a/internal/monitoring/monitor_pve_guest_helpers.go b/internal/monitoring/monitor_pve_guest_helpers.go
index 47fdc9ec2e..19da63dba8 100644
--- a/internal/monitoring/monitor_pve_guest_helpers.go
+++ b/internal/monitoring/monitor_pve_guest_helpers.go
@@ -105,16 +105,42 @@ func (m *Monitor) preserveGuestsForGracePeriod(
return allVMs, allContainers
}
-// recordGuestMetrics records metrics for all running VMs and containers.
-func (m *Monitor) recordGuestMetrics(allVMs []models.VM, allContainers []models.Container) {
+// guestObservedInCycle reports whether a guest's telemetry came from this poll
+// rather than being carried forward while its node sits in the grace period.
+//
+// Preserved guests keep the LastSeen of the cycle that actually observed them,
+// so anything older than this cycle's start was not observed. Recording one as
+// a sample fabricates a reading: the carried-forward projection has no counters,
+// so it writes CPU, disk and network zeroes for a guest Pulse cannot currently
+// see, and the history shows a collapse to zero instead of a gap.
+//
+// A zero LastSeen means we have no evidence either way, so this fails open and
+// records. Dropping a legitimate sample is the worse error of the two, and
+// harder to notice.
+func guestObservedInCycle(lastSeen, cycleStart time.Time) bool {
+ if lastSeen.IsZero() {
+ return true
+ }
+ return !lastSeen.Before(cycleStart)
+}
+
+// recordGuestMetrics records metrics for all running VMs and containers that
+// this cycle actually observed.
+func (m *Monitor) recordGuestMetrics(allVMs []models.VM, allContainers []models.Container, cycleStart time.Time) {
now := time.Now()
for _, vm := range allVMs {
+ if !guestObservedInCycle(vm.LastSeen, cycleStart) {
+ continue
+ }
if vm.Status == "running" {
diskRead, diskWrite, networkIn, networkOut := guestHistoryRates(vm.DiskRead, vm.DiskWrite, vm.NetworkIn, vm.NetworkOut, vm.IORateValidity)
m.recordGuestMetric("vm", vm.ID, unifiedresources.ProxmoxGuestCPUPercent(vm.CPU), historyMemoryUsage(vm.Memory), vm.Disk.Usage, diskRead, diskWrite, networkIn, networkOut, now)
}
}
for _, ct := range allContainers {
+ if !guestObservedInCycle(ct.LastSeen, cycleStart) {
+ continue
+ }
if ct.Status == "running" {
diskRead, diskWrite, networkIn, networkOut := guestHistoryRates(ct.DiskRead, ct.DiskWrite, ct.NetworkIn, ct.NetworkOut, ct.IORateValidity)
m.recordGuestMetric("container", ct.ID, unifiedresources.ProxmoxGuestCPUPercent(ct.CPU), historyMemoryUsage(ct.Memory), ct.Disk.Usage, diskRead, diskWrite, networkIn, networkOut, now)
diff --git a/internal/monitoring/monitor_pve_guest_poll.go b/internal/monitoring/monitor_pve_guest_poll.go
index cd9cae89f8..fcc97e2cf1 100644
--- a/internal/monitoring/monitor_pve_guest_poll.go
+++ b/internal/monitoring/monitor_pve_guest_poll.go
@@ -3,6 +3,7 @@ package monitoring
import (
"context"
"sync"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
@@ -21,6 +22,7 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
Msg("Polling VMs and containers using efficient cluster/resources endpoint")
// Get all resources in a single API call
+ cycleStart := time.Now()
resources, err := client.GetClusterResources(ctx, "vm")
if err != nil {
log.Debug().Err(err).Str("instance", instanceName).Msg("cluster/resources not available, falling back to traditional polling")
@@ -53,7 +55,7 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
// remove genuinely deleted guests.
m.state.UpdateGuestsForInstance(instanceName, allVMs, allContainers)
- m.recordGuestMetrics(allVMs, allContainers)
+ m.recordGuestMetrics(allVMs, allContainers, cycleStart)
m.pollReplicationStatus(ctx, instanceName, client, allVMs)