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
Bucket workload charts by time window
rcourtman4c4882b505ab
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 26dabc7635..00e1e258c0 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -132,6 +132,7 @@ management, and fleet control surfaces.8. Preserve backend-owned Pulse Mobile relay runtime credential minting in those same shared `internal/api/` auth/security helpers so lifecycle-adjacent setup and install flows reuse the canonical mobile token route instead of reintroducing wildcard or browser-authored runtime token bundles.9. Preserve the dedicated backend-owned `relay:mobile:access` capability and its governed backward-compatible route inventory plus the shared helper call sites around it, so lifecycle-adjacent setup and install flows do not widen the mobile device credential back into general AI chat/execute scope ownership.10. Preserve shipped security-doc guidance in shared lifecycle setup helpers so `internal/api/config_setup_handlers.go` and adjacent install/setup runtime paths point operators at the running build's local security documentation route rather than GitHub `main` links.+11. Keep shared `internal/api/router.go` workload-chart downsampling presentation-only: when that router caps mixed-cadence workload history into equal-time buckets for operator-facing cards, lifecycle-adjacent setup and fleet surfaces must not reuse the shaped chart samples as heartbeat, enrollment, or last-seen authority.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 1c69d7cdbc..a0a06fc5fa 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -174,6 +174,7 @@ Own canonical runtime payload shapes between backend and frontend.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.+24. Keep long-range workload chart transport time-proportional on the shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and workload chart consumers must cap mixed-cadence workload history by equal-time buckets rather than raw point index for the per-workload and aggregate workload chart APIs, so 7-day and 30-day workload cards do not bunch recent samples at the right edge just because recent telemetry is stored more densely.## 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 dc78a9da43..373cd2102d 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -9,7 +9,7 @@"contract_file": "docs/release-control/v6/internal/subsystems/performance-and-scalability.md","status_file": "docs/release-control/v6/internal/status.json","registry_file": "docs/release-control/v6/internal/subsystems/registry.json",- "dependency_subsystem_ids": ["frontend-primitives"]+ "dependency_subsystem_ids": ["api-contracts", "frontend-primitives"]}```@@ -165,6 +165,7 @@ regression protection.23. Extend grouped dashboard row windowing, reveal-index clamping, overscan math, and per-group visible-slice derivation through `frontend-modern/src/components/Dashboard/useGroupedTableWindowing.ts`, and extend viewport event wiring through `frontend-modern/src/components/Dashboard/useDashboardWorkloadViewportSync.ts` rather than rebuilding scroll handlers, mounted-row budgets, viewport listeners, or group-slice math inside `frontend-modern/src/components/Dashboard/useDashboardWorkloadDerivedState.ts`24. Extend dashboard shell rendering through `frontend-modern/src/components/Dashboard/DashboardStateCards.tsx`, `frontend-modern/src/components/Dashboard/DashboardWorkloadTable.tsx`, and `frontend-modern/src/components/Dashboard/DashboardStatsStrip.tsx` rather than accreting loading cards, workload table markup, or stats-strip presentation back into `frontend-modern/src/components/Dashboard/Dashboard.tsx`25. Extend dashboard workload table shell ownership through `frontend-modern/src/components/Dashboard/WorkloadTableHeader.tsx` and `frontend-modern/src/components/Dashboard/WorkloadPanel.tsx` rather than rebuilding sortable header markup, grouped node rows, row expansion, or guest-drawer rendering inside `frontend-modern/src/components/Dashboard/DashboardWorkloadTable.tsx`+26. Keep long-range workload chart capping time-proportional across `frontend-modern/src/components/Workloads/WorkloadsSummary.tsx`, `frontend-modern/src/api/charts.ts`, and `internal/api/router.go`: when the workload hot path caps mixed-cadence history for top cards, it must bucket by time window rather than raw point index so 7-day and 30-day workload cards stay visually even without relaxing the protected payload budget.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex f12690b5e6..0b74d47cf7 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -96,6 +96,7 @@ querying, and the operator-facing storage health presentation layer.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.+33. Keep workload chart downsampling presentation-only on that same adjacent shared API boundary. When `internal/api/router.go` caps mixed-cadence workload history into equal-time buckets for operator-facing workload cards, storage and recovery may consume the resulting visual context only; they must not reinterpret those shaped chart samples as recovery freshness windows, backup cadence, or restore evidence.## Forbidden Pathsdiff --git a/internal/api/charts_test.go b/internal/api/charts_test.goindex 4920652a2c..ab76b5b28c 100644--- a/internal/api/charts_test.go+++ b/internal/api/charts_test.go@@ -339,6 +339,120 @@ func TestNormalizeInfrastructureSummaryMetricPointSeriesAveragesPlateauMetrics(t}}+func TestTargetWorkloadsSummarySeriesPoints(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ duration time.Duration+ want int+ }{+ {name: "zero_defaults_to_minimum", duration: 0, want: workloadsSummaryMinSeriesPoints},+ {name: "one_hour_keeps_minute_resolution", duration: time.Hour, want: 60},+ {name: "four_hours_caps_at_maximum", duration: 4 * time.Hour, want: workloadsSummaryMaxSeriesPoints},+ {name: "seven_days_caps_at_maximum", duration: 7 * 24 * time.Hour, want: workloadsSummaryMaxSeriesPoints},+ }++ for _, tt := range tests {+ tt := tt+ t.Run(tt.name, func(t *testing.T) {+ if got := targetWorkloadsSummarySeriesPoints(tt.duration); got != tt.want {+ t.Fatalf("targetWorkloadsSummarySeriesPoints(%v) = %d, want %d", tt.duration, got, tt.want)+ }+ })+ }+}++func TestCapMetricPointSeriesSmoothsMixedCadenceTail(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})++ capped := capMetricPointSeries(points, 24)+ if len(capped) > 24 {+ t.Fatalf("expected capped point count <= 24, got %d", len(capped))+ }+ if capped[0].Timestamp != points[0].Timestamp {+ t.Fatalf("expected first timestamp %d, got %d", points[0].Timestamp, capped[0].Timestamp)+ }+ if capped[len(capped)-1].Timestamp != points[len(points)-1].Timestamp {+ t.Fatalf("expected latest timestamp %d, got %d", points[len(points)-1].Timestamp, capped[len(capped)-1].Timestamp)+ }++ recentWindowStart := now.Add(-24 * time.Hour).UnixMilli()+ recentCount := 0+ for _, point := range capped {+ if point.Timestamp >= recentWindowStart {+ recentCount+++ }+ }+ if recentCount > 6 {+ t.Fatalf("expected day-proportional capped points, got %d points in the final day", recentCount)+ }+}++func TestNormalizeWorkloadsSummaryMetricPointSeriesSmoothsMixedCadenceTail(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 := normalizeWorkloadsSummaryMetricPointSeries(WorkloadsSummaryMetricData{+ P50: append([]MetricPoint(nil), points...),+ P95: append([]MetricPoint(nil), points...),+ }, duration)+ if len(normalized.P50) > workloadsSummaryMaxSeriesPoints {+ t.Fatalf("expected p50 point count <= %d, got %d", workloadsSummaryMaxSeriesPoints, len(normalized.P50))+ }+ if len(normalized.P95) > workloadsSummaryMaxSeriesPoints {+ t.Fatalf("expected p95 point count <= %d, got %d", workloadsSummaryMaxSeriesPoints, len(normalized.P95))+ }+ if normalized.P50[len(normalized.P50)-1].Timestamp != now.UnixMilli() {+ t.Fatalf("expected latest p50 timestamp %d, got %d", now.UnixMilli(), normalized.P50[len(normalized.P50)-1].Timestamp)+ }+ if normalized.P95[len(normalized.P95)-1].Timestamp != now.UnixMilli() {+ t.Fatalf("expected latest p95 timestamp %d, got %d", now.UnixMilli(), normalized.P95[len(normalized.P95)-1].Timestamp)+ }++ recentWindowStart := now.Add(-24 * time.Hour).UnixMilli()+ recentCount := 0+ for _, point := range normalized.P50 {+ if point.Timestamp >= recentWindowStart {+ recentCount+++ }+ }+ if recentCount > 20 {+ t.Fatalf("expected day-proportional workload summary buckets, got %d recent p50 points", recentCount)+ }+}+func TestDockerMetricKeyFormat(t *testing.T) {t.Parallel()diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex e7ae312c4f..c9a587a45a 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -349,6 +349,237 @@ func TestContract_InfrastructureChartsNormalizeLongRangeMixedCadence(t *testing.}}+func TestContract_WorkloadChartsCapLongRangeMixedCadenceByTime(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",+ }}+ state.VMs = []models.VM{{+ ID: "vm-contract-1",+ VMID: 101,+ Name: "vm-contract-1",+ Node: "node-contract-1",+ Instance: "pve1",+ Status: "running",+ CPU: 0.75,+ Memory: models.Memory{Usage: 42.0},+ Disk: models.Disk{Usage: 55.0},+ NetworkIn: 128,+ NetworkOut: 256,+ DiskRead: 512,+ DiskWrite: 256,+ }}+ syncTestResourceStore(t, monitor, state)++ readState := monitor.GetUnifiedReadStateOrSnapshot()+ vms := readState.VMs()+ if len(vms) != 1 {+ t.Fatalf("expected 1 vm view, got %d", len(vms))+ }+ sourceID := strings.TrimSpace(vms[0].SourceID())+ if sourceID == "" {+ t.Fatal("expected vm source ID")+ }++ 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, 2000)+ appendMetric := func(ts time.Time, percentValue, rateValue float64) {+ for _, metricType := range []string{"cpu", "memory", "disk"} {+ seed = append(seed, metrics.WriteMetric{+ ResourceType: "vm",+ ResourceID: sourceID,+ MetricType: metricType,+ Value: percentValue,+ Timestamp: ts,+ Tier: metrics.TierMinute,+ })+ }+ for _, metricType := range []string{"diskread", "diskwrite", "netin", "netout"} {+ seed = append(seed, metrics.WriteMetric{+ ResourceType: "vm",+ ResourceID: sourceID,+ MetricType: metricType,+ Value: rateValue,+ Timestamp: ts,+ Tier: metrics.TierMinute,+ })+ }+ }+ for ts := windowStart; ts.Before(now.Add(-24 * time.Hour)); ts = ts.Add(65 * time.Minute) {+ appendMetric(ts, 20, 50)+ }+ for ts := now.Add(-24 * time.Hour); ts.Before(now.Add(-2 * time.Hour)); ts = ts.Add(2 * time.Minute) {+ appendMetric(ts, 40, 75)+ }+ for ts := now.Add(-2 * time.Hour); ts.Before(now); ts = ts.Add(time.Minute) {+ appendMetric(ts, 60, 100)+ }+ appendMetric(now, 75, 125)+ store.WriteBatchSync(seed)++ router := &Router{monitor: monitor}+ req := httptest.NewRequest(http.MethodGet, "/api/charts/workloads?range=7d&maxPoints=30", nil)+ rec := httptest.NewRecorder()+ router.handleWorkloadCharts(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }++ var decoded WorkloadChartsResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {+ t.Fatalf("unmarshal workload charts response: %v", err)+ }++ if len(decoded.ChartData) != 1 {+ t.Fatalf("expected 1 workload chart entry, got %d", len(decoded.ChartData))+ }+ var cpuSeries []MetricPoint+ for _, chartData := range decoded.ChartData {+ cpuSeries = chartData["cpu"]+ break+ }+ if len(cpuSeries) == 0 {+ t.Fatal("expected capped cpu series")+ }+ if len(cpuSeries) > 30 {+ t.Fatalf("expected cpu series <= 30 points, got %d", 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)+ }++ recentWindowStart := now.Add(-24 * time.Hour).UnixMilli()+ recentCount := 0+ for _, point := range cpuSeries {+ if point.Timestamp >= recentWindowStart {+ recentCount+++ }+ }+ if recentCount > 8 {+ t.Fatalf("expected day-proportional capped workload points, got %d recent cpu points", recentCount)+ }+}++func TestContract_WorkloadsSummaryChartsNormalizeLongRangeMixedCadence(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",+ }}+ state.VMs = []models.VM{{+ ID: "vm-contract-1",+ VMID: 101,+ Name: "vm-contract-1",+ Node: "node-contract-1",+ Instance: "pve1",+ Status: "running",+ CPU: 0.75,+ Memory: models.Memory{Usage: 42.0},+ Disk: models.Disk{Usage: 55.0},+ NetworkIn: 128,+ NetworkOut: 256,+ }}+ syncTestResourceStore(t, monitor, state)++ readState := monitor.GetUnifiedReadStateOrSnapshot()+ vms := readState.VMs()+ if len(vms) != 1 {+ t.Fatalf("expected 1 vm view, got %d", len(vms))+ }+ sourceID := strings.TrimSpace(vms[0].SourceID())+ if sourceID == "" {+ t.Fatal("expected vm source ID")+ }++ 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, 1500)+ appendMetric := func(ts time.Time, percentValue, rateValue float64) {+ for _, metricType := range []string{"cpu", "memory", "disk"} {+ seed = append(seed, metrics.WriteMetric{+ ResourceType: "vm",+ ResourceID: sourceID,+ MetricType: metricType,+ Value: percentValue,+ Timestamp: ts,+ Tier: metrics.TierMinute,+ })+ }+ for _, metricType := range []string{"netin", "netout"} {+ seed = append(seed, metrics.WriteMetric{+ ResourceType: "vm",+ ResourceID: sourceID,+ MetricType: metricType,+ Value: rateValue,+ Timestamp: ts,+ Tier: metrics.TierMinute,+ })+ }+ }+ for ts := windowStart; ts.Before(now.Add(-24 * time.Hour)); ts = ts.Add(65 * time.Minute) {+ appendMetric(ts, 20, 50)+ }+ for ts := now.Add(-24 * time.Hour); ts.Before(now.Add(-2 * time.Hour)); ts = ts.Add(2 * time.Minute) {+ appendMetric(ts, 40, 75)+ }+ for ts := now.Add(-2 * time.Hour); ts.Before(now); ts = ts.Add(time.Minute) {+ appendMetric(ts, 60, 100)+ }+ appendMetric(now, 75, 125)+ store.WriteBatchSync(seed)++ router := &Router{monitor: monitor}+ req := httptest.NewRequest(http.MethodGet, "/api/charts/workloads-summary?range=7d", nil)+ rec := httptest.NewRecorder()+ router.handleWorkloadsSummaryCharts(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }++ var decoded WorkloadsSummaryChartsResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {+ t.Fatalf("unmarshal workloads summary charts response: %v", err)+ }++ if len(decoded.CPU.P50) == 0 {+ t.Fatal("expected normalized workload summary p50 series")+ }+ if len(decoded.CPU.P50) > workloadsSummaryMaxSeriesPoints {+ t.Fatalf("expected workload summary p50 <= %d points, got %d", workloadsSummaryMaxSeriesPoints, len(decoded.CPU.P50))+ }+ if len(decoded.CPU.P95) > workloadsSummaryMaxSeriesPoints {+ t.Fatalf("expected workload summary p95 <= %d points, got %d", workloadsSummaryMaxSeriesPoints, len(decoded.CPU.P95))+ }+ if decoded.CPU.P50[len(decoded.CPU.P50)-1].Timestamp != now.UnixMilli() {+ t.Fatalf("expected latest workload summary timestamp %d, got %d", now.UnixMilli(), decoded.CPU.P50[len(decoded.CPU.P50)-1].Timestamp)+ }++ recentWindowStart := now.Add(-24 * time.Hour).UnixMilli()+ recentCount := 0+ for _, point := range decoded.CPU.P50 {+ if point.Timestamp >= recentWindowStart {+ recentCount+++ }+ }+ if recentCount > 20 {+ t.Fatalf("expected day-proportional summary buckets, got %d recent p50 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 314dad4fcc..ce2384de73 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -5501,7 +5501,7 @@ func appContainerChartRequest(container *unifiedresources.DockerContainerView) (}, true}-func capMetricPointSeries(points []MetricPoint, maxPoints int) []MetricPoint {+func capMetricPointSeriesByIndex(points []MetricPoint, maxPoints int) []MetricPoint {if len(points) <= maxPoints || maxPoints <= 0 {return points}@@ -5534,28 +5534,98 @@ func capMetricPointSeries(points []MetricPoint, maxPoints int) []MetricPoint {const (infrastructureSummaryMinSeriesPoints = 24infrastructureSummaryMaxSeriesPoints = 96+ workloadsSummaryMinSeriesPoints = 24+ workloadsSummaryMaxSeriesPoints = 96)-type infrastructureSummaryBucket struct {- count int- sum float64- max float64- firstTimestamp int64- lastTimestamp int64- lastValue float64+// capMetricPointSeries keeps mixed-cadence series visually proportional across+// the selected time window. Index-based capping over-selects recent dense+// samples, which bunches the right edge on long ranges.+func capMetricPointSeries(points []MetricPoint, maxPoints int) []MetricPoint {+ if len(points) <= maxPoints || maxPoints <= 0 {+ return points+ }+ if maxPoints == 1 {+ return []MetricPoint{points[len(points)-1]}+ }++ startTimestamp := points[0].Timestamp+ endTimestamp := points[len(points)-1].Timestamp+ if endTimestamp <= startTimestamp {+ return capMetricPointSeriesByIndex(points, maxPoints)+ }++ bucketSpan := float64(endTimestamp-startTimestamp) / float64(maxPoints-1)+ if bucketSpan < 1 {+ return capMetricPointSeriesByIndex(points, maxPoints)+ }++ type timeBucketRepresentative struct {+ point MetricPoint+ distance float64+ ok bool+ }++ buckets := make([]timeBucketRepresentative, maxPoints)+ for _, point := range points {+ index := int(math.Round(float64(point.Timestamp-startTimestamp) / bucketSpan))+ if index < 0 {+ index = 0+ }+ if index >= maxPoints {+ index = maxPoints - 1+ }++ targetTimestamp := float64(startTimestamp) + bucketSpan*float64(index)+ distance := math.Abs(float64(point.Timestamp) - targetTimestamp)+ current := buckets[index]+ if !current.ok ||+ distance < current.distance ||+ (distance == current.distance && point.Timestamp > current.point.Timestamp) {+ buckets[index] = timeBucketRepresentative{+ point: point,+ distance: distance,+ ok: true,+ }+ }+ }++ result := make([]MetricPoint, 0, maxPoints)+ result = append(result, points[0])+ lastAddedTimestamp := points[0].Timestamp+ for index := 1; index < maxPoints-1; index++ {+ bucket := buckets[index]+ if !bucket.ok {+ continue+ }+ if bucket.point.Timestamp <= lastAddedTimestamp {+ continue+ }+ result = append(result, bucket.point)+ lastAddedTimestamp = bucket.point.Timestamp+ }++ lastPoint := points[len(points)-1]+ if lastPoint.Timestamp <= lastAddedTimestamp {+ result[len(result)-1] = lastPoint+ return result+ }++ result = append(result, lastPoint)+ return result}-func targetInfrastructureSummarySeriesPoints(duration time.Duration) int {+func targetBoundedSummarySeriesPoints(duration time.Duration, minPoints, maxPoints int) int {if duration <= 0 {- return infrastructureSummaryMinSeriesPoints+ return minPoints}target := int(duration / time.Minute)- if target < infrastructureSummaryMinSeriesPoints {- target = infrastructureSummaryMinSeriesPoints+ if target < minPoints {+ target = minPoints}- if target > infrastructureSummaryMaxSeriesPoints {- target = infrastructureSummaryMaxSeriesPoints+ if target > maxPoints {+ target = maxPoints}if target < 2 {target = 2@@ -5563,6 +5633,31 @@ func targetInfrastructureSummarySeriesPoints(duration time.Duration) int {return target}+type infrastructureSummaryBucket struct {+ count int+ sum float64+ max float64+ firstTimestamp int64+ lastTimestamp int64+ lastValue float64+}++func targetInfrastructureSummarySeriesPoints(duration time.Duration) int {+ return targetBoundedSummarySeriesPoints(+ duration,+ infrastructureSummaryMinSeriesPoints,+ infrastructureSummaryMaxSeriesPoints,+ )+}++func targetWorkloadsSummarySeriesPoints(duration time.Duration) int {+ return targetBoundedSummarySeriesPoints(+ duration,+ workloadsSummaryMinSeriesPoints,+ workloadsSummaryMaxSeriesPoints,+ )+}+func aggregateInfrastructureSummaryBucketValue(metricType string,bucket infrastructureSummaryBucket,@@ -6840,6 +6935,16 @@ func summaryMetricPointCount(metric WorkloadsSummaryMetricData) int {return len(metric.P50) + len(metric.P95)}+func normalizeWorkloadsSummaryMetricPointSeries(+ metric WorkloadsSummaryMetricData,+ duration time.Duration,+) WorkloadsSummaryMetricData {+ targetPoints := targetWorkloadsSummarySeriesPoints(duration)+ metric.P50 = capMetricPointSeries(metric.P50, targetPoints)+ metric.P95 = capMetricPointSeries(metric.P95, targetPoints)+ return metric+}+func latestSummaryMetricValue(points []monitoring.MetricPoint, fallback float64, clamp func(float64) float64) float64 {if len(points) == 0 {return clamp(fallback)@@ -7397,6 +7502,10 @@ func (r *Router) handleWorkloadsSummaryCharts(w http.ResponseWriter, req *http.RnetworkMetric := buildWorkloadsSummaryMetric(buckets, func(bucket *workloadSummaryBuckets) []float64 {return bucket.network})+ cpuMetric = normalizeWorkloadsSummaryMetricPointSeries(cpuMetric, duration)+ memoryMetric = normalizeWorkloadsSummaryMetricPointSeries(memoryMetric, duration)+ diskMetric = normalizeWorkloadsSummaryMetricPointSeries(diskMetric, duration)+ networkMetric = normalizeWorkloadsSummaryMetricPointSeries(networkMetric, duration)summaryPointCount := summaryMetricPointCount(cpuMetric) +summaryMetricPointCount(memoryMetric) +diff --git a/tests/integration/tests/44-workloads-chart-spacing.spec.ts b/tests/integration/tests/44-workloads-chart-spacing.spec.tsnew file mode 100644index 0000000000..ec7b0470ae--- /dev/null+++ b/tests/integration/tests/44-workloads-chart-spacing.spec.ts@@ -0,0 +1,140 @@+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { expect, test as base } from '@playwright/test';++import { createAuthenticatedStorageState, getMockMode, setMockMode } from './helpers';++const __dirname = path.dirname(fileURLToPath(import.meta.url));++type WorkerFixtures = {+ authStorageStatePath: string;+};++type MetricPoint = {+ timestamp: number;+ value: number;+};++type ChartData = {+ cpu?: MetricPoint[];+};++type WorkloadChartsResponse = {+ data?: Record<string, ChartData>;+ dockerData?: Record<string, ChartData>;+};++const WORKLOADS_SCREENSHOT_PATH = path.resolve(+ __dirname,+ '..',+ '..',+ 'tmp',+ 'workloads-summary-7d-spacing.png',+);++let mockModeWasEnabled: boolean | null = null;++const test = base.extend<{}, WorkerFixtures>({+ storageState: async ({ authStorageStatePath }, use) => {+ await use(authStorageStatePath);+ },+ authStorageStatePath: [async ({ browser }, use, workerInfo) => {+ const storageStatePath = path.resolve(+ __dirname,+ '..',+ '..',+ 'tmp',+ 'playwright-auth',+ `workloads-chart-spacing-${workerInfo.project.name}.json`,+ );+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });+ await createAuthenticatedStorageState(browser, storageStatePath);+ try {+ await use(storageStatePath);+ } finally {+ fs.rmSync(storageStatePath, { force: true });+ }+ }, { scope: 'worker' }],+});++async function ensureMockModeEnabled(page: import('@playwright/test').Page): Promise<void> {+ const state = await getMockMode(page);+ if (mockModeWasEnabled === null) {+ mockModeWasEnabled = state.enabled;+ }+ if (!state.enabled) {+ await setMockMode(page, true);+ }+}++function average(values: number[]): number {+ if (values.length === 0) return 0;+ return values.reduce((sum, value) => sum + value, 0) / values.length;+}++function longestCPUSeries(payload: WorkloadChartsResponse): MetricPoint[] {+ const candidates = [+ ...Object.values(payload.data || {}).map((chartData) => chartData.cpu || []),+ ...Object.values(payload.dockerData || {}).map((chartData) => chartData.cpu || []),+ ];+ return candidates.sort((a, b) => b.length - a.length)[0] || [];+}++test.describe.serial('Workloads chart spacing', () => {+ test.setTimeout(180_000);++ test.afterAll(async ({ browser }) => {+ if (mockModeWasEnabled === null) {+ return;+ }++ const context = await browser.newContext();+ const page = await context.newPage();+ try {+ const current = await getMockMode(page);+ if (current.enabled !== mockModeWasEnabled) {+ await setMockMode(page, mockModeWasEnabled);+ }+ } finally {+ await context.close();+ }+ });++ test('keeps 7d workload charts time-proportional on the live page', async ({ page }, testInfo) => {+ test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop runtime proof');++ await ensureMockModeEnabled(page);++ await page.goto('/workloads', { waitUntil: 'domcontentloaded' });+ await expect(page.getByTestId('workloads-summary')).toBeVisible();++ const responsePromise = page.waitForResponse((response) => {+ const url = response.url();+ return response.request().method() === 'GET' &&+ url.includes('/api/charts/workloads?') &&+ url.includes('range=7d');+ });++ await page.getByRole('button', { name: '7d', exact: true }).click();+ const response = await responsePromise;+ expect(response.ok()).toBeTruthy();++ const payload = (await response.json()) as WorkloadChartsResponse;+ const cpuSeries = longestCPUSeries(payload);+ expect(cpuSeries.length).toBeGreaterThan(40);++ const deltas = cpuSeries+ .slice(1)+ .map((point, index) => point.timestamp - cpuSeries[index].timestamp)+ .filter((delta) => delta > 0);+ const firstAverage = average(deltas.slice(0, 10));+ const lastAverage = average(deltas.slice(-10));++ expect(lastAverage).toBeGreaterThan(firstAverage * 0.5);+ expect(lastAverage).toBeLessThan(firstAverage * 1.5);++ fs.mkdirSync(path.dirname(WORKLOADS_SCREENSHOT_PATH), { recursive: true });+ await page.getByTestId('workloads-summary').screenshot({ path: WORKLOADS_SCREENSHOT_PATH });+ });+});