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): reduce downsampled batch query tail latency

Richard Courtmandbd470398a15
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 2a257177dc..fc0a9c20f7 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -508,3 +508,9 @@ identifiers and metric names passed back into `Query`, `QueryAll`, and
case-polluted callers cannot manufacture false "missing metrics" results,
split one governed metric stream into mixed-case query buckets, or trigger
redundant batch work against otherwise valid stored samples.
+The downsampled `QueryAllBatch` path is a protected metrics-store hot path.
+When callers request grouped batch data, the contract is ordered timestamps
+within each `resource_id + metric_type` series, not a globally SQL-sorted row
+stream. The store must preserve that per-series ordering without paying for an
+extra SQLite global sort on the grouped query path, and regressions on that
+tail-latency boundary must be caught by `pkg/metrics/store_slo_test.go`.
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index 0811357784..c391664d6d 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -8,6 +8,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "sort"
"strconv"
"strings"
"sync"
@@ -890,7 +891,6 @@ func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string,
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, bucket_ts ASC
`, inClause)
} else {
params = make([]interface{}, 0, len(resourceIDs)+4)
@@ -925,7 +925,8 @@ func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string,
}
defer rows.Close()
- result := make(map[string]map[string][]MetricPoint)
+ result := make(map[string]map[string][]MetricPoint, len(resourceIDs))
+ seriesCapacity := estimateQueryAllBatchSeriesCapacity(start, end, stepSecs)
for rows.Next() {
var resourceID, metricType string
var ts int64
@@ -937,12 +938,52 @@ func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string,
p.Timestamp = time.Unix(ts, 0)
if _, exists := result[resourceID]; !exists {
- result[resourceID] = make(map[string][]MetricPoint)
+ 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], p)
}
- return result, rows.Err()
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ if stepSecs > 1 {
+ sortMetricSeriesPoints(result)
+ }
+
+ return result, nil
+}
+
+func estimateQueryAllBatchSeriesCapacity(start, end time.Time, stepSecs int64) int {
+ if stepSecs <= 1 {
+ return 0
+ }
+ if !end.After(start) {
+ return 1
+ }
+
+ stepDuration := time.Duration(stepSecs) * time.Second
+ buckets := int(end.Sub(start)/stepDuration) + 2
+ if buckets < 1 {
+ return 1
+ }
+ 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
diff --git a/pkg/metrics/store_slo_test.go b/pkg/metrics/store_slo_test.go
index 668f40e14b..9f4fa509bc 100644
--- a/pkg/metrics/store_slo_test.go
+++ b/pkg/metrics/store_slo_test.go
@@ -406,6 +406,9 @@ func TestSLO_QueryAllBatch(t *testing.T) {
// TestSLO_QueryAllBatchDownsampled validates the grouped QueryAllBatch path
// used for longer-range dashboard windows where bucketed SQL is required.
+// 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.
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 b916c733ce..b3356b860e 100644
--- a/pkg/metrics/store_test.go
+++ b/pkg/metrics/store_test.go
@@ -565,6 +565,39 @@ func TestQueryAllBatch(t *testing.T) {
}
})
+ t.Run("downsampled results stay ordered per metric series", func(t *testing.T) {
+ downsampledStoreDir := t.TempDir()
+ downsampledCfg := DefaultConfig(downsampledStoreDir)
+ downsampledCfg.DBPath = filepath.Join(downsampledStoreDir, "metrics-batch-downsampled.db")
+ downsampledCfg.FlushInterval = time.Hour
+
+ downsampledStore, err := NewStore(downsampledCfg)
+ if err != nil {
+ t.Fatalf("NewStore(downsampled): %v", err)
+ }
+ defer downsampledStore.Close()
+
+ base := time.Unix(10_000, 0)
+ downsampledStore.writeBatch([]bufferedMetric{
+ {resourceType: "disk", resourceID: "disk-ordered", metricType: "smart_temp", value: 33, timestamp: base.Add(130 * time.Second), tier: TierRaw},
+ {resourceType: "disk", resourceID: "disk-ordered", metricType: "smart_temp", value: 31, timestamp: base.Add(10 * time.Second), tier: TierRaw},
+ {resourceType: "disk", resourceID: "disk-ordered", metricType: "smart_temp", value: 32, timestamp: base.Add(70 * time.Second), tier: TierRaw},
+ })
+
+ batch, err := downsampledStore.QueryAllBatch("disk", []string{"disk-ordered"}, base, base.Add(3*time.Minute), 60)
+ if err != nil {
+ t.Fatalf("QueryAllBatch(downsampled): %v", err)
+ }
+
+ points := batch["disk-ordered"]["smart_temp"]
+ if len(points) != 3 {
+ t.Fatalf("expected 3 bucketed points, got %d", len(points))
+ }
+ if !points[0].Timestamp.Before(points[1].Timestamp) || !points[1].Timestamp.Before(points[2].Timestamp) {
+ t.Fatalf("expected ascending timestamps, got %+v", points)
+ }
+ })
+
t.Run("chunked resource lists return complete results beyond sqlite parameter threshold", func(t *testing.T) {
chunkedStoreDir := t.TempDir()
chunkedCfg := DefaultConfig(chunkedStoreDir)