Keep History reads and writes moving during expiry logging (#5403)

**Keep History reads and writes moving during expiry logging**

Capture cleanup counts under the History mutex and write the diagnostic
after unlocking so an independent sample and chart read can finish while
the sink is blocked.

**Make the History logging regression fail promptly on a held lock**

Use a nonblocking check before exercising actual chart reads and writes
while cleanup logging is gated.

---
Fleet candidate `20261128T134519Z-core-runtime` from the `core-runtime`
lane. Reviewed tip `3c7fb97150785e1ec66368aa5bbeb62132b09316` on `main`.

[How Pulse handles
triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
pulse-triage[bot]
2026-11-28 15:53:39 +00:00
committed by GitHub
3 changed files with 98 additions and 13 deletions
@@ -263,6 +263,17 @@ The affected poll still reports the same grace-adjusted status and does not
move its last-online timestamp.
These fixtures do not establish an installed outage's cause or recovery.
### History expiry diagnostics do not own the metrics lock
The in-memory History sweep finishes expiry and snapshots its removed and
remaining counts under the History lock, then releases it before debug output.
A blocked diagnostic may still delay the calling maintenance tick; it must not
prevent independent poll writers from adding samples or charts from reading
them. Retention and chart selection are unchanged.
`TestMetricsHistoryCleanupLoggingDoesNotBlockHistory` gates the cleanup log
after an expired guest is dropped and verifies a live node's retained and newly
written CPU points are readable before the sink returns.
### Idle poll workers wake when work becomes eligible sooner
An empty active queue has no idle recheck timer. If its head is in the
+19 -13
View File
@@ -969,7 +969,6 @@ func (mh *MetricsHistory) GetDiskMetrics(resourceID string, metricType string, d
// This prevents unbounded memory growth when containers/VMs are deleted.
func (mh *MetricsHistory) Cleanup() {
mh.mu.Lock()
defer mh.mu.Unlock()
cutoffTime := time.Now().Add(-mh.retentionTime)
var guestsRemoved, nodesRemoved, storageRemoved, disksRemoved int
@@ -1046,19 +1045,26 @@ func (mh *MetricsHistory) Cleanup() {
}
}
// Log cleanup activity at debug level
if guestsRemoved > 0 || nodesRemoved > 0 || storageRemoved > 0 || disksRemoved > 0 {
log.Debug().
Int("guestsRemoved", guestsRemoved).
Int("nodesRemoved", nodesRemoved).
Int("storageRemoved", storageRemoved).
Int("disksRemoved", disksRemoved).
Int("guestsRemaining", len(mh.guestMetrics)).
Int("nodesRemaining", len(mh.nodeMetrics)).
Int("storageRemaining", len(mh.storageMetrics)).
Int("disksRemaining", len(mh.diskMetrics)).
Msg("Cleaned up stale metrics history entries")
if guestsRemoved == 0 && nodesRemoved == 0 && storageRemoved == 0 && disksRemoved == 0 {
mh.mu.Unlock()
return
}
// Report counts from the completed sweep, without making chart readers
// or poll writers wait for a slow diagnostic sink.
guestsRemaining, nodesRemaining := len(mh.guestMetrics), len(mh.nodeMetrics)
storageRemaining, disksRemaining := len(mh.storageMetrics), len(mh.diskMetrics)
mh.mu.Unlock()
log.Debug().
Int("guestsRemoved", guestsRemoved).
Int("nodesRemoved", nodesRemoved).
Int("storageRemoved", storageRemoved).
Int("disksRemoved", disksRemoved).
Int("guestsRemaining", guestsRemaining).
Int("nodesRemaining", nodesRemaining).
Int("storageRemaining", storageRemaining).
Int("disksRemaining", disksRemaining).
Msg("Cleaned up stale metrics history entries")
}
// cleanupMetrics removes points older than cutoff time.
@@ -4,7 +4,11 @@ import (
"math/rand"
"sync"
"testing"
"testing/synctest"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func TestMetricsHistoryConcurrentAccess(t *testing.T) {
@@ -75,4 +79,68 @@ func TestMetricsHistoryConcurrentAccess(t *testing.T) {
}
}
func TestMetricsHistoryCleanupLoggingDoesNotBlockHistory(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
now := time.Now()
history := NewMetricsHistory(1000, time.Hour)
// Insert via the real writer while the point is fresh, then age it
// out. An unrelated node still has recent CPU readings.
history.AddGuestMetric("expired", "cpu", 1, now)
time.Sleep(2 * time.Hour)
history.AddNodeMetric("live", "cpu", 7, time.Now())
time.Sleep(time.Minute)
// The package logger is shared. Do not run in parallel, and wait
// for all work to exit before restoring it.
saved, level := log.Logger, zerolog.GlobalLevel()
sink := blockedCacheExpiryLog{
message: "Cleaned up stale metrics history entries",
entered: make(chan struct{}),
resume: make(chan struct{}),
}
log.Logger = zerolog.New(sink).Level(zerolog.DebugLevel)
zerolog.SetGlobalLevel(zerolog.DebugLevel)
done := make(chan struct{})
go func() {
defer close(done)
history.Cleanup()
}()
defer func() {
close(sink.resume)
<-done
synctest.Wait()
log.Logger = saved
zerolog.SetGlobalLevel(level)
}()
synctest.Wait()
select {
case <-sink.entered:
default:
t.Fatal("cleanup did not emit the expiry diagnostic")
}
// Trying the lock first also makes the adverse case fail without
// leaving the reader or writer stuck behind the gated logger.
if !history.mu.TryLock() {
t.Fatal("expiry diagnostic still owns the History lock needed by poll writers and chart readers")
}
_, retained := history.guestMetrics["expired"]
history.mu.Unlock()
if retained {
t.Error("expired entry was still present when its removal was logged")
}
m := &Monitor{metricsHistory: history}
before := m.GetNodeMetricsForChart("live", "cpu", time.Hour)
if len(before) != 1 || before[0].Value != 7 {
t.Error("chart could not read the retained point while cleanup was logging")
}
history.AddNodeMetric("live", "cpu", 42, time.Now())
after := m.GetNodeMetricsForChart("live", "cpu", time.Hour)
if len(after) != 2 || after[0].Value != 7 || after[1].Value != 42 {
t.Error("node sample write and chart read did not finish while cleanup was logging")
}
})
}
// rand is automatically seeded in Go 1.20+