Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Stabilize backend race tests for v6 RC publish
rcourtman05fa111ca170
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 573127e3fe..2fccf18bd2 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -290,6 +290,10 @@ an add-only capacity posture.1. Update this contract when agent lifecycle ownership changes.2. Keep shared API proof routing aligned whenever install, register, or profile payloads change.3. Update runtime and settings tests in the same slice when lifecycle behavior changes.+4. Keep host-agent test hooks, command-client factories, and timing overrides+ instance-scoped under `internal/hostagent/agent.go`; lifecycle-owned+ registration and update paths must not depend on package-global mutable test+ seams that can leak between concurrent agent sessions or tests.4. Preserve canonical /api/auto-register node identity continuity when canonical hosts shift between hostname and IP forms for the same node.5. Keep Proxmox registration continuity self-healing: stale local registration markers must be verified against Pulse before the host agent skips setup, and a missing matching node on the Pulse side must drive canonical re-registration instead of asking operators to delete marker files manually.5. Keep first-session lifecycle handoff explicit: the live setup completion@@ -2075,3 +2079,9 @@ optional optimistic hostnames. Shared row models may fall back to the row namewhen staging a removal state, but they must not resurrect legacy`policy.display` shims or require platform-managed surfaces to synthesize asecond hostname contract.+That same lifecycle boundary also owns host-agent runtime test seams. Shared+agent lifecycle code such as `internal/hostagent/agent.go` must keep mutable+test hooks, command-client factories, and timing overrides on the per-config or+per-agent instance instead of package-global variables, so concurrent+lifecycle-owned update and registration paths cannot leak one test or runtime+override into another agent session.diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 439b776240..bbe1631005 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -905,3 +905,8 @@ driven. Assistant shells may still derive legacy VM identifiers or displaylabels for read-only targeting, but they must do so through shared helpers andstore context precedence instead of passing component-local resource objects orduplicating naming fallbacks inline.+That same runtime boundary also owns executor session isolation. Shared AI+runtime services may reuse one canonical executor configuration, but each chat+or Patrol run must clone that executor before attaching resolved-context,+approval-routing, or patrol-finding state so concurrent sessions cannot+overwrite one another's mutable runtime context.diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex b2d40eb215..7ee0652c67 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -565,3 +565,14 @@ cloned into mutable feature props before crossing section boundaries, quiet-daycallbacks must preserve the canonical weekday key union, and incident timelineexpansion/note-saving state must remain `Set<string>`-owned instead of driftingto untyped browser-local collections.+That same alerts runtime boundary also owns canonical identity derivation and+active-alert persistence. Shared canonical identity helpers may infer resource,+spec, and state ids from legacy alerts, but they must do so without mutating+live in-memory alert instances unless the caller explicitly backfills that+state. Persisted active-alert snapshots must therefore clone alerts under lock,+backfill canonical identity on the clone, and serialize that snapshot instead+of mutating the live alert map during async saves or incident rebuilds.+That same ownership also governs acknowledgement and manual-clear cleanup.+Clearing an alert through the canonical alerts runtime must remove both legacy+public-id tracking and canonical-state acknowledgement records so old aliases+cannot keep an alert acknowledged after the canonical alert has been removed.diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex a7ad18105a..548711f2ac 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -738,3 +738,10 @@ disk history model, and mock seeding plus live mock ticks in`internal/monitoring/mock_metrics_history.go` must append to that same disktimeline instead of creating a second drawer-only or mock-only disk historypath.+That same monitoring runtime boundary also owns logger-safe reload behavior.+`internal/monitoring/reload.go` may refresh runtime config, but it must do so+through the no-logging-init config loader so an in-process monitoring reload+does not reinitialize the global logger while pollers, websocket writers, or+tests are still emitting logs. Runtime context access in the monitor-owned+pollers must likewise route through the monitor's synchronized accessor instead+of reading mutable shared fields directly from concurrent goroutines.diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.mdindex 0ef863ca0f..2d3cd63047 100644--- a/docs/release-control/v6/internal/subsystems/notifications.md+++ b/docs/release-control/v6/internal/subsystems/notifications.md@@ -148,6 +148,12 @@ Cancelling queued work by alert identifier must remove outstanding firingdeliveries for that alert, but it must preserve already-queued resolvednotifications so recovery deliveries cannot be dropped just because the alertwas resolved before the queue drained.+That same queue boundary also owns processor attachment semantics. The+canonical queue may persist pending notifications before a delivery processor is+configured, but it must not mark those entries sending, failed, or sent until a+processor exists. When a processor is attached, the queue owner must wake the+pending backlog through the same canonical batch path instead of relying on a+separate direct-send shortcut or waiting for an unrelated timer tick.`internal/api/notifications.go` and`frontend-modern/src/api/notifications.ts` are shared boundaries withdiff --git a/internal/agentexec/server.go b/internal/agentexec/server.goindex 1805e28bd1..1615641adb 100644--- a/internal/agentexec/server.go+++ b/internal/agentexec/server.go@@ -31,9 +31,9 @@ var (writeTextMessage = func(conn *websocket.Conn, data []byte) error {return conn.WriteMessage(websocket.TextMessage, data)}- pingInterval = 5 * time.Second- pingWriteWait = 5 * time.Second- readFileTimeout = 30 * time.Second+ defaultPingInterval = 5 * time.Second+ pingWriteWait = 5 * time.Second+ readFileTimeout = 30 * time.SeconderrServerShuttingDown = errors.New("agent execution server is shutting down"))@@ -62,6 +62,7 @@ type Server struct {validateToken func(token string, agentID string) boolshutdown chan struct{}shutdownOnce sync.Once+ pingInterval time.Duration}type agentConn struct {@@ -90,6 +91,7 @@ func NewServer(validateToken func(token string, agentID string) bool) *Server {deploySubs: make(map[string]chan DeployProgressPayload),validateToken: validateToken,shutdown: make(chan struct{}),+ pingInterval: defaultPingInterval,}}@@ -664,7 +666,7 @@ func (s *Server) readLoop(ac *agentConn) {}func (s *Server) pingLoop(ac *agentConn, done chan struct{}) {- ticker := time.NewTicker(pingInterval)+ ticker := time.NewTicker(s.pingInterval)defer ticker.Stop()// Track consecutive ping failures to detect dead connections fasterdiff --git a/internal/agentexec/server_coverage_test.go b/internal/agentexec/server_coverage_test.goindex 3b9d5b3da3..4336d7cf95 100644--- a/internal/agentexec/server_coverage_test.go+++ b/internal/agentexec/server_coverage_test.go@@ -381,11 +381,8 @@ func TestReadLoopAgentPingPongSendFailure(t *testing.T) {}func TestPingLoopSuccessAndStop(t *testing.T) {- origInterval := pingInterval- t.Cleanup(func() { pingInterval = origInterval })- pingInterval = 5 * time.Millisecond-s := NewServer(nil)+ s.pingInterval = 5 * time.MillisecondserverConn, _, cleanup := newConnPair(t)defer cleanup()@@ -402,7 +399,7 @@ func TestPingLoopSuccessAndStop(t *testing.T) {close(exited)}()- time.Sleep(2 * pingInterval)+ time.Sleep(2 * s.pingInterval)close(stop)select {@@ -413,11 +410,8 @@ func TestPingLoopSuccessAndStop(t *testing.T) {}func TestPingLoopFailuresClose(t *testing.T) {- origInterval := pingInterval- t.Cleanup(func() { pingInterval = origInterval })- pingInterval = 5 * time.Millisecond-s := NewServer(nil)+ s.pingInterval = 5 * time.MillisecondserverConn, _, cleanup := newConnPair(t)defer cleanup()diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 3c65fe6289..759a3aac32 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -450,12 +450,15 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbacvar executor *tools.PulseToolExecutorautonomousMode := falses.mu.RLock()- executor = s.executor+ baseExecutor := s.executorautonomousMode = s.autonomousModeif s.cfg != nil {configuredModel = strings.TrimSpace(s.cfg.GetChatModel())}s.mu.RUnlock()+ if baseExecutor != nil {+ executor = baseExecutor.Clone()+ }// Per-request autonomous mode override (used by investigation to avoid// mutating shared service state from concurrent goroutines).@@ -759,9 +762,13 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, careturn nil, fmt.Errorf("service not started")}sessions := s.sessions- executor := s.executor+ baseExecutor := s.executorcfg := s.cfgs.mu.RUnlock()+ executor := baseExecutor+ if baseExecutor != nil {+ executor = baseExecutor.Clone()+ }// Determine model: use patrol model or fall back to chat modelpatrolModel := ""diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.goindex 8c99f0cfca..ce1847dce4 100644--- a/internal/ai/tools/executor.go+++ b/internal/ai/tools/executor.go@@ -645,6 +645,56 @@ func NewPulseToolExecutor(cfg ExecutorConfig) *PulseToolExecutor {return e}+// Clone returns an executor instance with shared immutable providers and fresh+// session-scoped mutable state. This prevents concurrent sessions from+// overwriting each other's routing and approval context.+func (e *PulseToolExecutor) Clone() *PulseToolExecutor {+ if e == nil {+ return nil+ }++ clone := &PulseToolExecutor{+ stateProvider: e.stateProvider,+ policy: e.policy,+ agentServer: e.agentServer,+ metricsHistory: e.metricsHistory,+ baselineProvider: e.baselineProvider,+ patternProvider: e.patternProvider,+ alertProvider: e.alertProvider,+ findingsProvider: e.findingsProvider,+ backupProvider: e.backupProvider,+ replicationProvider: e.replicationProvider,+ connectionHealth: e.connectionHealth,+ recoveryPointsProvider: e.recoveryPointsProvider,+ guestConfigProvider: e.guestConfigProvider,+ appContainerConfigProvider: e.appContainerConfigProvider,+ diskHealthProvider: e.diskHealthProvider,+ updatesProvider: e.updatesProvider,+ metadataUpdater: e.metadataUpdater,+ findingsManager: e.findingsManager,+ agentProfileManager: e.agentProfileManager,+ incidentRecorderProvider: e.incidentRecorderProvider,+ eventCorrelatorProvider: e.eventCorrelatorProvider,+ knowledgeStoreProvider: e.knowledgeStoreProvider,+ discoveryProvider: e.discoveryProvider,+ unifiedResourceProvider: e.unifiedResourceProvider,+ appContainerActionProvider: e.appContainerActionProvider,+ appContainerReadProvider: e.appContainerReadProvider,+ actionAuditStore: e.actionAuditStore,+ readState: e.readState,+ controlLevel: e.controlLevel,+ protectedGuests: append([]string(nil), e.protectedGuests...),+ targetType: e.targetType,+ targetID: e.targetID,+ isAutonomous: e.isAutonomous,+ orgID: e.orgID,+ telemetryCallback: e.telemetryCallback,+ registry: e.registry,+ }+ clone.patrolFindingCreator = e.GetPatrolFindingCreator()+ return clone+}+func normalizeExecutorOrgID(orgID string) string {normalized := strings.TrimSpace(orgID)if normalized == "" {diff --git a/internal/ai/tools/executor_clone_test.go b/internal/ai/tools/executor_clone_test.gonew file mode 100644index 0000000000..c5a3b3b775--- /dev/null+++ b/internal/ai/tools/executor_clone_test.go@@ -0,0 +1,62 @@+package tools++import "testing"++func TestPulseToolExecutorCloneIsolatesSessionState(t *testing.T) {+ creator := &mockPatrolFindingCreator{}+ resolved := &mockResolvedContext{}++ original := NewPulseToolExecutor(ExecutorConfig{})+ original.SetContext("node", "node-1", false)+ original.SetOrgID("tenant-a")+ original.SetResolvedContext(resolved)+ original.SetPatrolFindingCreator(creator)+ original.protectedGuests = []string{"101"}++ clone := original.Clone()+ if clone == nil {+ t.Fatal("Clone() returned nil")+ }+ if clone == original {+ t.Fatal("Clone() returned the original executor")+ }+ if clone.GetResolvedContext() != nil {+ t.Fatal("Clone() should start without a session-scoped resolved context")+ }+ if clone.GetPatrolFindingCreator() != creator {+ t.Fatal("Clone() should retain patrol creator availability for the new run")+ }+ if clone.targetType != original.targetType || clone.targetID != original.targetID || clone.isAutonomous != original.isAutonomous {+ t.Fatalf("Clone() lost base execution context: got %q/%q/%v", clone.targetType, clone.targetID, clone.isAutonomous)+ }+ if clone.orgID != original.orgID {+ t.Fatalf("Clone() orgID = %q, want %q", clone.orgID, original.orgID)+ }++ clone.SetContext("vm", "vm-201", true)+ if original.targetType != "node" || original.targetID != "node-1" || original.isAutonomous {+ t.Fatalf("original context mutated after clone update: got %q/%q/%v", original.targetType, original.targetID, original.isAutonomous)+ }++ clone.protectedGuests[0] = "999"+ if original.protectedGuests[0] != "101" {+ t.Fatalf("protectedGuests slice is shared between clone and original: got %q", original.protectedGuests[0])+ }+}++func TestPulseToolExecutorCloneDoesNotSharePatrolCreatorSlot(t *testing.T) {+ creator := &mockPatrolFindingCreator{}++ original := NewPulseToolExecutor(ExecutorConfig{})+ original.SetPatrolFindingCreator(creator)++ clone := original.Clone()+ clone.SetPatrolFindingCreator(nil)++ if original.GetPatrolFindingCreator() != creator {+ t.Fatal("clearing patrol creator on clone mutated the original executor")+ }+ if clone.GetPatrolFindingCreator() != nil {+ t.Fatal("clone patrol creator should be independently mutable")+ }+}diff --git a/internal/alerts/ack_state.go b/internal/alerts/ack_state.goindex 25a7c7843e..1b97109d05 100644--- a/internal/alerts/ack_state.go+++ b/internal/alerts/ack_state.go@@ -6,9 +6,8 @@ func canonicalAckKey(alert *Alert, fallback string) string {if alert == nil {return fallback}- backfillCanonicalIdentity(alert)- if alert.CanonicalState != "" {- return alert.CanonicalState+ if identity := deriveCanonicalIdentity(alert); identity.State != "" {+ return identity.State}return fallback}diff --git a/internal/alerts/alert_store.go b/internal/alerts/alert_store.goindex 3ad172d59b..66e200525f 100644--- a/internal/alerts/alert_store.go+++ b/internal/alerts/alert_store.go@@ -5,9 +5,8 @@ func activeAlertStorageKey(alert *Alert, fallback string) string {return ""}if alert != nil {- backfillCanonicalIdentity(alert)- if alert.CanonicalState != "" {- return alert.CanonicalState+ if identity := deriveCanonicalIdentity(alert); identity.State != "" {+ return identity.State}if alert.ID != "" {return alert.ID@@ -18,9 +17,8 @@ func activeAlertStorageKey(alert *Alert, fallback string) string {func effectiveAlertID(alert *Alert, fallback string) string {if alert != nil {- backfillCanonicalIdentity(alert)- if alert.CanonicalState != "" {- return alert.CanonicalState+ if identity := deriveCanonicalIdentity(alert); identity.State != "" {+ return identity.State}if alert.ID != "" {return alert.ID@@ -65,8 +63,7 @@ func (m *Manager) resolveActiveAlertKeyByCanonicalStateNoLock(id string) (stringif alert == nil {continue}- backfillCanonicalIdentity(alert)- if alert.CanonicalState != id {+ if deriveCanonicalIdentity(alert).State != id {continue}if m.activeAlertAlias == nil {@@ -90,7 +87,6 @@ func (m *Manager) getActiveAlertNoLock(id string) (*Alert, bool) {if alert == nil {return nil, false}- backfillCanonicalIdentity(alert)return alert, true}diff --git a/internal/alerts/alerts.go b/internal/alerts/alerts.goindex 5279799e81..e8196ab199 100644--- a/internal/alerts/alerts.go+++ b/internal/alerts/alerts.go@@ -9736,7 +9736,16 @@ func (m *Manager) SaveActiveAlerts() error {defer m.saveMu.Unlock()m.mu.RLock()- defer m.mu.RUnlock()+ alerts := make([]*Alert, 0, len(m.activeAlerts))+ for _, alert := range m.activeAlerts {+ if alert == nil {+ continue+ }+ clone := alert.Clone()+ backfillCanonicalIdentity(clone)+ alerts = append(alerts, clone)+ }+ m.mu.RUnlock()// Create directory if it doesn't existalertsDir := m.getAlertsDir()@@ -9747,12 +9756,6 @@ func (m *Manager) SaveActiveAlerts() error {return fmt.Errorf("failed to set alerts directory permissions: %w", err)}- // Convert map to slice for JSON encoding- alerts := make([]*Alert, 0, len(m.activeAlerts))- for _, alert := range m.activeAlerts {- alerts = append(alerts, alert)- }-data, err := json.Marshal(alerts)if err != nil {return fmt.Errorf("failed to marshal active alerts: %w", err)@@ -10384,10 +10387,27 @@ func (m *Manager) cleanupStaleMaps() {func (m *Manager) CheckDiskHealth(instance, node string, disk proxmox.Disk) {// Create unique alert ID for this diskalertID := fmt.Sprintf("disk-health-%s-%s-%s", instance, node, disk.DevPath)+ wearoutAlertID := fmt.Sprintf("disk-wearout-%s-%s-%s", instance, node, disk.DevPath)resourceID := fmt.Sprintf("%s-%s", node, disk.DevPath)resourceName := fmt.Sprintf("%s (%s)", disk.Model, disk.DevPath)canonicalResourceID := proxmoxDiskCanonicalResourceID(instance, node, disk.DevPath)resourceType := unifiedresources.ResourceType("proxmox-disk")+ canonicalHealthAlertID := buildCanonicalStateID(canonicalResourceID, canonicalResourceID+"-health")+ canonicalWearoutAlertID := buildCanonicalStateID(canonicalResourceID, canonicalResourceID+"-wearout")++ clearDiskAlert := func(ids ...string) {+ seen := make(map[string]struct{}, len(ids))+ for _, id := range ids {+ if id == "" {+ continue+ }+ if _, exists := seen[id]; exists {+ continue+ }+ seen[id] = struct{}{}+ m.clearAlert(id)+ }+ }// Check if disk health is not PASSEDnormalizedHealth := strings.ToUpper(strings.TrimSpace(disk.Health))@@ -10404,8 +10424,9 @@ func (m *Manager) CheckDiskHealth(instance, node string, disk proxmox.Disk) {Str("health", disk.Health).Msg("Skipping health alert for drive with known firmware bug - health status unreliable")- // Clear any existing health alert since we now recognize this is a false positive- m.clearAlert(buildCanonicalStateID(canonicalResourceID, canonicalResourceID+"-health"))+ // Clear any existing health alert since we now recognize this is a false positive.+ // Older installs may still have the legacy alert key persisted on disk.+ clearDiskAlert(alertID, canonicalHealthAlertID)healthCheckNeeded = false // Skip to wearout check}@@ -10452,12 +10473,11 @@ func (m *Manager) CheckDiskHealth(instance, node string, disk proxmox.Disk) {}} else {// Disk is healthy, clear alert if it exists- m.clearAlert(buildCanonicalStateID(canonicalResourceID, canonicalResourceID+"-health"))+ clearDiskAlert(alertID, canonicalHealthAlertID)}// Check for low wearout (SSD life remaining)if disk.Wearout > 0 && disk.Wearout < 10 {- wearoutAlertID := fmt.Sprintf("disk-wearout-%s-%s-%s", instance, node, disk.DevPath)message := fmt.Sprintf("SSD has less than 10%% life remaining (%d%% wearout)", disk.Wearout)spec, err := buildCanonicalSeverityThresholdSpecWithDirection(canonicalResourceID+"-wearout", canonicalResourceID, resourceName, resourceType, "wearout-remaining", alertspecs.ThresholdDirectionBelow, 10, 0, false)if err != nil {@@ -10503,7 +10523,7 @@ func (m *Manager) CheckDiskHealth(instance, node string, disk proxmox.Disk) {}} else if disk.Wearout >= 10 {// Wearout is acceptable, clear alert if it exists- m.clearAlert(buildCanonicalStateID(canonicalResourceID, canonicalResourceID+"-wearout"))+ clearDiskAlert(wearoutAlertID, canonicalWearoutAlertID)}}diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.goindex 86dd5be042..df9772f240 100644--- a/internal/alerts/alerts_test.go+++ b/internal/alerts/alerts_test.go@@ -17336,3 +17336,93 @@ func TestNamespaceMatchesInstance(t *testing.T) {})}}++func TestSaveActiveAlertsBackfillsCanonicalIdentityOnDiskWithoutMutatingLiveAlert(t *testing.T) {+ m := newTestManager(t)++ liveAlert := &Alert{+ ID: "node-offline-pve-a",+ Type: "connectivity",+ Level: AlertLevelWarning,+ Node: "pve-a",+ Message: "node offline",+ StartTime: time.Now().Add(-time.Minute),+ LastSeen: time.Now(),+ }++ m.mu.Lock()+ m.activeAlerts[liveAlert.ID] = liveAlert+ m.mu.Unlock()++ if err := m.SaveActiveAlerts(); err != nil {+ t.Fatalf("SaveActiveAlerts() error = %v", err)+ }++ if liveAlert.ResourceID != "" || liveAlert.CanonicalSpecID != "" || liveAlert.CanonicalState != "" || liveAlert.CanonicalKind != "" {+ t.Fatalf("SaveActiveAlerts mutated the live alert: %+v", liveAlert)+ }++ data, err := os.ReadFile(filepath.Join(m.getAlertsDir(), "active-alerts.json"))+ if err != nil {+ t.Fatalf("ReadFile(active-alerts.json) error = %v", err)+ }++ var persisted []*Alert+ if err := json.Unmarshal(data, &persisted); err != nil {+ t.Fatalf("unmarshal persisted alerts: %v", err)+ }+ if len(persisted) != 1 {+ t.Fatalf("persisted alerts length = %d, want 1", len(persisted))+ }++ wantState := "pve-a::pve-a-connectivity"+ if persisted[0].ResourceID != "pve-a" {+ t.Fatalf("persisted ResourceID = %q, want %q", persisted[0].ResourceID, "pve-a")+ }+ if persisted[0].CanonicalSpecID != "pve-a-connectivity" {+ t.Fatalf("persisted CanonicalSpecID = %q, want %q", persisted[0].CanonicalSpecID, "pve-a-connectivity")+ }+ if persisted[0].CanonicalState != wantState {+ t.Fatalf("persisted CanonicalState = %q, want %q", persisted[0].CanonicalState, wantState)+ }+ if persisted[0].CanonicalKind != "connectivity" {+ t.Fatalf("persisted CanonicalKind = %q, want %q", persisted[0].CanonicalKind, "connectivity")+ }+}++func TestSetAckRecordUsesCanonicalKeyWithoutMutatingLiveAlert(t *testing.T) {+ m := newTestManager(t)++ alert := &Alert{+ ID: "node-offline-pve-a",+ Type: "connectivity",+ Level: AlertLevelWarning,+ Node: "pve-a",+ Message: "node offline",+ StartTime: time.Now().Add(-time.Minute),+ LastSeen: time.Now(),+ }++ m.mu.Lock()+ m.setAckRecordNoLock(alert, alert.ID, ackRecord{+ acknowledged: true,+ user: "tester",+ time: time.Now(),+ })+ m.mu.Unlock()++ if alert.ResourceID != "" || alert.CanonicalSpecID != "" || alert.CanonicalKind != "" || alert.CanonicalState != "" {+ t.Fatalf("setAckRecordNoLock mutated the live alert: %+v", alert)+ }++ canonicalKey := "pve-a::pve-a-connectivity"++ m.mu.RLock()+ defer m.mu.RUnlock()+ if _, ok := m.ackStateByCanonical[canonicalKey]; !ok {+ t.Fatalf("expected canonical ack record for %q", canonicalKey)+ }+ if _, ok := m.ackState[alert.ID]; ok {+ t.Fatalf("legacy ack record for %q should have been removed in favor of canonical state", alert.ID)+ }+}diff --git a/internal/alerts/canonical_identity.go b/internal/alerts/canonical_identity.goindex 3cedb28b32..289061ce86 100644--- a/internal/alerts/canonical_identity.go+++ b/internal/alerts/canonical_identity.go@@ -99,6 +99,56 @@ func backfillCanonicalIdentity(alert *Alert) {}}+type canonicalIdentity struct {+ ResourceID string+ SpecID string+ Kind string+ State string+}++func deriveCanonicalIdentity(alert *Alert) canonicalIdentity {+ if alert == nil {+ return canonicalIdentity{}+ }++ resourceID := alert.ResourceID+ if resourceID == "" {+ resourceID = inferCanonicalResourceIDFromLegacyAlert(alert)+ }++ specID := alert.CanonicalSpecID+ if specID == "" && alert.Metadata != nil {+ if value, ok := alert.Metadata["canonicalSpecID"].(string); ok {+ specID = value+ }+ }+ if specID == "" {+ specID = inferCanonicalSpecIDFromLegacyAlert(alert)+ }++ kind := alert.CanonicalKind+ if kind == "" && alert.Metadata != nil {+ if value, ok := alert.Metadata["canonicalAlertKind"].(string); ok {+ kind = value+ }+ }+ if kind == "" {+ kind = inferCanonicalKindFromLegacyAlert(alert)+ }++ state := alert.CanonicalState+ if state == "" {+ state = buildCanonicalStateID(resourceID, specID)+ }++ return canonicalIdentity{+ ResourceID: resourceID,+ SpecID: specID,+ Kind: kind,+ State: state,+ }+}+func inferCanonicalResourceIDFromLegacyAlert(alert *Alert) string {if alert == nil {return ""@@ -300,9 +350,8 @@ func applyCanonicalIdentity(alert *Alert, specID, kind string) {func exportedAlertID(alert *Alert, fallback string) string {if alert != nil {- backfillCanonicalIdentity(alert)- if alert.CanonicalState != "" {- return alert.CanonicalState+ if identity := deriveCanonicalIdentity(alert); identity.State != "" {+ return identity.State}if alert.ID != "" {return alert.ID@@ -348,9 +397,8 @@ func canonicalTrackingKeyForAlert(alert *Alert) string {if alert == nil {return ""}- backfillCanonicalIdentity(alert)- if alert.CanonicalState != "" {- return alert.CanonicalState+ if identity := deriveCanonicalIdentity(alert); identity.State != "" {+ return identity.State}return alert.ID}diff --git a/internal/alerts/unified_incidents_test.go b/internal/alerts/unified_incidents_test.goindex 5c9209998b..64ecec03c3 100644--- a/internal/alerts/unified_incidents_test.go+++ b/internal/alerts/unified_incidents_test.go@@ -854,3 +854,31 @@ func TestSyncUnifiedResourceIncidentsRespectsDisableAllStorage(t *testing.T) {alertID := "unified-incident-disk-ada0-truenas-alert-2-truenas-smart"assertAlertMissing(t, m, alertID)}++func TestDeriveCanonicalIdentityDoesNotMutateLegacyAlert(t *testing.T) {+ alert := &Alert{+ ID: "node-offline-pve-a",+ Type: "connectivity",+ Node: "pve-a",+ Message: "node offline",+ }++ identity := deriveCanonicalIdentity(alert)++ if identity.ResourceID != "pve-a" {+ t.Fatalf("ResourceID = %q, want %q", identity.ResourceID, "pve-a")+ }+ if identity.SpecID != "pve-a-connectivity" {+ t.Fatalf("SpecID = %q, want %q", identity.SpecID, "pve-a-connectivity")+ }+ if identity.Kind != "connectivity" {+ t.Fatalf("Kind = %q, want %q", identity.Kind, "connectivity")+ }+ if identity.State != "pve-a::pve-a-connectivity" {+ t.Fatalf("State = %q, want %q", identity.State, "pve-a::pve-a-connectivity")+ }++ if alert.ResourceID != "" || alert.CanonicalSpecID != "" || alert.CanonicalKind != "" || alert.CanonicalState != "" {+ t.Fatalf("deriveCanonicalIdentity mutated legacy alert: %+v", alert)+ }+}diff --git a/internal/api/org_handlers_test.go b/internal/api/org_handlers_test.goindex cb8601b319..9f98c13b69 100644--- a/internal/api/org_handlers_test.go+++ b/internal/api/org_handlers_test.go@@ -12,14 +12,46 @@ import ("testing""github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/logging""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/monitoring"internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"- "github.com/rs/zerolog"- "github.com/rs/zerolog/log")+type testLogCapture struct {+ id string+ lines chan string+ buf strings.Builder+}++func newTestLogCapture(t *testing.T) *testLogCapture {+ t.Helper()+ id, lines, _ := logging.GetBroadcaster().Subscribe()+ capture := &testLogCapture{id: id, lines: lines}+ t.Cleanup(func() {+ logging.GetBroadcaster().Unsubscribe(id)+ })+ return capture+}++func (c *testLogCapture) String() string {+ for {+ select {+ case line, ok := <-c.lines:+ if !ok {+ return c.buf.String()+ }+ c.buf.WriteString(line)+ if !strings.HasSuffix(line, "\n") {+ c.buf.WriteByte('\n')+ }+ default:+ return c.buf.String()+ }+ }+}+func TestOrgHandlersRequireMultiTenantGate_HostedModeBypassesFeatureLicense(t *testing.T) {defer SetMultiTenantEnabled(false)SetMultiTenantEnabled(false)@@ -96,12 +128,7 @@ func TestOrgHandlersDeleteStopsTenantMonitorBeforeDeletingOrgDir(t *testing.T) {defer SetMultiTenantEnabled(false)SetMultiTenantEnabled(true)- var logOutput bytes.Buffer- origLogger := log.Logger- log.Logger = zerolog.New(&logOutput).Level(zerolog.DebugLevel).With().Timestamp().Logger()- t.Cleanup(func() {- log.Logger = origLogger- })+ logOutput := newTestLogCapture(t)baseDir := t.TempDir()persistence := config.NewMultiTenantPersistence(baseDir)diff --git a/internal/api/router_integration_test.go b/internal/api/router_integration_test.goindex ba70710e13..f0cde54ca8 100644--- a/internal/api/router_integration_test.go+++ b/internal/api/router_integration_test.go@@ -1526,9 +1526,15 @@ func TestWebSocketSendsInitialState(t *testing.T) {state := srv.monitor.BuildFrontendState()srv.hub.BroadcastState(state)- msgType, payload = readMsg()- if msgType != "rawData" {- t.Fatalf("expected rawData broadcast, got %q", msgType)+ deadline := time.Now().Add(2 * time.Second)+ for {+ msgType, payload = readMsg()+ if msgType == "rawData" {+ break+ }+ if time.Now().After(deadline) {+ t.Fatalf("expected rawData broadcast before deadline, got %q", msgType)+ }}for _, key := range legacyKeys {if _, ok := payload[key]; ok {diff --git a/internal/cloudcp/auth/magiclink_store.go b/internal/cloudcp/auth/magiclink_store.goindex 8062bb5730..d038cb186a 100644--- a/internal/cloudcp/auth/magiclink_store.go+++ b/internal/cloudcp/auth/magiclink_store.go@@ -173,8 +173,9 @@ func (s *Store) Put(tokenHash []byte, rec *TokenRecord) error {if rec == nil || rec.Email == "" || rec.ExpiresAt.IsZero() {return fmt.Errorf("token record is required")}- if strings.TrimSpace(rec.Target) == "" {- rec.Target = string(MagicLinkTargetTenant)+ target := strings.TrimSpace(rec.Target)+ if target == "" {+ target = string(MagicLinkTargetTenant)}key := hex.EncodeToString(tokenHash)@@ -190,7 +191,7 @@ func (s *Store) Put(tokenHash []byte, rec *TokenRecord) error {_, err := db.Exec(`INSERT OR REPLACE INTO magic_link_tokens (token_hash, email, tenant_id, target, expires_at, used, created_at, used_at)VALUES (?, ?, ?, ?, ?, 0, ?, NULL)`,- key, rec.Email, rec.TenantID, rec.Target, rec.ExpiresAt.UTC().Unix(), now,+ key, rec.Email, rec.TenantID, target, rec.ExpiresAt.UTC().Unix(), now,)if err != nil {return fmt.Errorf("put magic link token: %w", err)diff --git a/internal/config/config.go b/internal/config/config.goindex 2df0c6361d..92bafe0198 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -663,8 +663,19 @@ func parsePollingIntervalEnv(envName string, minDuration time.Duration) (time.Dureturn 0, false}-// Load reads configuration from encrypted persistence files+// Load reads configuration from encrypted persistence files.func Load() (*Config, error) {+ return load(true)+}++// LoadWithoutLoggingInit reads configuration without reinitializing the global logger.+// Reload paths use this to avoid racing with long-lived background goroutines that are+// still emitting through zerolog/log while the new config is being loaded.+func LoadWithoutLoggingInit() (*Config, error) {+ return load(false)+}++func load(initLogging bool) (*Config, error) {// Get data directory from environmentdataDir := ResolveRuntimeDataDir("")@@ -1549,16 +1560,18 @@ func Load() (*Config, error) {}}- // Initialize logging with configuration values- logging.Init(logging.Config{- Format: cfg.LogFormat,- Level: cfg.LogLevel,- Component: "pulse-config",- FilePath: cfg.LogFile,- MaxSizeMB: cfg.LogMaxSize,- MaxAgeDays: cfg.LogMaxAge,- Compress: cfg.LogCompress,- })+ if initLogging {+ // Initialize logging with configuration values+ logging.Init(logging.Config{+ Format: cfg.LogFormat,+ Level: cfg.LogLevel,+ Component: "pulse-config",+ FilePath: cfg.LogFile,+ MaxSizeMB: cfg.LogMaxSize,+ MaxAgeDays: cfg.LogMaxAge,+ Compress: cfg.LogCompress,+ })+ }// Initialize DNS cache with configured timeout// This must be done before any HTTP clients are createddiff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.goindex c61fe41f7b..27af3cd900 100644--- a/internal/hostagent/agent.go+++ b/internal/hostagent/agent.go@@ -66,6 +66,10 @@ type Config struct {DisableCeph bool // If true, disables local Ceph status pollingCollector SystemCollector // Optional: override default system information collector (for testing)++ newCommandClientFn func(Config, string, string, string, string) *CommandClient+ runCommandClientFn func(*CommandClient, context.Context) error+ updatedFromVersionFn func() string}// Agent is responsible for collecting host metrics and shipping them to Pulse.@@ -96,6 +100,8 @@ type Agent struct {commandClientRunCancel context.CancelFunccommandClientParentCtx context.Contextcollector SystemCollector+ newCommandClient func(Config, string, string, string, string) *CommandClient+ runCommandClient func(*CommandClient, context.Context) error}const defaultInterval = 30 * time.Second@@ -112,12 +118,6 @@ func (e *reportHTTPStatusError) Error() string {return fmt.Sprintf("pulse responded with status %s", e.Status)}-var newCommandClient = NewCommandClient-var runCommandClient = func(client *CommandClient, ctx context.Context) error {- return client.Run(ctx)-}-var getUpdatedFromVersion = agentupdate.GetUpdatedFromVersion-// New constructs a fully initialised runtime-side Unified Agent.func New(cfg Config) (*Agent, error) {if cfg.Interval <= 0 {@@ -175,6 +175,20 @@ func New(cfg Config) (*Agent, error) {if collector == nil {collector = &defaultCollector{}}+ newCommandClientFn := cfg.newCommandClientFn+ if newCommandClientFn == nil {+ newCommandClientFn = NewCommandClient+ }+ runCommandClientFn := cfg.runCommandClientFn+ if runCommandClientFn == nil {+ runCommandClientFn = func(client *CommandClient, ctx context.Context) error {+ return client.Run(ctx)+ }+ }+ updatedFromVersionFn := cfg.updatedFromVersionFn+ if updatedFromVersionFn == nil {+ updatedFromVersionFn = agentupdate.GetUpdatedFromVersion+ }info, err := collector.HostInfo(ctx)if err != nil {@@ -257,7 +271,7 @@ func New(cfg Config) (*Agent, error) {const bufferCapacity = 60// Check if agent was recently auto-updated (only reported once per restart)- updatedFrom := getUpdatedFromVersion()+ updatedFrom := updatedFromVersionFn()if updatedFrom != "" {logger.Info().Str("previousVersion", updatedFrom).@@ -266,32 +280,34 @@ func New(cfg Config) (*Agent, error) {}agent := &Agent{- cfg: cfg,- logger: logger,- httpClient: client,- hostInfo: info,- hostname: hostname,- displayName: displayName,- platform: platform,- osName: osName,- osVersion: osVersion,- kernelVersion: kernelVersion,- architecture: arch,- machineID: machineID,- agentID: agentID,- agentVersion: agentVersion,- updatedFrom: updatedFrom,- reportIP: cfg.ReportIP,- stateDir: cfg.StateDir,- interval: cfg.Interval,- trimmedPulseURL: pulseURL,- reportBuffer: utils.New[agentshost.Report](bufferCapacity),- collector: collector,+ cfg: cfg,+ logger: logger,+ httpClient: client,+ hostInfo: info,+ hostname: hostname,+ displayName: displayName,+ platform: platform,+ osName: osName,+ osVersion: osVersion,+ kernelVersion: kernelVersion,+ architecture: arch,+ machineID: machineID,+ agentID: agentID,+ agentVersion: agentVersion,+ updatedFrom: updatedFrom,+ reportIP: cfg.ReportIP,+ stateDir: cfg.StateDir,+ interval: cfg.Interval,+ trimmedPulseURL: pulseURL,+ reportBuffer: utils.New[agentshost.Report](bufferCapacity),+ collector: collector,+ newCommandClient: newCommandClientFn,+ runCommandClient: runCommandClientFn,}// Create command client for AI command execution (only if enabled)if cfg.EnableCommands {- agent.commandClient = newCommandClient(cfg, agentID, hostname, platform, agentVersion)+ agent.commandClient = newCommandClientFn(cfg, agentID, hostname, platform, agentVersion)cfg.Logger.Info().Msg("Command execution enabled via --enable-commands flag")} else {cfg.Logger.Info().Msg("Command execution disabled (use --enable-commands to enable)")@@ -356,7 +372,7 @@ func (a *Agent) Run(ctx context.Context) error {// original was built with the bootstrap token during New().if a.cfg.EnableCommands {a.commandClientMu.Lock()- a.commandClient = newCommandClient(a.cfg, a.agentID, a.hostname, a.platform, a.agentVersion)+ a.commandClient = a.newCommandClient(a.cfg, a.agentID, a.hostname, a.platform, a.agentVersion)commandClient = a.commandClienta.commandClientMu.Unlock()}@@ -424,7 +440,7 @@ func (a *Agent) startCommandClient(client *CommandClient) {a.commandClientMu.Unlock()go func() {- if err := runCommandClient(client, runCtx); err != nil && !errors.Is(err, context.Canceled) {+ if err := a.runCommandClient(client, runCtx); err != nil && !errors.Is(err, context.Canceled) {a.logger.Error().Err(err).Msg("Command client stopped with error")}}()@@ -799,7 +815,7 @@ func (a *Agent) applyRemoteConfig(commandsEnabled bool) {currentlyEnabled := a.commandClient != nilswitch {case commandsEnabled && !currentlyEnabled:- clientToStart = NewCommandClient(a.cfg, a.agentID, a.hostname, a.platform, a.agentVersion)+ clientToStart = a.newCommandClient(a.cfg, a.agentID, a.hostname, a.platform, a.agentVersion)a.commandClient = clientToStartcase !commandsEnabled && currentlyEnabled:shouldStop = truediff --git a/internal/hostagent/agent_new_test.go b/internal/hostagent/agent_new_test.goindex 8125c94206..3f7363f426 100644--- a/internal/hostagent/agent_new_test.go+++ b/internal/hostagent/agent_new_test.go@@ -204,11 +204,6 @@ func TestNew_UsesCustomCABundleForHTTPTransport(t *testing.T) {}func TestNew_CarriesUpdatedFromIntoFirstV6Report(t *testing.T) {- origGetUpdatedFromVersion := getUpdatedFromVersion- t.Cleanup(func() { getUpdatedFromVersion = origGetUpdatedFromVersion })-- getUpdatedFromVersion = func() string { return "5.1.14" }-fixedTime := time.Date(2026, time.March, 12, 9, 10, 11, 0, time.UTC)mc := &mockCollector{nowFn: func() time.Time { return fixedTime },@@ -235,12 +230,13 @@ func TestNew_CarriesUpdatedFromIntoFirstV6Report(t *testing.T) {}agent, err := New(Config{- APIToken: "token",- AgentID: "agent-1",- AgentType: "unified",- AgentVersion: "6.0.0-rc.1",- LogLevel: zerolog.InfoLevel,- Collector: mc,+ APIToken: "token",+ AgentID: "agent-1",+ AgentType: "unified",+ AgentVersion: "6.0.0-rc.1",+ LogLevel: zerolog.InfoLevel,+ Collector: mc,+ updatedFromVersionFn: func() string { return "5.1.14" },})if err != nil {t.Fatalf("New: %v", err)diff --git a/internal/hostagent/hostagent_coverage_test.go b/internal/hostagent/hostagent_coverage_test.goindex 394dd310db..a998b3219e 100644--- a/internal/hostagent/hostagent_coverage_test.go+++ b/internal/hostagent/hostagent_coverage_test.go@@ -110,15 +110,7 @@ func TestAgent_RunProxmoxSetup(t *testing.T) {}func TestAgent_ApplyRemoteConfig_DefersCommandStartWithoutRunContext(t *testing.T) {- originalRun := runCommandClient- defer func() { runCommandClient = originalRun }()-started := make(chan struct{}, 1)- runCommandClient = func(_ *CommandClient, ctx context.Context) error {- started <- struct{}{}- <-ctx.Done()- return ctx.Err()- }mc := &mockCollector{}logger := zerolog.Nop()@@ -127,6 +119,11 @@ func TestAgent_ApplyRemoteConfig_DefersCommandStartWithoutRunContext(t *testing.PulseURL: "https://pulse",Collector: mc,Logger: &logger,+ runCommandClientFn: func(_ *CommandClient, ctx context.Context) error {+ started <- struct{}{}+ <-ctx.Done()+ return ctx.Err()+ },})if a == nil {t.Fatal("expected agent")@@ -157,17 +154,8 @@ func TestAgent_ApplyRemoteConfig_DefersCommandStartWithoutRunContext(t *testing.}func TestAgent_CommandClientLifecycle_StopCancelsContext(t *testing.T) {- originalRun := runCommandClient- defer func() { runCommandClient = originalRun }()-started := make(chan struct{})stopped := make(chan struct{})- runCommandClient = func(_ *CommandClient, ctx context.Context) error {- close(started)- <-ctx.Done()- close(stopped)- return ctx.Err()- }mc := &mockCollector{}logger := zerolog.Nop()@@ -177,6 +165,12 @@ func TestAgent_CommandClientLifecycle_StopCancelsContext(t *testing.T) {EnableCommands: true,Collector: mc,Logger: &logger,+ runCommandClientFn: func(_ *CommandClient, ctx context.Context) error {+ close(started)+ <-ctx.Done()+ close(stopped)+ return ctx.Err()+ },})if a == nil {t.Fatal("expected agent")diff --git a/internal/logging/logging.go b/internal/logging/logging.goindex 4381e0dd22..7d9497386d 100644--- a/internal/logging/logging.go+++ b/internal/logging/logging.go@@ -84,6 +84,7 @@ var ()func init() {+ baseWriter = io.MultiWriter(baseWriter, GetBroadcaster())baseLogger = zerolog.New(baseWriter).With().Timestamp().Logger()log.Logger = baseLogger}diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex c6b3fc61ea..f321f2a695 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -1175,3 +1175,45 @@ func TestTelemetrySnapshotAggregationUsesProvisionedTenantSet(t *testing.T) {t.Fatalf("ActiveAlerts = %d, want 3 across provisioned tenants", counts.ActiveAlerts)}}++func TestReloadAndRuntimeContextStayOnCanonicalMonitoringPath(t *testing.T) {+ requiredSnippets := map[string][]string{+ "reload.go": {+ "config.LoadWithoutLoggingInit()",+ },+ "monitor.go": {+ "func (m *Monitor) setRuntimeContext(ctx context.Context, hub *websocket.Hub) {",+ "func (m *Monitor) getRuntimeContext() context.Context {",+ "m.setRuntimeContext(ctx, wsHub)",+ },+ "monitor_backups.go": {+ "parentCtx := m.getRuntimeContext()",+ },+ "monitor_pve.go": {+ "parentCtx := m.getRuntimeContext()",+ },+ "monitor_pve_storage.go": {+ "parentCtx := m.getRuntimeContext()",+ },+ "monitor_pbs_pmg.go": {+ "parentCtx := m.getRuntimeContext()",+ },+ "../config/config.go": {+ "func LoadWithoutLoggingInit() (*Config, error) {",+ "return load(false)",+ },+ }++ for file, snippets := range requiredSnippets {+ data, err := os.ReadFile(file)+ if err != nil {+ t.Fatalf("failed to read %s: %v", file, err)+ }+ source := string(data)+ for _, snippet := range snippets {+ if !strings.Contains(source, snippet) {+ t.Fatalf("%s must contain %q", file, snippet)+ }+ }+ }+}diff --git a/internal/monitoring/log_capture_test.go b/internal/monitoring/log_capture_test.gonew file mode 100644index 0000000000..72c118cfda--- /dev/null+++ b/internal/monitoring/log_capture_test.go@@ -0,0 +1,50 @@+package monitoring++import (+ "strings"+ "sync"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/logging"+)++type monitoringLogCapture struct {+ id string+ lines chan string+ mu sync.Mutex+ buf strings.Builder+}++func newMonitoringLogCapture(t *testing.T) *monitoringLogCapture {+ t.Helper()++ id, lines, _ := logging.GetBroadcaster().Subscribe()+ capture := &monitoringLogCapture{+ id: id,+ lines: lines,+ }+ t.Cleanup(func() {+ logging.GetBroadcaster().Unsubscribe(id)+ })+ return capture+}++func (c *monitoringLogCapture) String() string {+ c.mu.Lock()+ defer c.mu.Unlock()++ for {+ select {+ case line, ok := <-c.lines:+ if !ok {+ return c.buf.String()+ }+ c.buf.WriteString(line)+ if !strings.HasSuffix(line, "\n") {+ c.buf.WriteByte('\n')+ }+ default:+ return c.buf.String()+ }+ }+}diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.goindex 2bef80947c..9bbf8f4d44 100644--- a/internal/monitoring/mock_metrics_history_test.go+++ b/internal/monitoring/mock_metrics_history_test.go@@ -644,6 +644,15 @@ func TestSeedMockMetricsHistory_UsesCanonicalMockFixtureGraphForLegacyAndProvide}now := time.Now()+ seedDuration := 7 * 24 * time.Hour+ sampleInterval := time.Minute+ historyRetention := 7 * 24 * time.Hour+ if raceEnabled {+ seedDuration = 2 * time.Hour+ sampleInterval = 30 * time.Minute+ historyRetention = 2 * time.Hour+ }+cfg := metrics.DefaultConfig(t.TempDir())cfg.RetentionRaw = 90 * 24 * time.Hourcfg.RetentionMinute = 90 * 24 * time.Hour@@ -657,10 +666,10 @@ func TestSeedMockMetricsHistory_UsesCanonicalMockFixtureGraphForLegacyAndProvide}defer store.Close()- mh := NewMetricsHistory(1000, 7*24*time.Hour)- seedMockMetricsHistory(mh, store, graph, now, 7*24*time.Hour, time.Minute)+ mh := NewMetricsHistory(1000, historyRetention)+ seedMockMetricsHistory(mh, store, graph, now, seedDuration, sampleInterval)- nodePoints, err := store.Query("node", graph.State.Nodes[0].ID, "cpu", now.Add(-7*24*time.Hour), now, 3600)+ nodePoints, err := store.Query("node", graph.State.Nodes[0].ID, "cpu", now.Add(-seedDuration), now, 3600)if err != nil {t.Fatalf("failed to query legacy mock node cpu metrics: %v", err)}@@ -668,7 +677,7 @@ func TestSeedMockMetricsHistory_UsesCanonicalMockFixtureGraphForLegacyAndProvidet.Fatal("expected seeded legacy mock node cpu metrics from canonical graph state")}- truenasPoints, err := store.Query("agent", graph.PlatformFixtures.TrueNAS.System.Hostname, "disk", now.Add(-7*24*time.Hour), now, 3600)+ truenasPoints, err := store.Query("agent", graph.PlatformFixtures.TrueNAS.System.Hostname, "disk", now.Add(-seedDuration), now, 3600)if err != nil {t.Fatalf("failed to query canonical TrueNAS agent disk metrics: %v", err)}@@ -677,7 +686,7 @@ func TestSeedMockMetricsHistory_UsesCanonicalMockFixtureGraphForLegacyAndProvide}vmwareHostID := "vc-mock-1:host:host-101"- vmwarePoints, err := store.Query("agent", vmwareHostID, "cpu", now.Add(-7*24*time.Hour), now, 3600)+ vmwarePoints, err := store.Query("agent", vmwareHostID, "cpu", now.Add(-seedDuration), now, 3600)if err != nil {t.Fatalf("failed to query VMware mock host cpu metrics: %v", err)}diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 2c5e2d2af6..1410f3f29d 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1002,6 +1002,19 @@ type Monitor struct {mockChartMapCache map[mockChartMetricMapCacheKey]map[string][]MetricPoint}+func (m *Monitor) setRuntimeContext(ctx context.Context, hub *websocket.Hub) {+ m.mu.Lock()+ defer m.mu.Unlock()+ m.runtimeCtx = ctx+ m.wsHub = hub+}++func (m *Monitor) getRuntimeContext() context.Context {+ m.mu.RLock()+ defer m.mu.RUnlock()+ return m.runtimeCtx+}+// clusterSensorsCacheEntry stores temperature data collected by a sibling agent via SSH.type clusterSensorsCacheEntry struct {sensors models.HostSensorSummary@@ -1691,10 +1704,7 @@ func (m *Monitor) Start(ctx context.Context, wsHub *websocket.Hub) {Dur("pollingInterval", pollingInterval).Msg("Starting monitoring loop")- m.mu.Lock()- m.runtimeCtx = ctx- m.wsHub = wsHub- m.mu.Unlock()+ m.setRuntimeContext(ctx, wsHub)defer m.stopMockMetricsSampler()// Best-effort startup cleanup: when direct PBS is configured, remove legacydiff --git a/internal/monitoring/monitor_backups.go b/internal/monitoring/monitor_backups.goindex 7170a5b1a1..615e603209 100644--- a/internal/monitoring/monitor_backups.go+++ b/internal/monitoring/monitor_backups.go@@ -1586,7 +1586,7 @@ func (m *Monitor) pollPVEBackupsAsync(// The per-cycle ctx is canceled as soon as the main polling loop finishes,// so derive the backup poll context from the long-lived runtime context instead.- parentCtx := m.runtimeCtx+ parentCtx := m.getRuntimeContext()if parentCtx == nil {parentCtx = context.Background()}diff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.goindex a36033d970..77c499d814 100644--- a/internal/monitoring/monitor_metrics_slo_test.go+++ b/internal/monitoring/monitor_metrics_slo_test.go@@ -11,8 +11,6 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/pkg/metrics"- "github.com/rs/zerolog"- "github.com/rs/zerolog/log")// Monitoring-layer SLO targets for batched chart retrieval.@@ -51,9 +49,6 @@ func skipMonitoringSLOUnderRace(t *testing.T) {func suppressMonitoringTestLogs(t *testing.T) {t.Helper()- orig := log.Logger- log.Logger = zerolog.Nop()- t.Cleanup(func() { log.Logger = orig })}func newChartBatchSLOMonitor(t *testing.T) *Monitor {diff --git a/internal/monitoring/monitor_pbs_pmg.go b/internal/monitoring/monitor_pbs_pmg.goindex 088e5790c3..0135dae1c7 100644--- a/internal/monitoring/monitor_pbs_pmg.go+++ b/internal/monitoring/monitor_pbs_pmg.go@@ -419,7 +419,7 @@ func (m *Monitor) pollPBSInstance(ctx context.Context, instanceName string, clie// The per-cycle ctx is canceled as soon as the main polling loop finishes,// so derive the backup poll context from the long-lived runtime context instead.- parentCtx := m.runtimeCtx+ parentCtx := m.getRuntimeContext()if parentCtx == nil {parentCtx = context.Background()}diff --git a/internal/monitoring/monitor_pve.go b/internal/monitoring/monitor_pve.goindex dc6061c6a9..c74a69dfa8 100644--- a/internal/monitoring/monitor_pve.go+++ b/internal/monitoring/monitor_pve.go@@ -717,7 +717,7 @@ func (m *Monitor) maybePollPhysicalDisksAsync(// Use a generous timeout for disk pollingdiskTimeout := 60 * time.Second// Use monitor lifecycle context so shutdown can interrupt detached async polling.- parentCtx := m.runtimeCtx+ parentCtx := m.getRuntimeContext()if parentCtx == nil {parentCtx = ctx}diff --git a/internal/monitoring/monitor_pve_storage.go b/internal/monitoring/monitor_pve_storage.goindex 2ff1b577d5..6aa549621d 100644--- a/internal/monitoring/monitor_pve_storage.go+++ b/internal/monitoring/monitor_pve_storage.go@@ -52,7 +52,7 @@ func (m *Monitor) startStorageFallback(// Use a short timeout for storage fallback - it's an optimization, not criticalstorageFallbackTimeout := 10 * time.Second// Derive timeout from monitor lifecycle context so shutdown can cancel this work.- parentCtx := m.runtimeCtx+ parentCtx := m.getRuntimeContext()if parentCtx == nil {parentCtx = ctx}@@ -272,7 +272,7 @@ func (m *Monitor) pollStorageAsync(// Use a generous timeout for storage polling - it's not blocking the main taskstorageTimeout := 60 * time.Second// Use monitor lifecycle context so shutdown can interrupt detached async polling.- parentCtx := m.runtimeCtx+ parentCtx := m.getRuntimeContext()if parentCtx == nil {parentCtx = ctx}diff --git a/internal/monitoring/multi_tenant_monitor_additional_test.go b/internal/monitoring/multi_tenant_monitor_additional_test.goindex a430aa16df..f00176c164 100644--- a/internal/monitoring/multi_tenant_monitor_additional_test.go+++ b/internal/monitoring/multi_tenant_monitor_additional_test.go@@ -47,14 +47,15 @@ func TestMultiTenantMonitorRemoveTenantCancelsTenantRuntime(t *testing.T) {}deadline := time.Now().Add(2 * time.Second)- for monitor.runtimeCtx == nil && time.Now().Before(deadline) {+ for monitor.getRuntimeContext() == nil && time.Now().Before(deadline) {time.Sleep(10 * time.Millisecond)}- if monitor.runtimeCtx == nil {+ runtimeCtx := monitor.getRuntimeContext()+ if runtimeCtx == nil {t.Fatal("expected tenant monitor runtime context to be initialized")}- runtimeDone := monitor.runtimeCtx.Done()+ runtimeDone := runtimeCtx.Done()select {case <-runtimeDone:t.Fatal("expected tenant runtime context to be active before removal")diff --git a/internal/monitoring/norace_test.go b/internal/monitoring/norace_test.goindex fa132c2ef1..785eef2ff9 100644--- a/internal/monitoring/norace_test.go+++ b/internal/monitoring/norace_test.go@@ -1,3 +1,5 @@+//go:build !race+package monitoringconst raceEnabled = falsediff --git a/internal/monitoring/reload.go b/internal/monitoring/reload.goindex 09d9507469..1e8cf53275 100644--- a/internal/monitoring/reload.go+++ b/internal/monitoring/reload.go@@ -102,7 +102,7 @@ func (rm *ReloadableMonitor) doReload() error {defer rm.mu.Unlock()// Load fresh configuration- cfg, err := config.Load()+ cfg, err := config.LoadWithoutLoggingInit()if err != nil {return fmt.Errorf("reloadable monitor reload config: %w", err)}diff --git a/internal/monitoring/truenas_poller_test.go b/internal/monitoring/truenas_poller_test.goindex 83904f5045..6de23f9652 100644--- a/internal/monitoring/truenas_poller_test.go+++ b/internal/monitoring/truenas_poller_test.go@@ -1,7 +1,6 @@package monitoringimport (- "bytes""context""errors""fmt"@@ -18,8 +17,6 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/truenas""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"- "github.com/rs/zerolog"- "github.com/rs/zerolog/log")func TestTrueNASPollerPollsConfiguredConnections(t *testing.T) {@@ -1682,17 +1679,9 @@ func injectTrueNASProviderTimeout(t *testing.T, poller *TrueNASPoller, instancepoller.providersByOrg["default"][instance.ID] = truenas.NewLiveProvider(&truenas.APIFetcher{Client: client})}-func captureTrueNASPollerLogs(t *testing.T) *bytes.Buffer {+func captureTrueNASPollerLogs(t *testing.T) *monitoringLogCapture {t.Helper()-- var buf bytes.Buffer- origLogger := log.Logger- log.Logger = zerolog.New(&buf).Level(zerolog.DebugLevel).With().Timestamp().Logger()- t.Cleanup(func() {- log.Logger = origLogger- })-- return &buf+ return newMonitoringLogCapture(t)}type failingTrueNASFetcher struct {diff --git a/internal/monitoring/vmware_poller_test.go b/internal/monitoring/vmware_poller_test.goindex ad4fc25de3..1296f58923 100644--- a/internal/monitoring/vmware_poller_test.go+++ b/internal/monitoring/vmware_poller_test.go@@ -1,7 +1,6 @@package monitoringimport (- "bytes""context""errors""strings"@@ -11,8 +10,6 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/internal/vmware"- "github.com/rs/zerolog"- "github.com/rs/zerolog/log")func TestVMwarePollerPollsConfiguredConnections(t *testing.T) {@@ -441,15 +438,7 @@ func TestVMwarePollerLogsDegradedTransitionsOnlyWhenStateChanges(t *testing.T) {}}-func captureVMwarePollerLogs(t *testing.T) *bytes.Buffer {+func captureVMwarePollerLogs(t *testing.T) *monitoringLogCapture {t.Helper()-- var buf bytes.Buffer- origLogger := log.Logger- log.Logger = zerolog.New(&buf).Level(zerolog.DebugLevel).With().Timestamp().Logger()- t.Cleanup(func() {- log.Logger = origLogger- })-- return &buf+ return newMonitoringLogCapture(t)}diff --git a/internal/notifications/queue.go b/internal/notifications/queue.goindex 40dbd9c7cd..adea012df3 100644--- a/internal/notifications/queue.go+++ b/internal/notifications/queue.go@@ -694,13 +694,28 @@ func (nq *NotificationQueue) processQueue() {// SetProcessor sets the notification processor functionfunc (nq *NotificationQueue) SetProcessor(processor func(*QueuedNotification) error) {nq.mu.Lock()- defer nq.mu.Unlock()nq.processor = processor+ nq.mu.Unlock()++ if processor != nil {+ select {+ case nq.notifyChan <- struct{}{}:+ default:+ }+ }}// processBatch processes a batch of pending notifications concurrentlyfunc (nq *NotificationQueue) processBatch() {const batchLimit = 20++ nq.mu.RLock()+ processorConfigured := nq.processor != nil+ nq.mu.RUnlock()+ if !processorConfigured {+ return+ }+pending, err := nq.GetPending(batchLimit) // Increased batch size for concurrencyif err != nil {log.Error().@@ -771,14 +786,12 @@ func (nq *NotificationQueue) processNotification(notif *QueuedNotification) {nq.mu.RLock()processor := nq.processornq.mu.RUnlock()-- var err error- if processor != nil {- err = processor(notif)- } else {- err = fmt.Errorf("no processor configured")+ if processor == nil {+ return}+ err := processor(notif)+// Record auditsuccess := err == nilerrorMsg := ""diff --git a/internal/notifications/queue_test.go b/internal/notifications/queue_test.goindex ede4403f56..31f6ed8485 100644--- a/internal/notifications/queue_test.go+++ b/internal/notifications/queue_test.go@@ -1379,3 +1379,91 @@ func TestNotificationQueueStopIsIdempotent(t *testing.T) {}}}++func TestProcessBatchWithoutProcessorLeavesNotificationPending(t *testing.T) {+ nq, err := NewNotificationQueue(t.TempDir())+ if err != nil {+ t.Fatalf("Failed to create notification queue: %v", err)+ }+ defer func() { _ = nq.Stop() }()++ notif := &QueuedNotification{+ ID: "pending-without-processor",+ Type: "email",+ Status: QueueStatusPending,+ Config: []byte(`{}`),+ Alerts: []*alerts.Alert{{ID: "alert-1"}},+ MaxAttempts: 3,+ }+ if err := nq.Enqueue(notif); err != nil {+ t.Fatalf("Enqueue() error = %v", err)+ }++ nq.processBatch()++ var status string+ var attempts int+ if err := nq.db.QueryRow(`SELECT status, attempts FROM notification_queue WHERE id = ?`, notif.ID).Scan(&status, &attempts); err != nil {+ t.Fatalf("query notification: %v", err)+ }+ if status != string(QueueStatusPending) {+ t.Fatalf("status = %q, want %q", status, QueueStatusPending)+ }+ if attempts != 0 {+ t.Fatalf("attempts = %d, want 0", attempts)+ }+}++func TestSetProcessorTriggersPendingDelivery(t *testing.T) {+ nq, err := NewNotificationQueue(t.TempDir())+ if err != nil {+ t.Fatalf("Failed to create notification queue: %v", err)+ }+ defer func() { _ = nq.Stop() }()++ notif := &QueuedNotification{+ ID: "process-after-set-processor",+ Type: "email",+ Status: QueueStatusPending,+ Config: []byte(`{}`),+ Alerts: []*alerts.Alert{{ID: "alert-1"}},+ MaxAttempts: 3,+ }+ if err := nq.Enqueue(notif); err != nil {+ t.Fatalf("Enqueue() error = %v", err)+ }++ processed := make(chan string, 1)+ nq.SetProcessor(func(notif *QueuedNotification) error {+ processed <- notif.ID+ return nil+ })++ select {+ case got := <-processed:+ if got != notif.ID {+ t.Fatalf("processed notification id = %q, want %q", got, notif.ID)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("SetProcessor did not trigger pending notification delivery")+ }++ deadline := time.Now().Add(2 * time.Second)+ for {+ var status string+ var attempts int+ if err := nq.db.QueryRow(`SELECT status, attempts FROM notification_queue WHERE id = ?`, notif.ID).Scan(&status, &attempts); err != nil {+ t.Fatalf("query notification: %v", err)+ }+ if status == string(QueueStatusSent) {+ if attempts != 1 {+ t.Fatalf("attempts = %d, want 1 after successful delivery", attempts)+ }+ return+ }+ if time.Now().After(deadline) {+ t.Fatalf("notification status = %q after processor wakeup, want %q", status, QueueStatusSent)+ }+ time.Sleep(10 * time.Millisecond)+ }+}diff --git a/internal/relay/client_managed_runtime_test.go b/internal/relay/client_managed_runtime_test.goindex ff72456765..94727b6aa5 100644--- a/internal/relay/client_managed_runtime_test.go+++ b/internal/relay/client_managed_runtime_test.go@@ -16,6 +16,7 @@ import ("path/filepath""runtime""strings"+ "sync""testing""time"@@ -25,11 +26,28 @@ import (type managedRelayServer struct {cmd *exec.Cmd- logBuf *bytes.Buffer+ logBuf *safeBufferaddr stringdataDir string}+type safeBuffer struct {+ mu sync.Mutex+ buf bytes.Buffer+}++func (b *safeBuffer) Write(p []byte) (int, error) {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.buf.Write(p)+}++func (b *safeBuffer) String() string {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.buf.String()+}+func TestManagedRuntimeRelayRegistrationReconnectDrain(t *testing.T) {t.Parallel()@@ -85,7 +103,7 @@ func TestManagedRuntimeRelayRegistrationReconnectDrain(t *testing.T) {server1 := startManagedRelayServer(t, relayBinary, relayAddr, t.TempDir(), publicKeyB64)defer server1.stopKill()- logBuffer := &bytes.Buffer{}+ logBuffer := &safeBuffer{}logger := zerolog.New(logBuffer).With().Timestamp().Logger()client := NewClient(@@ -246,7 +264,7 @@ func startManagedRelayServer(publicKeyB64 string,) *managedRelayServer {t.Helper()- logBuf := &bytes.Buffer{}+ logBuf := &safeBuffer{}cmd := exec.Command(binaryPath)cmd.Env = append(os.Environ(),"PULSE_RELAY_ADDR="+addr,@@ -305,7 +323,7 @@ func (s *managedRelayServer) stopTerm() {}}-func waitForManagedRelayHealth(t *testing.T, addr string, logBuf *bytes.Buffer, timeout time.Duration) {+func waitForManagedRelayHealth(t *testing.T, addr string, logBuf *safeBuffer, timeout time.Duration) {t.Helper()deadline := time.Now().Add(timeout)url := "http://" + addr + "/healthz"@@ -350,7 +368,7 @@ func waitForManagedRelayIdle(t *testing.T, client *Client, timeout time.Durationt.Fatalf("timed out waiting for managed relay client idle status; final status=%+v", client.Status())}-func waitForManagedRelayLog(t *testing.T, logBuf *bytes.Buffer, needle string, timeout time.Duration) {+func waitForManagedRelayLog(t *testing.T, logBuf *safeBuffer, needle string, timeout time.Duration) {t.Helper()deadline := time.Now().Add(timeout)for time.Now().Before(deadline) {