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.

perf(metrics): stream downsampled batch aggregation

Richard Courtman257dd55f12d8
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 fc0a9c20f7..29e0f07212 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -192,6 +192,14 @@ The dashboard workload selector path and the dashboard runtime that consumes it
are now part of the protected performance surface rather than proof-only
context. Future hot-path filter/group/sort/windowing changes must route through
the explicit dashboard performance proof policy in the subsystem registry.
+The downsampled `pkg/metrics/store.go` `QueryAllBatch` hot path is also a
+protected surface. Its contract is ordered timestamps and correct avg/min/max
+bucket aggregates within each `resource_id + metric_type` series, but the
+runtime must meet its SLO through one ordered index scan plus Go-side bucket
+aggregation rather than forcing SQLite to `GROUP BY` computed buckets through a
+temp B-tree on the fleet-scale dashboard path. `pkg/metrics/store_test.go` and
+`pkg/metrics/store_slo_test.go` now guard both the aggregate contract and the
+tail-latency budget for that ownership boundary.
That workload route now also treats readiness as a route-owned contract instead
of a raw websocket proxy signal: `frontend-modern/src/components/Dashboard/Dashboard.tsx`
and `frontend-modern/src/components/Dashboard/useDashboardState.ts` must keep
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index c391664d6d..ead9284d8f 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -8,7 +8,6 @@ import (
"net/url"
"os"
"path/filepath"
- "sort"
"strconv"
"strings"
"sync"
@@ -872,8 +871,8 @@ func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string,
var sqlQuery string
if stepSecs > 1 {
- params = make([]interface{}, 0, len(resourceIDs)+7)
- params = append(params, stepSecs, stepSecs, stepSecs, resourceType)
+ params = make([]interface{}, 0, len(resourceIDs)+4)
+ params = append(params, resourceType)
for _, id := range resourceIDs {
params = append(params, id)
}
@@ -883,14 +882,14 @@ func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string,
SELECT
resource_id,
metric_type,
- (timestamp / ?) * ? + (? / 2) as bucket_ts,
- AVG(value),
- MIN(COALESCE(min_value, value)),
- MAX(COALESCE(max_value, value))
+ timestamp,
+ value,
+ COALESCE(min_value, value),
+ COALESCE(max_value, value)
FROM metrics
WHERE resource_type = ? AND resource_id IN (%s) AND tier = ?
AND timestamp >= ? AND timestamp <= ?
- GROUP BY resource_id, metric_type, bucket_ts
+ ORDER BY resource_id, metric_type, timestamp ASC
`, inClause)
} else {
params = make([]interface{}, 0, len(resourceIDs)+4)
@@ -927,6 +926,98 @@ func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string,
result := make(map[string]map[string][]MetricPoint, len(resourceIDs))
seriesCapacity := estimateQueryAllBatchSeriesCapacity(start, end, stepSecs)
+ if stepSecs > 1 {
+ type bucketAggregate struct {
+ active bool
+ resourceID string
+ metricType string
+ bucketStart int64
+ sum float64
+ min float64
+ max float64
+ count int
+ }
+
+ appendBucketPoint := func(resourceID, metricType string, point MetricPoint) {
+ if _, exists := result[resourceID]; !exists {
+ result[resourceID] = make(map[string][]MetricPoint, 8)
+ }
+ if _, exists := result[resourceID][metricType]; !exists {
+ result[resourceID][metricType] = make([]MetricPoint, 0, seriesCapacity)
+ }
+ result[resourceID][metricType] = append(result[resourceID][metricType], point)
+ }
+
+ var aggregate bucketAggregate
+ flushAggregate := func() {
+ if !aggregate.active || aggregate.count == 0 {
+ return
+ }
+ appendBucketPoint(aggregate.resourceID, aggregate.metricType, MetricPoint{
+ Timestamp: time.Unix(aggregate.bucketStart+(stepSecs/2), 0),
+ Value: aggregate.sum / float64(aggregate.count),
+ Min: aggregate.min,
+ Max: aggregate.max,
+ })
+ aggregate = bucketAggregate{}
+ }
+
+ for rows.Next() {
+ var resourceID, metricType string
+ var ts int64
+ var value, minVal, maxVal float64
+ if err := rows.Scan(&resourceID, &metricType, &ts, &value, &minVal, &maxVal); err != nil {
+ log.Warn().Err(err).Msg("Failed to scan batch metric row")
+ continue
+ }
+
+ bucketStart := (ts / stepSecs) * stepSecs
+ if !aggregate.active {
+ aggregate = bucketAggregate{
+ active: true,
+ resourceID: resourceID,
+ metricType: metricType,
+ bucketStart: bucketStart,
+ sum: value,
+ min: minVal,
+ max: maxVal,
+ count: 1,
+ }
+ continue
+ }
+
+ if aggregate.resourceID != resourceID || aggregate.metricType != metricType || aggregate.bucketStart != bucketStart {
+ flushAggregate()
+ aggregate = bucketAggregate{
+ active: true,
+ resourceID: resourceID,
+ metricType: metricType,
+ bucketStart: bucketStart,
+ sum: value,
+ min: minVal,
+ max: maxVal,
+ count: 1,
+ }
+ continue
+ }
+
+ aggregate.sum += value
+ if minVal < aggregate.min {
+ aggregate.min = minVal
+ }
+ if maxVal > aggregate.max {
+ aggregate.max = maxVal
+ }
+ aggregate.count++
+ }
+
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ flushAggregate()
+ return result, nil
+ }
+
for rows.Next() {
var resourceID, metricType string
var ts int64
@@ -949,9 +1040,6 @@ func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string,
if err := rows.Err(); err != nil {
return nil, err
}
- if stepSecs > 1 {
- sortMetricSeriesPoints(result)
- }
return result, nil
}
@@ -972,20 +1060,6 @@ func estimateQueryAllBatchSeriesCapacity(start, end time.Time, stepSecs int64) i
return buckets
}
-func sortMetricSeriesPoints(result map[string]map[string][]MetricPoint) {
- for _, metricMap := range result {
- for metricType, points := range metricMap {
- if len(points) < 2 {
- continue
- }
- sort.Slice(points, func(i, j int) bool {
- return points[i].Timestamp.Before(points[j].Timestamp)
- })
- metricMap[metricType] = points
- }
- }
-}
-
// selectTier chooses the appropriate data tier based on time range
// Note: Tier selection uses fixed thresholds to ensure queries use tiers with complete data:
// - Raw: up to 2 hours (high-resolution real-time data)
diff --git a/pkg/metrics/store_slo_test.go b/pkg/metrics/store_slo_test.go
index 9f4fa509bc..1a2f60434c 100644
--- a/pkg/metrics/store_slo_test.go
+++ b/pkg/metrics/store_slo_test.go
@@ -404,11 +404,12 @@ func TestSLO_QueryAllBatch(t *testing.T) {
}
}
-// TestSLO_QueryAllBatchDownsampled validates the grouped QueryAllBatch path
-// used for longer-range dashboard windows where bucketed SQL is required.
+// TestSLO_QueryAllBatchDownsampled validates the downsampled QueryAllBatch path
+// used for longer-range dashboard windows.
// The API contract is ordered timestamps within each resource/metric series,
-// but the hot path must meet its SLO without relying on an extra global SQL
-// sort across the entire grouped result set.
+// but the hot path now owns bucket aggregation through one ordered scan plus
+// Go-side accumulation instead of forcing SQLite to GROUP BY computed buckets
+// across the whole result set.
func TestSLO_QueryAllBatchDownsampled(t *testing.T) {
skipUnderRace(t)
suppressTestLogs(t)
diff --git a/pkg/metrics/store_test.go b/pkg/metrics/store_test.go
index b3356b860e..ac3934cfac 100644
--- a/pkg/metrics/store_test.go
+++ b/pkg/metrics/store_test.go
@@ -598,6 +598,59 @@ func TestQueryAllBatch(t *testing.T) {
}
})
+ t.Run("downsampled results preserve bucket aggregates", func(t *testing.T) {
+ downsampledStoreDir := t.TempDir()
+ downsampledCfg := DefaultConfig(downsampledStoreDir)
+ downsampledCfg.DBPath = filepath.Join(downsampledStoreDir, "metrics-batch-downsampled-aggregates.db")
+ downsampledCfg.FlushInterval = time.Hour
+
+ downsampledStore, err := NewStore(downsampledCfg)
+ if err != nil {
+ t.Fatalf("NewStore(downsampled aggregates): %v", err)
+ }
+ defer downsampledStore.Close()
+
+ base := time.Unix(20_000, 0)
+ downsampledStore.writeBatch([]bufferedMetric{
+ {resourceType: "disk", resourceID: "disk-agg", metricType: "smart_temp", value: 10, timestamp: base.Add(5 * time.Second), tier: TierRaw},
+ {resourceType: "disk", resourceID: "disk-agg", metricType: "smart_temp", value: 16, timestamp: base.Add(25 * time.Second), tier: TierRaw},
+ {resourceType: "disk", resourceID: "disk-agg", metricType: "smart_temp", value: 22, timestamp: base.Add(65 * time.Second), tier: TierRaw},
+ {resourceType: "disk", resourceID: "disk-agg", metricType: "smart_temp", value: 28, timestamp: base.Add(95 * time.Second), tier: TierRaw},
+ })
+
+ batch, err := downsampledStore.QueryAllBatch("disk", []string{"disk-agg"}, base, base.Add(2*time.Minute), 60)
+ if err != nil {
+ t.Fatalf("QueryAllBatch(downsampled aggregates): %v", err)
+ }
+
+ points := batch["disk-agg"]["smart_temp"]
+ if len(points) != 2 {
+ t.Fatalf("expected 2 bucketed points, got %d", len(points))
+ }
+
+ firstBucketCenter := time.Unix(((base.Add(5*time.Second).Unix()/60)*60)+(60/2), 0)
+ if points[0].Timestamp != firstBucketCenter {
+ t.Fatalf("first bucket timestamp = %v, want %v", points[0].Timestamp, firstBucketCenter)
+ }
+ if points[0].Value != 13 {
+ t.Fatalf("first bucket avg = %v, want 13", points[0].Value)
+ }
+ if points[0].Min != 10 || points[0].Max != 16 {
+ t.Fatalf("first bucket min/max = %v/%v, want 10/16", points[0].Min, points[0].Max)
+ }
+
+ secondBucketCenter := time.Unix(((base.Add(65*time.Second).Unix()/60)*60)+(60/2), 0)
+ if points[1].Timestamp != secondBucketCenter {
+ t.Fatalf("second bucket timestamp = %v, want %v", points[1].Timestamp, secondBucketCenter)
+ }
+ if points[1].Value != 25 {
+ t.Fatalf("second bucket avg = %v, want 25", points[1].Value)
+ }
+ if points[1].Min != 22 || points[1].Max != 28 {
+ t.Fatalf("second bucket min/max = %v/%v, want 22/28", points[1].Min, points[1].Max)
+ }
+ })
+
t.Run("chunked resource lists return complete results beyond sqlite parameter threshold", func(t *testing.T) {
chunkedStoreDir := t.TempDir()
chunkedCfg := DefaultConfig(chunkedStoreDir)