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.

fix(notifications): gate queued work until destinations load

pulse-triage[bot]25e526b7e57b
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 96b37c309b..6f9c952fda 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -7967,13 +7967,21 @@ The monitoring constructor installs external alert callbacks before it returns
the monitor to API routing. An agent report accepted immediately after process
startup can therefore create a canonical alert and reach notification and push
delivery even if the long-running `Monitor.Start` goroutine has not yet begun.
+Before that callback boundary, the constructor restores saved notification
+destinations and activates the queue processor. The five-second queue ticker
+must not process an older agent-disk alert against an empty startup destination
+list; a first accepted agent report then uses the restored routing state rather
+than outrunning delivery readiness. This ordering grants no enrollment, token,
+command, removal, or re-enrollment authority.
`Start` may replace those single callback slots with runtime-specific WebSocket
context and add lifecycle projection replay, but it cannot be the first owner
of outbound alert wiring. This ordering changes no enrollment or token
authority; it only prevents the first accepted agent observation from losing
its alert consequence. `TestNewMonitorRoutesStartupCustomSensorWarningBeforeStart`
in `internal/monitoring/monitor_host_agents_test.go` pins the pre-`Start`
-warning path.
+warning path. `TestMonitorStartupRetainsQueuedAgentDiskAlertUntilDestinationRestored`
+in `internal/monitoring/physical_disk_roundtrip_test.go` covers the adjacent
+persisted-disk-alert queue activation without claiming installed delivery.
### Alert correlation consumes links without gaining lifecycle authority
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 6966db9f18..f24fdce42c 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -4098,6 +4098,12 @@ retry semantics, acknowledgement, or the critical-repeat cadence.
before returning a monitor that API handlers can publish. The asynchronous
`Monitor.Start` loop adds lifecycle projection handling and rewires escalation
with its WebSocket hub, but it is not the first notification-delivery boundary.
+Before those callbacks are installed, the constructor restores saved email,
+Apprise, and webhook destinations, then activates the queue processor. A due
+persisted notification cannot be consumed against an incomplete destination
+list by the queue's five-second ticker during a slow startup. Activation wakes
+the backlog only after the destination load stage completes; it does not
+change alert admission, agent identity, or provider-delivery policy.
This closes the startup interval in which an immediately reconnecting agent
could create and persist an active warning while the outbound callback was
still nil. The constructor-time callbacks use the already loaded alert and
@@ -4105,6 +4111,11 @@ destination configuration; runtime rewiring replaces single callback slots and
does not duplicate delivery. `TestNewMonitorRoutesStartupCustomSensorWarningBeforeStart`
in `internal/monitoring/monitor_host_agents_test.go` proves a first custom-sensor
warning reaches the external path before `Start` runs.
+`TestMonitorStartupRetainsQueuedAgentDiskAlertUntilDestinationRestored` in
+`internal/monitoring/physical_disk_roundtrip_test.go` verifies that the real
+constructor activates a persisted disk-alert job without policy-cancelling it.
+The test uses a deliberately blocked local URL and does not claim provider
+acceptance or installed delivery.
### Proxmox node unavailability is not credential evidence
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index 44d11627a7..f542cf02be 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -432,18 +432,18 @@ processor exists. An explicit processor attachment 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.
-Manager construction is the one attachment that must not wake the worker.
-Construction runs before the owner has applied saved destination configuration
-(webhooks, email, Apprise), so an already-due persisted job would be evaluated
-against a still-empty destination list and terminally cancelled as
-`ErrNotificationDeliverySkipped`. Construction records the processor without
-waking it; the worker's own ticker and any later enqueue begin delivery once
-configuration is present. This preserves the disabled-destination cancellation
-policy at processing time without letting startup order decide it.
-`TestRestartKeepsDueDeliveryPendingUntilConfigured` in
-`resolved_grouping_contract_test.go` seeds a due persisted delivery, constructs
-the manager before restoring its webhook, and proves the row stays `pending`
-until configuration is applied and then delivers.
+The monitor constructs its manager before applying saved destinations (webhooks,
+email, Apprise). It must defer processor installation until those load attempts
+finish: suppressing only the initial wake would still let the five-second queue
+tick consume an already-due job against a still-empty destination list and
+terminally cancel it as `ErrNotificationDeliverySkipped`. Explicit activation
+then wakes the pending backlog through the canonical queue path. Ordinary
+manager constructors retain autonomous processing for callers without a saved
+configuration bootstrap. `TestRestartKeepsDueDeliveryPendingUntilConfigured`
+in `resolved_grouping_contract_test.go` forces a pre-configuration batch,
+proves the due row stays `pending`, then installs the webhook and proves that
+activation delivers it. This preserves disabled-destination policy at
+processing time without letting startup timing decide it.
Alert delivery cooldown is also owned at this boundary. Normal alert delivery
must suppress duplicate sends for the same active alert occurrence when
cooldown is disabled or still active. A manager-admitted increase above the
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index bc2c975f06..79cf5db0cd 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -1775,7 +1775,7 @@ func New(cfg *config.Config) (*Monitor, error) {
metricsStore: metricsStore, // Persistent SQLite storage
alertManager: alerts.NewManagerWithDataDir(cfg.DataPath, alertManagerRestoreOptions()...),
incidentStore: incidentStore,
- notificationMgr: notifications.NewNotificationManagerWithDataDir(cfg.PublicURL, cfg.DataPath),
+ notificationMgr: notifications.NewNotificationManagerWithDeferredQueue(cfg.PublicURL, cfg.DataPath),
deadMan: newDeadManRuntime(config.ResolveRuntimeDataDir(cfg.DataPath)),
configPersist: config.NewConfigPersistence(cfg.DataPath),
discoveryService: nil, // Will be initialized in Start()
@@ -1921,6 +1921,10 @@ func New(cfg *config.Config) (*Monitor, error) {
} else {
log.Warn().Err(err).Msg("failed to load webhook configuration")
}
+ // The queue worker starts with the manager but has no processor until all
+ // saved destinations are installed. Activate it only after the last load;
+ // a slow migration or config read must not cancel due persisted work.
+ m.notificationMgr.StartQueueProcessing()
// In mock mode the canonical sampler owns demo chart history by default.
// Support-only hybrid runs can opt back into real client initialization.
diff --git a/internal/monitoring/physical_disk_roundtrip_test.go b/internal/monitoring/physical_disk_roundtrip_test.go
index 3d85327069..23f1c0b7a5 100644
--- a/internal/monitoring/physical_disk_roundtrip_test.go
+++ b/internal/monitoring/physical_disk_roundtrip_test.go
@@ -6,11 +6,90 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
+// Monitor construction restores notification destinations before admitting
+// agent observations. A previously queued disk alert must not be cancelled as
+// "delivery disabled" just because its saved webhook has not loaded yet.
+func TestMonitorStartupRetainsQueuedAgentDiskAlertUntilDestinationRestored(t *testing.T) {
+ dir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", dir)
+ persistence := config.NewConfigPersistence(dir)
+ if err := persistence.SaveAlertConfig(alerts.AlertConfig{
+ Enabled: true, ActivationState: alerts.ActivationActive,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ hook := notifications.WebhookConfig{
+ ID: "disk-ops", Name: "disk-ops", URL: "http://127.0.0.1:1/alert",
+ Enabled: true, Service: "generic",
+ }
+ if err := persistence.SaveWebhooks([]notifications.WebhookConfig{hook}); err != nil {
+ t.Fatal(err)
+ }
+ configJSON, err := json.Marshal(hook)
+ if err != nil {
+ t.Fatal(err)
+ }
+ seed, err := notifications.NewNotificationQueue(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := seed.Enqueue(&notifications.QueuedNotification{
+ ID: "startup-agent-disk-wearout", Type: "webhook", Status: notifications.QueueStatusPending,
+ DestinationID: hook.ID, Config: configJSON, MaxAttempts: 3,
+ Alerts: []*alerts.Alert{{
+ ID: "disk-wearout", Type: "disk-wearout", ResourceName: "agent-disk",
+ Level: alerts.AlertLevelWarning, StartTime: time.Now().Add(-time.Minute),
+ }},
+ }); err != nil {
+ _ = seed.Stop()
+ t.Fatal(err)
+ }
+ if err := seed.Stop(); err != nil {
+ t.Fatal(err)
+ }
+
+ monitor, err := New(&config.Config{DataPath: dir})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(monitor.Stop)
+ queue := monitor.GetNotificationManager().GetQueue()
+ if queue == nil {
+ t.Fatal("notification queue unavailable")
+ }
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ stats, err := queue.GetQueueStats()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if stats[string(notifications.QueueStatusCancelled)] != 0 {
+ t.Fatalf("queued disk alert cancelled before destination restore: %v", stats)
+ }
+ telemetry, err := queue.GetTelemetryStats(time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if telemetry.Attempts != 0 {
+ if telemetry.Deliveries != 0 {
+ t.Fatalf("synthetic blocked endpoint unexpectedly delivered: %+v", telemetry)
+ }
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("restored destination never reached queue processor: %v", stats)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
// Exercise the real skipped-poll path, not just the ID helper: canonical views
// are converted back into source state and then re-ingested by the adapter.
func TestPhysicalDiskSkippedPollPreservesSourceIdentity(t *testing.T) {
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index 1ec9051bd7..e9f85bc28b 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -702,6 +702,18 @@ func NewNotificationManager(publicURL string) *NotificationManager {
// This enables tenant-scoped notification queue persistence in multi-tenant deployments.
// If dataDir is empty, it uses the global data directory.
func NewNotificationManagerWithDataDir(publicURL string, dataDir string) *NotificationManager {
+ return newNotificationManagerWithDataDir(publicURL, dataDir, false)
+}
+
+// NewNotificationManagerWithDeferredQueue creates a manager whose persisted
+// deliveries stay idle until StartQueueProcessing is called. Owners that load
+// saved destinations after construction must use this form so a queue ticker
+// cannot interpret incomplete startup configuration as a removed destination.
+func NewNotificationManagerWithDeferredQueue(publicURL string, dataDir string) *NotificationManager {
+ return newNotificationManagerWithDataDir(publicURL, dataDir, true)
+}
+
+func newNotificationManagerWithDataDir(publicURL string, dataDir string, deferQueueProcessing bool) *NotificationManager {
cleanURL := strings.TrimRight(strings.TrimSpace(publicURL), "/")
if cleanURL != "" {
log.Info().Str("publicURL", cleanURL).Msg("notification manager initialized with public URL")
@@ -755,13 +767,10 @@ func NewNotificationManagerWithDataDir(publicURL string, dataDir string) *Notifi
// Create webhook client after NotificationManager is initialized
nm.webhookClient = nm.createSecureWebhookClient(WebhookTimeout)
- // Wire up the queue processor without waking the worker. Construction runs
- // before the owner applies saved destination configuration (webhooks,
- // email, Apprise); waking here would let an already-due persisted job be
- // processed while the destination list is still empty and be terminally
- // cancelled as "delivery disabled". The worker's ticker and later enqueues
- // begin delivery once configuration is present.
- if queue != nil {
+ // Ordinary callers retain the historical autonomous queue. A bootstrap
+ // owner leaves the processor absent until every saved destination is loaded;
+ // not waking the worker alone cannot guard against its periodic ticker.
+ if queue != nil && !deferQueueProcessing {
queue.installProcessor(nm.ProcessQueuedNotification)
}
@@ -772,6 +781,17 @@ func NewNotificationManagerWithDataDir(publicURL string, dataDir string) *Notifi
return nm
}
+// StartQueueProcessing activates persisted deliveries after the owner has
+// restored its complete notification policy and destination configuration.
+func (n *NotificationManager) StartQueueProcessing() {
+ n.mu.RLock()
+ queue := n.queue
+ n.mu.RUnlock()
+ if queue != nil {
+ queue.SetProcessor(n.ProcessQueuedNotification)
+ }
+}
+
// SetTenantIdentityResolver installs an org-backed resolver for the tenant
// identity stamped into webhook payloads. It overrides the
// PULSE_TENANT_ID / PULSE_TENANT_NAME environment defaults; multi-tenant
diff --git a/internal/notifications/resolved_grouping_contract_test.go b/internal/notifications/resolved_grouping_contract_test.go
index 0e0241a3a9..528fb59ec4 100644
--- a/internal/notifications/resolved_grouping_contract_test.go
+++ b/internal/notifications/resolved_grouping_contract_test.go
@@ -272,19 +272,19 @@ func TestRestartKeepsDueDeliveryPendingUntilConfigured(t *testing.T) {
}
// Production order: construct the manager, then apply saved configuration.
- m := NewNotificationManagerWithDataDir("", dir)
+ m := NewNotificationManagerWithDeferredQueue("", dir)
defer m.Stop()
m.webhookClient = server.Client()
if err := m.UpdateAllowedPrivateCIDRs("127.0.0.1/32"); err != nil {
t.Fatal(err)
}
- // A premature startup wake must not consume the due job before the
- // destination configuration is restored.
- time.Sleep(250 * time.Millisecond)
+ // Force the same batch path the five-second ticker uses while saved
+ // configuration is still absent. It must leave the due row pending.
queue := m.GetQueue()
if queue == nil {
t.Fatal("queue unavailable")
}
+ queue.processBatch()
var status string
if err := queue.db.QueryRow(`SELECT status FROM notification_queue WHERE id = 'restart-due'`).Scan(&status); err != nil {
t.Fatal(err)
@@ -294,7 +294,7 @@ func TestRestartKeepsDueDeliveryPendingUntilConfigured(t *testing.T) {
}
m.AddWebhook(hook)
- queue.processBatch()
+ m.StartQueueProcessing()
select {
case <-received:
case <-time.After(5 * time.Second):