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.

Reconcile delivery health and Proxmox Assistant controls

rcourtmancba1e2abeb71
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index a1bc7e83c5..5b530a823e 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -2341,6 +2341,11 @@ security/API-contract boundary. It must remain a one-time startup and shutdown
dependency and must not alter agent registration, install tokens, profiles,
command transport, update policy, or fleet lifecycle authority.
+Construction-time callbacks added to the shared monitor for monitoring-owned
+state, including notification-delivery reconciliation, grant no agent
+enrollment, report, command, or lifecycle authority. They must remain separate
+from the fail-closed host continuity hydration that agent lifecycle owns.
+
1. Update this contract when agent lifecycle ownership changes. Routes added under the shared `internal/api/` extension point that are clearly outside lifecycle ownership (for example `POST /api/ai/patrol/preflight`, the `patrol_preflight` snapshot field added to `/api/settings/ai`, the auto-trigger preflight dispatch on settings save, the startup-seed dispatch in `NewAISettingsHandler`, and the cached-preflight integration into the Patrol `tools` readiness check — all owned by ai-runtime) do not extend this subsystem's contract; they live in their owning subsystem. Canonical scoped Patrol resolution on `POST /api/ai/patrol/run` and structured `patrol_assess_finding` lifecycle outcomes are likewise adjacent AI/API contracts: they may consume agent-reported identities and evidence, but they do not change agent registration, install, token, profile, command transport, update, or fleet-lifecycle authority.
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. Shell installer lifecycle changes must keep `scripts/installtests/install_sh_test.go` covering explicit flags, persisted connection state, legacy running-process/service recovery, legacy single-dash v5 agent flag recovery, repeated disk-exclusion recovery, and secure token-file service argument rendering for update re-entry. Host metrics tests must prove excluded FreeBSD `fdescfs` mounts are filtered before filesystem usage is attempted.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 1ce3397e3c..967eaa9084 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -5903,7 +5903,15 @@ That same boundary also governs shared Assistant wording in
base system prompt and `pulse_control` schema/description must not claim that a
generic `vm` or `system-container` is controllable. Shared AI text must describe
control as capability-gated and explicitly allow read-only platform variants
-such as VMware phase-1 guests.
+such as VMware phase-1 guests. For a canonical Proxmox VM or LXC that does
+advertise a lifecycle capability, that advertised hypervisor action is the
+authority: start, stop, shutdown, and reboot do not depend on QEMU guest-agent
+availability, and Assistant must not replace the offered governed action with
+manual `qm` or `pct` instructions. Claims that a guest agent or capability is
+unavailable require current tool evidence. The provider-facing `pulse_control`
+schema exposes only `type=resource`, `resource_id`, and `action`; retired guest,
+raw-command, target-host, host-routing, and force fields must not remain in the
+schema as misleading alternate paths.
That same VMware AI rule also includes the investigation path. Alarm, health,
event, task, metrics-history, and snapshot-tree context for VMware-backed
resources must stay reachable through those same shared read/query surfaces
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index aed2edf724..3b83b4cccf 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -959,7 +959,13 @@ cleanup so readers cannot retain orphaned runtime or alert projections.
result must be raised through `alerts.RaiseSystemAlert` so identity and
idempotence stay owned by the alerts subsystem. Evaluation runs on the poll
ticker and must stay throttled well below the polling cadence, because
- reading queue health costs a database query. New Monitor struct fields
+ reading queue health costs a database query. Monitor construction also
+ registers the notification queue's committed health-transition callback;
+ that path bypasses the timer throttle so terminal failures appear and
+ operator retry/dismissal clears the warning immediately. The callback may
+ run only after the queue has released its database lock, and monitoring
+ must still derive the result from the canonical notification verdict rather
+ than trusting the transition that triggered the refresh. New Monitor struct fields
added for this must fit the existing field alignment column: a longer name
makes gofmt re-pad the whole block and breaks the canonical guardrail tests
that pin those declarations verbatim.
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index 72ddbe7429..f18f1182d8 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -67,7 +67,13 @@ group headings, and HTML-escape every resource, message, and category field.
reports `unavailable` and never `healthy`, because an unreadable queue must
not be mistaken for successful delivery. `internal/api/alerting/notifications.go`
delegates to this rule rather than reimplementing it, and `monitoring`
- consumes it to raise the notification-delivery system alert.
+ consumes it to raise the notification-delivery system alert. The queue also
+ emits one process-local health-changed callback after a relevant transition
+ has committed and after its database lock is released. Monitoring installs
+ that callback and owns the alert projection; notification code must not
+ raise or clear alerts directly. Retry and dismissal reconcile even when no
+ row changed, because an already-repaired queue may still have a persisted
+ stale warning from an earlier process.
## Forbidden Paths
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 363bdf6b43..a28b9a1174 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -3859,6 +3859,8 @@ func (s *Service) buildSystemPromptWithToolGovernance(toolGovernance string) str
- Use only tools that are explicitly offered in this turn's available-tool manifest.
- Write tools change infrastructure state. Mixed tools may include read subactions and write or decision-recording subactions; follow the governed path described in the manifest.
- Not every VM or container supports control. Some API-backed platforms are read-only even when the resource type is "vm" or "system-container".
+- A Proxmox VM or LXC reboot is a hypervisor lifecycle action and does not require the QEMU guest agent. When the canonical resource advertises the requested lifecycle capability, use pulse_control and let Pulse enforce planning, approval, execution, and verification.
+- Never redirect the user to manual qm or pct commands when Pulse offers the requested lifecycle capability. Do not claim that a guest agent or capability is unavailable without current tool evidence; if a governed tool reports a real boundary, explain that exact result instead of inventing a prerequisite.
- Write tools are allowed only when the user explicitly asks you to perform an action.
- Status checks and monitoring are read-oriented; do not change state unless the user asked for a state change.
- Resolve a missing target yourself before asking: use read-only query/topology tools to see which hosts, VMs, or containers exist. If exactly one plausible target matches the request (a single connected host, or one resource by that name), run read-only diagnostics against it and name the target in your answer instead of asking.
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
index 039c211e47..2af0ab0e18 100644
--- a/internal/ai/chat/service_tooling_test.go
+++ b/internal/ai/chat/service_tooling_test.go
@@ -327,6 +327,15 @@ func TestBuildSystemPrompt_DoesNotClaimGenericVMControl(t *testing.T) {
if !strings.Contains(prompt, "Plans shared Pulse resource actions; approval and execution stay on the canonical action lifecycle") {
t.Fatalf("expected system prompt to describe capability-bound pulse_control usage, got %q", prompt)
}
+ if !strings.Contains(prompt, "A Proxmox VM or LXC reboot is a hypervisor lifecycle action and does not require the QEMU guest agent") {
+ t.Fatalf("expected system prompt to distinguish Proxmox lifecycle control from guest-agent operations, got %q", prompt)
+ }
+ if !strings.Contains(prompt, "Never redirect the user to manual qm or pct commands when Pulse offers the requested lifecycle capability") {
+ t.Fatalf("expected system prompt to keep offered Proxmox lifecycle actions on the governed Pulse path, got %q", prompt)
+ }
+ if !strings.Contains(prompt, "Do not claim that a guest agent or capability is unavailable without current tool evidence") {
+ t.Fatalf("expected system prompt to prohibit invented guest-agent limitations, got %q", prompt)
+ }
if !strings.Contains(prompt, "## AVAILABLE TOOL GOVERNANCE") {
t.Fatalf("expected system prompt to include generated tool governance section, got %q", prompt)
}
diff --git a/internal/ai/tools/control_resource_test.go b/internal/ai/tools/control_resource_test.go
index 0fffc73809..b8b6d6998e 100644
--- a/internal/ai/tools/control_resource_test.go
+++ b/internal/ai/tools/control_resource_test.go
@@ -76,9 +76,17 @@ func TestPulseToolExecutor_ListTools_PulseControlDescriptionStaysCapabilityBound
if !strings.Contains(tool.Description, "never executes commands") {
t.Fatalf("expected pulse_control description to name the command-free boundary, got %q", tool.Description)
}
+ if !strings.Contains(tool.Description, "Proxmox VM and LXC lifecycle actions do not require the QEMU guest agent") {
+ t.Fatalf("expected pulse_control description to distinguish hypervisor lifecycle from guest-agent operations, got %q", tool.Description)
+ }
if action := tool.InputSchema.Properties["action"].Description; !strings.Contains(action, "Advertised resource capability") {
t.Fatalf("expected pulse_control action schema to describe shared action gating, got %q", action)
}
+ for _, retired := range []string{"guest_id", "command", "target_host", "run_on_host", "force"} {
+ if _, exists := tool.InputSchema.Properties[retired]; exists {
+ t.Fatalf("pulse_control schema still exposes retired %q input", retired)
+ }
+ }
return
}
t.Fatalf("expected pulse_control to be available, got %+v", tools)
diff --git a/internal/ai/tools/provider_projection_test.go b/internal/ai/tools/provider_projection_test.go
index 5e04165c63..3e7ae1faa0 100644
--- a/internal/ai/tools/provider_projection_test.go
+++ b/internal/ai/tools/provider_projection_test.go
@@ -71,6 +71,34 @@ func TestPulseToolExecutorAssistantProviderToolsUsesRuntimeAvailability(t *testi
if controlTool.BehaviorHints == nil || controlTool.BehaviorHints.DestructiveHint == nil || !*controlTool.BehaviorHints.DestructiveHint {
t.Fatalf("%s provider behavior hints = %+v, want destructive hint", agentcapabilities.PulseControlToolName, controlTool.BehaviorHints)
}
+ if !strings.Contains(controlTool.Description, "Proxmox VM and LXC lifecycle actions do not require the QEMU guest agent") {
+ t.Fatalf("%s provider description does not distinguish lifecycle actions from guest-agent operations: %q", agentcapabilities.PulseControlToolName, controlTool.Description)
+ }
+ properties, ok := controlTool.InputSchema["properties"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("%s provider properties = %#v, want object", agentcapabilities.PulseControlToolName, controlTool.InputSchema["properties"])
+ }
+ for _, retired := range []string{"guest_id", "command", "target_host", "run_on_host", "force"} {
+ if _, exists := properties[retired]; exists {
+ t.Fatalf("%s provider schema still exposes retired %q input", agentcapabilities.PulseControlToolName, retired)
+ }
+ }
+ required, ok := controlTool.InputSchema["required"].([]string)
+ if !ok {
+ t.Fatalf("%s provider required fields = %#v, want array", agentcapabilities.PulseControlToolName, controlTool.InputSchema["required"])
+ }
+ for _, field := range []string{"type", "resource_id", "action"} {
+ found := false
+ for _, value := range required {
+ if value == field {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("%s provider schema required fields = %#v, missing %q", agentcapabilities.PulseControlToolName, required, field)
+ }
+ }
}
func TestPulseToolExecutorAssistantProviderToolsEnterThroughManifestSurfaceAffordances(t *testing.T) {
diff --git a/internal/ai/tools/tools_control.go b/internal/ai/tools/tools_control.go
index dd41a48ef4..a7d5d341ca 100644
--- a/internal/ai/tools/tools_control.go
+++ b/internal/ai/tools/tools_control.go
@@ -23,7 +23,7 @@ func (e *PulseToolExecutor) registerControlTools() {
e.registry.registerBuiltin(RegisteredTool{
Definition: Tool{
Name: agentcapabilities.PulseControlToolName,
- Description: `Plan one typed action for a canonical resource that explicitly advertises the requested capability. The plan is persisted on Pulse's shared action lifecycle; this tool never executes commands or contacts infrastructure directly.`,
+ Description: `Plan one typed action for a canonical resource that explicitly advertises the requested capability. The plan is persisted on Pulse's shared action lifecycle; this tool never executes commands or contacts infrastructure directly. Proxmox VM and LXC lifecycle actions do not require the QEMU guest agent; they use the advertised hypervisor capability.`,
InputSchema: InputSchema{
Type: "object",
Properties: map[string]PropertySchema{
@@ -32,37 +32,17 @@ func (e *PulseToolExecutor) registerControlTools() {
Description: "Canonical control type. Only resource is supported.",
Enum: []string{"resource"},
},
- "guest_id": {
- Type: "string",
- Description: "For guest: VMID or name",
- },
"resource_id": {
Type: "string",
- Description: "For resource: discovered resource name or canonical resource ID from pulse_query",
+ Description: "Discovered resource name or canonical resource ID from pulse_query",
},
"action": {
Type: "string",
- Description: "Advertised resource capability name, such as start, stop, shutdown, reboot, or restart",
+ Description: "Advertised resource capability name, such as start, stop, shutdown, reboot, or restart. Proxmox lifecycle capabilities operate at the hypervisor boundary and do not require in-guest QEMU agent functionality.",
Enum: []string{"start", "stop", "shutdown", "reboot", "restart"},
},
- "command": {
- Type: "string",
- Description: "For command type: the shell command to execute",
- },
- "target_host": {
- Type: "string",
- Description: "For command type: hostname to run command on",
- },
- "run_on_host": {
- Type: "boolean",
- Description: "For command type: run on host (default true)",
- },
- "force": {
- Type: "boolean",
- Description: "For guest stop: force stop without graceful shutdown",
- },
},
- Required: []string{"type"},
+ Required: []string{"type", "resource_id", "action"},
},
},
Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
diff --git a/internal/api/alerting/notification_queue_additional_test.go b/internal/api/alerting/notification_queue_additional_test.go
index bf1ea67f34..367c3a7af2 100644
--- a/internal/api/alerting/notification_queue_additional_test.go
+++ b/internal/api/alerting/notification_queue_additional_test.go
@@ -119,6 +119,10 @@ func TestNotificationQueueHandlers_RetryAndDelete(t *testing.T) {
func TestNotificationQueueHandlers_BulkTerminalFailureRecovery(t *testing.T) {
handler, queue := newNotificationQueueHandlers(t)
enqueueDLQNotification(t, queue, "notif-bulk")
+ if err := queue.UpdateStatus("notif-bulk", notifications.QueueStatusDLQ, "destination unavailable"); err != nil {
+ t.Fatalf("mark notification DLQ: %v", err)
+ }
+ assertNotificationDeliveryAlertActive(t, handler.monitor)
req := httptest.NewRequest(http.MethodPost, "/api/notifications/terminal-failures/retry", nil)
rec := httptest.NewRecorder()
@@ -135,10 +139,16 @@ func TestNotificationQueueHandlers_BulkTerminalFailureRecovery(t *testing.T) {
if response.Affected != 1 {
t.Fatalf("retry affected = %d, want 1", response.Affected)
}
+ for _, active := range handler.monitor.GetAlertManager().GetActiveAlerts() {
+ if active.Type == alerts.NotificationDeliveryAlertType {
+ t.Fatalf("notification delivery alert remained active after retry: %+v", active)
+ }
+ }
if err := queue.UpdateStatus("notif-bulk", notifications.QueueStatusDLQ, "still unavailable"); err != nil {
t.Fatalf("mark retried notification DLQ: %v", err)
}
+ assertNotificationDeliveryAlertActive(t, handler.monitor)
req = httptest.NewRequest(http.MethodPost, "/api/notifications/terminal-failures/dismiss", nil)
rec = httptest.NewRecorder()
handler.DismissTerminalFailures(rec, req)
@@ -151,6 +161,21 @@ func TestNotificationQueueHandlers_BulkTerminalFailureRecovery(t *testing.T) {
if response.Affected != 1 {
t.Fatalf("dismiss affected = %d, want 1", response.Affected)
}
+ for _, active := range handler.monitor.GetAlertManager().GetActiveAlerts() {
+ if active.Type == alerts.NotificationDeliveryAlertType {
+ t.Fatalf("notification delivery alert remained active after dismiss: %+v", active)
+ }
+ }
+}
+
+func assertNotificationDeliveryAlertActive(t *testing.T, monitor *monitoring.Monitor) {
+ t.Helper()
+ for _, active := range monitor.GetAlertManager().GetActiveAlerts() {
+ if active.Type == alerts.NotificationDeliveryAlertType {
+ return
+ }
+ }
+ t.Fatal("expected notification delivery alert to be active")
}
func TestNotificationQueueHandlers_HandleNotificationQueue(t *testing.T) {
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 2032c0e49a..c2e84e0201 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -1753,6 +1753,9 @@ func New(cfg *config.Config) (*Monitor, error) {
}
m.executor = newRealExecutor(m)
+ if queue := m.notificationMgr.GetQueue(); queue != nil {
+ queue.SetDeliveryHealthChangedCallback(m.reconcileNotificationDelivery)
+ }
m.hydrateRemovedHostAgents(time.Now().UTC())
m.alertManager.SetBackupIntentContextResolver(m.resolveBackupIntentContext)
m.registerBuiltInPollProviders()
diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.go
index f12c1ce1ce..fd5064b20c 100644
--- a/internal/monitoring/monitor_host_agents_test.go
+++ b/internal/monitoring/monitor_host_agents_test.go
@@ -14,6 +14,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"
"github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
"github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
@@ -5191,3 +5192,48 @@ func TestApplyHostReportCarriesAgentPrivilegeProfile(t *testing.T) {
t.Fatalf("legacy report invented a privilege profile: %+v", legacyHost.AgentPrivilege)
}
}
+
+func TestMonitorConstructionWiresNotificationDeliveryReconciliation(t *testing.T) {
+ monitor, err := New(&config.Config{DataPath: t.TempDir()})
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ t.Cleanup(func() { monitor.Stop() })
+
+ queue := monitor.GetNotificationManager().GetQueue()
+ if queue == nil {
+ t.Fatal("expected notification queue")
+ }
+ if err := queue.Enqueue(&notifications.QueuedNotification{
+ ID: "delivery-reconcile",
+ Type: "webhook",
+ Status: notifications.QueueStatusPending,
+ MaxAttempts: 8,
+ Config: json.RawMessage(`{}`),
+ }); err != nil {
+ t.Fatalf("Enqueue: %v", err)
+ }
+ if err := queue.UpdateStatus("delivery-reconcile", notifications.QueueStatusDLQ, "destination unavailable"); err != nil {
+ t.Fatalf("mark DLQ: %v", err)
+ }
+
+ found := false
+ for _, active := range monitor.GetAlertManager().GetActiveAlerts() {
+ if active.Type == alerts.NotificationDeliveryAlertType {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatal("expected committed DLQ transition to raise notification delivery alert")
+ }
+
+ if _, err := queue.DismissTerminalFailures(); err != nil {
+ t.Fatalf("DismissTerminalFailures: %v", err)
+ }
+ for _, active := range monitor.GetAlertManager().GetActiveAlerts() {
+ if active.Type == alerts.NotificationDeliveryAlertType {
+ t.Fatalf("notification delivery alert remained active after committed recovery: %+v", active)
+ }
+ }
+}
diff --git a/internal/monitoring/system_alerts.go b/internal/monitoring/system_alerts.go
index 54e61f3b29..f49b28f5ef 100644
--- a/internal/monitoring/system_alerts.go
+++ b/internal/monitoring/system_alerts.go
@@ -23,6 +23,18 @@ const notificationDeliveryCheckInterval = 5 * time.Minute
// RaiseSystemAlert is idempotent for an unchanged condition, so repeating this
// on a timer neither re-notifies nor accumulates alerts.
func (m *Monitor) evaluateNotificationDelivery(now time.Time) {
+ m.evaluateNotificationDeliveryAt(now, false)
+}
+
+// reconcileNotificationDelivery projects a committed queue-health transition
+// immediately. Timer-driven evaluations remain throttled, but an operator's
+// retry or dismissal must not leave a known-stale warning visible until the
+// next polling interval.
+func (m *Monitor) reconcileNotificationDelivery() {
+ m.evaluateNotificationDeliveryAt(time.Now(), true)
+}
+
+func (m *Monitor) evaluateNotificationDeliveryAt(now time.Time, force bool) {
if m == nil {
return
}
@@ -31,7 +43,7 @@ func (m *Monitor) evaluateNotificationDelivery(now time.Time) {
}
m.mu.Lock()
- if !m.lastDeliveryHealthCheck.IsZero() &&
+ if !force && !m.lastDeliveryHealthCheck.IsZero() &&
now.Sub(m.lastDeliveryHealthCheck) < notificationDeliveryCheckInterval {
m.mu.Unlock()
return
diff --git a/internal/notifications/queue.go b/internal/notifications/queue.go
index 26496544ff..a903b2a14b 100644
--- a/internal/notifications/queue.go
+++ b/internal/notifications/queue.go
@@ -161,20 +161,21 @@ type QueuedNotification struct {
// NotificationQueue manages persistent notification delivery with retries and DLQ
type NotificationQueue struct {
- mu sync.RWMutex
- deliveryGateMu sync.Mutex
- deliveryGates map[string]*notificationDeliveryGate
- stopOnce sync.Once
- stopErr error
- db *sql.DB
- dbPath string
- stopChan chan struct{}
- wg sync.WaitGroup
- processorTicker *time.Ticker
- cleanupTicker *time.Ticker
- notifyChan chan struct{} // Signal when new notifications are added
- processor func(*QueuedNotification) error // Notification processor function
- workerSem chan struct{} // Semaphore for limiting concurrent workers
+ mu sync.RWMutex
+ deliveryGateMu sync.Mutex
+ deliveryGates map[string]*notificationDeliveryGate
+ stopOnce sync.Once
+ stopErr error
+ db *sql.DB
+ dbPath string
+ stopChan chan struct{}
+ wg sync.WaitGroup
+ processorTicker *time.Ticker
+ cleanupTicker *time.Ticker
+ notifyChan chan struct{} // Signal when new notifications are added
+ processor func(*QueuedNotification) error // Notification processor function
+ deliveryHealthChanged func() // Reconcile the monitoring-owned delivery alert after health-changing transitions
+ workerSem chan struct{} // Semaphore for limiting concurrent workers
}
// notificationDeliveryGate orders delivery and cancellation for a single
@@ -830,9 +831,22 @@ func (nq *NotificationQueue) Enqueue(notif *QueuedNotification) error {
// UpdateStatus updates the status of a queued notification without incrementing attempts
func (nq *NotificationQueue) UpdateStatus(id string, status NotificationQueueStatus, errorMsg string) error {
nq.mu.Lock()
- defer nq.mu.Unlock()
+ err := nq.updateNotificationStatusNoLock(id, status, errorMsg, time.Now())
+ nq.mu.Unlock()
- return nq.updateNotificationStatusNoLock(id, status, errorMsg, time.Now())
+ if err == nil && notificationStatusChangesDeliveryHealth(status) {
+ nq.notifyDeliveryHealthChanged()
+ }
+ return err
+}
+
+func notificationStatusChangesDeliveryHealth(status NotificationQueueStatus) bool {
+ switch status {
+ case QueueStatusFailed, QueueStatusDLQ, QueueStatusCancelled:
+ return true
+ default:
+ return false
+ }
}
func (nq *NotificationQueue) updateNotificationStatusNoLock(
@@ -1189,10 +1203,10 @@ func (nq *NotificationQueue) ScheduleRetry(id string, attempt int) error {
nextRetry := time.Now().Add(backoff)
nq.mu.Lock()
- defer nq.mu.Unlock()
links, err := nq.readNotificationLinksNoLock(id)
if err != nil {
+ nq.mu.Unlock()
return err
}
links = transitionNotificationLinks(
@@ -1202,6 +1216,7 @@ func (nq *NotificationQueue) ScheduleRetry(id string, attempt int) error {
)
linksJSON, err := json.Marshal(links)
if err != nil {
+ nq.mu.Unlock()
return fmt.Errorf("marshal notification links for retry: %w", err)
}
query := `
@@ -1219,8 +1234,10 @@ func (nq *NotificationQueue) ScheduleRetry(id string, attempt int) error {
id,
)
if err != nil {
+ nq.mu.Unlock()
return fmt.Errorf("failed to schedule retry: %w", err)
}
+ nq.mu.Unlock()
log.Debug().
Str("id", id).
@@ -1229,6 +1246,7 @@ func (nq *NotificationQueue) ScheduleRetry(id string, attempt int) error {
Time("nextRetry", nextRetry).
Msg("notification retry scheduled")
+ nq.notifyDeliveryHealthChanged()
return nil
}
@@ -1300,8 +1318,19 @@ func (nq *NotificationQueue) resolveTerminalFailures(retry bool) (int, error) {
}
nq.mu.Lock()
- defer nq.mu.Unlock()
+ affected, err := nq.resolveTerminalFailuresNoLock(retry)
+ nq.mu.Unlock()
+ if err != nil {
+ return 0, err
+ }
+
+ // Reconcile even when no rows were affected. A prior process may already
+ // have repaired the queue while leaving a persisted system alert active.
+ nq.notifyDeliveryHealthChanged()
+ return affected, nil
+}
+func (nq *NotificationQueue) resolveTerminalFailuresNoLock(retry bool) (int, error) {
rows, err := nq.db.Query(`
SELECT id, operational_links
FROM notification_queue
@@ -1394,6 +1423,31 @@ func (nq *NotificationQueue) resolveTerminalFailures(retry bool) (int, error) {
return affected, nil
}
+// SetDeliveryHealthChangedCallback installs the monitoring-owned reconciliation
+// hook. Notification delivery owns queue truth; monitoring owns its system
+// alert projection, so the queue only announces that the verdict may have
+// changed after committing and releasing its database lock.
+func (nq *NotificationQueue) SetDeliveryHealthChangedCallback(callback func()) {
+ if nq == nil {
+ return
+ }
+ nq.mu.Lock()
+ nq.deliveryHealthChanged = callback
+ nq.mu.Unlock()
+}
+
+func (nq *NotificationQueue) notifyDeliveryHealthChanged() {
+ if nq == nil {
+ return
+ }
+ nq.mu.RLock()
+ callback := nq.deliveryHealthChanged
+ nq.mu.RUnlock()
+ if callback != nil {
+ callback()
+ }
+}
+
// RecordAudit records a notification delivery attempt in the audit log
func (nq *NotificationQueue) RecordAudit(notif *QueuedNotification, success bool, errorMsg string) error {
nq.mu.Lock()
diff --git a/internal/notifications/queue_test.go b/internal/notifications/queue_test.go
index 5fbfea700f..163287bcfb 100644
--- a/internal/notifications/queue_test.go
+++ b/internal/notifications/queue_test.go
@@ -1387,6 +1387,14 @@ func TestGetQueueStats(t *testing.T) {
t.Fatalf("NewNotificationQueue: %v", err)
}
defer func() { _ = nq.Stop() }()
+ observedHealth := make([]DeliveryHealth, 0, 6)
+ nq.SetDeliveryHealthChangedCallback(func() {
+ stats, statsErr := nq.GetQueueStats()
+ if statsErr != nil {
+ t.Fatalf("read queue health from committed callback: %v", statsErr)
+ }
+ observedHealth = append(observedHealth, ClassifyQueueHealth(stats))
+ })
for _, notif := range []*QueuedNotification{
{ID: "failed-recovery", Type: "email", Status: QueueStatusPending, Attempts: 8, MaxAttempts: 8, Config: []byte(`{}`)},
@@ -1411,6 +1419,9 @@ func TestGetQueueStats(t *testing.T) {
if affected != 2 {
t.Fatalf("retry affected = %d, want 2", affected)
}
+ if len(observedHealth) == 0 || !observedHealth[len(observedHealth)-1].Healthy {
+ t.Fatalf("health after retry = %#v, want healthy callback after commit", observedHealth)
+ }
for _, id := range []string{"failed-recovery", "dlq-recovery"} {
var status string
var attempts int
@@ -1439,6 +1450,9 @@ func TestGetQueueStats(t *testing.T) {
if affected != 2 {
t.Fatalf("dismiss affected = %d, want 2", affected)
}
+ if len(observedHealth) == 0 || !observedHealth[len(observedHealth)-1].Healthy {
+ t.Fatalf("health after dismiss = %#v, want healthy callback after commit", observedHealth)
+ }
stats, err := nq.GetQueueStats()
if err != nil {
t.Fatalf("GetQueueStats: %v", err)