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.

Add rolling-window metric alert evaluation

rcourtman4b9abd4eca5a
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 79076d6b67..e331fee70b 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -209,6 +209,23 @@ emitting a forecast recovery plus a second capacity alert. The same contract
applies to Proxmox, Ceph, TrueNAS pools/datasets, and vSphere datastores through
their existing platform thresholds and disable policy.
+Rolling metric evaluation is alert policy over monitoring-owned history, not a
+second incident family. `metricEvaluationWindows` stores seconds by canonical
+resource type and metric, with an explicit zero meaning current-value
+evaluation and platform-specific entries inheriting the `all` rule. CPU seeds a
+five-minute default; only CPU and burst-prone disk/network rate metrics may use
+rolling averages, while memory, capacity, and temperature remain instantaneous
+evidence boundaries. A window requires at least three samples, at least 80%
+temporal coverage, and no gap larger than the bounded cadence allowance. Weak,
+stale, or unavailable history is unknown: it cannot open or recover an
+incident, and an existing incident retains its last trusted value. Ready
+windows use time-weighted averaging so polling jitter cannot bias the result.
+The evaluated value drives trigger, hysteresis, severity, delay, and recovery;
+the current value, sample count, coverage, and window remain alert metadata and
+operator-visible message evidence. Window changes never change the canonical
+`metric-threshold:<metric>` identity, so start time, acknowledgement, history,
+timeline, escalation, and recovery stay one occurrence.
+
Active-alert restore is opt-out at construction. `NewManagerWithDataDir` accepts
`ManagerOption` values, and `WithoutPersistedAlertRestore` starts the manager
with an empty active-alert set instead of reading `active-alerts.json`. Mock
@@ -269,6 +286,7 @@ default construction path still restores.
46. `internal/alerts/pbs.go`
47. `internal/alerts/storage.go`
47a. `internal/alerts/capacity_forecast.go`
+47b. `internal/alerts/windowed_metric.go`
48. `internal/alerts/node.go`
49. `internal/alerts/host.go`
50. `internal/alerts/backup_snapshot.go`
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 5a2efdc11f..9cb55650fb 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -507,6 +507,16 @@ and the warning/critical pair reconciliation in the thresholds helpers adjusts
the untouched field on a conflicting single-field edit. Primitives must not
absorb those persistence or validation rules into shared form/table chrome
(#1126).
+
+The alerts-owned threshold surface also owns rolling metric evaluation
+configuration. `ThresholdsTab` presents the understandable policy (current
+value or a named rolling duration) rather than a query language, with one
+global CPU rule and sparse platform overrides that visibly inherit it. The
+configuration snapshot and payload models must round-trip explicit zero and
+resource-specific maps without flattening inheritance. Copy must explain that
+incomplete history holds incident state instead of firing or recovering, and
+the control must remain usable at desktop and narrow viewports through shared
+`Card`, label, and native-select primitives.
PlatformTableToolbar may accept compact consumer-owned context through its
shared leading-control rail when the context is actionable for the inventory
immediately below it. Consumers must use that extension point for local
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index b942763508..eb03af73eb 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -432,6 +432,16 @@ their source-native storage history IDs. Monitoring supplies evidence only and
must not choose forecast horizons, severity, hysteresis, notification routing,
or lifecycle identity.
+Rolling alert evaluation uses the same monitoring-owned canonical metric
+identity and durable history as charts. `internal/monitoring/metric_window_provider.go`
+resolves the unified resource metrics target, reads the fresh in-memory tail,
+and falls back to the SQLite metrics store when that tail lacks the requested
+coverage. Persistent fallbacks are briefly cached to bound restart-time query
+load, merged by timestamp, and returned as observations only; alert policy owns
+averaging, readiness, hysteresis, and lifecycle decisions. Missing target,
+query failure, shallow history, or gapped history must remain unknown at the
+alerts boundary rather than being replaced by a synthetic healthy value.
+
Monitoring ingest keeps mock mode hermetic. The unified read path already
substitutes the mock snapshot wholesale, so anything that runs after that
substitution has to be suppressed explicitly rather than assumed hidden. Server
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index 91072ee1a6..534cd0dec8 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,36 +1,38 @@
{
"version": 1,
- "base_sha": "b0c1eca4cdace3cb798a77b2fa0c01a220f76981",
- "verified_at": "2026-08-27T19:35:10Z",
+ "base_sha": "478a39bdec4b3a20f309490a564bcaca8e423a34",
+ "verified_at": "2026-08-27T20:06:10Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/components/Infrastructure/AvailabilityProbeStatusCard.tsx",
- "frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx",
- "frontend-modern/src/components/Workloads/AvailabilityProbeSuggestionCard.tsx",
- "frontend-modern/src/features/docker/DockerHostDrawerOverview.tsx"
+ "frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx",
+ "frontend-modern/src/features/alerts/alertsConfigurationModel.ts",
+ "frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx",
+ "frontend-modern/src/features/alerts/thresholds/types.ts",
+ "frontend-modern/src/features/alerts/useAlertsConfigurationSnapshotState.ts",
+ "frontend-modern/src/types/alerts.ts"
],
"content_sha256": {
- "frontend-modern/src/components/Infrastructure/AvailabilityProbeStatusCard.tsx": "2d991718c178866ba5bd7d1b89e7a1a9bec6fcd30133bc2fd549aa2fd3ccf4e5",
- "frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx": "ac68e2e7f5d954ca5bd23b44f347817ce9a39414ab493d22ad52340ceb3296e2",
- "frontend-modern/src/components/Workloads/AvailabilityProbeSuggestionCard.tsx": "a8c549b1284befee652c9ecc79c3c449602d1a102f3867acb81f4a5c9f5fd042",
- "frontend-modern/src/features/docker/DockerHostDrawerOverview.tsx": "ab63fba8e1a06cb5951e0d3dc637d92ef371f2b5db5da2dfb80408cd477c0ea5"
+ "frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx": "6e52a34562926185ae32483add8e303b0a8fae5c3d5315f5b87865f960f54929",
+ "frontend-modern/src/features/alerts/alertsConfigurationModel.ts": "adb7c745b8fdee148edf56beea8f1b7a02f30e6495d6fc6d7e2eff36f228d10c",
+ "frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx": "00e8e50cd3892262c9195129b28fc834d4dbc87adb37aeb6f652957869367ad8",
+ "frontend-modern/src/features/alerts/thresholds/types.ts": "d87f4509648798b55c01ac9e701faa2b9a96de7e25bf6453bfc10fbc5176e1f3",
+ "frontend-modern/src/features/alerts/useAlertsConfigurationSnapshotState.ts": "34fff486ecf33457f42cefeb0b04bbd4b3e04dad24faca8bd99bfd86a75e70f7",
+ "frontend-modern/src/types/alerts.ts": "ef4e8322a38e8443393f762ee4ba6c512ffd4ff18b3f32ff5fd64f5d3754585d"
},
- "routes": ["/standalone/availability", "/proxmox/backups/date", "/docker/overview"],
+ "routes": ["/alerts/thresholds/proxmox"],
"viewports": [
- { "width": 1920, "height": 800 },
+ { "width": 1440, "height": 900 },
{ "width": 390, "height": 844 }
],
"states": [
- "Solar inverter web panel expanded with availability facts visible",
- "backup-vault expanded with Platform details and PBS service facts visible",
- "auth-service-01 expanded on Manage with Container updates visible"
+ "CPU evaluation window loaded with the global five-minute rule and inherited platform overrides",
+ "mobile platform overrides collapsed and expanded",
+ "global rule changed to one minute with inherited labels updating immediately"
],
"interactions": [
- "expanded the Solar inverter web panel and confirmed desktop availability values use an adjacent fixed label track",
- "confirmed availability facts retain condensed right-aligned values and clean wrapping at 390px",
- "expanded backup-vault, opened Platform details, and revealed the PBS service section",
- "confirmed PBS service facts use adjacent desktop values and retain compact mobile alignment",
- "expanded auth-service-01, selected Manage, and confirmed Container updates facts use adjacent desktop values",
- "confirmed Docker management facts retain condensed right alignment at 390px"
+ "confirmed the desktop three-column profile grid is readable without displacing threshold navigation",
+ "confirmed the narrow layout keeps the global rule visible and collapses platform overrides",
+ "expanded mobile platform overrides and confirmed every selector remains accessible",
+ "changed the global CPU window to one minute and confirmed inherited labels and unsaved-change state update"
]
}
diff --git a/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx b/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx
index 4364ef6c04..a662485d11 100644
--- a/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx
+++ b/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx
@@ -159,6 +159,8 @@ export function AlertsConfigurationSurface(props: AlertsConfigurationSurfaceProp
timeThresholds={state.timeThresholds}
metricTimeThresholds={state.metricTimeThresholds}
setMetricTimeThresholds={state.setMetricTimeThresholds}
+ metricEvaluationWindows={state.metricEvaluationWindows}
+ setMetricEvaluationWindows={state.setMetricEvaluationWindows}
backupDefaults={state.backupDefaults}
setBackupDefaults={state.setBackupDefaults}
snapshotDefaults={state.snapshotDefaults}
diff --git a/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.snapshot.test.ts b/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.snapshot.test.ts
index 7ade851d69..98e5f5a656 100644
--- a/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.snapshot.test.ts
+++ b/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.snapshot.test.ts
@@ -83,11 +83,12 @@ describe('readAlertsConfigurationSnapshot — absent optional sections', () => {
expect(snapshot.pmgThresholds.quarantineGrowthCritMin).toBe(500);
});
- it('keeps default timeThresholds / metricTimeThresholds', () => {
+ it('keeps default delays and the five-minute CPU evaluation window', () => {
expect(snapshot.timeThresholds.guest).toBe(5);
expect(snapshot.timeThresholds.pod).toBe(5);
expect(snapshot.timeThresholds['vmware-network']).toBe(5);
expect(snapshot.metricTimeThresholds).toEqual({});
+ expect(snapshot.metricEvaluationWindows).toEqual({ all: { cpu: 300 } });
});
it('keeps default schedule sections when schedule is absent', () => {
@@ -722,6 +723,20 @@ describe('readAlertsConfigurationSnapshot — metricTimeThresholds', () => {
});
});
+describe('readAlertsConfigurationSnapshot — metricEvaluationWindows', () => {
+ it('normalizes keys and preserves explicit current-value overrides', () => {
+ const snapshot = readAlertsConfigurationSnapshot(
+ cfg({
+ metricEvaluationWindows: {
+ ALL: { CPU: 300 },
+ VM: { CPU: 0 },
+ },
+ }),
+ );
+ expect(snapshot.metricEvaluationWindows).toEqual({ all: { cpu: 300 }, vm: { cpu: 0 } });
+ });
+});
+
// ---------------------------------------------------------------------------
// backupDefaults fallbacks
// ---------------------------------------------------------------------------
diff --git a/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.test.ts b/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.test.ts
index 9f99bc8924..71bb7bac74 100644
--- a/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.test.ts
+++ b/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.test.ts
@@ -118,6 +118,10 @@ describe('alertsConfigurationModel', () => {
snapshot.metricTimeThresholds = {
Guest: { CPU: 17 },
} as Record<string, Record<string, number>>;
+ snapshot.metricEvaluationWindows = {
+ ALL: { CPU: 300 },
+ VM: { CPU: 0 },
+ } as Record<string, Record<string, number>>;
snapshot.scheduleCooldown = {
enabled: true,
minutes: 47,
@@ -172,6 +176,10 @@ describe('alertsConfigurationModel', () => {
expect(result.alertConfig?.dockerIgnoredContainerPrefixes).toEqual(['web']);
expect(result.alertConfig?.guestTagWhitelist).toEqual(['prod']);
expect(result.alertConfig?.metricTimeThresholds).toEqual({ guest: { cpu: 17 } });
+ expect(result.alertConfig?.metricEvaluationWindows).toEqual({
+ all: { cpu: 300 },
+ vm: { cpu: 0 },
+ });
expect(result.alertConfig?.schedule?.cooldown).toBe(47);
expect(result.alertConfig?.schedule?.initialNotify).toBe('email');
expect(result.alertConfig?.schedule?.maxAlertsHour).toBe(10);
diff --git a/frontend-modern/src/features/alerts/alertsConfigurationModel.ts b/frontend-modern/src/features/alerts/alertsConfigurationModel.ts
index 5f7b94ffe8..dd99913281 100644
--- a/frontend-modern/src/features/alerts/alertsConfigurationModel.ts
+++ b/frontend-modern/src/features/alerts/alertsConfigurationModel.ts
@@ -113,6 +113,7 @@ export interface AlertsConfigurationSnapshot {
'vmware-network': number;
};
metricTimeThresholds: Record<string, Record<string, number>>;
+ metricEvaluationWindows: Record<string, Record<string, number>>;
snapshotDefaults: SnapshotAlertConfig;
pmgThresholds: {
queueTotalWarning: number;
@@ -288,6 +289,7 @@ export function createDefaultAlertsConfigurationSnapshot(): AlertsConfigurationS
'vmware-network': DEFAULT_DELAY_SECONDS,
},
metricTimeThresholds: {},
+ metricEvaluationWindows: { all: { cpu: 300 } },
snapshotDefaults: { ...FACTORY_SNAPSHOT_DEFAULTS },
pmgThresholds: {
queueTotalWarning: 500,
@@ -543,6 +545,9 @@ export function readAlertsConfigurationSnapshot(config: AlertConfig): AlertsConf
if (config.metricTimeThresholds) {
snapshot.metricTimeThresholds = normalizeMetricDelayMap(config.metricTimeThresholds);
}
+ if (config.metricEvaluationWindows) {
+ snapshot.metricEvaluationWindows = normalizeMetricDelayMap(config.metricEvaluationWindows);
+ }
if (config.backupDefaults) {
const normalizedPair = normalizeWarningCriticalPair(
@@ -878,6 +883,7 @@ export function buildAlertsConfigurationPayload({
hysteresisMargin: 5.0,
timeThresholds: { ...snapshot.timeThresholds },
metricTimeThresholds: normalizeMetricDelayMap(snapshot.metricTimeThresholds),
+ metricEvaluationWindows: normalizeMetricDelayMap(snapshot.metricEvaluationWindows),
snapshotDefaults: {
enabled: snapshot.snapshotDefaults.enabled,
warningDays: normalizedSnapshotPair.warning,
diff --git a/frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx b/frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx
index 5e40292543..9bc16c364d 100644
--- a/frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx
+++ b/frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx
@@ -1,4 +1,5 @@
-import { createSignal } from 'solid-js';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+import { Card } from '@/components/shared/Card';
import { ThresholdsTable } from '@/components/Alerts/ThresholdsTable';
import {
AlertIntentPolicyPanel,
@@ -22,12 +23,115 @@ export function ThresholdsTab(props: ThresholdsTabProps) {
});
};
+ const evaluationProfiles = [
+ { key: 'all', label: 'All resources' },
+ { key: 'vm', label: 'Virtual machines' },
+ { key: 'app-container', label: 'Application containers' },
+ { key: 'node', label: 'Infrastructure nodes' },
+ { key: 'agent', label: 'Pulse agents' },
+ { key: 'k8s-node', label: 'Kubernetes nodes' },
+ { key: 'truenas-system', label: 'TrueNAS systems' },
+ { key: 'vmware-host', label: 'VMware hosts' },
+ { key: 'pbs', label: 'Proxmox Backup Servers' },
+ ] as const;
+ const globalCPUWindow = createMemo(() => props.metricEvaluationWindows?.().all?.cpu ?? 300);
+ const evaluationLabel = (seconds: number) => {
+ if (seconds === 0) return 'Current value';
+ if (seconds < 60) return `${seconds} seconds`;
+ return `${seconds / 60} minute${seconds === 60 ? '' : 's'}`;
+ };
+ const updateCPUWindow = (profile: string, rawValue: string) => {
+ if (!props.setMetricEvaluationWindows) return;
+ props.setMetricEvaluationWindows((previous) => {
+ const next = structuredClone(previous);
+ if (rawValue === 'inherit') {
+ if (next[profile]) {
+ delete next[profile].cpu;
+ if (Object.keys(next[profile]).length === 0) delete next[profile];
+ }
+ return next;
+ }
+ next[profile] = { ...(next[profile] ?? {}), cpu: Number(rawValue) };
+ return next;
+ });
+ props.setHasUnsavedChanges(true);
+ };
+ const evaluationProfileControl = (profile: (typeof evaluationProfiles)[number]) => {
+ const configured = () => props.metricEvaluationWindows?.()[profile.key]?.cpu;
+ return (
+ <label class="block rounded-lg border border-gray-200 p-3 dark:border-gray-700">
+ <span class="block text-xs font-medium text-gray-700 dark:text-gray-300">
+ {profile.label}
+ </span>
+ <select
+ aria-label={`${profile.label} CPU evaluation window`}
+ class="mt-2 w-full rounded-md border border-gray-300 bg-white px-2 py-1.5 text-sm text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
+ value={
+ profile.key === 'all'
+ ? String(configured() ?? 300)
+ : configured() === undefined
+ ? 'inherit'
+ : String(configured())
+ }
+ onInput={(event) => updateCPUWindow(profile.key, event.currentTarget.value)}
+ >
+ <Show when={profile.key !== 'all'}>
+ <option value="inherit">Inherit ({evaluationLabel(globalCPUWindow())})</option>
+ </Show>
+ <option value="0">Current value</option>
+ <option value="60">1 minute average</option>
+ <option value="300">5 minute average</option>
+ <option value="900">15 minute average</option>
+ </select>
+ </label>
+ );
+ };
+
return (
<div class="space-y-4">
<AlertIntentPolicyPanel
resources={props.allResources}
selectionTarget={intentSelectionTarget()}
/>
+ <Show when={props.metricEvaluationWindows && props.setMetricEvaluationWindows}>
+ <Card padding="md">
+ <div class="space-y-4">
+ <div>
+ <h3 class="text-sm font-semibold text-gray-900 dark:text-gray-100">
+ CPU evaluation window
+ </h3>
+ <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
+ Pulse averages CPU over time before applying trigger and recovery thresholds. This
+ filters harmless bursts without delaying a sustained incident or splitting its
+ timeline.
+ </p>
+ </div>
+ <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ <For each={evaluationProfiles}>
+ {(profile) => (
+ <div class={profile.key === 'all' ? 'block' : 'hidden sm:block'}>
+ {evaluationProfileControl(profile)}
+ </div>
+ )}
+ </For>
+ </div>
+ <details class="rounded-lg border border-gray-200 p-3 sm:hidden dark:border-gray-700">
+ <summary class="cursor-pointer text-sm font-medium text-gray-800 dark:text-gray-200">
+ Platform overrides
+ </summary>
+ <div class="mt-3 space-y-3">
+ <For each={evaluationProfiles.slice(1)}>
+ {(profile) => evaluationProfileControl(profile)}
+ </For>
+ </div>
+ </details>
+ <p class="text-xs text-gray-500 dark:text-gray-400">
+ A rolling rule waits for enough recent, gap-free samples. If history is incomplete,
+ Pulse holds the existing incident state instead of firing or resolving on weak data.
+ </p>
+ </div>
+ </Card>
+ </Show>
<ThresholdsTable
onConfigureResourceIntent={configureResourceIntent}
overrides={props.overrides}
diff --git a/frontend-modern/src/features/alerts/thresholds/types.ts b/frontend-modern/src/features/alerts/thresholds/types.ts
index b3306aa9b6..338c601d5c 100644
--- a/frontend-modern/src/features/alerts/thresholds/types.ts
+++ b/frontend-modern/src/features/alerts/thresholds/types.ts
@@ -260,6 +260,12 @@ export interface ThresholdsTableProps {
| Record<string, Record<string, number>>
| ((prev: Record<string, Record<string, number>>) => Record<string, Record<string, number>>),
) => void;
+ metricEvaluationWindows?: () => Record<string, Record<string, number>>;
+ setMetricEvaluationWindows?: (
+ value:
+ | Record<string, Record<string, number>>
+ | ((prev: Record<string, Record<string, number>>) => Record<string, Record<string, number>>),
+ ) => void;
snapshotDefaults: () => SnapshotAlertConfig;
setSnapshotDefaults: (
value: SnapshotAlertConfig | ((prev: SnapshotAlertConfig) => SnapshotAlertConfig),
diff --git a/frontend-modern/src/features/alerts/useAlertsConfigurationSnapshotState.ts b/frontend-modern/src/features/alerts/useAlertsConfigurationSnapshotState.ts
index 715d2cc555..865b30e6a7 100644
--- a/frontend-modern/src/features/alerts/useAlertsConfigurationSnapshotState.ts
+++ b/frontend-modern/src/features/alerts/useAlertsConfigurationSnapshotState.ts
@@ -122,6 +122,9 @@ export function useAlertsConfigurationSnapshotState(
const [metricTimeThresholds, setMetricTimeThresholds] = createSignal<
Record<string, Record<string, number>>
>(defaultSnapshot.metricTimeThresholds);
+ const [metricEvaluationWindows, setMetricEvaluationWindows] = createSignal<
+ Record<string, Record<string, number>>
+ >(defaultSnapshot.metricEvaluationWindows);
const [snapshotDefaults, setSnapshotDefaults] = createSignal<SnapshotAlertConfig>(
defaultSnapshot.snapshotDefaults,
);
@@ -211,6 +214,7 @@ export function useAlertsConfigurationSnapshotState(
});
setTimeThresholds({ ...snapshot.timeThresholds });
setMetricTimeThresholds(structuredClone(snapshot.metricTimeThresholds));
+ setMetricEvaluationWindows(structuredClone(snapshot.metricEvaluationWindows));
setSnapshotDefaults({ ...snapshot.snapshotDefaults });
setPMGThresholds({ ...snapshot.pmgThresholds });
setDisableAllNodes(snapshot.disableAllNodes);
@@ -279,6 +283,7 @@ export function useAlertsConfigurationSnapshotState(
},
timeThresholds: { ...timeThresholds() },
metricTimeThresholds: structuredClone(metricTimeThresholds()),
+ metricEvaluationWindows: structuredClone(metricEvaluationWindows()),
snapshotDefaults: { ...snapshotDefaults() },
pmgThresholds: { ...pmgThresholds() },
disableAllNodes: disableAllNodes(),
@@ -420,6 +425,8 @@ export function useAlertsConfigurationSnapshotState(
setTimeThresholds,
metricTimeThresholds,
setMetricTimeThresholds,
+ metricEvaluationWindows,
+ setMetricEvaluationWindows,
snapshotDefaults,
setSnapshotDefaults,
pmgThresholds,
diff --git a/frontend-modern/src/types/alerts.ts b/frontend-modern/src/types/alerts.ts
index 2cb7b1579a..87ec3d257e 100644
--- a/frontend-modern/src/types/alerts.ts
+++ b/frontend-modern/src/types/alerts.ts
@@ -178,6 +178,7 @@ export interface AlertConfig {
'vmware-network'?: number;
};
metricTimeThresholds?: Record<string, Record<string, number>>;
+ metricEvaluationWindows?: Record<string, Record<string, number>>;
aggregation?: {
enabled: boolean;
timeWindow: number;
diff --git a/internal/alerts/canonical_metric.go b/internal/alerts/canonical_metric.go
index e8422355c7..d4befbc792 100644
--- a/internal/alerts/canonical_metric.go
+++ b/internal/alerts/canonical_metric.go
@@ -27,6 +27,12 @@ func metricClearThreshold(spec *alertspecs.MetricThresholdSpec, threshold *Hyste
func resourceTypeLabel(resourceType string) string {
switch strings.TrimSpace(resourceType) {
+ case "vm":
+ return "VM"
+ case "system-container":
+ return "System container"
+ case "app-container", "oci-container":
+ return "Application container"
case "agent-disk":
return "Disk"
case "agent":
@@ -97,6 +103,12 @@ func (m *Manager) evaluateCanonicalMetricAlert(spec alertspecs.ResourceAlertSpec
}
observedAt := m.policyNow()
+ windowed := m.evaluateMetricWindow(spec.ResourceID, resourceType, metricType, value, observedAt)
+ if !windowed.Ready {
+ return
+ }
+ value = windowed.Value
+ opts = metricWindowOptions(opts, metricType, resourceType, windowed)
m.mu.Lock()
migratedAlertIdentity := false
diff --git a/internal/alerts/config/evaluation_windows_test.go b/internal/alerts/config/evaluation_windows_test.go
new file mode 100644
index 0000000000..d2f127abac
--- /dev/null
+++ b/internal/alerts/config/evaluation_windows_test.go
@@ -0,0 +1,27 @@
+package config
+
+import "testing"
+
+func TestNormalizeMetricEvaluationWindowsSeedsCPUAndPreservesCurrentValue(t *testing.T) {
+ if got := NormalizeMetricEvaluationWindows(nil)["all"]["cpu"]; got != DefaultCPUEvaluationWindowSeconds {
+ t.Fatalf("default CPU window = %d, want %d", got, DefaultCPUEvaluationWindowSeconds)
+ }
+
+ got := NormalizeMetricEvaluationWindows(map[string]map[string]int{
+ "all": {"CPU": 0, "memory": 900},
+ "VM": {"diskRead": 900},
+ "agent": {"networkOut": MaxMetricEvaluationWindowSeconds + 1},
+ })
+ if got["all"]["cpu"] != 0 {
+ t.Fatalf("explicit current-value mode was not preserved: %+v", got)
+ }
+ if _, exists := got["all"]["memory"]; exists {
+ t.Fatalf("safety-sensitive memory metric should not be windowed: %+v", got)
+ }
+ if got["vm"]["diskread"] != 900 {
+ t.Fatalf("resource override was not canonicalized: %+v", got)
+ }
+ if got["agent"]["networkout"] != MaxMetricEvaluationWindowSeconds {
+ t.Fatalf("window was not bounded: %+v", got)
+ }
+}
diff --git a/internal/alerts/config/normalize.go b/internal/alerts/config/normalize.go
index 39503d49ff..6916831cd3 100644
--- a/internal/alerts/config/normalize.go
+++ b/internal/alerts/config/normalize.go
@@ -696,6 +696,56 @@ func NormalizeMetricTimeThresholds(input map[string]map[string]int) map[string]m
return normalizeMetricTimeThresholds(input)
}
+const (
+ // DefaultCPUEvaluationWindowSeconds smooths short-lived CPU bursts while
+ // remaining responsive enough for operational alerting.
+ DefaultCPUEvaluationWindowSeconds = 5 * 60
+ MaxMetricEvaluationWindowSeconds = 60 * 60
+)
+
+var supportedWindowedMetrics = map[string]struct{}{
+ "cpu": {},
+ "diskread": {},
+ "diskwrite": {},
+ "networkin": {},
+ "networkout": {},
+}
+
+// NormalizeMetricEvaluationWindows canonicalizes rolling-window settings.
+// Explicit zero values are retained because zero means evaluate the current
+// observation. An absent global CPU rule is seeded with the safe 5-minute
+// default for both new and migrated configurations.
+func NormalizeMetricEvaluationWindows(input map[string]map[string]int) map[string]map[string]int {
+ normalized := make(map[string]map[string]int)
+ for rawType, metrics := range input {
+ typeKey := CanonicalAlertResourceType(rawType)
+ if typeKey == "" || (typeKey != "all" && isUnsupportedLegacyAlertResourceType(typeKey)) {
+ continue
+ }
+ for rawMetric, window := range metrics {
+ metricKey := strings.ToLower(strings.TrimSpace(rawMetric))
+ if _, supported := supportedWindowedMetrics[metricKey]; !supported || window < 0 {
+ continue
+ }
+ if window > MaxMetricEvaluationWindowSeconds {
+ window = MaxMetricEvaluationWindowSeconds
+ }
+ if _, exists := normalized[typeKey]; !exists {
+ normalized[typeKey] = make(map[string]int)
+ }
+ normalized[typeKey][metricKey] = window
+ }
+ }
+
+ if _, exists := normalized["all"]; !exists {
+ normalized["all"] = make(map[string]int)
+ }
+ if _, exists := normalized["all"]["cpu"]; !exists {
+ normalized["all"]["cpu"] = DefaultCPUEvaluationWindowSeconds
+ }
+ return normalized
+}
+
// NormalizeDockerIgnoredPrefixes trims, deduplicates, and lowercases comparison keys for ignored Docker containers.
func NormalizeDockerIgnoredPrefixes(prefixes []string) []string {
if len(prefixes) == 0 {
diff --git a/internal/alerts/config/types.go b/internal/alerts/config/types.go
index 83b64372f0..763eecdce1 100644
--- a/internal/alerts/config/types.go
+++ b/internal/alerts/config/types.go
@@ -363,6 +363,7 @@ type AlertConfig struct {
HysteresisMargin float64 `json:"hysteresisMargin"` // Default margin for legacy thresholds
TimeThresholds map[string]int `json:"timeThresholds"` // Per-type delays: guest, node, agent, storage, pbs
MetricTimeThresholds map[string]map[string]int `json:"metricTimeThresholds"` // Optional per-metric delays keyed by resource type
+ MetricEvaluationWindows map[string]map[string]int `json:"metricEvaluationWindows"` // Rolling-average seconds keyed by resource type and metric; explicit zero uses the current value
MaxAlertAgeDays int `json:"maxAlertAgeDays"` // Maximum age for alerts before auto-cleanup (0 = disabled)
MaxAcknowledgedAgeDays int `json:"maxAcknowledgedAgeDays"` // Maximum age for acknowledged alerts (0 = disabled)
AutoAcknowledgeAfterHours int `json:"autoAcknowledgeAfterHours"` // Auto-acknowledge alerts after X hours (0 = disabled)
@@ -408,17 +409,18 @@ func NormalizeAlertConfigAliases(config *AlertConfig) {
}
}
- if len(config.MetricTimeThresholds) == 0 {
- return
- }
-
- for key := range config.MetricTimeThresholds {
- typeKey := CanonicalAlertResourceType(key)
- if typeKey == "" || typeKey == "all" {
- continue
- }
- if isUnsupportedLegacyAlertResourceType(typeKey) {
- delete(config.MetricTimeThresholds, key)
+ for _, keyedMetrics := range []map[string]map[string]int{
+ config.MetricTimeThresholds,
+ config.MetricEvaluationWindows,
+ } {
+ for key := range keyedMetrics {
+ typeKey := CanonicalAlertResourceType(key)
+ if typeKey == "" || typeKey == "all" {
+ continue
+ }
+ if isUnsupportedLegacyAlertResourceType(typeKey) {
+ delete(keyedMetrics, key)
+ }
}
}
}
diff --git a/internal/alerts/config_facade.go b/internal/alerts/config_facade.go
index b27cd84a1d..5105175b64 100644
--- a/internal/alerts/config_facade.go
+++ b/internal/alerts/config_facade.go
@@ -47,6 +47,8 @@ const (
MaxEscalationDelayMinutes = alertconfig.MaxEscalationDelayMinutes
MinEscalationRepeatMinutes = alertconfig.MinEscalationRepeatMinutes
MaxEscalationRepeatMinutes = alertconfig.MaxEscalationRepeatMinutes
+ DefaultCPUEvaluationWindowSeconds = alertconfig.DefaultCPUEvaluationWindowSeconds
+ MaxMetricEvaluationWindowSeconds = alertconfig.MaxMetricEvaluationWindowSeconds
)
func NewAlertIntentPolicyDocument() AlertIntentPolicyDocument {
@@ -79,6 +81,10 @@ func NormalizeMetricTimeThresholds(input map[string]map[string]int) map[string]m
return alertconfig.NormalizeMetricTimeThresholds(input)
}
+func NormalizeMetricEvaluationWindows(input map[string]map[string]int) map[string]map[string]int {
+ return alertconfig.NormalizeMetricEvaluationWindows(input)
+}
+
func NormalizeDockerIgnoredPrefixes(prefixes []string) []string {
return alertconfig.NormalizeDockerIgnoredPrefixes(prefixes)
}
diff --git a/internal/alerts/config_runtime.go b/internal/alerts/config_runtime.go
index 2f7a626db0..efeabf8192 100644
--- a/internal/alerts/config_runtime.go
+++ b/internal/alerts/config_runtime.go
@@ -47,6 +47,7 @@ func (m *Manager) UpdateConfig(config AlertConfig) {
alertconfig.NormalizeVMwareDefaults(&config)
alertconfig.NormalizeGeneralSettings(&config)
alertconfig.NormalizeTimeThresholds(&config)
+ config.MetricEvaluationWindows = alertconfig.NormalizeMetricEvaluationWindows(config.MetricEvaluationWindows)
config.GuestDefaults.PoweredOffSeverity = alertconfig.NormalizePoweredOffSeverity(config.GuestDefaults.PoweredOffSeverity)
config.NodeDefaults.PoweredOffSeverity = alertconfig.NormalizePoweredOffSeverity(config.NodeDefaults.PoweredOffSeverity)
diff --git a/internal/alerts/default_config.go b/internal/alerts/default_config.go
index 9f13ec8645..68ad22a5de 100644
--- a/internal/alerts/default_config.go
+++ b/internal/alerts/default_config.go
@@ -153,6 +153,9 @@ func defaultAlertConfig() AlertConfig {
"vmware-datastore": 5,
"vmware-network": 5,
},
+ MetricEvaluationWindows: map[string]map[string]int{
+ "all": {"cpu": 5 * 60},
+ },
Overrides: make(map[string]ThresholdConfig),
Schedule: ScheduleConfig{
QuietHours: QuietHours{
diff --git a/internal/alerts/manager.go b/internal/alerts/manager.go
index e3718ffe76..7968188f56 100644
--- a/internal/alerts/manager.go
+++ b/internal/alerts/manager.go
@@ -60,6 +60,7 @@ type Manager struct {
operatorIntentResolver OperatorIntentContextResolver
backupIntentResolver BackupIntentContextResolver
resourceIntentResolver ResourceIntentIdentityResolver
+ metricWindowProvider MetricWindowProvider
// Offline confirmation tracking
// core is the authoritative transition state for the canonical
// lifecycle (match-spec) family: the deterministic reducer owns
diff --git a/internal/alerts/metric_runtime.go b/internal/alerts/metric_runtime.go
index e941f354f8..498f50a3f0 100644
--- a/internal/alerts/metric_runtime.go
+++ b/internal/alerts/metric_runtime.go
@@ -196,6 +196,13 @@ func (m *Manager) checkMetric(resourceID, resourceName, node, instance, resource
return
}
+ windowed := m.evaluateMetricWindow(resourceID, resourceType, metricType, value, m.policyNow())
+ if !windowed.Ready {
+ return
+ }
+ value = windowed.Value
+ opts = metricWindowOptions(opts, metricType, resourceType, windowed)
+
m.mu.Lock()
migratedAlertIdentity := false
defer func() {
diff --git a/internal/alerts/windowed_metric.go b/internal/alerts/windowed_metric.go
new file mode 100644
index 0000000000..f305d1b73c
--- /dev/null
+++ b/internal/alerts/windowed_metric.go
@@ -0,0 +1,197 @@
+package alerts
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+)
+
+const minimumMetricWindowSamples = 3
+
+// MetricWindowPoint is one trustworthy observation in a metric series.
+type MetricWindowPoint struct {
+ Timestamp time.Time
+ Value float64
+}
+
+// MetricWindowRequest identifies the canonical series required to evaluate a
+// rolling alert rule. Providers may resolve resourceID to a different durable
+// metrics identity, but must not substitute a different resource.
+type MetricWindowRequest struct {
+ ResourceID string
+ ResourceType string
+ Metric string
+ Start time.Time
+ End time.Time
+}
+
+// MetricWindowProvider bridges alert policy to monitoring-owned history.
+type MetricWindowProvider func(MetricWindowRequest) ([]MetricWindowPoint, error)
+
+type metricWindowObservation struct {
+ Value float64
+ CurrentValue float64
+ WindowSeconds int
+ CoverageSeconds int
+ SampleCount int
+ Ready bool
+}
+
+// SetMetricWindowProvider installs the monitoring-owned history bridge.
+func (m *Manager) SetMetricWindowProvider(provider MetricWindowProvider) {
+ m.mu.Lock()
+ m.metricWindowProvider = provider
+ m.mu.Unlock()
+}
+
+func (m *Manager) metricEvaluationWindowNoLock(resourceType, metricType string) int {
+ metricKey := strings.ToLower(strings.TrimSpace(metricType))
+ for _, typeKey := range CanonicalResourceTypeKeys(resourceType) {
+ if perType := m.config.MetricEvaluationWindows[typeKey]; perType != nil {
+ if window, ok := perType[metricKey]; ok {
+ return window
+ }
+ }
+ }
+ if perType := m.config.MetricEvaluationWindows["all"]; perType != nil {
+ return perType[metricKey]
+ }
+ return 0
+}
+
+func (m *Manager) evaluateMetricWindow(resourceID, resourceType, metricType string, current float64, observedAt time.Time) metricWindowObservation {
+ m.mu.RLock()
+ windowSeconds := m.metricEvaluationWindowNoLock(resourceType, metricType)
+ provider := m.metricWindowProvider
+ m.mu.RUnlock()
+
+ instant := metricWindowObservation{Value: current, CurrentValue: current, Ready: true}
+ if windowSeconds <= 0 {
+ return instant
+ }
+ instant.WindowSeconds = windowSeconds
+ // Unit tests and embedders that construct an alert manager without the
+ // monitoring runtime retain current-value behavior. Production always wires
+ // a provider; a wired provider returning insufficient evidence is unknown.
+ if provider == nil {
+ return instant
+ }
+
+ start := observedAt.Add(-time.Duration(windowSeconds) * time.Second)
+ points, err := provider(MetricWindowRequest{
+ ResourceID: resourceID, ResourceType: resourceType, Metric: metricType,
+ Start: start, End: observedAt,
+ })
+ if err != nil {
+ return metricWindowObservation{CurrentValue: current, WindowSeconds: windowSeconds}
+ }
+ points = append(points, MetricWindowPoint{Timestamp: observedAt, Value: current})
+ return calculateMetricWindow(points, start, observedAt, current, windowSeconds)
+}
+
+func calculateMetricWindow(points []MetricWindowPoint, start, end time.Time, current float64, windowSeconds int) metricWindowObservation {
+ result := metricWindowObservation{CurrentValue: current, WindowSeconds: windowSeconds}
+ filtered := make([]MetricWindowPoint, 0, len(points))
+ for _, point := range points {
+ if point.Timestamp.Before(start) || point.Timestamp.After(end) {
+ continue
+ }
+ filtered = append(filtered, point)
+ }
+ sort.SliceStable(filtered, func(i, j int) bool { return filtered[i].Timestamp.Before(filtered[j].Timestamp) })
+
+ // Collapse duplicate timestamps, preferring the last value (the current
+ // observation appended by the caller wins over an already-persisted point).
+ unique := filtered[:0]
+ for _, point := range filtered {
+ if len(unique) > 0 && unique[len(unique)-1].Timestamp.Equal(point.Timestamp) {
+ unique[len(unique)-1] = point
+ continue
+ }
+ unique = append(unique, point)
+ }
+ result.SampleCount = len(unique)
+ if len(unique) < minimumMetricWindowSamples {
+ return result
+ }
+
+ coverage := unique[len(unique)-1].Timestamp.Sub(unique[0].Timestamp)
+ result.CoverageSeconds = int(coverage.Seconds())
+ requiredCoverage := time.Duration(windowSeconds) * time.Second * 8 / 10
+ maxGap := 2 * time.Minute
+ if windowDuration := time.Duration(windowSeconds) * time.Second; windowDuration < maxGap {
+ maxGap = windowDuration
+ }
+ if coverage < requiredCoverage || end.Sub(unique[len(unique)-1].Timestamp) > maxGap {
+ return result
+ }
+
+ weightedTotal := 0.0
+ weightedDuration := time.Duration(0)
+ for i := 1; i < len(unique); i++ {
+ segment := unique[i].Timestamp.Sub(unique[i-1].Timestamp)
+ if segment <= 0 || segment > maxGap {
+ return result
+ }
+ // Trapezoidal integration avoids bias from variable polling cadence.
+ weightedTotal += ((unique[i-1].Value + unique[i].Value) / 2) * segment.Seconds()
+ weightedDuration += segment
+ }
+ if weightedDuration <= 0 {
+ return result
+ }
+ result.Value = weightedTotal / weightedDuration.Seconds()
+ result.Ready = true
+ return result
+}
+
+func metricWindowOptions(opts *metricOptions, metricType, resourceType string, observation metricWindowObservation) *metricOptions {
+ if observation.WindowSeconds <= 0 {
+ return opts
+ }
+ merged := &metricOptions{}
+ if opts != nil {
+ *merged = *opts
+ merged.Metadata = cloneMetricMetadata(opts.Metadata)
+ merged.RemoveMetadata = append([]string(nil), opts.RemoveMetadata...)
+ } else {
+ merged.Metadata = make(map[string]interface{})
+ }
+ if merged.Metadata == nil {
+ merged.Metadata = make(map[string]interface{})
+ }
+ merged.Metadata["evaluationMode"] = "rolling_average"
+ merged.Metadata["evaluationWindowSeconds"] = observation.WindowSeconds
+ merged.Metadata["evaluationCoverageSeconds"] = observation.CoverageSeconds
+ merged.Metadata["evaluationSampleCount"] = observation.SampleCount
+ merged.Metadata["currentValue"] = observation.CurrentValue
+ merged.Metadata["evaluatedValue"] = observation.Value
+ if merged.Message == "" {
+ label := resourceTypeLabel(resourceType)
+ unit := "%"
+ if metricType == "diskRead" || metricType == "diskWrite" || metricType == "networkIn" || metricType == "networkOut" {
+ unit = " MB/s"
+ }
+ merged.Message = fmt.Sprintf("%s %s %s average at %.1f%s (current %.1f%s)", label, metricType, metricWindowLabel(observation.WindowSeconds), observation.Value, unit, observation.CurrentValue, unit)
+ }
+ return merged
+}
+
+func cloneMetricMetadata(input map[string]interface{}) map[string]interface{} {
+ result := make(map[string]interface{}, len(input)+6)
+ for key, value := range input {
+ result[key] = value
+ }
+ return result
+}
+
+func metricWindowLabel(seconds int) string {
+ if seconds%3600 == 0 {
+ return fmt.Sprintf("%d-hour", seconds/3600)
+ }
+ if seconds%60 == 0 {
+ return fmt.Sprintf("%d-minute", seconds/60)
+ }
+ return fmt.Sprintf("%d-second", seconds)
+}
diff --git a/internal/alerts/windowed_metric_test.go b/internal/alerts/windowed_metric_test.go
new file mode 100644
index 0000000000..664b1199dd
--- /dev/null
+++ b/internal/alerts/windowed_metric_test.go
@@ -0,0 +1,135 @@
+package alerts
+
+import (
+ "math"
+ "testing"
+ "time"
+)
+
+func TestCalculateMetricWindowUsesTimeWeightedAverage(t *testing.T) {
+ end := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC)
+ start := end.Add(-5 * time.Minute)
+ points := []MetricWindowPoint{
+ {Timestamp: start, Value: 40},
+ {Timestamp: start.Add(2 * time.Minute), Value: 40},
+ {Timestamp: start.Add(4 * time.Minute), Value: 40},
+ {Timestamp: end, Value: 100},
+ }
+
+ got := calculateMetricWindow(points, start, end, 100, 300)
+ if !got.Ready {
+ t.Fatal("expected complete window to be ready")
+ }
+ if math.Abs(got.Value-46) > 0.001 {
+ t.Fatalf("expected a time-weighted average of 46, got %.3f", got.Value)
+ }
+ if got.SampleCount != 4 || got.CoverageSeconds != 300 {
+ t.Fatalf("unexpected evidence: %+v", got)
+ }
+}
+
+func TestCalculateMetricWindowRejectsIncompleteAndGappedEvidence(t *testing.T) {
+ end := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC)
+ start := end.Add(-5 * time.Minute)
+
+ for name, points := range map[string][]MetricWindowPoint{
+ "too few samples": {
+ {Timestamp: start, Value: 90},
+ {Timestamp: end, Value: 90},
+ },
+ "insufficient coverage": {
+ {Timestamp: end.Add(-2 * time.Minute), Value: 90},
+ {Timestamp: end.Add(-time.Minute), Value: 90},
+ {Timestamp: end, Value: 90},
+ },
+ "large internal gap": {
+ {Timestamp: start, Value: 90},
+ {Timestamp: start.Add(30 * time.Second), Value: 90},
+ {Timestamp: end, Value: 90},
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ if got := calculateMetricWindow(points, start, end, 90, 300); got.Ready {
+ t.Fatalf("expected weak evidence to remain unknown, got %+v", got)
+ }
+ })
+ }
+}
+
+func TestWindowedMetricSpikeDoesNotFireAndMetadataExplainsAverage(t *testing.T) {
+ m := NewManagerWithDataDir(t.TempDir())
+ defer m.Stop()
+ now := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC)
+ m.now = func() time.Time { return now }
+ cfg := m.GetConfig()
+ cfg.ActivationState = ActivationActive
+ cfg.MetricEvaluationWindows = map[string]map[string]int{"all": {"cpu": 300}}
+ m.UpdateConfig(cfg)
+ m.SetMetricWindowProvider(func(request MetricWindowRequest) ([]MetricWindowPoint, error) {
+ return []MetricWindowPoint{
+ {Timestamp: request.Start, Value: 40},
+ {Timestamp: request.Start.Add(2 * time.Minute), Value: 40},
+ {Timestamp: request.Start.Add(4 * time.Minute), Value: 40},
+ }, nil
+ })
+
+ threshold := &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.checkMetric("vm-1", "web-1", "node-1", "pve-1", "vm", "cpu", 100, threshold, nil)
+ if alerts := m.GetActiveAlerts(); len(alerts) != 0 {
+ t.Fatalf("expected a short CPU spike to be filtered, got %+v", alerts)
+ }
+
+ m.SetMetricWindowProvider(func(request MetricWindowRequest) ([]MetricWindowPoint, error) {
+ return []MetricWindowPoint{
+ {Timestamp: request.Start, Value: 90},
+ {Timestamp: request.Start.Add(2 * time.Minute), Value: 90},
+ {Timestamp: request.Start.Add(4 * time.Minute), Value: 90},
+ }, nil
+ })
+ m.checkMetric("vm-1", "web-1", "node-1", "pve-1", "vm", "cpu", 90, threshold, nil)
+ now = now.Add(6 * time.Second)
+ m.checkMetric("vm-1", "web-1", "node-1", "pve-1", "vm", "cpu", 90, threshold, nil)
+ active := m.GetActiveAlerts()
+ if len(active) != 1 {
+ t.Fatalf("expected sustained CPU to fire, got %+v", active)
+ }
+ alert := active[0]
+ if alert.Metadata["evaluationMode"] != "rolling_average" || alert.Metadata["evaluationWindowSeconds"] != 300 {
+ t.Fatalf("missing rolling-window evidence: %+v", alert.Metadata)
+ }
+ if alert.Message == "" || alert.Value != 90 {
+ t.Fatalf("unexpected rolling alert presentation: %+v", alert)
+ }
+}
+
+func TestWindowedMetricUnknownHistoryPreservesActiveIncident(t *testing.T) {
+ m := NewManagerWithDataDir(t.TempDir())
+ defer m.Stop()
+ now := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC)
+ m.now = func() time.Time { return now }
+ cfg := m.GetConfig()
+ cfg.ActivationState = ActivationActive
+ cfg.MetricEvaluationWindows = map[string]map[string]int{"all": {"cpu": 300}}
+ m.UpdateConfig(cfg)
+ complete := true
+ m.SetMetricWindowProvider(func(request MetricWindowRequest) ([]MetricWindowPoint, error) {
+ if !complete {
+ return nil, nil
+ }
+ return []MetricWindowPoint{
+ {Timestamp: request.Start, Value: 90},
+ {Timestamp: request.Start.Add(2 * time.Minute), Value: 90},
+ {Timestamp: request.Start.Add(4 * time.Minute), Value: 90},
+ }, nil
+ })
+ threshold := &HysteresisThreshold{Trigger: 80, Clear: 75}
+ m.checkMetric("vm-1", "web-1", "node-1", "pve-1", "vm", "cpu", 90, threshold, nil)
+ now = now.Add(6 * time.Second)
+ m.checkMetric("vm-1", "web-1", "node-1", "pve-1", "vm", "cpu", 90, threshold, nil)
+ complete = false
+ now = now.Add(time.Minute)
+ m.checkMetric("vm-1", "web-1", "node-1", "pve-1", "vm", "cpu", 10, threshold, nil)
+ if active := m.GetActiveAlerts(); len(active) != 1 {
+ t.Fatalf("expected unknown history to preserve the incident, got %+v", active)
+ }
+}
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index 7bdf9e3750..7a1e2d85f8 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -866,6 +866,7 @@ func normalizeAlertDefaults(config *alerts.AlertConfig) {
// Time thresholds
config.MetricTimeThresholds = alerts.NormalizeMetricTimeThresholds(config.MetricTimeThresholds)
+ config.MetricEvaluationWindows = alerts.NormalizeMetricEvaluationWindows(config.MetricEvaluationWindows)
if config.TimeThresholds == nil {
config.TimeThresholds = make(map[string]int)
}
diff --git a/internal/monitoring/metric_window_provider.go b/internal/monitoring/metric_window_provider.go
new file mode 100644
index 0000000000..70c6fbe0f8
--- /dev/null
+++ b/internal/monitoring/metric_window_provider.go
@@ -0,0 +1,165 @@
+package monitoring
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rs/zerolog/log"
+)
+
+const metricWindowPersistentCacheTTL = 30 * time.Second
+
+type metricWindowCacheEntry struct {
+ points []alerts.MetricWindowPoint
+ expiresAt time.Time
+}
+
+func metricHistoryName(metric string) string {
+ switch strings.ToLower(strings.TrimSpace(metric)) {
+ case "diskread":
+ return "diskread"
+ case "diskwrite":
+ return "diskwrite"
+ case "networkin":
+ return "netin"
+ case "networkout":
+ return "netout"
+ default:
+ return strings.ToLower(strings.TrimSpace(metric))
+ }
+}
+
+func (m *Monitor) metricWindowPoints(request alerts.MetricWindowRequest) ([]alerts.MetricWindowPoint, error) {
+ if m == nil {
+ return nil, fmt.Errorf("monitor unavailable")
+ }
+ resourceType := strings.TrimSpace(request.ResourceType)
+ resourceID := strings.TrimSpace(request.ResourceID)
+ if target := m.MetricsTargetForResource(request.ResourceID); target != nil {
+ if strings.TrimSpace(target.ResourceType) != "" {
+ resourceType = strings.TrimSpace(target.ResourceType)
+ }
+ if strings.TrimSpace(target.ResourceID) != "" {
+ resourceID = strings.TrimSpace(target.ResourceID)
+ }
+ }
+ if resourceType == "" || resourceID == "" {
+ return nil, fmt.Errorf("metric target unavailable for %q", request.ResourceID)
+ }
+
+ metric := metricHistoryName(request.Metric)
+ duration := request.End.Sub(request.Start)
+ if duration <= 0 {
+ return nil, fmt.Errorf("invalid metric window")
+ }
+ points := m.inMemoryMetricWindow(resourceType, resourceID, metric, duration)
+ if metricWindowCoverage(points) < duration*8/10 {
+ stored := m.persistentMetricWindow(resourceType, resourceID, metric, request.Start, request.End)
+ points = mergeMetricWindowPoints(points, stored, request.Start, request.End)
+ }
+
+ result := make([]alerts.MetricWindowPoint, 0, len(points))
+ for _, point := range points {
+ result = append(result, alerts.MetricWindowPoint{Timestamp: point.Timestamp, Value: point.Value})
+ }
+ return result, nil
+}
+
+func (m *Monitor) inMemoryMetricWindow(resourceType, resourceID, metric string, duration time.Duration) []MetricPoint {
+ if m.metricsHistory == nil {
+ return nil
+ }
+ switch strings.ToLower(resourceType) {
+ case "node":
+ return m.metricsHistory.GetNodeMetrics(resourceID, metric, duration)
+ case "storage":
+ return m.metricsHistory.GetAllStorageMetrics(resourceID, duration)[metric]
+ case "disk":
+ return m.metricsHistory.GetDiskMetrics(resourceID, metric, duration)
+ default:
+ return m.metricsHistory.GetGuestMetrics(resourceID, metric, duration)
+ }
+}
+
+func (m *Monitor) persistentMetricWindow(resourceType, resourceID, metric string, start, end time.Time) []MetricPoint {
+ if m.metricsStore == nil {
+ return nil
+ }
+ cacheKey := strings.Join([]string{resourceType, resourceID, metric, fmt.Sprint(end.Sub(start).Seconds())}, "\x00")
+ now := time.Now()
+ if m.metricsHistory != nil {
+ m.metricsHistory.metricWindowMu.Lock()
+ if cached, ok := m.metricsHistory.metricWindowCache[cacheKey]; ok && now.Before(cached.expiresAt) {
+ points := make([]MetricPoint, len(cached.points))
+ for i, point := range cached.points {
+ points[i] = MetricPoint{Timestamp: point.Timestamp, Value: point.Value}
+ }
+ m.metricsHistory.metricWindowMu.Unlock()
+ return points
+ }
+ m.metricsHistory.metricWindowMu.Unlock()
+ }
+
+ var best []MetricPoint
+ for _, candidate := range monitorStoreResourceTypeCandidates(resourceType) {
+ stored, err := m.metricsStore.Query(candidate, resourceID, metric, start, end, 0)
+ if err != nil {
+ log.Debug().Err(err).Str("resource", resourceID).Str("metric", metric).Msg("Rolling alert history unavailable")
+ continue
+ }
+ converted := make([]MetricPoint, len(stored))
+ for i, point := range stored {
+ converted[i] = MetricPoint{Timestamp: point.Timestamp, Value: point.Value}
+ }
+ if metricWindowCoverage(converted) > metricWindowCoverage(best) {
+ best = converted
+ }
+ }
+ if m.metricsHistory != nil {
+ cached := make([]alerts.MetricWindowPoint, len(best))
+ for i, point := range best {
+ cached[i] = alerts.MetricWindowPoint{Timestamp: point.Timestamp, Value: point.Value}
+ }
+ m.metricsHistory.metricWindowMu.Lock()
+ if m.metricsHistory.metricWindowCache == nil {
+ m.metricsHistory.metricWindowCache = make(map[string]metricWindowCacheEntry)
+ }
+ if len(m.metricsHistory.metricWindowCache) >= 1024 {
+ for key, entry := range m.metricsHistory.metricWindowCache {
+ if !now.Before(entry.expiresAt) {
+ delete(m.metricsHistory.metricWindowCache, key)
+ }
+ }
+ }
+ m.metricsHistory.metricWindowCache[cacheKey] = metricWindowCacheEntry{points: cached, expiresAt: now.Add(metricWindowPersistentCacheTTL)}
+ m.metricsHistory.metricWindowMu.Unlock()
+ }
+ return best
+}
+
+func metricWindowCoverage(points []MetricPoint) time.Duration {
+ if len(points) < 2 {
+ return 0
+ }
+ return points[len(points)-1].Timestamp.Sub(points[0].Timestamp)
+}
+
+func mergeMetricWindowPoints(left, right []MetricPoint, start, end time.Time) []MetricPoint {
+ combined := append(append(make([]MetricPoint, 0, len(left)+len(right)), left...), right...)
+ sort.SliceStable(combined, func(i, j int) bool { return combined[i].Timestamp.Before(combined[j].Timestamp) })
+ result := combined[:0]
+ for _, point := range combined {
+ if point.Timestamp.Before(start) || point.Timestamp.After(end) {
+ continue
+ }
+ if len(result) > 0 && result[len(result)-1].Timestamp.Equal(point.Timestamp) {
+ result[len(result)-1] = point
+ continue
+ }
+ result = append(result, point)
+ }
+ return result
+}
diff --git a/internal/monitoring/metrics_history.go b/internal/monitoring/metrics_history.go
index ea7accbb84..ba4ab659b8 100644
--- a/internal/monitoring/metrics_history.go
+++ b/internal/monitoring/metrics_history.go
@@ -56,6 +56,8 @@ type MetricsHistory struct {
capacityForecastMu sync.Mutex
capacityForecastCache map[string]storageCapacityForecastCacheEntry
+ metricWindowMu sync.Mutex
+ metricWindowCache map[string]metricWindowCacheEntry
}
// NewMetricsHistory creates a new metrics history tracker
@@ -135,12 +137,15 @@ func cloneGuestMetrics(metrics *GuestMetrics) *GuestMetrics {
// Reset clears all historical metrics data.
func (mh *MetricsHistory) Reset() {
mh.mu.Lock()
- defer mh.mu.Unlock()
-
mh.guestMetrics = make(map[string]*GuestMetrics)
mh.nodeMetrics = make(map[string]*GuestMetrics)
mh.storageMetrics = make(map[string]*StorageMetrics)
mh.diskMetrics = make(map[string]*DiskMetrics)
+ mh.mu.Unlock()
+
+ mh.metricWindowMu.Lock()
+ mh.metricWindowCache = nil
+ mh.metricWindowMu.Unlock()
}
// AddGuestMetric adds a metric value for a guest
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index a6157b8a01..bd335410af 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -1765,6 +1765,7 @@ func New(cfg *config.Config) (*Monitor, error) {
}
m.hydrateRemovedHostAgents(time.Now().UTC())
m.alertManager.SetBackupIntentContextResolver(m.resolveBackupIntentContext)
+ m.alertManager.SetMetricWindowProvider(m.metricWindowPoints)
m.alertManager.EnableShadowFeed()
m.registerBuiltInPollProviders()
m.buildInstanceInfoCache(cfg)