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
Route physical disk drawer IO through canonical history
rcourtman1bde5976a01b
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 677c6a9f9c..a6305f992f 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -259,6 +259,13 @@ This subsystem now sits under the dedicated agent lifecycle and fleetoperations lane so install, registration, update continuity, profilemanagement, and fleet safety stop hiding inside architecture, migration, ormonitoring work.+Lifecycle-adjacent storage and fleet surfaces now also depend on one governed+physical-disk history transport. When agent-backed disk telemetry is rendered+through shared drawers or lifecycle-adjacent resource context, those reads+must flow through the canonical `/api/metrics-store/history` boundary and the+disk `MetricsTarget.ResourceID` that monitoring projects for the resource,+rather than reviving a browser-local collector or a lifecycle-only+agent/device identity.That shared `internal/api/` dependency now also assumes hosted tenant AI andrelay bootstrap reads use one effective hosted billing lease beforelifecycle-adjacent flows inspect runtime readiness, so install and setup@@ -1738,3 +1745,10 @@ they must not assume a displayed relay pairing token is disposable once`lastUsedAt` is set. Shared helper changes that refresh, hide, or replace apairing credential must preserve used-token continuity instead of deleting acredential that an already paired device still depends on.+That same shared `internal/api/` boundary now also owns agent-derived+physical-disk history transport. Lifecycle-adjacent storage drawers and fleet+resource surfaces may show host SMART-backed disk telemetry through the shared+`/api/metrics-store/history` route, but they must read the canonical disk+metrics target that monitoring projects for the resource instead of reviving a+browser-local disk collector, agent/device concatenation scheme, or other+surface-local history identity.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex f102356f06..30d0f73794 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -329,6 +329,13 @@ Own canonical runtime payload shapes between backend and frontend.The API layer already uses contract tests in many places, but every major livecontract should continue moving toward canonical-only runtime shapes.+The shared metrics-history contract now also owns physical-disk live I/O+windows. `/api/metrics-store/history` must accept `resourceType=disk`, keep+`30m` as a valid compact live range, and resolve `disk`, `diskread`,+`diskwrite`, and `smart_temp` against the canonical disk+`MetricsTarget.ResourceID` that unified resources already expose, instead of+leaving storage drawers or other callers to fork a disk-local history route or+invent an alternate disk identity.The Pulse Account commercial shell now also owns a dedicated bootstrapcontract in `internal/cloudcp/portal/page.go`, `internal/cloudcp/portal/handlers.go`,and `internal/cloudcp/portal/handlers_test.go`. `/api/portal/bootstrap` and@@ -2294,3 +2301,11 @@ alongside `proxmox`, `pbs`, and `pmg`, and the settings reporting/installsurfaces must keep those platform-managed rows navigable back to platformconnections instead of presenting host uninstall or stop-monitoring actionsthat only apply to `agent`, `docker`, and `kubernetes`.+That same shared metrics-history contract now also owns physical-disk live I/O+windows. `internal/api/router.go` must accept `resourceType=disk` on+`/api/metrics-store/history`, keep `30m` as a valid compact live range, and+resolve `disk`, `diskread`, `diskwrite`, and `smart_temp` against the+canonical disk `MetricsTarget.ResourceID` the unified resource already+exposes. Storage drawers and other consumers must not fork a disk-local live+history route, alternate query identity, or feature-specific fallback payload+when the governed chart API already owns that transport.diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 49336a07ff..d9c78d8d9e 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -334,6 +334,12 @@ bounds, including provider-backed alert-history wording. `frontend-modern/src/febacked host and VM incidents with the shared `resource-incident` vocabularyand existing alert-history shells instead of introducing VMware-only labels,badges, or panel copy just because the underlying signal came from vSphere.+Storage disk drawers now also sit on that same shared-primitives floor.+`frontend-modern/src/components/Storage/DiskDetail.tsx` must render physical-+disk read, write, and busy charts through `HistoryChart` plus+`useHistoryChartState`, using the canonical physical-disk history resource id,+instead of reviving `diskMetricsHistory`, a page-local ring buffer, or another+storage-only live chart primitive for the same telemetry.The subsystem registry now also requires explicit proof-policy coverage for allshared runtime files, and shared-component guardrails fail if raw tablediff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 398b352b45..c4da403e79 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -652,3 +652,12 @@ shared guest metadata cache must keep VM network and identity metadata alivelong enough to survive short Proxmox status failures, while incompleteguest-agent metadata stays on a short retry cadence instead of freezingpartial VM summary data for minutes.+That same monitoring boundary now also owns physical-disk I/O history as a+first-class canonical metric stream. `internal/monitoring/monitor_agents.go`+must project host per-device I/O counters onto the same SMART-resolved disk+resource id that unified resources expose, `internal/monitoring/metrics_history.go`+must retain `disk`, `diskread`, `diskwrite`, and `smart_temp` on one shared+disk history model, and mock seeding plus live mock ticks in+`internal/monitoring/mock_metrics_history.go` must append to that same disk+timeline instead of creating a second drawer-only or mock-only disk history+path.diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 2f34ba9e0a..2ff2c0f2e3 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -186,6 +186,12 @@ regression protection.This lane already has strong evidence and guardrails, but it still trails onscore because critical hot paths need more complete protection and verification.+Compact physical-disk drawer charts now also belong to the protected hot path.+Thirty-minute storage detail charts must query the same in-memory plus+store-backed disk history path as longer-term disk charts, with the backend+owning range selection and fallback. Feature-local polling loops or+browser-side disk ring buffers are forbidden because they duplicate live+sampling work and drift out of sync with the governed history timeline.All governed performance-owned runtime files now require explicit registrypath-policy coverage, so new protected hot paths must be mapped to a concretediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex ffeb16b9c5..d940c9653a 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -238,6 +238,13 @@ querying, and the operator-facing storage health presentation layer.This subsystem now sits under the dedicated storage and recovery lane so theoperator-facing storage page, recovery timeline, and recovery-point persistenceengine stop hiding inside broader monitoring and E2E buckets.+Physical-disk live I/O drawers now also sit on the canonical storage surface.+Storage disk drawers may show read, write, busy, and SMART history, but every+chart must route through the shared `HistoryChart` API contract using the disk+resource's canonical history target. Storage must not keep a drawer-local live+metrics collector, agent-id/device fallback stream, or separate real-time+history store once monitoring and `/api/metrics-store/history` already own the+disk timeline.Storage and recovery still consume the shared unified-resource contract, butthey do not own the timeline store itself. The canonical resource-changediff --git a/frontend-modern/src/api/__tests__/chartsApi.test.ts b/frontend-modern/src/api/__tests__/chartsApi.test.tsindex c85e4f2868..2f16093021 100644--- a/frontend-modern/src/api/__tests__/chartsApi.test.ts+++ b/frontend-modern/src/api/__tests__/chartsApi.test.ts@@ -80,6 +80,21 @@ describe('ChartsAPI', () => {);});+ it('builds canonical physical-disk history queries for 30m live I/O charts', async () => {+ apiFetchJSONMock.mockResolvedValueOnce({} as any);++ await ChartsAPI.getMetricsHistory({+ resourceType: 'disk',+ resourceId: 'SERIAL884006359727',+ metric: 'diskread',+ range: '30m',+ });++ expect(apiFetchJSONMock).toHaveBeenCalledWith(+ '/api/metrics-store/history?resourceType=disk&resourceId=SERIAL884006359727&metric=diskread&range=30m',+ );+ });+it('passes through agent metrics history requests', async () => {apiFetchJSONMock.mockResolvedValueOnce({} as any);diff --git a/frontend-modern/src/api/charts.ts b/frontend-modern/src/api/charts.tsindex 57ae1ed860..3bc8102eb7 100644--- a/frontend-modern/src/api/charts.ts+++ b/frontend-modern/src/api/charts.ts@@ -128,7 +128,7 @@ export interface WorkloadsSummaryChartsResponse {}// Persistent metrics history types (SQLite-backed, longer retention)-export type HistoryTimeRange = '1h' | '6h' | '12h' | '24h' | '7d' | '30d' | '90d';+export type HistoryTimeRange = '30m' | '1h' | '6h' | '12h' | '24h' | '7d' | '30d' | '90d';type MetricsHistoryAPIResourceType =| 'vm'| 'system-container'@@ -252,7 +252,7 @@ export interface SingleMetricHistoryResponse {start: number; // Unix timestamp in millisecondsend: number; // Unix timestamp in millisecondspoints: AggregatedMetricPoint[];- source?: 'store' | 'memory' | 'live';+ source?: 'store' | 'memory' | 'live' | 'mock_synthetic';}export interface AllMetricsHistoryResponse {@@ -262,7 +262,7 @@ export interface AllMetricsHistoryResponse {start: number; // Unix timestamp in millisecondsend: number; // Unix timestamp in millisecondsmetrics: Record<string, AggregatedMetricPoint[]>;- source?: 'store' | 'memory' | 'live';+ source?: 'store' | 'memory' | 'live' | 'mock_synthetic';}export type TimeRange = '5m' | '15m' | '30m' | '1h' | '4h' | '12h' | '24h' | '7d' | '30d';diff --git a/frontend-modern/src/components/Storage/DiskDetail.tsx b/frontend-modern/src/components/Storage/DiskDetail.tsxindex 418bae8d64..80c1d802ef 100644--- a/frontend-modern/src/components/Storage/DiskDetail.tsx+++ b/frontend-modern/src/components/Storage/DiskDetail.tsx@@ -49,12 +49,8 @@ export const DiskDetail: Component<DiskDetailProps> = (props) => {attributeCards,historyCharts,metricResourceId,- readData,- writeData,- ioData,} = useDiskDetailModel({disk: () => props.disk,- nodes: () => props.nodes,});return (@@ -122,18 +118,18 @@ export const DiskDetail: Component<DiskDetailProps> = (props) => {{(chart) => (<div class={STORAGE_DETAIL_CARD_CLASS}><HistoryChart- resourceType="agent"- resourceId="dummy"- metric={chart.metric}- label={chart.label}- unit={chart.unit}- data={+ resourceType="disk"+ resourceId={metricResourceId()!}+ metric={chart.series === 'read'- ? readData()+ ? 'diskread': chart.series === 'write'- ? writeData()- : ioData()+ ? 'diskwrite'+ : 'disk'}+ label={chart.label}+ unit={chart.unit}+ range="30m"hideSelectorhideLockheight={120}diff --git a/frontend-modern/src/components/Storage/__tests__/useDiskDetailModel.test.ts b/frontend-modern/src/components/Storage/__tests__/useDiskDetailModel.test.tsindex 8e136b0068..9cb4ad7c8e 100644--- a/frontend-modern/src/components/Storage/__tests__/useDiskDetailModel.test.ts+++ b/frontend-modern/src/components/Storage/__tests__/useDiskDetailModel.test.ts@@ -1,17 +1,9 @@import { renderHook } from '@solidjs/testing-library';import { createSignal } from 'solid-js';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';import type { Resource } from '@/types/resource';import { useDiskDetailModel } from '@/components/Storage/useDiskDetailModel';-vi.mock('@/stores/diskMetricsHistory', () => ({- getDiskMetricsVersion: () => 1,- getDiskMetricHistory: () => [- { timestamp: 1000, readBps: 10, writeBps: 20, ioTime: 30 },- { timestamp: 2000, readBps: 15, writeBps: 25, ioTime: 35 },- ],-}));-const buildDisk = (overrides: Partial<Resource> = {}): Resource =>({id: 'disk-1',@@ -46,12 +38,10 @@ const buildDisk = (overrides: Partial<Resource> = {}): Resource =>describe('useDiskDetailModel', () => {it('builds canonical disk detail model state', () => {const [disk] = createSignal(buildDisk());- const [nodes] = createSignal<Resource[]>([]);const { result } = renderHook(() =>useDiskDetailModel({disk,- nodes,}),);@@ -63,18 +53,6 @@ describe('useDiskDetailModel', () => {'smart_temp','smart_reallocated_sectors',]);- expect(result.readData()).toEqual([- { timestamp: 1000, value: 10, min: 10, max: 10 },- { timestamp: 2000, value: 15, min: 15, max: 15 },- ]);- expect(result.writeData()).toEqual([- { timestamp: 1000, value: 20, min: 20, max: 20 },- { timestamp: 2000, value: 25, min: 25, max: 25 },- ]);- expect(result.ioData()).toEqual([- { timestamp: 1000, value: 30, min: 30, max: 30 },- { timestamp: 2000, value: 35, min: 35, max: 35 },- ]);});it('keeps historical charts available for api-backed disks without serial or wwn when a canonical disk target exists', () => {@@ -91,12 +69,9 @@ describe('useDiskDetailModel', () => {},} as Partial<Resource>),);- const [nodes] = createSignal<Resource[]>([]);-const { result } = renderHook(() =>useDiskDetailModel({disk,- nodes,}),);diff --git a/frontend-modern/src/components/Storage/useDiskDetailModel.ts b/frontend-modern/src/components/Storage/useDiskDetailModel.tsindex 8f52842910..e121278a86 100644--- a/frontend-modern/src/components/Storage/useDiskDetailModel.ts+++ b/frontend-modern/src/components/Storage/useDiskDetailModel.ts@@ -1,5 +1,5 @@-import { Accessor, createEffect, createMemo, createSignal, onCleanup } from 'solid-js';-import type { HistoryTimeRange, AggregatedMetricPoint } from '@/api/charts';+import { Accessor, createMemo, createSignal } from 'solid-js';+import type { HistoryTimeRange } from '@/api/charts';import {extractPhysicalDiskPresentationData,type PhysicalDiskPresentationData,@@ -8,32 +8,17 @@ import {getDiskDetailAttributeCards,getDiskDetailHistoryCharts,} from '@/features/storageBackups/diskDetailPresentation';-import { getDiskMetricHistory, getDiskMetricsVersion } from '@/stores/diskMetricsHistory';import type { Resource } from '@/types/resource';import {resolvePhysicalDiskHistoryResourceId,- resolvePhysicalDiskMetricResourceId,} from './diskResourceUtils';type UseDiskDetailModelOptions = {disk: Accessor<Resource>;- nodes: Accessor<Resource[]>;};-const toAggregatedSeries = (- historyData: Array<{ timestamp: number; readBps: number; writeBps: number; ioTime: number }>,- key: 'readBps' | 'writeBps' | 'ioTime',-): AggregatedMetricPoint[] =>- historyData.map((point) => ({- timestamp: point.timestamp,- value: point[key],- min: point[key],- max: point[key],- }));-export const useDiskDetailModel = (options: UseDiskDetailModelOptions) => {const [chartRange, setChartRange] = createSignal<HistoryTimeRange>('24h');- const [diskVer, setDiskVer] = createSignal(getDiskMetricsVersion());const diskData = createMemo<PhysicalDiskPresentationData>(() =>extractPhysicalDiskPresentationData(options.disk()),@@ -41,31 +26,7 @@ export const useDiskDetailModel = (options: UseDiskDetailModelOptions) => {const historyResourceId = createMemo(() => resolvePhysicalDiskHistoryResourceId(options.disk()));const attributeCards = createMemo(() => getDiskDetailAttributeCards(diskData()));const historyCharts = createMemo(() => getDiskDetailHistoryCharts(diskData()));- const metricResourceId = createMemo(() =>- resolvePhysicalDiskMetricResourceId(options.disk(), options.nodes(), diskData().devPath),- );-- createEffect(() => {- const timer = setInterval(() => setDiskVer(getDiskMetricsVersion()), 2000);- onCleanup(() => clearInterval(timer));- });-- const historyData = createMemo(() => {- diskVer();- const id = metricResourceId();- if (!id) return [];- return getDiskMetricHistory(id, 30 * 60 * 1000);- });-- const readData = createMemo<AggregatedMetricPoint[]>(() =>- toAggregatedSeries(historyData(), 'readBps'),- );- const writeData = createMemo<AggregatedMetricPoint[]>(() =>- toAggregatedSeries(historyData(), 'writeBps'),- );- const ioData = createMemo<AggregatedMetricPoint[]>(() =>- toAggregatedSeries(historyData(), 'ioTime'),- );+ const metricResourceId = createMemo(() => historyResourceId());return {chartRange,@@ -75,8 +36,5 @@ export const useDiskDetailModel = (options: UseDiskDetailModelOptions) => {attributeCards,historyCharts,metricResourceId,- readData,- writeData,- ioData,};};diff --git a/frontend-modern/src/components/shared/__tests__/HistoryChart.test.tsx b/frontend-modern/src/components/shared/__tests__/HistoryChart.test.tsxindex 5e2c1e69a1..5bea5d5e54 100644--- a/frontend-modern/src/components/shared/__tests__/HistoryChart.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/HistoryChart.test.tsx@@ -68,6 +68,7 @@ describe('HistoryChart', () => {expect(historyChartStateSource).toContain('setupCanvasDPR');expect(historyChartStateSource).toContain('export function useHistoryChartState');expect(historyChartStateSource).toContain('HISTORY_CHART_RANGES');+ expect(historyChartStateSource).toContain("'mock_synthetic' | null");expect(historyChartStateSource).toContain('return ent.trial_eligible !== false;');expect(historyChartStateSource).toContain('runStartProTrialAction({');expect(historyChartStateSource).not.toContain('startProTrial()');diff --git a/frontend-modern/src/components/shared/useHistoryChartState.ts b/frontend-modern/src/components/shared/useHistoryChartState.tsindex 06b79ad0a4..78674ac2d4 100644--- a/frontend-modern/src/components/shared/useHistoryChartState.ts+++ b/frontend-modern/src/components/shared/useHistoryChartState.ts@@ -43,7 +43,7 @@ export function useHistoryChartState(props: HistoryChartProps, refs: HistoryCharconst [data, setData] = createSignal(props.data ?? []);const [loading, setLoading] = createSignal(false);const [error, setError] = createSignal<string | null>(null);- const [source, setSource] = createSignal<'store' | 'memory' | 'live' | null>(null);+ const [source, setSource] = createSignal<'store' | 'memory' | 'live' | 'mock_synthetic' | null>(null);const [maxPoints, setMaxPoints] = createSignal<number | null>(null);const [refreshTick, setRefreshTick] = createSignal(0);const [hasLoadedOnce, setHasLoadedOnce] = createSignal(false);diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.tsindex b6d443fb69..1460f29fc7 100644--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts@@ -1780,7 +1780,7 @@ describe('frontend resource type boundaries', () => {);expect(diskDetailSource).not.toContain('class="relative"');expect(useDiskDetailModelSource).toContain('extractPhysicalDiskPresentationData');- expect(useDiskDetailModelSource).toContain('resolvePhysicalDiskMetricResourceId');+ expect(useDiskDetailModelSource).toContain('resolvePhysicalDiskHistoryResourceId');expect(diskLiveMetricSource).toContain('useDiskLiveMetricModel');expect(diskLiveMetricSource).not.toContain('const latestMetric = createMemo(() => {');expect(diskLiveMetricSource).not.toContain('const formatted = createMemo(() => {');diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 7355f92ac5..aabed9f304 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -5810,6 +5810,56 @@ func TestContract_MetricsHistoryLiveFallbackJSONSnapshot(t *testing.T) {assertJSONSnapshot(t, got, want)}+func TestContract_MetricsHistoryPhysicalDiskIOLiveWindowUsesCanonicalDiskTarget(t *testing.T) {+ mh := monitoring.NewMetricsHistory(1000, time.Hour)+ now := time.Now().UTC().Truncate(time.Second)+ resourceID := "SERIAL884006359727"+ for i, value := range []float64{1.5, 2.25, 3.0} {+ mh.AddDiskMetric(resourceID, "diskread", value*1024*1024, now.Add(time.Duration(i-2)*10*time.Minute))+ }++ router := &Router{+ monitor: &monitoring.Monitor{},+ }+ setUnexportedField(t, router.monitor, "metricsHistory", mh)++ req := httptest.NewRequest(+ http.MethodGet,+ "/api/metrics-store/history?resourceType=disk&resourceId="+resourceID+"&metric=diskread&range=30m",+ nil,+ )+ rec := httptest.NewRecorder()+ router.handleMetricsHistory(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())+ }++ var resp metricsHistoryResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("failed to unmarshal response: %v", err)+ }++ if resp.ResourceType != "disk" {+ t.Fatalf("expected resourceType disk, got %q", resp.ResourceType)+ }+ if resp.ResourceId != resourceID {+ t.Fatalf("expected canonical disk resource id %q, got %q", resourceID, resp.ResourceId)+ }+ if resp.Metric != "diskread" {+ t.Fatalf("expected metric diskread, got %q", resp.Metric)+ }+ if resp.Range != "30m" {+ t.Fatalf("expected range 30m, got %q", resp.Range)+ }+ if resp.Source != "memory" {+ t.Fatalf("expected source memory, got %q", resp.Source)+ }+ if len(resp.Points) != 3 {+ t.Fatalf("expected 3 diskread points, got %d", len(resp.Points))+ }+}+func TestContract_PatrolStatusResponseJSONSnapshot(t *testing.T) {lastPatrolAt := time.Date(2026, 3, 12, 9, 30, 0, 0, time.UTC)lastActivityAt := lastPatrolAt.Add(5 * time.Minute)diff --git a/internal/api/metrics_history_fallback_test.go b/internal/api/metrics_history_fallback_test.goindex e5465153b3..407c03a6e8 100644--- a/internal/api/metrics_history_fallback_test.go+++ b/internal/api/metrics_history_fallback_test.go@@ -141,6 +141,49 @@ func TestMetricsHistoryFallbackMockDiskSynthesizesSeries(t *testing.T) {}}+func TestMetricsHistoryDiskIOMetricsUseMemoryFallback(t *testing.T) {+ mh := monitoring.NewMetricsHistory(1000, time.Hour)+ now := time.Now().UTC().Truncate(time.Second)+ resourceID := "SERIAL884006359727"+ for i, value := range []float64{12.5, 14.0, 11.0, 16.2} {+ mh.AddDiskMetric(resourceID, "diskread", value*1024*1024, now.Add(time.Duration(i-3)*10*time.Minute))+ mh.AddDiskMetric(resourceID, "diskwrite", value*512*1024, now.Add(time.Duration(i-3)*10*time.Minute))+ mh.AddDiskMetric(resourceID, "disk", 20+value, now.Add(time.Duration(i-3)*10*time.Minute))+ }++ monitor := &monitoring.Monitor{}+ setUnexportedField(t, monitor, "metricsHistory", mh)++ router := &Router{monitor: monitor}++ req := httptest.NewRequest(+ http.MethodGet,+ "/api/metrics-store/history?resourceType=disk&resourceId="+resourceID+"&metric=diskread&range=30m",+ nil,+ )+ rec := httptest.NewRecorder()+ router.handleMetricsHistory(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status 200, got %d", rec.Code)+ }++ var resp metricsHistoryResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("failed to unmarshal response: %v", err)+ }++ if resp.Source != "memory" {+ t.Fatalf("expected source memory, got %q", resp.Source)+ }+ if resp.Metric != "diskread" {+ t.Fatalf("expected metric diskread, got %q", resp.Metric)+ }+ if len(resp.Points) < 2 {+ t.Fatalf("expected diskread history points, got %d", len(resp.Points))+ }+}+func TestMetricsHistoryStorageDiskAliasUsesMemory(t *testing.T) {state := models.NewState()state.UpdateStorageForInstance("pve1", []models.Storage{diff --git a/internal/api/router.go b/internal/api/router.goindex 24215d4c6d..9f60104757 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -6040,6 +6040,7 @@ func buildSyntheticMetricHistorySeries(current float64,) []monitoring.MetricPoint {switch metricType {+ case "disk", "diskread", "diskwrite":case "smart_temp":if current <= 0 {return nil@@ -7918,6 +7919,8 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)var stepSecs int64 = 0 // Default to no downsampling (use tier resolution)switch timeRange {+ case "30m":+ duration = 30 * time.Minutecase "1h":duration = time.Hourcase "6h":@@ -8234,7 +8237,12 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)disk := &physicalDisks[i]serial := strings.TrimSpace(disk.PhysicalDisk.Serial)wwn := strings.TrimSpace(disk.PhysicalDisk.WWN)+ metricsTargetID := ""+ if disk.MetricsTarget != nil {+ metricsTargetID = strings.TrimSpace(disk.MetricsTarget.ResourceID)+ }if strings.EqualFold(disk.ID, target) ||+ (metricsTargetID != "" && strings.EqualFold(metricsTargetID, target)) ||(serial != "" && strings.EqualFold(serial, target)) ||(wwn != "" && strings.EqualFold(wwn, target)) {return disk@@ -8399,8 +8407,12 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)return nil, "", false}- if mock.IsMockEnabled() && runtimeResourceType == "disk" && metricType == "smart_temp" {- if disk := findDisk(resourceID); disk != nil && disk.PhysicalDisk != nil && disk.PhysicalDisk.Temperature > 0 {+ if mock.IsMockEnabled() && runtimeResourceType == "disk" {+ current := 0.0+ if disk := findDisk(resourceID); disk != nil && disk.PhysicalDisk != nil && metricType == "smart_temp" {+ current = float64(disk.PhysicalDisk.Temperature)+ }+ if current > 0 || metricType == "disk" || metricType == "diskread" || metricType == "diskwrite" {series := buildSyntheticMetricHistorySeries(end,duration,@@ -8408,7 +8420,7 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)"disk",resourceID,metricType,- float64(disk.PhysicalDisk.Temperature),+ current,)if len(series) > 0 {return buildHistoryPoints(series, stepSecs), historySourceMock, true@@ -8485,6 +8497,16 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)return nil, "", false}return buildHistoryPoints(points, stepSecs), historySourceMemory, true+ case "disk":+ points := monitor.GetDiskMetricsForChart(resourceID, queryMetric, duration)+ if len(points) == 0 {+ livePoints := liveMetricPoints(runtimeResourceType, resourceID)+ if live, ok := livePoints[metricType]; ok {+ return buildHistoryPoints([]monitoring.MetricPoint{live}, 0), historySourceLive, true+ }+ return nil, "", false+ }+ return buildHistoryPoints(points, stepSecs), historySourceMemory, truedefault:livePoints := liveMetricPoints(runtimeResourceType, resourceID)if live, ok := livePoints[metricType]; ok {@@ -8518,6 +8540,13 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)metrics = monitor.GetGuestMetrics(fmt.Sprintf("docker:%s", resourceID), duration)case "storage":metrics = monitor.GetStorageMetrics(resourceID, duration)+ case "disk":+ metrics = map[string][]monitoring.MetricPoint{+ "disk": monitor.GetDiskMetricsForChart(resourceID, "disk", duration),+ "diskread": monitor.GetDiskMetricsForChart(resourceID, "diskread", duration),+ "diskwrite": monitor.GetDiskMetricsForChart(resourceID, "diskwrite", duration),+ "smart_temp": monitor.GetDiskMetricsForChart(resourceID, "smart_temp", duration),+ }default:if runtimeResourceType == "node" {metrics = map[string][]monitoring.MetricPoint{@@ -8674,33 +8703,38 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)}}- if response == nil && mock.IsMockEnabled() && runtimeResourceType == "disk" && metricType == "smart_temp" {+ if response == nil && mock.IsMockEnabled() && runtimeResourceType == "disk" &&+ (metricType == "smart_temp" || metricType == "disk" || metricType == "diskread" || metricType == "diskwrite") {targetPoints := targetMockSeriesPoints(duration, historyMaxPoints)if len(points) > 0 && len(points) < targetPoints {current := points[len(points)-1].Value- if disk := findDisk(resourceID); disk != nil && disk.PhysicalDisk != nil && disk.PhysicalDisk.Temperature > 0 {- current = float64(disk.PhysicalDisk.Temperature)+ if metricType == "smart_temp" {+ if disk := findDisk(resourceID); disk != nil && disk.PhysicalDisk != nil && disk.PhysicalDisk.Temperature > 0 {+ current = float64(disk.PhysicalDisk.Temperature)+ }}- series := buildSyntheticMetricHistorySeries(- end,- duration,- historyMaxPoints,- "disk",- resourceID,- metricType,- current,- )- if len(series) > len(points) {- source = historySourceMock- response = map[string]interface{}{- "resourceType": responseResourceType,- "resourceId": resourceID,- "metric": metricType,- "range": timeRange,- "start": start.UnixMilli(),- "end": end.UnixMilli(),- "points": buildHistoryPoints(series, stepSecs),- "source": source,+ if metricType != "smart_temp" || current > 0 {+ series := buildSyntheticMetricHistorySeries(+ end,+ duration,+ historyMaxPoints,+ "disk",+ resourceID,+ metricType,+ current,+ )+ if len(series) > len(points) {+ source = historySourceMock+ response = map[string]interface{}{+ "resourceType": responseResourceType,+ "resourceId": resourceID,+ "metric": metricType,+ "range": timeRange,+ "start": start.UnixMilli(),+ "end": end.UnixMilli(),+ "points": buildHistoryPoints(series, stepSecs),+ "source": source,+ }}}}diff --git a/internal/models/metrics_types.go b/internal/models/metrics_types.goindex da0150278e..d18d8ef9ea 100644--- a/internal/models/metrics_types.go+++ b/internal/models/metrics_types.go@@ -12,6 +12,7 @@ type MetricPoint struct {type IOMetrics struct {DiskRead int64 `json:"diskRead"`DiskWrite int64 `json:"diskWrite"`+ DiskBusy int64 `json:"diskBusy,omitempty"`NetworkIn int64 `json:"networkIn"`NetworkOut int64 `json:"networkOut"`Timestamp time.Time `json:"timestamp"`diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex ec0055fca2..aa28766c31 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -670,6 +670,27 @@ func TestUnifiedVMMetricsUseCanonicalVMHistoryPath(t *testing.T) {}}+func TestHostPhysicalDiskIOMetricsUseCanonicalDiskHistoryPath(t *testing.T) {+ data, err := os.ReadFile("monitor_agents.go")+ if err != nil {+ t.Fatalf("failed to read monitor_agents.go: %v", err)+ }+ source := string(data)+ requiredSnippets := []string{+ "m.writeHostPhysicalDiskIOMetrics(host, now)",+ "func (m *Monitor) writeHostPhysicalDiskIOMetrics(host models.Host, now time.Time) {",+ `resourceID := unifiedresources.HostSMARTDiskSourceID(host, disk)`,+ `m.metricsHistory.AddDiskMetric(resourceID, "diskread", readRate, now)`,+ `m.metricsStore.Write("disk", resourceID, "diskwrite", writeRate, now)`,+ `m.metricsStore.Write("disk", resourceID, "disk", busyPct, now)`,+ }+ for _, snippet := range requiredSnippets {+ if !strings.Contains(source, snippet) {+ t.Fatalf("monitor_agents.go must contain %q", snippet)+ }+ }+}+func TestMockNativePollersDeferToCanonicalMockSampler(t *testing.T) {cases := []struct {file stringdiff --git a/internal/monitoring/metrics_history.go b/internal/monitoring/metrics_history.goindex e3dfc73f6e..68d7650f68 100644--- a/internal/monitoring/metrics_history.go+++ b/internal/monitoring/metrics_history.go@@ -33,6 +33,9 @@ type StorageMetrics struct {// DiskMetrics holds historical metrics for a single physical disk.type DiskMetrics struct {Temperature []MetricPoint `json:"smart_temp"`+ Utilization []MetricPoint `json:"disk"`+ DiskRead []MetricPoint `json:"diskread"`+ DiskWrite []MetricPoint `json:"diskwrite"`}// MetricsHistory maintains historical metrics for guests, nodes, storage, and disks.@@ -339,6 +342,12 @@ func (mh *MetricsHistory) AddDiskMetric(resourceID string, metricType string, vapoint := MetricPoint{Value: value, Timestamp: timestamp}switch metricType {+ case "disk":+ metrics.Utilization = mh.appendMetric(metrics.Utilization, point)+ case "diskread":+ metrics.DiskRead = mh.appendMetric(metrics.DiskRead, point)+ case "diskwrite":+ metrics.DiskWrite = mh.appendMetric(metrics.DiskWrite, point)case "smart_temp":metrics.Temperature = mh.appendMetric(metrics.Temperature, point)}@@ -357,6 +366,12 @@ func (mh *MetricsHistory) GetDiskMetrics(resourceID string, metricType string, dcutoffTime := time.Now().Add(-duration)switch metricType {+ case "disk":+ return filterMetricsByTime(metrics.Utilization, cutoffTime)+ case "diskread":+ return filterMetricsByTime(metrics.DiskRead, cutoffTime)+ case "diskwrite":+ return filterMetricsByTime(metrics.DiskWrite, cutoffTime)case "smart_temp":return filterMetricsByTime(metrics.Temperature, cutoffTime)default:@@ -419,9 +434,15 @@ func (mh *MetricsHistory) Cleanup() {}}+ // Cleanup physical disk metrics and remove empty entriesfor key, metrics := range mh.diskMetrics {metrics.Temperature = mh.cleanupMetrics(metrics.Temperature, cutoffTime)- if len(metrics.Temperature) == 0 {+ metrics.Utilization = mh.cleanupMetrics(metrics.Utilization, cutoffTime)+ metrics.DiskRead = mh.cleanupMetrics(metrics.DiskRead, cutoffTime)+ metrics.DiskWrite = mh.cleanupMetrics(metrics.DiskWrite, cutoffTime)++ if len(metrics.Temperature) == 0 && len(metrics.Utilization) == 0 &&+ len(metrics.DiskRead) == 0 && len(metrics.DiskWrite) == 0 {delete(mh.diskMetrics, key)disksRemoved++}diff --git a/internal/monitoring/mock_chart_history.go b/internal/monitoring/mock_chart_history.goindex 0da4050d13..ecd74e6f7b 100644--- a/internal/monitoring/mock_chart_history.go+++ b/internal/monitoring/mock_chart_history.go@@ -9,6 +9,7 @@ import (var (mockGuestChartMetricTypes = []string{"cpu", "memory", "disk", "diskread", "diskwrite", "netin", "netout"}mockNodeChartMetricTypes = []string{"cpu", "memory", "disk", "netin", "netout"}+ mockDiskChartMetricTypes = []string{"disk", "diskread", "diskwrite", "smart_temp"})func normalizeMockChartResourceType(resourceType string) string {@@ -98,6 +99,23 @@ func mockNodeMetricsForChart(nodeID string, metricTypes []string, duration time.return result}+func mockDiskMetricsForChart(resourceID string, metricTypes []string, duration time.Duration) map[string][]MetricPoint {+ resourceID = strings.TrimSpace(resourceID)+ if resourceID == "" {+ return map[string][]MetricPoint{}+ }+ if len(metricTypes) == 0 {+ metricTypes = mockDiskChartMetricTypes+ }++ timestamps := mockChartTimestamps(duration)+ result := make(map[string][]MetricPoint, len(metricTypes))+ for _, metricType := range metricTypes {+ result[metricType] = mockCanonicalMetricSeries("disk", resourceID, metricType, timestamps)+ }+ return result+}+func latestMetricPoint(points []MetricPoint) (MetricPoint, bool) {if len(points) == 0 {return MetricPoint{}, falsediff --git a/internal/monitoring/mock_metrics_history.go b/internal/monitoring/mock_metrics_history.goindex bc86f9e38d..50b81f28e1 100644--- a/internal/monitoring/mock_metrics_history.go+++ b/internal/monitoring/mock_metrics_history.go@@ -684,10 +684,19 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi}tempSeries := canonicalMetricSeries("disk", resourceID, "smart_temp", seedTimestamps)+ busySeries := canonicalMetricSeries("disk", resourceID, "disk", seedTimestamps)+ diskReadSeries := canonicalMetricSeries("disk", resourceID, "diskread", seedTimestamps)+ diskWriteSeries := canonicalMetricSeries("disk", resourceID, "diskwrite", seedTimestamps)for i := 0; i < numPoints; i++ {ts := seedTimestamps[i]mh.AddDiskMetric(resourceID, "smart_temp", tempSeries[i], ts)+ mh.AddDiskMetric(resourceID, "disk", busySeries[i], ts)+ mh.AddDiskMetric(resourceID, "diskread", diskReadSeries[i], ts)+ mh.AddDiskMetric(resourceID, "diskwrite", diskWriteSeries[i], ts)queueMetric("disk", resourceID, "smart_temp", tempSeries[i], ts)+ queueMetric("disk", resourceID, "disk", busySeries[i], ts)+ queueMetric("disk", resourceID, "diskread", diskReadSeries[i], ts)+ queueMetric("disk", resourceID, "diskwrite", diskWriteSeries[i], ts)}}@@ -810,10 +819,19 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi}tempSeries := canonicalMetricSeries("disk", resourceID, "smart_temp", seedTimestamps)+ busySeries := canonicalMetricSeries("disk", resourceID, "disk", seedTimestamps)+ diskReadSeries := canonicalMetricSeries("disk", resourceID, "diskread", seedTimestamps)+ diskWriteSeries := canonicalMetricSeries("disk", resourceID, "diskwrite", seedTimestamps)for i := 0; i < numPoints; i++ {ts := seedTimestamps[i]mh.AddDiskMetric(resourceID, "smart_temp", tempSeries[i], ts)+ mh.AddDiskMetric(resourceID, "disk", busySeries[i], ts)+ mh.AddDiskMetric(resourceID, "diskread", diskReadSeries[i], ts)+ mh.AddDiskMetric(resourceID, "diskwrite", diskWriteSeries[i], ts)queueMetric("disk", resourceID, "smart_temp", tempSeries[i], ts)+ queueMetric("disk", resourceID, "disk", busySeries[i], ts)+ queueMetric("disk", resourceID, "diskread", diskReadSeries[i], ts)+ queueMetric("disk", resourceID, "diskwrite", diskWriteSeries[i], ts)}}@@ -981,10 +999,19 @@ func recordTrueNASFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, fixturecontinue}temp := mock.SampleMetric("disk", resourceID, "smart_temp", ts)+ busy := mock.SampleMetric("disk", resourceID, "disk", ts)+ diskRead := mock.SampleMetric("disk", resourceID, "diskread", ts)+ diskWrite := mock.SampleMetric("disk", resourceID, "diskwrite", ts)mh.AddDiskMetric(resourceID, "smart_temp", temp, ts)+ mh.AddDiskMetric(resourceID, "disk", busy, ts)+ mh.AddDiskMetric(resourceID, "diskread", diskRead, ts)+ mh.AddDiskMetric(resourceID, "diskwrite", diskWrite, ts)if ms != nil {ms.Write("disk", resourceID, "smart_temp", temp, ts)+ ms.Write("disk", resourceID, "disk", busy, ts)+ ms.Write("disk", resourceID, "diskread", diskRead, ts)+ ms.Write("disk", resourceID, "diskwrite", diskWrite, ts)}}@@ -1334,10 +1361,19 @@ func recordMockStateToMetricsHistory(mh *MetricsHistory, ms *metrics.Store, grapcontinue}temp := mock.SampleMetric("disk", resourceID, "smart_temp", ts)+ busy := mock.SampleMetric("disk", resourceID, "disk", ts)+ diskRead := mock.SampleMetric("disk", resourceID, "diskread", ts)+ diskWrite := mock.SampleMetric("disk", resourceID, "diskwrite", ts)mh.AddDiskMetric(resourceID, "smart_temp", temp, ts)+ mh.AddDiskMetric(resourceID, "disk", busy, ts)+ mh.AddDiskMetric(resourceID, "diskread", diskRead, ts)+ mh.AddDiskMetric(resourceID, "diskwrite", diskWrite, ts)if ms != nil {ms.Write("disk", resourceID, "smart_temp", temp, ts)+ ms.Write("disk", resourceID, "disk", busy, ts)+ ms.Write("disk", resourceID, "diskread", diskRead, ts)+ ms.Write("disk", resourceID, "diskwrite", diskWrite, ts)}}diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.goindex d990daa58a..b3580630ba 100644--- a/internal/monitoring/mock_metrics_history_test.go+++ b/internal/monitoring/mock_metrics_history_test.go@@ -160,6 +160,30 @@ func TestSeedMockMetricsHistory_PopulatesSeries(t *testing.T) {if got, want := diskTemps[len(diskTemps)-1].Value, mock.SampleMetric("disk", "SERIAL-LOCAL-1", "smart_temp", diskTemps[len(diskTemps)-1].Timestamp); math.Abs(got-want) > 1e-9 {t.Fatalf("expected last disk temp point to match canonical sampler, got=%v want=%v", got, want)}++ diskRead := mh.GetDiskMetrics("SERIAL-LOCAL-1", "diskread", time.Hour)+ if len(diskRead) < 10 {+ t.Fatalf("expected seeded disk read history, got %d points", len(diskRead))+ }+ if got, want := diskRead[len(diskRead)-1].Value, mock.SampleMetric("disk", "SERIAL-LOCAL-1", "diskread", diskRead[len(diskRead)-1].Timestamp); math.Abs(got-want) > 1e-9 {+ t.Fatalf("expected last disk read point to match canonical sampler, got=%v want=%v", got, want)+ }++ diskWrite := mh.GetDiskMetrics("SERIAL-LOCAL-1", "diskwrite", time.Hour)+ if len(diskWrite) < 10 {+ t.Fatalf("expected seeded disk write history, got %d points", len(diskWrite))+ }+ if got, want := diskWrite[len(diskWrite)-1].Value, mock.SampleMetric("disk", "SERIAL-LOCAL-1", "diskwrite", diskWrite[len(diskWrite)-1].Timestamp); math.Abs(got-want) > 1e-9 {+ t.Fatalf("expected last disk write point to match canonical sampler, got=%v want=%v", got, want)+ }++ diskBusy := mh.GetDiskMetrics("SERIAL-LOCAL-1", "disk", time.Hour)+ if len(diskBusy) < 10 {+ t.Fatalf("expected seeded disk busy history, got %d points", len(diskBusy))+ }+ if got, want := diskBusy[len(diskBusy)-1].Value, mock.SampleMetric("disk", "SERIAL-LOCAL-1", "disk", diskBusy[len(diskBusy)-1].Timestamp); math.Abs(got-want) > 1e-9 {+ t.Fatalf("expected last disk busy point to match canonical sampler, got=%v want=%v", got, want)+ }}func TestSeedMockMetricsHistory_AppendsSingleTerminalNowPoint(t *testing.T) {diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex e934b72c71..fa9dc9fa97 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -1762,15 +1762,18 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.totalTXBytes += nic.TXBytes}var totalDiskReadBytes, totalDiskWriteBytes uint64+ var totalDiskBusyMs uint64for _, d := range host.DiskIO {totalDiskReadBytes += d.ReadBytestotalDiskWriteBytes += d.WriteBytes+ totalDiskBusyMs += d.IOTime}hostRateKey := fmt.Sprintf("agent:%s", host.ID)currentMetrics := IOMetrics{DiskRead: int64(totalDiskReadBytes),DiskWrite: int64(totalDiskWriteBytes),+ DiskBusy: int64(totalDiskBusyMs),NetworkIn: int64(totalRXBytes),NetworkOut: int64(totalTXBytes),Timestamp: now,@@ -1844,6 +1847,8 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.}}+ m.writeHostPhysicalDiskIOMetrics(host, now)+if m.metricsStore != nil {m.metricsStore.Write("agent", host.ID, "cpu", host.CPUUsage, now)m.metricsStore.Write("agent", host.ID, "memory", host.Memory.Usage, now)@@ -1923,6 +1928,83 @@ func (m *Monitor) writeHostSMARTMetrics(host models.Host, now time.Time) {}}+func normalizeHostDiskDevice(device string) string {+ return strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(device), "/dev/"))+}++func hostDiskIOMetricResourceID(host models.Host, io models.DiskIO) string {+ device := normalizeHostDiskDevice(io.Device)+ if device == "" {+ return ""+ }++ for _, disk := range host.Sensors.SMART {+ if disk.Standby {+ continue+ }+ if strings.EqualFold(normalizeHostDiskDevice(disk.Device), device) {+ return unifiedresources.HostSMARTDiskSourceID(host, disk)+ }+ }++ return ""+}++func (m *Monitor) writeHostPhysicalDiskIOMetrics(host models.Host, now time.Time) {+ if shouldSkipNativeMockStateMetricWrites() || (m.metricsHistory == nil && m.metricsStore == nil) {+ return+ }+ if len(host.DiskIO) == 0 || len(host.Sensors.SMART) == 0 {+ return+ }++ seenResourceIDs := make(map[string]struct{}, len(host.DiskIO))+ for _, io := range host.DiskIO {+ resourceID := hostDiskIOMetricResourceID(host, io)+ if resourceID == "" {+ continue+ }+ if _, seen := seenResourceIDs[resourceID]; seen {+ continue+ }+ seenResourceIDs[resourceID] = struct{}{}++ trackerKey := fmt.Sprintf("disk:%s:%s", host.ID, normalizeHostDiskDevice(io.Device))+ current := IOMetrics{+ DiskRead: int64(io.ReadBytes),+ DiskWrite: int64(io.WriteBytes),+ DiskBusy: int64(io.IOTime),+ Timestamp: now,+ }+ readRate, writeRate, busyPct, _, _ := m.rateTracker.CalculateRatesWithBusy(trackerKey, current)++ if readRate >= 0 {+ if m.metricsHistory != nil {+ m.metricsHistory.AddDiskMetric(resourceID, "diskread", readRate, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("disk", resourceID, "diskread", readRate, now)+ }+ }+ if writeRate >= 0 {+ if m.metricsHistory != nil {+ m.metricsHistory.AddDiskMetric(resourceID, "diskwrite", writeRate, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("disk", resourceID, "diskwrite", writeRate, now)+ }+ }+ if busyPct >= 0 {+ if m.metricsHistory != nil {+ m.metricsHistory.AddDiskMetric(resourceID, "disk", busyPct, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("disk", resourceID, "disk", busyPct, now)+ }+ }+ }+}+// applyClusterSensors stores temperature data collected from Proxmox cluster// siblings via SSH. Each entry is keyed by lowercase node name so that// getHostAgentTemperatureByID can use it as a fallback.diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.goindex 20c518930c..9e1545ce55 100644--- a/internal/monitoring/monitor_host_agents_test.go+++ b/internal/monitoring/monitor_host_agents_test.go@@ -670,6 +670,109 @@ func TestApplyHostReportPersistsSMARTMetricsForAgentDisksWithFallbackID(t *testi}}+func TestApplyHostReportPersistsPhysicalDiskIOMetricsForAgentDisks(t *testing.T) {+ t.Helper()++ storeCfg := metrics.DefaultConfig(t.TempDir())+ storeCfg.WriteBufferSize = 1+ store, err := metrics.NewStore(storeCfg)+ if err != nil {+ t.Fatalf("NewStore: %v", err)+ }+ defer store.Close()++ monitor := &Monitor{+ state: models.NewState(),+ alertManager: alerts.NewManager(),+ hostTokenBindings: make(map[string]string),+ config: &config.Config{},+ rateTracker: NewRateTracker(),+ metricsHistory: NewMetricsHistory(1000, 24*time.Hour),+ metricsStore: store,+ }+ t.Cleanup(func() { monitor.alertManager.Stop() })++ baseReport := agentshost.Report{+ Agent: agentshost.AgentInfo{+ ID: "agent-pve2",+ Version: "1.0.0",+ IntervalSeconds: 30,+ },+ Host: agentshost.HostInfo{+ ID: "host-pve2",+ Hostname: "pve2",+ MachineID: "machine-pve2",+ },+ Metrics: agentshost.Metrics{+ Memory: agentshost.MemoryMetric{TotalBytes: 1024, UsedBytes: 512, FreeBytes: 512, Usage: 50},+ },+ Sensors: agentshost.Sensors{+ SMART: []agentshost.DiskSMART{+ {+ Device: "/dev/nvme2",+ Model: "Samsung 980 PRO 2TB",+ Serial: "SERIAL884006359727",+ Temperature: 46,+ },+ },+ },+ DiskIO: []agentshost.DiskIO{+ {+ Device: "nvme2",+ ReadBytes: 1_000_000,+ WriteBytes: 2_000_000,+ ReadOps: 100,+ WriteOps: 200,+ IOTime: 10_000,+ },+ },+ Timestamp: time.Now().UTC(),+ }++ if _, err := monitor.ApplyHostReport(baseReport, nil); err != nil {+ t.Fatalf("ApplyHostReport initial: %v", err)+ }++ nextReport := baseReport+ nextReport.Timestamp = baseReport.Timestamp.Add(30 * time.Second)+ nextReport.DiskIO = []agentshost.DiskIO{+ {+ Device: "nvme2",+ ReadBytes: 4_000_000,+ WriteBytes: 5_000_000,+ ReadOps: 250,+ WriteOps: 350,+ IOTime: 22_000,+ },+ }++ if _, err := monitor.ApplyHostReport(nextReport, nil); err != nil {+ t.Fatalf("ApplyHostReport second: %v", err)+ }+ store.Flush()++ readPoints := waitForStoredDiskMetric(t, store, "SERIAL884006359727", "diskread")+ writePoints := waitForStoredDiskMetric(t, store, "SERIAL884006359727", "diskwrite")+ busyPoints := waitForStoredDiskMetric(t, store, "SERIAL884006359727", "disk")++ if got := readPoints[len(readPoints)-1].Value; got <= 0 {+ t.Fatalf("expected persisted diskread rate > 0, got %+v", readPoints)+ }+ if got := writePoints[len(writePoints)-1].Value; got <= 0 {+ t.Fatalf("expected persisted diskwrite rate > 0, got %+v", writePoints)+ }+ if got := busyPoints[len(busyPoints)-1].Value; got <= 0 || got > 100 {+ t.Fatalf("expected persisted disk busy percent within (0,100], got %+v", busyPoints)+ }++ if got := monitor.metricsHistory.GetDiskMetrics("SERIAL884006359727", "diskread", time.Hour); len(got) == 0 {+ t.Fatal("expected in-memory diskread history for physical disk")+ }+ if got := monitor.metricsHistory.GetDiskMetrics("SERIAL884006359727", "disk", time.Hour); len(got) == 0 {+ t.Fatal("expected in-memory busy history for physical disk")+ }+}+func TestApplyHostReportSkipsMetricsAndSMARTWritesInMockMode(t *testing.T) {previous := mock.IsMockEnabled()mock.SetEnabled(true)diff --git a/internal/monitoring/monitor_metrics.go b/internal/monitoring/monitor_metrics.goindex 54e78d01c1..a583c46efb 100644--- a/internal/monitoring/monitor_metrics.go+++ b/internal/monitoring/monitor_metrics.go@@ -144,6 +144,40 @@ func (m *Monitor) GetStorageMetrics(storageID string, duration time.Duration) mareturn m.metricsHistory.GetAllStorageMetrics(storageID, duration)}+// GetDiskMetrics returns historical metrics for a physical disk.+func (m *Monitor) GetDiskMetrics(resourceID string, metricType string, duration time.Duration) []MetricPoint {+ if m == nil || m.metricsHistory == nil {+ return nil+ }+ return m.metricsHistory.GetDiskMetrics(resourceID, metricType, duration)+}++// GetDiskMetricsForChart returns physical-disk metrics optimized for chart+// display, preferring in-memory data for freshness and falling back to the+// persistent store when coverage is shallow.+func (m *Monitor) GetDiskMetricsForChart(resourceID string, metricType string, duration time.Duration) []MetricPoint {+ if mock.IsMockEnabled() {+ if synthetic := mockDiskMetricsForChart(resourceID, []string{metricType}, duration); len(synthetic) > 0 {+ return synthetic[metricType]+ }+ return m.GetDiskMetrics(resourceID, metricType, duration)+ }++ inMemoryPoints := m.GetDiskMetrics(resourceID, metricType, duration)+ if hasSufficientChartSeriesCoverage(inMemoryPoints, duration) {+ return inMemoryPoints+ }++ best := cloneMetricSeries(inMemoryPoints)+ if converted, ok := m.queryStoreMetricMapWithGapFill("disk", resourceID, duration); ok {+ if candidate := converted[metricType]; shouldPreferMetricSeries(best, candidate, duration) {+ best = cloneMetricSeries(candidate)+ }+ }++ return best+}+// GetStorageMetricsForChart returns storage metrics, falling back to SQLite +// LTTB for longer ranges.func (m *Monitor) GetStorageMetricsForChart(storageID string, duration time.Duration) map[string][]MetricPoint {diff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.goindex b37c2a3841..4f5b4c36b0 100644--- a/internal/monitoring/monitor_metrics_slo_test.go+++ b/internal/monitoring/monitor_metrics_slo_test.go@@ -302,6 +302,42 @@ func TestSLO_GetPhysicalDiskTemperatureCharts_WithNativeHistoryFallback(t *testi}}+func TestSLO_GetDiskMetricsForChart_WithNativeStoreFallback(t *testing.T) {+ skipMonitoringSLOUnderRace(t)+ suppressMonitoringTestLogs(t)++ monitor := newChartFallbackTestMonitor(t)+ now := time.Now().UTC().Truncate(time.Second)+ duration := 4 * time.Hour++ writeRawMetricBatch(t, monitor.metricsStore, "disk", "SERIAL-DISK-IO-1", "diskread", []MetricPoint{+ {Timestamp: now.Add(-2 * time.Hour), Value: 1.25 * 1024 * 1024},+ {Timestamp: now.Add(-1 * time.Hour), Value: 2.5 * 1024 * 1024},+ {Timestamp: now, Value: 3.75 * 1024 * 1024},+ })++ sanity := monitor.GetDiskMetricsForChart("SERIAL-DISK-IO-1", "diskread", duration)+ if got := len(sanity); got != 3 {+ t.Fatalf("sanity: expected native diskread history, got %+v", sanity)+ }++ latencies := measureMonitoringLatencies(t, func() {+ result := monitor.GetDiskMetricsForChart("SERIAL-DISK-IO-1", "diskread", duration)+ if got := len(result); got != 3 {+ t.Fatalf("expected native diskread history, got %+v", result)+ }+ })++ target := effectiveMonitoringSLOTarget(SLOPhysicalDiskChartFallbackP95, SLOPhysicalDiskChartFallbackGHA)+ p95 := monitoringPercentile(latencies, 0.95)+ t.Logf("GetDiskMetricsForChart(native-store fallback) p50=%v p95=%v p99=%v SLO=%v",+ monitoringPercentile(latencies, 0.50), p95, monitoringPercentile(latencies, 0.99), target)++ if p95 > target {+ t.Errorf("SLO VIOLATION: p95=%v exceeds target %v", p95, target)+ }+}+func TestSLO_GetGuestMetricsForChart_WithNativeHistoryFallback(t *testing.T) {skipMonitoringSLOUnderRace(t)suppressMonitoringTestLogs(t)diff --git a/internal/monitoring/ratetracker.go b/internal/monitoring/ratetracker.goindex 5b561bb733..61d1163bf7 100644--- a/internal/monitoring/ratetracker.go+++ b/internal/monitoring/ratetracker.go@@ -59,6 +59,7 @@ type RateTracker struct {type RateCache struct {DiskReadRate float64DiskWriteRate float64+ DiskBusyPct float64NetInRate float64NetOutRate float64}@@ -74,6 +75,18 @@ func NewRateTracker() *RateTracker {// CalculateRates calculates I/O rates for a guest// Returns -1 for rates that don't have enough data yet (will be converted to null in JSON)func (rt *RateTracker) CalculateRates(guestID string, current IOMetrics) (diskReadRate, diskWriteRate, netInRate, netOutRate float64) {+ diskReadRate, diskWriteRate, _, netInRate, netOutRate = rt.calculateRates(guestID, current)+ return+}++// CalculateRatesWithBusy calculates disk/network rates plus disk busy percent+// from cumulative counters. Returns -1 for metrics that do not yet have enough+// data to produce a rate.+func (rt *RateTracker) CalculateRatesWithBusy(guestID string, current IOMetrics) (diskReadRate, diskWriteRate, diskBusyPct, netInRate, netOutRate float64) {+ return rt.calculateRates(guestID, current)+}++func (rt *RateTracker) calculateRates(guestID string, current IOMetrics) (diskReadRate, diskWriteRate, diskBusyPct, netInRate, netOutRate float64) {rt.mu.Lock()defer rt.mu.Unlock()@@ -84,7 +97,7 @@ func (rt *RateTracker) CalculateRates(guestID string, current IOMetrics) (diskRering = &counterRing{}ring.add(current)rt.history[guestID] = ring- return -1, -1, -1, -1+ return -1, -1, -1, -1, -1}prev := ring.newest()@@ -93,14 +106,15 @@ func (rt *RateTracker) CalculateRates(guestID string, current IOMetrics) (diskRe// If all cumulative values are the same, we're getting cached data from Proxmoxif current.DiskRead == prev.DiskRead &¤t.DiskWrite == prev.DiskWrite &&+ current.DiskBusy == prev.DiskBusy &¤t.NetworkIn == prev.NetworkIn &¤t.NetworkOut == prev.NetworkOut {// Data hasn't changed - return last known good ratesif lastRate, hasRate := rt.lastRates[guestID]; hasRate {- return lastRate.DiskReadRate, lastRate.DiskWriteRate, lastRate.NetInRate, lastRate.NetOutRate+ return lastRate.DiskReadRate, lastRate.DiskWriteRate, lastRate.DiskBusyPct, lastRate.NetInRate, lastRate.NetOutRate}// No last rates available, return 0- return 0, 0, 0, 0+ return 0, 0, 0, 0, 0}// Data has changed, add to ring buffer@@ -114,9 +128,9 @@ func (rt *RateTracker) CalculateRates(guestID string, current IOMetrics) (diskReif timeDiff <= 0 {// Return last known rates if time hasn't advancedif lastRate, hasRate := rt.lastRates[guestID]; hasRate {- return lastRate.DiskReadRate, lastRate.DiskWriteRate, lastRate.NetInRate, lastRate.NetOutRate+ return lastRate.DiskReadRate, lastRate.DiskWriteRate, lastRate.DiskBusyPct, lastRate.NetInRate, lastRate.NetOutRate}- return 0, 0, 0, 0+ return 0, 0, 0, 0, 0}// Calculate rates (bytes per second) over the window@@ -126,6 +140,15 @@ func (rt *RateTracker) CalculateRates(guestID string, current IOMetrics) (diskReif current.DiskWrite >= oldest.DiskWrite {diskWriteRate = float64(current.DiskWrite-oldest.DiskWrite) / timeDiff}+ if current.DiskBusy >= oldest.DiskBusy {+ diskBusyPct = (float64(current.DiskBusy-oldest.DiskBusy) / (timeDiff * 1000)) * 100+ if diskBusyPct < 0 {+ diskBusyPct = 0+ }+ if diskBusyPct > 100 {+ diskBusyPct = 100+ }+ }if current.NetworkIn >= oldest.NetworkIn {netInRate = float64(current.NetworkIn-oldest.NetworkIn) / timeDiff}@@ -137,6 +160,7 @@ func (rt *RateTracker) CalculateRates(guestID string, current IOMetrics) (diskRert.lastRates[guestID] = RateCache{DiskReadRate: diskReadRate,DiskWriteRate: diskWriteRate,+ DiskBusyPct: diskBusyPct,NetInRate: netInRate,NetOutRate: netOutRate,}diff --git a/tests/integration/tests/50-storage-physical-disk-io-history.spec.ts b/tests/integration/tests/50-storage-physical-disk-io-history.spec.tsnew file mode 100644index 0000000000..21481c2786--- /dev/null+++ b/tests/integration/tests/50-storage-physical-disk-io-history.spec.ts@@ -0,0 +1,191 @@+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { expect, test as base, type Page } from '@playwright/test';++import { createAuthenticatedStorageState, getMockMode, setMockMode } from './helpers';++const __dirname = path.dirname(fileURLToPath(import.meta.url));++type WorkerFixtures = {+ authStorageStatePath: string;+};++let mockModeWasEnabled: boolean | null = null;++const test = base.extend<{}, WorkerFixtures>({+ storageState: async ({ authStorageStatePath }, use) => {+ await use(authStorageStatePath);+ },+ authStorageStatePath: [async ({ browser }, use, workerInfo) => {+ const storageStatePath = path.resolve(+ __dirname,+ '..',+ '..',+ 'tmp',+ 'playwright-auth',+ `storage-physical-disk-io-history-${workerInfo.project.name}.json`,+ );+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });+ await createAuthenticatedStorageState(browser, storageStatePath);+ try {+ await use(storageStatePath);+ } finally {+ fs.rmSync(storageStatePath, { force: true });+ }+ }, { scope: 'worker' }],+});++async function ensureMockModeEnabled(page: Page): Promise<void> {+ const state = await getMockMode(page);+ if (mockModeWasEnabled === null) {+ mockModeWasEnabled = state.enabled;+ }+ if (!state.enabled) {+ await setMockMode(page, true);+ }+}++test.describe.serial('Storage physical disk drawer history', () => {+ test.setTimeout(180_000);++ test.afterAll(async ({ browser }) => {+ if (mockModeWasEnabled === null) return;++ const context = await browser.newContext();+ const page = await context.newPage();+ try {+ const current = await getMockMode(page);+ if (current.enabled !== mockModeWasEnabled) {+ await setMockMode(page, mockModeWasEnabled);+ }+ } finally {+ await context.close();+ }+ });++ test('renders canonical live I/O history for Proxmox physical disks', async ({ page }) => {+ await ensureMockModeEnabled(page);++ const diskHistoryResponses = new Map<string, { resourceId: string; points: number }>();+ page.on('response', async (response) => {+ const url = response.url();+ if (!url.includes('/api/metrics-store/history')) {+ return;+ }+ const parsed = new URL(url);+ if (parsed.searchParams.get('resourceType') !== 'disk') {+ return;+ }+ const metric = parsed.searchParams.get('metric') || '';+ if (!['diskread', 'diskwrite', 'disk'].includes(metric)) {+ return;+ }++ const payload = (await response.json()) as { resourceId?: string; points?: unknown[] };+ diskHistoryResponses.set(metric, {+ resourceId: payload.resourceId || '',+ points: Array.isArray(payload.points) ? payload.points.length : 0,+ });+ });++ await page.goto('/storage?tab=disks&source=proxmox-pve', { waitUntil: 'domcontentloaded' });+ await expect(page.getByTestId('storage-summary')).toBeVisible();+ await page.getByRole('textbox', { name: /search storage/i }).fill('nvme2');++ const row = page+ .locator('table tbody tr')+ .filter({ hasText: 'Samsung 980 PRO 2TB' })+ .filter({ hasText: 'pve2' })+ .first();++ await expect(row).toBeVisible();+ await row.getByRole('button', { name: /toggle details/i }).click();++ const detail = page.locator('[data-inline-detail-for]').filter({ has: page.getByText('Live I/O (30m)') }).first();+ await expect(detail).toBeVisible();+ await expect(detail.getByText('Collecting data... History will appear here.')).toHaveCount(0);++ await expect+ .poll(() => Array.from(diskHistoryResponses.keys()).sort().join(','))+ .toBe('disk,diskread,diskwrite');++ for (const metric of ['diskread', 'diskwrite', 'disk'] as const) {+ await expect+ .poll(() => diskHistoryResponses.get(metric)?.resourceId || '')+ .toBe('SERIAL884006359727');+ await expect+ .poll(() => diskHistoryResponses.get(metric)?.points || 0)+ .toBeGreaterThan(0);+ }+ });++ test('keeps visible physical-disk drawers hydrated with live I/O history', async ({ page }) => {+ await ensureMockModeEnabled(page);++ await page.goto('/storage?tab=disks', { waitUntil: 'domcontentloaded' });+ await expect(page.getByTestId('storage-summary')).toBeVisible();++ const rows = page.locator('table tbody tr[data-row-id]');+ const rowCount = await rows.count();+ expect(rowCount).toBeGreaterThan(0);++ const failures: string[] = [];+ const maxRows = Math.min(rowCount, 12);++ for (let index = 0; index < maxRows; index += 1) {+ const row = rows.nth(index);+ await row.scrollIntoViewIfNeeded();++ const rowText = (await row.innerText()).replace(/\s+/g, ' ').trim();+ const summarySeriesId = (await row.getAttribute('data-summary-series-id')) || '';+ const detailResponsePoints = new Map<string, number>();++ const responseHandler = async (response: { url(): string; json(): Promise<unknown> }) => {+ const url = response.url();+ if (!url.includes('/api/metrics-store/history')) return;++ const parsed = new URL(url);+ if (parsed.searchParams.get('resourceType') !== 'disk') return;+ if (parsed.searchParams.get('resourceId') !== summarySeriesId) return;++ const metric = parsed.searchParams.get('metric') || '';+ if (!['diskread', 'diskwrite', 'disk'].includes(metric)) return;++ const payload = (await response.json()) as { points?: unknown[] };+ detailResponsePoints.set(metric, Array.isArray(payload.points) ? payload.points.length : 0);+ };++ page.on('response', responseHandler);+ try {+ await row.getByRole('button', { name: /toggle details/i }).click();++ const detail = page.locator(`[data-inline-detail-for="${summarySeriesId}"]`);+ await expect(detail).toBeVisible();+ await page.waitForTimeout(250);++ const collectingCount = await detail+ .getByText('Collecting data... History will appear here.')+ .count();++ if (collectingCount > 0) {+ failures.push(`${rowText} [overlay]`);+ } else {+ for (const metric of ['diskread', 'diskwrite', 'disk'] as const) {+ const points = detailResponsePoints.get(metric) || 0;+ if (points <= 0) {+ failures.push(`${rowText} [${metric}:0 points via ${summarySeriesId || 'no-series-id'}]`);+ break;+ }+ }+ }++ await row.getByRole('button', { name: /toggle details/i }).click();+ } finally {+ page.off('response', responseHandler);+ }+ }++ expect(failures, failures.join('\n')).toEqual([]);+ });+});