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.

Bound metrics rollup working set

rcourtman760eb32aaf63
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index af031f8c37..3611132f1e 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -1051,17 +1051,21 @@ resource type, resource id, metric type, timestamp, and tier must be treated as
idempotent writes against the metrics table's unique key rather than as noisy
SQLite constraint failures; for raw writes, the latest buffered value wins and
aggregate-only min/max columns stay unset. Rollups must not be hard-coded to a
-5-minute disk-write cadence: the default cadence should favor fewer, larger
-rollup transactions, remain bounded by raw retention so data is aggregated
-before pruning, and stay overrideable for operators who deliberately trade
-freshness for lower write frequency. The runtime must also allow an explicit
+5-minute disk-write cadence: the default cadence should favor set-based
+transactions, remain bounded by raw retention so data is aggregated before
+pruning, and stay overrideable for operators who deliberately trade freshness
+for lower write frequency. Rollup transactions must also keep a bounded
+time-window working set and resume from checkpoints across invocations instead
+of aggregating every pending series and bucket in one global SQLite GROUP BY
+that can spike RSS on agent-heavy installs. The runtime must also allow an explicit
metrics database path so SSD-sensitive Docker/LXC installs can place only the
metrics SQLite store on tmpfs while keeping secrets and general configuration on
durable storage. Any future change that reduces that batching headroom, makes
-WAL checkpoints more aggressive again, reopens duplicate-write failures, or
-removes the metrics DB path/cadence controls must re-prove the metrics-store
-hot path with the owned store tests rather than assuming the earlier vacuum
-fixes are sufficient. Retention must also return freed SQLite pages to the OS
+WAL checkpoints more aggressive again, reopens duplicate-write failures,
+removes the bounded rollup-window checkpointing, or removes the metrics DB
+path/cadence controls must re-prove the metrics-store hot path with the owned
+store tests rather than assuming the earlier vacuum fixes are sufficient.
+Retention must also return freed SQLite pages to the OS
proportionally to the current freelist, bounded per cycle, and on every
retention cycle rather than only when that cycle deleted rows: a fixed small
incremental-vacuum batch lets the freelist outpace reclaim on busy instances,
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index 86bf29573a..9ec4540bc1 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -60,6 +60,8 @@ type StoreConfig struct {
const (
minRollupInterval = 5 * time.Minute
defaultRollupInterval = 15 * time.Minute
+ maxRollupChunkWindow = 5 * time.Minute
+ maxRollupChunksPerRun = 128
)
// DefaultConfig returns sensible defaults for metrics storage
@@ -1577,29 +1579,100 @@ func (s *Store) rollupTier(fromTier, toTier Tier, bucketSize, minAge time.Durati
return
}
- // Fast check: skip rollup and preserve the checkpoint if the source tier
- // has no data in this window. This matches the old per-candidate path's
- // len(candidates)==0 early return, preventing the checkpoint from advancing
- // past windows where late or backfilled data may arrive later.
- var hasSource bool
- if err := s.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM metrics WHERE tier = ? AND timestamp >= ? AND timestamp < ?)`,
- string(fromTier), lastBucket, cutoffBucket).Scan(&hasSource); err != nil {
- log.Warn().Err(err).Str("tier", string(fromTier)).Msg("Failed to check rollup source data")
- return
+ chunkWindow := rollupChunkWindow(bucketSize)
+ chunkSecs := int64(chunkWindow.Seconds())
+ if chunkSecs <= 0 {
+ chunkSecs = bucketSecs
}
- if !hasSource {
- return
+
+ windowStart := lastBucket
+ processedChunks := 0
+ processedAny := false
+
+ for windowStart < cutoffBucket {
+ nextBucket, hasSource := s.nextSourceRollupBucket(fromTier, windowStart, cutoffBucket, bucketSecs)
+ if !hasSource {
+ if processedAny {
+ if err := s.setMetaInt(metaKey, cutoffBucket); err != nil {
+ log.Warn().Err(err).Str("tier", string(fromTier)).Msg("Failed to persist rollup checkpoint")
+ }
+ }
+ return
+ }
+
+ if nextBucket > windowStart {
+ windowStart = nextBucket
+ }
+ windowEnd := windowStart + chunkSecs
+ if windowEnd > cutoffBucket {
+ windowEnd = cutoffBucket
+ }
+ if windowEnd <= windowStart {
+ return
+ }
+
+ if !s.rollupTierWindow(fromTier, toTier, bucketSecs, windowStart, windowEnd) {
+ return
+ }
+
+ windowStart = windowEnd
+ processedChunks++
+ processedAny = true
+
+ if err := s.setMetaInt(metaKey, windowStart); err != nil {
+ log.Warn().Err(err).Str("tier", string(fromTier)).Msg("Failed to persist rollup checkpoint")
+ return
+ }
+ if processedChunks >= maxRollupChunksPerRun && windowStart < cutoffBucket {
+ log.Debug().
+ Str("from", string(fromTier)).
+ Str("to", string(toTier)).
+ Int("chunks", processedChunks).
+ Msg("Metrics rollup paused after bounded chunk budget")
+ return
+ }
}
+}
- // Batch rollup: aggregate ALL resource/metric combinations in a single
- // SQL statement. The GROUP BY naturally partitions results by
- // (resource_type, resource_id, metric_type, bucket_ts), producing the
- // same output as the previous per-candidate loop but in one query and
- // one transaction instead of N+1.
+func rollupChunkWindow(bucketSize time.Duration) time.Duration {
+ if bucketSize <= 0 {
+ return maxRollupChunkWindow
+ }
+ if bucketSize >= maxRollupChunkWindow {
+ return bucketSize
+ }
+ buckets := int64(maxRollupChunkWindow / bucketSize)
+ if buckets < 1 {
+ buckets = 1
+ }
+ return time.Duration(buckets) * bucketSize
+}
+
+func (s *Store) nextSourceRollupBucket(tier Tier, startBucket, cutoffBucket, bucketSecs int64) (int64, bool) {
+ var next sql.NullInt64
+ if err := s.db.QueryRow(`
+ SELECT MIN(timestamp)
+ FROM metrics
+ WHERE tier = ? AND timestamp >= ? AND timestamp < ?
+ `, string(tier), startBucket, cutoffBucket).Scan(&next); err != nil {
+ log.Warn().Err(err).Str("tier", string(tier)).Msg("Failed to locate next rollup source window")
+ return 0, false
+ }
+ if !next.Valid {
+ return 0, false
+ }
+ nextBucket := (next.Int64 / bucketSecs) * bucketSecs
+ if nextBucket < startBucket {
+ nextBucket = startBucket
+ }
+ return nextBucket, true
+}
+
+func (s *Store) rollupTierWindow(fromTier, toTier Tier, bucketSecs, startTs, endTs int64) bool {
tx, err := s.db.Begin()
if err != nil {
log.Error().Err(err).Str("tier", string(fromTier)).Msg("Failed to begin rollup transaction")
- return
+ return false
}
defer func() { _ = tx.Rollback() }()
@@ -1617,13 +1690,13 @@ func (s *Store) rollupTier(fromTier, toTier Tier, bucketSize, minAge time.Durati
FROM metrics
WHERE tier = ? AND timestamp >= ? AND timestamp < ?
GROUP BY resource_type, resource_id, metric_type, bucket_ts
- `, bucketSecs, bucketSecs, string(toTier), string(fromTier), lastBucket, cutoffBucket)
+ `, bucketSecs, bucketSecs, string(toTier), string(fromTier), startTs, endTs)
if err != nil {
log.Warn().Err(err).
Str("from", string(fromTier)).
Str("to", string(toTier)).
Msg("Failed to batch rollup metrics")
- return
+ return false
}
if err := tx.Commit(); err != nil {
@@ -1631,12 +1704,9 @@ func (s *Store) rollupTier(fromTier, toTier Tier, bucketSize, minAge time.Durati
Str("from", string(fromTier)).
Str("to", string(toTier)).
Msg("Failed to commit rollup transaction")
- return
- }
-
- if err := s.setMetaInt(metaKey, cutoffBucket); err != nil {
- log.Warn().Err(err).Str("tier", string(fromTier)).Msg("Failed to persist rollup checkpoint")
+ return false
}
+ return true
}
// rollupCandidate aggregates a single resource/metric from one tier to another
diff --git a/pkg/metrics/store_loadtest_test.go b/pkg/metrics/store_loadtest_test.go
index 6982e742ba..70fac418ef 100644
--- a/pkg/metrics/store_loadtest_test.go
+++ b/pkg/metrics/store_loadtest_test.go
@@ -296,7 +296,7 @@ func BenchmarkLoadTest500Nodes_RollupAtScale(b *testing.B) {
// BenchmarkLoadTest500Nodes_RollupTierBatched measures the production batched
// rollupTier path at 500-node scale. This is the real aggregation path used in
-// the store: one INSERT...SELECT...GROUP BY across all node/metric series.
+// the store: bounded INSERT...SELECT...GROUP BY chunks across node/metric series.
func BenchmarkLoadTest500Nodes_RollupTierBatched(b *testing.B) {
suppressLogs(b)
store := newBenchStore(b)
diff --git a/pkg/metrics/store_slo_test.go b/pkg/metrics/store_slo_test.go
index 262c8868ff..e40abbf6de 100644
--- a/pkg/metrics/store_slo_test.go
+++ b/pkg/metrics/store_slo_test.go
@@ -624,7 +624,7 @@ func TestSLO_QueryManyResources(t *testing.T) {
}
// TestSLO_RollupTierBatched validates the production rollupTier path that
-// aggregates all resource/metric combinations in a single SQL statement.
+// aggregates resource/metric combinations with bounded grouped SQL statements.
func TestSLO_RollupTierBatched(t *testing.T) {
skipUnderRace(t)
suppressTestLogs(t)
@@ -767,8 +767,8 @@ func TestSLO_ConcurrentReadWrite(t *testing.T) {
}
// TestSLO_RollupTierBatchedFleet validates the production batched rollupTier
-// path at 500-node scale, where all node/metric series are aggregated in a
-// single grouped SQL statement.
+// path at 500-node scale, where node/metric series are aggregated through the
+// bounded grouped SQL path.
func TestSLO_RollupTierBatchedFleet(t *testing.T) {
skipUnderRace(t)
suppressTestLogs(t)
diff --git a/pkg/metrics/store_test.go b/pkg/metrics/store_test.go
index 775d08476c..716f9e2903 100644
--- a/pkg/metrics/store_test.go
+++ b/pkg/metrics/store_test.go
@@ -275,6 +275,64 @@ func TestStoreRollupTierMultiResource(t *testing.T) {
}
}
+func TestStoreRollupTierUsesBoundedChunkBudget(t *testing.T) {
+ dir := t.TempDir()
+ cfg := DefaultConfig(dir)
+ cfg.DBPath = filepath.Join(dir, "metrics-rollup-chunks.db")
+ cfg.FlushInterval = time.Hour
+
+ store, err := NewStore(cfg)
+ if err != nil {
+ t.Fatalf("NewStore returned error: %v", err)
+ }
+ defer store.Close()
+
+ chunkWindow := rollupChunkWindow(time.Minute)
+ base := time.Now().UTC().Add(-24 * time.Hour).Truncate(time.Minute)
+ batch := make([]WriteMetric, 0, maxRollupChunksPerRun+1)
+ for i := 0; i <= maxRollupChunksPerRun; i++ {
+ batch = append(batch, WriteMetric{
+ ResourceType: "vm",
+ ResourceID: fmt.Sprintf("vm-%d", i),
+ MetricType: "cpu",
+ Value: float64(i),
+ Timestamp: base.Add(time.Duration(i) * chunkWindow),
+ Tier: TierRaw,
+ })
+ }
+ store.WriteBatchSync(batch)
+
+ metaKey := "rollup:raw:minute"
+ store.rollupTier(TierRaw, TierMinute, time.Minute, 0)
+
+ var firstCount int
+ if err := store.db.QueryRow(`SELECT COUNT(*) FROM metrics WHERE tier = ?`, string(TierMinute)).Scan(&firstCount); err != nil {
+ t.Fatalf("count first rollup: %v", err)
+ }
+ if firstCount != maxRollupChunksPerRun {
+ t.Fatalf("first rollup should stop at chunk budget: got %d rows, want %d", firstCount, maxRollupChunksPerRun)
+ }
+
+ firstCheckpoint, ok := store.getMetaInt(metaKey)
+ if !ok {
+ t.Fatalf("expected checkpoint after bounded rollup")
+ }
+ wantCheckpoint := base.Add(time.Duration(maxRollupChunksPerRun) * chunkWindow).Unix()
+ if firstCheckpoint != wantCheckpoint {
+ t.Fatalf("checkpoint = %d, want %d", firstCheckpoint, wantCheckpoint)
+ }
+
+ store.rollupTier(TierRaw, TierMinute, time.Minute, 0)
+
+ var finalCount int
+ if err := store.db.QueryRow(`SELECT COUNT(*) FROM metrics WHERE tier = ?`, string(TierMinute)).Scan(&finalCount); err != nil {
+ t.Fatalf("count final rollup: %v", err)
+ }
+ if finalCount != maxRollupChunksPerRun+1 {
+ t.Fatalf("second rollup should resume remaining source rows: got %d rows, want %d", finalCount, maxRollupChunksPerRun+1)
+ }
+}
+
// TestStoreRollupTierEmptyWindowPreservesCheckpoint verifies that rollupTier
// does not advance the checkpoint when no source rows exist in the rollup
// window. This ensures late or backfilled samples are still rolled up when