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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Normalize infrastructure summary chart buckets
rcourtmancd22b303ebb4
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 5e6aba9983..26dabc7635 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -573,6 +573,10 @@ count. Lifecycle-adjacent install or discovery surfaces must not fork thatinto a VMware-only install wizard, direct-ESXi setup branch, or agent-firstbootstrap story just because the runtime now has a live VMware connectionpanel and poller.+That same shared router boundary must treat infrastructure summary chart+normalization as summary-only presentation transport: long-range chart bucket+shaping may improve operator-facing summary readability, but it must not be+reused as lifecycle freshness, heartbeat, or enrollment-state authority.That same lifecycle-owned settings slice now also owns the shared VMwaresummary and handoff framing. `InfrastructurePlatformConnectionsSummaryCard.tsx`,`InfrastructureReportingPanel.tsx`, `useInfrastructureSettingsState.ts`, anddiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 2fb65cd2ec..1c69d7cdbc 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -173,6 +173,7 @@ Own canonical runtime payload shapes between backend and frontend.20. Keep hosted billing-state quickstart payload fields on the shared API contract: `internal/api/hosted_entitlement_refresh.go`, `internal/api/subscription_state_handlers.go`, and `internal/api/contract_test.go` must preserve `quickstart_credits_granted`, `quickstart_credits_used`, and `quickstart_credits_granted_at` through hosted signup, hosted lease refresh, and billing-state reads instead of letting lease rewrites silently erase seeded quickstart inventory.21. Keep hosted AI settings bootstrap on the shared API contract: `internal/api/ai_hosted_runtime.go`, `internal/api/ai_handlers.go`, `internal/api/ai_handler.go`, and `internal/api/contract_test.go` must treat a missing `ai.enc` in hosted mode as a canonical bootstrap condition, persist one machine-owned quickstart-backed AI config when hosted entitlements grant AI capability, and preserve that configured settings payload as the same public contract that Chat, Patrol, and AI Settings consume.22. Keep post-boot AI enablement contract-backed on the shared AI/mobile approval surface: `internal/api/ai_handler.go`, `internal/api/ai_handlers.go`, `internal/api/router_routes_ai_relay.go`, and `internal/api/contract_test.go` must turn the governed approvals-list API into the canonical empty-list payload as soon as settings-driven AI enablement succeeds, rather than leaving that surface on `503 Approval store not initialized` until some separate startup-only side effect happens.+23. Keep infrastructure summary chart transport contract-backed on the shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and frontend infrastructure summary consumers must normalize long-range mixed-cadence history into equal-time summary buckets before shipping the infrastructure charts API payload, so 7-day and 30-day summary cards do not expose compressed right-edge tails just because recent samples arrive at a finer storage resolution.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex b0eb94f32b..dc78a9da43 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -415,6 +415,10 @@ The infrastructure summary hot path is now explicit shared ownership too:selection, empty-state wording, and summary-series/metric derivation. Futuresummary-chart work must not put polling, cache hydration, and series mathback into the shell.+The summary API feeding that hot path must also normalize mixed-resolution+history into equal-time summary buckets before it reaches the shell/runtime+owners, so long-range cards do not bunch recent higher-resolution samples at+the right edge.It now also includes the compact resource-facet summary chips rendered nextto policy metadata, and those chips must stay within the same boundedwindowing and mounted-row budget proved bydiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex dd7d26c98b..f12690b5e6 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -95,6 +95,7 @@ querying, and the operator-facing storage health presentation layer.29. Keep VMware datastore projection on the shared unified-resource and storage-source contracts. When `frontend-modern/src/hooks/useUnifiedResources.ts` or shared `internal/api/router.go` wiring starts surfacing VMware-backed canonical `storage` resources, storage and recovery may expose those datastores through the owned `vmware-vsphere` source/platform vocabulary for inventory, capacity, and handoff flows only; they must not reinterpret that projection as VMware recovery support, restore semantics, or a provider-local protection surface.30. Keep VMware placement and guest-detail enrichment descriptive on that same shared unified-resource contract. When `internal/vmware/provider.go`, `internal/unifiedresources/types.go`, and `frontend-modern/src/hooks/useUnifiedResources.ts` project datacenter, cluster, folder, runtime-host, datastore-attachment, guest-hostname, or guest-IP metadata onto canonical VMware `agent` / `vm` / `storage` resources, storage and recovery may use that detail for labeling and navigation only; they must not promote those topology or guest fields into recovery ownership, restore targeting, protection grouping, or a VMware-local recovery taxonomy without a separately governed slice.31. Keep VMware datastore classification neutral on the shared storage adapter contract. When `frontend-modern/src/features/storageBackups/resourceStorageMapping.ts`, `frontend-modern/src/features/storageBackups/resourceStoragePresentation.ts`, and `frontend-modern/src/features/storageBackups/storageAdapters.ts` evolve canonical storage-record mapping, VMware-backed datastores must continue to land on the shared storage route as inventory-only datastores with neutral protection fallback, not as backup repositories, backup targets, or recovery-protected resources.+32. Keep infrastructure summary chart bucketing presentation-only on the adjacent shared API boundary. When `internal/api/router.go` normalizes mixed-cadence infrastructure history into equal-time summary buckets for operator-facing summary cards, storage and recovery may consume the resulting visual context only; they must not reinterpret those normalized chart samples as recovery freshness windows, backup cadence, or restore evidence.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex cf7a92db83..e51af530da 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -680,6 +680,10 @@ while chart matching and summary-series derivation route throughand `frontend-modern/src/components/Infrastructure/InfrastructureSummary.tsx`stays the render shell, so summary charts are no longer an unowned mixedresource consumer surface.+The shared summary chart contract now also requires the backend feed to+normalize tiered infrastructure history into equal-time summary buckets, so+long-range unified-resource cards do not expose storage-tier density changes as+right-edge chart compression.The shared `ResourceFacetSummary` consumer now omits capability andrelationship badges from the default table/detail surface entirely, while thebackend contract keeps capability and relationship data on the owned resourcediff --git a/frontend-modern/src/utils/infrastructureSummaryCache.ts b/frontend-modern/src/utils/infrastructureSummaryCache.tsindex 0a1f42cae8..a92aff1604 100644--- a/frontend-modern/src/utils/infrastructureSummaryCache.ts+++ b/frontend-modern/src/utils/infrastructureSummaryCache.ts@@ -11,7 +11,7 @@ import { eventBus } from '@/stores/events';export const INFRA_SUMMARY_CACHE_PREFIX = 'pulse.infrastructureSummaryCharts.';export const INFRA_SUMMARY_CACHE_MAX_AGE_MS = 5 * 60_000;-const INFRA_SUMMARY_CACHE_VERSION = 1;+const INFRA_SUMMARY_CACHE_VERSION = 2;const INFRA_SUMMARY_CACHE_MAX_CHARS = 900_000;const INFRA_SUMMARY_CACHE_MAX_POINTS_PER_SERIES = 360;diff --git a/internal/api/charts_test.go b/internal/api/charts_test.goindex b7f3d3326b..4920652a2c 100644--- a/internal/api/charts_test.go+++ b/internal/api/charts_test.go@@ -230,6 +230,115 @@ func TestTimeRangeConversion(t *testing.T) {}}+func TestTargetInfrastructureSummarySeriesPoints(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ duration time.Duration+ want int+ }{+ {name: "zero_defaults_to_minimum", duration: 0, want: infrastructureSummaryMinSeriesPoints},+ {name: "one_hour_keeps_minute_resolution", duration: time.Hour, want: 60},+ {name: "four_hours_caps_at_maximum", duration: 4 * time.Hour, want: infrastructureSummaryMaxSeriesPoints},+ {name: "seven_days_caps_at_maximum", duration: 7 * 24 * time.Hour, want: infrastructureSummaryMaxSeriesPoints},+ }++ for _, tt := range tests {+ tt := tt+ t.Run(tt.name, func(t *testing.T) {+ if got := targetInfrastructureSummarySeriesPoints(tt.duration); got != tt.want {+ t.Fatalf("targetInfrastructureSummarySeriesPoints(%v) = %d, want %d", tt.duration, got, tt.want)+ }+ })+ }+}++func TestNormalizeInfrastructureSummaryMetricPointSeriesSmoothsMixedCadenceTail(t *testing.T) {+ t.Parallel()++ now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC)+ duration := 7 * 24 * time.Hour+ windowStart := now.Add(-duration)++ var points []MetricPoint+ for ts := windowStart; ts.Before(now.Add(-24 * time.Hour)); ts = ts.Add(65 * time.Minute) {+ points = append(points, MetricPoint{+ Timestamp: ts.UnixMilli(),+ Value: 20,+ })+ }+ for ts := now.Add(-24 * time.Hour); ts.Before(now.Add(-2 * time.Hour)); ts = ts.Add(2 * time.Minute) {+ points = append(points, MetricPoint{+ Timestamp: ts.UnixMilli(),+ Value: 40,+ })+ }+ for ts := now.Add(-2 * time.Hour); ts.Before(now); ts = ts.Add(time.Minute) {+ points = append(points, MetricPoint{+ Timestamp: ts.UnixMilli(),+ Value: 60,+ })+ }+ points = append(points, MetricPoint{Timestamp: now.UnixMilli(), Value: 75})++ normalized := normalizeInfrastructureSummaryMetricPointSeries(points, "cpu", duration, now.UnixMilli())+ if len(normalized) > infrastructureSummaryMaxSeriesPoints {+ t.Fatalf("expected normalized point count <= %d, got %d", infrastructureSummaryMaxSeriesPoints, len(normalized))+ }+ if len(normalized) < 60 {+ t.Fatalf("expected a range-wide summary series, got only %d points", len(normalized))+ }+ if normalized[len(normalized)-1].Timestamp != points[len(points)-1].Timestamp {+ t.Fatalf("expected latest timestamp %d, got %d", points[len(points)-1].Timestamp, normalized[len(normalized)-1].Timestamp)+ }+ if normalized[len(normalized)-1].Value != points[len(points)-1].Value {+ t.Fatalf("expected latest value %.1f, got %.1f", points[len(points)-1].Value, normalized[len(normalized)-1].Value)+ }++ recentWindowStart := now.Add(-24 * time.Hour).UnixMilli()+ recentCount := 0+ for _, point := range normalized {+ if point.Timestamp >= recentWindowStart {+ recentCount+++ }+ }+ if recentCount > 20 {+ t.Fatalf("expected roughly day-proportional recent buckets after normalization, got %d recent points", recentCount)+ }+}++func TestNormalizeInfrastructureSummaryMetricPointSeriesAveragesPlateauMetrics(t *testing.T) {+ t.Parallel()++ now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC)+ duration := 4 * time.Hour+ bucketCount := targetInfrastructureSummarySeriesPoints(duration)+ windowStart := now.Add(-duration)+ durationMillis := duration.Milliseconds()+ firstBucketEnd := windowStart.UnixMilli() + durationMillis/int64(bucketCount)++ points := []MetricPoint{+ {Timestamp: windowStart.UnixMilli() + 1_000, Value: 20},+ {Timestamp: windowStart.UnixMilli() + 30_000, Value: 40},+ {Timestamp: firstBucketEnd - 1_000, Value: 80},+ {Timestamp: now.UnixMilli(), Value: 55},+ }++ normalized := normalizeInfrastructureSummaryMetricPointSeries(points, "memory", duration, now.UnixMilli())+ if len(normalized) < 2 {+ t.Fatalf("expected at least two normalized points, got %d", len(normalized))+ }++ firstValue := normalized[0].Value+ if firstValue != (20+40+80)/3.0 {+ t.Fatalf("expected first bucket average %.2f, got %.2f", (20+40+80)/3.0, firstValue)+ }+ if normalized[len(normalized)-1].Value != 55 {+ t.Fatalf("expected latest point to preserve final value 55, got %.2f", normalized[len(normalized)-1].Value)+ }+}+func TestDockerMetricKeyFormat(t *testing.T) {t.Parallel()diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 4117742f6c..e7ae312c4f 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -37,6 +37,7 @@ import (authpkg "github.com/rcourtman/pulse-go-rewrite/pkg/auth""github.com/rcourtman/pulse-go-rewrite/pkg/cloudauth"pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"+ "github.com/rcourtman/pulse-go-rewrite/pkg/metrics""github.com/rcourtman/pulse-go-rewrite/pkg/reporting")@@ -265,6 +266,89 @@ func TestContract_VMwareConnectionListCarriesObservedSummary(t *testing.T) {}}+func TestContract_InfrastructureChartsNormalizeLongRangeMixedCadence(t *testing.T) {+ store := newTestMetricsStore(t)+ monitor, state, _ := newTestMonitor(t)+ setTestUnexportedField(t, monitor, "metricsStore", store)++ state.Nodes = []models.Node{{+ ID: "node-contract-1",+ Name: "node-contract-1",+ Instance: "pve1",+ Status: "online",+ CPU: 0.75,+ Memory: models.Memory{Usage: 42.0},+ Disk: models.Disk{Usage: 55.0},+ }}+ syncTestResourceStore(t, monitor, state)++ now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC)+ windowStart := now.Add(-7 * 24 * time.Hour)+ seed := make([]metrics.WriteMetric, 0, 1200)+ appendMetric := func(ts time.Time, value float64) {+ for _, metricType := range []string{"cpu", "memory", "disk"} {+ seed = append(seed, metrics.WriteMetric{+ ResourceType: "node",+ ResourceID: "node-contract-1",+ MetricType: metricType,+ Value: value,+ Timestamp: ts,+ Tier: metrics.TierMinute,+ })+ }+ }+ for ts := windowStart; ts.Before(now.Add(-24 * time.Hour)); ts = ts.Add(65 * time.Minute) {+ appendMetric(ts, 20)+ }+ for ts := now.Add(-24 * time.Hour); ts.Before(now.Add(-2 * time.Hour)); ts = ts.Add(2 * time.Minute) {+ appendMetric(ts, 40)+ }+ for ts := now.Add(-2 * time.Hour); ts.Before(now); ts = ts.Add(time.Minute) {+ appendMetric(ts, 60)+ }+ appendMetric(now, 75)+ store.WriteBatchSync(seed)++ router := &Router{monitor: monitor}+ req := httptest.NewRequest(http.MethodGet, "/api/charts/infrastructure?range=7d", nil)+ rec := httptest.NewRecorder()+ router.handleInfrastructureCharts(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }++ var decoded InfrastructureChartsResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {+ t.Fatalf("unmarshal infrastructure charts response: %v", err)+ }++ cpuSeries := decoded.NodeData["node-contract-1"]["cpu"]+ if len(cpuSeries) == 0 {+ t.Fatal("expected normalized cpu series")+ }+ if len(cpuSeries) > infrastructureSummaryMaxSeriesPoints {+ t.Fatalf("expected cpu series <= %d points, got %d", infrastructureSummaryMaxSeriesPoints, len(cpuSeries))+ }+ if cpuSeries[len(cpuSeries)-1].Timestamp != now.UnixMilli() {+ t.Fatalf("expected latest cpu timestamp %d, got %d", now.UnixMilli(), cpuSeries[len(cpuSeries)-1].Timestamp)+ }+ if cpuSeries[len(cpuSeries)-1].Value != 75 {+ t.Fatalf("expected latest cpu value 75, got %.2f", cpuSeries[len(cpuSeries)-1].Value)+ }++ recentWindowStart := now.Add(-24 * time.Hour).UnixMilli()+ recentCount := 0+ for _, point := range cpuSeries {+ if point.Timestamp >= recentWindowStart {+ recentCount+++ }+ }+ if recentCount > 20 {+ t.Fatalf("expected day-proportional recent summary buckets, got %d recent cpu points", recentCount)+ }+}+func TestContract_PlatformMockToggleRebindsRuntimeConnectionsAndResources(t *testing.T) {t.Setenv("PULSE_MOCK_MODE", "false")prevMock := mock.IsMockEnabled()diff --git a/internal/api/router.go b/internal/api/router.goindex bb97bf8114..314dad4fcc 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -5531,6 +5531,164 @@ func capMetricPointSeries(points []MetricPoint, maxPoints int) []MetricPoint {return result}+const (+ infrastructureSummaryMinSeriesPoints = 24+ infrastructureSummaryMaxSeriesPoints = 96+)++type infrastructureSummaryBucket struct {+ count int+ sum float64+ max float64+ firstTimestamp int64+ lastTimestamp int64+ lastValue float64+}++func targetInfrastructureSummarySeriesPoints(duration time.Duration) int {+ if duration <= 0 {+ return infrastructureSummaryMinSeriesPoints+ }++ target := int(duration / time.Minute)+ if target < infrastructureSummaryMinSeriesPoints {+ target = infrastructureSummaryMinSeriesPoints+ }+ if target > infrastructureSummaryMaxSeriesPoints {+ target = infrastructureSummaryMaxSeriesPoints+ }+ if target < 2 {+ target = 2+ }+ return target+}++func aggregateInfrastructureSummaryBucketValue(+ metricType string,+ bucket infrastructureSummaryBucket,+ isLastBucket bool,+) float64 {+ if bucket.count == 0 {+ return 0+ }+ if isLastBucket {+ return bucket.lastValue+ }++ switch metricType {+ case "memory", "disk":+ return bucket.sum / float64(bucket.count)+ default:+ return bucket.max+ }+}++// normalizeInfrastructureSummaryMetricPointSeries folds mixed-cadence history+// into equal-time buckets for the infrastructure summary endpoint so long-range+// sparklines do not bunch recent higher-resolution samples at the right edge.+func normalizeInfrastructureSummaryMetricPointSeries(+ points []MetricPoint,+ metricType string,+ duration time.Duration,+ windowEndMillis int64,+) []MetricPoint {+ targetPoints := targetInfrastructureSummarySeriesPoints(duration)+ if len(points) <= targetPoints || targetPoints < 2 || duration <= 0 {+ return points+ }++ durationMillis := int64(duration / time.Millisecond)+ if durationMillis <= 0 {+ return points+ }++ windowStartMillis := windowEndMillis - durationMillis+ bucketCount := targetPoints+ buckets := make([]infrastructureSummaryBucket, bucketCount)+ firstNonEmpty := -1+ lastNonEmpty := -1++ for _, point := range points {+ if point.Timestamp < windowStartMillis || point.Timestamp > windowEndMillis {+ continue+ }+ bucketIndex := int(((point.Timestamp - windowStartMillis) * int64(bucketCount)) / durationMillis)+ if bucketIndex < 0 {+ bucketIndex = 0+ }+ if bucketIndex >= bucketCount {+ bucketIndex = bucketCount - 1+ }++ bucket := &buckets[bucketIndex]+ if bucket.count == 0 {+ bucket.max = point.Value+ bucket.firstTimestamp = point.Timestamp+ if firstNonEmpty == -1 {+ firstNonEmpty = bucketIndex+ }+ } else if point.Value > bucket.max {+ bucket.max = point.Value+ }+ bucket.count+++ bucket.sum += point.Value+ bucket.lastTimestamp = point.Timestamp+ bucket.lastValue = point.Value+ lastNonEmpty = bucketIndex+ }++ if firstNonEmpty == -1 || lastNonEmpty == -1 {+ return points+ }++ result := make([]MetricPoint, 0, targetPoints)+ for bucketIndex := 0; bucketIndex < bucketCount; bucketIndex++ {+ bucket := buckets[bucketIndex]+ if bucket.count == 0 {+ continue+ }++ bucketStartMillis := windowStartMillis + (int64(bucketIndex)*durationMillis)/int64(bucketCount)+ bucketEndMillis := windowStartMillis + (int64(bucketIndex+1)*durationMillis)/int64(bucketCount)+ timestamp := bucketStartMillis + (bucketEndMillis-bucketStartMillis)/2+ switch bucketIndex {+ case firstNonEmpty:+ timestamp = bucket.firstTimestamp+ case lastNonEmpty:+ timestamp = bucket.lastTimestamp+ }++ result = append(result, MetricPoint{+ Timestamp: timestamp,+ Value: aggregateInfrastructureSummaryBucketValue(+ metricType,+ bucket,+ bucketIndex == lastNonEmpty,+ ),+ })+ }++ if len(result) == 0 {+ return points+ }+ return result+}++func normalizeInfrastructureSummaryChartSeries(+ metrics map[string][]MetricPoint,+ duration time.Duration,+ windowEndMillis int64,+) {+ for metricType, points := range metrics {+ metrics[metricType] = normalizeInfrastructureSummaryMetricPointSeries(+ points,+ metricType,+ duration,+ windowEndMillis,+ )+ }+}+// sparklineMetrics lists the metric types consumed by summary sparklines// and density maps. Metrics not in this set are omitted to keep payloads small.var sparklineMetrics = map[string]bool{@@ -6222,6 +6380,7 @@ func (r *Router) handleInfrastructureCharts(w http.ResponseWriter, req *http.Req}}}+ normalizeInfrastructureSummaryChartSeries(nodeData[nid], duration, currentTime)}// Process Docker hosts - batch-load historical data (1-2 SQL calls instead of N).@@ -6276,6 +6435,7 @@ func (r *Router) handleInfrastructureCharts(w http.ResponseWriter, req *http.Req}dockerHostData[dhID]["disk"] = []MetricPoint{{Timestamp: currentTime, Value: diskPercent}}}+ normalizeInfrastructureSummaryChartSeries(dockerHostData[dhID], duration, currentTime)}// Process unified agents - batch-load historical data (1-2 SQL calls instead of N).@@ -6319,6 +6479,7 @@ func (r *Router) handleInfrastructureCharts(w http.ResponseWriter, req *http.ReqagentData[hID]["memory"] = []MetricPoint{{Timestamp: currentTime, Value: h.MemoryPercent()}}agentData[hID]["disk"] = []MetricPoint{{Timestamp: currentTime, Value: h.DiskPercent()}}}+ normalizeInfrastructureSummaryChartSeries(agentData[hID], duration, currentTime)}countNodePoints := func(metricsMap map[string]NodeChartData) int {