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
Optimize compact storage summary chart path
rcourtman4ca488101e8b
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex cc6c8b307a..27a7e98ce8 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -208,6 +208,12 @@ an add-only capacity posture.problem rows, and top-resource rankings for dashboard hot paths, butlifecycle surfaces must not treat `/api/resources/dashboard-summary` asinstall inventory authority, enrollment proof, or fleet freshness truth.+ The same presentation-only boundary now covers compact storage summary+ chart reads as well. Shared `/api/charts/storage-summary` transport may+ request only the canonical `used` and `avail` storage series needed for the+ dashboard capacity sparkline, and lifecycle surfaces must not reinterpret+ the omitted `usage` or `total` series as missing lifecycle telemetry or+ enrollment-state evidence.Dashboard storage trend consumers on that shared router boundary must now reuse the single `/api/storage-charts` summary response instead of fanning out per-pool `/api/metrics-store/history` reads, and lifecycle surfaces still must treat that batched storage summary transport as presentation context only rather than install, enrollment, or freshness truth.12. Keep lifecycle installer fallback pinned to published release lineage only.When `internal/api/unified_agent.go` has to proxy `/install.sh` ordiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 1676916ac4..aba6aed5d4 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -197,6 +197,15 @@ when the disabled candidate no longer counts toward monitored-system capacity.25. Keep chart timestamp precision canonical on that same shared API surface: when `internal/api/router.go` serializes monitoring history into infrastructure or workload chart payloads, it must preserve canonical millisecond timestamps from the shared monitoring timeline instead of rounding through whole-second conversion, so seeded mock history and live appends collapse onto one operator-visible timeline instead of appearing as duplicated tail samples.26. Keep storage chart identity canonical on that same shared API surface: the shared storage charts endpoint must key pool and physical-disk series by the resolved unified-resource `MetricsTarget.ResourceID`, not by canonical resource IDs or page-local aliases, so storage rows, focused summary cards, sticky summary shells, and detail charts all address the same history series in live and mock mode.27. Keep synthetic summary-chart fallback identity canonical on that same shared API surface: when `internal/api/router.go` has to synthesize mock summary history for infrastructure, workloads, or storage cards, it must derive the fallback from canonical `resourceType`, `resourceID`, and `metricType` ownership instead of raw min/max seed-prefix helpers, so range changes and runtime mock updates stay on one governed timeline.+ The same compact chart boundary also owns aggregate-only storage summary+ transport. `/api/charts/storage-summary` may batch only the canonical+ `used` and `avail` storage series required for the aggregate capacity+ sparkline, and it must not regress into the full per-pool storage payload+ or a fetch-all-metrics backend path just because the storage page carries a+ broader chart surface.+ When mock mode is active, that same endpoint must come from the+ monitor-owned aggregate summary cache rather than rehydrating each pool+ chart on request.28. Keep workload-chart response identity canonical on that same shared API surface: `internal/api/router.go`, `internal/api/contract_test.go`, and workload summary consumers must emit provider-backed VM and system-container series under the same canonical workload IDs that workloads page rows use, while resolving history through the unified `MetricsTarget.ResourceID`, so hover and focus selection do not fall off for provider-backed rows.29. Keep the hosted account portal bootstrap intelligible without duplicatechrome. `internal/cloudcp/portal/page.go`, the maintained portal frontenddiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 01c543d6f4..4b99b568ab 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -210,6 +210,17 @@ sampler generation instead of regenerating or re-downsampling the same seededtimeline on every endpoint hit. When seeded mock history is rebuilt or a livemock tick advances, monitoring must invalidate that cache so preview chartsstay current without paying repeated per-request synthesis cost.+That same sampler-owned cache contract also covers compact dashboard summary+reads. When live mock ticks advance, monitoring must repopulate the canonical+24-hour aggregate `/api/charts/storage-summary` cache inside the sampler path+instead of leaving the first operator request after each tick to rebuild+per-pool mock storage charts on demand.+That same metrics-hot-path ownership also includes metric-type selection for+compact summary reads. When dashboard infrastructure or storage summary routes+request only a subset of canonical chart series, `internal/monitoring/monitor_metrics.go`+must preserve that narrowed metric set through the batch store fallback path+instead of querying every metric type for each resource and discarding most of+the payload afterward.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/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex ebe4c02e4d..e0d59ccb29 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -274,6 +274,15 @@ REST fetch. Dashboard trend loading must also key off stable target identityand selected range only; reconciled resource snapshots that do not change theeffective target set must not trigger duplicate infrastructure or storagechart requests.+That same protected metrics-store boundary now also owns selected-series batch+queries. Compact dashboard routes that request only CPU/memory or only+storage `used`/`avail` capacity must keep that metric-type filter all the way+through `pkg/metrics/store.go` instead of fetching every series for every+resource and discarding the extra payload in higher layers.+That same hot path now also covers mock-mode cache warmth. The canonical+24-hour `/api/charts/storage-summary` dashboard transport must stay prewarmed+across live mock sampler ticks so the first dashboard request after a refresh+does not pay the full aggregate-storage synthesis cost on the operator path.contract instead of inventing an infrastructure-local summary filter branch.For shared line charts on that hot path, the shared sparkline primitive mayisolate the selected series inside the existing render budget, but thatdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex d16d1cb92c..cdf7368aaa 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -180,6 +180,15 @@ querying, and the operator-facing storage health presentation layer.storage-local hard-coded provider arrays.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.+ The same adjacent chart boundary now covers compact storage capacity+ transport. `internal/api/router.go` may batch only the canonical `used`+ and `avail` storage series for `/api/charts/storage-summary`, but storage+ and recovery must not treat the omitted `usage` or `total` series as lost+ recovery truth or widen that compact route back into the full storage-page+ payload.+ In mock mode, that same compact route must stay aggregate-only and+ sampler-prewarmed; storage and recovery must not trigger per-pool chart+ reconstruction on the first dashboard request after each mock refresh.34. Keep storage and recovery websocket reads on the neutral app-runtime boundary. `frontend-modern/src/components/Recovery/RecoveryPointDetails.tsx`, `frontend-modern/src/components/Storage/useStoragePageResources.ts`, and storage/recovery-adjacent dashboard composition may consume live websocket state only through `frontend-modern/src/contexts/appRuntime.ts`, not by importing `frontend-modern/src/App.tsx` or rebuilding shell-local providers.That same dashboard composition boundary also owns compact summary reads.When `frontend-modern/src/pages/Dashboard.tsx` renders storage anddiff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 86e548b571..be263edfb1 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -653,6 +653,46 @@ func TestContract_StorageChartsUseCanonicalMetricsTargetIDs(t *testing.T) {}}+func TestContract_StorageSummaryChartsStayAggregateOnly(t *testing.T) {+ monitor, state, metricsHistory := newTestMonitor(t)+ now := time.Now().UTC().Truncate(time.Second)+ state.Storage = []models.Storage{+ {ID: "store-1", Name: "Store One"},+ {ID: "store-2", Name: "Store Two"},+ }+ metricsHistory.AddStorageMetric("store-1", "used", 400, now)+ metricsHistory.AddStorageMetric("store-1", "avail", 600, now)+ metricsHistory.AddStorageMetric("store-1", "total", 1000, now)+ metricsHistory.AddStorageMetric("store-2", "used", 100, now)+ metricsHistory.AddStorageMetric("store-2", "avail", 900, now)+ metricsHistory.AddStorageMetric("store-2", "total", 1000, now)+ syncTestResourceStore(t, monitor, state)++ router := &Router{monitor: monitor}+ req := httptest.NewRequest(http.MethodGet, "/api/charts/storage-summary?range=24h", nil)+ rec := httptest.NewRecorder()++ router.handleStorageSummaryCharts(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }++ var decoded StorageSummaryTrendResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {+ t.Fatalf("unmarshal storage summary response: %v", err)+ }+ if len(decoded.Capacity) != 1 {+ t.Fatalf("expected one aggregate capacity point, got %+v", decoded.Capacity)+ }+ if decoded.Capacity[0].Value != 25 {+ t.Fatalf("expected aggregate capacity of 25%%, got %+v", decoded.Capacity[0])+ }+ if decoded.Stats.PointCounts.Total != 1 || decoded.Stats.PointCounts.Storage != 1 {+ t.Fatalf("expected aggregate-only point counts, got %+v", decoded.Stats.PointCounts)+ }+}+func TestContract_TrueNASConnectionsDisabledMessageIsExplicit(t *testing.T) {setTrueNASFeatureForTest(t, false)handler, _, _ := newTrueNASHandlersForTest(t, nil)diff --git a/internal/api/router.go b/internal/api/router.goindex 4943560544..0474fc4fba 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -7952,28 +7952,9 @@ func (r *Router) handleStorageSummaryCharts(w http.ResponseWriter, req *http.Reqhttp.Error(w, "Tenant monitor is not available", http.StatusInternalServerError)return}- readState := monitor.GetUnifiedReadStateOrSnapshot()- if readState == nil {- http.Error(w, "State unavailable", http.StatusInternalServerError)- return- }-- storageIDs := make([]string, 0, len(readState.StoragePools()))- for _, pool := range readState.StoragePools() {- if pool == nil {- continue- }- storageID := strings.TrimSpace(pool.SourceID())- if storageID == "" {- continue- }- storageIDs = append(storageIDs, storageID)- }currentTime := time.Now().UnixMilli()- capacity, oldestTimestamp := buildStorageSummaryCapacityTrend(- monitor.GetStorageMetricsForChartBatch(storageIDs, duration),- )+ capacity, oldestTimestamp := monitor.GetStorageSummaryCapacityTrend(duration)if oldestTimestamp == 0 {oldestTimestamp = currentTime}@@ -7985,7 +7966,7 @@ func (r *Router) handleStorageSummaryCharts(w http.ResponseWriter, req *http.Req}resp := EmptyStorageSummaryTrendResponse()- resp.Capacity = capacity+ resp.Capacity = monitorPointsToAPI(capacity)resp.Timestamp = currentTimeresp.Stats = ChartStats{OldestDataTimestamp: oldestTimestamp,@@ -7995,8 +7976,8 @@ func (r *Router) handleStorageSummaryCharts(w http.ResponseWriter, req *http.ReqPrimarySourceHint: primarySourceHint,InMemoryThresholdSecs: int64(inMemoryChartThreshold / time.Second),PointCounts: ChartPointCounts{- Total: len(capacity),- Storage: len(capacity),+ Total: len(resp.Capacity),+ Storage: len(resp.Capacity),},}@@ -8020,78 +8001,6 @@ func monitorPointsToAPI(points []monitoring.MetricPoint) []MetricPoint {return out}-func buildStorageSummaryCapacityTrend(- poolMetrics map[string]map[string][]monitoring.MetricPoint,-) ([]MetricPoint, int64) {- type aggregateBucket struct {- used float64- avail float64- hasUsed bool- hasAvail bool- }-- buckets := make(map[int64]*aggregateBucket)- var oldestTimestamp int64- for _, metrics := range poolMetrics {- for _, point := range metrics["used"] {- timestamp := point.Timestamp.UnixMilli()- bucket := buckets[timestamp]- if bucket == nil {- bucket = &aggregateBucket{}- buckets[timestamp] = bucket- }- bucket.used += point.Value- bucket.hasUsed = true- if oldestTimestamp == 0 || timestamp < oldestTimestamp {- oldestTimestamp = timestamp- }- }- for _, point := range metrics["avail"] {- timestamp := point.Timestamp.UnixMilli()- bucket := buckets[timestamp]- if bucket == nil {- bucket = &aggregateBucket{}- buckets[timestamp] = bucket- }- bucket.avail += point.Value- bucket.hasAvail = true- if oldestTimestamp == 0 || timestamp < oldestTimestamp {- oldestTimestamp = timestamp- }- }- }-- if len(buckets) == 0 {- return nil, oldestTimestamp- }-- timestamps := make([]int64, 0, len(buckets))- for timestamp := range buckets {- timestamps = append(timestamps, timestamp)- }- sort.Slice(timestamps, func(i, j int) bool {- return timestamps[i] < timestamps[j]- })-- out := make([]MetricPoint, 0, len(timestamps))- for _, timestamp := range timestamps {- bucket := buckets[timestamp]- if bucket == nil || !bucket.hasUsed || !bucket.hasAvail {- continue- }- total := bucket.used + bucket.avail- if math.IsNaN(total) || math.IsInf(total, 0) || total <= 0 {- continue- }- out = append(out, MetricPoint{- Timestamp: timestamp,- Value: (bucket.used / total) * 100,- })- }-- return out, oldestTimestamp-}-// handleMetricsStoreStats returns statistics about the persistent metrics storefunc (r *Router) handleMetricsStoreStats(w http.ResponseWriter, req *http.Request) {if req.Method != http.MethodGet {diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 7adf6e523a..d86e35632b 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -824,6 +824,8 @@ func TestMockNativePollersDeferToCanonicalMockSampler(t *testing.T) {"func (m *Monitor) nativePhysicalDiskTemperatureHistory(duration time.Duration) map[string][]MetricPoint {","if mock.IsMockEnabled() {","return nil",+ "func (m *Monitor) prewarmMockDashboardChartCaches() {",+ "_, _ = m.mockStorageSummaryCapacityTrendCached(24 * time.Hour)",},},{@@ -832,6 +834,8 @@ func TestMockNativePollersDeferToCanonicalMockSampler(t *testing.T) {"func mockCanonicalMetricSeries(resourceType, resourceID, metricType string, timestamps []time.Time) []MetricPoint {","values := canonicalMetricSeries(resourceType, resourceID, metricType, timestamps)","return lttb(points, chartDownsampleTarget)",+ "func (m *Monitor) mockStorageSummaryCapacityTrend(duration time.Duration) []MetricPoint {",+ `usageValues := canonicalMetricSeries("storage", storageID, "usage", timestamps)`,},},{@@ -840,6 +844,7 @@ func TestMockNativePollersDeferToCanonicalMockSampler(t *testing.T) {`cpu := mock.SampleMetric("k8s", metricID, "cpu", ts)`,`memory := mock.SampleMetric("k8s", metricID, "memory", ts)`,`ms.Write("k8s", metricID, "memory", memory, ts)`,+ "m.prewarmMockDashboardChartCaches()",},},{diff --git a/internal/monitoring/mock_chart_history.go b/internal/monitoring/mock_chart_history.goindex ecd74e6f7b..5201baecf7 100644--- a/internal/monitoring/mock_chart_history.go+++ b/internal/monitoring/mock_chart_history.go@@ -184,6 +184,66 @@ func (m *Monitor) mockStorageMetricsForChart(storageID string, duration time.Dur}}+func (m *Monitor) mockStorageSummaryCapacityTrend(duration time.Duration) []MetricPoint {+ if m == nil {+ return nil+ }++ readState := m.GetUnifiedReadStateOrSnapshot()+ if readState == nil {+ return nil+ }++ timestamps := mockChartTimestamps(duration)+ if len(timestamps) == 0 {+ return nil+ }++ usedTotals := make([]float64, len(timestamps))+ capacityTotals := make([]float64, len(timestamps))++ for _, pool := range readState.StoragePools() {+ if pool == nil {+ continue+ }++ storageID := strings.TrimSpace(pool.SourceID())+ if storageID == "" {+ continue+ }++ total := m.resolveMockStorageTotal(storageID, nil)+ if total <= 0 {+ continue+ }++ usageValues := canonicalMetricSeries("storage", storageID, "usage", timestamps)+ if len(usageValues) != len(timestamps) {+ continue+ }++ for i, usage := range usageValues {+ usedTotals[i] += total * (clampFloat(usage, 0, 100) / 100.0)+ capacityTotals[i] += total+ }+ }++ points := make([]MetricPoint, 0, len(timestamps))+ for i, ts := range timestamps {+ total := capacityTotals[i]+ if math.IsNaN(total) || math.IsInf(total, 0) || total <= 0 {+ continue+ }++ points = append(points, MetricPoint{+ Timestamp: ts,+ Value: (usedTotals[i] / total) * 100,+ })+ }++ return lttb(points, chartDownsampleTarget)+}+func (m *Monitor) mockPhysicalDiskTemperatureCharts(duration time.Duration) map[string]DiskChartEntry {if m == nil {return nildiff --git a/internal/monitoring/mock_metrics_history.go b/internal/monitoring/mock_metrics_history.goindex 077096b26d..2740e9787d 100644--- a/internal/monitoring/mock_metrics_history.go+++ b/internal/monitoring/mock_metrics_history.go@@ -1569,6 +1569,7 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {// 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.prewarmMockDashboardChartCaches()m.mockMetricsWg.Add(1)go func() {@@ -1587,6 +1588,7 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {}recordMockStateToMetricsHistory(m.metricsHistory, nil, mock.CurrentFixtureGraph(), normalizeMockMetricTimestamp(time.Now(), cfg.SampleInterval))m.invalidateMockChartCaches()+ m.prewarmMockDashboardChartCaches()}}}()diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.goindex 5b5c4e8ab5..92671ce1bc 100644--- a/internal/monitoring/mock_metrics_history_test.go+++ b/internal/monitoring/mock_metrics_history_test.go@@ -745,8 +745,22 @@ func TestStartAndStopMockMetricsSampler_ClearStaleMockChartCaches(t *testing.T)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)+ if _, ok := monitor.mockChartMapCache[mockChartMetricMapCacheKey{+ kind: "guest",+ resourceType: "vm",+ resourceID: "vm-stale",+ duration: time.Hour,+ }]; ok {+ t.Fatalf("expected mock sampler start to clear stale guest chart caches, got %+v", monitor.mockChartMapCache)+ }+ summaryKey := mockChartMetricMapCacheKey{+ kind: "storage-summary",+ resourceType: "storage",+ resourceID: "__aggregate__",+ duration: 24 * time.Hour,+ }+ if _, ok := monitor.mockChartMapCache[summaryKey]; !ok {+ t.Fatalf("expected mock sampler start to prewarm storage summary cache, got %+v", monitor.mockChartMapCache)}monitor.mockChartMapCache[mockChartMetricMapCacheKey{diff --git a/internal/monitoring/monitor_metrics.go b/internal/monitoring/monitor_metrics.goindex 52d33e1b6b..ecbc3c7221 100644--- a/internal/monitoring/monitor_metrics.go+++ b/internal/monitoring/monitor_metrics.go@@ -1,6 +1,7 @@package monitoringimport (+ "math""sort""strings""time"@@ -45,6 +46,7 @@ const ()var storageChartMetricTypes = []string{"usage", "used", "avail", "total"}+var storageSummaryChartMetricTypes = []string{"used", "avail"}type mockChartMetricMapCacheKey struct {kind string@@ -300,7 +302,7 @@ func (m *Monitor) GetPhysicalDiskTemperatureCharts(duration time.Duration) map[svar batchMetrics map[string]map[string][]MetricPointvar nativeHistory map[string][]MetricPointif !mockEnabled {- batchMetrics = m.queryStoreBatchMetricMapWithGapFill("disk", resourceIDs, duration)+ batchMetrics = m.queryStoreBatchMetricMapWithGapFill("disk", resourceIDs, duration, []string{"smart_temp"})nativeHistory = m.nativePhysicalDiskTemperatureHistory(duration)}@@ -406,7 +408,7 @@ func (m *Monitor) currentMetricsTargetStore() MetricsTargetResourceStore {// of the same type in a single batch. If some resources have no data in the// primary window, re-queries those with a broader lookback window.// Returns map[resourceID]map[metricType][]MetricPoint (already downsampled).-func (m *Monitor) queryStoreBatchMetricMapWithGapFill(resourceType string, resourceIDs []string, duration time.Duration) map[string]map[string][]MetricPoint {+func (m *Monitor) queryStoreBatchMetricMapWithGapFill(resourceType string, resourceIDs []string, duration time.Duration, metricTypes []string) map[string]map[string][]MetricPoint {if m == nil || m.metricsStore == nil || len(resourceIDs) == 0 {return nil}@@ -416,7 +418,7 @@ 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.QueryAllBatch(resourceType, ids, from, end, 0)+ sqlResult, err := m.metricsStore.QueryMetricTypesBatch(resourceType, ids, metricTypes, from, end, 0)if err != nil || len(sqlResult) == 0 {return nil}@@ -510,7 +512,7 @@ func (m *Monitor) GetGuestMetricsForChartBatch(storeResults := make(map[string]map[string][]MetricPoint)if m.metricsStore != nil {for _, candidate := range monitorStoreResourceTypeCandidates(sqlResourceType) {- batch := m.queryStoreBatchMetricMapWithGapFill(candidate, needFallback, duration)+ batch := m.queryStoreBatchMetricMapWithGapFill(candidate, needFallback, duration, nil)for id, metricMap := range batch {if existing, ok := storeResults[id]; ok {newSpan := chartMapCoverageSpan(metricMap)@@ -596,7 +598,7 @@ func (m *Monitor) GetNodeMetricsForChartBatch(}// Phase 2: Batch-query store for all nodes that need it.- batchResult := m.queryStoreBatchMetricMapWithGapFill("node", needStore, duration)+ batchResult := m.queryStoreBatchMetricMapWithGapFill("node", needStore, duration, metricTypes)// Phase 3: Merge — per metric type, use store data if better coverage.for _, nid := range needStore {@@ -668,7 +670,7 @@ func (m *Monitor) GetStorageMetricsForChartBatch(}// Phase 2: Batch-query store.- batchResult := m.queryStoreBatchMetricMapWithGapFill("storage", needStore, duration)+ batchResult := m.queryStoreBatchMetricMapWithGapFill("storage", needStore, duration, storageChartMetricTypes)// Phase 3: Merge — use store data if better coverage.for _, id := range needStore {@@ -682,6 +684,107 @@ func (m *Monitor) GetStorageMetricsForChartBatch(return result}+// GetStorageCapacityMetricsForSummaryBatch returns only the canonical capacity+// metrics required for the compact dashboard storage summary card.+func (m *Monitor) GetStorageCapacityMetricsForSummaryBatch(+ storageIDs []string,+ duration time.Duration,+) map[string]map[string][]MetricPoint {+ if m == nil || len(storageIDs) == 0 {+ return nil+ }++ result := make(map[string]map[string][]MetricPoint, len(storageIDs))++ if mock.IsMockEnabled() {+ for _, sid := range storageIDs {+ inMemory := map[string][]MetricPoint{}+ if m.metricsHistory != nil {+ inMemory = filterMetricPointMap(+ m.metricsHistory.GetAllStorageMetrics(sid, duration),+ storageSummaryChartMetricTypes,+ )+ }+ fullMetrics := m.mockStorageMetricsForChartCached(sid, duration, inMemory)+ result[sid] = filterMetricPointMap(fullMetrics, storageSummaryChartMetricTypes)+ }+ return result+ }++ var needStore []string+ for _, sid := range storageIDs {+ inMemory := map[string][]MetricPoint{}+ if m.metricsHistory != nil {+ inMemory = filterMetricPointMap(+ m.metricsHistory.GetAllStorageMetrics(sid, duration),+ storageSummaryChartMetricTypes,+ )+ }+ if m.metricsStore == nil {+ result[sid] = inMemory+ continue+ }+ if hasSufficientChartMapCoverageForMetrics(inMemory, duration, storageSummaryChartMetricTypes) {+ result[sid] = inMemory+ continue+ }+ needStore = append(needStore, sid)+ result[sid] = inMemory+ }++ if len(needStore) == 0 {+ return result+ }++ batchResult := m.queryStoreBatchMetricMapWithGapFill(+ "storage",+ needStore,+ duration,+ storageSummaryChartMetricTypes,+ )+ for _, sid := range needStore {+ storeData, ok := batchResult[sid]+ if !ok {+ continue+ }+ result[sid] = mergeMetricHistory(result[sid], storeData, duration)+ }++ return result+}++func (m *Monitor) GetStorageSummaryCapacityTrend(duration time.Duration) ([]MetricPoint, int64) {+ if m == nil {+ return nil, 0+ }++ if mock.IsMockEnabled() {+ return m.mockStorageSummaryCapacityTrendCached(duration)+ }++ readState := m.GetUnifiedReadStateOrSnapshot()+ if readState == nil {+ return nil, 0+ }++ storageIDs := make([]string, 0, len(readState.StoragePools()))+ for _, pool := range readState.StoragePools() {+ if pool == nil {+ continue+ }++ storageID := strings.TrimSpace(pool.SourceID())+ if storageID == "" {+ continue+ }+ storageIDs = append(storageIDs, storageID)+ }++ return buildStorageSummaryCapacityTrend(+ m.GetStorageCapacityMetricsForSummaryBatch(storageIDs, duration),+ )+}+func (m *Monitor) nativeGuestMetricHistory(resourceType string, duration time.Duration) map[string]map[string][]MetricPoint {providers := m.supplementalProviderSnapshot()if len(providers) == 0 {@@ -942,6 +1045,14 @@ func (m *Monitor) invalidateMockChartCaches() {}}+func (m *Monitor) prewarmMockDashboardChartCaches() {+ if m == nil || !mock.IsMockEnabled() {+ return+ }++ _, _ = m.mockStorageSummaryCapacityTrendCached(24 * time.Hour)+}+func (m *Monitor) mockGuestMetricsForChart(inMemoryKey,sqlResourceType,@@ -1060,6 +1171,24 @@ func (m *Monitor) mockStorageMetricsForChartCached(return m.writeMockChartMetricMapCache(cacheKey, computed)}+func (m *Monitor) mockStorageSummaryCapacityTrendCached(duration time.Duration) ([]MetricPoint, int64) {+ cacheKey := mockChartMetricMapCacheKey{+ kind: "storage-summary",+ resourceType: "storage",+ resourceID: "__aggregate__",+ duration: duration,+ }+ if cached, ok := m.readMockChartMetricMapCache(cacheKey); ok {+ return cached["capacity"], oldestMetricSeriesTimestamp(cached["capacity"])+ }++ computed := m.mockStorageSummaryCapacityTrend(duration)+ cached := m.writeMockChartMetricMapCache(cacheKey, map[string][]MetricPoint{+ "capacity": computed,+ })+ return cached["capacity"], oldestMetricSeriesTimestamp(cached["capacity"])+}+func mergeGuestMetricHistory(base, candidate map[string][]MetricPoint, duration time.Duration) map[string][]MetricPoint {return mergeMetricHistory(base, candidate, duration)}@@ -1079,6 +1208,103 @@ func mergeMetricHistory(base, candidate map[string][]MetricPoint, duration time.return merged}+func filterMetricPointMap(metricMap map[string][]MetricPoint, metricTypes []string) map[string][]MetricPoint {+ if len(metricTypes) == 0 {+ return cloneMetricPointMap(metricMap)+ }+ filtered := make(map[string][]MetricPoint, len(metricTypes))+ for _, metricType := range metricTypes {+ if len(metricMap[metricType]) == 0 {+ continue+ }+ filtered[metricType] = cloneMetricSeries(metricMap[metricType])+ }+ return filtered+}++func buildStorageSummaryCapacityTrend(+ poolMetrics map[string]map[string][]MetricPoint,+) ([]MetricPoint, int64) {+ type aggregateBucket struct {+ used float64+ avail float64+ hasUsed bool+ hasAvail bool+ }++ buckets := make(map[int64]*aggregateBucket)+ var oldestTimestamp int64+ for _, metrics := range poolMetrics {+ for _, point := range metrics["used"] {+ timestamp := point.Timestamp.UnixMilli()+ bucket := buckets[timestamp]+ if bucket == nil {+ bucket = &aggregateBucket{}+ buckets[timestamp] = bucket+ }+ bucket.used += point.Value+ bucket.hasUsed = true+ if oldestTimestamp == 0 || timestamp < oldestTimestamp {+ oldestTimestamp = timestamp+ }+ }+ for _, point := range metrics["avail"] {+ timestamp := point.Timestamp.UnixMilli()+ bucket := buckets[timestamp]+ if bucket == nil {+ bucket = &aggregateBucket{}+ buckets[timestamp] = bucket+ }+ bucket.avail += point.Value+ bucket.hasAvail = true+ if oldestTimestamp == 0 || timestamp < oldestTimestamp {+ oldestTimestamp = timestamp+ }+ }+ }++ if len(buckets) == 0 {+ return nil, oldestTimestamp+ }++ timestamps := make([]int64, 0, len(buckets))+ for timestamp := range buckets {+ timestamps = append(timestamps, timestamp)+ }+ sort.Slice(timestamps, func(i, j int) bool {+ return timestamps[i] < timestamps[j]+ })++ out := make([]MetricPoint, 0, len(timestamps))+ for _, timestamp := range timestamps {+ bucket := buckets[timestamp]+ if bucket == nil || !bucket.hasUsed || !bucket.hasAvail {+ continue+ }+ total := bucket.used + bucket.avail+ if math.IsNaN(total) || math.IsInf(total, 0) || total <= 0 {+ continue+ }+ out = append(out, MetricPoint{+ Timestamp: time.UnixMilli(timestamp),+ Value: (bucket.used / total) * 100,+ })+ }++ return out, oldestTimestamp+}++func oldestMetricSeriesTimestamp(points []MetricPoint) int64 {+ var oldest int64+ for _, point := range points {+ timestamp := point.Timestamp.UnixMilli()+ if oldest == 0 || timestamp < oldest {+ oldest = timestamp+ }+ }+ return oldest+}+func shouldPreferMetricSeries(current, candidate []MetricPoint, duration time.Duration) bool {if len(candidate) == 0 {return falsediff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.goindex 9f27247d48..d7ba94991d 100644--- a/internal/monitoring/monitor_metrics_slo_test.go+++ b/internal/monitoring/monitor_metrics_slo_test.go@@ -242,6 +242,103 @@ func TestSLO_GetNodeMetricsForChartBatch(t *testing.T) {}}+func TestGetNodeMetricsForChartBatch_FiltersStoreReadsToRequestedMetricTypes(t *testing.T) {+ suppressMonitoringTestLogs(t)++ monitor := newChartBatchSLOMonitor(t)+ now := time.Now().UTC().Truncate(time.Second)+ duration := 4 * time.Hour+ writeBatch := []metrics.WriteMetric{+ {ResourceType: "node", ResourceID: "node-filter-1", MetricType: "cpu", Value: 41, Timestamp: now.Add(-2 * time.Hour), Tier: metrics.TierMinute},+ {ResourceType: "node", ResourceID: "node-filter-1", MetricType: "cpu", Value: 43, Timestamp: now.Add(-1 * time.Hour), Tier: metrics.TierMinute},+ {ResourceType: "node", ResourceID: "node-filter-1", MetricType: "memory", Value: 62, Timestamp: now.Add(-2 * time.Hour), Tier: metrics.TierMinute},+ {ResourceType: "node", ResourceID: "node-filter-1", MetricType: "memory", Value: 64, Timestamp: now.Add(-1 * time.Hour), Tier: metrics.TierMinute},+ {ResourceType: "node", ResourceID: "node-filter-1", MetricType: "disk", Value: 83, Timestamp: now.Add(-2 * time.Hour), Tier: metrics.TierMinute},+ {ResourceType: "node", ResourceID: "node-filter-1", MetricType: "disk", Value: 84, Timestamp: now.Add(-1 * time.Hour), Tier: metrics.TierMinute},+ }+ monitor.metricsStore.WriteBatchSync(writeBatch)++ result := monitor.GetNodeMetricsForChartBatch([]string{"node-filter-1"}, []string{"cpu", "memory"}, duration)+ if got := len(result["node-filter-1"]["cpu"]); got == 0 {+ t.Fatalf("expected cpu series, got %+v", result["node-filter-1"])+ }+ if got := len(result["node-filter-1"]["memory"]); got == 0 {+ t.Fatalf("expected memory series, got %+v", result["node-filter-1"])+ }+ if _, ok := result["node-filter-1"]["disk"]; ok {+ t.Fatalf("expected filtered batch query to omit disk series, got %+v", result["node-filter-1"])+ }+}++func TestGetStorageCapacityMetricsForSummaryBatch_FiltersStoreReadsToCapacitySeries(t *testing.T) {+ suppressMonitoringTestLogs(t)++ monitor := newChartBatchSLOMonitor(t)+ now := time.Now().UTC().Truncate(time.Second)+ duration := 24 * time.Hour+ monitor.metricsStore.WriteBatchSync([]metrics.WriteMetric{+ {ResourceType: "storage", ResourceID: "storage-summary-1", MetricType: "used", Value: 400, Timestamp: now.Add(-2 * time.Hour), Tier: metrics.TierMinute},+ {ResourceType: "storage", ResourceID: "storage-summary-1", MetricType: "avail", Value: 600, Timestamp: now.Add(-2 * time.Hour), Tier: metrics.TierMinute},+ {ResourceType: "storage", ResourceID: "storage-summary-1", MetricType: "usage", Value: 40, Timestamp: now.Add(-2 * time.Hour), Tier: metrics.TierMinute},+ {ResourceType: "storage", ResourceID: "storage-summary-1", MetricType: "total", Value: 1000, Timestamp: now.Add(-2 * time.Hour), Tier: metrics.TierMinute},+ })++ result := monitor.GetStorageCapacityMetricsForSummaryBatch([]string{"storage-summary-1"}, duration)+ if got := len(result["storage-summary-1"]["used"]); got != 1 {+ t.Fatalf("expected used series, got %+v", result["storage-summary-1"])+ }+ if got := len(result["storage-summary-1"]["avail"]); got != 1 {+ t.Fatalf("expected avail series, got %+v", result["storage-summary-1"])+ }+ if _, ok := result["storage-summary-1"]["usage"]; ok {+ t.Fatalf("expected compact summary batch to omit usage, got %+v", result["storage-summary-1"])+ }+ if _, ok := result["storage-summary-1"]["total"]; ok {+ t.Fatalf("expected compact summary batch to omit total, got %+v", result["storage-summary-1"])+ }+}++func TestGetStorageSummaryCapacityTrend_MockAvoidsPerPoolChartCacheFanout(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)+ }+ })++ mock.SetEnabled(false)+ mock.SetMockConfig(previousConfig)+ mock.SetEnabled(true)++ monitor := newChartFallbackTestMonitor(t)+ points, oldestTimestamp := monitor.GetStorageSummaryCapacityTrend(24 * time.Hour)+ if len(points) == 0 {+ t.Fatal("expected aggregate mock storage summary capacity trend")+ }+ if oldestTimestamp == 0 {+ t.Fatal("expected aggregate mock storage summary oldest timestamp")+ }++ summaryKey := mockChartMetricMapCacheKey{+ kind: "storage-summary",+ resourceType: "storage",+ resourceID: "__aggregate__",+ duration: 24 * time.Hour,+ }+ if _, ok := monitor.mockChartMapCache[summaryKey]; !ok {+ t.Fatalf("expected summary cache entry, got %+v", monitor.mockChartMapCache)+ }+ for key := range monitor.mockChartMapCache {+ if key.kind == "storage" {+ t.Fatalf("expected aggregate summary cache without per-pool storage fanout, found %+v", key)+ }+ }+}+func TestSLO_GetPhysicalDiskTemperatureCharts_WithNativeHistoryFallback(t *testing.T) {skipMonitoringSLOUnderRace(t)suppressMonitoringTestLogs(t)diff --git a/pkg/metrics/store.go b/pkg/metrics/store.goindex 6da6ed301e..8f495b786d 100644--- a/pkg/metrics/store.go+++ b/pkg/metrics/store.go@@ -854,6 +854,29 @@ const queryAllBatchChunkSize = 500// This avoids N+1 query patterns when loading charts for many resources.// Resource IDs are deduplicated and chunked to stay within SQLite limits.func (s *Store) QueryAllBatch(resourceType string, resourceIDs []string, start, end time.Time, stepSecs int64) (map[string]map[string][]MetricPoint, error) {+ return s.queryBatch(resourceType, resourceIDs, nil, start, end, stepSecs)+}++// QueryMetricTypesBatch retrieves only the requested metric types for multiple+// resources of the same type in a single query. Passing no metricTypes falls+// back to QueryAllBatch semantics.+func (s *Store) QueryMetricTypesBatch(+ resourceType string,+ resourceIDs []string,+ metricTypes []string,+ start, end time.Time,+ stepSecs int64,+) (map[string]map[string][]MetricPoint, error) {+ return s.queryBatch(resourceType, resourceIDs, metricTypes, start, end, stepSecs)+}++func (s *Store) queryBatch(+ resourceType string,+ resourceIDs []string,+ metricTypes []string,+ start, end time.Time,+ stepSecs int64,+) (map[string]map[string][]MetricPoint, error) {resourceType = normalizeMetricResourceType(resourceType)// Deduplicate resource IDs.seen := make(map[string]struct{}, len(resourceIDs))@@ -871,6 +894,7 @@ func (s *Store) QueryAllBatch(resourceType string, resourceIDs []string, start,if len(unique) == 0 {return map[string]map[string][]MetricPoint{}, nil}+ normalizedMetricTypes := normalizeMetricTypes(metricTypes)tiers := s.tierFallbacks(end.Sub(start))if len(tiers) == 0 {@@ -894,7 +918,7 @@ func (s *Store) QueryAllBatch(resourceType string, resourceIDs []string, start,hi = len(unresolved)}chunk := unresolved[lo:hi]- tierResult, err := s.queryAllBatchWithTier(resourceType, chunk, start, end, stepSecs, tier)+ tierResult, err := s.queryAllBatchWithTier(resourceType, chunk, normalizedMetricTypes, start, end, stepSecs, tier)if err != nil {return nil, err}@@ -917,22 +941,57 @@ func (s *Store) QueryAllBatch(resourceType string, resourceIDs []string, start,return result, nil}-func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string, start, end time.Time, stepSecs int64, tier Tier) (map[string]map[string][]MetricPoint, error) {+func normalizeMetricTypes(metricTypes []string) []string {+ if len(metricTypes) == 0 {+ return nil+ }++ seen := make(map[string]struct{}, len(metricTypes))+ normalized := make([]string, 0, len(metricTypes))+ for _, metricType := range metricTypes {+ canonical := normalizeMetricType(metricType)+ if canonical == "" {+ continue+ }+ if _, exists := seen[canonical]; exists {+ continue+ }+ seen[canonical] = struct{}{}+ normalized = append(normalized, canonical)+ }+ if len(normalized) == 0 {+ return nil+ }+ return normalized+}++func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string, metricTypes []string, start, end time.Time, stepSecs int64, tier Tier) (map[string]map[string][]MetricPoint, error) {placeholders := make([]string, len(resourceIDs))for i := range resourceIDs {placeholders[i] = "?"}inClause := strings.Join(placeholders, ",")+ metricClause := ""+ metricArgs := make([]interface{}, 0, len(metricTypes))+ if len(metricTypes) > 0 {+ metricPlaceholders := make([]string, len(metricTypes))+ for i, metricType := range metricTypes {+ metricPlaceholders[i] = "?"+ metricArgs = append(metricArgs, metricType)+ }+ metricClause = fmt.Sprintf(" AND metric_type IN (%s)", strings.Join(metricPlaceholders, ","))+ }var params []interface{}var sqlQuery stringif stepSecs > 1 {- params = make([]interface{}, 0, len(resourceIDs)+4)+ params = make([]interface{}, 0, len(resourceIDs)+len(metricArgs)+4)params = append(params, resourceType)for _, id := range resourceIDs {params = append(params, id)}+ params = append(params, metricArgs...)params = append(params, string(tier), start.Unix(), end.Unix())sqlQuery = fmt.Sprintf(`@@ -944,25 +1003,26 @@ func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string,COALESCE(min_value, value),COALESCE(max_value, value)FROM metrics- WHERE resource_type = ? AND resource_id IN (%s) AND tier = ?+ WHERE resource_type = ? AND resource_id IN (%s)%s AND tier = ?AND timestamp >= ? AND timestamp <= ?ORDER BY resource_id, metric_type, timestamp ASC- `, inClause)+ `, inClause, metricClause)} else {- params = make([]interface{}, 0, len(resourceIDs)+4)+ params = make([]interface{}, 0, len(resourceIDs)+len(metricArgs)+4)params = append(params, resourceType)for _, id := range resourceIDs {params = append(params, id)}+ params = append(params, metricArgs...)params = append(params, string(tier), start.Unix(), end.Unix())sqlQuery = fmt.Sprintf(`SELECT resource_id, metric_type, timestamp, value, COALESCE(min_value, value), COALESCE(max_value, value)FROM metrics- WHERE resource_type = ? AND resource_id IN (%s) AND tier = ?+ WHERE resource_type = ? AND resource_id IN (%s)%s AND tier = ?AND timestamp >= ? AND timestamp <= ?ORDER BY resource_id, metric_type, timestamp ASC- `, inClause)+ `, inClause, metricClause)}// Retry on SQLITE_BUSYdiff --git a/pkg/metrics/store_additional_test.go b/pkg/metrics/store_additional_test.goindex 6f4e003b7d..e462b38c27 100644--- a/pkg/metrics/store_additional_test.go+++ b/pkg/metrics/store_additional_test.go@@ -519,3 +519,47 @@ func TestStoreQueryAllBatchCanonicalizesAndDeduplicatesIdentifiers(t *testing.T)t.Fatalf("expected agent-2 cpu metric after normalization, got %+v", result["agent-2"])}}++func TestStoreQueryMetricTypesBatchFiltersMetricTypes(t *testing.T) {+ dir := t.TempDir()+ store, err := NewStore(DefaultConfig(dir))+ if err != nil {+ t.Fatalf("NewStore returned error: %v", err)+ }+ defer store.Close()+ ts := time.Now().UTC().Truncate(time.Second)++ store.WriteBatchSync([]WriteMetric{+ {ResourceType: "agent", ResourceID: "agent-1", MetricType: "cpu", Value: 11.0, Timestamp: ts, Tier: TierRaw},+ {ResourceType: "agent", ResourceID: "agent-1", MetricType: "memory", Value: 21.0, Timestamp: ts, Tier: TierRaw},+ {ResourceType: "agent", ResourceID: "agent-2", MetricType: "cpu", Value: 12.0, Timestamp: ts, Tier: TierRaw},+ {ResourceType: "agent", ResourceID: "agent-2", MetricType: "memory", Value: 22.0, Timestamp: ts, Tier: TierRaw},+ })++ result, err := store.QueryMetricTypesBatch(+ " agent ",+ []string{" agent-1 ", "agent-2", "agent-2"},+ []string{" CPU ", "cpu"},+ ts.Add(-time.Second),+ ts.Add(time.Second),+ 0,+ )+ if err != nil {+ t.Fatalf("query metric types batch failed: %v", err)+ }+ if len(result) != 2 {+ t.Fatalf("expected 2 resources after normalization, got %+v", result)+ }+ if got := len(result["agent-1"]["cpu"]); got != 1 {+ t.Fatalf("expected agent-1 cpu metric, got %+v", result["agent-1"])+ }+ if got := len(result["agent-2"]["cpu"]); got != 1 {+ t.Fatalf("expected agent-2 cpu metric, got %+v", result["agent-2"])+ }+ if _, ok := result["agent-1"]["memory"]; ok {+ t.Fatalf("expected metric filter to exclude memory for agent-1, got %+v", result["agent-1"])+ }+ if _, ok := result["agent-2"]["memory"]; ok {+ t.Fatalf("expected metric filter to exclude memory for agent-2, got %+v", result["agent-2"])+ }+}diff --git a/pkg/metrics/store_query_plan_test.go b/pkg/metrics/store_query_plan_test.goindex 82a19ab7a2..b85572bda7 100644--- a/pkg/metrics/store_query_plan_test.go+++ b/pkg/metrics/store_query_plan_test.go@@ -130,6 +130,15 @@ func TestQueryPlansUseIndexes(t *testing.T) {ORDER BY resource_id, metric_type, bucket_ts ASC`,args: []any{int64(60), int64(60), int64(60), "vm", "vm-1", "vm-2", "vm-3", "raw", int64(0), farFuture},},+ {+ name: "multi-resource filtered-metric lookup (QueryMetricTypesBatch)",+ query: `SELECT resource_id, metric_type, timestamp, value, COALESCE(min_value, value), COALESCE(max_value, value)+ FROM metrics+ WHERE resource_type = ? AND resource_id IN (?, ?, ?) AND metric_type IN (?, ?) AND tier = ?+ AND timestamp >= ? AND timestamp <= ?+ ORDER BY resource_id, metric_type, timestamp ASC`,+ args: []any{"vm", "vm-1", "vm-2", "vm-3", "cpu", "memory", "raw", int64(0), farFuture},+ },{name: "retention delete by tier+time",query: `DELETE FROM metrics WHERE tier = ? AND timestamp < ?`,