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.

Prove TrueNAS alert threshold identity persistence

rcourtman577258936390
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index a4d18a44c7..ba53f8f52b 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -252,6 +252,30 @@ alert feature gating from the shared entitlements layer, not from a per-surface
Canonical alert identity and evaluation are the live runtime model. Remaining
legacy references should exist only in explicit migration or negative test
boundaries.
+TrueNAS per-resource threshold overrides use the unified resource's current
+canonical ID as their persistence and evaluation key. API-backed TrueNAS
+systems are keyed by configured connection, never reported hostname or DMI
+serial, so repolls, result reordering, missing serials, DR clones, and multiple
+same-hostname appliances cannot transfer or strand an override. The browser
+may read provider-declared superseded IDs and metric-target IDs while
+projecting a legacy `alerts.json`, but an edit must remove those candidates
+and persist exactly one row under the current canonical ID. While an input is
+active, the thresholds projector must retain the edited row across WebSocket
+resource refreshes; blur commits that retained row into the unsaved
+configuration, and the global configuration save remains the only API
+persistence boundary.
+
+The monitoring bridge may migrate only provider-declared, unambiguous
+canonical-ID successions before evaluation. It must persist the migrated
+configuration before installing it in the alert manager, let a current-key
+override win while removing its retired duplicate, and retain unknown or
+temporarily absent override rows until a provider proves succession. The same
+persisted override must drive trigger, clear, derived critical severity, and
+notification dispatch before and after restart. Regression ownership is
+`frontend-modern/src/features/alerts/thresholds/hooks/__tests__/truenasThresholdPersistence.test.tsx`,
+`frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx`,
+`internal/alerts/canonical_override_migration_test.go`, and
+`internal/monitoring/monitor_alert_override_migration_test.go`.
All v6 platform alert targets must enter runtime threshold evaluation through
`UnifiedResourceInput` and `internal/alerts/unified_eval.go`: Proxmox guests/
nodes/storage, Docker hosts/containers/services, Kubernetes clusters/nodes/
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index f4a8ef54ed..39f186b78e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -8053,6 +8053,28 @@ acceptance and typed-conflict payloads, while
`frontend-modern/src/features/patrol/__tests__/patrolRunAcceptance.test.ts`
proves bounded status/history reconciliation against the returned run ID.
+### Alert configuration persistence transport
+
+`GET /api/alerts/config` and `PUT /api/alerts/config` carry the one canonical
+alert configuration shape used by the thresholds editor, alert evaluator, and
+notification runtime. Per-resource TrueNAS overrides are keyed by the current
+unified canonical resource ID; connection IDs and provider-declared
+superseded IDs are read/migration candidates, not additional writable rows.
+The browser's blur commit is local unsaved state. Only a successful
+`PUT /api/alerts/config` confirms persistence, and an API or persistence
+failure must remain an error so the browser keeps the unsaved banner and shows
+the actionable backend message instead of claiming that the threshold was
+saved.
+
+`internal/api/alerts_test.go`,
+`frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx`,
+and
+`internal/monitoring/monitor_alert_override_migration_test.go` jointly prove
+the transport, persistence-error, canonical-key, reload, and restart
+boundaries. Alert evaluation after that save remains alerts-owned and must use
+the persisted trigger/recovery pair plus a valid derived critical threshold;
+the API must not invent a TrueNAS-specific threshold sidecar.
+
### Alert intent and UDP availability transport
`GET /api/alerts/intent-policies` and
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 6cdc6eb89b..d9faffb726 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -4044,6 +4044,21 @@ owns availability-state policy and alert-removal side effects. The table-shell
hook should not re-accumulate raw override mutation logic,
recovery-threshold defaults policy, or resource-family projection engines
inline.
+TrueNAS system threshold rows follow that same feature-owner split and the
+canonical alert identity chain. `useThresholdsPlatformData.ts` must project
+the current canonical resource ID as the writable storage ID, accept bounded
+superseded/metric-target candidates for legacy readback, and retain the
+projected row while `editingId` is active so WebSocket resource repolls,
+reordering, or changing display telemetry cannot reset the input.
+`useThresholdsOverrideMutations.ts` owns the blur commit: it removes every
+bounded candidate, writes exactly one current-ID raw override, marks the
+configuration dirty, and leaves the global Save Changes control to perform the
+API persistence. Multiple same-hostname TrueNAS systems must stay independent
+because configured connection identity, not display name or DMI serial, owns
+the row. The regression boundary is
+`frontend-modern/src/features/alerts/thresholds/hooks/__tests__/truenasThresholdPersistence.test.tsx`;
+the global payload boundary is
+`frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx`.
The updates settings surface now follows the same presentation-owner rule.
`frontend-modern/src/components/Settings/UpdatesSettingsPanel.tsx` stays the
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx
index f09a43ec63..fdf6059f45 100644
--- a/frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx
@@ -2,8 +2,11 @@ import { renderHook, waitFor } from '@solidjs/testing-library';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mockGetConfig = vi.fn();
+const mockUpdateConfig = vi.fn();
const mockLoadDestinations = vi.fn();
+const mockSaveDestinations = vi.fn();
const mockReplaceRawOverridesConfig = vi.fn();
+const mockRawOverridesConfig = vi.fn();
const containerRuntimeResources = () =>
[
{
@@ -16,7 +19,7 @@ const containerRuntimeResources = () =>
vi.mock('@/api/alerts', () => ({
AlertsAPI: {
getConfig: (...args: unknown[]) => mockGetConfig(...args),
- updateConfig: vi.fn(),
+ updateConfig: (...args: unknown[]) => mockUpdateConfig(...args),
},
}));
@@ -30,7 +33,7 @@ vi.mock('../useAlertDestinationsState', () => ({
setAppriseConfig: vi.fn(),
resetDestinations: vi.fn(),
loadDestinations: (...args: unknown[]) => mockLoadDestinations(...args),
- saveDestinations: vi.fn(),
+ saveDestinations: (...args: unknown[]) => mockSaveDestinations(...args),
}),
}));
@@ -38,7 +41,7 @@ vi.mock('../useAlertOverridesState', () => ({
useAlertOverridesState: () => ({
overrides: () => [],
setOverrides: vi.fn(),
- rawOverridesConfig: () => ({}),
+ rawOverridesConfig: (...args: unknown[]) => mockRawOverridesConfig(...args),
setRawOverridesConfig: vi.fn(),
replaceRawOverridesConfig: (...args: unknown[]) => mockReplaceRawOverridesConfig(...args),
allGuests: () => [],
@@ -54,10 +57,16 @@ import { useAlertsConfigurationState } from '../useAlertsConfigurationState';
describe('useAlertsConfigurationState', () => {
beforeEach(() => {
mockGetConfig.mockReset();
+ mockUpdateConfig.mockReset();
mockLoadDestinations.mockReset();
+ mockSaveDestinations.mockReset();
mockReplaceRawOverridesConfig.mockReset();
+ mockRawOverridesConfig.mockReset();
mockGetConfig.mockResolvedValue({ overrides: {} });
+ mockUpdateConfig.mockResolvedValue({ success: true });
mockLoadDestinations.mockResolvedValue(undefined);
+ mockSaveDestinations.mockResolvedValue(undefined);
+ mockRawOverridesConfig.mockReturnValue({});
});
it('surfaces canonical container runtime resources from the overrides owner', async () => {
@@ -87,4 +96,51 @@ describe('useAlertsConfigurationState', () => {
}),
]);
});
+
+ it('sends the canonical TrueNAS override through the global configuration save', async () => {
+ const setHasUnsavedChanges = vi.fn();
+ mockRawOverridesConfig.mockReturnValue({
+ 'agent-b9ed6d0e20e94eaf': {
+ memory: {
+ trigger: 95,
+ clear: 90,
+ },
+ },
+ });
+
+ const { result } = renderHook(() =>
+ useAlertsConfigurationState({
+ activeTab: () => 'thresholds',
+ allResources: () => [],
+ byType: () => [],
+ children: () => [],
+ activeAlerts: {},
+ removeAlerts: vi.fn(),
+ setOverviewOverrides: vi.fn(),
+ hasUnsavedChanges: () => true,
+ setHasUnsavedChanges,
+ alertsActivationState: () => 'active',
+ alertsActivationConfig: () => ({ enabled: true }),
+ }),
+ );
+
+ await waitFor(() => expect(mockGetConfig).toHaveBeenCalledTimes(1));
+ await result.saveAlertConfiguration();
+
+ expect(mockUpdateConfig).toHaveBeenCalledTimes(1);
+ expect(mockUpdateConfig.mock.calls[0]?.[0]).toEqual(
+ expect.objectContaining({
+ overrides: {
+ 'agent-b9ed6d0e20e94eaf': {
+ memory: {
+ trigger: 95,
+ clear: 90,
+ },
+ },
+ },
+ }),
+ );
+ expect(mockSaveDestinations).toHaveBeenCalledTimes(1);
+ expect(setHasUnsavedChanges).toHaveBeenLastCalledWith(false);
+ });
});
diff --git a/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/truenasThresholdPersistence.test.tsx b/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/truenasThresholdPersistence.test.tsx
index c8815dd024..8bef6d6069 100644
--- a/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/truenasThresholdPersistence.test.tsx
+++ b/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/truenasThresholdPersistence.test.tsx
@@ -14,10 +14,25 @@ import { useThresholdsPlatformData } from '../useThresholdsPlatformData';
const canonicalID = 'agent-b9ed6d0e20e94eaf';
const legacyCanonicalID = 'agent-535886018cb53055';
const connectionID = 'truenas-connection-1';
+const secondCanonicalID = 'agent-4266ee45469c27f1';
+const secondLegacyCanonicalID = 'agent-0d4080c143654b4f';
+const secondConnectionID = 'truenas-connection-2';
-const connectionBackedTrueNASResource = (machineId: string): Resource =>
+const connectionBackedTrueNASResource = ({
+ canonicalId = canonicalID,
+ legacyId = legacyCanonicalID,
+ connectionId = connectionID,
+ machineId,
+ memory = 87,
+}: {
+ canonicalId?: string;
+ legacyId?: string;
+ connectionId?: string;
+ machineId: string;
+ memory?: number;
+}): Resource =>
({
- id: canonicalID,
+ id: canonicalId,
type: 'agent',
name: 'strawberrynas',
displayName: 'Strawberry NAS',
@@ -33,21 +48,21 @@ const connectionBackedTrueNASResource = (machineId: string): Resource =>
},
metricsTarget: {
resourceType: 'agent',
- resourceId: connectionID,
+ resourceId: connectionId,
},
canonicalIdentity: {
- primaryId: `agent:${connectionID}`,
- aliases: [canonicalID, connectionID, 'strawberrynas'],
- supersededIds: [legacyCanonicalID],
+ primaryId: `agent:${connectionId}`,
+ aliases: [canonicalId, connectionId, 'strawberrynas'],
+ supersededIds: [legacyId],
},
memory: {
- current: 87,
+ current: memory,
},
}) as Resource;
const projectOverrides = (
rawConfig: Record<string, RawOverrideConfig>,
- resource: Resource,
+ resources: Resource[],
): Override[] =>
buildProjectedOverrides({
rawConfig,
@@ -55,17 +70,17 @@ const projectOverrides = (
vmResources: [],
containerResources: [],
storageResources: [],
- agentResourceList: [resource],
- containerRuntimeResources: [resource],
+ agentResourceList: resources,
+ containerRuntimeResources: resources,
getChildren: () => [],
pbsInstanceById: new Map(),
- allResources: [resource],
+ allResources: resources,
});
describe('TrueNAS threshold persistence identity', () => {
it('re-homes a connection-target override onto the canonical ID and survives reload/refetch', () => {
const [resource, setResource] = createSignal(
- connectionBackedTrueNASResource('serial-visible-on-first-poll'),
+ connectionBackedTrueNASResource({ machineId: 'serial-visible-on-first-poll' }),
);
const initialRawConfig: Record<string, RawOverrideConfig> = {
[connectionID]: {
@@ -77,7 +92,7 @@ describe('TrueNAS threshold persistence identity', () => {
};
const [rawOverridesConfig, setRawOverridesConfig] = createSignal(initialRawConfig);
const [overrides, setOverrides] = createSignal<Override[]>(
- projectOverrides(initialRawConfig, resource()),
+ projectOverrides(initialRawConfig, [resource()]),
);
const [editingId] = createSignal<string | null>(null);
const [editingThresholds] = createSignal<Record<string, number | undefined>>({
@@ -176,8 +191,8 @@ describe('TrueNAS threshold persistence identity', () => {
RawOverrideConfig
>;
setRawOverridesConfig(persisted);
- setResource(connectionBackedTrueNASResource('serial-missing-on-next-poll'));
- setOverrides(projectOverrides(persisted, resource()));
+ setResource(connectionBackedTrueNASResource({ machineId: 'serial-missing-on-next-poll' }));
+ setOverrides(projectOverrides(persisted, [resource()]));
expect(platform.result.trueNASSystemsWithOverrides()).toEqual([
expect.objectContaining({
@@ -190,4 +205,151 @@ describe('TrueNAS threshold persistence identity', () => {
]);
expect(setHasUnsavedChanges).toHaveBeenCalledWith(true);
});
+
+ it('keeps the edited connection stable through a websocket repoll/reorder and the blur save handler', () => {
+ const firstPoll = connectionBackedTrueNASResource({
+ machineId: 'shared-dr-serial',
+ memory: 87,
+ });
+ const secondSystem = connectionBackedTrueNASResource({
+ canonicalId: secondCanonicalID,
+ legacyId: secondLegacyCanonicalID,
+ connectionId: secondConnectionID,
+ machineId: 'shared-dr-serial',
+ memory: 68,
+ });
+ const [resources, setResources] = createSignal<Resource[]>([firstPoll, secondSystem]);
+ const [rawOverridesConfig, setRawOverridesConfig] = createSignal<
+ Record<string, RawOverrideConfig>
+ >({});
+ const [overrides, setOverrides] = createSignal<Override[]>([]);
+ const [editingId, setEditingId] = createSignal<string | null>(null);
+ const [editingThresholds, setEditingThresholds] = createSignal<
+ Record<string, number | undefined>
+ >({});
+ const [editingNote, setEditingNote] = createSignal('');
+ const [bulkEditIds] = createSignal<string[]>([]);
+ const setHasUnsavedChanges = vi.fn();
+ const cancelEdit = () => {
+ setEditingId(null);
+ setEditingThresholds({});
+ setEditingNote('');
+ };
+
+ const props = {
+ get allResources() {
+ return resources();
+ },
+ overrides,
+ setOverrides,
+ rawOverridesConfig,
+ setRawOverridesConfig,
+ trueNASDefaults: {
+ memory: 85,
+ },
+ trueNASDiskDefaults: {},
+ backupDefaults: () => ({ enabled: false, warningDays: 7, criticalDays: 14 }),
+ snapshotDefaults: () => ({
+ enabled: false,
+ warningDays: 30,
+ criticalDays: 45,
+ warningSizeGiB: 0,
+ criticalSizeGiB: 0,
+ }),
+ guestDisableConnectivity: () => false,
+ guestPoweredOffSeverity: () => 'warning' as const,
+ dockerDisableConnectivity: () => false,
+ dockerPoweredOffSeverity: () => 'warning' as const,
+ setHasUnsavedChanges,
+ } as unknown as ThresholdsTableProps;
+
+ const platform = renderHook(() =>
+ useThresholdsPlatformData({
+ props,
+ editingId,
+ searchTerm: () => '',
+ }),
+ );
+ const mutations = renderHook(() =>
+ useThresholdsOverrideMutations({
+ props,
+ resources: {
+ nodesWithOverrides: () => [],
+ agentsWithOverrides: () => [],
+ agentDisksWithOverrides: () => [],
+ dockerHostsWithOverrides: () => [],
+ guestsFlat: () => [],
+ dockerContainersFlat: () => [],
+ pbsServersWithOverrides: () => [],
+ pmgServersWithOverrides: () => [],
+ storageWithOverrides: () => [],
+ trueNASSystemsWithOverrides: platform.result.trueNASSystemsWithOverrides,
+ },
+ editingThresholds,
+ editingNote,
+ bulkEditIds,
+ cancelEdit,
+ updateBackupDefaults: vi.fn(),
+ updateSnapshotDefaults: vi.fn(),
+ }),
+ );
+
+ expect(platform.result.trueNASSystemsWithOverrides().map((resource) => resource.id)).toEqual([
+ canonicalID,
+ secondCanonicalID,
+ ]);
+
+ // AlertResourceTableRow wires number-input blur directly to saveEdit. Seed
+ // the exact table-state payload that callback receives so this regression
+ // can focus on identity stability while the shared row blur behavior stays
+ // covered by ResourceTable.test.tsx.
+ setEditingId(canonicalID);
+ setEditingThresholds({ memory: 95 });
+ expect(editingId()).toBe(canonicalID);
+ expect(editingThresholds().memory).toBe(95);
+
+ // Model a WebSocket state refresh while the input is active: resource
+ // order changes and the reported DMI serial disappears. Both systems keep
+ // the same display hostname, so only the configured connection can own
+ // the edit.
+ const repolledFirst = connectionBackedTrueNASResource({
+ machineId: '',
+ memory: 88,
+ });
+ setResources([secondSystem, repolledFirst]);
+ setOverrides(projectOverrides(rawOverridesConfig(), resources()));
+
+ expect(platform.result.trueNASSystemsWithOverrides().map((resource) => resource.id)).toEqual([
+ canonicalID,
+ secondCanonicalID,
+ ]);
+ expect(editingThresholds().memory).toBe(95);
+
+ mutations.result.saveEdit(canonicalID);
+
+ expect(rawOverridesConfig()).toEqual({
+ [canonicalID]: {
+ memory: {
+ trigger: 95,
+ clear: 90,
+ },
+ },
+ });
+ expect(rawOverridesConfig()).not.toHaveProperty(connectionID);
+ expect(rawOverridesConfig()).not.toHaveProperty(legacyCanonicalID);
+ expect(rawOverridesConfig()).not.toHaveProperty(secondCanonicalID);
+ expect(setHasUnsavedChanges).toHaveBeenCalledWith(true);
+ expect(editingId()).toBeNull();
+
+ const refreshedRows = platform.result.trueNASSystemsWithOverrides();
+ expect(refreshedRows.map((resource) => resource.id)).toEqual([secondCanonicalID, canonicalID]);
+ expect(refreshedRows.find((resource) => resource.id === canonicalID)).toEqual(
+ expect.objectContaining({
+ hasOverride: true,
+ thresholds: {
+ memory: 95,
+ },
+ }),
+ );
+ });
});
diff --git a/internal/alerts/canonical_override_migration_test.go b/internal/alerts/canonical_override_migration_test.go
index fb3e0bc15d..44cd55ce89 100644
--- a/internal/alerts/canonical_override_migration_test.go
+++ b/internal/alerts/canonical_override_migration_test.go
@@ -66,3 +66,58 @@ func TestMigrateCanonicalOverrideKeysRefusesAmbiguousOrLiveIdentity(t *testing.T
})
}
}
+
+func TestMigrateCanonicalOverrideKeysCurrentIdentityWinsAndCleansRetiredOrphan(t *testing.T) {
+ const (
+ oldID = "agent-535886018cb53055"
+ newID = "agent-b9ed6d0e20e94eaf"
+ )
+ config := AlertConfig{
+ Overrides: map[string]ThresholdConfig{
+ oldID: {
+ Memory: &HysteresisThreshold{Trigger: 90, Clear: 85},
+ },
+ newID: {
+ Memory: &HysteresisThreshold{Trigger: 95, Clear: 90},
+ },
+ },
+ }
+ resources := []unifiedresources.Resource{{
+ ID: newID,
+ SupersededCanonicalIDs: []string{oldID},
+ }}
+
+ if !MigrateCanonicalOverrideKeys(&config, resources) {
+ t.Fatal("expected the retired duplicate override to be cleaned")
+ }
+ if _, exists := config.Overrides[oldID]; exists {
+ t.Fatalf("retired duplicate override %s was not removed", oldID)
+ }
+ override := config.Overrides[newID]
+ if override.Memory == nil || override.Memory.Trigger != 95 || override.Memory.Clear != 90 {
+ t.Fatalf("current canonical override did not win: %+v", override.Memory)
+ }
+ if MigrateCanonicalOverrideKeys(&config, resources) {
+ t.Fatal("idempotent migration reported a second change")
+ }
+}
+
+func TestMigrateCanonicalOverrideKeysRetainsUnknownOrphanUntilSuccessionIsProven(t *testing.T) {
+ const orphanID = "agent-not-currently-polled"
+ config := AlertConfig{
+ Overrides: map[string]ThresholdConfig{
+ orphanID: {
+ Memory: &HysteresisThreshold{Trigger: 95, Clear: 90},
+ },
+ },
+ }
+
+ if MigrateCanonicalOverrideKeys(&config, []unifiedresources.Resource{{
+ ID: "agent-other-system",
+ }}) {
+ t.Fatal("unknown override was deleted without a provider-declared succession")
+ }
+ if _, exists := config.Overrides[orphanID]; !exists {
+ t.Fatal("transiently absent TrueNAS override was not retained for a later repoll")
+ }
+}
diff --git a/internal/monitoring/monitor_alert_override_migration_test.go b/internal/monitoring/monitor_alert_override_migration_test.go
index 8724fd83e6..254767ee00 100644
--- a/internal/monitoring/monitor_alert_override_migration_test.go
+++ b/internal/monitoring/monitor_alert_override_migration_test.go
@@ -1,7 +1,9 @@
package monitoring
import (
+ "strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
@@ -9,10 +11,76 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
-func TestSyncUnifiedResourceAlertsPersistsCanonicalOverrideSuccession(t *testing.T) {
+func trueNASMemoryAlertResource(id, supersededID, hostname string, memory float64) unifiedresources.Resource {
+ resource := unifiedresources.Resource{
+ ID: id,
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: hostname,
+ Sources: []unifiedresources.DataSource{unifiedresources.SourceTrueNAS},
+ TrueNAS: &unifiedresources.TrueNASData{Hostname: hostname},
+ Metrics: &unifiedresources.ResourceMetrics{
+ Memory: &unifiedresources.MetricValue{
+ Value: memory,
+ Percent: memory,
+ Unit: "percent",
+ Source: unifiedresources.SourceTrueNAS,
+ },
+ },
+ }
+ if supersededID != "" {
+ resource.SupersededCanonicalIDs = []string{supersededID}
+ }
+ return resource
+}
+
+func activeMemoryAlertForResource(manager *alerts.Manager, resourceID string) (alerts.Alert, bool) {
+ for _, alert := range manager.GetActiveAlerts() {
+ if alert.ResourceID == resourceID && alert.Type == "memory" {
+ return alert, true
+ }
+ }
+ return alerts.Alert{}, false
+}
+
+func waitForAlertNotification(t *testing.T, notifications <-chan alerts.Alert, resourceID string, level alerts.AlertLevel) alerts.Alert {
+ t.Helper()
+ timeout := time.NewTimer(time.Second)
+ defer timeout.Stop()
+ for {
+ select {
+ case notification := <-notifications:
+ if notification.ResourceID == resourceID && notification.Level == level {
+ return notification
+ }
+ case <-timeout.C:
+ t.Fatalf("timed out waiting for %s notification for %s", level, resourceID)
+ }
+ }
+}
+
+func waitForAlertResolution(t *testing.T, resolutions <-chan string, resourceID string) {
+ t.Helper()
+ timeout := time.NewTimer(time.Second)
+ defer timeout.Stop()
+ for {
+ select {
+ case alertID := <-resolutions:
+ if strings.Contains(alertID, resourceID) {
+ return
+ }
+ case <-timeout.C:
+ t.Fatalf("timed out waiting for resolution callback for %s", resourceID)
+ }
+ }
+}
+
+func TestSyncUnifiedResourceAlertsPersistsAndEvaluatesTrueNASOverrideSuccession(t *testing.T) {
const (
- oldID = "agent-535886018cb53055"
- newID = "agent-b9ed6d0e20e94eaf"
+ oldID = "agent-535886018cb53055"
+ newID = "agent-b9ed6d0e20e94eaf"
+ secondID = "agent-4266ee45469c27f1"
+ sharedName = "strawberrynas"
+ overridePct = 95.0
)
dataDir := t.TempDir()
@@ -21,10 +89,13 @@ func TestSyncUnifiedResourceAlertsPersistsCanonicalOverrideSuccession(t *testing
t.Cleanup(manager.Stop)
alertConfig := manager.GetConfig()
- alertConfig.Enabled = false
+ alertConfig.Enabled = true
+ alertConfig.ActivationState = alerts.ActivationActive
+ alertConfig.TrueNASDefaults.Memory = &alerts.HysteresisThreshold{Trigger: 85, Clear: 80}
+ alertConfig.TimeThresholds["truenas-system"] = 0
alertConfig.Overrides = map[string]alerts.ThresholdConfig{
oldID: {
- Memory: &alerts.HysteresisThreshold{Trigger: 95, Clear: 90},
+ Memory: &alerts.HysteresisThreshold{Trigger: overridePct, Clear: 90},
},
}
manager.UpdateConfig(alertConfig)
@@ -37,11 +108,24 @@ func TestSyncUnifiedResourceAlertsPersistsCanonicalOverrideSuccession(t *testing
configPersist: persistence,
state: models.NewState(),
}
- monitor.syncUnifiedResourceAlertsToState([]unifiedresources.Resource{{
- ID: newID,
- Type: unifiedresources.ResourceTypeAgent,
- SupersededCanonicalIDs: []string{oldID},
- }})
+ notifications := make(chan alerts.Alert, 8)
+ resolutions := make(chan string, 4)
+ manager.SetAlertCallback(func(alert *alerts.Alert) {
+ notifications <- *alert
+ })
+ manager.SetResolvedCallback(func(alertID string) {
+ resolutions <- alertID
+ })
+
+ // Two configured TrueNAS systems can legitimately report the same
+ // hostname. The first resource owns the migrated 95% threshold; the
+ // second remains on the 85% default. Reordered resource snapshots must
+ // never transfer the override between their connection-scoped IDs.
+ resources := []unifiedresources.Resource{
+ trueNASMemoryAlertResource(secondID, "", sharedName, 90),
+ trueNASMemoryAlertResource(newID, oldID, sharedName, 90),
+ }
+ monitor.syncUnifiedResourceAlertsToState(resources)
inMemory := manager.GetConfig()
if _, exists := inMemory.Overrides[oldID]; exists {
@@ -50,6 +134,14 @@ func TestSyncUnifiedResourceAlertsPersistsCanonicalOverrideSuccession(t *testing
if override := inMemory.Overrides[newID]; override.Memory == nil || override.Memory.Trigger != 95 {
t.Fatalf("in-memory override missing under canonical identity %s: %+v", newID, override)
}
+ if _, exists := activeMemoryAlertForResource(manager, newID); exists {
+ t.Fatalf("custom TrueNAS threshold fired at the default threshold for %s", newID)
+ }
+ defaultAlert, exists := activeMemoryAlertForResource(manager, secondID)
+ if !exists || defaultAlert.Threshold != 85 {
+ t.Fatalf("second TrueNAS system did not retain its independent default threshold: %+v", defaultAlert)
+ }
+ waitForAlertNotification(t, notifications, secondID, alerts.AlertLevelWarning)
reloaded, err := config.NewConfigPersistence(dataDir).LoadAlertConfig()
if err != nil {
@@ -61,4 +153,55 @@ func TestSyncUnifiedResourceAlertsPersistsCanonicalOverrideSuccession(t *testing
if override := reloaded.Overrides[newID]; override.Memory == nil || override.Memory.Trigger != 95 {
t.Fatalf("reloaded override missing under canonical identity %s: %+v", newID, override)
}
+
+ resources = []unifiedresources.Resource{
+ trueNASMemoryAlertResource(newID, oldID, sharedName, 96),
+ trueNASMemoryAlertResource(secondID, "", sharedName, 70),
+ }
+ monitor.syncUnifiedResourceAlertsToState(resources)
+ warning := waitForAlertNotification(t, notifications, newID, alerts.AlertLevelWarning)
+ waitForAlertResolution(t, resolutions, secondID)
+ if warning.Threshold != overridePct {
+ t.Fatalf("warning notification threshold = %.1f, want %.1f", warning.Threshold, overridePct)
+ }
+
+ resources[0] = trueNASMemoryAlertResource(newID, oldID, sharedName, 99)
+ monitor.syncUnifiedResourceAlertsToState(resources)
+ critical := waitForAlertNotification(t, notifications, newID, alerts.AlertLevelCritical)
+ if critical.Threshold != overridePct {
+ t.Fatalf("critical notification threshold = %.1f, want %.1f", critical.Threshold, overridePct)
+ }
+ if active, exists := activeMemoryAlertForResource(manager, newID); !exists || active.Level != alerts.AlertLevelCritical {
+ t.Fatalf("expected critical TrueNAS alert at derived 99%% escalation, got %+v", active)
+ }
+
+ resources[0] = trueNASMemoryAlertResource(newID, oldID, sharedName, 89)
+ monitor.syncUnifiedResourceAlertsToState(resources)
+ if _, exists := activeMemoryAlertForResource(manager, newID); exists {
+ t.Fatalf("TrueNAS alert did not clear below the persisted 90%% recovery threshold")
+ }
+ waitForAlertResolution(t, resolutions, newID)
+
+ // Model a process restart from alerts.json. No provider-declared legacy ID
+ // is required after migration, and a 90% sample must remain below the
+ // persisted 95% override instead of reverting to the 85% default.
+ restartedManager := alerts.NewManagerWithDataDir(t.TempDir())
+ t.Cleanup(restartedManager.Stop)
+ restartedManager.UpdateConfig(*reloaded)
+ restartedMonitor := &Monitor{
+ alertManager: restartedManager,
+ configPersist: persistence,
+ state: models.NewState(),
+ }
+ restartedMonitor.syncUnifiedResourceAlertsToState([]unifiedresources.Resource{
+ trueNASMemoryAlertResource(newID, "", sharedName, 90),
+ trueNASMemoryAlertResource(secondID, "", sharedName, 70),
+ })
+ if _, exists := activeMemoryAlertForResource(restartedManager, newID); exists {
+ t.Fatalf("restarted manager evaluated %s at the default threshold", newID)
+ }
+ restartedConfig := restartedManager.GetConfig()
+ if override := restartedConfig.Overrides[newID]; override.Memory == nil || override.Memory.Trigger != overridePct || override.Memory.Clear != 90 {
+ t.Fatalf("restarted manager lost persisted TrueNAS hysteresis: %+v", override.Memory)
+ }
}