Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Scale large-estate realtime monitoring

rcourtman10116cc17efb
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index ed6463d29a..f253ccb890 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -246,8 +246,9 @@ default construction path still restores.
## Shared Boundaries
-1. `internal/operationaltrust/contracts.go` shared with `notifications`: the operational trust contract is jointly consumed by canonical alert lifecycle ownership and notification delivery linkage without making delivery state operational truth.
-2. `internal/proxmoxidentity/backup_identity.go` shared with `monitoring`, `storage-recovery`: Proxmox PBS backup subject identity is a shared runtime boundary for monitoring backup freshness, backup-age alert attribution, and recovery-point guest mapping.
+1. `frontend-modern/src/stores/websocket.ts` shared with `performance-and-scalability`: the connection-owned realtime store is both the canonical alert truth boundary and the fleet-scale resource reconciliation hot path.
+2. `internal/operationaltrust/contracts.go` shared with `notifications`: the operational trust contract is jointly consumed by canonical alert lifecycle ownership and notification delivery linkage without making delivery state operational truth.
+3. `internal/proxmoxidentity/backup_identity.go` shared with `monitoring`, `storage-recovery`: Proxmox PBS backup subject identity is a shared runtime boundary for monitoring backup freshness, backup-age alert attribution, and recovery-point guest mapping.
Alert multiline field presentation is shared with frontend-primitives:
notification, timeline, threshold ignored-prefix, and resource threshold note
editors must compose the shared `FormTextarea` primitive for label/id/help
@@ -283,6 +284,12 @@ invalidation is not lost. Late socket callbacks and REST responses from a
retired connection must be ignored, while a current oversized connection
remains free to hydrate without waiting for the retired connection's request
to settle.
+While the document is hidden, that same connection-scoped baseline must keep
+accepting resource deltas without reconciling the visible resource store on
+every message. The store accumulates changed resource IDs and performs one
+canonical catch-up reconciliation on `visibilitychange` to visible. Alert and
+resolved-alert truth continues to update normally while hidden; this resource
+optimization must not defer, clear, or reinterpret alert lifecycle state.
Operational evidence and lifecycle identity are typed through
`internal/operationaltrust`. Evidence envelopes distinguish completeness,
confidence, permissions, freshness, correlation, and bounded provider detail.
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index fe0f06b69f..46bf04146d 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -1170,7 +1170,10 @@ not a replacement status card, CTA band, or page-local nested card.
`frontend-modern/src/components/shared/AnimatedNumber.tsx` and its
`useAnimatedNumberState` owner. Feature surfaces may opt metric labels and
compact counters into that primitive, but must not create local counter
- timers, page-specific easing, or independent reduced-motion policy.
+ timers, page-specific easing, or independent reduced-motion policy. The
+ shared owner must also cap concurrent numeric animations and snap overflow
+ readouts to their current target so a realtime estate update cannot make
+ animation cost grow with the number of visible resources.
Shared primitives must not reintroduce app-shell monitored-system capacity
banners. Monitored-system grouping and ledger presentation belongs in the
owned settings surfaces, while commercial plan explanation belongs in
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 14541ceb06..9e1ca2f422 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -463,6 +463,7 @@ cleanup so readers cannot retain orphaned runtime or alert projections.
35a. `internal/mock/action_fixtures.go`
35b. `internal/mock/availability_fixtures.go`
35c. `internal/mock/recovery_points.go`
+35d. `internal/mock/integration.go`
36. `internal/dockeragent/docker_client.go`
37. `pkg/agents/docker/report.go`
38. `internal/models/models.go`
@@ -505,11 +506,14 @@ cleanup so readers cannot retain orphaned runtime or alert projections.
1. `internal/config/host_continuity.go` shared with `agent-lifecycle`: the durable host identity, report-order watermark, and removal tombstone journal is jointly owned by agent lifecycle admission and monitoring report continuity.
2. `internal/kubernetesagent/agent.go` shared with `agent-lifecycle`: the Kubernetes native agent runtime is both a monitoring inventory source and an agent lifecycle Pulse control-plane transport client.
-3. `internal/models/models.go` shared with `agent-lifecycle`: removed host-agent identity aliases and tombstone state are both agent lifecycle authority and monitoring runtime report state.
-4. `internal/monitoring/monitor.go` shared with `agent-lifecycle`: monitor construction owns both monitoring runtime initialization and fail-closed agent lifecycle journal hydration before report admission.
-5. `internal/monitoring/monitor_agents.go` shared with `agent-lifecycle`: server-side Unified Agent report, removal, token binding, tombstone expiry, and re-enrollment semantics are jointly owned by agent lifecycle authority and monitoring ingest.
-6. `internal/proxmoxidentity/backup_identity.go` shared with `alerts`, `storage-recovery`: Proxmox PBS backup subject identity is a shared runtime boundary for monitoring backup freshness, backup-age alert attribution, and recovery-point guest mapping.
-7. `pkg/agents/host/report.go` shared with `agent-lifecycle`: the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host maintenance posture.
+3. `internal/mock/fixture_graph.go` shared with `performance-and-scalability`: the canonical mock fixture graph is both monitoring-owned runtime data and a protected large-estate demo transport hot path.
+4. `internal/mock/generator.go` shared with `performance-and-scalability`: mock metric generation is both monitoring-owned runtime data and a protected large-estate demo update hot path.
+5. `internal/mock/integration.go` shared with `performance-and-scalability`: the mock runtime scheduler is both monitoring-owned sampling infrastructure and a protected large-estate demo cadence boundary.
+6. `internal/models/models.go` shared with `agent-lifecycle`: removed host-agent identity aliases and tombstone state are both agent lifecycle authority and monitoring runtime report state.
+7. `internal/monitoring/monitor.go` shared with `agent-lifecycle`: monitor construction owns both monitoring runtime initialization and fail-closed agent lifecycle journal hydration before report admission.
+8. `internal/monitoring/monitor_agents.go` shared with `agent-lifecycle`: server-side Unified Agent report, removal, token binding, tombstone expiry, and re-enrollment semantics are jointly owned by agent lifecycle authority and monitoring ingest.
+9. `internal/proxmoxidentity/backup_identity.go` shared with `alerts`, `storage-recovery`: Proxmox PBS backup subject identity is a shared runtime boundary for monitoring backup freshness, backup-age alert attribution, and recovery-point guest mapping.
+10. `pkg/agents/host/report.go` shared with `agent-lifecycle`: the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host maintenance posture.
## Extension Points
@@ -682,6 +686,17 @@ cleanup so readers cannot retain orphaned runtime or alert projections.
`GetState()` owns lazy fixture alert-snapshot initialization, so the ticker
must preserve that maintenance call before its subscriber early-exit while
production monitors continue to skip the snapshot build.
+ The mock update loop must advance the 50-node demo through ten node-scoped
+ metric cohorts on the shared two-second sampler. It must preserve unchanged
+ resource timestamps between cohorts, cover every node within twenty seconds,
+ and refresh provider-backed fixtures only once per full rotation so one demo
+ tick cannot manufacture an estate-wide WebSocket delta.
+ Mock metrics history must also stay bounded independently of estate size:
+ eager multi-day PVE guest history is limited to a deterministic sample spread
+ across the estate, while every omitted guest continues to receive the same
+ canonical timeline through deterministic on-demand chart synthesis. Dashboard
+ chart prewarming is limited per workload family and must never rebuild an
+ estate-sized guest chart cache on each mock sampler tick.
`POLL_TASK_WORKERS` is a process-wide scheduled-task concurrency ceiling,
not a per-monitor pool size. Each monitor may own one queue dispatcher, but
all dispatchers must acquire the shared bounded limiter before executing a
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 1f5e95f70a..3084198373 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -145,6 +145,14 @@ start a goroutine, timer, or notification lifecycle per target.
110. `frontend-modern/src/utils/__tests__/searchQuery.test.ts`
111. `pkg/server/gzip_middleware.go`
112. `pkg/server/gzip_middleware_test.go`
+113. `frontend-modern/src/stores/websocket.ts`
+114. `frontend-modern/src/utils/resourceStateAdapters.ts`
+115. `internal/mock/fixture_graph.go`
+116. `internal/mock/generator.go`
+117. `internal/mock/integration.go`
+118. `internal/mock/platform_fixtures_test.go`
+119. `frontend-modern/src/stores/__tests__/websocket-unified.test.ts`
+120. `frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts`
## Shared Boundaries
@@ -160,6 +168,7 @@ start a goroutine, timer, or notification lifecycle per target.
10. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableState.ts` shared with `unified-resources`: unified resource table state, grouping, and windowing are both a canonical unified-resource consumer surface and a fleet-scale performance hot-path boundary.
11. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableViewportSync.ts` shared with `unified-resources`: unified resource table viewport sync and selected-row reveal are both a canonical unified-resource consumer surface and a fleet-scale performance hot-path boundary.
15. `frontend-modern/src/routing/routePreload.ts` shared with `frontend-primitives`, `unified-resources`: the app-shell route preload registry is a canonical frontend shell boundary, an authenticated hot-path performance boundary, and the entry point for the unified-resource Actions workspace.
+19. `frontend-modern/src/stores/websocket.ts` shared with `alerts`: the connection-owned realtime store is both the canonical alert truth boundary and the fleet-scale resource reconciliation hot path.
16. `frontend-modern/src/useAppRuntimeState.ts` shared with `cloud-paid`: the authenticated app runtime bootstrap is both a hosted commercial org-context boundary and a protected app-shell performance boundary.
Security-status SSO display labels are part of the existing authenticated
bootstrap payload. The app shell may project `ssoSessionDisplayName` into
@@ -177,8 +186,28 @@ start a goroutine, timer, or notification lifecycle per target.
WebSocket startup, so a delayed or blocked first stream snapshot cannot
hide server-owned platform scopes; auth-mode branches must not fork
additional state probes or perform the same hydration twice.
+20. `frontend-modern/src/utils/resourceStateAdapters.ts` shared with `unified-resources`: canonical resource compatibility and host coalescence are both a unified-resource contract and a fleet-scale reconciliation hot path.
17. `frontend-modern/src/utils/workloads.ts` shared with `unified-resources`: the stable workload metadata identity helper is both a unified-resource persistence boundary and a workloads hot-path lookup boundary.
18. `internal/api/slo.go` shared with `api-contracts`: the SLO endpoint is both an API contract surface and a protected performance hot-path boundary.
+21. `internal/mock/fixture_graph.go` shared with `monitoring`: the canonical mock fixture graph is both monitoring-owned runtime data and a protected large-estate demo transport hot path.
+22. `internal/mock/generator.go` shared with `monitoring`: mock metric generation is both monitoring-owned runtime data and a protected large-estate demo update hot path.
+23. `internal/mock/integration.go` shared with `monitoring`: the mock runtime scheduler is both monitoring-owned sampling infrastructure and a protected large-estate demo cadence boundary.
+
+Large-estate realtime updates must be sparse end to end. The public 50-node,
+900-guest demo advances node-scoped metrics through ten bounded cohorts on the
+shared two-second sampler, keeping each node current within twenty seconds while
+leaving broadcast headroom to coalesce several sampler invalidations. A cohort
+must not rebase unchanged guest, node, storage, or disk evidence, and the
+provider-backed fixture set refreshes once per full rotation rather than on
+every tick.
+
+The browser applies resource deltas to its connection-scoped raw baseline, but
+canonicalizes and reconciles only changed resources plus the bounded
+host-coalescing set. Unchanged non-host display resources retain object identity.
+Hidden tabs continue advancing the raw baseline without reconciling the estate;
+all hidden changes are materialized once when the document becomes visible.
+These rules must be proved against a 50-node fixture and may not be replaced by
+blank-row virtualization or a second page-local polling path.
Governed action decisions preserve SQLite and MemoryStore parity through one
shared pure append command. Every accepted approval advances a monotonic
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index ca8dbfa59d..dde8926577 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -467,6 +467,14 @@
"frontend-primitives"
]
},
+ {
+ "path": "frontend-modern/src/stores/websocket.ts",
+ "rationale": "the connection-owned realtime store is both the canonical alert truth boundary and the fleet-scale resource reconciliation hot path",
+ "subsystems": [
+ "alerts",
+ "performance-and-scalability"
+ ]
+ },
{
"path": "frontend-modern/src/useAppRuntimeState.ts",
"rationale": "the authenticated app runtime bootstrap is both a hosted commercial org-context boundary and a protected app-shell performance boundary",
@@ -507,6 +515,14 @@
"unified-resources"
]
},
+ {
+ "path": "frontend-modern/src/utils/resourceStateAdapters.ts",
+ "rationale": "canonical resource compatibility and host coalescence are both a unified-resource contract and a fleet-scale reconciliation hot path",
+ "subsystems": [
+ "performance-and-scalability",
+ "unified-resources"
+ ]
+ },
{
"path": "frontend-modern/src/utils/sourcePlatforms.ts",
"rationale": "the source platform normalizer is both a canonical unified-resource source adapter boundary and a shared frontend source/platform vocabulary boundary",
@@ -1046,6 +1062,30 @@
"monitoring"
]
},
+ {
+ "path": "internal/mock/fixture_graph.go",
+ "rationale": "the canonical mock fixture graph is both monitoring-owned runtime data and a protected large-estate demo transport hot path",
+ "subsystems": [
+ "monitoring",
+ "performance-and-scalability"
+ ]
+ },
+ {
+ "path": "internal/mock/generator.go",
+ "rationale": "mock metric generation is both monitoring-owned runtime data and a protected large-estate demo update hot path",
+ "subsystems": [
+ "monitoring",
+ "performance-and-scalability"
+ ]
+ },
+ {
+ "path": "internal/mock/integration.go",
+ "rationale": "the mock runtime scheduler is both monitoring-owned sampling infrastructure and a protected large-estate demo cadence boundary",
+ "subsystems": [
+ "monitoring",
+ "performance-and-scalability"
+ ]
+ },
{
"path": "internal/models/models.go",
"rationale": "removed host-agent identity aliases and tombstone state are both agent lifecycle authority and monitoring runtime report state",
@@ -2212,6 +2252,7 @@
"test_prefixes": [],
"exact_files": [
"frontend-modern/src/stores/__tests__/websocket-resilience.test.ts",
+ "frontend-modern/src/stores/__tests__/websocket-unified.test.ts",
"frontend-modern/src/utils/__tests__/alertsActivation.branchcov0712c.test.ts",
"frontend-modern/src/utils/__tests__/alertsActivation.test.ts"
]
@@ -5363,6 +5404,7 @@
"frontend-modern/src/components/shared/__tests__/TagBadges.test.tsx",
"frontend-modern/src/components/shared/__tests__/UpgradeLink.test.tsx",
"frontend-modern/src/components/shared/__tests__/WebInterfaceUrlField.test.tsx",
+ "frontend-modern/src/components/shared/AnimatedNumber.test.tsx",
"frontend-modern/src/components/shared/ColumnPicker.test.tsx",
"frontend-modern/src/components/shared/FilterToolbar.test.tsx",
"frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts",
@@ -5401,6 +5443,7 @@
"internal/mock/demo_scenarios.go",
"internal/mock/fixture_graph.go",
"internal/mock/generator.go",
+ "internal/mock/integration.go",
"internal/mock/platform_fixtures.go",
"internal/mock/recovery_points.go",
"internal/models/converters.go",
@@ -5771,6 +5814,7 @@
"internal/mock/demo_scenarios.go",
"internal/mock/fixture_graph.go",
"internal/mock/generator.go",
+ "internal/mock/integration.go",
"internal/mock/platform_fixtures.go",
"internal/mock/recovery_points.go"
],
@@ -5781,6 +5825,7 @@
"internal/mock/canonical_api_guardrails_test.go",
"internal/mock/demo_scenarios_test.go",
"internal/mock/generator_test.go",
+ "internal/mock/integration_coverage_test.go",
"internal/mock/platform_fixtures_test.go",
"internal/mock/recovery_points_test.go",
"tests/integration/tests/43-platform-mock-runtime.spec.ts"
@@ -6448,8 +6493,10 @@
"frontend-modern/src/components/Workloads/workloadUrlSyncModel.ts",
"frontend-modern/src/hooks/useWorkloads.ts",
"frontend-modern/src/routing/routePreload.ts",
+ "frontend-modern/src/stores/websocket.ts",
"frontend-modern/src/types/workloads.ts",
"frontend-modern/src/useAppRuntimeState.ts",
+ "frontend-modern/src/utils/resourceStateAdapters.ts",
"frontend-modern/src/utils/searchQuery.ts",
"frontend-modern/src/utils/thresholdSliderPresentation.ts",
"frontend-modern/src/utils/workloads.ts",
@@ -6457,6 +6504,9 @@
"internal/api/router_bench_test.go",
"internal/api/slo.go",
"internal/api/slo_bench_test.go",
+ "internal/mock/fixture_graph.go",
+ "internal/mock/generator.go",
+ "internal/mock/integration.go",
"pkg/server/gzip_middleware.go"
],
"verification": {
@@ -6525,6 +6575,26 @@
"pkg/metrics/store_slo_test.go"
]
},
+ {
+ "id": "large-estate-realtime-state",
+ "label": "large-estate realtime state update proof",
+ "match_prefixes": [],
+ "match_files": [
+ "frontend-modern/src/stores/websocket.ts",
+ "frontend-modern/src/utils/resourceStateAdapters.ts",
+ "internal/mock/fixture_graph.go",
+ "internal/mock/generator.go",
+ "internal/mock/integration.go"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "frontend-modern/src/stores/__tests__/websocket-unified.test.ts",
+ "frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts",
+ "internal/mock/integration_coverage_test.go",
+ "internal/mock/platform_fixtures_test.go"
+ ]
+ },
{
"id": "app-shell-route-preload",
"label": "app-shell route preload proof",
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index bb11766a6b..184b6ed6bb 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -795,7 +795,8 @@ container inventory table.
It must carry the manifest `surface_kind` distinction so `docker` remains
machine-readable as a `runtime-lens` while owning infrastructure sources
remain `platform` entries.
-17. `frontend-modern/src/utils/sourcePlatforms.ts` shared with `frontend-primitives`: the source platform normalizer is both a canonical unified-resource source adapter boundary and a shared frontend source/platform vocabulary boundary.
+17. `frontend-modern/src/utils/resourceStateAdapters.ts` shared with `performance-and-scalability`: canonical resource compatibility and host coalescence are both a unified-resource contract and a fleet-scale reconciliation hot path.
+18. `frontend-modern/src/utils/sourcePlatforms.ts` shared with `frontend-primitives`: the source platform normalizer is both a canonical unified-resource source adapter boundary and a shared frontend source/platform vocabulary boundary.
That shared vocabulary boundary owns the generic `docker` platform label:
selectors, badges, and filter options render it as "Docker / Podman" so
v5 Docker users can still find the runtime surface while Podman-backed
@@ -817,8 +818,8 @@ container inventory table.
display/source family; `platformScopes` is the overlap set used when a
runtime workload belongs to both Docker and an owning infrastructure
platform.
-18. `frontend-modern/src/utils/workloads.ts` shared with `performance-and-scalability`: the stable workload metadata identity helper is both a unified-resource persistence boundary and a workloads hot-path lookup boundary.
-19. `internal/api/resourceapi/resources.go` shared with `api-contracts`: the unified resource endpoint is both a backend payload contract surface and a unified-resource runtime boundary.
+19. `frontend-modern/src/utils/workloads.ts` shared with `performance-and-scalability`: the stable workload metadata identity helper is both a unified-resource persistence boundary and a workloads hot-path lookup boundary.
+20. `internal/api/resourceapi/resources.go` shared with `api-contracts`: the unified resource endpoint is both a backend payload contract surface and a unified-resource runtime boundary.
`/api/resources` type filters must accept URL-encoded comma-separated lists
from browser query builders exactly like literal comma separators, so Docker
/ Podman runtime pages do not lose `docker-host` inventory while requesting
@@ -1147,6 +1148,11 @@ AI-only summary payloads, or page-local heuristics.
`name -> type -> id` order across registry reads, REST pagination, and
websocket-backed refreshes so equal-name resources do not silently reshuffle
between cold hydrate and later runtime updates
+ Realtime delta reconciliation must preserve exact display-object identity
+ for untouched non-host resources, canonicalize changed and newly added rows,
+ and always recompute the bounded agent/host coalescing set. Incremental and
+ full-snapshot paths must therefore produce the same canonical host identity,
+ labels, and compatibility fields without cloning the entire estate per tick.
That same unified-resource owner also defines the canonical transport
projection for operator-facing resources: `/api/resources` and websocket
`state.resources` must share `ContractResourceType`, canonical display
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index f485f23714..ddb4b93cb4 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,13 +1,17 @@
{
"version": 1,
- "base_sha": "35b8c0a4c2ccbc11a1bb67116cb2d1e8f6d72391",
- "verified_at": "2026-08-23T18:52:30Z",
+ "base_sha": "6ee36bc1ea456938a22f5a4bae4d3332ca98d9ed",
+ "verified_at": "2026-08-23T18:54:26Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/features/proxmox/ProxmoxPageSurface.tsx"
+ "frontend-modern/src/components/shared/useAnimatedNumberState.ts",
+ "frontend-modern/src/stores/websocket.ts",
+ "frontend-modern/src/utils/resourceStateAdapters.ts"
],
"content_sha256": {
- "frontend-modern/src/features/proxmox/ProxmoxPageSurface.tsx": "5fbcb11d536ff657dcbffbe25c3b749bcf8bd4ff545dbdd0c02d3414c703c759"
+ "frontend-modern/src/components/shared/useAnimatedNumberState.ts": "eff0a4e3e886c41515e1ebfb563004bad0218dda1e1465d45ab6d0025ab10363",
+ "frontend-modern/src/stores/websocket.ts": "f2d071acd989ba5fa3c2877be66ae54231adfe34e311e19151b3ddeb1de4e923",
+ "frontend-modern/src/utils/resourceStateAdapters.ts": "3999af02f025c93d3ffd8fc2d28d801d264b35e7091f0262d869ce8e60569433"
},
"routes": [
"/proxmox/overview"
@@ -23,15 +27,16 @@
}
],
"states": [
- "Fresh desktop navigation to /proxmox/overview hydrated the connected 50-node and 929-guest mock estate",
- "Searching for guest artifact-cache-310 reduced the node result from 50 to 1 and retained only its Analytics A parent node",
- "The same guest search at 390x844 retained one matching node and one matching guest without page-level horizontal overflow",
- "Clearing the search restored all 50 nodes, and the browser console remained free of warnings and errors"
+ "Fresh desktop navigation hydrated the connected 50-node and 929-guest mock estate with both Nodes and Guests tables visible",
+ "A fast desktop table scroll to scrollTop 20000 retained populated guest rows with no blank virtualized section",
+ "At 390x844 the node summary, Nodes table, and Guests table remained visible, and a fast table scroll to scrollTop 12000 retained populated rows",
+ "The Back to top control appeared after deep scrolling and returned the desktop table to scrollTop 0",
+ "A clean phone-width reload remained stable during sustained realtime updates with no console errors"
],
"interactions": [
- "Loaded /proxmox/overview in a fresh desktop tab and waited for the full large-estate resource snapshot",
- "Entered artifact-cache-310 in the shared VM and LXC search and inspected both the Nodes and Guests tables",
- "Cleared the search with the visible Clear search control and confirmed the complete node estate returned",
- "Repeated the guest search at 390x844 and measured document clientWidth and scrollWidth at 390 pixels"
+ "Loaded /proxmox/overview in fresh desktop and phone-width tabs and waited for the full large-estate snapshot",
+ "Performed fast wheel-equivalent guest-table scrolling at desktop and phone widths and inspected the rendered row window",
+ "Activated Back to top after a deep desktop scroll and confirmed the scroll settled at the table origin",
+ "Reloaded the phone-width route after the animation bound changed and sampled sustained renderer metrics and console output"
]
}
diff --git a/frontend-modern/src/components/shared/AnimatedNumber.test.tsx b/frontend-modern/src/components/shared/AnimatedNumber.test.tsx
index 6d1c0f39ec..4290d07955 100644
--- a/frontend-modern/src/components/shared/AnimatedNumber.test.tsx
+++ b/frontend-modern/src/components/shared/AnimatedNumber.test.tsx
@@ -1,8 +1,9 @@
-import { createSignal } from 'solid-js';
+import { createSignal, For } from 'solid-js';
import { cleanup, render } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { formatPercent } from '@/utils/format';
import { AnimatedNumber } from './AnimatedNumber';
+import { MAX_CONCURRENT_ANIMATED_NUMBER_ENTRIES } from './useAnimatedNumberState';
let queuedFrames: FrameRequestCallback[] = [];
let reducedMotionMatches = false;
@@ -99,4 +100,24 @@ describe('AnimatedNumber', () => {
expect(readout).toHaveAttribute('aria-label', '50%');
expect(queuedFrames).toHaveLength(0);
});
+
+ it('bounds concurrent animation work when many readouts change together', () => {
+ const indices = Array.from(
+ { length: MAX_CONCURRENT_ANIMATED_NUMBER_ENTRIES + 1 },
+ (_, index) => index,
+ );
+ const [value, setValue] = createSignal(10);
+ const { container } = render(() => (
+ <For each={indices}>{() => <AnimatedNumber value={value()} format={formatPercent} />}</For>
+ ));
+
+ setValue(50);
+
+ const readouts = Array.from(container.querySelectorAll('[data-animated-number="true"]'));
+ expect(queuedFrames).toHaveLength(1);
+ expect(readouts.filter((readout) => readout.textContent === '10%')).toHaveLength(
+ MAX_CONCURRENT_ANIMATED_NUMBER_ENTRIES,
+ );
+ expect(readouts.filter((readout) => readout.textContent === '50%')).toHaveLength(1);
+ });
});
diff --git a/frontend-modern/src/components/shared/useAnimatedNumberState.ts b/frontend-modern/src/components/shared/useAnimatedNumberState.ts
index 6a885f6921..9e2d7495e1 100644
--- a/frontend-modern/src/components/shared/useAnimatedNumberState.ts
+++ b/frontend-modern/src/components/shared/useAnimatedNumberState.ts
@@ -29,6 +29,7 @@ type MotionMediaQueryList = MediaQueryList & {
};
const activeFrameEntries = new Map<number, AnimatedNumberFrameEntry>();
+export const MAX_CONCURRENT_ANIMATED_NUMBER_ENTRIES = 24;
let nextFrameEntryId = 1;
let frameRequestId: number | undefined;
@@ -84,6 +85,15 @@ function startAnimatedNumberFrame(entry: AnimatedNumberFrameEntry): () => void {
return () => undefined;
}
+ // A single estate update can change hundreds of visible metric labels at
+ // once. Keep a small amount of motion for continuity, then snap overflow
+ // labels to their target so animation work cannot scale with estate size.
+ if (activeFrameEntries.size >= MAX_CONCURRENT_ANIMATED_NUMBER_ENTRIES) {
+ entry.onFrame(entry.to);
+ entry.onDone();
+ return () => undefined;
+ }
+
const id = nextFrameEntryId;
nextFrameEntryId += 1;
activeFrameEntries.set(id, entry);
diff --git a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
index ad08d0ecbe..a46913d98c 100644
--- a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
+++ b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
@@ -445,6 +445,59 @@ describe('websocket store unified resource contract', () => {
}
});
+ it('coalesces hidden-tab resource deltas into one visible-state reconciliation', async () => {
+ const visibility = vi.spyOn(document, 'visibilityState', 'get');
+ visibility.mockReturnValue('visible');
+ const { store, dispose } = await createStoreHarness();
+ try {
+ await waitForOpenTick();
+ emitMessage({
+ type: 'initialState',
+ data: {
+ resources: [
+ {
+ id: 'vm-1',
+ type: 'vm',
+ name: 'vm-1',
+ status: 'running',
+ cpu: { current: 10 },
+ },
+ ],
+ lastUpdate: 100,
+ activeAlerts: [],
+ recentlyResolved: [],
+ },
+ });
+
+ visibility.mockReturnValue('hidden');
+ emitMessage({
+ type: 'rawData',
+ data: {
+ lastUpdate: 200,
+ resourceDelta: { upserts: [{ id: 'vm-1', cpu: { current: 20 } }] },
+ },
+ });
+ emitMessage({
+ type: 'rawData',
+ data: {
+ lastUpdate: 300,
+ resourceDelta: { upserts: [{ id: 'vm-1', cpu: { current: 30 } }] },
+ },
+ });
+
+ expect(store.state.resources[0]?.cpu?.current).toBe(10);
+ expect(store.state.lastUpdate).toBe(300);
+
+ visibility.mockReturnValue('visible');
+ document.dispatchEvent(new Event('visibilitychange'));
+
+ expect(store.state.resources[0]?.cpu?.current).toBe(30);
+ } finally {
+ dispose();
+ visibility.mockRestore();
+ }
+ });
+
// Regression: on estates large enough that the full snapshot exceeds the
// inbound guard (~3100 resources at the ~2.7 KB/resource measured against a
// real /api/state payload; ~12.8 MB at 5000), the client dropped initialState
diff --git a/frontend-modern/src/stores/websocket.ts b/frontend-modern/src/stores/websocket.ts
index 166adf81ef..a8c461efb1 100644
--- a/frontend-modern/src/stores/websocket.ts
+++ b/frontend-modern/src/stores/websocket.ts
@@ -18,7 +18,10 @@ import {
getAgentDiscoveryResourceId,
isAppContainerDiscoveryResourceType,
} from '@/utils/discoveryTarget';
-import { mergeCanonicalResourceSnapshot } from '@/utils/resourceStateAdapters';
+import {
+ mergeCanonicalResourceDeltaSnapshot,
+ mergeCanonicalResourceSnapshot,
+} from '@/utils/resourceStateAdapters';
import { apiFetchJSON } from '@/utils/apiClient';
// Advertised to the server as max_message_bytes on the upgrade request; the
@@ -94,18 +97,20 @@ const applyJSONMergePatch = (current: unknown, patch: unknown): unknown => {
const applyResourceStateDelta = (
current: readonly Resource[],
delta: { upserts?: unknown; removed?: unknown; order?: unknown },
-): Resource[] => {
+): { resources: Resource[]; changedIds: Set<string> } => {
const resourcesById = new Map(current.map((resource) => [resource.id, resource] as const));
const removed = Array.isArray(delta.removed)
? new Set(delta.removed.filter((id): id is string => typeof id === 'string'))
: new Set<string>();
removed.forEach((id) => resourcesById.delete(id));
+ const changedIds = new Set(removed);
const addedIds: string[] = [];
if (Array.isArray(delta.upserts)) {
delta.upserts.forEach((patch) => {
const id = asString(asRecord(patch)?.id);
if (!id) return;
+ changedIds.add(id);
if (!resourcesById.has(id)) addedIds.push(id);
const next = applyJSONMergePatch(resourcesById.get(id), patch) as Resource;
if (next.id === id) resourcesById.set(id, next);
@@ -126,7 +131,7 @@ const applyResourceStateDelta = (
resourcesById.forEach((resource, id) => {
if (!included.has(id)) ordered.push(resource);
});
- return ordered;
+ return { resources: ordered, changedIds };
};
const parseTimestampMs = (value: unknown): number | null => {
@@ -329,6 +334,7 @@ export function createWebSocketStore(url: string) {
// merge are cloned first, because the merge output shares nested references
// and Solid's reconcile mutates adopted objects in place.
let rawServerResources: Resource[] | null = null;
+ const deferredResourceIds = new Set<string>();
let lastFullStateRecoveryAt = 0;
// Set once the server has sent a full snapshot too large for the inbound
// guard. Asking for another one over the socket would only reproduce the same
@@ -394,6 +400,7 @@ export function createWebSocketStore(url: string) {
const resetConnectionBaseline = () => {
rawServerResources = null;
+ deferredResourceIds.clear();
lastFullStateRecoveryAt = 0;
oversizedSnapshotObserved = false;
// A recovery request from a retired connection may still settle, but its
@@ -407,6 +414,71 @@ export function createWebSocketStore(url: string) {
}
};
+ const syncContainerCommands = (
+ resources: readonly Resource[],
+ changedResourceIds?: ReadonlySet<string>,
+ ) => {
+ const commandSyncResources = changedResourceIds
+ ? resources.filter((resource) => changedResourceIds.has(resource.id))
+ : resources;
+ commandSyncResources.forEach((resource: any) => {
+ if (resource?.type !== 'docker-host') return;
+ const platformData = asRecord(resource.platformData);
+ const dockerData = asRecord(platformData?.docker);
+ const command = dockerData?.command || platformData?.command;
+ if (!command || typeof command !== 'object') return;
+
+ const agentIds = new Set<string>([
+ resource.id,
+ asString(dockerData?.hostSourceId) || '',
+ asString(platformData?.hostSourceId) || '',
+ asString(resource?.discoveryTarget?.agentId) || '',
+ isAppContainerDiscoveryResourceType(resource?.discoveryTarget?.resourceType)
+ ? asString(resource?.discoveryTarget?.resourceId) || ''
+ : '',
+ ]);
+ agentIds.forEach((agentId) => {
+ if (agentId) {
+ syncWithAgentCommand(agentId, command as any);
+ }
+ });
+ });
+ };
+
+ const commitResources = (nextResources: Resource[], changedResourceIds?: ReadonlySet<string>) => {
+ logger.debug('[WebSocket] Updating resources', {
+ count: nextResources.length,
+ changedCount: changedResourceIds?.size ?? nextResources.length,
+ });
+ setState('resources', reconcile(nextResources, { key: 'id' }));
+ syncContainerCommands(nextResources, changedResourceIds);
+ };
+
+ const handleResourceVisibilityChange = () => {
+ if (
+ document.visibilityState !== 'visible' ||
+ rawServerResources === null ||
+ deferredResourceIds.size === 0
+ ) {
+ return;
+ }
+
+ const changedResourceIds = new Set(deferredResourceIds);
+ deferredResourceIds.clear();
+ const nextResources = mergeCanonicalResourceDeltaSnapshot(
+ rawServerResources,
+ state.resources,
+ changedResourceIds,
+ );
+ batch(() => commitResources(nextResources, changedResourceIds));
+ };
+
+ if (typeof document !== 'undefined') {
+ document.addEventListener('visibilitychange', handleResourceVisibilityChange, {
+ passive: true,
+ });
+ }
+
const beginConnection = () => {
const connectionId = ++nextConnectionId;
activeConnectionId = connectionId;
@@ -560,7 +632,9 @@ export function createWebSocketStore(url: string) {
}
// Handle unified resources
let nextResources: Resource[] | undefined;
+ let changedResourceIds: ReadonlySet<string> | undefined;
if (message.data.resources !== undefined) {
+ deferredResourceIds.clear();
if (Array.isArray(message.data.resources)) {
// Only a full payload actually delivered on this socket can
// establish its server-owned delta baseline. REST recovery is
@@ -591,14 +665,23 @@ export function createWebSocketStore(url: string) {
message.data.resourceDelta !== undefined
) {
if (rawServerResources) {
- rawServerResources = applyResourceStateDelta(
+ const appliedDelta = applyResourceStateDelta(
rawServerResources,
message.data.resourceDelta,
);
- nextResources = mergeCanonicalResourceSnapshot(
- structuredClone(rawServerResources) as Resource[],
- state.resources,
- );
+ rawServerResources = appliedDelta.resources;
+ changedResourceIds = appliedDelta.changedIds;
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
+ changedResourceIds.forEach((id) => deferredResourceIds.add(id));
+ } else {
+ changedResourceIds = new Set([...deferredResourceIds, ...changedResourceIds]);
+ deferredResourceIds.clear();
+ nextResources = mergeCanonicalResourceDeltaSnapshot(
+ rawServerResources,
+ state.resources,
+ changedResourceIds,
+ );
+ }
} else {
// A delta landed before any full snapshot (e.g. the initial
// payload was dropped as oversized). There is no baseline to
@@ -608,35 +691,7 @@ export function createWebSocketStore(url: string) {
}
}
if (nextResources !== undefined) {
- logger.debug('[WebSocket] Updating resources', {
- count: nextResources.length,
- types: [...new Set(nextResources.map((resource) => resource.type) || [])],
- });
- setState('resources', reconcile(nextResources, { key: 'id' }));
-
- // Sync container update states with docker host command status payloads.
- nextResources.forEach((resource: any) => {
- if (resource?.type !== 'docker-host') return;
- const platformData = asRecord(resource.platformData);
- const dockerData = asRecord(platformData?.docker);
- const command = dockerData?.command || platformData?.command;
- if (!command || typeof command !== 'object') return;
-
- const agentIds = new Set<string>([
- resource.id,
- asString(dockerData?.hostSourceId) || '',
- asString(platformData?.hostSourceId) || '',
- asString(resource?.discoveryTarget?.agentId) || '',
- isAppContainerDiscoveryResourceType(resource?.discoveryTarget?.resourceType)
- ? asString(resource?.discoveryTarget?.resourceId) || ''
- : '',
- ]);
- agentIds.forEach((agentId) => {
- if (agentId) {
- syncWithAgentCommand(agentId, command as any);
- }
- });
- });
+ commitResources(nextResources, changedResourceIds);
}
// Sync active alerts from state
if (message.data.activeAlerts !== undefined) {
@@ -1024,6 +1079,9 @@ export function createWebSocketStore(url: string) {
if (typeof window !== 'undefined') {
window.removeEventListener(ALERTS_DETECTION_EVENT, handleAlertsDetectionEvent);
}
+ if (typeof document !== 'undefined') {
+ document.removeEventListener('visibilitychange', handleResourceVisibilityChange);
+ }
if (ws) {
ws.close(1000, 'Component unmounting');
ws = null;
diff --git a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
index 3f017c4e59..1fba926680 100644
--- a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
+++ b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ mergeCanonicalResourceDeltaSnapshot,
mergeCanonicalResourceSnapshot,
nodeFromResource,
pbsInstanceFromResource,
@@ -1052,3 +1053,36 @@ describe('resourceStateAdapters unavailable memory contract', () => {
});
});
});
+
+describe('incremental canonical resource snapshots', () => {
+ it('preserves untouched row identity while refreshing changed resources', () => {
+ const unchanged = {
+ id: 'vm-unchanged',
+ type: 'vm',
+ name: 'vm-unchanged',
+ status: 'running',
+ cpu: { current: 10 },
+ } as Resource;
+ const changed = {
+ id: 'vm-changed',
+ type: 'vm',
+ name: 'vm-changed',
+ status: 'running',
+ cpu: { current: 20 },
+ } as Resource;
+ const incoming = [
+ structuredClone(unchanged),
+ { ...structuredClone(changed), cpu: { current: 75 } },
+ ];
+
+ const result = mergeCanonicalResourceDeltaSnapshot(
+ incoming,
+ [unchanged, changed],
+ new Set(['vm-changed']),
+ );
+
+ expect(result[0]).toBe(unchanged);
+ expect(result[1]).not.toBe(changed);
+ expect(result[1]?.cpu?.current).toBe(75);
+ });
+});
diff --git a/frontend-modern/src/utils/resourceStateAdapters.ts b/frontend-modern/src/utils/resourceStateAdapters.ts
index 4e98adc2d0..03a04a795b 100644
--- a/frontend-modern/src/utils/resourceStateAdapters.ts
+++ b/frontend-modern/src/utils/resourceStateAdapters.ts
@@ -587,12 +587,11 @@ const mergeRealtimeHostResources = (incoming: Resource, existing: Resource): Res
);
};
-const coalesceRealtimeResourceSnapshot = (resources: Resource[]): Resource[] => {
+const coalesceCanonicalRealtimeResourceSnapshot = (resources: Resource[]): Resource[] => {
const coalesced: Resource[] = [];
const indexByHostKey = new Map<string, number>();
- for (const rawResource of resources) {
- const resource = canonicalizeRealtimeResource(rawResource, { synthesizePlatformScopes: false });
+ for (const resource of resources) {
const hostKey = getHostResourceMergeKey(resource);
if (!hostKey) {
coalesced.push(resource);
@@ -618,6 +617,13 @@ const coalesceRealtimeResourceSnapshot = (resources: Resource[]): Resource[] =>
return coalesced;
};
+const coalesceRealtimeResourceSnapshot = (resources: Resource[]): Resource[] =>
+ coalesceCanonicalRealtimeResourceSnapshot(
+ resources.map((resource) =>
+ canonicalizeRealtimeResource(resource, { synthesizePlatformScopes: false }),
+ ),
+ );
+
const hasAvailabilityFacet = (
resource: Resource,
platformData?: Resource['platformData'],
@@ -830,6 +836,48 @@ export const mergeCanonicalResourceSnapshot = (
);
};
+// Incremental counterpart to mergeCanonicalResourceSnapshot. Server delta
+// application preserves the raw object identity of untouched resources, so
+// only changed rows and the small host-coalescing set need to be cloned and
+// canonicalized. Non-host resources outside the delta retain their exact display
+// objects, preventing an estate-wide reactive invalidation on every metrics
+// tick while keeping the full-snapshot compatibility semantics intact.
+export const mergeCanonicalResourceDeltaSnapshot = (
+ incoming: Resource[],
+ existing: Resource[],
+ changedIds: ReadonlySet<string>,
+): Resource[] => {
+ if (incoming.length === 0) {
+ return [];
+ }
+
+ const existingById = new Map(existing.map((resource) => [resource.id, resource] as const));
+ const prepared = incoming.map((resource) => {
+ const existingResource = existingById.get(resource.id);
+ const mustRefresh =
+ resource.type === 'agent' || changedIds.has(resource.id) || existingResource === undefined;
+ if (!mustRefresh) {
+ return existingResource;
+ }
+ return canonicalizeRealtimeResource(structuredClone(resource), {
+ synthesizePlatformScopes: false,
+ });
+ });
+
+ const coalesced = coalesceCanonicalRealtimeResourceSnapshot(prepared);
+ return coalesced.map((resource) => {
+ const existingResource = existingById.get(resource.id);
+ if (
+ resource.type !== 'agent' &&
+ !changedIds.has(resource.id) &&
+ existingResource !== undefined
+ ) {
+ return existingResource;
+ }
+ return mergeCanonicalResource(resource, existingResource);
+ });
+};
+
const buildMemory = (
metric: Resource['memory'],
fallback?: Record<string, unknown>,
diff --git a/internal/mock/fixture_graph.go b/internal/mock/fixture_graph.go
index fee6e1c4fe..71965f5b93 100644
--- a/internal/mock/fixture_graph.go
+++ b/internal/mock/fixture_graph.go
@@ -71,6 +71,53 @@ func (g *FixtureGraph) UpdateMetrics(cfg MockConfig, now time.Time) {
syncMetricFixtureRegistriesFromGraph(*g)
}
+// UpdateMetricCohort advances one bounded slice of the demo estate. The full
+// UpdateMetrics path remains the fixture-construction and explicit refresh
+// boundary; the long-running mock sampler uses cohorts so a large public demo
+// does not make every resource appear changed on every two-second tick.
+func (g *FixtureGraph) UpdateMetricCohort(
+ cfg MockConfig,
+ now time.Time,
+ cohortIndex int,
+ cohortCount int,
+) {
+ if g == nil {
+ return
+ }
+ if cohortCount <= 0 {
+ cohortCount = 1
+ }
+ cohortIndex %= cohortCount
+ if cohortIndex < 0 {
+ cohortIndex += cohortCount
+ }
+
+ setMockUpdateInterval(cfg.UpdateInterval)
+ selectedNodes := make(map[string]struct{}, (len(g.State.Nodes)+cohortCount-1)/cohortCount)
+ for index := range g.State.Nodes {
+ if index%cohortCount != cohortIndex {
+ continue
+ }
+ selectedNodes[g.State.Nodes[index].Name] = struct{}{}
+ }
+
+ includeSupplemental := cohortIndex == 0
+ updateFixtureStateMetricsSelectedAt(&g.State, cfg, now, fixtureMetricSelection{
+ proxmoxNodeNames: selectedNodes,
+ includeSupplemental: includeSupplemental,
+ uptimeStep: currentMockUpdateStepInt64() * int64(cohortCount),
+ })
+ if includeSupplemental {
+ // Provider-backed demo fixtures are much smaller than the PVE estate and
+ // refresh once per full cohort rotation. Their timestamps stay live
+ // without forcing every provider resource through every socket delta.
+ g.PlatformFixtures = rebasePlatformFixtures(g.PlatformFixtures, now)
+ g.AvailabilityFixtures = rebaseAvailabilityFixtures(g.AvailabilityFixtures, now)
+ g.DiscoveryFixtures = buildDiscoveryFixtures(g.State, now)
+ }
+ syncMetricFixtureRegistriesFromGraph(*g)
+}
+
func (g *FixtureGraph) UpdateAlertSnapshots(active []alerts.Alert, resolved []models.ResolvedAlert) {
if g == nil {
return
diff --git a/internal/mock/generator.go b/internal/mock/generator.go
index 21fa452dc6..a127c16fda 100644
--- a/internal/mock/generator.go
+++ b/internal/mock/generator.go
@@ -6085,64 +6085,99 @@ func updateFixtureStateMetrics(data *models.StateSnapshot, config MockConfig) {
}
func updateFixtureStateMetricsAt(data *models.StateSnapshot, config MockConfig, refreshNow time.Time) {
+ updateFixtureStateMetricsSelectedAt(data, config, refreshNow, fixtureMetricSelection{
+ includeSupplemental: true,
+ uptimeStep: currentMockUpdateStepInt64(),
+ })
+}
+
+type fixtureMetricSelection struct {
+ // A nil map means every Proxmox node. A non-nil map limits node-owned
+ // metrics, sightings, storage, and physical disks to the named cohort.
+ proxmoxNodeNames map[string]struct{}
+ includeSupplemental bool
+ uptimeStep int64
+}
+
+func (selection fixtureMetricSelection) includesProxmoxNode(nodeName string) bool {
+ if selection.proxmoxNodeNames == nil {
+ return true
+ }
+ _, ok := selection.proxmoxNodeNames[nodeName]
+ return ok
+}
+
+func updateFixtureStateMetricsSelectedAt(
+ data *models.StateSnapshot,
+ config MockConfig,
+ refreshNow time.Time,
+ selection fixtureMetricSelection,
+) {
if refreshNow.IsZero() {
refreshNow = time.Now()
}
+ if selection.uptimeStep <= 0 {
+ selection.uptimeStep = currentMockUpdateStepInt64()
+ }
- updateDockerHosts(data, config, refreshNow)
- updateKubernetesClusters(data, config, refreshNow)
- updateHosts(data, config, refreshNow)
- syncMockKubernetesNodeHosts(data)
-
- step := currentMockUpdateStepInt64()
-
- for i := range data.PBSInstances {
- inst := &data.PBSInstances[i]
- inst.Status = "online"
- inst.ConnectionHealth = "healthy"
- inst.LastSeen = refreshNow.Add(-time.Duration(randIntnSafe(12)) * time.Second)
- inst.Uptime += step
+ if selection.includeSupplemental {
+ updateDockerHosts(data, config, refreshNow)
+ updateKubernetesClusters(data, config, refreshNow)
+ updateHosts(data, config, refreshNow)
+ syncMockKubernetesNodeHosts(data)
+ }
- if data.ConnectionHealth != nil {
- data.ConnectionHealth[fmt.Sprintf("pbs-%s", inst.Name)] = true
- }
+ step := selection.uptimeStep
- if !config.RandomMetrics {
- continue
- }
+ if selection.includeSupplemental {
+ for i := range data.PBSInstances {
+ inst := &data.PBSInstances[i]
+ inst.Status = "online"
+ inst.ConnectionHealth = "healthy"
+ inst.LastSeen = refreshNow.Add(-time.Duration(randIntnSafe(12)) * time.Second)
+ inst.Uptime += step
- inst.CPU = SampleMetric("pbs", inst.ID, "cpu", refreshNow)
- inst.Memory = SampleMetric("pbs", inst.ID, "memory", refreshNow)
- if inst.MemoryTotal > 0 {
- inst.MemoryUsed = int64(float64(inst.MemoryTotal) * (inst.Memory / 100.0))
- if inst.MemoryUsed < 0 {
- inst.MemoryUsed = 0
+ if data.ConnectionHealth != nil {
+ data.ConnectionHealth[fmt.Sprintf("pbs-%s", inst.Name)] = true
}
- }
- for j := range inst.Datastores {
- datastore := &inst.Datastores[j]
- if datastore.Total <= 0 {
+ if !config.RandomMetrics {
continue
}
- datastore.Usage = SampleMetric("pbsDatastore", inst.ID+":"+datastore.Name, "usage", refreshNow)
- datastore.Used = int64(float64(datastore.Total) * (datastore.Usage / 100.0))
- if datastore.Used < 0 {
- datastore.Used = 0
+ inst.CPU = SampleMetric("pbs", inst.ID, "cpu", refreshNow)
+ inst.Memory = SampleMetric("pbs", inst.ID, "memory", refreshNow)
+ if inst.MemoryTotal > 0 {
+ inst.MemoryUsed = int64(float64(inst.MemoryTotal) * (inst.Memory / 100.0))
+ if inst.MemoryUsed < 0 {
+ inst.MemoryUsed = 0
+ }
}
- if datastore.Used > datastore.Total {
- datastore.Used = datastore.Total
+
+ for j := range inst.Datastores {
+ datastore := &inst.Datastores[j]
+ if datastore.Total <= 0 {
+ continue
+ }
+
+ datastore.Usage = SampleMetric("pbsDatastore", inst.ID+":"+datastore.Name, "usage", refreshNow)
+ datastore.Used = int64(float64(datastore.Total) * (datastore.Usage / 100.0))
+ if datastore.Used < 0 {
+ datastore.Used = 0
+ }
+ if datastore.Used > datastore.Total {
+ datastore.Used = datastore.Total
+ }
+ datastore.Free = datastore.Total - datastore.Used
+ datastore.Status = "available"
}
- datastore.Free = datastore.Total - datastore.Used
- datastore.Status = "available"
}
- }
- for i := range data.PMGInstances {
- inst := &data.PMGInstances[i]
- inst.LastSeen = refreshNow
- inst.LastUpdated = refreshNow
+ for i := range data.PMGInstances {
+ inst := &data.PMGInstances[i]
+ inst.LastSeen = refreshNow
+ inst.LastUpdated = refreshNow
+ }
}
// Sighting stamps simulate each poll delivering the PVE inventory; they
@@ -6161,9 +6196,15 @@ func updateFixtureStateMetricsAt(data *models.StateSnapshot, config MockConfig,
}
continue
}
+ if !selection.includesProxmoxNode(node.Name) {
+ continue
+ }
node.LastSeen = refreshNow
}
stampGuestSighting := func(nodeName string, lastSeen *time.Time) {
+ if !selection.includesProxmoxNode(nodeName) {
+ return
+ }
if _, offline := offlineNodes[nodeName]; offline {
if lastSeen.IsZero() {
*lastSeen = staleSighting
@@ -6190,6 +6231,10 @@ func updateFixtureStateMetricsAt(data *models.StateSnapshot, config MockConfig,
// Update node metrics
for i := range data.Nodes {
node := &data.Nodes[i]
+ if !selection.includesProxmoxNode(node.Name) ||
+ node.Status != "online" || node.ConnectionHealth == "offline" || node.Uptime <= 0 {
+ continue
+ }
node.CPU = SampleMetric("node", node.ID, "cpu", refreshNow) / 100.0
applyMemoryUsage(&node.Memory, SampleMetric("node", node.ID, "memory", refreshNow))
applyDiskUsage(&node.Disk, SampleMetric("node", node.ID, "disk", refreshNow))
@@ -6198,7 +6243,7 @@ func updateFixtureStateMetricsAt(data *models.StateSnapshot, config MockConfig,
// Update VM metrics
for i := range data.VMs {
vm := &data.VMs[i]
- if vm.Status != "running" {
+ if !selection.includesProxmoxNode(vm.Node) || vm.Status != "running" {
continue
}
@@ -6211,13 +6256,13 @@ func updateFixtureStateMetricsAt(data *models.StateSnapshot, config MockConfig,
vm.DiskWrite = SampleMetricInt("vm", vm.ID, "diskwrite", refreshNow)
// Update uptime
- vm.Uptime += 2 // Add 2 seconds per update
+ vm.Uptime += step
}
// Update container metrics
for i := range data.Containers {
ct := &data.Containers[i]
- if ct.Status != "running" {
+ if !selection.includesProxmoxNode(ct.Node) || ct.Status != "running" {
continue
}
@@ -6230,12 +6275,12 @@ func updateFixtureStateMetricsAt(data *models.StateSnapshot, config MockConfig,
ct.DiskWrite = SampleMetricInt("container", ct.ID, "diskwrite", refreshNow)
// Update uptime
- ct.Uptime += 2
+ ct.Uptime += step
}
for i := range data.Storage {
storage := &data.Storage[i]
- if storage.ID == "" || storage.Total <= 0 || storage.Status != "available" {
+ if !selection.includesProxmoxNode(storage.Node) || storage.ID == "" || storage.Total <= 0 || storage.Status != "available" {
continue
}
ApplyStorageUsage(storage, SampleMetric("storage", storage.ID, "usage", refreshNow))
@@ -6244,6 +6289,9 @@ func updateFixtureStateMetricsAt(data *models.StateSnapshot, config MockConfig,
// Update disk metrics.
for i := range data.PhysicalDisks {
disk := &data.PhysicalDisks[i]
+ if !selection.includesProxmoxNode(disk.Node) {
+ continue
+ }
resourceID := disk.Serial
if strings.TrimSpace(resourceID) == "" {
resourceID = disk.ID
@@ -6261,74 +6309,76 @@ func updateFixtureStateMetricsAt(data *models.StateSnapshot, config MockConfig,
}
}
- disk.LastChecked = time.Now()
+ disk.LastChecked = refreshNow
}
// Update PMG metrics with gentle fluctuations
- for i := range data.PMGInstances {
- inst := &data.PMGInstances[i]
- inst.LastSeen = refreshNow
- inst.LastUpdated = refreshNow
-
- if inst.MailStats != nil {
- inst.MailStats.CountTotal = fluctuateFloat(inst.MailStats.CountTotal, 0.05, 0, math.MaxFloat64)
- inst.MailStats.CountIn = fluctuateFloat(inst.MailStats.CountIn, 0.05, 0, math.MaxFloat64)
- inst.MailStats.CountOut = fluctuateFloat(inst.MailStats.CountOut, 0.05, 0, math.MaxFloat64)
- inst.MailStats.SpamIn = fluctuateFloat(inst.MailStats.SpamIn, 0.08, 0, math.MaxFloat64)
- inst.MailStats.SpamOut = fluctuateFloat(inst.MailStats.SpamOut, 0.08, 0, math.MaxFloat64)
- inst.MailStats.VirusIn = fluctuateFloat(inst.MailStats.VirusIn, 0.1, 0, math.MaxFloat64)
- inst.MailStats.VirusOut = fluctuateFloat(inst.MailStats.VirusOut, 0.1, 0, math.MaxFloat64)
- inst.MailStats.RBLRejects = fluctuateFloat(inst.MailStats.RBLRejects, 0.07, 0, math.MaxFloat64)
- inst.MailStats.PregreetRejects = fluctuateFloat(inst.MailStats.PregreetRejects, 0.07, 0, math.MaxFloat64)
- inst.MailStats.GreylistCount = fluctuateFloat(inst.MailStats.GreylistCount, 0.05, 0, math.MaxFloat64)
- inst.MailStats.AverageProcessTimeMs = fluctuateFloat(inst.MailStats.AverageProcessTimeMs, 0.05, 200, 2000)
- inst.MailStats.UpdatedAt = refreshNow
- }
-
- if len(inst.MailCount) > 0 {
- // Drop oldest point if we already have 24
- if len(inst.MailCount) >= 24 {
- inst.MailCount = inst.MailCount[1:]
- }
-
- base := 60 + rand.Float64()*30
- newPoint := models.PMGMailCountPoint{
- Timestamp: refreshNow,
- Count: base + rand.Float64()*15,
- CountIn: base*0.6 + rand.Float64()*10,
- CountOut: base*0.4 + rand.Float64()*8,
- SpamIn: base*0.1 + rand.Float64()*5,
- SpamOut: base*0.02 + rand.Float64()*1,
- VirusIn: rand.Float64() * 2,
- VirusOut: rand.Float64(),
- RBLRejects: rand.Float64() * 4,
- Pregreet: rand.Float64() * 3,
- BouncesIn: rand.Float64() * 3,
- BouncesOut: rand.Float64() * 2,
- Greylist: rand.Float64() * 5,
- Index: len(inst.MailCount),
- Timeframe: "hour",
- }
- inst.MailCount = append(inst.MailCount, newPoint)
- }
-
- if len(inst.SpamDistribution) > 0 {
- for j := range inst.SpamDistribution {
- inst.SpamDistribution[j].Count = fluctuateFloat(inst.SpamDistribution[j].Count, 0.05, 0, math.MaxFloat64)
- }
- }
-
- if inst.Quarantine != nil {
- inst.Quarantine.Spam = fluctuateInt(inst.Quarantine.Spam, 5, 0, 500)
- inst.Quarantine.Virus = fluctuateInt(inst.Quarantine.Virus, 2, 0, 200)
- inst.Quarantine.Attachment = fluctuateInt(inst.Quarantine.Attachment, 2, 0, 200)
- inst.Quarantine.Blacklisted = fluctuateInt(inst.Quarantine.Blacklisted, 1, 0, 100)
- }
-
- if len(inst.Nodes) > 0 {
- for j := range inst.Nodes {
- if inst.Nodes[j].Status == "online" {
- inst.Nodes[j].Uptime += currentMockUpdateStepInt64()
+ if selection.includeSupplemental {
+ for i := range data.PMGInstances {
+ inst := &data.PMGInstances[i]
+ inst.LastSeen = refreshNow
+ inst.LastUpdated = refreshNow
+
+ if inst.MailStats != nil {
+ inst.MailStats.CountTotal = fluctuateFloat(inst.MailStats.CountTotal, 0.05, 0, math.MaxFloat64)
+ inst.MailStats.CountIn = fluctuateFloat(inst.MailStats.CountIn, 0.05, 0, math.MaxFloat64)
+ inst.MailStats.CountOut = fluctuateFloat(inst.MailStats.CountOut, 0.05, 0, math.MaxFloat64)
+ inst.MailStats.SpamIn = fluctuateFloat(inst.MailStats.SpamIn, 0.08, 0, math.MaxFloat64)
+ inst.MailStats.SpamOut = fluctuateFloat(inst.MailStats.SpamOut, 0.08, 0, math.MaxFloat64)
+ inst.MailStats.VirusIn = fluctuateFloat(inst.MailStats.VirusIn, 0.1, 0, math.MaxFloat64)
+ inst.MailStats.VirusOut = fluctuateFloat(inst.MailStats.VirusOut, 0.1, 0, math.MaxFloat64)
+ inst.MailStats.RBLRejects = fluctuateFloat(inst.MailStats.RBLRejects, 0.07, 0, math.MaxFloat64)
+ inst.MailStats.PregreetRejects = fluctuateFloat(inst.MailStats.PregreetRejects, 0.07, 0, math.MaxFloat64)
+ inst.MailStats.GreylistCount = fluctuateFloat(inst.MailStats.GreylistCount, 0.05, 0, math.MaxFloat64)
+ inst.MailStats.AverageProcessTimeMs = fluctuateFloat(inst.MailStats.AverageProcessTimeMs, 0.05, 200, 2000)
+ inst.MailStats.UpdatedAt = refreshNow
+ }
+
+ if len(inst.MailCount) > 0 {
+ // Drop oldest point if we already have 24
+ if len(inst.MailCount) >= 24 {
+ inst.MailCount = inst.MailCount[1:]
+ }
+
+ base := 60 + rand.Float64()*30
+ newPoint := models.PMGMailCountPoint{
+ Timestamp: refreshNow,
+ Count: base + rand.Float64()*15,
+ CountIn: base*0.6 + rand.Float64()*10,
+ CountOut: base*0.4 + rand.Float64()*8,
+ SpamIn: base*0.1 + rand.Float64()*5,
+ SpamOut: base*0.02 + rand.Float64()*1,
+ VirusIn: rand.Float64() * 2,
+ VirusOut: rand.Float64(),
+ RBLRejects: rand.Float64() * 4,
+ Pregreet: rand.Float64() * 3,
+ BouncesIn: rand.Float64() * 3,
+ BouncesOut: rand.Float64() * 2,
+ Greylist: rand.Float64() * 5,
+ Index: len(inst.MailCount),
+ Timeframe: "hour",
+ }
+ inst.MailCount = append(inst.MailCount, newPoint)
+ }
+
+ if len(inst.SpamDistribution) > 0 {
+ for j := range inst.SpamDistribution {
+ inst.SpamDistribution[j].Count = fluctuateFloat(inst.SpamDistribution[j].Count, 0.05, 0, math.MaxFloat64)
+ }
+ }
+
+ if inst.Quarantine != nil {
+ inst.Quarantine.Spam = fluctuateInt(inst.Quarantine.Spam, 5, 0, 500)
+ inst.Quarantine.Virus = fluctuateInt(inst.Quarantine.Virus, 2, 0, 200)
+ inst.Quarantine.Attachment = fluctuateInt(inst.Quarantine.Attachment, 2, 0, 200)
+ inst.Quarantine.Blacklisted = fluctuateInt(inst.Quarantine.Blacklisted, 1, 0, 100)
+ }
+
+ if len(inst.Nodes) > 0 {
+ for j := range inst.Nodes {
+ if inst.Nodes[j].Status == "online" {
+ inst.Nodes[j].Uptime += currentMockUpdateStepInt64()
+ }
}
}
}
diff --git a/internal/mock/integration.go b/internal/mock/integration.go
index 585be04b2e..e26d4a5674 100644
--- a/internal/mock/integration.go
+++ b/internal/mock/integration.go
@@ -29,12 +29,19 @@ var (
// this; fixtureRevision stays structural-only so the expensive seeded
// trend history can be reused across monitor restarts within a process.
fixtureDataVersion atomic.Uint64
+ metricCohort atomic.Uint64
updateEveryNS atomic.Int64
updateTicker *time.Ticker
stopUpdatesCh chan struct{}
updateLoopWg sync.WaitGroup
)
+// Ten two-second cohorts keep every PVE node and its guests fresh within twenty
+// seconds while bounding each realtime delta to roughly one tenth of a large
+// demo estate. The WebSocket publisher may coalesce several sampler ticks into
+// one broadcast, so this leaves enough headroom for that union to remain small.
+const mockMetricCohortCount = 10
+
func init() {
loadedConfig := normalizeMockConfig(LoadMockConfig())
setMockUpdateInterval(loadedConfig.UpdateInterval)
@@ -177,6 +184,7 @@ func enableMockMode(config MockConfig, fromInit bool) {
mockGraph = buildFixtureGraph(config, now)
fixtureRevision.Add(1)
fixtureDataVersion.Add(1)
+ metricCohort.Store(0)
enabled.Store(true)
dataMu.Unlock()
startUpdateLoop()
@@ -277,7 +285,8 @@ func updateMetrics(cfg MockConfig) {
dataMu.Lock()
defer dataMu.Unlock()
- mockGraph.UpdateMetrics(cfg, time.Now())
+ cohort := int(metricCohort.Add(1)-1) % mockMetricCohortCount
+ mockGraph.UpdateMetricCohort(cfg, time.Now(), cohort, mockMetricCohortCount)
fixtureDataVersion.Add(1)
}
diff --git a/internal/mock/integration_coverage_test.go b/internal/mock/integration_coverage_test.go
index ada78ef1cd..dd7ec0a58b 100644
--- a/internal/mock/integration_coverage_test.go
+++ b/internal/mock/integration_coverage_test.go
@@ -35,6 +35,7 @@ func resetMockIntegrationState(t *testing.T) {
mockConfig = DefaultConfig
dataMu.Unlock()
setMockUpdateInterval(DefaultConfig.UpdateInterval)
+ metricCohort.Store(0)
enabled.Store(false)
for _, key := range mockEnvKeys {
@@ -48,6 +49,7 @@ func resetMockIntegrationState(t *testing.T) {
mockConfig = DefaultConfig
dataMu.Unlock()
setMockUpdateInterval(DefaultConfig.UpdateInterval)
+ metricCohort.Store(0)
enabled.Store(false)
for _, key := range mockEnvKeys {
_ = os.Unsetenv(key)
diff --git a/internal/mock/platform_fixtures_test.go b/internal/mock/platform_fixtures_test.go
index 98bc397835..ee94417f05 100644
--- a/internal/mock/platform_fixtures_test.go
+++ b/internal/mock/platform_fixtures_test.go
@@ -1,6 +1,8 @@
package mock
import (
+ "bytes"
+ "encoding/json"
"fmt"
"math"
"slices"
@@ -626,3 +628,121 @@ func TestCloneTrueNASFixtureSnapshotIsolatesPoolHealthEvidence(t *testing.T) {
t.Fatalf("clone mutated original pool evidence: %+v", original.Pools[0])
}
}
+
+func TestFixtureGraphMetricCohortsBoundPVEChurnAndCoverTheEstate(t *testing.T) {
+ cfg := DefaultConfig
+ cfg.NodeCount = 10
+ cfg.VMsPerNode = 2
+ cfg.LXCsPerNode = 2
+ cfg.DockerHostCount = 0
+ cfg.GenericHostCount = 0
+ cfg.K8sClusterCount = 0
+ cfg.RandomMetrics = true
+
+ base := time.Date(2026, 8, 23, 12, 0, 0, 0, time.UTC)
+ graph := buildFixtureGraph(cfg, base)
+ initialVMSeen := make(map[string]time.Time, len(graph.State.VMs))
+ initialContainerSeen := make(map[string]time.Time, len(graph.State.Containers))
+ for _, vm := range graph.State.VMs {
+ initialVMSeen[vm.ID] = vm.LastSeen
+ }
+ for _, container := range graph.State.Containers {
+ initialContainerSeen[container.ID] = container.LastSeen
+ }
+
+ graph.UpdateMetricCohort(cfg, base.Add(cfg.UpdateInterval), 0, 5)
+ selectedNodes := map[string]struct{}{
+ graph.State.Nodes[0].Name: {},
+ graph.State.Nodes[5].Name: {},
+ }
+ changedGuests := 0
+ for _, vm := range graph.State.VMs {
+ _, selected := selectedNodes[vm.Node]
+ changed := !vm.LastSeen.Equal(initialVMSeen[vm.ID])
+ if changed {
+ changedGuests++
+ }
+ if changed != selected {
+ t.Fatalf("VM %s on %s changed=%v, selected=%v", vm.ID, vm.Node, changed, selected)
+ }
+ }
+ for _, container := range graph.State.Containers {
+ _, selected := selectedNodes[container.Node]
+ changed := !container.LastSeen.Equal(initialContainerSeen[container.ID])
+ if changed {
+ changedGuests++
+ }
+ if changed != selected {
+ t.Fatalf("container %s on %s changed=%v, selected=%v", container.ID, container.Node, changed, selected)
+ }
+ }
+ if total := len(graph.State.VMs) + len(graph.State.Containers); changedGuests <= 0 || changedGuests >= total/2 {
+ t.Fatalf("expected a bounded non-empty guest cohort, changed=%d total=%d", changedGuests, total)
+ }
+
+ for cohort := 1; cohort < 5; cohort++ {
+ graph.UpdateMetricCohort(cfg, base.Add(time.Duration(cohort+1)*cfg.UpdateInterval), cohort, 5)
+ }
+ for _, vm := range graph.State.VMs {
+ if !vm.LastSeen.After(initialVMSeen[vm.ID]) {
+ t.Fatalf("VM %s was not refreshed during a full cohort rotation", vm.ID)
+ }
+ }
+ for _, container := range graph.State.Containers {
+ if !container.LastSeen.After(initialContainerSeen[container.ID]) {
+ t.Fatalf("container %s was not refreshed during a full cohort rotation", container.ID)
+ }
+ }
+}
+
+func TestFixtureGraphMetricCohortProducesSparseUnifiedResourceChanges(t *testing.T) {
+ cfg := DefaultConfig
+ cfg.NodeCount = 50
+ cfg.VMsPerNode = 10
+ cfg.LXCsPerNode = 8
+ cfg.RandomMetrics = true
+
+ base := time.Date(2026, 8, 23, 12, 0, 0, 0, time.UTC)
+ graph := buildFixtureGraph(cfg, base)
+ before, _ := graph.UnifiedResourceSnapshot()
+
+ graph.UpdateMetricCohort(cfg, base.Add(cfg.UpdateInterval), 0, mockMetricCohortCount)
+ after, _ := graph.UnifiedResourceSnapshot()
+
+ encodeBroadcastRelevant := func(resource unifiedresources.Resource) []byte {
+ encoded, err := json.Marshal(resource)
+ if err != nil {
+ t.Fatalf("marshal resource %s: %v", resource.ID, err)
+ }
+ var payload map[string]json.RawMessage
+ if err := json.Unmarshal(encoded, &payload); err != nil {
+ t.Fatalf("decode resource %s: %v", resource.ID, err)
+ }
+ // ResourceFrontend intentionally omits the registry's ingestion timestamp.
+ // It is regenerated whenever a throwaway mock registry is built and is not
+ // part of the WebSocket resource payload.
+ delete(payload, "updatedAt")
+ encoded, err = json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("re-marshal resource %s: %v", resource.ID, err)
+ }
+ return encoded
+ }
+
+ encodedBefore := make(map[string][]byte, len(before))
+ for _, resource := range before {
+ encodedBefore[resource.ID] = encodeBroadcastRelevant(resource)
+ }
+
+ changed := 0
+ for _, resource := range after {
+ encoded := encodeBroadcastRelevant(resource)
+ if !bytes.Equal(encodedBefore[resource.ID], encoded) {
+ changed++
+ }
+ }
+
+ if changed == 0 || changed >= len(after)/2 {
+ t.Fatalf("expected sparse unified resource churn, changed=%d total=%d", changed, len(after))
+ }
+}
diff --git a/internal/monitoring/mock_metrics_history.go b/internal/monitoring/mock_metrics_history.go
index 0d45f7ff7e..de6e9b5484 100644
--- a/internal/monitoring/mock_metrics_history.go
+++ b/internal/monitoring/mock_metrics_history.go
@@ -30,6 +30,12 @@ const (
// PULSE_MOCK_TRENDS_SEED_DURATION.
defaultMockSeedDuration = 48 * time.Hour
defaultMockSampleInterval = 1 * time.Minute // 1m for detailed recent charts
+ // Large demo estates use deterministic on-demand chart synthesis for most
+ // workloads. Eagerly materialising multi-day history for every guest would
+ // otherwise turn a 50-node showcase into millions of retained MetricPoints.
+ // Keep a representative cross-estate sample warm and let the existing chart
+ // fallback produce an equivalent canonical series for every other guest.
+ mockEagerHistoryPVEGuestLimit = 64
)
type mockMetricsSamplerConfig struct {
@@ -1717,6 +1723,49 @@ func trueNASDiskMetricsResourceID(disk truenas.Disk) string {
return resourceID
}
+func evenlySampleMockHistoryValues[T any](values []T, limit int) []T {
+ if limit <= 0 || len(values) == 0 {
+ return nil
+ }
+ if len(values) <= limit {
+ return values
+ }
+
+ selected := make([]T, 0, limit)
+ for index := 0; index < limit; index++ {
+ selected = append(selected, values[index*len(values)/limit])
+ }
+ return selected
+}
+
+// boundMockMetricsHistoryGraph limits only the eager PVE guest-history
+// materialisation. The canonical fixture graph and realtime inventory remain
+// complete, and chart reads for guests outside this sample use the existing
+// deterministic mock series fallback.
+func boundMockMetricsHistoryGraph(graph mock.FixtureGraph) mock.FixtureGraph {
+ vmCount := len(graph.State.VMs)
+ containerCount := len(graph.State.Containers)
+ total := vmCount + containerCount
+ if total <= mockEagerHistoryPVEGuestLimit {
+ return graph
+ }
+
+ vmLimit := mockEagerHistoryPVEGuestLimit * vmCount / total
+ containerLimit := mockEagerHistoryPVEGuestLimit - vmLimit
+ if vmCount > 0 && vmLimit == 0 {
+ vmLimit = 1
+ containerLimit--
+ }
+ if containerCount > 0 && containerLimit == 0 {
+ containerLimit = 1
+ vmLimit--
+ }
+
+ graph.State.VMs = evenlySampleMockHistoryValues(graph.State.VMs, vmLimit)
+ graph.State.Containers = evenlySampleMockHistoryValues(graph.State.Containers, containerLimit)
+ return graph
+}
+
func (m *Monitor) startMockMetricsSampler(ctx context.Context) {
if ctx == nil || m == nil {
log.Debug().Msg("mock metrics sampler: nil context or monitor")
@@ -1752,10 +1801,13 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {
graph, fixtureRevision := mock.CurrentFixtureGraphWithRevision()
state := graph.State
+ historyGraph := boundMockMetricsHistoryGraph(graph)
log.Info().
Int("nodes", len(state.Nodes)).
Int("vms", len(state.VMs)).
Int("containers", len(state.Containers)).
+ Int("eagerHistoryVMs", len(historyGraph.State.VMs)).
+ Int("eagerHistoryContainers", len(historyGraph.State.Containers)).
Dur("seedDuration", seedDuration).
Dur("sampleInterval", cfg.SampleInterval).
Msg("Mock metrics sampler: seeding historical data")
@@ -1774,7 +1826,7 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {
}
}
history, cacheHit := prepareMockMetricsHistory(
- graph,
+ historyGraph,
fixtureRevision,
time.Now(),
seedDuration,
@@ -1806,7 +1858,12 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {
if !mock.IsMockEnabled() {
continue
}
- recordMockStateToMetricsHistory(m.metricsHistory, storeSink, mock.CurrentFixtureGraph(), normalizeMockMetricTimestamp(time.Now(), cfg.SampleInterval))
+ recordMockStateToMetricsHistory(
+ m.metricsHistory,
+ storeSink,
+ boundMockMetricsHistoryGraph(mock.CurrentFixtureGraph()),
+ normalizeMockMetricTimestamp(time.Now(), cfg.SampleInterval),
+ )
m.invalidateMockChartCaches()
m.prewarmMockDashboardChartCaches()
}
diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.go
index af3dd00401..b6aa658600 100644
--- a/internal/monitoring/mock_metrics_history_test.go
+++ b/internal/monitoring/mock_metrics_history_test.go
@@ -1165,6 +1165,47 @@ func TestStartMockMetricsSampler_SeedsCanonicalMockResourceHistory(t *testing.T)
}
}
+func TestBoundMockMetricsHistoryGraphCapsLargeEstateGuestsAcrossTheEstate(t *testing.T) {
+ cfg := mock.DefaultConfig
+ cfg.NodeCount = 50
+ cfg.VMsPerNode = 10
+ cfg.LXCsPerNode = 8
+
+ previousEnabled := mock.IsMockEnabled()
+ previousConfig := mock.GetConfig()
+ t.Cleanup(func() {
+ mustSetMockEnabled(t, false)
+ mock.SetMockConfig(previousConfig)
+ if previousEnabled {
+ mustSetMockEnabled(t, true)
+ }
+ })
+ mustSetMockEnabled(t, false)
+ mock.SetMockConfig(cfg)
+ mustSetMockEnabled(t, true)
+
+ full := mock.CurrentFixtureGraph()
+ bounded := boundMockMetricsHistoryGraph(full)
+ boundedCount := len(bounded.State.VMs) + len(bounded.State.Containers)
+ if boundedCount != mockEagerHistoryPVEGuestLimit {
+ t.Fatalf("bounded eager guest count=%d, want=%d", boundedCount, mockEagerHistoryPVEGuestLimit)
+ }
+ if got := len(full.State.VMs) + len(full.State.Containers); got <= boundedCount {
+ t.Fatalf("large fixture guest count=%d, want more than bounded count=%d", got, boundedCount)
+ }
+
+ selectedNodes := make(map[string]struct{})
+ for _, vm := range bounded.State.VMs {
+ selectedNodes[vm.Node] = struct{}{}
+ }
+ for _, container := range bounded.State.Containers {
+ selectedNodes[container.Node] = struct{}{}
+ }
+ if len(selectedNodes) < cfg.NodeCount/2 {
+ t.Fatalf("bounded history sample covered only %d/%d nodes", len(selectedNodes), cfg.NodeCount)
+ }
+}
+
func keysDiskCharts(charts map[string]DiskChartEntry) []string {
keys := make([]string, 0, len(charts))
for key := range charts {
diff --git a/internal/monitoring/monitor_metrics.go b/internal/monitoring/monitor_metrics.go
index fe38bc744e..86f5a8026d 100644
--- a/internal/monitoring/monitor_metrics.go
+++ b/internal/monitoring/monitor_metrics.go
@@ -46,7 +46,13 @@ const (
mockChartPointTargetExtended = 64
)
-const mockDashboardWorkloadPrewarmDuration = time.Hour
+const (
+ mockDashboardWorkloadPrewarmDuration = time.Hour
+ // Prewarming every guest creates an estate-sized chart cache once per mock
+ // sampler tick. A first-viewport cohort removes cold-start latency while
+ // keeping the rest available through the same lazy deterministic path.
+ mockDashboardWorkloadPrewarmLimitPerType = 16
+)
var storageChartMetricTypes = []string{"usage", "used", "avail", "total"}
var storageSummaryChartMetricTypes = []string{"used", "avail"}
@@ -1248,12 +1254,30 @@ func mockWorkloadChartRequestsForReadState(
return requests
}
+func boundMockWorkloadChartPrewarmRequests(
+ requests mockWorkloadChartPrewarmRequests,
+) mockWorkloadChartPrewarmRequests {
+ bound := func(values []GuestChartRequest) []GuestChartRequest {
+ if len(values) <= mockDashboardWorkloadPrewarmLimitPerType {
+ return values
+ }
+ return values[:mockDashboardWorkloadPrewarmLimitPerType]
+ }
+ requests.vms = bound(requests.vms)
+ requests.containers = bound(requests.containers)
+ requests.pods = bound(requests.pods)
+ requests.dockerContainers = bound(requests.dockerContainers)
+ return requests
+}
+
func (m *Monitor) prewarmMockWorkloadChartCaches(duration time.Duration) {
if m == nil || duration <= 0 {
return
}
- requests := mockWorkloadChartRequestsForReadState(m.GetUnifiedReadStateOrSnapshot())
+ requests := boundMockWorkloadChartPrewarmRequests(
+ mockWorkloadChartRequestsForReadState(m.GetUnifiedReadStateOrSnapshot()),
+ )
if len(requests.vms) > 0 {
_ = m.GetGuestMetricsForChartBatch("vm", requests.vms, duration)
}
diff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.go
index 609c2c64d0..29e82d0f22 100644
--- a/internal/monitoring/monitor_metrics_slo_test.go
+++ b/internal/monitoring/monitor_metrics_slo_test.go
@@ -122,6 +122,32 @@ func TestStartMockMetricsSampler_PrewarmsDefaultWorkloadChartCaches(t *testing.T
assertPrewarmed("dockerContainer", requests.dockerContainers)
}
+func TestBoundMockWorkloadChartPrewarmRequestsCapsEveryWorkloadFamily(t *testing.T) {
+ makeRequests := func(count int) []GuestChartRequest {
+ requests := make([]GuestChartRequest, count)
+ for index := range requests {
+ id := fmt.Sprintf("guest-%d", index)
+ requests[index] = GuestChartRequest{InMemoryKey: id, SQLResourceID: id}
+ }
+ return requests
+ }
+
+ bounded := boundMockWorkloadChartPrewarmRequests(mockWorkloadChartPrewarmRequests{
+ vms: makeRequests(100),
+ containers: makeRequests(90),
+ pods: makeRequests(80),
+ dockerContainers: makeRequests(70),
+ })
+ for family, requests := range map[string][]GuestChartRequest{
+ "vms": bounded.vms, "containers": bounded.containers,
+ "pods": bounded.pods, "dockerContainers": bounded.dockerContainers,
+ } {
+ if len(requests) != mockDashboardWorkloadPrewarmLimitPerType {
+ t.Fatalf("%s prewarm requests=%d, want=%d", family, len(requests), mockDashboardWorkloadPrewarmLimitPerType)
+ }
+ }
+}
+
func newChartBatchSLOMonitor(t *testing.T) *Monitor {
t.Helper()
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 6582c0c484..9f3345a43f 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -3980,15 +3980,20 @@ class SubsystemLookupTest(unittest.TestCase):
self.assertEqual(result["unowned_runtime_files"], [])
self.assertEqual(
{item["subsystem"] for item in result["impacted_subsystems"]},
- {"monitoring"},
+ {"monitoring", "performance-and-scalability"},
)
for file_entry in result["files"]:
self.assertEqual(file_entry["classification"], "runtime")
+ expected_subsystems = {"monitoring"}
+ if file_entry["path"] == "internal/mock/fixture_graph.go":
+ expected_subsystems.add("performance-and-scalability")
self.assertEqual(
{match["subsystem"] for match in file_entry["matches"]},
- {"monitoring"},
+ expected_subsystems,
+ )
+ match = next(
+ match for match in file_entry["matches"] if match["subsystem"] == "monitoring"
)
- match = file_entry["matches"][0]
self.assertEqual(
match["contract"],
"docs/release-control/v6/internal/subsystems/monitoring.md",
@@ -4005,11 +4010,23 @@ class SubsystemLookupTest(unittest.TestCase):
"internal/mock/canonical_api_guardrails_test.go",
"internal/mock/demo_scenarios_test.go",
"internal/mock/generator_test.go",
+ "internal/mock/integration_coverage_test.go",
"internal/mock/platform_fixtures_test.go",
"internal/mock/recovery_points_test.go",
"tests/integration/tests/43-platform-mock-runtime.spec.ts",
],
)
+ if file_entry["path"] == "internal/mock/fixture_graph.go":
+ performance_match = next(
+ match
+ for match in file_entry["matches"]
+ if match["subsystem"] == "performance-and-scalability"
+ )
+ self.assertEqual(performance_match["lane_context"]["lane_id"], "L10")
+ self.assertEqual(
+ performance_match["verification_requirement"]["id"],
+ "large-estate-realtime-state",
+ )
def test_lookup_paths_normalizes_absolute_repo_paths(self) -> None:
absolute = str(Path(REPO_ROOT, "internal/api/resources.go"))