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
Sharpen mock summary isolation and role shaping
rcourtman41187c6678d0
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 45dee3eb25..38861359f8 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -279,6 +279,11 @@ That same lifecycle-adjacent mock path must stay graph-first at the sharedplatform inventory or recovery context, they must consume`internal/mock/fixture_graph.go` and its graph-owned projections instead ofreintroducing snapshot-only or platform-only helper exports.+Lifecycle-adjacent summary chart consumers may still depend on shared+`internal/api/router.go` transport, but any synthetic mock series on that path+must resolve through canonical `resourceType` and `resourceID` identities+rather than lifecycle-local seed prefixes, so platform handoff surfaces do not+see a different recent tail than the runtime mock inventory they describe.That same hosted continuity contract also applies to the older direct tenantmagic-link path. Lifecycle-adjacent control-plane redirects through`/auth/cloud-handoff` must preserve canonical account/user/role identity in thediff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex bc5e6a63aa..9b9afb2379 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -177,6 +177,7 @@ Own canonical runtime payload shapes between backend and frontend.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.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.## Forbidden Paths@@ -1664,6 +1665,12 @@ aggregate workload charts must preserve stable guest counts while batchingstore-backed metric reads across workload types, with no payload shape change.That endpoint now also carries an explicit API p95 budget under the samestore-backed mixed-workload fixture used to verify the batched hot path.+That same summary-chart contract now also owns synthetic mock fallback+identity. When `internal/api/router.go` needs to synthesize summary history+for workloads, infrastructure, or storage cards, it must key those series by+canonical `resourceType`, `resourceID`, and `metricType` instead of ad hoc+seed-prefix bounds, so all time ranges and runtime mock samples stay on one+governed timeline.Frontend AI API clients now also normalize `402 Payment Required` responses foroptional paywalled collections into explicit empty states, so Pulse Pro gatingdoes not become a transport error path during page bootstrap.diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 7756aebc18..9eb00cd43f 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -576,6 +576,12 @@ and `frontend-modern/src/components/shared/interactiveSparklineModel.ts` ownssparkline downsampling, gap segmentation, axis-tick math, and hover-selectionpolicy. Future sparkline work should extend those owners instead of pushingcanvas scheduling or chart-shape math back into the shared component shell.+That same shared sparkline boundary now also owns active-series isolation+metadata. The shell may expose `data-active-series-display` and+`data-rendered-series-count` for proof and inspection, but only the shared+runtime/model owners may decide whether a hovered or focused series is merely+emphasized or fully isolated; feature shells must not fork their own row-hover+line filtering.The dashboard overview trend cards now also have an explicit shared-shellobligation: `frontend-modern/src/features/dashboardOverview/TrendCharts.tsx`must treat missing infrastructure history as a governed empty state rather thandiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 7ebe5fb33b..c750b486e0 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -131,6 +131,12 @@ window instead of stitching a second live tail onto the end of seededsparklines. Monitoring must not let provider-owned mock resources receive aduplicate generic unified-resource writer that appends a divergent recent tailafter the canonical mock sampler has already seeded and extended that series.+That same chart boundary also owns role-shaped realism. Seeded history,+synthetic summary fallbacks, and runtime mock writes must derive their bounds+and curve shape from the same canonical resource-role registry, so database,+cache, backup, web, and storage workloads keep believable long-range behavior+instead of switching from one generic seeded pattern to a different recent+runtime pattern.That same chart boundary also owns storage-series identity. Monitoring and`ReadState` consumers must address storage pool and physical-disk historythrough the resolved unified-resource metrics target, so seeded history,diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex b33cb64156..6b2858dd64 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -200,13 +200,19 @@ and workloads summary cards must treat hover and focus as one shared active-sericontract so time-range switches and row scrubbing reuse one existing chart pathinstead of repainting page-local “selected row” overlays on top of alreadydownsampled summary history.+For shared line charts on that hot path, the shared sparkline primitive may+isolate the selected series inside the existing render budget, but that+isolation must still reuse the same summary series set and timeline data rather+than triggering a second page-local chart recomputation.That same hot-path rule now covers contextual row focus on those pages.`frontend-modern/src/components/Dashboard/useDashboardSelectionState.ts` mustwrite workload selection back into the workloads route through the sharedsame-path route-state scheduler so opening a focused workload preserves scrolland does not look like a full page reload, and the governed infrastructure and-workloads summary surfaces must keep rendering the page-level series set while-that focus only changes the emphasized label and active-series highlight.+workloads summary surfaces must keep the summary page-scoped while that focus+reuses the shared highlight contract; density maps may retain page-level+context, but line-card isolation must still flow through the shared sparkline+runtime instead of a page-local focus overlay.That same hot-path rule now applies to infrastructure summary resourcefiltering: `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`must include API-backed systems such as top-level TrueNAS appliances throughdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex eaa08e8e5e..c5fd1b4bbb 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -216,6 +216,12 @@ ID for shared summary emphasis, but `frontend-modern/src/components/Storage/Stormust keep the storage summary page-scoped instead of collapsing its sparklinesto the single expanded row or replacing the page overview with row-local emptystates.+That same page-scoped summary contract now also owns canonical hover-isolation+behavior. Pool and disk rows must publish the resolved metrics-target ID into+the shared summary contract so pool usage, used capacity, and available space+cards can isolate the active row through the shared sparkline primitive while+non-matching cards such as disk temperature demote to inactive context instead+of rebuilding a row-local summary surface.The recovery backend is a real product boundary, not just a helper package:`internal/recovery/` owns per-tenant SQLite persistence, rollup derivation,diff --git a/frontend-modern/src/components/Storage/StoragePoolRow.tsx b/frontend-modern/src/components/Storage/StoragePoolRow.tsxindex d9608d4130..3a88b2ee12 100644--- a/frontend-modern/src/components/Storage/StoragePoolRow.tsx+++ b/frontend-modern/src/components/Storage/StoragePoolRow.tsx@@ -61,7 +61,7 @@ export const StoragePoolRow: Component<StoragePoolRowProps> = (props) => {class={`${STORAGE_POOL_ROW_CLASS} ${props.rowClass} ${props.expanded ? STORAGE_POOL_ROW_EXPANDED_CLASS : ''}`}style={{ ...props.rowStyle, ...STORAGE_POOL_ROW_STYLE }}onClick={props.onToggleExpand}- onMouseEnter={() => props.onHoverChange?.(props.record.id)}+ onMouseEnter={() => props.onHoverChange?.(props.summarySeriesId)}onMouseLeave={() => props.onHoverChange?.(null)}data-summary-series-id={props.summarySeriesId}{...props.alertDataAttrs}diff --git a/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx b/frontend-modern/src/components/Storage/__tests__/Storage.test.tsxindex 8be371e9f7..bba63e7888 100644--- a/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx+++ b/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx@@ -452,6 +452,11 @@ describe('Storage', () => {'[data-highlight-series-active="true"][data-highlight-series-id="pool:alpha"]',).length,).toBe(3);+ expect(+ summary.querySelectorAll(+ '[data-highlight-series-active="true"][data-highlight-series-id="pool:alpha"][data-active-series-display="isolate"][data-rendered-series-count="1"]',+ ).length,+ ).toBe(3);expect(summary.querySelectorAll('[data-summary-card-state="inactive"]').length).toBe(1);});diff --git a/frontend-modern/src/components/shared/InteractiveSparkline.tsx b/frontend-modern/src/components/shared/InteractiveSparkline.tsxindex 39825e86fd..32062bcde7 100644--- a/frontend-modern/src/components/shared/InteractiveSparkline.tsx+++ b/frontend-modern/src/components/shared/InteractiveSparkline.tsx@@ -34,6 +34,8 @@ export const InteractiveSparkline: Component<InteractiveSparklineProps> = (props}`.trim()}data-highlight-series-id={props.highlightSeriesId ?? ''}data-highlight-series-active={sparkline.externalSeriesIndex() !== null ? 'true' : 'false'}+ data-active-series-display={sparkline.activeSeriesDisplay()}+ data-rendered-series-count={sparkline.renderedSeriesCount()}data-summary-chart-state={interactionState()}><div class="relative flex-1 min-h-0">@@ -134,42 +136,34 @@ export const InteractiveSparkline: Component<InteractiveSparklineProps> = (props<For each={sparkline.chartData().paths}>{(pathData) => (- <g>- <Show when={pathData.areaPath}>- <path d={pathData.areaPath} fill="url(#single-series-area)" stroke="none" />- </Show>- <path- d={pathData.path}- fill="none"- stroke={(() => {- const active = sparkline.activeEmphasisSeriesIndex();- if (active !== null && active !== pathData.seriesIndex) {- return inactiveSeriesColor();- }- return pathData.color;- })()}- stroke-width={(() => {- const active = sparkline.activeEmphasisSeriesIndex();- if (active === null) {- return '1.5';- }- return active === pathData.seriesIndex ? '3.2' : '0.7';- })()}- stroke-linecap="round"- stroke-linejoin="round"- opacity={(() => {- const active = sparkline.activeEmphasisSeriesIndex();- const interactionOpacity =- interactionState() === 'inactive' ? 0.35 : 1;- if (active === null) {- return `${0.75 * interactionOpacity}`;- }- return `${(active === pathData.seriesIndex ? 1 : 0.05) * interactionOpacity}`;- })()}- style={{ transition: 'opacity 90ms linear, stroke-width 90ms linear' }}- vector-effect="non-scaling-stroke"- />- </g>+ <Show when={sparkline.shouldRenderSeries(pathData.seriesIndex)}>+ <g>+ <Show when={pathData.areaPath}>+ <path+ d={pathData.areaPath}+ fill="url(#single-series-area)"+ stroke="none"+ />+ </Show>+ <path+ d={pathData.path}+ fill="none"+ stroke={(() => {+ const active = sparkline.activeEmphasisSeriesIndex();+ if (active !== null && active !== pathData.seriesIndex) {+ return inactiveSeriesColor();+ }+ return pathData.color;+ })()}+ stroke-width={sparkline.lineWidthForSeries(pathData.seriesIndex)}+ stroke-linecap="round"+ stroke-linejoin="round"+ opacity={sparkline.opacityForSeries(pathData.seriesIndex)}+ style={{ transition: 'opacity 90ms linear, stroke-width 90ms linear' }}+ vector-effect="non-scaling-stroke"+ />+ </g>+ </Show>)}</For></svg>diff --git a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.tsindex 1ceedcd293..95f929b2a7 100644--- a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts+++ b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts@@ -507,12 +507,17 @@ describe('shared primitive guardrails', () => {it('keeps interactive sparkline on shell, runtime, and model owners', () => {expect(interactiveSparklineSource).toContain('useInteractiveSparklineState');+ expect(interactiveSparklineSource).toContain('data-active-series-display');+ expect(interactiveSparklineSource).toContain('data-rendered-series-count');expect(interactiveSparklineSource).not.toContain('createEffect');expect(interactiveSparklineSource).not.toContain('createSignal');expect(interactiveSparklineSource).not.toContain('scheduleSparkline');expect(interactiveSparklineSource).not.toContain('downsampleLTTB');expect(interactiveSparklineStateSource).toContain('export function useInteractiveSparklineState');+ expect(interactiveSparklineStateSource).toContain('activeSeriesDisplay');+ expect(interactiveSparklineStateSource).toContain('shouldRenderSeries');+ expect(interactiveSparklineStateSource).toContain('renderedSeriesCount');expect(interactiveSparklineStateSource).toContain('createSignal');expect(interactiveSparklineStateSource).toContain('scheduleSparkline');expect(interactiveSparklineStateSource).toContain('computeInteractiveSparklineHoverState');diff --git a/frontend-modern/src/components/shared/__tests__/InteractiveSparkline.test.tsx b/frontend-modern/src/components/shared/__tests__/InteractiveSparkline.test.tsxindex 8473a13f2e..560280fda0 100644--- a/frontend-modern/src/components/shared/__tests__/InteractiveSparkline.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/InteractiveSparkline.test.tsx@@ -374,4 +374,48 @@ describe('InteractiveSparkline hover behavior', () => {const paths = container.querySelectorAll('path[vector-effect="non-scaling-stroke"]');expect(paths.length).toBe(1);});++ it('renders only the active series when isolate mode is enabled', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2024-01-02T00:00:00Z'));+ const now = Date.now();++ const { container } = render(() => (+ <InteractiveSparkline+ timeRange="1h"+ activeSeriesDisplay="isolate"+ highlightSeriesId="beta"+ series={[+ {+ id: 'alpha',+ name: 'Alpha',+ color: '#ff0000',+ data: [+ { timestamp: now - 30 * 60_000, value: 30 },+ { timestamp: now - 5 * 60_000, value: 45 },+ ],+ },+ {+ id: 'beta',+ name: 'Beta',+ color: '#00ff00',+ data: [+ { timestamp: now - 30 * 60_000, value: 70 },+ { timestamp: now - 5 * 60_000, value: 80 },+ ],+ },+ ]}+ />+ ));++ await Promise.resolve();++ const root = container.firstElementChild as HTMLElement | null;+ expect(root).not.toBeNull();+ expect(root?.getAttribute('data-active-series-display')).toBe('isolate');+ expect(root?.getAttribute('data-rendered-series-count')).toBe('1');++ const paths = container.querySelectorAll('path[vector-effect="non-scaling-stroke"]');+ expect(paths.length).toBe(1);+ });});diff --git a/frontend-modern/src/components/shared/interactiveSparklineModel.ts b/frontend-modern/src/components/shared/interactiveSparklineModel.tsindex 8aa90c98ed..995c6f12e2 100644--- a/frontend-modern/src/components/shared/interactiveSparklineModel.ts+++ b/frontend-modern/src/components/shared/interactiveSparklineModel.ts@@ -15,6 +15,7 @@ export interface InteractiveSparklineProps {rangeLabel?: string;timeRange?: TimeRange;renderMode?: 'auto' | 'svg' | 'canvas';+ activeSeriesDisplay?: 'emphasize' | 'isolate';yMode?: 'percent' | 'auto';size?: 'sm' | 'md' | 'lg';bridgeLeadingGap?: boolean;@@ -370,10 +371,7 @@ export const buildInteractiveSparklineTopLabel = ({return formatTopLabel ? formatTopLabel(scaleMax) : scaleMax.toFixed(1);};-export const buildInteractiveSparklineAxisTicks = (- yMode: 'percent' | 'auto',- topLabel: string,-) => {+export const buildInteractiveSparklineAxisTicks = (yMode: 'percent' | 'auto', topLabel: string) => {if (yMode === 'percent') {return [{ label: '100%', top: '0%', anchor: 'top' as const },@@ -391,10 +389,7 @@ export const buildInteractiveSparklineAxisTicks = (];};-export const buildInteractiveSparklineGridLineY = (- yMode: 'percent' | 'auto',- vbH: number,-) => {+export const buildInteractiveSparklineGridLineY = (yMode: 'percent' | 'auto', vbH: number) => {if (yMode === 'percent') {return [vbH * 0.2, vbH * 0.4, vbH * 0.6, vbH * 0.8];}diff --git a/frontend-modern/src/components/shared/useInteractiveSparklineState.ts b/frontend-modern/src/components/shared/useInteractiveSparklineState.tsindex 29ed5a4b27..b8ab9f1ce7 100644--- a/frontend-modern/src/components/shared/useInteractiveSparklineState.ts+++ b/frontend-modern/src/components/shared/useInteractiveSparklineState.ts@@ -34,6 +34,7 @@ export function useInteractiveSparklineState(const tooltipEstimatedWidth = 190;const maxRows = () => props.maxTooltipRows ?? 6;const yMode = () => props.yMode ?? 'percent';+ const activeSeriesDisplay = () => props.activeSeriesDisplay ?? 'emphasize';const shouldUseCanvas = createMemo(() =>getInteractiveSparklineShouldUseCanvas(props.series, props.renderMode),);@@ -161,6 +162,56 @@ export function useInteractiveSparklineState(externalSeriesIndex: externalSeriesIndex(),}),);+ const shouldIsolateActiveSeries = createMemo(+ () => activeSeriesDisplay() === 'isolate' && activeEmphasisSeriesIndex() !== null,+ );+ const shouldRenderSeries = (seriesIndex: number) => {+ const active = activeEmphasisSeriesIndex();+ if (active === null) {+ return true;+ }+ if (shouldIsolateActiveSeries()) {+ return active === seriesIndex;+ }+ return true;+ };+ const renderedSeriesCount = createMemo(() => {+ const active = activeEmphasisSeriesIndex();+ if (active === null) {+ return chartData().validSeries.length;+ }+ if (shouldIsolateActiveSeries()) {+ return 1;+ }+ return chartData().validSeries.length;+ });+ const lineWidthForSeries = (seriesIndex: number) => {+ const active = activeEmphasisSeriesIndex();+ const isLg = props.size === 'lg';+ if (active === null) {+ return isLg ? 2 : 1.5;+ }+ if (active === seriesIndex) {+ return isLg ? 4 : 3.2;+ }+ if (shouldIsolateActiveSeries()) {+ return 0;+ }+ return isLg ? 0.7 : 0.6;+ };+ const opacityForSeries = (seriesIndex: number) => {+ const active = activeEmphasisSeriesIndex();+ if (active === null) {+ return 0.75 * interactionOpacityMultiplier();+ }+ if (active === seriesIndex) {+ return interactionOpacityMultiplier();+ }+ if (shouldIsolateActiveSeries()) {+ return 0;+ }+ return 0.05 * interactionOpacityMultiplier();+ };const drawCanvas = () => {const canvas = refs.getCanvas();@@ -210,23 +261,12 @@ export function useInteractiveSparklineState(const valueToY = createInteractiveSparklineValueToY(yMode(), computed.scaleMax, height);for (let seriesIndex = 0; seriesIndex < computed.validSeries.length; seriesIndex++) {+ if (!shouldRenderSeries(seriesIndex)) {+ continue;+ }const series = computed.validSeries[seriesIndex];- const isLg = props.size === 'lg';- const lineWidth =- active === null- ? isLg- ? 2- : 1.5- : active === seriesIndex- ? isLg- ? 4- : 3.2- : isLg- ? 0.7- : 0.6;- const opacity =- (active === null ? 0.75 : active === seriesIndex ? 1 : 0.05) *- interactionOpacityMultiplier();+ const lineWidth = lineWidthForSeries(seriesIndex);+ const opacity = opacityForSeries(seriesIndex);ctx.save();ctx.globalAlpha = opacity;@@ -364,6 +404,7 @@ export function useInteractiveSparklineState(return {activeEmphasisSeriesIndex,+ activeSeriesDisplay,axisTicks,chartData,externalSeriesIndex,@@ -374,7 +415,11 @@ export function useInteractiveSparklineState(handleMouseLeave,handleMouseMove,hoveredState,+ lineWidthForSeries,+ opacityForSeries,+ renderedSeriesCount,shouldUseCanvas,+ shouldRenderSeries,vbH,vbW,xAxisBandPx,diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex c1035c6bd8..87cbcac8de 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -688,9 +688,7 @@ func TestContract_GenerateStyledMockSeries_UsesTimestampBasedCurve(t *testing.T)time.Hour,7,51.9,- 0,- 100,- "history-mock",+ "dockerContainer","orion-2-f54579833f9c","memory",)@@ -699,9 +697,7 @@ func TestContract_GenerateStyledMockSeries_UsesTimestampBasedCurve(t *testing.T)time.Hour,13,51.9,- 0,- 100,- "history-mock",+ "dockerContainer","orion-2-f54579833f9c","memory",)diff --git a/internal/api/router.go b/internal/api/router.goindex a58015653d..0a9e45c9a3 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -5909,13 +5909,10 @@ func generateStyledMockSeries(duration time.Duration,numPoints int,current float64,- min float64,- max float64,- seedPrefix string,+ resourceType string,resourceID string,metricType string,) []MetricPoint {- seed := monitoring.HashSeed(seedPrefix, resourceID, metricType)style := mockMetricStyle(metricType)durationMillis := int64(duration / time.Millisecond)@@ -5931,7 +5928,14 @@ func generateStyledMockSeries(for i := 0; i < numPoints; i++ {timestamps[i] = time.UnixMilli(startMillis + int64(i)*step)}- values := monitoring.GenerateSeededMetricSeriesForTimestamps(current, timestamps, seed, min, max, metricType, style)+ values := monitoring.GenerateSeededResourceMetricSeriesForTimestamps(+ current,+ timestamps,+ resourceType,+ resourceID,+ metricType,+ style,+ )points := make([]MetricPoint, numPoints)for i := 0; i < numPoints; i++ {points[i] = MetricPoint{@@ -5959,20 +5963,16 @@ func buildSyntheticMetricHistorySeries(now time.Time,duration time.Duration,maxPoints int,+ resourceType string,resourceID string,metricType string,current float64,) []monitoring.MetricPoint {- var min float64- var max float64-switch metricType {case "smart_temp":if current <= 0 {return nil}- min = 25- max = 95default:return nil}@@ -5980,8 +5980,7 @@ func buildSyntheticMetricHistorySeries(numPoints := targetMockSeriesPoints(duration, maxPoints)series := generateStyledMockSeries(now.UnixMilli(), duration, numPoints,- current, min, max,- "history-mock", resourceID, metricType,+ current, resourceType, resourceID, metricType,)converted := make([]monitoring.MetricPoint, len(series))@@ -5999,20 +5998,14 @@ func buildMockWorkloadMetricHistorySeries(now time.Time,duration time.Duration,maxPoints int,+ resourceType string,resourceID string,metricType string,current float64,) []monitoring.MetricPoint {- var min float64- var max float64-switch metricType {case "cpu", "memory", "disk":- min = 0- max = 100case "diskread", "diskwrite", "netin", "netout":- min = 0- max = math.Max(current*1.8, 1)default:return nil}@@ -6020,8 +6013,7 @@ func buildMockWorkloadMetricHistorySeries(numPoints := targetMockSeriesPoints(duration, maxPoints)series := generateStyledMockSeries(now.UnixMilli(), duration, numPoints,- current, min, max,- "history-mock", resourceID, metricType,+ current, resourceType, resourceID, metricType,)converted := make([]monitoring.MetricPoint, len(series))@@ -7398,19 +7390,19 @@ func (r *Router) handleWorkloadsSummaryCharts(w http.ResponseWriter, req *http.Rif mockModeEnabled {if len(cpuPoints) < mockWorkloadMinSeriesPoints {- cpuPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, metricKey, "cpu", snapshot.cpu)+ cpuPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, "k8s", metricKey, "cpu", snapshot.cpu)}if len(memoryPoints) < mockWorkloadMinSeriesPoints {- memoryPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, metricKey, "memory", snapshot.memory)+ memoryPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, "k8s", metricKey, "memory", snapshot.memory)}if len(diskPoints) < mockWorkloadMinSeriesPoints {- diskPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, metricKey, "disk", snapshot.disk)+ diskPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, "k8s", metricKey, "disk", snapshot.disk)}if len(netInPoints) < mockWorkloadMinSeriesPoints {- netInPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, metricKey, "netin", pod.NetInRate())+ netInPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, "k8s", metricKey, "netin", pod.NetInRate())}if len(netOutPoints) < mockWorkloadMinSeriesPoints {- netOutPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, metricKey, "netout", pod.NetOutRate())+ netOutPoints = buildMockWorkloadMetricHistorySeries(currentTimeTime, duration, 0, "k8s", metricKey, "netout", pod.NetOutRate())}}@@ -8330,6 +8322,7 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)end,duration,historyMaxPoints,+ "disk",resourceID,metricType,float64(disk.PhysicalDisk.Temperature),@@ -8609,6 +8602,7 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)end,duration,historyMaxPoints,+ "disk",resourceID,metricType,current,diff --git a/internal/mock/fixture_graph.go b/internal/mock/fixture_graph.goindex 8fd8eb0aa2..bbcd2dc207 100644--- a/internal/mock/fixture_graph.go+++ b/internal/mock/fixture_graph.go@@ -31,6 +31,7 @@ func buildFixtureGraph(cfg MockConfig, now time.Time) FixtureGraph {}graph.UpdateMetrics(cfg, now)graph.AlertHistory = buildAlertHistory(graph.State.Nodes, graph.State.VMs, graph.State.Containers)+ syncMetricRoleRegistryFromGraph(graph)return graph}diff --git a/internal/mock/generator.go b/internal/mock/generator.goindex 61bd904a8b..596f9ceac7 100644--- a/internal/mock/generator.go+++ b/internal/mock/generator.go@@ -3449,7 +3449,7 @@ func normalizeMockBlendWeight(weight float64, step, reference time.Duration) flofunc sampleNaturalMetric(resourceClass, resourceID, metric string, min, max float64, speed float64, at time.Time) float64 {seed := MetricSeed(resourceClass, resourceID, metric)- return mockmodel.ValueAtMetric(seed, min, max, metric, speed, at)+ return mockmodel.ValueAtMetricWithRole(seed, min, max, metric, speed, MetricRole(resourceClass, resourceID), at)}func applyMemoryUsage(memory *models.Memory, usage float64) {diff --git a/internal/mock/metric_personas.go b/internal/mock/metric_personas.gonew file mode 100644index 0000000000..a2c1133cde--- /dev/null+++ b/internal/mock/metric_personas.go@@ -0,0 +1,274 @@+package mock++import (+ "strings"+ "sync/atomic"++ "github.com/rcourtman/pulse-go-rewrite/internal/vmware"+)++const (+ metricRoleGeneral = "general"+ metricRoleWeb = "web"+ metricRoleAPI = "api"+ metricRoleDatabase = "database"+ metricRoleCache = "cache"+ metricRoleQueue = "queue"+ metricRoleMonitoring = "monitoring"+ metricRoleBackup = "backup"+ metricRoleStorage = "storage"+ metricRoleIngress = "ingress"+ metricRoleCI = "ci"+ metricRoleMedia = "media"+ metricRoleSecurity = "security"+ metricRoleBatch = "batch"+)++type weightedMetricRole struct {+ role string+ weight int+}++var metricRoleRegistry atomic.Value++func init() {+ metricRoleRegistry.Store(map[string]string{})+}++func metricRoleRegistryKey(resourceClass, resourceID string) string {+ return normalizeMetricClass(resourceClass) + "::" + strings.TrimSpace(resourceID)+}++func setMetricRoleRegistry(registry map[string]string) {+ cloned := make(map[string]string, len(registry))+ for key, value := range registry {+ key = strings.TrimSpace(key)+ value = strings.TrimSpace(value)+ if key == "" || value == "" {+ continue+ }+ cloned[key] = value+ }+ metricRoleRegistry.Store(cloned)+}++func clearMetricRoleRegistry() {+ metricRoleRegistry.Store(map[string]string{})+}++func currentMetricRoleRegistry() map[string]string {+ raw := metricRoleRegistry.Load()+ if raw == nil {+ return nil+ }+ registry, _ := raw.(map[string]string)+ return registry+}++// MetricRole resolves the canonical mock persona for the given resource. When+// the fixture graph has richer naming metadata, it is used; otherwise the role+// falls back to stable token inference from the resource identity itself.+func MetricRole(resourceClass, resourceID string) string {+ resourceID = strings.TrimSpace(resourceID)+ if resourceID != "" {+ if registry := currentMetricRoleRegistry(); registry != nil {+ if role := strings.TrimSpace(registry[metricRoleRegistryKey(resourceClass, resourceID)]); role != "" {+ return role+ }+ }+ }+ return inferMetricRole(resourceClass, resourceID)+}++func syncMetricRoleRegistryFromGraph(graph FixtureGraph) {+ setMetricRoleRegistry(buildMetricRoleRegistry(graph))+}++func buildMetricRoleRegistry(graph FixtureGraph) map[string]string {+ registry := make(map[string]string)+ register := func(resourceClass, resourceID string, hints ...string) {+ resourceID = strings.TrimSpace(resourceID)+ if resourceID == "" {+ return+ }+ if role := inferMetricRole(resourceClass, resourceID, hints...); role != "" {+ registry[metricRoleRegistryKey(resourceClass, resourceID)] = role+ }+ }++ for _, node := range graph.State.Nodes {+ register("node", node.ID, node.Name, node.DisplayName, node.ClusterName, node.Host)+ }+ for _, vm := range graph.State.VMs {+ register("vm", vm.ID, vm.Name, vm.OSName, vm.Node, vm.Pool, strings.Join(vm.Tags, " "))+ }+ for _, ct := range graph.State.Containers {+ register("container", ct.ID, ct.Name, ct.OSName, ct.OSTemplate, ct.Node, ct.Pool, strings.Join(ct.Tags, " "))+ }+ for _, host := range graph.State.Hosts {+ register("agent", host.ID, host.Hostname, host.DisplayName, host.Platform, host.OSName, strings.Join(host.Tags, " "))+ }+ for _, host := range graph.State.DockerHosts {+ register("dockerHost", host.ID, host.Hostname, host.DisplayName, host.OS, host.Runtime)+ for _, container := range host.Containers {+ hints := []string{container.Name, container.Image}+ for key, value := range container.Labels {+ hints = append(hints, key, value)+ }+ register("dockerContainer", container.ID, hints...)+ }+ }+ for _, storage := range graph.State.Storage {+ register("storage", storage.ID, storage.Name, storage.Type, storage.Content, storage.Path, storage.Node, storage.Instance)+ }+ for _, ceph := range graph.State.CephClusters {+ register("ceph", ceph.ID, ceph.Name, "ceph", "storage")+ }+ for _, pbs := range graph.State.PBSInstances {+ register("pbs", pbs.ID, pbs.Name, pbs.Host, "backup")+ for _, datastore := range pbs.Datastores {+ register("pbsDatastore", pbs.ID+":"+datastore.Name, pbs.Name, datastore.Name, "backup", "datastore")+ }+ }++ truenasFixtures := graph.PlatformFixtures.TrueNAS+ register("agent", truenasFixtures.System.Hostname, truenasFixtures.System.Hostname, "truenas", "storage")+ for _, pool := range truenasFixtures.Pools {+ register("storage", "pool:"+pool.Name, pool.Name, "truenas", "pool", "storage")+ }+ for _, dataset := range truenasFixtures.Datasets {+ register("storage", "dataset:"+dataset.Name, dataset.Name, "truenas", "dataset", "storage")+ }+ for _, disk := range truenasFixtures.Disks {+ register("disk", trueNASDiskMetricID(disk), disk.Name, disk.Model, disk.Serial, "storage", "disk")+ }+ for _, app := range truenasFixtures.Apps {+ appID := strings.TrimSpace(app.ID)+ if appID == "" {+ appID = strings.TrimSpace(app.Name)+ }+ if appID == "" {+ continue+ }+ hints := []string{app.Name, app.ID}+ hints = append(hints, app.Images...)+ register("dockerContainer", appID, hints...)+ }++ vmwareFixtures := graph.PlatformFixtures.VMware+ for _, host := range vmwareFixtures.Hosts {+ sourceID := vmware.SourceID(vmwareFixtures.ConnectionID, "host", host.Host)+ register("agent", sourceID, host.Name, host.Host, host.ClusterName, host.DatacenterName, "vmware", "esxi")+ }+ for _, guest := range vmwareFixtures.VMs {+ sourceID := vmware.SourceID(vmwareFixtures.ConnectionID, "vm", guest.VM)+ register("vm", sourceID, guest.Name, guest.GuestOSFamily, guest.GuestHostname, guest.RuntimeHostName, guest.ClusterName, guest.FolderName)+ }+ for _, datastore := range vmwareFixtures.Datastores {+ sourceID := vmware.SourceID(vmwareFixtures.ConnectionID, "datastore", datastore.Datastore)+ register("storage", sourceID, datastore.Name, datastore.Type, datastore.URL, datastore.DatacenterName, datastore.FolderName, strings.Join(datastore.VMNames, " "))+ }++ return registry+}++func inferMetricRole(resourceClass, resourceID string, hints ...string) string {+ classKey := normalizeMetricClass(resourceClass)+ tokens := normalizeMetricRoleTokens(append([]string{resourceID, classKey}, hints...)...)++ for _, classifier := range []struct {+ role string+ keywords []string+ }{+ {metricRoleDatabase, []string{"postgres", "mysql", "mariadb", "mongodb", "database", "db", "sql", "pg", "influxdb"}},+ {metricRoleCache, []string{"redis", "memcached", "cache", "valkey"}},+ {metricRoleMonitoring, []string{"prometheus", "grafana", "loki", "monitoring", "metrics", "telemetry", "alertmanager", "jaeger"}},+ {metricRoleBackup, []string{"backup", "pbs", "archive", "snapshot", "replica", "replication", "offsite", "borg", "restic"}},+ {metricRoleStorage, []string{"storage", "datastore", "dataset", "pool", "zfs", "nfs", "smb", "ceph", "nas", "minio"}},+ {metricRoleIngress, []string{"nginx", "traefik", "haproxy", "envoy", "proxy", "ingress", "loadbalancer", "load-balancer"}},+ {metricRoleSecurity, []string{"bitwarden", "vaultwarden", "wireguard", "openvpn", "firewall", "pihole", "cloudflare", "auth", "vpn"}},+ {metricRoleMedia, []string{"jellyfin", "plex", "sonarr", "radarr", "transmission", "deluge", "sabnzbd", "media", "stream"}},+ {metricRoleCI, []string{"jenkins", "gitlab", "runner", "build", "ci"}},+ {metricRoleQueue, []string{"queue", "worker", "rabbitmq", "kafka", "broker"}},+ {metricRoleAPI, []string{"api", "backend", "service", "worker-api"}},+ {metricRoleWeb, []string{"web", "frontend", "portal", "site", "ui", "dashboard", "nextcloud", "seafile", "owncloud", "gitea"}},+ } {+ for _, keyword := range classifier.keywords {+ if keyword != "" && strings.Contains(tokens, keyword) {+ return classifier.role+ }+ }+ }++ switch classKey {+ case "pbs", "pbsdatastore":+ return metricRoleBackup+ case "storage", "pool", "dataset", "disk", "ceph":+ return metricRoleStorage+ case "node", "agent", "dockerhost":+ return stableMetricRoleChoice(resourceID, []weightedMetricRole{+ {role: metricRoleGeneral, weight: 4},+ {role: metricRoleStorage, weight: 2},+ {role: metricRoleMonitoring, weight: 2},+ {role: metricRoleBackup, weight: 1},+ {role: metricRoleIngress, weight: 1},+ })+ case "vm", "container", "dockercontainer":+ return stableMetricRoleChoice(resourceID, []weightedMetricRole{+ {role: metricRoleWeb, weight: 4},+ {role: metricRoleAPI, weight: 3},+ {role: metricRoleDatabase, weight: 2},+ {role: metricRoleCache, weight: 1},+ {role: metricRoleMonitoring, weight: 1},+ {role: metricRoleMedia, weight: 1},+ {role: metricRoleCI, weight: 1},+ {role: metricRoleBatch, weight: 1},+ })+ default:+ return metricRoleGeneral+ }+}++func stableMetricRoleChoice(seed string, roles []weightedMetricRole) string {+ if len(roles) == 0 {+ return metricRoleGeneral+ }++ totalWeight := 0+ for _, role := range roles {+ if role.weight > 0 {+ totalWeight += role.weight+ }+ }+ if totalWeight <= 0 {+ return roles[0].role+ }++ index := int(mockStableHash64(strings.TrimSpace(seed), "metric-role") % uint64(totalWeight))+ for _, role := range roles {+ if role.weight <= 0 {+ continue+ }+ if index < role.weight {+ return role.role+ }+ index -= role.weight+ }+ return roles[0].role+}++func normalizeMetricRoleTokens(values ...string) string {+ var builder strings.Builder+ for _, value := range values {+ normalized := strings.ToLower(strings.TrimSpace(value))+ if normalized == "" {+ continue+ }+ normalized = strings.NewReplacer("-", " ", "_", " ", "/", " ", ":", " ").Replace(normalized)+ if builder.Len() > 0 {+ builder.WriteByte(' ')+ }+ builder.WriteString(normalized)+ }+ return builder.String()+}diff --git a/internal/mock/metric_runtime.go b/internal/mock/metric_runtime.gonew file mode 100644index 0000000000..2ae136f3c6--- /dev/null+++ b/internal/mock/metric_runtime.go@@ -0,0 +1,253 @@+package mock++import (+ "math"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++func normalizeMetricClass(resourceClass string) string {+ normalized := strings.ToLower(strings.TrimSpace(resourceClass))+ normalized = strings.ReplaceAll(normalized, "-", "")+ normalized = strings.ReplaceAll(normalized, "_", "")+ return normalized+}++func MetricSeed(resourceClass, resourceID, metric string) uint64 {+ classKey := normalizeMetricClass(resourceClass)+ idKey := strings.TrimSpace(resourceID)+ metricKey := strings.ToLower(strings.TrimSpace(metric))+ return mockStableHash64(classKey, idKey, metricKey)+}++func MetricBounds(resourceClass, metric string) (float64, float64) {+ classKey := normalizeMetricClass(resourceClass)+ metricKey := strings.ToLower(strings.TrimSpace(metric))++ switch metricKey {+ case "cpu":+ switch classKey {+ case "node":+ return 5, 85+ case "vm":+ return 1, 85+ case "container":+ return 1, 75+ case "agent":+ return 4, 97+ case "dockerhost":+ return 3, 99+ case "dockercontainer":+ return 0, 190+ case "pbs", "pbsdatastore":+ return 6, 62+ default:+ return 0, 100+ }+ case "memory":+ switch classKey {+ case "node", "vm":+ return 10, 85+ case "container":+ return 5, 85+ case "agent", "dockerhost":+ return 12, 96+ case "dockercontainer":+ return 1, 97+ case "pbs", "pbsdatastore":+ return 24, 78+ default:+ return 0, 100+ }+ case "disk":+ switch classKey {+ case "node":+ return 5, 95+ case "vm":+ return 10, 90+ case "container":+ return 5, 85+ case "agent":+ return 5, 98+ case "dockerhost":+ return 8, 92+ case "dockercontainer":+ return 5, 72+ default:+ return 0, 100+ }+ case "usage":+ switch classKey {+ case "pbs", "pbsdatastore":+ return 12, 78+ case "storage", "pool", "dataset":+ return 8, 88+ default:+ return 0, 100+ }+ case "diskread":+ switch classKey {+ case "container", "dockercontainer":+ return 0, 30 * 1024 * 1024+ case "vm":+ return 0, 100 * 1024 * 1024+ case "agent", "dockerhost":+ return 0, 120 * 1024 * 1024+ default:+ return 0, 80 * 1024 * 1024+ }+ case "diskwrite":+ switch classKey {+ case "container", "dockercontainer":+ return 0, 18 * 1024 * 1024+ case "vm":+ return 0, 60 * 1024 * 1024+ case "agent", "dockerhost":+ return 0, 90 * 1024 * 1024+ default:+ return 0, 48 * 1024 * 1024+ }+ case "netin":+ switch classKey {+ case "container", "dockercontainer":+ return 0, 40 * 1024 * 1024+ case "vm":+ return 0, 80 * 1024 * 1024+ case "agent", "dockerhost":+ return 0, 250 * 1024 * 1024+ default:+ return 0, 64 * 1024 * 1024+ }+ case "netout":+ switch classKey {+ case "container", "dockercontainer":+ return 0, 24 * 1024 * 1024+ case "vm":+ return 0, 48 * 1024 * 1024+ case "agent", "dockerhost":+ return 0, 200 * 1024 * 1024+ default:+ return 0, 48 * 1024 * 1024+ }+ case "smart_temp", "temperature", "temp":+ return 25, 95+ default:+ return 0, 100+ }+}++func MetricBoundsForResource(resourceClass, resourceID, metric string) (float64, float64) {+ min, max := MetricBounds(resourceClass, metric)+ role := MetricRole(resourceClass, resourceID)+ metricKey := strings.ToLower(strings.TrimSpace(metric))++ switch metricKey {+ case "cpu":+ switch role {+ case metricRoleDatabase:+ min, max = maxFloat(min, 8), max*1.05+ case metricRoleCI, metricRoleBatch:+ max *= 1.18+ case metricRoleBackup, metricRoleStorage:+ max *= 0.9+ case metricRoleWeb, metricRoleAPI, metricRoleIngress, metricRoleMedia:+ max *= 1.1+ }+ case "memory":+ switch role {+ case metricRoleDatabase, metricRoleCache:+ min, max = maxFloat(min, 24), max*1.08+ case metricRoleMonitoring:+ min, max = maxFloat(min, 18), max*1.03+ case metricRoleBackup:+ max *= 0.85+ case metricRoleWeb, metricRoleIngress:+ max *= 0.92+ }+ case "disk", "usage":+ switch role {+ case metricRoleBackup, metricRoleStorage:+ min, max = maxFloat(min, 12), max*1.05+ case metricRoleCache, metricRoleIngress:+ max *= 0.82+ }+ case "diskread", "diskwrite":+ switch role {+ case metricRoleBackup, metricRoleDatabase, metricRoleBatch, metricRoleStorage:+ max *= 1.4+ case metricRoleWeb, metricRoleIngress:+ max *= 0.75+ case metricRoleCache:+ max *= 0.65+ }+ case "netin", "netout":+ switch role {+ case metricRoleWeb, metricRoleAPI, metricRoleIngress, metricRoleMedia, metricRoleSecurity:+ max *= 1.35+ case metricRoleBackup:+ max *= 1.2+ case metricRoleDatabase, metricRoleStorage:+ max *= 0.78+ }+ case "smart_temp", "temperature", "temp":+ switch role {+ case metricRoleMedia, metricRoleCI, metricRoleDatabase:+ max += 4+ case metricRoleBackup:+ max -= 2+ }+ }++ if max <= min {+ max = min + 1+ }+ return min, max+}++func metricSpeed(metric string) float64 {+ switch strings.ToLower(strings.TrimSpace(metric)) {+ case "memory":+ return 0.5+ case "disk", "usage", "storage", "capacity", "smart_temp", "temperature", "temp":+ return 0.12+ default:+ return 1.0+ }+}++func SampleMetric(resourceClass, resourceID, metric string, at time.Time) float64 {+ min, max := MetricBoundsForResource(resourceClass, resourceID, metric)+ return sampleNaturalMetric(resourceClass, resourceID, metric, min, max, metricSpeed(metric), at)+}++func SampleMetricInt(resourceClass, resourceID, metric string, at time.Time) int64 {+ return int64(math.Round(SampleMetric(resourceClass, resourceID, metric, at)))+}++func ApplyStorageUsage(storage *models.Storage, usage float64) {+ if storage == nil || storage.Total <= 0 {+ return+ }++ storage.Usage = clampFloat(usage, 0, 100)+ storage.Used = int64(float64(storage.Total) * (storage.Usage / 100.0))+ if storage.Used < 0 {+ storage.Used = 0+ }+ if storage.Used > storage.Total {+ storage.Used = storage.Total+ }+ storage.Free = storage.Total - storage.Used+ if storage.Free < 0 {+ storage.Free = 0+ }+}++func maxFloat(a, b float64) float64 {+ if a > b {+ return a+ }+ return b+}diff --git a/internal/mockmodel/metrics.go b/internal/mockmodel/metrics.gonew file mode 100644index 0000000000..7de79c40e9--- /dev/null+++ b/internal/mockmodel/metrics.go@@ -0,0 +1,655 @@+package mockmodel++import (+ "hash/fnv"+ "math"+ "strconv"+ "strings"+ "time"+)++type SeriesStyle int++const (+ StyleSpiky SeriesStyle = iota+ StylePlateau+ StyleFlat+)++type StorageCapacitySeries struct {+ Usage []float64+ Used []float64+ Avail []float64+ Total []float64+}++type metricProfile int++const (+ profileCompute metricProfile = iota+ profileMemory+ profileDiskIO+ profileNetwork+ profileCapacity+ profileThermal+ profileFlat+)++type metricRoleModifiers struct {+ steadyStateScale float64+ activityScale float64+ diurnalScale float64+ burstScale float64+ maintenanceScale float64+ memoryBaseScale float64+ memoryDriftScale float64+ storageDriftScale float64+ thermalScale float64+}++func normalizeMetricRole(role string) string {+ role = strings.ToLower(strings.TrimSpace(role))+ if role == "" {+ return "general"+ }+ return role+}++func metricRoleProfile(role string) metricRoleModifiers {+ switch normalizeMetricRole(role) {+ case "web":+ return metricRoleModifiers{steadyStateScale: 0.95, activityScale: 0.95, diurnalScale: 1.35, burstScale: 1.15, maintenanceScale: 0.7, memoryBaseScale: 0.92, memoryDriftScale: 0.95, storageDriftScale: 0.88, thermalScale: 1.0}+ case "api":+ return metricRoleModifiers{steadyStateScale: 1.0, activityScale: 1.1, diurnalScale: 1.15, burstScale: 1.2, maintenanceScale: 0.85, memoryBaseScale: 1.0, memoryDriftScale: 1.05, storageDriftScale: 0.92, thermalScale: 1.04}+ case "database":+ return metricRoleModifiers{steadyStateScale: 1.22, activityScale: 0.82, diurnalScale: 0.7, burstScale: 0.8, maintenanceScale: 1.2, memoryBaseScale: 1.35, memoryDriftScale: 0.72, storageDriftScale: 1.12, thermalScale: 1.08}+ case "cache":+ return metricRoleModifiers{steadyStateScale: 0.82, activityScale: 1.02, diurnalScale: 0.95, burstScale: 1.35, maintenanceScale: 0.65, memoryBaseScale: 1.45, memoryDriftScale: 0.75, storageDriftScale: 0.72, thermalScale: 1.03}+ case "queue", "batch":+ return metricRoleModifiers{steadyStateScale: 0.9, activityScale: 0.95, diurnalScale: 0.85, burstScale: 1.45, maintenanceScale: 1.35, memoryBaseScale: 0.9, memoryDriftScale: 1.15, storageDriftScale: 1.0, thermalScale: 1.06}+ case "monitoring":+ return metricRoleModifiers{steadyStateScale: 1.05, activityScale: 0.8, diurnalScale: 0.85, burstScale: 0.75, maintenanceScale: 0.9, memoryBaseScale: 1.2, memoryDriftScale: 0.7, storageDriftScale: 1.05, thermalScale: 0.98}+ case "backup":+ return metricRoleModifiers{steadyStateScale: 0.58, activityScale: 0.45, diurnalScale: 0.5, burstScale: 0.7, maintenanceScale: 1.95, memoryBaseScale: 0.72, memoryDriftScale: 0.65, storageDriftScale: 1.2, thermalScale: 0.95}+ case "storage":+ return metricRoleModifiers{steadyStateScale: 1.08, activityScale: 0.65, diurnalScale: 0.55, burstScale: 0.6, maintenanceScale: 1.35, memoryBaseScale: 0.96, memoryDriftScale: 0.62, storageDriftScale: 1.28, thermalScale: 1.02}+ case "ingress":+ return metricRoleModifiers{steadyStateScale: 0.88, activityScale: 1.0, diurnalScale: 1.25, burstScale: 1.3, maintenanceScale: 0.65, memoryBaseScale: 0.82, memoryDriftScale: 0.88, storageDriftScale: 0.8, thermalScale: 1.0}+ case "ci":+ return metricRoleModifiers{steadyStateScale: 0.86, activityScale: 1.08, diurnalScale: 0.92, burstScale: 1.5, maintenanceScale: 1.25, memoryBaseScale: 1.02, memoryDriftScale: 1.22, storageDriftScale: 0.95, thermalScale: 1.08}+ case "media":+ return metricRoleModifiers{steadyStateScale: 1.0, activityScale: 1.05, diurnalScale: 1.45, burstScale: 1.28, maintenanceScale: 0.8, memoryBaseScale: 1.05, memoryDriftScale: 0.98, storageDriftScale: 1.0, thermalScale: 1.12}+ case "security":+ return metricRoleModifiers{steadyStateScale: 0.84, activityScale: 0.9, diurnalScale: 0.95, burstScale: 1.0, maintenanceScale: 0.85, memoryBaseScale: 0.9, memoryDriftScale: 0.72, storageDriftScale: 0.85, thermalScale: 1.0}+ default:+ return metricRoleModifiers{steadyStateScale: 1.0, activityScale: 1.0, diurnalScale: 1.0, burstScale: 1.0, maintenanceScale: 1.0, memoryBaseScale: 1.0, memoryDriftScale: 1.0, storageDriftScale: 1.0, thermalScale: 1.0}+ }+}++func NormalizeBlendWeight(weight float64, step, reference time.Duration) float64 {+ if weight <= 0 {+ return 0.01+ }+ if weight >= 1 {+ return 1+ }+ if step <= 0 || reference <= 0 || step == reference {+ return weight+ }++ ratio := float64(step) / float64(reference)+ normalized := 1 - math.Pow(1-weight, ratio)+ return clampFloat(normalized, 0.0005, 0.999)+}++func StyleSpeed(style SeriesStyle) float64 {+ switch style {+ case StylePlateau:+ return 0.5+ case StyleFlat:+ return 0.12+ default:+ return 1.0+ }+}++func ValueAt(seed uint64, min, max float64, speed float64, at time.Time) float64 {+ return valueAtProfile(seed, min, max, profileFromSpeed(speed), at)+}++func ValueAtMetric(seed uint64, min, max float64, metric string, speed float64, at time.Time) float64 {+ return ValueAtMetricWithRole(seed, min, max, metric, speed, "", at)+}++func ValueAtMetricWithRole(+ seed uint64,+ min, max float64,+ metric string,+ speed float64,+ role string,+ at time.Time,+) float64 {+ return valueAtProfileWithRole(seed, min, max, profileFromMetric(metric, profileFromSpeed(speed)), role, at)+}++func SeriesForTimestamps(current float64, timestamps []time.Time, seed uint64, min, max float64, style SeriesStyle) []float64 {+ return seriesForProfile(current, timestamps, seed, min, max, profileFromStyle(style))+}++func SeriesForMetricTimestamps(+ current float64,+ timestamps []time.Time,+ seed uint64,+ min float64,+ max float64,+ metric string,+ style SeriesStyle,+) []float64 {+ return SeriesForMetricTimestampsWithRole(current, timestamps, seed, min, max, metric, style, "")+}++func SeriesForMetricTimestampsWithRole(+ current float64,+ timestamps []time.Time,+ seed uint64,+ min float64,+ max float64,+ metric string,+ style SeriesStyle,+ role string,+) []float64 {+ return seriesForProfileWithRole(current, timestamps, seed, min, max, profileFromMetric(metric, profileFromStyle(style)), role)+}++func StorageCapacitySeriesForTimestamps(+ currentUsed float64,+ currentTotal float64,+ timestamps []time.Time,+ seed uint64,+) StorageCapacitySeries {+ return StorageCapacitySeriesForTimestampsWithRole(currentUsed, currentTotal, timestamps, seed, "")+}++func StorageCapacitySeriesForTimestampsWithRole(+ currentUsed float64,+ currentTotal float64,+ timestamps []time.Time,+ seed uint64,+ role string,+) StorageCapacitySeries {+ if len(timestamps) == 0 {+ return StorageCapacitySeries{}+ }++ total := math.Max(0, currentTotal)+ if total <= 0 {+ zeros := make([]float64, len(timestamps))+ return StorageCapacitySeries{+ Usage: zeros,+ Used: append([]float64(nil), zeros...),+ Avail: append([]float64(nil), zeros...),+ Total: append([]float64(nil), zeros...),+ }+ }++ used := clampFloat(currentUsed, 0, total)+ currentUsage := clampFloat((used/total)*100, 0, 100)+ usageSeries := SeriesForMetricTimestampsWithRole(currentUsage, timestamps, seed, 0, 100, "usage", StyleFlat, role)++ usedSeries := make([]float64, len(timestamps))+ availSeries := make([]float64, len(timestamps))+ totalSeries := make([]float64, len(timestamps))+ for i, usage := range usageSeries {+ totalSeries[i] = total+ occupancy := clampFloat(usage/100, 0, 1)+ usedSeries[i] = total * occupancy+ availSeries[i] = total - usedSeries[i]+ }++ last := len(timestamps) - 1+ usageSeries[last] = currentUsage+ usedSeries[last] = used+ availSeries[last] = total - used+ totalSeries[last] = total++ return StorageCapacitySeries{+ Usage: usageSeries,+ Used: usedSeries,+ Avail: availSeries,+ Total: totalSeries,+ }+}++func seriesForProfile(+ current float64,+ timestamps []time.Time,+ seed uint64,+ min float64,+ max float64,+ profile metricProfile,+) []float64 {+ return seriesForProfileWithRole(current, timestamps, seed, min, max, profile, "")+}++func seriesForProfileWithRole(+ current float64,+ timestamps []time.Time,+ seed uint64,+ min float64,+ max float64,+ profile metricProfile,+ role string,+) []float64 {+ if len(timestamps) == 0 {+ return nil+ }++ current = clampFloat(current, min, max)+ values := make([]float64, len(timestamps))+ for i, ts := range timestamps {+ values[i] = valueAtProfileWithRole(seed, min, max, profile, role, ts)+ }++ now := timestamps[len(timestamps)-1]+ shift := current - values[len(values)-1]+ halfLife := anchorHalfLife(profile)+ for i, ts := range timestamps {+ age := now.Sub(ts)+ if age < 0 {+ age = 0+ }+ values[i] = clampFloat(values[i]+shift*anchorWeight(age, halfLife), min, max)+ }+ values[len(values)-1] = current+ return values+}++func valueAtProfile(seed uint64, min, max float64, profile metricProfile, at time.Time) float64 {+ return valueAtProfileWithRole(seed, min, max, profile, "", at)+}++func valueAtProfileWithRole(seed uint64, min, max float64, profile metricProfile, role string, at time.Time) float64 {+ span := math.Max(1, max-min)+ modifiers := metricRoleProfile(role)+ switch profile {+ case profileMemory:+ return clampFloat(memoryValue(seed, min, span, modifiers, at), min, max)+ case profileDiskIO:+ return clampFloat(diskIOValue(seed, min, span, modifiers, at), min, max)+ case profileNetwork:+ return clampFloat(networkValue(seed, min, span, modifiers, at), min, max)+ case profileCapacity:+ return clampFloat(capacityValue(seed, min, span, modifiers, at), min, max)+ case profileThermal:+ return clampFloat(thermalValue(seed, min, span, modifiers, at), min, max)+ case profileFlat:+ return clampFloat(flatValue(seed, min, span, modifiers, at), min, max)+ default:+ return clampFloat(computeValue(seed, min, span, modifiers, at), min, max)+ }+}++func computeValue(seed uint64, min, span float64, modifiers metricRoleModifiers, at time.Time) float64 {+ activity := clamp01(scheduledActivity(seed, at) * modifiers.activityScale)+ utilBias := 0.04 + unitFloat(seed, "cpu-util", 0)*0.12+ platformBias := 0.03 + unitFloat(seed, "cpu-platform", 0)*0.08+ sustained := span * modifiers.steadyStateScale * (utilBias + platformBias + activity*(0.10+unitFloat(seed, "cpu-active", 0)*0.24))+ diurnal := span * modifiers.diurnalScale * scheduledWave(seed, "cpu-diurnal", at, 0.04)+ trend := span * slowTrend(seed, "cpu-trend", at, 6*time.Hour, 24*time.Hour, 0.08)+ chatter := span * (0.008 + activity*0.018) * positiveFloat(seed, "cpu-chatter", at.Unix(), 5*60)+ spikes := span * modifiers.burstScale * (0.08 + activity*0.22 + unitFloat(seed, "cpu-spike-amp", 0)*0.10) *+ eventPulse(seed, "cpu-spike", at, 8*time.Minute, 0.02+activity*0.06)+ batch := span * modifiers.burstScale * (0.05 + activity*0.18) *+ eventPulse(seed, "cpu-batch", at, 36*time.Minute, 0.012+activity*0.03)+ noise := span * 0.004 * interpolatedCenteredFloat(seed, "cpu-noise", at.Unix(), 90)++ return min + sustained + diurnal + trend + chatter + spikes + batch + noise+}++func memoryValue(seed uint64, min, span float64, modifiers metricRoleModifiers, at time.Time) float64 {+ activity := clamp01(scheduledActivity(seed, at) * modifiers.activityScale)+ base := span * modifiers.memoryBaseScale * (0.20 + unitFloat(seed, "mem-base", 0)*0.42)+ workingSet := span * (0.03 + activity*0.07*modifiers.activityScale)+ plateau := span * 0.11 * modifiers.memoryDriftScale * plateauComponent(seed, "mem-plateau", at, 6*time.Hour, 0.16)+ trend := span * 0.05 * modifiers.memoryDriftScale * plateauComponent(seed, "mem-trend", at, 24*time.Hour, 0.10)+ hotset := span * (0.006 + activity*0.018) * positiveFloat(seed, "mem-hotset", at.Unix(), 20*60)+ reclaim := span * (0.02 + unitFloat(seed, "mem-reclaim", 0)*0.05) *+ eventPulse(seed, "mem-reclaim", at, 12*time.Hour, 0.04)+ noise := span * 0.0015 * interpolatedCenteredFloat(seed, "mem-noise", at.Unix(), 5*60)++ return min + base + workingSet + plateau + trend + hotset - reclaim + noise+}++func diskIOValue(seed uint64, min, span float64, modifiers metricRoleModifiers, at time.Time) float64 {+ activity := clamp01(scheduledActivity(seed, at) * modifiers.activityScale)+ backup := maintenanceWindow(seed, at) * modifiers.maintenanceScale+ base := span * modifiers.steadyStateScale * (0.015 + unitFloat(seed, "io-base", 0)*0.035)+ sustained := span * activity * modifiers.steadyStateScale * (0.03 + unitFloat(seed, "io-active", 0)*0.07)+ backupLoad := span * backup * (0.05 + unitFloat(seed, "io-backup", 0)*0.10)+ bursts := span * modifiers.burstScale * (0.10 + activity*0.12 + backup*0.18) *+ eventPulse(seed, "io-burst", at, 12*time.Minute, 0.04+activity*0.05+backup*0.03)+ sweeps := span * modifiers.maintenanceScale * (0.06 + backup*0.18) *+ eventPulse(seed, "io-sweep", at, 48*time.Minute, 0.02+backup*0.05)+ chatter := span * (0.006 + activity*0.010) * positiveFloat(seed, "io-chatter", at.Unix(), 8*60)+ noise := span * 0.003 * interpolatedCenteredFloat(seed, "io-noise", at.Unix(), 120)++ return min + base + sustained + backupLoad + bursts + sweeps + chatter + noise+}++func networkValue(seed uint64, min, span float64, modifiers metricRoleModifiers, at time.Time) float64 {+ activity := clamp01(scheduledActivity(seed, at) * modifiers.activityScale)+ backup := maintenanceWindow(seed+17, at) * 0.45 * modifiers.maintenanceScale+ base := span * modifiers.steadyStateScale * (0.012 + unitFloat(seed, "net-base", 0)*0.04)+ flow := span * activity * modifiers.steadyStateScale * (0.05 + unitFloat(seed, "net-flow", 0)*0.09)+ diurnal := span * modifiers.diurnalScale * scheduledWave(seed, "net-diurnal", at, 0.05)+ bursts := span * modifiers.burstScale * (0.08 + activity*0.16 + backup*0.12) *+ eventPulse(seed, "net-burst", at, 7*time.Minute, 0.05+activity*0.07)+ sessions := span * modifiers.burstScale * (0.05 + activity*0.14) *+ eventPulse(seed, "net-session", at, 28*time.Minute, 0.025+activity*0.03+backup*0.02)+ chatter := span * (0.008 + activity*0.012) * positiveFloat(seed, "net-chatter", at.Unix(), 4*60)+ noise := span * 0.003 * interpolatedCenteredFloat(seed, "net-noise", at.Unix(), 90)++ return min + base + flow + diurnal + bursts + sessions + chatter + noise+}++func capacityValue(seed uint64, min, span float64, modifiers metricRoleModifiers, at time.Time) float64 {+ base := span * modifiers.steadyStateScale * (0.20 + unitFloat(seed, "capacity-base", 0)*0.58)+ cycle := capacityCycle(seed, at)+ drift := span * 0.05 * modifiers.storageDriftScale * plateauComponent(seed, "capacity-drift", at, 36*time.Hour, 0.08)+ usageWave := span * modifiers.storageDriftScale * (0.07 + unitFloat(seed, "capacity-amp", 0)*0.10) * (cycle - 0.40)+ noise := span * 0.001 * interpolatedCenteredFloat(seed, "capacity-noise", at.Unix(), 30*60)++ return min + base + usageWave + drift + noise+}++func flatValue(seed uint64, min, span float64, modifiers metricRoleModifiers, at time.Time) float64 {+ base := span * modifiers.steadyStateScale * (0.24 + unitFloat(seed, "flat-base", 0)*0.44)+ drift := span * 0.05 * modifiers.storageDriftScale * plateauComponent(seed, "flat-drift", at, 18*time.Hour, 0.12)+ micro := span * 0.012 * interpolatedCenteredFloat(seed, "flat-micro", at.Unix(), 30*60)+ noise := span * 0.001 * interpolatedCenteredFloat(seed, "flat-noise", at.Unix(), 10*60)++ return min + base + drift + micro + noise+}++func thermalValue(seed uint64, min, span float64, modifiers metricRoleModifiers, at time.Time) float64 {+ base := span * modifiers.thermalScale * (0.18 + unitFloat(seed, "thermal-base", 0)*0.22)+ drift := span * 0.02 * plateauComponent(seed, "thermal-drift", at, 24*time.Hour, 0.06)+ diurnal := span * 0.012 * scheduledWave(seed, "thermal-diurnal", at, 1.0)+ chatter := span * 0.004 * interpolatedCenteredFloat(seed, "thermal-chatter", at.Unix(), 45*60)+ noise := span * 0.0007 * interpolatedCenteredFloat(seed, "thermal-noise", at.Unix(), 15*60)++ return min + base + drift + diurnal + chatter + noise+}++func profileFromMetric(metric string, fallback metricProfile) metricProfile {+ switch strings.ToLower(strings.TrimSpace(metric)) {+ case "cpu":+ return profileCompute+ case "memory":+ return profileMemory+ case "diskread", "diskwrite", "diskio", "iops":+ return profileDiskIO+ case "netin", "netout", "network", "rx", "tx":+ return profileNetwork+ case "disk", "usage", "used", "avail", "total", "free", "storage", "capacity":+ return profileCapacity+ case "temperature", "temp", "smart_temp":+ return profileThermal+ default:+ return fallback+ }+}++func profileFromStyle(style SeriesStyle) metricProfile {+ switch style {+ case StylePlateau:+ return profileMemory+ case StyleFlat:+ return profileCapacity+ default:+ return profileCompute+ }+}++func profileFromSpeed(speed float64) metricProfile {+ switch {+ case speed >= 0.8:+ return profileCompute+ case speed >= 0.3:+ return profileMemory+ default:+ return profileCapacity+ }+}++func anchorHalfLife(profile metricProfile) time.Duration {+ switch profile {+ case profileMemory:+ return 18 * time.Hour+ case profileCapacity:+ return 72 * time.Hour+ case profileThermal, profileFlat:+ return 96 * time.Hour+ case profileDiskIO, profileNetwork:+ return 10 * time.Hour+ default:+ return 6 * time.Hour+ }+}++func anchorWeight(age, halfLife time.Duration) float64 {+ if age <= 0 || halfLife <= 0 {+ return 1+ }+ return math.Exp(-math.Ln2 * float64(age) / float64(halfLife))+}++func scheduledActivity(seed uint64, at time.Time) float64 {+ utc := at.UTC()+ hour := float64(utc.Hour()) + float64(utc.Minute())/60 + float64(utc.Second())/3600+ weekday := utc.Weekday()+ mode := seed % 6+ intensity := 0.82 + unitFloat(seed, "schedule-intensity", 0)*0.36+ weekendScale := 0.35 + unitFloat(seed, "weekend-scale", 0)*0.45++ var activity float64+ switch mode {+ case 0: // office-heavy+ activity = 0.05 + 0.72*wrappedPeak(hour, 10.0, 2.2) + 0.58*wrappedPeak(hour, 14.5, 2.6)+ if weekday == time.Saturday || weekday == time.Sunday {+ activity *= weekendScale+ }+ case 1: // always-on SaaS+ activity = 0.38 + 0.18*wrappedPeak(hour, 11.0, 4.5) + 0.14*wrappedPeak(hour, 20.0, 3.6)+ case 2: // evening-heavy+ activity = 0.07 + 0.24*wrappedPeak(hour, 12.5, 3.0) + 0.72*wrappedPeak(hour, 20.0, 2.8)+ if weekday == time.Saturday || weekday == time.Sunday {+ activity *= 1.15+ }+ case 3: // batch/night+ activity = 0.09 + 0.64*wrappedPeak(hour, 1.5, 2.1) + 0.34*wrappedPeak(hour, 5.0, 2.0)+ case 4: // follow-the-sun+ activity = 0.26 + 0.22*wrappedPeak(hour, 8.0, 4.0) + 0.20*wrappedPeak(hour, 16.0, 4.0) + 0.12*wrappedPeak(hour, 22.0, 3.3)+ default: // weekend/media+ activity = 0.08 + 0.28*wrappedPeak(hour, 11.5, 3.3) + 0.62*wrappedPeak(hour, 21.0, 3.0)+ if weekday == time.Saturday || weekday == time.Sunday {+ activity *= 1.22+ } else {+ activity *= 0.85+ }+ }++ return clamp01(activity * intensity)+}++func scheduledWave(seed uint64, label string, at time.Time, amplitude float64) float64 {+ activity := scheduledActivity(seed, at)+ return amplitude * (activity - 0.42)+}++func maintenanceWindow(seed uint64, at time.Time) float64 {+ hour := float64(at.UTC().Hour()) + float64(at.UTC().Minute())/60+ center := unitFloat(seed, "maintenance-hour", 0) * 24+ width := 0.9 + unitFloat(seed, "maintenance-width", 0)*1.7+ strength := 0.35 + unitFloat(seed, "maintenance-strength", 0)*0.65+ return wrappedPeak(hour, center, width) * strength+}++func slowTrend(seed uint64, label string, at time.Time, shortWindow, longWindow time.Duration, amplitude float64) float64 {+ short := interpolatedCenteredFloat(seed, label+"-short", at.Unix(), int64(shortWindow/time.Second))+ long := interpolatedCenteredFloat(seed, label+"-long", at.Unix(), int64(longWindow/time.Second))+ return amplitude * (short*0.45 + long*0.55)+}++func plateauComponent(seed uint64, label string, at time.Time, window time.Duration, transitionFraction float64) float64 {+ seconds := int64(window / time.Second)+ if seconds <= 0 {+ return centeredFloat(seed, label, 0)+ }+ if transitionFraction <= 0 {+ transitionFraction = 0.1+ }+ if transitionFraction >= 1 {+ transitionFraction = 0.95+ }++ bucket := floorDiv(at.Unix(), seconds)+ progress := float64(mod(at.Unix(), seconds)) / float64(seconds)+ current := centeredFloat(seed, label, bucket)+ startTransition := 1 - transitionFraction+ if progress <= startTransition {+ return current+ }++ next := centeredFloat(seed, label, bucket+1)+ t := smoothstep((progress - startTransition) / transitionFraction)+ return current*(1-t) + next*t+}++func capacityCycle(seed uint64, at time.Time) float64 {+ cycleHours := 42 + unitFloat(seed, "capacity-cycle", 0)*120+ offset := unitFloat(seed, "capacity-offset", 0) * cycleHours+ phase := math.Mod(float64(at.Unix())/3600+offset, cycleHours) / cycleHours+ if phase < 0.9 {+ return phase / 0.9+ }+ return 1 - smoothstep((phase-0.9)/0.1)+}++func eventPulse(seed uint64, label string, at time.Time, window time.Duration, probability float64) float64 {+ seconds := int64(window / time.Second)+ if seconds <= 0 {+ return 0+ }+ probability = clampFloat(probability, 0, 0.92)+ bucket := floorDiv(at.Unix(), seconds)+ if unitFloat(seed, label+"-gate", bucket) >= probability {+ return 0+ }++ progress := float64(mod(at.Unix(), seconds)) / float64(seconds)+ riseFraction := 0.08 + unitFloat(seed, label+"-rise", bucket)*0.18+ if progress <= riseFraction {+ return progress / riseFraction+ }++ decay := (progress - riseFraction) / math.Max(1e-6, 1-riseFraction)+ power := 1.2 + unitFloat(seed, label+"-power", bucket)*2.2+ return math.Pow(1-decay, power)+}++func positiveFloat(seed uint64, label string, unixSeconds, window int64) float64 {+ return math.Max(0, interpolatedCenteredFloat(seed, label, unixSeconds, window))+}++func wrappedPeak(hour, center, width float64) float64 {+ if width <= 0 {+ width = 1+ }+ delta := math.Abs(hour - center)+ if delta > 12 {+ delta = 24 - delta+ }+ x := delta / width+ return math.Exp(-0.5 * x * x)+}++func clamp01(value float64) float64 {+ return clampFloat(value, 0, 1)+}++func interpolatedCenteredFloat(seed uint64, label string, unixSeconds, window int64) float64 {+ if window <= 0 {+ return centeredFloat(seed, label, 0)+ }++ bucket := floorDiv(unixSeconds, window)+ progress := float64(mod(unixSeconds, window)) / float64(window)+ a := centeredFloat(seed, label, bucket)+ b := centeredFloat(seed, label, bucket+1)+ t := smoothstep(progress)+ return a*(1-t) + b*t+}++func centeredFloat(seed uint64, label string, bucket int64) float64 {+ return unitFloat(seed, label, bucket)*2 - 1+}++func unitFloat(seed uint64, label string, bucket int64) float64 {+ hash := hashKey(seed, label, bucket)+ const mask = uint64(1<<53) - 1+ return float64(hash&mask) / float64(mask)+}++func hashKey(seed uint64, label string, bucket int64) uint64 {+ h := fnv.New64a()+ _, _ = h.Write([]byte(strconv.FormatUint(seed, 10)))+ _, _ = h.Write([]byte{0})+ _, _ = h.Write([]byte(label))+ _, _ = h.Write([]byte{0})+ _, _ = h.Write([]byte(strconv.FormatInt(bucket, 10)))+ return h.Sum64()+}++func smoothstep(t float64) float64 {+ if t <= 0 {+ return 0+ }+ if t >= 1 {+ return 1+ }+ return t * t * (3 - 2*t)+}++func floorDiv(value, divisor int64) int64 {+ if divisor == 0 {+ return 0+ }+ quotient := value / divisor+ remainder := value % divisor+ if remainder != 0 && ((remainder < 0) != (divisor < 0)) {+ quotient--+ }+ return quotient+}++func mod(value, divisor int64) int64 {+ if divisor == 0 {+ return 0+ }+ remainder := value % divisor+ if remainder < 0 {+ remainder += divisor+ }+ return remainder+}++func clampFloat(value, min, max float64) float64 {+ if value < min {+ return min+ }+ if value > max {+ return max+ }+ return value+}diff --git a/internal/mockmodel/metrics_test.go b/internal/mockmodel/metrics_test.gonew file mode 100644index 0000000000..7b0f50a0d7--- /dev/null+++ b/internal/mockmodel/metrics_test.go@@ -0,0 +1,181 @@+package mockmodel++import (+ "math"+ "testing"+ "time"+)++func TestValueAtMetric_CPUTracksActivityWindows(t *testing.T) {+ seed := uint64(0) // office-heavy persona+ day := time.Date(2026, time.March, 31, 10, 30, 0, 0, time.UTC)+ night := time.Date(2026, time.March, 31, 3, 30, 0, 0, time.UTC)++ dayValue := ValueAtMetric(seed, 0, 100, "cpu", 1.0, day)+ nightValue := ValueAtMetric(seed, 0, 100, "cpu", 1.0, night)+ if dayValue <= nightValue+8 {+ t.Fatalf("expected office-hour cpu value to exceed overnight value, got day=%f night=%f", dayValue, nightValue)+ }+}++func TestSeriesForMetricTimestamps_AnchorsTailWithoutRebasingHistory(t *testing.T) {+ now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC)+ timestamps := make([]time.Time, 0, 7*24+1)+ for ts := now.Add(-7 * 24 * time.Hour); !ts.After(now); ts = ts.Add(time.Hour) {+ timestamps = append(timestamps, ts)+ }++ seed := uint64(42)+ baseCurrent := ValueAtMetric(seed, 0, 100, "cpu", 1.0, now)+ baseline := SeriesForMetricTimestamps(baseCurrent, timestamps, seed, 0, 100, "cpu", StyleSpiky)+ anchored := SeriesForMetricTimestamps(baseCurrent+24, timestamps, seed, 0, 100, "cpu", StyleSpiky)++ if anchored[len(anchored)-1] != baseCurrent+24 {+ t.Fatalf("expected anchored tail to match current, got %f want %f", anchored[len(anchored)-1], baseCurrent+24)+ }++ farDelta := math.Abs(anchored[0] - baseline[0])+ recentDelta := math.Abs(anchored[len(anchored)-2] - baseline[len(baseline)-2])+ if farDelta >= recentDelta {+ t.Fatalf("expected tail anchoring to affect recent points more than far history, got far=%f recent=%f", farDelta, recentDelta)+ }+ if farDelta > 2.5 {+ t.Fatalf("expected 7d-old history to remain mostly intact, got far delta %f", farDelta)+ }+}++func TestSeriesForMetricTimestamps_MemoryAndCapacityStaySmootherThanCPU(t *testing.T) {+ now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC)+ timestamps := make([]time.Time, 0, 7*24+1)+ for ts := now.Add(-7 * 24 * time.Hour); !ts.After(now); ts = ts.Add(time.Hour) {+ timestamps = append(timestamps, ts)+ }++ cpuSeed := uint64(0)+ memSeed := uint64(11)+ diskSeed := uint64(23)++ cpuCurrent := ValueAtMetric(cpuSeed, 0, 100, "cpu", 1.0, now)+ memCurrent := ValueAtMetric(memSeed, 0, 100, "memory", 0.5, now)+ diskCurrent := ValueAtMetric(diskSeed, 0, 100, "usage", 0.12, now)++ cpuSeries := SeriesForMetricTimestamps(cpuCurrent, timestamps, cpuSeed, 0, 100, "cpu", StyleSpiky)+ memSeries := SeriesForMetricTimestamps(memCurrent, timestamps, memSeed, 0, 100, "memory", StylePlateau)+ diskSeries := SeriesForMetricTimestamps(diskCurrent, timestamps, diskSeed, 0, 100, "usage", StyleFlat)++ cpuStep := averageAdjacentDelta(cpuSeries)+ memStep := averageAdjacentDelta(memSeries)+ diskStep := averageAdjacentDelta(diskSeries[len(diskSeries)-7:])+ diskRange := seriesRange(diskSeries)++ if memStep >= cpuStep {+ t.Fatalf("expected memory to move more smoothly than cpu, got mem=%f cpu=%f", memStep, cpuStep)+ }+ if diskStep > 3 {+ t.Fatalf("expected short-term capacity movement to stay gentle, got average 6h delta %f", diskStep)+ }+ if diskRange < 2 {+ t.Fatalf("expected weekly capacity series to show meaningful drift, got range %f", diskRange)+ }+}++func TestStorageCapacitySeriesForTimestamps_KeepsStorageMetricsAligned(t *testing.T) {+ now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC)+ timestamps := make([]time.Time, 0, 7*24+1)+ for ts := now.Add(-7 * 24 * time.Hour); !ts.After(now); ts = ts.Add(time.Hour) {+ timestamps = append(timestamps, ts)+ }++ total := 10.0 * 1024 * 1024 * 1024 * 1024+ used := 6.2 * 1024 * 1024 * 1024 * 1024+ series := StorageCapacitySeriesForTimestamps(used, total, timestamps, 77)++ if len(series.Usage) != len(timestamps) || len(series.Used) != len(timestamps) || len(series.Avail) != len(timestamps) {+ t.Fatalf("expected aligned storage series lengths, got usage=%d used=%d avail=%d", len(series.Usage), len(series.Used), len(series.Avail))+ }++ last := len(timestamps) - 1+ if math.Abs(series.Used[last]-used) > 0.5 {+ t.Fatalf("expected tail used bytes to match current value, got %f want %f", series.Used[last], used)+ }+ if math.Abs(series.Avail[last]-(total-used)) > 0.5 {+ t.Fatalf("expected tail available bytes to complement used bytes, got %f want %f", series.Avail[last], total-used)+ }++ for i := range timestamps {+ if math.Abs((series.Used[i]+series.Avail[i])-series.Total[i]) > 0.5 {+ t.Fatalf("expected used+avail to equal total at index %d", i)+ }+ if math.Abs(series.Usage[i]-((series.Used[i]/series.Total[i])*100)) > 0.001 {+ t.Fatalf("expected usage percent to match used/total at index %d", i)+ }+ }+}++func TestSeriesForMetricTimestamps_SmartTempUsesThermalProfile(t *testing.T) {+ now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC)+ timestamps := make([]time.Time, 0, 7*24+1)+ for ts := now.Add(-7 * 24 * time.Hour); !ts.After(now); ts = ts.Add(time.Hour) {+ timestamps = append(timestamps, ts)+ }++ series := SeriesForMetricTimestamps(42, timestamps, 19, 25, 95, "smart_temp", StyleFlat)+ if got := seriesRange(series); got > 10 {+ t.Fatalf("expected thermal history to remain gentle, got range %f", got)+ }+}++func TestValueAtMetricWithRole_DatabaseRunsHotterOnMemoryThanWeb(t *testing.T) {+ seed := uint64(17)+ at := time.Date(2026, time.March, 31, 14, 0, 0, 0, time.UTC)++ database := ValueAtMetricWithRole(seed, 0, 100, "memory", 0.5, "database", at)+ web := ValueAtMetricWithRole(seed, 0, 100, "memory", 0.5, "web", at)+ if database <= web+8 {+ t.Fatalf("expected database memory profile to sit materially above web profile, got database=%f web=%f", database, web)+ }+}++func TestSeriesForMetricTimestampsWithRole_WebNetworkVariesMoreThanDatabase(t *testing.T) {+ now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC)+ timestamps := make([]time.Time, 0, 48)+ for ts := now.Add(-47 * time.Hour); !ts.After(now); ts = ts.Add(time.Hour) {+ timestamps = append(timestamps, ts)+ }++ seed := uint64(29)+ current := ValueAtMetricWithRole(seed, 0, 100, "netin", 1.0, "web", now)+ web := SeriesForMetricTimestampsWithRole(current, timestamps, seed, 0, 100, "netin", StyleSpiky, "web")+ database := SeriesForMetricTimestampsWithRole(current, timestamps, seed, 0, 100, "netin", StyleSpiky, "database")+ if seriesRange(web) <= seriesRange(database)+4 {+ t.Fatalf("expected web network profile to vary more than database network profile, got web=%f database=%f", seriesRange(web), seriesRange(database))+ }+}++func averageAdjacentDelta(series []float64) float64 {+ if len(series) < 2 {+ return 0+ }+ total := 0.0+ for i := 1; i < len(series); i++ {+ total += math.Abs(series[i] - series[i-1])+ }+ return total / float64(len(series)-1)+}++func seriesRange(series []float64) float64 {+ if len(series) == 0 {+ return 0+ }+ minValue := series[0]+ maxValue := series[0]+ for _, value := range series[1:] {+ if value < minValue {+ minValue = value+ }+ if value > maxValue {+ maxValue = value+ }+ }+ return maxValue - minValue+}diff --git a/internal/monitoring/mock_metrics_history.go b/internal/monitoring/mock_metrics_history.goindex be5311333a..b34916c6e7 100644--- a/internal/monitoring/mock_metrics_history.go+++ b/internal/monitoring/mock_metrics_history.go@@ -313,6 +313,42 @@ func GenerateSeededMetricSeriesForTimestamps(max float64,metricType string,style SeriesStyle,+) []float64 {+ return GenerateSeededMetricSeriesForTimestampsWithRole(current, timestamps, seed, min, max, metricType, style, "")+}++func GenerateSeededResourceMetricSeriesForTimestamps(+ current float64,+ timestamps []time.Time,+ resourceType string,+ resourceID string,+ metricType string,+ style SeriesStyle,+) []float64 {+ min, max := mock.MetricBoundsForResource(resourceType, resourceID, metricType)+ seed := mock.MetricSeed(resourceType, resourceID, metricType)+ role := mock.MetricRole(resourceType, resourceID)+ return GenerateSeededMetricSeriesForTimestampsWithRole(+ current,+ timestamps,+ seed,+ min,+ max,+ metricType,+ style,+ role,+ )+}++func GenerateSeededMetricSeriesForTimestampsWithRole(+ current float64,+ timestamps []time.Time,+ seed uint64,+ min float64,+ max float64,+ metricType string,+ style SeriesStyle,+ role string,) []float64 {var mappedStyle mockmodel.SeriesStyleswitch style {@@ -323,7 +359,7 @@ func GenerateSeededMetricSeriesForTimestamps(default:mappedStyle = mockmodel.StyleSpiky}- return mockmodel.SeriesForMetricTimestamps(current, timestamps, seed, min, max, metricType, mappedStyle)+ return mockmodel.SeriesForMetricTimestampsWithRole(current, timestamps, seed, min, max, metricType, mappedStyle, role)}// generateSpikySeries produces a low baseline with occasional sharp spikes —@@ -533,9 +569,6 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.FiseedTimestamps := buildTieredTimestamps(now, seedDuration)const seedBatchSize = 5000numPoints := len(seedTimestamps)- generateSeries := func(metricType string, current float64, seed uint64, min, max float64, style SeriesStyle) []float64 {- return GenerateSeededMetricSeriesForTimestamps(current, seedTimestamps, seed, min, max, metricType, style)- }var seedBatch []metrics.WriteMetricqueueMetric := func(resourceType, resourceID, metricType string, value float64, ts time.Time) {if ms == nil {@@ -570,11 +603,12 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fireturn}- series := mockmodel.StorageCapacitySeriesForTimestamps(+ series := mockmodel.StorageCapacitySeriesForTimestampsWithRole(currentUsed,currentTotal,seedTimestamps,mock.MetricSeed("storage", storageID, "usage"),+ mock.MetricRole("storage", storageID),)for i := 0; i < numPoints; i++ {ts := seedTimestamps[i]@@ -604,12 +638,13 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fireturn}- cpuMin, cpuMax := mock.MetricBounds("node", "cpu")- memMin, memMax := mock.MetricBounds("node", "memory")- diskMin, diskMax := mock.MetricBounds("node", "disk")- cpuSeries := generateSeries("cpu", node.CPU*100, mock.MetricSeed("node", node.ID, "cpu"), cpuMin, cpuMax, styleSpiky)- memSeries := generateSeries("memory", node.Memory.Usage, mock.MetricSeed("node", node.ID, "memory"), memMin, memMax, stylePlateau)- diskSeries := generateSeries("disk", node.Disk.Usage, mock.MetricSeed("node", node.ID, "disk"), diskMin, diskMax, styleFlat)+ role := mock.MetricRole("node", node.ID)+ cpuMin, cpuMax := mock.MetricBoundsForResource("node", node.ID, "cpu")+ memMin, memMax := mock.MetricBoundsForResource("node", node.ID, "memory")+ diskMin, diskMax := mock.MetricBoundsForResource("node", node.ID, "disk")+ cpuSeries := GenerateSeededMetricSeriesForTimestampsWithRole(node.CPU*100, seedTimestamps, mock.MetricSeed("node", node.ID, "cpu"), cpuMin, cpuMax, "cpu", styleSpiky, role)+ memSeries := GenerateSeededMetricSeriesForTimestampsWithRole(node.Memory.Usage, seedTimestamps, mock.MetricSeed("node", node.ID, "memory"), memMin, memMax, "memory", stylePlateau, role)+ diskSeries := GenerateSeededMetricSeriesForTimestampsWithRole(node.Disk.Usage, seedTimestamps, mock.MetricSeed("node", node.ID, "disk"), diskMin, diskMax, "disk", styleFlat, role)for i := 0; i < numPoints; i++ {ts := seedTimestamps[i]@@ -657,27 +692,28 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fireturn}- cpuMin, cpuMax := mock.MetricBounds(storeType, "cpu")- memMin, memMax := mock.MetricBounds(storeType, "memory")- diskMin, diskMax := mock.MetricBounds(storeType, "disk")- readMin, readMax := mock.MetricBounds(storeType, "diskread")- writeMin, writeMax := mock.MetricBounds(storeType, "diskwrite")- netInMin, netInMax := mock.MetricBounds(storeType, "netin")- netOutMin, netOutMax := mock.MetricBounds(storeType, "netout")- cpuSeries := generateSeries("cpu", cpuPercent, mock.MetricSeed(storeType, storeID, "cpu"), cpuMin, cpuMax, styleSpiky)- memSeries := generateSeries("memory", memPercent, mock.MetricSeed(storeType, storeID, "memory"), memMin, memMax, stylePlateau)+ role := mock.MetricRole(storeType, storeID)+ cpuMin, cpuMax := mock.MetricBoundsForResource(storeType, storeID, "cpu")+ memMin, memMax := mock.MetricBoundsForResource(storeType, storeID, "memory")+ diskMin, diskMax := mock.MetricBoundsForResource(storeType, storeID, "disk")+ readMin, readMax := mock.MetricBoundsForResource(storeType, storeID, "diskread")+ writeMin, writeMax := mock.MetricBoundsForResource(storeType, storeID, "diskwrite")+ netInMin, netInMax := mock.MetricBoundsForResource(storeType, storeID, "netin")+ netOutMin, netOutMax := mock.MetricBoundsForResource(storeType, storeID, "netout")+ cpuSeries := GenerateSeededMetricSeriesForTimestampsWithRole(cpuPercent, seedTimestamps, mock.MetricSeed(storeType, storeID, "cpu"), cpuMin, cpuMax, "cpu", styleSpiky, role)+ memSeries := GenerateSeededMetricSeriesForTimestampsWithRole(memPercent, seedTimestamps, mock.MetricSeed(storeType, storeID, "memory"), memMin, memMax, "memory", stylePlateau, role)var diskSeries []float64if includeDisk {- diskSeries = generateSeries("disk", diskPercent, mock.MetricSeed(storeType, storeID, "disk"), diskMin, diskMax, styleFlat)+ diskSeries = GenerateSeededMetricSeriesForTimestampsWithRole(diskPercent, seedTimestamps, mock.MetricSeed(storeType, storeID, "disk"), diskMin, diskMax, "disk", styleFlat, role)}var diskReadSeries, diskWriteSeries, netInSeries, netOutSeries []float64if includeDiskIO {- diskReadSeries = generateSeries("diskread", diskRead, mock.MetricSeed(storeType, storeID, "diskread"), readMin, readMax, styleSpiky)- diskWriteSeries = generateSeries("diskwrite", diskWrite, mock.MetricSeed(storeType, storeID, "diskwrite"), writeMin, writeMax, styleSpiky)+ diskReadSeries = GenerateSeededMetricSeriesForTimestampsWithRole(diskRead, seedTimestamps, mock.MetricSeed(storeType, storeID, "diskread"), readMin, readMax, "diskread", styleSpiky, role)+ diskWriteSeries = GenerateSeededMetricSeriesForTimestampsWithRole(diskWrite, seedTimestamps, mock.MetricSeed(storeType, storeID, "diskwrite"), writeMin, writeMax, "diskwrite", styleSpiky, role)}if includeNetwork {- netInSeries = generateSeries("netin", netIn, mock.MetricSeed(storeType, storeID, "netin"), netInMin, netInMax, styleSpiky)- netOutSeries = generateSeries("netout", netOut, mock.MetricSeed(storeType, storeID, "netout"), netOutMin, netOutMax, styleSpiky)+ netInSeries = GenerateSeededMetricSeriesForTimestampsWithRole(netIn, seedTimestamps, mock.MetricSeed(storeType, storeID, "netin"), netInMin, netInMax, "netin", styleSpiky, role)+ netOutSeries = GenerateSeededMetricSeriesForTimestampsWithRole(netOut, seedTimestamps, mock.MetricSeed(storeType, storeID, "netout"), netOutMin, netOutMax, "netout", styleSpiky, role)}for i := 0; i < numPoints; i++ {@@ -868,8 +904,17 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Ficontinue}- tempMin, tempMax := mock.MetricBounds("disk", "smart_temp")- tempSeries := generateSeries("smart_temp", float64(disk.Temperature), mock.MetricSeed("disk", resourceID, "smart_temp"), tempMin, tempMax, styleFlat)+ tempMin, tempMax := mock.MetricBoundsForResource("disk", resourceID, "smart_temp")+ tempSeries := GenerateSeededMetricSeriesForTimestampsWithRole(+ float64(disk.Temperature),+ seedTimestamps,+ mock.MetricSeed("disk", resourceID, "smart_temp"),+ tempMin,+ tempMax,+ "smart_temp",+ styleFlat,+ mock.MetricRole("disk", resourceID),+ )for i := 0; i < numPoints; i++ {ts := seedTimestamps[i]mh.AddDiskMetric(resourceID, "smart_temp", tempSeries[i], ts)@@ -894,7 +939,16 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Ficontinue}- usageSeries := generateSeries("usage", cluster.UsagePercent, mock.MetricSeed("ceph", cephID, "usage"), 0, 100, styleFlat)+ usageSeries := GenerateSeededMetricSeriesForTimestampsWithRole(+ cluster.UsagePercent,+ seedTimestamps,+ mock.MetricSeed("ceph", cephID, "usage"),+ 0,+ 100,+ "usage",+ styleFlat,+ mock.MetricRole("ceph", cephID),+ )for i := 0; i < numPoints; i++ {ts := seedTimestamps[i]queueMetric("ceph", cephID, "usage", usageSeries[i], ts)@@ -1010,14 +1064,23 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fiif pool.TotalBytes > 0 {diskPercent = float64(pool.UsedBytes) / float64(pool.TotalBytes) * 100}- diskSeries := generateSeries("usage", diskPercent, mock.MetricSeed("pool", pool.Name, "disk"), 0, 100, styleFlat)+ diskSeries := GenerateSeededMetricSeriesForTimestampsWithRole(+ diskPercent,+ seedTimestamps,+ mock.MetricSeed("storage", poolKey, "usage"),+ 0,+ 100,+ "usage",+ styleFlat,+ mock.MetricRole("storage", poolKey),+ )for i := 0; i < numPoints; i++ {ts := seedTimestamps[i]mh.AddGuestMetric(poolKey, "disk", diskSeries[i], ts)- queueMetric("pool", pool.Name, "disk", diskSeries[i], ts)+ queueMetric("storage", poolKey, "usage", diskSeries[i], ts)}mh.AddGuestMetric(poolKey, "disk", diskPercent, now)- queueMetric("pool", pool.Name, "disk", diskPercent, now)+ queueMetric("storage", poolKey, "usage", diskPercent, now)recordStorageTimeline(poolKey, float64(pool.UsedBytes), float64(pool.TotalBytes))}@@ -1028,14 +1091,23 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fiif totalBytes > 0 {diskPercent = float64(dataset.UsedBytes) / float64(totalBytes) * 100}- diskSeries := generateSeries("usage", diskPercent, mock.MetricSeed("dataset", dataset.Name, "disk"), 0, 100, styleFlat)+ diskSeries := GenerateSeededMetricSeriesForTimestampsWithRole(+ diskPercent,+ seedTimestamps,+ mock.MetricSeed("storage", dsKey, "usage"),+ 0,+ 100,+ "usage",+ styleFlat,+ mock.MetricRole("storage", dsKey),+ )for i := 0; i < numPoints; i++ {ts := seedTimestamps[i]mh.AddGuestMetric(dsKey, "disk", diskSeries[i], ts)- queueMetric("dataset", dataset.Name, "disk", diskSeries[i], ts)+ queueMetric("storage", dsKey, "usage", diskSeries[i], ts)}mh.AddGuestMetric(dsKey, "disk", diskPercent, now)- queueMetric("dataset", dataset.Name, "disk", diskPercent, now)+ queueMetric("storage", dsKey, "usage", diskPercent, now)recordStorageTimeline(dsKey, float64(dataset.UsedBytes), float64(totalBytes))}@@ -1048,7 +1120,17 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Ficontinue}- tempSeries := generateSeries("smart_temp", float64(disk.Temperature), mock.MetricSeed("disk", resourceID, "smart_temp"), 25, 95, styleFlat)+ tempMin, tempMax := mock.MetricBoundsForResource("disk", resourceID, "smart_temp")+ tempSeries := GenerateSeededMetricSeriesForTimestampsWithRole(+ float64(disk.Temperature),+ seedTimestamps,+ mock.MetricSeed("disk", resourceID, "smart_temp"),+ tempMin,+ tempMax,+ "smart_temp",+ styleFlat,+ mock.MetricRole("disk", resourceID),+ )for i := 0; i < numPoints; i++ {ts := seedTimestamps[i]mh.AddDiskMetric(resourceID, "smart_temp", tempSeries[i], ts)diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.goindex fdac38d535..d161bab252 100644--- a/internal/monitoring/mock_metrics_history_test.go+++ b/internal/monitoring/mock_metrics_history_test.go@@ -478,12 +478,12 @@ func TestSeedMockMetricsHistory_SeedsTrueNASMetricsStore(t *testing.T) {t.Fatal("expected metrics store to have seeded canonical TrueNAS agent cpu points")}- datasetPoints, err := store.Query("dataset", fixtures.Datasets[0].Name, "disk", now.Add(-7*24*time.Hour), now, 3600)+ datasetPoints, err := store.Query("storage", "dataset:"+fixtures.Datasets[0].Name, "usage", now.Add(-7*24*time.Hour), now, 3600)if err != nil {- t.Fatalf("failed to query TrueNAS dataset disk metrics: %v", err)+ t.Fatalf("failed to query canonical TrueNAS dataset usage metrics: %v", err)}if len(datasetPoints) == 0 {- t.Fatal("expected metrics store to have seeded TrueNAS dataset disk points")+ t.Fatal("expected metrics store to have seeded canonical TrueNAS dataset usage points")}poolUsedPoints, err := store.Query("storage", "pool:"+fixtures.Pools[0].Name, "used", now.Add(-7*24*time.Hour), now, 3600)@@ -900,10 +900,15 @@ func TestGenerateSeededMetricSeriesForTimestamps_UsesSameTimelineAsMockRuntime(t}for _, tc := range cases {- min, max := mock.MetricBounds(tc.resourceType, tc.metricType)current := mock.SampleMetric(tc.resourceType, tc.resourceID, tc.metricType, now)- seed := mock.MetricSeed(tc.resourceType, tc.resourceID, tc.metricType)- series := GenerateSeededMetricSeriesForTimestamps(current, timestamps, seed, min, max, tc.metricType, tc.style)+ series := GenerateSeededResourceMetricSeriesForTimestamps(+ current,+ timestamps,+ tc.resourceType,+ tc.resourceID,+ tc.metricType,+ tc.style,+ )for i, ts := range timestamps {want := mock.SampleMetric(tc.resourceType, tc.resourceID, tc.metricType, ts)diff --git a/tests/integration/tests/48-summary-hover-selection.spec.ts b/tests/integration/tests/48-summary-hover-selection.spec.tsindex 78d3d68179..30a3367c18 100644--- a/tests/integration/tests/48-summary-hover-selection.spec.ts+++ b/tests/integration/tests/48-summary-hover-selection.spec.ts@@ -62,13 +62,37 @@ async function expectSummaryHighlightCount(): Promise<void> {await expect.poll(async () =>- summary.locator("[data-highlight-series-id]").evaluateAll((nodes, expectedId) =>- nodes.filter(- (node) =>- node.getAttribute("data-highlight-series-id") === expectedId &&- node.getAttribute("data-highlight-series-active") === "true",- ).length,- resourceId),+ summary+ .locator("[data-highlight-series-id]")+ .evaluateAll(+ (nodes, expectedId) =>+ nodes.filter(+ (node) =>+ node.getAttribute("data-highlight-series-id") === expectedId &&+ node.getAttribute("data-highlight-series-active") === "true",+ ).length,+ resourceId,+ ),+ )+ .toBe(expectedCount);+}++async function expectActiveIsolatedLineCards(+ summary: import("@playwright/test").Locator,+ expectedCount: number,+): Promise<void> {+ await expect+ .poll(async () =>+ summary+ .locator('[data-active-series-display="isolate"]')+ .evaluateAll(+ (nodes) =>+ nodes.filter(+ (node) =>+ node.getAttribute("data-highlight-series-active") === "true" &&+ node.getAttribute("data-rendered-series-count") === "1",+ ).length,+ ),).toBe(expectedCount);}@@ -141,6 +165,15 @@ test.describe.serial("Summary hover selection", () => {infrastructureRowId,4,);+ await expectActiveIsolatedLineCards(infrastructureSummary, 2);+ await infrastructureRow.click();+ await infrastructureSummary.hover();+ await expectSummaryHighlightCount(+ infrastructureSummary,+ infrastructureRowId,+ 4,+ );+ await expectActiveIsolatedLineCards(infrastructureSummary, 2);await page.goto("/workloads", { waitUntil: "domcontentloaded" });const workloadsSummary = page.getByTestId("workloads-summary");@@ -152,6 +185,7 @@ test.describe.serial("Summary hover selection", () => {expect(workloadRowId).not.toBe("");await workloadRow.hover();await expectSummaryHighlightCount(workloadsSummary, workloadRowId, 4);+ await expectActiveIsolatedLineCards(workloadsSummary, 2);await page.goto("/storage", { waitUntil: "domcontentloaded" });const storageSummary = page.getByTestId("storage-summary");@@ -173,6 +207,7 @@ test.describe.serial("Summary hover selection", () => {expect(storagePoolRowId).not.toBe("");await storagePoolRow.hover();await expectSummaryHighlightCount(storageSummary, storagePoolRowId, 3);+ await expectActiveIsolatedLineCards(storageSummary, 3);await page.getByRole("tab", { name: "Physical Disks" }).click();const storageDiskRow = page.locator("tr[data-row-id]").first();@@ -184,6 +219,7 @@ test.describe.serial("Summary hover selection", () => {expect(storageDiskRowId).not.toBe("");await storageDiskRow.hover();await expectSummaryHighlightCount(storageSummary, storageDiskRowId, 1);+ await expectActiveIsolatedLineCards(storageSummary, 1);await scrollPrimaryViewportToBottom(page);await page.waitForTimeout(250);