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
Speed up demo mock chart loading
rcourtman4692d88a0dcd
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 60bf51cde3..01c543d6f4 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -204,6 +204,12 @@ and curve shape from the same canonical resource-role registry, so database,cache, backup, web, and storage workloads keep believable long-range behaviorinstead of switching from one generic seeded pattern to a different recentruntime pattern.+That same mock chart boundary also owns request-path efficiency. Demo chart+reads must reuse monitor-owned downsampled mock history for the current mock+sampler generation instead of regenerating or re-downsampling the same seeded+timeline on every endpoint hit. When seeded mock history is rebuilt or a live+mock tick advances, monitoring must invalidate that cache so preview charts+stay current without paying repeated per-request synthesis cost.That same mock-runtime owner now also owns demo-scenario curation. Thecanonical `internal/mock/fixture_graph.go` path may project an authored demoestate over generic fixture synthesis, but that authored layer must staydiff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 7e80720f61..7adf6e523a 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -874,6 +874,23 @@ func TestMockNativePollersDeferToCanonicalMockSampler(t *testing.T) {}}+func TestMockChartCacheRemainsMonitorOwned(t *testing.T) {+ data, err := os.ReadFile("monitor.go")+ if err != nil {+ t.Fatalf("failed to read monitor.go: %v", err)+ }+ source := string(data)++ for _, snippet := range []string{+ "mockChartCacheMu sync.RWMutex",+ "mockChartMapCache map[mockChartMetricMapCacheKey]map[string][]MetricPoint",+ } {+ if !strings.Contains(source, snippet) {+ t.Fatalf("monitor.go must contain %q", snippet)+ }+ }+}+func TestUnifiedPhysicalDiskMetricsUseCanonicalDiskHistoryPath(t *testing.T) {data, err := os.ReadFile("monitor.go")if err != nil {diff --git a/internal/monitoring/mock_metrics_history.go b/internal/monitoring/mock_metrics_history.goindex 50b81f28e1..077096b26d 100644--- a/internal/monitoring/mock_metrics_history.go+++ b/internal/monitoring/mock_metrics_history.go@@ -1568,6 +1568,7 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {// Keep mock trend generation in-memory only so production history in the// persistent metrics store remains untouched while mock mode is active.seedMockMetricsHistory(m.metricsHistory, nil, graph, normalizeMockMetricTimestamp(time.Now(), cfg.SampleInterval), seedDuration, cfg.SampleInterval)+ m.invalidateMockChartCaches()m.mockMetricsWg.Add(1)go func() {@@ -1585,6 +1586,7 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {continue}recordMockStateToMetricsHistory(m.metricsHistory, nil, mock.CurrentFixtureGraph(), normalizeMockMetricTimestamp(time.Now(), cfg.SampleInterval))+ m.invalidateMockChartCaches()}}}()@@ -1608,6 +1610,7 @@ func (m *Monitor) stopMockMetricsSampler() {if cancel != nil {cancel()m.mockMetricsWg.Wait()+ m.invalidateMockChartCaches()log.Info().Msg("mock metrics history sampler stopped")}}diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.goindex 3e76d8173e..5b5c4e8ab5 100644--- a/internal/monitoring/mock_metrics_history_test.go+++ b/internal/monitoring/mock_metrics_history_test.go@@ -699,6 +699,71 @@ func TestStartMockMetricsSampler_DoesNotClearExistingMetricsStoreData(t *testing}}+func TestStartAndStopMockMetricsSampler_ClearStaleMockChartCaches(t *testing.T) {+ previousEnabled := mock.IsMockEnabled()+ previousConfig := mock.GetConfig()+ t.Cleanup(func() {+ mock.SetEnabled(false)+ mock.SetMockConfig(previousConfig)+ if previousEnabled {+ mock.SetEnabled(true)+ mock.SetMockConfig(previousConfig)+ }+ })++ cfg := mock.DefaultConfig+ cfg.NodeCount = 1+ cfg.VMsPerNode = 0+ cfg.LXCsPerNode = 0+ cfg.DockerHostCount = 0+ cfg.DockerContainersPerHost = 0+ cfg.GenericHostCount = 0+ cfg.K8sClusterCount = 0+ cfg.K8sNodesPerCluster = 0+ cfg.K8sPodsPerCluster = 0+ cfg.K8sDeploymentsPerCluster = 0++ mock.SetEnabled(false)+ mock.SetMockConfig(cfg)+ mock.SetEnabled(true)++ monitor := &Monitor{+ metricsHistory: NewMetricsHistory(128, 24*time.Hour),+ mockChartMapCache: map[mockChartMetricMapCacheKey]map[string][]MetricPoint{+ {+ kind: "guest",+ resourceType: "vm",+ resourceID: "vm-stale",+ duration: time.Hour,+ }: {+ "cpu": {{Timestamp: time.Now().UTC().Add(-time.Minute), Value: 42}},+ },+ },+ }++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ monitor.startMockMetricsSampler(ctx)+ if got := len(monitor.mockChartMapCache); got != 0 {+ t.Fatalf("expected mock sampler start to clear stale chart caches, got %d entries", got)+ }++ monitor.mockChartMapCache[mockChartMetricMapCacheKey{+ kind: "storage",+ resourceType: "storage",+ resourceID: "pool-stale",+ duration: time.Hour,+ }] = map[string][]MetricPoint{+ "usage": {{Timestamp: time.Now().UTC(), Value: 88}},+ }++ monitor.stopMockMetricsSampler()+ if got := len(monitor.mockChartMapCache); got != 0 {+ t.Fatalf("expected mock sampler stop to clear chart caches, got %d entries", got)+ }+}+func TestStartMockMetricsSampler_SeedsCanonicalMockResourceHistory(t *testing.T) {previousEnabled := mock.IsMockEnabled()previousConfig := mock.GetConfig()diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex bbe42b6568..7e29ab0a81 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -998,6 +998,8 @@ type Monitor struct {// cluster node via SSH to its siblings. Keyed by lowercase node name.clusterSensorsMu sync.RWMutexclusterSensorsCache map[string]clusterSensorsCacheEntry+ mockChartCacheMu sync.RWMutex+ mockChartMapCache map[mockChartMetricMapCacheKey]map[string][]MetricPoint}// clusterSensorsCacheEntry stores temperature data collected by a sibling agent via SSH.diff --git a/internal/monitoring/monitor_metrics.go b/internal/monitoring/monitor_metrics.goindex a583c46efb..52d33e1b6b 100644--- a/internal/monitoring/monitor_metrics.go+++ b/internal/monitoring/monitor_metrics.go@@ -1,6 +1,7 @@package monitoringimport (+ "sort""strings""time"@@ -36,8 +37,23 @@ const (shortRangeCoverageMaxSlack = 2 * time.Minute)+const (+ mockChartPointTargetShortRange = 20+ mockChartPointTargetMedium = 32+ mockChartPointTargetLong = 48+ mockChartPointTargetExtended = 64+)+var storageChartMetricTypes = []string{"usage", "used", "avail", "total"}+type mockChartMetricMapCacheKey struct {+ kind string+ resourceType string+ resourceID string+ aux string+ duration time.Duration+}+// MonitorGuestMetricHistoryProvider optionally exposes source-native guest// metric history through the canonical chart boundary when local Pulse history// is shallow.@@ -80,14 +96,11 @@ func (m *Monitor) GetGuestMetrics(guestID string, duration time.Duration) map[st// sqlResourceType/sqlResourceID are the type/id used in the SQLite store// (e.g. "dockerContainer"/"abc123").func (m *Monitor) GetGuestMetricsForChart(inMemoryKey, sqlResourceType, sqlResourceID string, duration time.Duration) map[string][]MetricPoint {+ inMemoryResult := m.GetGuestMetrics(inMemoryKey, duration)if mock.IsMockEnabled() {- if synthetic := mockGuestMetricsForChart(sqlResourceType, sqlResourceID, duration); len(synthetic) > 0 {- return synthetic- }- return m.GetGuestMetrics(inMemoryKey, duration)+ return m.mockGuestMetricsForChart(inMemoryKey, sqlResourceType, sqlResourceID, duration, inMemoryResult)}- inMemoryResult := m.GetGuestMetrics(inMemoryKey, duration)if hasSufficientChartMapCoverage(inMemoryResult, duration) {return inMemoryResult}@@ -114,11 +127,15 @@ func (m *Monitor) GetNodeMetrics(nodeID string, metricType string, duration time// GetNodeMetricsForChart returns node metrics for a single metric type,// falling back to SQLite + LTTB for longer ranges.func (m *Monitor) GetNodeMetricsForChart(nodeID, metricType string, duration time.Duration) []MetricPoint {+ var inMemoryPoints []MetricPoint+ if m != nil && m.metricsHistory != nil {+ inMemoryPoints = m.metricsHistory.GetNodeMetrics(nodeID, metricType, duration)+ }+if mock.IsMockEnabled() {- return mockNodeMetricsForChart(nodeID, []string{metricType}, duration)[metricType]+ return m.mockNodeMetricsForChart(nodeID, metricType, duration, inMemoryPoints)}- inMemoryPoints := m.metricsHistory.GetNodeMetrics(nodeID, metricType, duration)if m.metricsStore == nil {return inMemoryPoints}@@ -156,14 +173,11 @@ func (m *Monitor) GetDiskMetrics(resourceID string, metricType string, duration// display, preferring in-memory data for freshness and falling back to the// persistent store when coverage is shallow.func (m *Monitor) GetDiskMetricsForChart(resourceID string, metricType string, duration time.Duration) []MetricPoint {+ inMemoryPoints := m.GetDiskMetrics(resourceID, metricType, duration)if mock.IsMockEnabled() {- if synthetic := mockDiskMetricsForChart(resourceID, []string{metricType}, duration); len(synthetic) > 0 {- return synthetic[metricType]- }- return m.GetDiskMetrics(resourceID, metricType, duration)+ return m.mockDiskMetricsForChart(resourceID, metricType, duration, inMemoryPoints)}- inMemoryPoints := m.GetDiskMetrics(resourceID, metricType, duration)if hasSufficientChartSeriesCoverage(inMemoryPoints, duration) {return inMemoryPoints}@@ -186,7 +200,7 @@ func (m *Monitor) GetStorageMetricsForChart(storageID string, duration time.DurainMemoryResult = m.metricsHistory.GetAllStorageMetrics(storageID, duration)}if mock.IsMockEnabled() {- return m.mockStorageMetricsForChart(storageID, duration, inMemoryResult)+ return m.mockStorageMetricsForChartCached(storageID, duration, inMemoryResult)}if m.metricsStore == nil {return inMemoryResult@@ -222,10 +236,7 @@ func (m *Monitor) GetPhysicalDiskTemperatureCharts(duration time.Duration) map[sif m == nil {return nil}-- if mock.IsMockEnabled() {- return m.mockPhysicalDiskTemperatureCharts(duration)- }+ mockEnabled := mock.IsMockEnabled()readState := m.GetUnifiedReadStateOrSnapshot()if readState == nil {@@ -286,24 +297,32 @@ func (m *Monitor) GetPhysicalDiskTemperatureCharts(duration time.Duration) map[sinMemoryHistory[d.resourceID] = m.metricsHistory.GetDiskMetrics(d.resourceID, "smart_temp", duration)}}- batchMetrics := m.queryStoreBatchMetricMapWithGapFill("disk", resourceIDs, duration)- nativeHistory := m.nativePhysicalDiskTemperatureHistory(duration)+ var batchMetrics map[string]map[string][]MetricPoint+ var nativeHistory map[string][]MetricPoint+ if !mockEnabled {+ batchMetrics = m.queryStoreBatchMetricMapWithGapFill("disk", resourceIDs, duration)+ nativeHistory = m.nativePhysicalDiskTemperatureHistory(duration)+ }// Phase 3: Build result entries.result := make(map[string]DiskChartEntry, len(disks))for _, d := range disks {tempPoints := cloneMetricSeries(inMemoryHistory[d.resourceID])- if resMetrics, ok := batchMetrics[d.resourceID]; ok {- if pts, found := resMetrics["smart_temp"]; found {- if shouldPreferMetricSeries(tempPoints, pts, duration) {- tempPoints = cloneMetricSeries(pts)+ if mockEnabled {+ tempPoints = m.mockDiskMetricsForChart(d.resourceID, "smart_temp", duration, tempPoints)+ } else {+ if resMetrics, ok := batchMetrics[d.resourceID]; ok {+ if pts, found := resMetrics["smart_temp"]; found {+ if shouldPreferMetricSeries(tempPoints, pts, duration) {+ tempPoints = cloneMetricSeries(pts)+ }}}- }- if nativePoints, ok := nativeHistory[d.resourceID]; ok {- nativePoints = lttb(nativePoints, chartDownsampleTarget)- if shouldPreferMetricSeries(tempPoints, nativePoints, duration) {- tempPoints = cloneMetricSeries(nativePoints)+ if nativePoints, ok := nativeHistory[d.resourceID]; ok {+ nativePoints = lttb(nativePoints, chartDownsampleTarget)+ if shouldPreferMetricSeries(tempPoints, nativePoints, duration) {+ tempPoints = cloneMetricSeries(nativePoints)+ }}}@@ -455,11 +474,14 @@ func (m *Monitor) GetGuestMetricsForChartBatch(if mock.IsMockEnabled() {result := make(map[string]map[string][]MetricPoint, len(requests))for _, req := range requests {- if synthetic := mockGuestMetricsForChart(sqlResourceType, req.SQLResourceID, duration); len(synthetic) > 0 {- result[req.SQLResourceID] = synthetic- continue- }- result[req.SQLResourceID] = m.GetGuestMetrics(req.InMemoryKey, duration)+ inMemory := m.GetGuestMetrics(req.InMemoryKey, duration)+ result[req.SQLResourceID] = m.mockGuestMetricsForChart(+ req.InMemoryKey,+ sqlResourceType,+ req.SQLResourceID,+ duration,+ inMemory,+ )}return result}@@ -536,7 +558,15 @@ func (m *Monitor) GetNodeMetricsForChartBatch(if mock.IsMockEnabled() {result := make(map[string]map[string][]MetricPoint, len(nodeIDs))for _, nodeID := range nodeIDs {- result[nodeID] = mockNodeMetricsForChart(nodeID, metricTypes, duration)+ nodeResult := make(map[string][]MetricPoint, len(metricTypes))+ for _, metricType := range metricTypes {+ var inMemoryPoints []MetricPoint+ if m != nil && m.metricsHistory != nil {+ inMemoryPoints = m.metricsHistory.GetNodeMetrics(nodeID, metricType, duration)+ }+ nodeResult[metricType] = m.mockNodeMetricsForChart(nodeID, metricType, duration, inMemoryPoints)+ }+ result[nodeID] = nodeResult}return result}@@ -609,7 +639,7 @@ func (m *Monitor) GetStorageMetricsForChartBatch(if m.metricsHistory != nil {inMemory = m.metricsHistory.GetAllStorageMetrics(sid, duration)}- result[sid] = m.mockStorageMetricsForChart(sid, duration, inMemory)+ result[sid] = m.mockStorageMetricsForChartCached(sid, duration, inMemory)}return result}@@ -812,6 +842,224 @@ func cloneMetricPointMap(metrics map[string][]MetricPoint) map[string][]MetricPoreturn cloned}+func mockChartPointTarget(duration time.Duration) int {+ switch {+ case duration <= time.Hour:+ return mockChartPointTargetShortRange+ case duration <= 6*time.Hour:+ return mockChartPointTargetMedium+ case duration <= 24*time.Hour:+ return mockChartPointTargetLong+ default:+ return mockChartPointTargetExtended+ }+}++func downsampleMetricSeriesForMockChart(points []MetricPoint, duration time.Duration) []MetricPoint {+ target := mockChartPointTarget(duration)+ return lttb(cloneMetricSeries(points), target)+}++func downsampleMetricMapForMockChart(metrics map[string][]MetricPoint, duration time.Duration) map[string][]MetricPoint {+ if len(metrics) == 0 {+ return map[string][]MetricPoint{}+ }+ downsampled := make(map[string][]MetricPoint, len(metrics))+ for metricType, points := range metrics {+ downsampled[metricType] = downsampleMetricSeriesForMockChart(points, duration)+ }+ return downsampled+}++func normalizeMockChartMetricTypes(metricTypes []string) string {+ if len(metricTypes) == 0 {+ return ""+ }+ normalized := make([]string, 0, len(metricTypes))+ for _, metricType := range metricTypes {+ trimmed := strings.TrimSpace(metricType)+ if trimmed == "" {+ continue+ }+ normalized = append(normalized, trimmed)+ }+ if len(normalized) == 0 {+ return ""+ }+ sort.Strings(normalized)+ return strings.Join(normalized, ",")+}++func (m *Monitor) readMockChartMetricMapCache(+ key mockChartMetricMapCacheKey,+) (map[string][]MetricPoint, bool) {+ if m == nil {+ return nil, false+ }++ m.mockChartCacheMu.RLock()+ defer m.mockChartCacheMu.RUnlock()++ if m.mockChartMapCache == nil {+ return nil, false+ }+ cached, ok := m.mockChartMapCache[key]+ if !ok {+ return nil, false+ }+ return cloneMetricPointMap(cached), true+}++func (m *Monitor) writeMockChartMetricMapCache(+ key mockChartMetricMapCacheKey,+ metrics map[string][]MetricPoint,+) map[string][]MetricPoint {+ cloned := cloneMetricPointMap(metrics)+ if m == nil {+ return cloned+ }++ m.mockChartCacheMu.Lock()+ defer m.mockChartCacheMu.Unlock()++ if m.mockChartMapCache == nil {+ m.mockChartMapCache = make(map[mockChartMetricMapCacheKey]map[string][]MetricPoint)+ }+ m.mockChartMapCache[key] = cloneMetricPointMap(cloned)+ return cloned+}++func (m *Monitor) invalidateMockChartCaches() {+ if m == nil {+ return+ }++ m.mockChartCacheMu.Lock()+ defer m.mockChartCacheMu.Unlock()++ if m.mockChartMapCache != nil {+ clear(m.mockChartMapCache)+ }+}++func (m *Monitor) mockGuestMetricsForChart(+ inMemoryKey,+ sqlResourceType,+ sqlResourceID string,+ duration time.Duration,+ inMemoryResult map[string][]MetricPoint,+) map[string][]MetricPoint {+ key := mockChartMetricMapCacheKey{+ kind: "guest",+ resourceType: strings.TrimSpace(sqlResourceType),+ resourceID: strings.TrimSpace(sqlResourceID),+ aux: strings.TrimSpace(inMemoryKey),+ duration: duration,+ }+ if cached, ok := m.readMockChartMetricMapCache(key); ok {+ return cached+ }++ var computed map[string][]MetricPoint+ switch {+ case hasSufficientChartMapCoverage(inMemoryResult, duration):+ computed = downsampleMetricMapForMockChart(inMemoryResult, duration)+ case len(sqlResourceID) > 0:+ if synthetic := mockGuestMetricsForChart(sqlResourceType, sqlResourceID, duration); len(synthetic) > 0 {+ computed = downsampleMetricMapForMockChart(synthetic, duration)+ }+ }+ if computed == nil {+ computed = downsampleMetricMapForMockChart(inMemoryResult, duration)+ }+ return m.writeMockChartMetricMapCache(key, computed)+}++func (m *Monitor) mockNodeMetricsForChart(+ nodeID string,+ metricType string,+ duration time.Duration,+ inMemoryPoints []MetricPoint,+) []MetricPoint {+ cacheKey := mockChartMetricMapCacheKey{+ kind: "node",+ resourceType: "node",+ resourceID: strings.TrimSpace(nodeID),+ aux: normalizeMockChartMetricTypes([]string{metricType}),+ duration: duration,+ }+ if cached, ok := m.readMockChartMetricMapCache(cacheKey); ok {+ return cloneMetricSeries(cached[metricType])+ }++ computed := map[string][]MetricPoint{}+ if hasSufficientChartSeriesCoverage(inMemoryPoints, duration) {+ computed[metricType] = downsampleMetricSeriesForMockChart(inMemoryPoints, duration)+ } else {+ computed[metricType] = downsampleMetricSeriesForMockChart(+ mockNodeMetricsForChart(nodeID, []string{metricType}, duration)[metricType],+ duration,+ )+ }+ return cloneMetricSeries(m.writeMockChartMetricMapCache(cacheKey, computed)[metricType])+}++func (m *Monitor) mockDiskMetricsForChart(+ resourceID string,+ metricType string,+ duration time.Duration,+ inMemoryPoints []MetricPoint,+) []MetricPoint {+ cacheKey := mockChartMetricMapCacheKey{+ kind: "disk",+ resourceType: "disk",+ resourceID: strings.TrimSpace(resourceID),+ aux: normalizeMockChartMetricTypes([]string{metricType}),+ duration: duration,+ }+ if cached, ok := m.readMockChartMetricMapCache(cacheKey); ok {+ return cloneMetricSeries(cached[metricType])+ }++ computed := map[string][]MetricPoint{}+ if hasSufficientChartSeriesCoverage(inMemoryPoints, duration) {+ computed[metricType] = downsampleMetricSeriesForMockChart(inMemoryPoints, duration)+ } else {+ computed[metricType] = downsampleMetricSeriesForMockChart(+ mockDiskMetricsForChart(resourceID, []string{metricType}, duration)[metricType],+ duration,+ )+ }+ return cloneMetricSeries(m.writeMockChartMetricMapCache(cacheKey, computed)[metricType])+}++func (m *Monitor) mockStorageMetricsForChartCached(+ storageID string,+ duration time.Duration,+ inMemoryResult map[string][]MetricPoint,+) map[string][]MetricPoint {+ cacheKey := mockChartMetricMapCacheKey{+ kind: "storage",+ resourceType: "storage",+ resourceID: strings.TrimSpace(storageID),+ duration: duration,+ }+ if cached, ok := m.readMockChartMetricMapCache(cacheKey); ok {+ return cached+ }++ var computed map[string][]MetricPoint+ if hasSufficientChartMapCoverageForMetrics(inMemoryResult, duration, storageChartMetricTypes) {+ computed = downsampleMetricMapForMockChart(inMemoryResult, duration)+ } else {+ computed = downsampleMetricMapForMockChart(+ m.mockStorageMetricsForChart(storageID, duration, inMemoryResult),+ duration,+ )+ }+ return m.writeMockChartMetricMapCache(cacheKey, computed)+}+func mergeGuestMetricHistory(base, candidate map[string][]MetricPoint, duration time.Duration) map[string][]MetricPoint {return mergeMetricHistory(base, candidate, duration)}diff --git a/internal/monitoring/monitor_metrics_chart_fallback_test.go b/internal/monitoring/monitor_metrics_chart_fallback_test.goindex ccb1fbee70..5116dd0556 100644--- a/internal/monitoring/monitor_metrics_chart_fallback_test.go+++ b/internal/monitoring/monitor_metrics_chart_fallback_test.go@@ -476,7 +476,7 @@ func TestGetPhysicalDiskTemperatureCharts_UsesNativeHistoryWhenStoreCoverageShal}}-func TestGetPhysicalDiskTemperatureCharts_SkipsNativeHistoryInMockMode(t *testing.T) {+func TestGetPhysicalDiskTemperatureCharts_PrefersSeededMockHistoryInMockMode(t *testing.T) {previous := mock.IsMockEnabled()mock.SetEnabled(true)defer mock.SetEnabled(previous)@@ -510,9 +510,9 @@ func TestGetPhysicalDiskTemperatureCharts_SkipsNativeHistoryInMockMode(t *testinoffset time.Durationvalue float64}{- {-4 * time.Minute, 32},- {-2 * time.Minute, 33},- {0, 34},+ {-58 * time.Minute, 32},+ {-30 * time.Minute, 33},+ {-1 * time.Minute, 34},} {monitor.metricsHistory.AddDiskMetric(resourceID, "smart_temp", sample.value, now.Add(sample.offset))}@@ -522,7 +522,12 @@ func TestGetPhysicalDiskTemperatureCharts_SkipsNativeHistoryInMockMode(t *testinif !ok {t.Fatalf("expected chart entry for canonical disk metric id, got %#v", charts)}- assertFollowsCanonicalMockSeries(t, entry.Temperature, "disk", resourceID, "smart_temp")+ if len(entry.Temperature) != 3 {+ t.Fatalf("expected seeded in-memory history to win, got %+v", entry.Temperature)+ }+ if entry.Temperature[0].Value != 32 || entry.Temperature[len(entry.Temperature)-1].Value != 34 {+ t.Fatalf("expected seeded mock history values to win, got %+v", entry.Temperature)+ }}func TestGetGuestMetricsForChart_UsesCanonicalMockSamplerInMockMode(t *testing.T) {@@ -543,6 +548,96 @@ func TestGetGuestMetricsForChart_UsesCanonicalMockSamplerInMockMode(t *testing.TassertFollowsCanonicalMockSeries(t, result["memory"], "vm", "vm-1", "memory")}+func TestGetGuestMetricsForChart_PrefersSeededMockHistoryInMockMode(t *testing.T) {+ previous := mock.IsMockEnabled()+ mock.SetEnabled(true)+ defer mock.SetEnabled(previous)++ monitor := newChartFallbackTestMonitor(t)+ now := time.Now().UTC().Truncate(time.Second)+ duration := time.Hour++ for _, sample := range []struct {+ offset time.Duration+ value float64+ }{+ {-58 * time.Minute, 12.5},+ {-30 * time.Minute, 37.25},+ {-1 * time.Minute, 81.75},+ } {+ monitor.metricsHistory.AddGuestMetric("vm-1", "memory", sample.value, now.Add(sample.offset))+ }++ result := monitor.GetGuestMetricsForChart("vm-1", "vm", "vm-1", duration)+ if len(result["memory"]) != 3 {+ t.Fatalf("expected seeded in-memory guest history to win, got %+v", result["memory"])+ }+ if result["memory"][0].Value != 12.5 || result["memory"][len(result["memory"])-1].Value != 81.75 {+ t.Fatalf("expected seeded guest values to win, got %+v", result["memory"])+ }+}++func TestGetGuestMetricsForChartBatch_PrefersSeededMockHistoryInMockMode(t *testing.T) {+ previous := mock.IsMockEnabled()+ mock.SetEnabled(true)+ defer mock.SetEnabled(previous)++ monitor := newChartFallbackTestMonitor(t)+ now := time.Now().UTC().Truncate(time.Second)+ duration := time.Hour++ for _, sample := range []struct {+ offset time.Duration+ value float64+ }{+ {-58 * time.Minute, 9.5},+ {-30 * time.Minute, 26.0},+ {-1 * time.Minute, 64.25},+ } {+ monitor.metricsHistory.AddGuestMetric("vm-1", "cpu", sample.value, now.Add(sample.offset))+ }++ result := monitor.GetGuestMetricsForChartBatch("vm", []GuestChartRequest{{+ InMemoryKey: "vm-1",+ SQLResourceID: "vm-1",+ }}, duration)+ if len(result["vm-1"]["cpu"]) != 3 {+ t.Fatalf("expected seeded in-memory guest batch history to win, got %+v", result["vm-1"]["cpu"])+ }+ if result["vm-1"]["cpu"][0].Value != 9.5 || result["vm-1"]["cpu"][len(result["vm-1"]["cpu"])-1].Value != 64.25 {+ t.Fatalf("expected seeded guest batch values to win, got %+v", result["vm-1"]["cpu"])+ }+}++func TestGetGuestMetricsForChartBatch_DownsamplesDenseSeededMockHistory(t *testing.T) {+ previous := mock.IsMockEnabled()+ mock.SetEnabled(true)+ defer mock.SetEnabled(previous)++ monitor := newChartFallbackTestMonitor(t)+ now := time.Now().UTC().Truncate(time.Minute)+ duration := time.Hour++ for i := 0; i < 61; i++ {+ monitor.metricsHistory.AddGuestMetric("vm-1", "cpu", float64(i), now.Add(-time.Duration(60-i)*time.Minute))+ }++ result := monitor.GetGuestMetricsForChartBatch("vm", []GuestChartRequest{{+ InMemoryKey: "vm-1",+ SQLResourceID: "vm-1",+ }}, duration)+ cpu := result["vm-1"]["cpu"]+ if len(cpu) == 0 {+ t.Fatal("expected downsampled seeded mock history")+ }+ if len(cpu) >= 61 {+ t.Fatalf("expected dense seeded mock history to be downsampled, got %d points", len(cpu))+ }+ if len(cpu) > 20 {+ t.Fatalf("expected 1h mock guest history to cap at 20 points, got %d", len(cpu))+ }+}+func TestGetStorageMetricsForChart_UsesCanonicalMockSamplerInMockMode(t *testing.T) {previous := mock.IsMockEnabled()mock.SetEnabled(true)@@ -573,6 +668,72 @@ func TestGetStorageMetricsForChart_UsesCanonicalMockSamplerInMockMode(t *testing}}+func TestGetStorageMetricsForChart_PrefersSeededMockHistoryInMockMode(t *testing.T) {+ previous := mock.IsMockEnabled()+ mock.SetEnabled(true)+ defer mock.SetEnabled(previous)++ monitor := newChartFallbackTestMonitor(t)+ now := time.Now().UTC().Truncate(time.Second)+ duration := time.Hour++ type sample struct {+ offset time.Duration+ value float64+ }+ metricsByType := map[string][]sample{+ "usage": {{-58 * time.Minute, 40}, {-30 * time.Minute, 41}, {-1 * time.Minute, 42}},+ "used": {{-58 * time.Minute, 400}, {-30 * time.Minute, 410}, {-1 * time.Minute, 420}},+ "avail": {{-58 * time.Minute, 600}, {-30 * time.Minute, 590}, {-1 * time.Minute, 580}},+ "total": {{-58 * time.Minute, 1000}, {-30 * time.Minute, 1000}, {-1 * time.Minute, 1000}},+ }+ for metricType, samples := range metricsByType {+ for _, sample := range samples {+ monitor.metricsHistory.AddStorageMetric("storage-1", metricType, sample.value, now.Add(sample.offset))+ }+ }++ result := monitor.GetStorageMetricsForChart("storage-1", duration)+ if len(result["usage"]) != 3 {+ t.Fatalf("expected seeded in-memory storage history to win, got %+v", result["usage"])+ }+ if result["usage"][0].Value != 40 || result["usage"][len(result["usage"])-1].Value != 42 {+ t.Fatalf("expected seeded storage values to win, got %+v", result["usage"])+ }+ if len(result["used"]) != 3 || len(result["avail"]) != 3 || len(result["total"]) != 3 {+ t.Fatalf("expected complete seeded storage metrics, got %+v", result)+ }+}++func TestGetStorageMetricsForChart_DownsamplesDenseSeededMockHistory(t *testing.T) {+ previous := mock.IsMockEnabled()+ mock.SetEnabled(true)+ defer mock.SetEnabled(previous)++ monitor := newChartFallbackTestMonitor(t)+ now := time.Now().UTC().Truncate(time.Minute)+ duration := time.Hour++ for i := 0; i < 61; i++ {+ ts := now.Add(-time.Duration(60-i) * time.Minute)+ monitor.metricsHistory.AddStorageMetric("storage-1", "usage", float64(40+i%5), ts)+ monitor.metricsHistory.AddStorageMetric("storage-1", "used", float64(400+i), ts)+ monitor.metricsHistory.AddStorageMetric("storage-1", "avail", float64(600-i), ts)+ monitor.metricsHistory.AddStorageMetric("storage-1", "total", 1000, ts)+ }++ result := monitor.GetStorageMetricsForChart("storage-1", duration)+ if len(result["usage"]) == 0 {+ t.Fatal("expected downsampled seeded storage history")+ }+ if len(result["usage"]) >= 61 {+ t.Fatalf("expected dense seeded storage history to be downsampled, got %d points", len(result["usage"]))+ }+ if len(result["usage"]) > 20 {+ t.Fatalf("expected 1h mock storage history to cap at 20 points, got %d", len(result["usage"]))+ }+}+func TestGetGuestMetricsForChart_UsesGapFillLookbackWhenRequestedRangeIsEmpty(t *testing.T) {t.Parallel()diff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.goindex 7d8798b616..9f27247d48 100644--- a/internal/monitoring/monitor_metrics_slo_test.go+++ b/internal/monitoring/monitor_metrics_slo_test.go@@ -416,7 +416,8 @@ func TestSLO_GetGuestMetricsForChartBatch_DoesNotStitchSparseStoreTailOntoCovere// This sparse late store point models the old stitched-tail behavior. In// mock mode the batch chart path must ignore persisted history entirely and- // serve the canonical sampler timeline instead.+ // reuse the seeded in-memory mock history instead of synthesizing or+ // stitching a different tail.writeRawMetricBatch(t, monitor.metricsStore, "vm", "vm-1", "memory", []MetricPoint{{Timestamp: now.Add(-1 * time.Minute), Value: 21},})@@ -427,20 +428,68 @@ func TestSLO_GetGuestMetricsForChartBatch_DoesNotStitchSparseStoreTailOntoCovere}}, duration)memoryPoints := result["vm-1"]["memory"]- if len(memoryPoints) < 2 {- t.Fatalf("expected canonical mock memory series, got %+v", memoryPoints)- }- checkIndices := []int{0, len(memoryPoints) / 2, len(memoryPoints) - 1}- seen := map[int]struct{}{}- for _, idx := range checkIndices {- if _, ok := seen[idx]; ok {- continue+ if len(memoryPoints) != len(inMemorySeries) {+ t.Fatalf("expected seeded mock memory series, got %+v", memoryPoints)+ }+ for idx, want := range inMemorySeries {+ if memoryPoints[idx].Timestamp != want.Timestamp || memoryPoints[idx].Value != want.Value {+ t.Fatalf("memoryPoints[%d] = %+v, want seeded %+v", idx, memoryPoints[idx], want)}- seen[idx] = struct{}{}+ }+}- want := mock.SampleMetric("vm", "vm-1", "memory", memoryPoints[idx].Timestamp)- if memoryPoints[idx].Value != want {- t.Fatalf("memoryPoints[%d] = %+v, want canonical %.12f", idx, memoryPoints[idx], want)- }+func TestMockChartCacheInvalidatesAfterMockHistoryRefresh(t *testing.T) {+ previous := mock.IsMockEnabled()+ mock.SetEnabled(true)+ t.Cleanup(func() { mock.SetEnabled(previous) })++ monitor := newChartFallbackTestMonitor(t)+ now := time.Now().UTC().Truncate(time.Second)+ duration := time.Hour++ for _, point := range []MetricPoint{+ {Timestamp: now.Add(-58 * time.Minute), Value: 41},+ {Timestamp: now.Add(-36 * time.Minute), Value: 43},+ {Timestamp: now.Add(-14 * time.Minute), Value: 47},+ {Timestamp: now.Add(-2 * time.Minute), Value: 49},+ } {+ monitor.metricsHistory.AddGuestMetric("vm-1", "cpu", point.Value, point.Timestamp)+ }++ first := monitor.GetGuestMetricsForChartBatch("vm", []GuestChartRequest{{+ InMemoryKey: "vm-1",+ SQLResourceID: "vm-1",+ }}, duration)+ firstCPU := first["vm-1"]["cpu"]+ if len(firstCPU) == 0 {+ t.Fatal("expected cached mock guest chart series")+ }+ if got := len(monitor.mockChartMapCache); got == 0 {+ t.Fatal("expected mock chart cache to populate after chart read")+ }++ newestTimestamp := now.Add(-30 * time.Second)+ monitor.metricsHistory.AddGuestMetric("vm-1", "cpu", 99, newestTimestamp)++ monitor.invalidateMockChartCaches()+ if got := len(monitor.mockChartMapCache); got != 0 {+ t.Fatalf("expected mock chart cache to clear after invalidation, got %d entries", got)+ }++ refreshed := monitor.GetGuestMetricsForChartBatch("vm", []GuestChartRequest{{+ InMemoryKey: "vm-1",+ SQLResourceID: "vm-1",+ }}, duration)+ refreshedCPU := refreshed["vm-1"]["cpu"]+ if len(refreshedCPU) == 0 {+ t.Fatal("expected refreshed mock guest chart series")+ }++ lastPoint := refreshedCPU[len(refreshedCPU)-1]+ if !lastPoint.Timestamp.Equal(newestTimestamp) || lastPoint.Value != 99 {+ t.Fatalf("expected refreshed mock chart tail %+v, got %+v", MetricPoint{+ Timestamp: newestTimestamp,+ Value: 99,+ }, lastPoint)}}