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.

Avoid unused extrema and copies in persisted chart reads

rcourtman03adb23556f6
diff --git a/docs/release-control/v6/internal/records/workload-chart-latency-2026-10-18.md b/docs/release-control/v6/internal/records/workload-chart-latency-2026-10-18.md
index c328ce911f..378824bed2 100644
--- a/docs/release-control/v6/internal/records/workload-chart-latency-2026-10-18.md
+++ b/docs/release-control/v6/internal/records/workload-chart-latency-2026-10-18.md
@@ -130,3 +130,75 @@ its measured allocation reduction. Executable hashes are
native proof directory. This is not an idle-worker result. The strict proof
for the resulting source remains the source-check run's retained artifact;
the 90 ms verification and broader L10 headroom follow-up remain open.
+
+## Nullable candidate qualification and available capacity
+
+At head `ea3d71a7990798c026a39480635a43ae1f3ea6c0`, the strict hosted
+test reported p50 99.543808 ms, p95 126.435066 ms and p99 132.762651 ms.
+The 90 ms assertion failed. Idle qualification also failed: two measurement
+intervals had up to 25.373% competing CPU, with `provjobd3520822` consuming
+24.875–25.124% of the four-logical-CPU guest. See
+[job 117774534298](https://github.com/rcourtman/Pulse/actions/runs/39161106967/job/117774534298)
+and [artifact 12149191504](https://github.com/rcourtman/Pulse/actions/runs/39161106967/artifacts/12149191504).
+These percentiles are retained adverse evidence, not an idle-worker result.
+
+The paired hosted comparison for the same source passed its regression
+check. Against the PR base, cold-service time fell from 145.5 to 122.2 ms/op
+(-16.04%, p<0.001, n=10). Allocated bytes fell 3.89% and allocations fell
+24.59%. Warm-handler time increased 5.23% (1.137 to 1.197 microseconds,
+p=0.001); this adverse change remains recorded even though it is below the
+job's 10% regression threshold. Transfer time was not significantly changed.
+See [job 117774534268](https://github.com/rcourtman/Pulse/actions/runs/39161106967/job/117774534268).
+The earlier failed history-filter comparisons remain historical evidence;
+this passing run does not erase them or establish absolute latency.
+
+A fresh native proof for that exact committed source waited five minutes
+and reached at most 15.001675 continuous quiet seconds. It never admitted
+the test and produced zero SLO samples. Its final-native-proof metadata and
+60 capacity intervals remain in the native proof directory.
+
+The worker inventory has no registered self-hosted runner in the public
+repository. The legacy enterprise runner shares pulse-dev; the separate
+disposable CI pool was occupied or queued, and the cloud latency runner is
+not an installed, eligible capability. No workload was interrupted, reserved
+VM started, runner label changed or infrastructure provisioned for this proof.
+Capacity and the 90 ms result remain unresolved.
+
+## Canonical value-only chart reads
+
+Chart consumers use timestamp/value points, but persisted chart reads first
+transported retained extrema and built full metrics points, then discarded
+the extrema while copying every series into the existing canonical model.
+The store now exposes value-only single-resource and batch projections using
+`models.MetricPoint`. Both projections use the same retained-read engine for
+identity normalization, filters, chunking, tier reconciliation, snapshots,
+ordering, display buckets and Docker observation provenance. The full reader
+continues to return extrema. Query shape keys distinguish the projections
+within the existing bounded cache; no result cache or tier cache was added.
+Monitoring applies its existing LTTB sampling directly to fresh owned value
+results. Payloads, point budgets and sampling algorithms are unchanged.
+
+Verification passed all 48 query-plan shapes, mixed nullable/tier projections,
+Docker observation/filter cases and fresh snapshot/caller-mutation checks.
+The full metrics suite passed in 209.013 seconds and the full monitoring
+suite in 480.630 seconds. A 1,000-point fixture proves the sampled chart
+output equals the full-reader conversion reference for all/single/multiple
+metric filters and remains detached across calls. Targeted API/chart route
+contracts also passed.
+
+Ten fixed alternating native pairs compared only the three runtime files
+against `ea3d71a7990798c026a39480635a43ae1f3ea6c0`, with identical API tests,
+Go 1.26.9 and GOMAXPROCS=2. Allocated bytes fell from 28.59 to 21.47 MiB/op
+(-24.90%, p<0.001); allocations fell 0.10%. The shared-worker timing was
+162.0 versus 183.8 ms/op (p=0.393, n=10, both +/-24%), so neither a latency
+improvement nor a regression is established. The projection is retained for
+its measured memory reduction and removal of unused transport/copies.
+This diagnostic does not satisfy the 90 ms SLO.
+
+The baseline executable SHA-256 is
+`843ea5877f711966fdbdf590854b5f3dca96319c5a9d4cd1f5f2fa3b03f98856`;
+the value-projection executable is
+`e737a0db1ea10c44a491f3ff14311ef913271c8300306bab6e259370107fb4c8`.
+All eight source hashes matched after both verification and comparison.
+Raw results, metadata and logs are retained as `value-*` in the native proof
+directory. The 90 ms proof and broader L10 follow-up remain open.
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 942bfdc5c2..0b967c1326 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -7982,3 +7982,29 @@ HTTP boundary, unknown-not-zero memory and resumed CPU/memory with the same
credential. `TestComputeDiagnosticsAPIRejectionsPreserveCredentials` covers
pinned PVE/PBS fixture use and preserves the separate PBS scheduler state.
Native scoped-fleet recovery, QGA/thaw and installed trust remain separate.
+
+
+### Persisted chart history uses the canonical value projection
+
+Single-resource and fleet chart history reads in `monitor_metrics.go` use
+`metrics.Store.QueryMetricValues` and `QueryMetricValuesBatch`. These return
+fresh, detached `models.MetricPoint` slices, the same canonical point type
+already aliased by monitoring. The shared retained reader projects timestamp
+and value without transporting unused extrema or constructing an intermediate
+full-point map and a second value-point copy. Existing metric filters, tier
+precedence, chronological ordering, gap-fill lookback and Docker observation
+provenance still apply through that same reader.
+
+The chart boundary applies the existing LTTB target to its owned result maps.
+It does not change chart sampling, point budgets, source precedence or payload
+meaning. Persisted results remain detached across calls; this ownership does
+not relax the separate detached-snapshot requirement for mutable in-memory
+History or the mock resource timeline rule. Full retained readers continue to
+return extrema for consumers that need them.
+
+`TestStoreValueProjectionPreservesChartSampling` in
+`internal/monitoring/monitor_metrics_slo_test.go` compares filtered and
+unfiltered chart results against the full reader with 1,000-point series,
+including LTTB selection and caller mutation. Metrics-store guards compare the
+projections across mixed tiers and buckets, changed database snapshots and
+Docker legacy/observed provenance; the query-plan guard covers both SQL forms.
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 ef19fe5b1b..b0b61b97fa 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -2713,7 +2713,15 @@ including zero. SQL display aggregation applies the same fallback before
MIN/MAX, and streamed buckets receive normalized bounds. Avoid materializing
the same float three times for observations without stored extrema. Mixed
nullable-bound tests cover single/fleet reads, metric filters and display
-buckets. Legacy databases keep their
+buckets. Value-only consumers must use the same retained read engine's
+`QueryMetricValues` / `QueryMetricValuesBatch` projection, returning the
+canonical `models.MetricPoint` timestamp/value type. That SQL form omits
+extrema columns and avoids materializing full points only to copy them into
+value points afterward. Full and value projections share scope normalization,
+filters, tier reconciliation, time ordering, display buckets and Docker
+observation provenance; their distinct SQL column shapes must have distinct
+keys within the existing bounded query cache. Neither mode caches results or
+tier presence. Full readers continue to preserve extrema. Legacy databases keep their
existing unique index authoritative while the replacement index is built, but
that O(rows) migration must run on deferred startup maintenance and swap indexes
in one SQLite transaction so constructor latency, concurrent reads, uniqueness,
diff --git a/internal/monitoring/monitor_metrics.go b/internal/monitoring/monitor_metrics.go
index 17b450a80e..e52b8e9c34 100644
--- a/internal/monitoring/monitor_metrics.go
+++ b/internal/monitoring/monitor_metrics.go
@@ -468,16 +468,16 @@ func (m *Monitor) queryStoreBatchMetricMapWithGapFill(resourceType string, resou
// queryBatch fetches and downsamples metrics for the given IDs.
queryBatch := func(ids []string, from time.Time) map[string]map[string][]MetricPoint {
- sqlResult, err := m.metricsStore.QueryMetricTypesBatch(resourceType, ids, metricTypes, from, end, 0)
+ sqlResult, err := m.metricsStore.QueryMetricValuesBatch(resourceType, ids, metricTypes, from, end, 0)
if err != nil || len(sqlResult) == 0 {
return nil
}
- // Convert metrics.MetricPoint → monitoring.MetricPoint and downsample.
- converted := make(map[string]map[string][]MetricPoint, len(sqlResult))
- for resID, metricMap := range sqlResult {
- converted[resID] = convertAndDownsample(metricMap, chartDownsampleTarget)
+ // The store returns detached canonical timestamp/value points. Keep
+ // their ownership while applying the existing chart sampling target.
+ for _, metricMap := range sqlResult {
+ downsampleMetricMap(metricMap, chartDownsampleTarget)
}
- return converted
+ return sqlResult
}
result := queryBatch(resourceIDs, start)
@@ -873,11 +873,11 @@ func (m *Monitor) queryStoreMetricHistory(resourceType, resourceID string, durat
start := end.Add(-duration)
query := func(from time.Time) (map[string][]MetricPoint, bool, error) {
- sqlResult, err := m.metricsStore.QueryAll(resourceType, resourceID, from, end, 0)
+ sqlResult, err := m.metricsStore.QueryMetricValues(resourceType, resourceID, from, end, 0)
if err != nil || len(sqlResult) == 0 {
return nil, false, err
}
- return convertAndDownsample(sqlResult, chartDownsampleTarget), true, nil
+ return downsampleMetricMap(sqlResult, chartDownsampleTarget), true, nil
}
if result, ok, err := query(start); ok || err != nil || !allowGapFill {
@@ -937,16 +937,11 @@ func (m *Monitor) queryStoreMetricSeriesWithGapFill(resourceType, resourceID, me
return query(end.Add(-chartGapFillLookbackWindow(duration)))
}
-// convertAndDownsample converts pkg/metrics.MetricPoint slices to
-// internal/monitoring.MetricPoint slices and applies LTTB downsampling.
-func convertAndDownsample(sqlResult map[string][]metrics.MetricPoint, target int) map[string][]MetricPoint {
- result := make(map[string][]MetricPoint, len(sqlResult))
- for metric, points := range sqlResult {
- converted := make([]MetricPoint, len(points))
- for i, p := range points {
- converted[i] = MetricPoint{Value: p.Value, Timestamp: p.Timestamp}
- }
- result[metric] = lttb(converted, target)
+// downsampleMetricMap samples detached store results at the existing chart
+// target. These slices are owned by this read and never alias retained History.
+func downsampleMetricMap(result map[string][]MetricPoint, target int) map[string][]MetricPoint {
+ for metric, points := range result {
+ result[metric] = lttb(points, target)
}
return result
}
diff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.go
index dc3478495a..120a6442a2 100644
--- a/internal/monitoring/monitor_metrics_slo_test.go
+++ b/internal/monitoring/monitor_metrics_slo_test.go
@@ -5,6 +5,7 @@ import (
"fmt"
"math"
"os"
+ "reflect"
"sort"
"testing"
"time"
@@ -1058,3 +1059,57 @@ func sharedMetricTimestampCount(a, b []MetricPoint) int {
}
return shared
}
+
+func TestStoreValueProjectionPreservesChartSampling(t *testing.T) {
+ store, err := metrics.NewStore(metrics.DefaultConfig(t.TempDir()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+ end := time.Now().Truncate(time.Minute)
+ start := end.Add(-24 * time.Hour)
+ batch := make([]metrics.WriteMetric, 0, 4000)
+ ids := []string{"a", "b"}
+ names := []string{"cpu", "memory"}
+ for _, id := range ids {
+ for _, metric := range names {
+ for i := 0; i < 1000; i++ {
+ batch = append(batch, metrics.WriteMetric{ResourceType: "vm", ResourceID: id, MetricType: metric, Value: float64((i * 37) % 97), Timestamp: end.Add(-18 * time.Hour).Add(time.Duration(i) * time.Minute), Tier: metrics.TierMinute})
+ }
+ }
+ }
+ store.WriteBatchSync(batch)
+ monitor := &Monitor{metricsStore: store}
+ for _, filter := range [][]string{nil, {"cpu"}, {"cpu", "memory"}} {
+ t.Run(fmt.Sprint(filter), func(t *testing.T) {
+ full, err := store.QueryMetricTypesBatch("vm", ids, filter, start, end, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := make(map[string]map[string][]MetricPoint, len(full))
+ for id, series := range full {
+ want[id] = make(map[string][]MetricPoint, len(series))
+ for metric, points := range series {
+ if len(points) != 1000 {
+ t.Fatalf("fixture %s/%s: got %d points", id, metric, len(points))
+ }
+ want[id][metric] = convertSeriesAndDownsample(points, chartDownsampleTarget)
+ }
+ }
+ got := monitor.queryStoreBatchMetricMapWithGapFill("vm", ids, 24*time.Hour, filter)
+ if !reflect.DeepEqual(got, want) {
+ t.Fatal("value projection changed the sampled chart observations")
+ }
+ for _, series := range got {
+ for _, points := range series {
+ points[0].Value = -999
+ points[0].Timestamp = time.Time{}
+ }
+ }
+ again := monitor.queryStoreBatchMetricMapWithGapFill("vm", ids, 24*time.Hour, filter)
+ if !reflect.DeepEqual(again, want) {
+ t.Fatal("mutating a chart result changed a subsequent read")
+ }
+ })
+ }
+}
diff --git a/pkg/metrics/docker_observation_contract.go b/pkg/metrics/docker_observation_contract.go
index 8b03199b56..b9e937ee06 100644
--- a/pkg/metrics/docker_observation_contract.go
+++ b/pkg/metrics/docker_observation_contract.go
@@ -21,7 +21,7 @@ func storedObservationMetric(resourceType, metricType string) string {
return metricType
}
-func projectDockerObservations(result map[string]map[string][]MetricPoint) {
+func projectDockerObservations[T any](result map[string]map[string][]T) {
for _, series := range result {
for _, metric := range []string{"disk", "diskread", "diskwrite"} {
delete(series, metric)
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index 9a9dc479c8..88328223b2 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -20,6 +20,7 @@ import (
"github.com/rs/zerolog/log"
sqlite "modernc.org/sqlite"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
pdb "github.com/rcourtman/pulse-go-rewrite/pkg/db"
)
@@ -1484,6 +1485,39 @@ func (s *Store) QueryMetricTypesBatch(
return s.queryBatch(resourceType, resourceIDs, metricTypes, start, end, stepSecs)
}
+// QueryMetricValues retrieves detached timestamp/value observations for one
+// resource. It uses the same tier reconciliation and display buckets as QueryAll.
+func (s *Store) QueryMetricValues(resourceType, resourceID string, start, end time.Time, stepSecs int64) (map[string][]models.MetricPoint, error) {
+ result, err := queryBatch(s, resourceType, []string{resourceID}, nil, start, end, stepSecs, retainedMetricValues)
+ if err != nil {
+ return nil, err
+ }
+ series := result[normalizeMetricIdentifier(resourceID)]
+ if series == nil {
+ series = make(map[string][]models.MetricPoint)
+ }
+ return series, nil
+}
+
+// QueryMetricValuesBatch retrieves only timestamp/value observations, using
+// canonical shared points and the same scope, filters, tiers and chunk limits as
+// QueryMetricTypesBatch. Callers that need retained extrema use the full reader.
+func (s *Store) QueryMetricValuesBatch(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, stepSecs int64) (map[string]map[string][]models.MetricPoint, error) {
+ return queryBatch(s, resourceType, resourceIDs, metricTypes, start, end, stepSecs, retainedMetricValues)
+}
+
+// The projection couples the SQL column shape with the returned point type.
+// Both readers share reconciliation, snapshot, ordering and chunking code.
+type retainedProjection[T any] struct {
+ valuesOnly bool
+ point func(MetricPoint) T
+}
+
+var retainedMetricPoints = retainedProjection[MetricPoint]{point: func(p MetricPoint) MetricPoint { return p }}
+var retainedMetricValues = retainedProjection[models.MetricPoint]{valuesOnly: true, point: func(p MetricPoint) models.MetricPoint {
+ return models.MetricPoint{Value: p.Value, Timestamp: p.Timestamp}
+}}
+
func (s *Store) queryBatch(
resourceType string,
resourceIDs []string,
@@ -1491,6 +1525,18 @@ func (s *Store) queryBatch(
start, end time.Time,
stepSecs int64,
) (map[string]map[string][]MetricPoint, error) {
+ return queryBatch(s, resourceType, resourceIDs, metricTypes, start, end, stepSecs, retainedMetricPoints)
+}
+
+func queryBatch[T any](
+ s *Store,
+ resourceType string,
+ resourceIDs []string,
+ metricTypes []string,
+ start, end time.Time,
+ stepSecs int64,
+ projection retainedProjection[T],
+) (map[string]map[string][]T, error) {
resourceType = normalizeMetricResourceType(resourceType)
// Deduplicate resource IDs.
seen := make(map[string]struct{}, len(resourceIDs))
@@ -1506,7 +1552,7 @@ func (s *Store) queryBatch(
}
}
if len(unique) == 0 {
- return map[string]map[string][]MetricPoint{}, nil
+ return map[string]map[string][]T{}, nil
}
normalizedMetricTypes := normalizeMetricTypes(metricTypes)
if hasDockerObservationContract(resourceType) {
@@ -1517,18 +1563,18 @@ func (s *Store) queryBatch(
tiers := s.tierFallbacks(end.Sub(start))
if len(tiers) == 0 {
- return map[string]map[string][]MetricPoint{}, nil
+ return map[string]map[string][]T{}, nil
}
if len(unique) <= queryAllBatchChunkSize {
- return s.queryRetainedChunk(resourceType, unique, normalizedMetricTypes, start, end, stepSecs, tiers)
+ return queryRetainedChunk(s, resourceType, unique, normalizedMetricTypes, start, end, stepSecs, tiers, projection)
}
- result := make(map[string]map[string][]MetricPoint, len(unique))
+ result := make(map[string]map[string][]T, len(unique))
// Reconcile every series in one snapshot per chunk. A resource with one
// aggregate must not hide another metric or a newer tail in a different tier.
for lo := 0; lo < len(unique); lo += queryAllBatchChunkSize {
hi := min(lo+queryAllBatchChunkSize, len(unique))
- chunkResult, err := s.queryRetainedChunk(resourceType, unique[lo:hi], normalizedMetricTypes, start, end, stepSecs, tiers)
+ chunkResult, err := queryRetainedChunk(s, resourceType, unique[lo:hi], normalizedMetricTypes, start, end, stepSecs, tiers, projection)
if err != nil {
return nil, err
}
@@ -1568,6 +1614,7 @@ type retainedQueryShape struct {
resources, metrics int
tiers [4]Tier
aggregate, groupSeries bool
+ valuesOnly bool
}
func retainedQueryParameters(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier) []interface{} {
@@ -1594,8 +1641,8 @@ func retainedQueryParameters(resourceType string, resourceIDs, metricTypes []str
return params
}
-func (s *Store) retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier, groupSeries bool) (string, []interface{}) {
- shape := retainedQueryShape{resources: len(resourceIDs), metrics: len(metricTypes), aggregate: stepSecs > 1, groupSeries: groupSeries}
+func (s *Store) retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier, groupSeries, valuesOnly bool) (string, []interface{}) {
+ shape := retainedQueryShape{resources: len(resourceIDs), metrics: len(metricTypes), aggregate: stepSecs > 1, groupSeries: groupSeries, valuesOnly: valuesOnly}
cacheable := len(tiers) <= len(shape.tiers)
copy(shape.tiers[:], tiers)
if cacheable {
@@ -1606,7 +1653,7 @@ func (s *Store) retainedQuerySQL(resourceType string, resourceIDs, metricTypes [
return query, retainedQueryParameters(resourceType, resourceIDs, metricTypes, start, end, stepSecs, tiers)
}
}
- query, params := retainedQuerySQL(resourceType, resourceIDs, metricTypes, start, end, stepSecs, tiers, groupSeries)
+ query, params := retainedQuerySQL(resourceType, resourceIDs, metricTypes, start, end, stepSecs, tiers, groupSeries, valuesOnly)
if cacheable {
s.queryMu.Lock()
if len(s.readQueryShapes) < maxRetainedReadStatements {
@@ -1625,7 +1672,7 @@ func (s *Store) retainedQuerySQL(resourceType string, resourceIDs, metricTypes [
// buckets, and a coarser fallback is omitted if a preferred point overlaps it.
// Presence never establishes continuous collection or per-series coverage.
// Every probe is restricted to the requested identities and timestamp window.
-func retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier, groupSeries bool) (string, []interface{}) {
+func retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier, groupSeries, valuesOnly bool) (string, []interface{}) {
params := retainedQueryParameters(resourceType, resourceIDs, metricTypes, start, end, stepSecs, tiers)
identityColumns := ""
if len(resourceIDs) != 1 {
@@ -1660,12 +1707,17 @@ func retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, st
// Preserve nullable extrema across the row boundary. Materializing the
// value again for each missing bound makes SQLite and its driver decode
// three floats for an observation that stores only one.
- projection := identityColumns + `m.timestamp, m.value, m.min_value, m.max_value`
+ projection := identityColumns + `m.timestamp, m.value`
+ if !valuesOnly {
+ projection += `, m.min_value, m.max_value`
+ }
directAggregate := stepSecs > 1 && len(tiers) == 1
bucketExpression := fmt.Sprintf("(timestamp / :p%d) * :p%d + (:p%d / 2)", stepParam, stepParam, stepParam)
if directAggregate {
- projection = identityColumns + bucketExpression + ` AS bucket_ts,
- AVG(m.value), MIN(COALESCE(m.min_value, m.value)), MAX(COALESCE(m.max_value, m.value))`
+ projection = identityColumns + bucketExpression + ` AS bucket_ts, AVG(m.value)`
+ if !valuesOnly {
+ projection += `, MIN(COALESCE(m.min_value, m.value)), MAX(COALESCE(m.max_value, m.value))`
+ }
}
branches := make([]string, 0, len(tiers))
for i, tier := range tiers {
@@ -1693,9 +1745,11 @@ func retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, st
if directAggregate {
query += " GROUP BY " + identityColumns + "bucket_ts ORDER BY " + identityColumns + "bucket_ts ASC"
} else if stepSecs > 1 {
- query = "SELECT " + identityColumns + bucketExpression + ` AS bucket_ts,
- AVG(value), MIN(COALESCE(min_value, value)), MAX(COALESCE(max_value, value))
- FROM (` + query + ") GROUP BY " + identityColumns + "bucket_ts ORDER BY " + identityColumns + "bucket_ts ASC"
+ aggregate := "SELECT " + identityColumns + bucketExpression + ` AS bucket_ts, AVG(value)`
+ if !valuesOnly {
+ aggregate += `, MIN(COALESCE(min_value, value)), MAX(COALESCE(max_value, value))`
+ }
+ query = aggregate + " FROM (" + query + ") GROUP BY " + identityColumns + "bucket_ts ORDER BY " + identityColumns + "bucket_ts ASC"
} else {
orderColumns := identityColumns
if !groupSeries {
@@ -1751,7 +1805,7 @@ func (s *Store) retainedReadStatement(query string) (*pdb.InstrumentedStmt, erro
return stmt, nil
}
-func (s *Store) queryRetainedChunk(resourceType string, resourceIDs []string, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier) (map[string]map[string][]MetricPoint, error) {
+func queryRetainedChunk[T any](s *Store, resourceType string, resourceIDs []string, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier, projection retainedProjection[T]) (map[string]map[string][]T, error) {
var tx *pdb.InstrumentedTx
var err error
if stepSecs > 1 {
@@ -1815,7 +1869,7 @@ func (s *Store) queryRetainedChunk(resourceType string, resourceIDs []string, me
}
}
if len(available) == 0 {
- return make(map[string]map[string][]MetricPoint), nil
+ return make(map[string]map[string][]T), nil
}
tiers = available
}
@@ -1827,7 +1881,7 @@ func (s *Store) queryRetainedChunk(resourceType string, resourceIDs []string, me
if streamBuckets {
queryStep = 0
}
- sqlQuery, params := s.retainedQuerySQL(resourceType, resourceIDs, metricTypes, start, end, queryStep, tiers, streamBuckets)
+ sqlQuery, params := s.retainedQuerySQL(resourceType, resourceIDs, metricTypes, start, end, queryStep, tiers, streamBuckets, projection.valuesOnly)
queryRows := func() (*sql.Rows, error) { return tx.Query(sqlQuery, params...) }
if tx == nil {
@@ -1860,15 +1914,15 @@ func (s *Store) queryRetainedChunk(resourceType string, resourceIDs []string, me
}
defer rows.Close()
- result := make(map[string]map[string][]MetricPoint, len(resourceIDs))
+ result := make(map[string]map[string][]T, len(resourceIDs))
seriesCapacity := estimateQueryAllBatchSeriesCapacity(start, end, stepSecs)
// Consecutive points in one series append directly to its slice. Flush on
// a series change so interleaved metrics can resume their existing slices
// without performing repeated nested-map lookups for every observation.
var outputResource, outputMetric string
- var outputMetrics map[string][]MetricPoint
- var outputPoints []MetricPoint
+ var outputMetrics map[string][]T
+ var outputPoints []T
flushSeries := func() {
if outputMetrics != nil {
outputMetrics[outputMetric] = outputPoints
@@ -1881,17 +1935,17 @@ func (s *Store) queryRetainedChunk(resourceType string, resourceIDs []string, me
outputResource = resourceID
outputMetrics = result[resourceID]
if outputMetrics == nil {
- outputMetrics = make(map[string][]MetricPoint, 8)
+ outputMetrics = make(map[string][]T, 8)
result[resourceID] = outputMetrics
}
}
outputMetric = metricType
outputPoints = outputMetrics[metricType]
if outputPoints == nil {
- outputPoints = make([]MetricPoint, 0, seriesCapacity)
+ outputPoints = make([]T, 0, seriesCapacity)
}
}
- outputPoints = append(outputPoints, point)
+ outputPoints = append(outputPoints, projection.point(point))
}
var bucketResource, bucketMetric string
var bucketStart int64
@@ -1921,18 +1975,23 @@ func (s *Store) queryRetainedChunk(resourceType string, resourceIDs []string, me
} else {
destinations = append(destinations, &metricType)
}
- destinations = append(destinations, &ts, &p.Value, &low, &high)
+ destinations = append(destinations, &ts, &p.Value)
+ if !projection.valuesOnly {
+ destinations = append(destinations, &low, &high)
+ }
for rows.Next() {
if err := rows.Scan(destinations...); err != nil {
log.Warn().Err(err).Msg("Failed to scan batch metric row")
continue
}
- p.Min, p.Max = p.Value, p.Value
- if low.Valid {
- p.Min = low.Float64
- }
- if high.Valid {
- p.Max = high.Float64
+ if !projection.valuesOnly {
+ p.Min, p.Max = p.Value, p.Value
+ if low.Valid {
+ p.Min = low.Float64
+ }
+ if high.Valid {
+ p.Max = high.Float64
+ }
}
if !streamBuckets {
p.Timestamp = time.Unix(ts, 0)
diff --git a/pkg/metrics/store_docker_observation_contract_test.go b/pkg/metrics/store_docker_observation_contract_test.go
index cde2531916..01b73dd074 100644
--- a/pkg/metrics/store_docker_observation_contract_test.go
+++ b/pkg/metrics/store_docker_observation_contract_test.go
@@ -87,6 +87,11 @@ func TestDockerObservationContractSeparatesLegacyAcrossRetainedReads(t *testing.
assert(batch["a"], false)
assert(batch["b"], false)
assert(batch["legacy-only"], true)
+ values, err := store.QueryMetricValuesBatch(family, []string{"a", "b", "legacy-only"}, nil, start, end, step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertMetricValueProjection(t, batch, values)
selected, err := store.QueryMetricTypesBatch(family, []string{"a", "b", "legacy-only"}, []string{"disk", "diskread", "diskwrite"}, start, end, step)
if err != nil {
t.Fatal(err)
@@ -94,6 +99,11 @@ func TestDockerObservationContractSeparatesLegacyAcrossRetainedReads(t *testing.
assert(selected["a"], false)
assert(selected["b"], false)
assert(selected["legacy-only"], true)
+ selectedValues, err := store.QueryMetricValuesBatch(family, []string{"a", "b", "legacy-only"}, []string{"disk", "diskread", "diskwrite"}, start, end, step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertMetricValueProjection(t, selected, selectedValues)
for _, metric := range []string{"disk", "diskread", "diskwrite"} {
points, err := store.Query(family, "a", metric, start, end, step)
if err != nil {
diff --git a/pkg/metrics/store_query_plan_test.go b/pkg/metrics/store_query_plan_test.go
index 4fd216b0a1..e9e7fafde2 100644
--- a/pkg/metrics/store_query_plan_test.go
+++ b/pkg/metrics/store_query_plan_test.go
@@ -178,7 +178,7 @@ func TestRetainedQueryPlansUseIndexes(t *testing.T) {
metrics = []string{"cpu", "memory"}
}
end := time.Unix(2000000000, 0)
- sql, args := retainedQuerySQL("vm", []string{"vm-1", "vm-2", "vm-3"}, metrics, end.Add(-window), end, step, store.tierFallbacks(window), false)
+ sql, args := retainedQuerySQL("vm", []string{"vm-1", "vm-2", "vm-3"}, metrics, end.Add(-window), end, step, store.tierFallbacks(window), false, false)
plan := explainQueryPlan(t, db, sql, args)
searches := 0
for _, line := range strings.Split(plan, "\n") {
@@ -216,7 +216,7 @@ func TestRetainedSingleTierQueryPlansUseIndexes(t *testing.T) {
if filtered {
metrics = []string{"cpu"}
}
- query, args := retainedQuerySQL("vm", []string{"vm-1"}, metrics, end.Add(-time.Hour), end, 60, []Tier{tier}, false)
+ query, args := retainedQuerySQL("vm", []string{"vm-1"}, metrics, end.Add(-time.Hour), end, 60, []Tier{tier}, false, false)
plan := explainQueryPlan(t, db, query, args)
if strings.Contains(plan, "SCAN m ") || !strings.Contains(plan, "SEARCH m ") {
t.Fatalf("single tier must use a bounded lookup: %s", plan)
@@ -539,18 +539,20 @@ func TestRetainedUnaggregatedQueryAvoidsMetricSort(t *testing.T) {
db := newPlanTestDB(t)
store := &Store{}
end := time.Unix(2000000040, 0)
- for _, window := range []time.Duration{time.Hour, 24 * time.Hour, 7 * 24 * time.Hour, 30 * 24 * time.Hour} {
- for _, ids := range [][]string{{"a"}, {"a", "b"}} {
- for _, metrics := range [][]string{nil, {"cpu"}, {"cpu", "memory"}} {
- t.Run(fmt.Sprintf("%s/resources_%d/metrics_%d", window, len(ids), len(metrics)), func(t *testing.T) {
- query, args := retainedQuerySQL("node", ids, metrics, end.Add(-window), end, 0, store.tierFallbacks(window), false)
- plan := explainQueryPlan(t, db, query, args)
- for _, line := range strings.Split(plan, "\n") {
- if strings.Contains(strings.ToUpper(line), "TEMP B-TREE") {
- t.Fatalf("unaggregated read sorts despite time-ordered index: %s", plan)
+ for _, valuesOnly := range []bool{false, true} {
+ for _, window := range []time.Duration{time.Hour, 24 * time.Hour, 7 * 24 * time.Hour, 30 * 24 * time.Hour} {
+ for _, ids := range [][]string{{"a"}, {"a", "b"}} {
+ for _, metrics := range [][]string{nil, {"cpu"}, {"cpu", "memory"}} {
+ t.Run(fmt.Sprintf("values_%t/%s/resources_%d/metrics_%d", valuesOnly, window, len(ids), len(metrics)), func(t *testing.T) {
+ query, args := retainedQuerySQL("node", ids, metrics, end.Add(-window), end, 0, store.tierFallbacks(window), false, valuesOnly)
+ plan := explainQueryPlan(t, db, query, args)
+ for _, line := range strings.Split(plan, "\n") {
+ if strings.Contains(strings.ToUpper(line), "TEMP B-TREE") {
+ t.Fatalf("unaggregated read sorts despite time-ordered index: %s", plan)
+ }
}
- }
- })
+ })
+ }
}
}
}
diff --git a/pkg/metrics/store_tier_coverage_test.go b/pkg/metrics/store_tier_coverage_test.go
index b054b40d4d..4b23a2f022 100644
--- a/pkg/metrics/store_tier_coverage_test.go
+++ b/pkg/metrics/store_tier_coverage_test.go
@@ -320,6 +320,11 @@ func TestStoreRetainedNullableExtrema(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ values, err := store.QueryMetricValuesBatch("node", ids, filter, base.Add(-2*time.Hour), base.Add(6*time.Minute), step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertMetricValueProjection(t, got, values)
for _, id := range ids {
metrics := filter
if len(metrics) == 0 {
diff --git a/pkg/metrics/store_value_projection_test.go b/pkg/metrics/store_value_projection_test.go
new file mode 100644
index 0000000000..5d0a1d8b71
--- /dev/null
+++ b/pkg/metrics/store_value_projection_test.go
@@ -0,0 +1,90 @@
+package metrics
+
+import (
+ "fmt"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ pdb "github.com/rcourtman/pulse-go-rewrite/pkg/db"
+ "testing"
+ "time"
+)
+
+func assertMetricValueProjection(t *testing.T, full map[string]map[string][]MetricPoint, values map[string]map[string][]models.MetricPoint) {
+ t.Helper()
+ if len(full) != len(values) {
+ t.Fatalf("resource scope changed: full=%v values=%v", full, values)
+ }
+ for id, series := range full {
+ projected, ok := values[id]
+ if !ok || len(series) != len(projected) {
+ t.Fatalf("metric scope changed for %s: full=%v values=%v", id, series, projected)
+ }
+ for metric, points := range series {
+ got, ok := projected[metric]
+ if !ok || len(got) != len(points) {
+ t.Fatalf("series shape changed for %s/%s: full=%v values=%v", id, metric, points, got)
+ }
+ for i, point := range points {
+ if point.Value != got[i].Value || !point.Timestamp.Equal(got[i].Timestamp) {
+ t.Fatalf("observation changed for %s/%s[%d]: full=%+v values=%+v", id, metric, i, point, got[i])
+ }
+ }
+ }
+ }
+}
+
+func TestMetricValueProjectionReadsCurrentDetachedSnapshot(t *testing.T) {
+ db := newPlanTestDB(t)
+ db.SetMaxOpenConns(1)
+ store := &Store{db: pdb.Wrap(db, "value-snapshot-test")}
+ end := time.Unix(2000000040, 0)
+ start := end.Add(-3 * time.Hour)
+ for _, step := range []int64{0, 120} {
+ t.Run(fmt.Sprint(step), func(t *testing.T) {
+ if _, err := db.Exec("DELETE FROM metrics"); err != nil {
+ t.Fatal(err)
+ }
+ read := func(want *float64) {
+ t.Helper()
+ full, err := store.QueryAll("node", "a", start, end, step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ values, err := store.QueryMetricValues("node", "a", start, end, step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertMetricValueProjection(t, map[string]map[string][]MetricPoint{"a": full}, map[string]map[string][]models.MetricPoint{"a": values})
+ if want == nil {
+ if len(values) != 0 {
+ t.Fatalf("invented data: %+v", values)
+ }
+ return
+ }
+ if len(values["cpu"]) != 1 || values["cpu"][0].Value != *want {
+ t.Fatalf("stale data: %+v", values)
+ }
+ values["cpu"][0].Value = -999
+ values["cpu"][0].Timestamp = time.Time{}
+ again, err := store.QueryMetricValues("node", "a", start, end, step)
+ if err != nil || len(again["cpu"]) != 1 || again["cpu"][0].Value != *want || again["cpu"][0].Timestamp.IsZero() {
+ t.Fatalf("caller mutation reached later read: %+v %v", again, err)
+ }
+ }
+ read(nil)
+ if _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value) VALUES ('node','a','cpu','raw',?,23)`, end.Add(-40*time.Second).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ raw := 23.0
+ read(&raw)
+ if _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value) VALUES ('node','a','cpu','minute',?,17)`, end.Add(-time.Minute).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ preferred := 17.0
+ read(&preferred)
+ if _, err := db.Exec("DELETE FROM metrics"); err != nil {
+ t.Fatal(err)
+ }
+ read(nil)
+ })
+ }
+}