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
feat(alerts): append-only alert event log with suppression reasons
rcourtman9572a113ae87
diff --git a/docs/API.md b/docs/API.mdindex 8d8784e20b..6f4a8d00ca 100644--- a/docs/API.md+++ b/docs/API.md@@ -618,6 +618,7 @@ Alert configuration and history (requires `monitoring:read`/`monitoring:write`).- `POST /api/alerts/activate`- `GET /api/alerts/active`- `GET /api/alerts/delivery-diagnosis?alertIdentifier=<alert-id>` (omit `alertIdentifier` to get the diagnosis array for every active alert)+- `GET /api/alerts/events?alertIdentifier=<alert-id>&type=<event-type,...>&since=<RFC3339>&limit=<n>` — append-only alert event log: lifecycle transitions and notification decisions, including suppressions with reasons; all parameters optional, newest first- `GET /api/alerts/history`- `DELETE /api/alerts/history`- `GET /api/alerts/incidents`diff --git a/internal/alerts/callbacks.go b/internal/alerts/callbacks.goindex 479d826b2c..5f78b6afa6 100644--- a/internal/alerts/callbacks.go+++ b/internal/alerts/callbacks.go@@ -1,8 +1,10 @@package alertsimport (+ "strconv""sync"+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog""github.com/rs/zerolog/log")@@ -343,6 +345,10 @@ func (m *Manager) getEscalateCallback() func(alert *Alert, level int) {// preserving canonical state as the internal identity and emitting the public// alert ID to external callbacks for compatibility.func (m *Manager) safeCallResolvedAlertCallback(alert *Alert, fallbackID string, async bool) {+ // Record the resolution before the callback guard: this funnel is the+ // resolve seam for every lifecycle path, with or without subscribers.+ m.recordAlertEvent(eventlog.TypeResolved, alert, fallbackID, "", "Alert resolved.", nil)+callbacks := m.getResolvedCallbacks()if len(callbacks) == 0 {return@@ -375,6 +381,9 @@ func (m *Manager) safeCallResolvedAlertCallback(alert *Alert, fallbackID string,// safeCallAcknowledgedCallback invokes onAcknowledged with panic recovery and alert cloning.func (m *Manager) safeCallAcknowledgedCallback(alert *Alert, user string) {+ m.recordAlertEvent(eventlog.TypeAcknowledged, alert, "", "", "Alert acknowledged.",+ map[string]string{"user": user})+callback := m.getAcknowledgedCallback()if callback == nil || alert == nil {return@@ -396,6 +405,9 @@ func (m *Manager) safeCallAcknowledgedCallback(alert *Alert, user string) {// safeCallUnacknowledgedCallback invokes onUnacknowledged with panic recovery and alert cloning.func (m *Manager) safeCallUnacknowledgedCallback(alert *Alert, user string) {+ m.recordAlertEvent(eventlog.TypeUnacknowledged, alert, "", "", "Alert acknowledgement removed.",+ map[string]string{"user": user})+callback := m.getUnacknowledgedCallback()if callback == nil || alert == nil {return@@ -417,6 +429,9 @@ func (m *Manager) safeCallUnacknowledgedCallback(alert *Alert, user string) {// safeCallEscalateCallback invokes onEscalate with panic recovery and alert cloning.func (m *Manager) safeCallEscalateCallback(alert *Alert, level int) {+ m.recordAlertEvent(eventlog.TypeEscalated, alert, "", "", "Alert escalated.",+ map[string]string{"level": strconv.Itoa(level)})+callback := m.getEscalateCallback()if callback == nil {returndiff --git a/internal/alerts/event_emission.go b/internal/alerts/event_emission.gonew file mode 100644index 0000000000..993078bb72--- /dev/null+++ b/internal/alerts/event_emission.go@@ -0,0 +1,96 @@+package alerts++// Alert event emission: the manager records lifecycle transitions and+// notification decisions — including suppressions, with reasons — into the+// append-only event log (docs/ALERT_ENGINE_EVOLUTION.md, Phase 0). Emission+// is additive and non-blocking: a nil or failed store records nothing and+// changes no lifecycle behavior.++import (+ "os"++ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog"+ "github.com/rs/zerolog/log"+)++// EnableEventLog opens the persistent alert event log under the manager's+// alerts directory. The monitoring bootstrap calls this once per manager;+// without it (tests, ephemeral managers) no events are recorded.+func (m *Manager) EnableEventLog() {+ if m == nil {+ return+ }+ if err := os.MkdirAll(m.alertsDir, 0700); err != nil {+ log.Warn().Err(err).Str("dir", m.alertsDir).Msg("alert event log disabled: cannot create alerts directory")+ return+ }+ store, err := eventlog.Open(m.alertsDir)+ if err != nil {+ log.Warn().Err(err).Msg("alert event log disabled")+ return+ }+ m.SetEventLog(store)+}++// SetEventLog installs an event log store. Passing nil disables recording.+// The previous store, if any, is closed.+func (m *Manager) SetEventLog(store *eventlog.Store) {+ if m == nil {+ return+ }+ previous := m.eventLog.Swap(store)+ if previous != nil && previous != store {+ previous.Close()+ }+}++func (m *Manager) eventLogStore() *eventlog.Store {+ if m == nil {+ return nil+ }+ return m.eventLog.Load()+}++// AlertEvents returns matching events from the persistent event log, newest+// first. It flushes buffered appends first so a caller reading right after a+// transition observes it.+func (m *Manager) AlertEvents(filter eventlog.Filter) ([]eventlog.Event, error) {+ store := m.eventLogStore()+ if store == nil {+ return nil, nil+ }+ store.Flush()+ return store.Query(filter)+}++// recordAlertEvent appends one event for an alert. alertID is the identity+// fallback for callers whose *Alert may be nil (some resolve paths); when the+// alert is present its exported ID wins. Never blocks; safe under m.mu.+func (m *Manager) recordAlertEvent(eventType string, alert *Alert, alertID, reason, message string, details map[string]string) {+ store := m.eventLogStore()+ if store == nil {+ return+ }++ event := eventlog.Event{+ OccurredAt: m.policyNow(),+ Type: eventType,+ AlertID: alertID,+ Reason: reason,+ Message: message,+ Details: details,+ }+ if alert != nil {+ if id := exportedAlertID(alert, alertID); id != "" {+ event.AlertID = id+ }+ event.ResourceID = alert.ResourceID+ event.ResourceName = alert.ResourceName+ event.AlertType = alert.Type+ event.Level = string(alert.Level)+ }+ if event.AlertID == "" {+ return+ }+ store.Append(event)+}diff --git a/internal/alerts/event_emission_test.go b/internal/alerts/event_emission_test.gonew file mode 100644index 0000000000..b935107b57--- /dev/null+++ b/internal/alerts/event_emission_test.go@@ -0,0 +1,208 @@+package alerts++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog"+)++func newEventLogManager(t *testing.T) *Manager {+ t.Helper()++ manager := NewManagerWithDataDir(t.TempDir(), WithoutPersistedAlertRestore())+ t.Cleanup(manager.Stop)++ store, err := eventlog.OpenInMemory()+ if err != nil {+ t.Fatalf("open in-memory event log: %v", err)+ }+ manager.SetEventLog(store)++ cfg := manager.GetConfig()+ cfg.Enabled = true+ cfg.ActivationState = ActivationActive+ cfg.Schedule.Cooldown = 5+ manager.UpdateConfig(cfg)++ return manager+}++func addEventLogAlert(manager *Manager, alert *Alert) *Alert {+ manager.mu.Lock()+ defer manager.mu.Unlock()+ manager.activeAlerts[alert.ID] = alert+ return alert+}++func queryAlertEvents(t *testing.T, manager *Manager, filter eventlog.Filter) []eventlog.Event {+ t.Helper()+ events, err := manager.AlertEvents(filter)+ if err != nil {+ t.Fatalf("AlertEvents: %v", err)+ }+ return events+}++func TestEventLogRecordsAcknowledgeAndUnacknowledge(t *testing.T) {+ manager := newEventLogManager(t)+ addEventLogAlert(manager, &Alert{+ ID: "ack-alert",+ Type: "cpu",+ Level: AlertLevelWarning,+ ResourceID: "node-1",+ ResourceName: "node-1",+ StartTime: time.Now().Add(-10 * time.Minute),+ })++ if err := manager.AcknowledgeAlert("ack-alert", "richard"); err != nil {+ t.Fatalf("AcknowledgeAlert: %v", err)+ }+ if err := manager.UnacknowledgeAlert("ack-alert"); err != nil {+ t.Fatalf("UnacknowledgeAlert: %v", err)+ }++ acked := queryAlertEvents(t, manager, eventlog.Filter{Types: []string{eventlog.TypeAcknowledged}})+ if len(acked) != 1 {+ t.Fatalf("acknowledged events = %d, want 1", len(acked))+ }+ if acked[0].AlertID != "ack-alert" || acked[0].Details["user"] != "richard" {+ t.Fatalf("acknowledged event = %+v, want ack-alert by richard", acked[0])+ }+ unacked := queryAlertEvents(t, manager, eventlog.Filter{Types: []string{eventlog.TypeUnacknowledged}})+ if len(unacked) != 1 {+ t.Fatalf("unacknowledged events = %d, want 1", len(unacked))+ }+}++func TestEventLogRecordsResolvedOnClear(t *testing.T) {+ manager := newEventLogManager(t)+ addEventLogAlert(manager, &Alert{+ ID: "resolve-alert",+ Type: "memory",+ Level: AlertLevelCritical,+ ResourceID: "node-2",+ ResourceName: "node-2",+ StartTime: time.Now().Add(-10 * time.Minute),+ })++ if !manager.ClearAlert("resolve-alert") {+ t.Fatal("ClearAlert returned false")+ }++ events := queryAlertEvents(t, manager, eventlog.Filter{+ AlertID: "resolve-alert",+ Types: []string{eventlog.TypeResolved},+ })+ if len(events) != 1 {+ t.Fatalf("resolved events = %d, want 1", len(events))+ }+ if events[0].ResourceName != "node-2" || events[0].Level != string(AlertLevelCritical) {+ t.Fatalf("resolved event = %+v, want node-2/critical context", events[0])+ }+}++func TestEventLogRecordsDispatchDecisions(t *testing.T) {+ manager := newEventLogManager(t)+ manager.SetAlertCallback(func(alert *Alert) {})++ dispatch := func(alert *Alert) bool {+ manager.mu.Lock()+ defer manager.mu.Unlock()+ return manager.dispatchAlert(alert, false)+ }++ sent := addEventLogAlert(manager, &Alert{+ ID: "dispatch-alert",+ Type: "cpu",+ Level: AlertLevelWarning,+ ResourceID: "node-1",+ ResourceName: "node-1",+ StartTime: time.Now().Add(-10 * time.Minute),+ })+ if !dispatch(sent) {+ t.Fatal("dispatchAlert returned false for eligible alert")+ }++ suppressedAlert := addEventLogAlert(manager, &Alert{+ ID: "suppressed-alert",+ Type: "cpu",+ Level: AlertLevelWarning,+ ResourceID: "node-1",+ ResourceName: "node-1",+ StartTime: time.Now().Add(-10 * time.Minute),+ Acknowledged: true,+ })+ if dispatch(suppressedAlert) {+ t.Fatal("dispatchAlert returned true for acknowledged alert")+ }++ dispatched := queryAlertEvents(t, manager, eventlog.Filter{Types: []string{eventlog.TypeNotificationDispatched}})+ if len(dispatched) != 1 || dispatched[0].AlertID != "dispatch-alert" {+ t.Fatalf("dispatched events = %+v, want one for dispatch-alert", dispatched)+ }++ suppressed := queryAlertEvents(t, manager, eventlog.Filter{Types: []string{eventlog.TypeNotificationSuppressed}})+ if len(suppressed) != 1 || suppressed[0].AlertID != "suppressed-alert" {+ t.Fatalf("suppressed events = %+v, want one for suppressed-alert", suppressed)+ }+ if suppressed[0].Reason != AlertDeliveryReasonAcknowledged {+ t.Fatalf("suppressed reason = %q, want %q", suppressed[0].Reason, AlertDeliveryReasonAcknowledged)+ }+}++func TestEventLogRecordsInactiveActivationSuppression(t *testing.T) {+ manager := newEventLogManager(t)+ manager.SetAlertCallback(func(alert *Alert) {})++ cfg := manager.GetConfig()+ cfg.ActivationState = ActivationPending+ manager.UpdateConfig(cfg)++ alert := addEventLogAlert(manager, &Alert{+ ID: "pending-alert",+ Type: "cpu",+ Level: AlertLevelWarning,+ ResourceID: "node-1",+ ResourceName: "node-1",+ StartTime: time.Now().Add(-10 * time.Minute),+ })++ manager.mu.Lock()+ dispatched := manager.dispatchAlert(alert, false)+ manager.mu.Unlock()+ if dispatched {+ t.Fatal("dispatchAlert returned true while activation is pending")+ }++ events := queryAlertEvents(t, manager, eventlog.Filter{Types: []string{eventlog.TypeNotificationSuppressed}})+ if len(events) != 1 {+ t.Fatalf("suppressed events = %d, want 1", len(events))+ }+ if events[0].Reason != AlertDeliveryReasonNotificationsInactive {+ t.Fatalf("reason = %q, want %q", events[0].Reason, AlertDeliveryReasonNotificationsInactive)+ }+}++func TestEventLogDisabledManagerRecordsNothing(t *testing.T) {+ manager := NewManagerWithDataDir(t.TempDir(), WithoutPersistedAlertRestore())+ t.Cleanup(manager.Stop)++ addEventLogAlert(manager, &Alert{+ ID: "no-log-alert",+ Type: "cpu",+ Level: AlertLevelWarning,+ StartTime: time.Now(),+ })+ if err := manager.AcknowledgeAlert("no-log-alert", "richard"); err != nil {+ t.Fatalf("AcknowledgeAlert: %v", err)+ }++ events, err := manager.AlertEvents(eventlog.Filter{})+ if err != nil {+ t.Fatalf("AlertEvents: %v", err)+ }+ if events != nil {+ t.Fatalf("events = %+v, want nil with no event log", events)+ }+}diff --git a/internal/alerts/eventlog/eventlog.go b/internal/alerts/eventlog/eventlog.gonew file mode 100644index 0000000000..57d9b06a5c--- /dev/null+++ b/internal/alerts/eventlog/eventlog.go@@ -0,0 +1,417 @@+// Package eventlog is the append-only alert event log: every alert lifecycle+// transition and notification decision — including suppressions, with the+// mechanism that held them — is recorded as one immutable event. It exists so+// "why didn't I get notified?" is answerable from durable data instead of+// being reconstructed from logs (docs/ALERT_ENGINE_EVOLUTION.md, Phase 0).+//+// The store is additive to the live alert manager: appends never block the+// evaluation path (a full buffer drops the event and counts the drop), and a+// store that fails to open degrades to a nil store whose methods are no-ops.+package eventlog++import (+ "database/sql"+ "encoding/json"+ "fmt"+ "net/url"+ "os"+ "strings"+ "sync"+ "sync/atomic"+ "time"++ "github.com/rs/zerolog/log"+ _ "modernc.org/sqlite"+)++// Event types recorded by the alert manager. Lifecycle "fired" is+// deliberately absent: the active-alert store funnel also runs on persisted+// restore, so firing cannot be recorded there without misreporting restarts.+// It arrives with the explicit activation seam in a later phase.+const (+ TypeResolved = "resolved"+ TypeAcknowledged = "acknowledged"+ TypeUnacknowledged = "unacknowledged"+ TypeEscalated = "escalated"+ TypeFlappingDetected = "flapping_detected"+ TypeNotificationDispatched = "notification_dispatched"+ TypeNotificationDeferred = "notification_deferred"+ TypeNotificationSuppressed = "notification_suppressed"+)++// Event is one immutable alert event.+type Event struct {+ ID int64 `json:"id"`+ OccurredAt time.Time `json:"occurredAt"`+ Type string `json:"type"`+ AlertID string `json:"alertId"`+ ResourceID string `json:"resourceId,omitempty"`+ ResourceName string `json:"resourceName,omitempty"`+ AlertType string `json:"alertType,omitempty"`+ Level string `json:"level,omitempty"`+ Reason string `json:"reason,omitempty"`+ Message string `json:"message,omitempty"`+ Details map[string]string `json:"details,omitempty"`+}++// Filter narrows a Query. Zero values mean "no constraint".+type Filter struct {+ AlertID string+ Types []string+ Since time.Time+ Until time.Time+ Limit int+}++const (+ defaultQueryLimit = 200+ maxQueryLimit = 1000+ appendBufferSize = 1024+ // defaultRetention keeps events long enough to explain a past incident+ // without growing without bound.+ defaultRetention = 90 * 24 * time.Hour+ pruneInterval = time.Hour+ eventLogFileName = "events.db"+)++// Store is the SQLite-backed event log. A nil *Store is valid: Append and+// Close are no-ops and Query returns no events.+type Store struct {+ db *sql.DB+ dbPath string+ events chan Event+ stop chan struct{}+ wg sync.WaitGroup+ closeOnce sync.Once+ dropped atomic.Int64+ appended atomic.Int64+ written atomic.Int64+ retention time.Duration+}++func sqliteDSN(path string) string {+ separator := "?"+ if strings.Contains(path, "?") {+ separator = "&"+ }+ return path + separator + url.Values{+ "_pragma": []string{+ "busy_timeout(30000)",+ "journal_mode(WAL)",+ "synchronous(NORMAL)",+ "cache_size(-16000)",+ },+ }.Encode()+}++// Open creates or opens the event log inside dir (the manager's alerts data+// directory). The directory must already exist.+func Open(dir string) (*Store, error) {+ trimmed := strings.TrimSpace(dir)+ if trimmed == "" {+ return nil, fmt.Errorf("event log directory is required")+ }+ if info, err := os.Stat(trimmed); err != nil {+ return nil, fmt.Errorf("event log directory: %w", err)+ } else if !info.IsDir() {+ return nil, fmt.Errorf("event log directory %q is not a directory", trimmed)+ }+ dbPath := trimmed + string(os.PathSeparator) + eventLogFileName+ return openDSN(dbPath, sqliteDSN(dbPath))+}++// OpenInMemory creates a non-persistent store with identical behavior, for+// tests and as a fallback owner when on-disk bootstrap fails.+func OpenInMemory() (*Store, error) {+ return openDSN(":memory:", sqliteDSN("file::memory:?mode=memory"))+}++func openDSN(dbPath, dsn string) (*Store, error) {+ db, err := sql.Open("sqlite", dsn)+ if err != nil {+ return nil, fmt.Errorf("open alert event log: %w", err)+ }+ // Single connection: the write path is one goroutine, and WAL keeps the+ // rare reads from blocking behind it for long.+ db.SetMaxOpenConns(1)+ db.SetMaxIdleConns(1)+ db.SetConnMaxLifetime(0)++ s := &Store{+ db: db,+ dbPath: dbPath,+ events: make(chan Event, appendBufferSize),+ stop: make(chan struct{}),+ retention: defaultRetention,+ }+ if err := s.initSchema(); err != nil {+ db.Close()+ return nil, fmt.Errorf("init alert event log schema: %w", err)+ }++ s.wg.Add(1)+ go s.writeLoop()++ log.Info().Str("dbPath", dbPath).Msg("alert event log initialized")+ return s, nil+}++func (s *Store) initSchema() error {+ _, err := s.db.Exec(`+ CREATE TABLE IF NOT EXISTS alert_events (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ occurred_at TEXT NOT NULL,+ event_type TEXT NOT NULL,+ alert_id TEXT NOT NULL,+ resource_id TEXT NOT NULL DEFAULT '',+ resource_name TEXT NOT NULL DEFAULT '',+ alert_type TEXT NOT NULL DEFAULT '',+ level TEXT NOT NULL DEFAULT '',+ reason TEXT NOT NULL DEFAULT '',+ message TEXT NOT NULL DEFAULT '',+ details TEXT NOT NULL DEFAULT ''+ );+ CREATE INDEX IF NOT EXISTS idx_alert_events_alert ON alert_events(alert_id, occurred_at);+ CREATE INDEX IF NOT EXISTS idx_alert_events_time ON alert_events(occurred_at);+ CREATE INDEX IF NOT EXISTS idx_alert_events_type ON alert_events(event_type, occurred_at);+ `)+ return err+}++// Append records one event without blocking: when the buffer is full the+// event is dropped and counted, never stalling alert evaluation. Safe to+// call on a nil store and while holding manager locks.+func (s *Store) Append(event Event) {+ if s == nil {+ return+ }+ if event.OccurredAt.IsZero() {+ event.OccurredAt = time.Now()+ }+ select {+ case s.events <- event:+ s.appended.Add(1)+ default:+ s.dropped.Add(1)+ }+}++// Dropped reports how many events were discarded because the append buffer+// was full. A non-zero value means the log is incomplete for that window.+func (s *Store) Dropped() int64 {+ if s == nil {+ return 0+ }+ return s.dropped.Load()+}++func (s *Store) writeLoop() {+ defer s.wg.Done()+ pruneTicker := time.NewTicker(pruneInterval)+ defer pruneTicker.Stop()+ s.pruneOld()++ for {+ select {+ case event := <-s.events:+ batch := []Event{event}+ drain:+ for len(batch) < 128 {+ select {+ case next := <-s.events:+ batch = append(batch, next)+ default:+ break drain+ }+ }+ if err := s.insertBatch(batch); err != nil {+ log.Error().Err(err).Int("events", len(batch)).Msg("alert event log write failed")+ }+ s.written.Add(int64(len(batch)))+ case <-pruneTicker.C:+ s.pruneOld()+ case <-s.stop:+ // Final drain so a clean shutdown does not lose buffered events.+ for {+ select {+ case event := <-s.events:+ if err := s.insertBatch([]Event{event}); err != nil {+ log.Error().Err(err).Msg("alert event log final drain write failed")+ }+ s.written.Add(1)+ default:+ return+ }+ }+ }+ }+}++func (s *Store) insertBatch(batch []Event) error {+ tx, err := s.db.Begin()+ if err != nil {+ return err+ }+ stmt, err := tx.Prepare(`+ INSERT INTO alert_events+ (occurred_at, event_type, alert_id, resource_id, resource_name, alert_type, level, reason, message, details)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `)+ if err != nil {+ _ = tx.Rollback()+ return err+ }+ defer stmt.Close()+ for _, event := range batch {+ details := ""+ if len(event.Details) > 0 {+ encoded, err := json.Marshal(event.Details)+ if err == nil {+ details = string(encoded)+ }+ }+ if _, err := stmt.Exec(+ event.OccurredAt.UTC().Format(time.RFC3339Nano),+ event.Type,+ event.AlertID,+ event.ResourceID,+ event.ResourceName,+ event.AlertType,+ event.Level,+ event.Reason,+ event.Message,+ details,+ ); err != nil {+ _ = tx.Rollback()+ return err+ }+ }+ return tx.Commit()+}++func (s *Store) pruneOld() {+ if s.retention <= 0 {+ return+ }+ cutoff := time.Now().Add(-s.retention).UTC().Format(time.RFC3339Nano)+ if _, err := s.db.Exec(`DELETE FROM alert_events WHERE occurred_at < ?`, cutoff); err != nil {+ log.Error().Err(err).Msg("alert event log prune failed")+ }+}++// Flush blocks until every event appended before the call has been written+// (or a short deadline passes). It exists for tests and API reads that must+// observe just-appended events.+func (s *Store) Flush() {+ if s == nil {+ return+ }+ target := s.appended.Load()+ deadline := time.Now().Add(5 * time.Second)+ for s.written.Load() < target && time.Now().Before(deadline) {+ time.Sleep(time.Millisecond)+ }+}++// Query returns matching events, newest first.+func (s *Store) Query(filter Filter) ([]Event, error) {+ if s == nil {+ return nil, nil+ }++ where := make([]string, 0, 4)+ args := make([]any, 0, 6)+ if trimmed := strings.TrimSpace(filter.AlertID); trimmed != "" {+ where = append(where, "alert_id = ?")+ args = append(args, trimmed)+ }+ if len(filter.Types) > 0 {+ placeholders := make([]string, 0, len(filter.Types))+ for _, eventType := range filter.Types {+ trimmed := strings.TrimSpace(eventType)+ if trimmed == "" {+ continue+ }+ placeholders = append(placeholders, "?")+ args = append(args, trimmed)+ }+ if len(placeholders) > 0 {+ where = append(where, "event_type IN ("+strings.Join(placeholders, ",")+")")+ }+ }+ if !filter.Since.IsZero() {+ where = append(where, "occurred_at >= ?")+ args = append(args, filter.Since.UTC().Format(time.RFC3339Nano))+ }+ if !filter.Until.IsZero() {+ where = append(where, "occurred_at <= ?")+ args = append(args, filter.Until.UTC().Format(time.RFC3339Nano))+ }++ limit := filter.Limit+ if limit <= 0 {+ limit = defaultQueryLimit+ }+ if limit > maxQueryLimit {+ limit = maxQueryLimit+ }++ query := "SELECT id, occurred_at, event_type, alert_id, resource_id, resource_name, alert_type, level, reason, message, details FROM alert_events"+ if len(where) > 0 {+ query += " WHERE " + strings.Join(where, " AND ")+ }+ query += " ORDER BY occurred_at DESC, id DESC LIMIT ?"+ args = append(args, limit)++ rows, err := s.db.Query(query, args...)+ if err != nil {+ return nil, fmt.Errorf("query alert event log: %w", err)+ }+ defer rows.Close()++ events := make([]Event, 0, limit)+ for rows.Next() {+ var event Event+ var occurredAt, details string+ if err := rows.Scan(+ &event.ID,+ &occurredAt,+ &event.Type,+ &event.AlertID,+ &event.ResourceID,+ &event.ResourceName,+ &event.AlertType,+ &event.Level,+ &event.Reason,+ &event.Message,+ &details,+ ); err != nil {+ return nil, fmt.Errorf("scan alert event: %w", err)+ }+ if parsed, err := time.Parse(time.RFC3339Nano, occurredAt); err == nil {+ event.OccurredAt = parsed+ }+ if details != "" {+ decoded := map[string]string{}+ if err := json.Unmarshal([]byte(details), &decoded); err == nil && len(decoded) > 0 {+ event.Details = decoded+ }+ }+ events = append(events, event)+ }+ return events, rows.Err()+}++// Close drains buffered events and closes the database.+func (s *Store) Close() {+ if s == nil {+ return+ }+ s.closeOnce.Do(func() {+ close(s.stop)+ s.wg.Wait()+ if err := s.db.Close(); err != nil {+ log.Error().Err(err).Msg("alert event log close failed")+ }+ })+}diff --git a/internal/alerts/eventlog/eventlog_test.go b/internal/alerts/eventlog/eventlog_test.gonew file mode 100644index 0000000000..91d9e226f8--- /dev/null+++ b/internal/alerts/eventlog/eventlog_test.go@@ -0,0 +1,156 @@+package eventlog++import (+ "testing"+ "time"+)++func newTestStore(t *testing.T) *Store {+ t.Helper()+ store, err := OpenInMemory()+ if err != nil {+ t.Fatalf("open in-memory store: %v", err)+ }+ t.Cleanup(store.Close)+ return store+}++func TestAppendAndQueryRoundTrip(t *testing.T) {+ store := newTestStore(t)+ occurred := time.Date(2026, 8, 26, 10, 0, 0, 0, time.UTC)++ store.Append(Event{+ OccurredAt: occurred,+ Type: TypeNotificationSuppressed,+ AlertID: "alert-1",+ ResourceID: "node/pve-1",+ ResourceName: "pve-1",+ AlertType: "cpu",+ Level: "warning",+ Reason: "flapping",+ Message: "Alert suppressed due to flapping",+ Details: map[string]string{"trackingKey": "node/pve-1/cpu"},+ })+ store.Flush()++ events, err := store.Query(Filter{AlertID: "alert-1"})+ if err != nil {+ t.Fatalf("query: %v", err)+ }+ if len(events) != 1 {+ t.Fatalf("len(events) = %d, want 1", len(events))+ }+ event := events[0]+ if event.Type != TypeNotificationSuppressed || event.Reason != "flapping" {+ t.Fatalf("event = %+v, want suppressed/flapping", event)+ }+ if !event.OccurredAt.Equal(occurred) {+ t.Fatalf("OccurredAt = %v, want %v", event.OccurredAt, occurred)+ }+ if event.Details["trackingKey"] != "node/pve-1/cpu" {+ t.Fatalf("Details = %v, want trackingKey preserved", event.Details)+ }+}++func TestQueryFiltersByTypeAndTime(t *testing.T) {+ store := newTestStore(t)+ base := time.Date(2026, 8, 26, 10, 0, 0, 0, time.UTC)++ store.Append(Event{OccurredAt: base, Type: TypeResolved, AlertID: "a1"})+ store.Append(Event{OccurredAt: base.Add(time.Minute), Type: TypeAcknowledged, AlertID: "a1"})+ store.Append(Event{OccurredAt: base.Add(2 * time.Minute), Type: TypeResolved, AlertID: "a2"})+ store.Flush()++ byType, err := store.Query(Filter{Types: []string{TypeResolved}})+ if err != nil {+ t.Fatalf("query by type: %v", err)+ }+ if len(byType) != 2 {+ t.Fatalf("len(byType) = %d, want 2", len(byType))+ }+ // Newest first.+ if byType[0].AlertID != "a2" || byType[1].AlertID != "a1" {+ t.Fatalf("order = %s,%s, want a2,a1", byType[0].AlertID, byType[1].AlertID)+ }++ windowed, err := store.Query(Filter{Since: base.Add(30 * time.Second), Until: base.Add(90 * time.Second)})+ if err != nil {+ t.Fatalf("query by window: %v", err)+ }+ if len(windowed) != 1 || windowed[0].Type != TypeAcknowledged {+ t.Fatalf("windowed = %+v, want the acknowledged event only", windowed)+ }+}++func TestQueryLimitCaps(t *testing.T) {+ store := newTestStore(t)+ base := time.Date(2026, 8, 26, 10, 0, 0, 0, time.UTC)+ for i := 0; i < 10; i++ {+ store.Append(Event{OccurredAt: base.Add(time.Duration(i) * time.Second), Type: TypeResolved, AlertID: "a1"})+ }+ store.Flush()++ events, err := store.Query(Filter{Limit: 3})+ if err != nil {+ t.Fatalf("query: %v", err)+ }+ if len(events) != 3 {+ t.Fatalf("len(events) = %d, want 3", len(events))+ }+}++func TestNilStoreIsSafe(t *testing.T) {+ var store *Store+ store.Append(Event{Type: TypeResolved, AlertID: "a1"})+ store.Flush()+ store.Close()+ if got := store.Dropped(); got != 0 {+ t.Fatalf("Dropped() = %d, want 0", got)+ }+ events, err := store.Query(Filter{})+ if err != nil || events != nil {+ t.Fatalf("Query = %v, %v, want nil, nil", events, err)+ }+}++func TestCloseDrainsBufferedEvents(t *testing.T) {+ store, err := OpenInMemory()+ if err != nil {+ t.Fatalf("open in-memory store: %v", err)+ }+ for i := 0; i < 50; i++ {+ store.Append(Event{Type: TypeNotificationDispatched, AlertID: "a1"})+ }+ store.Close()++ // Query after Close is not supported; reopen semantics do not apply to+ // the in-memory store, so assert via the counters instead.+ if store.Dropped() != 0 {+ t.Fatalf("Dropped() = %d, want 0", store.Dropped())+ }+ if store.written.Load() != 50 {+ t.Fatalf("written = %d, want 50", store.written.Load())+ }+}++func TestOpenRequiresExistingDirectory(t *testing.T) {+ if _, err := Open(""); err == nil {+ t.Fatal("Open(\"\") should fail")+ }+ if _, err := Open(t.TempDir() + "/missing"); err == nil {+ t.Fatal("Open on a missing directory should fail")+ }++ dir := t.TempDir()+ store, err := Open(dir)+ if err != nil {+ t.Fatalf("Open(%q): %v", dir, err)+ }+ store.Append(Event{Type: TypeResolved, AlertID: "a1"})+ store.Flush()+ events, err := store.Query(Filter{})+ if err != nil || len(events) != 1 {+ t.Fatalf("Query = %v, %v, want one event", events, err)+ }+ store.Close()+}diff --git a/internal/alerts/lifecycle.go b/internal/alerts/lifecycle.goindex a35386ece1..29c60f4f56 100644--- a/internal/alerts/lifecycle.go+++ b/internal/alerts/lifecycle.go@@ -23,6 +23,10 @@ func (m *Manager) Stop() {if err := m.SaveActiveAlerts(); err != nil {log.Error().Err(err).Msg("Failed to save active alerts on stop")}++ // Drain and close the event log last so shutdown-time transitions+ // are still recorded.+ m.SetEventLog(nil)})}diff --git a/internal/alerts/manager.go b/internal/alerts/manager.goindex 269e76c1dc..2f0c8ab799 100644--- a/internal/alerts/manager.go+++ b/internal/alerts/manager.go@@ -4,8 +4,10 @@ import ("path/filepath""strings""sync"+ "sync/atomic""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog""github.com/rcourtman/pulse-go-rewrite/internal/utils""github.com/rs/zerolog/log")@@ -99,6 +101,10 @@ type Manager struct {// License checking for Pro-only alert featureshasProFeature func(feature string) bool+ // Append-only alert event log (transitions + notification decisions).+ // Nil until EnableEventLog/SetEventLog; recording is then a no-op.+ eventLog atomic.Pointer[eventlog.Store]+// Cached timezone for quiet hoursquietHoursLoc *time.Locationnow func() time.Timediff --git a/internal/alerts/notification_policy.go b/internal/alerts/notification_policy.goindex a0f962f8fc..ec67dc594f 100644--- a/internal/alerts/notification_policy.go+++ b/internal/alerts/notification_policy.go@@ -5,6 +5,7 @@ import ("strings""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rs/zerolog/log")@@ -167,6 +168,8 @@ func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {Str("alertID", alert.ID).Str("ackUser", alert.AckUser).Msg("Alert notification suppressed - already acknowledged")+ m.recordAlertEvent(eventlog.TypeNotificationSuppressed, alert, "",+ AlertDeliveryReasonAcknowledged, "Notification suppressed: alert is acknowledged.", nil)return false}@@ -180,6 +183,9 @@ func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {// to take its own locks or re-enter the alerts package.suppress, justTransitioned := m.checkFlappingLocked(trackingKey)if justTransitioned {+ m.recordAlertEvent(eventlog.TypeFlappingDetected, alert, "",+ AlertDeliveryReasonFlapping, "Alert entered flapping suppression.",+ map[string]string{"trackingKey": trackingKey})cb := m.callbacks.flappingDetectedCallback()if cb != nil {alertCopy := cloneAlertForOutput(alert)@@ -202,6 +208,9 @@ func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {Str("alertID", alert.ID).Str("trackingKey", trackingKey).Msg("Alert suppressed due to flapping")+ m.recordAlertEvent(eventlog.TypeNotificationSuppressed, alert, "",+ AlertDeliveryReasonFlapping, "Notification suppressed: alert is flapping.",+ map[string]string{"trackingKey": trackingKey})return false}@@ -211,6 +220,9 @@ func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {Str("alertID", alert.ID).Str("activationState", string(m.config.ActivationState)).Msg("Alert notification suppressed - not activated")+ m.recordAlertEvent(eventlog.TypeNotificationSuppressed, alert, "",+ AlertDeliveryReasonNotificationsInactive, "Notification suppressed: alert delivery is not turned on.",+ map[string]string{"activationState": string(m.config.ActivationState)})return false}@@ -224,6 +236,13 @@ func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {Str("quietHoursRule", reason).Time("replayAt", replayAt).Msg("Alert notification deferred during quiet hours")+ deferredReason := AlertDeliveryReasonQuietHours+ if reason != "" {+ deferredReason += ":" + reason+ }+ m.recordAlertEvent(eventlog.TypeNotificationDeferred, alert, "",+ deferredReason, "Notification deferred by quiet hours; the queue replays it when they end.",+ map[string]string{"replayAt": replayAt.UTC().Format(time.RFC3339)})} else {clearQuietHoursNotificationReplay(alert)}@@ -234,6 +253,8 @@ func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {Str("resource", alert.ResourceName).Bool("monitorOnly", true).Msg("Monitor-only alert detected, skipping alert dispatch")+ m.recordAlertEvent(eventlog.TypeNotificationSuppressed, alert, "",+ AlertDeliveryReasonMonitorOnly, "Notification suppressed: alert is monitor-only.", nil)return false}@@ -245,6 +266,8 @@ func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {notifiedAt := time.Now()m.recordAlertNotifiedNoLock(alert, notifiedAt)m.saveActiveAlertsAsync("alert-dispatch")+ m.recordAlertEvent(eventlog.TypeNotificationDispatched, alert, "",+ AlertDeliveryReasonReady, "Notification dispatched to the delivery pipeline.", nil)alertCopy := cloneAlertForOutput(alert)if async {diff --git a/internal/api/alerting/alerts.go b/internal/api/alerting/alerts.goindex af4f113a37..3fd6e60615 100644--- a/internal/api/alerting/alerts.go+++ b/internal/api/alerting/alerts.go@@ -14,6 +14,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/memory""github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog""github.com/rcourtman/pulse-go-rewrite/internal/api/apicontext""github.com/rcourtman/pulse-go-rewrite/internal/api/apihttp""github.com/rcourtman/pulse-go-rewrite/internal/config"@@ -33,6 +34,7 @@ type AlertManager interface {GetActiveAlerts() []alerts.AlertDiagnoseAlertDelivery(alertIdentifier string) (alerts.AlertDeliveryDiagnosis, bool)DiagnoseActiveAlertDeliveries() []alerts.AlertDeliveryDiagnosis+ AlertEvents(filter eventlog.Filter) ([]eventlog.Event, error)NotifyExistingAlert(id string)ClearAlertHistory() errorUnacknowledgeAlert(id string) error@@ -475,6 +477,72 @@ func (h *AlertHandlers) GetAlertDeliveryDiagnosis(w http.ResponseWriter, r *http}}+// GetAlertEvents returns entries from the append-only alert event log:+// lifecycle transitions and notification decisions, including suppressions+// with reasons. Newest first.+func (h *AlertHandlers) GetAlertEvents(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ query := r.URL.Query()+ filter := eventlog.Filter{+ AlertID: strings.TrimSpace(query.Get("alertIdentifier")),+ }+ if filter.AlertID != "" && !validateAlertIdentifier(filter.AlertID) {+ http.Error(w, "Invalid alert identifier", http.StatusBadRequest)+ return+ }+ for _, raw := range query["type"] {+ for _, part := range strings.Split(raw, ",") {+ if trimmed := strings.TrimSpace(part); trimmed != "" {+ filter.Types = append(filter.Types, trimmed)+ }+ }+ }+ if since := strings.TrimSpace(query.Get("since")); since != "" {+ parsed, err := time.Parse(time.RFC3339, since)+ if err != nil {+ http.Error(w, "since must be RFC3339", http.StatusBadRequest)+ return+ }+ filter.Since = parsed+ }+ if limitRaw := strings.TrimSpace(query.Get("limit")); limitRaw != "" {+ limit, err := strconv.Atoi(limitRaw)+ if err != nil || limit <= 0 {+ http.Error(w, "limit must be a positive integer", http.StatusBadRequest)+ return+ }+ filter.Limit = limit+ }++ monitor := h.getMonitor(r.Context())+ if monitor == nil {+ http.Error(w, "monitor is not initialized", http.StatusServiceUnavailable)+ return+ }+ manager := monitor.GetAlertManager()+ if manager == nil {+ http.Error(w, "alert manager is not initialized", http.StatusServiceUnavailable)+ return+ }++ events, err := manager.AlertEvents(filter)+ if err != nil {+ log.Error().Err(err).Msg("Failed to query alert event log")+ http.Error(w, "failed to query alert events", http.StatusInternalServerError)+ return+ }+ if events == nil {+ events = []eventlog.Event{}+ }+ if err := utils.WriteJSONResponse(w, events); err != nil {+ log.Error().Err(err).Msg("Failed to write alert events response")+ }+}+// GetAlertHistory returns alert historyfunc (h *AlertHandlers) GetAlertHistory(w http.ResponseWriter, r *http.Request) {query := r.URL.Query()@@ -1215,6 +1283,11 @@ func (h *AlertHandlers) HandleAlerts(w http.ResponseWriter, r *http.Request) {return}h.GetAlertDeliveryDiagnosis(w, r)+ case path == "events" && r.Method == http.MethodGet:+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {+ return+ }+ h.GetAlertEvents(w, r)case path == "history" && r.Method == http.MethodGet:if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {returndiff --git a/internal/api/alerting/alerts_test.go b/internal/api/alerting/alerts_test.goindex 0e2ae5bb5f..31ac1339f0 100644--- a/internal/api/alerting/alerts_test.go+++ b/internal/api/alerting/alerts_test.go@@ -15,6 +15,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/memory""github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/notifications""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"@@ -85,6 +86,12 @@ func (m *MockAlertManager) DiagnoseActiveAlertDeliveries() []alerts.AlertDeliverreturn args.Get(0).([]alerts.AlertDeliveryDiagnosis)}+func (m *MockAlertManager) AlertEvents(filter eventlog.Filter) ([]eventlog.Event, error) {+ args := m.Called(filter)+ events, _ := args.Get(0).([]eventlog.Event)+ return events, args.Error(1)+}+func (m *MockAlertManager) NotifyExistingAlert(id string) {m.Called(id)}@@ -342,6 +349,65 @@ func TestGetAlertDeliveryDiagnosis(t *testing.T) {assert.Equal(t, expected.TrackingKey, resp.TrackingKey)}+func TestGetAlertEventsReturnsFilteredEvents(t *testing.T) {+ mockMonitor := new(MockAlertMonitor)+ mockManager := new(MockAlertManager)+ mockMonitor.On("GetAlertManager").Return(mockManager)++ expectedFilter := eventlog.Filter{+ AlertID: "a1",+ Types: []string{eventlog.TypeNotificationSuppressed, eventlog.TypeResolved},+ Limit: 10,+ }+ mockManager.On("AlertEvents", expectedFilter).Return([]eventlog.Event{+ {ID: 2, Type: eventlog.TypeNotificationSuppressed, AlertID: "a1", Reason: "flapping"},+ }, nil)++ h := NewAlertHandlers(nil, mockMonitor, nil)++ req := httptest.NewRequest(http.MethodGet,+ "/api/alerts/events?alertIdentifier=a1&type=notification_suppressed,resolved&limit=10", nil)+ w := httptest.NewRecorder()++ h.GetAlertEvents(w, req)++ assert.Equal(t, http.StatusOK, w.Code)+ var resp []eventlog.Event+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ assert.Len(t, resp, 1)+ assert.Equal(t, "flapping", resp[0].Reason)+}++func TestGetAlertEventsWritesEmptyArrayWithoutEventLog(t *testing.T) {+ mockMonitor := new(MockAlertMonitor)+ mockManager := new(MockAlertManager)+ mockMonitor.On("GetAlertManager").Return(mockManager)+ mockManager.On("AlertEvents", eventlog.Filter{}).Return([]eventlog.Event(nil), nil)++ h := NewAlertHandlers(nil, mockMonitor, nil)++ req := httptest.NewRequest(http.MethodGet, "/api/alerts/events", nil)+ w := httptest.NewRecorder()++ h.GetAlertEvents(w, req)++ assert.Equal(t, http.StatusOK, w.Code)+ assert.Equal(t, "[]", strings.TrimSpace(w.Body.String()))+}++func TestGetAlertEventsRejectsBadSince(t *testing.T) {+ h := NewAlertHandlers(nil, new(MockAlertMonitor), nil)++ req := httptest.NewRequest(http.MethodGet, "/api/alerts/events?since=yesterday", nil)+ w := httptest.NewRecorder()++ h.GetAlertEvents(w, req)++ assert.Equal(t, http.StatusBadRequest, w.Code)+}+func TestGetAlertDeliveryDiagnosisWithoutIdentifierReturnsAllActive(t *testing.T) {mockMonitor := new(MockAlertMonitor)mockManager := new(MockAlertManager)diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 357f5304d6..a0fee44d7d 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1758,6 +1758,7 @@ func New(cfg *config.Config) (*Monitor, error) {}m.hydrateRemovedHostAgents(time.Now().UTC())m.alertManager.SetBackupIntentContextResolver(m.resolveBackupIntentContext)+ m.alertManager.EnableEventLog()m.registerBuiltInPollProviders()m.buildInstanceInfoCache(cfg)