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
fix(alerts): harden event history recovery
rcourtman96add5d57a2b
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.jsonindex 9c1c5b8e7d..0f1795d2ec 100644--- a/docs/release-control/v6/internal/status.json+++ b/docs/release-control/v6/internal/status.json@@ -9764,35 +9764,6 @@}]},- {- "id": "alert-engine-suppression-observability",- "summary": "Alert notification suppression decisions (cooldown, quiet hours, flapping, grouping, rate limit, activation state) lacked operator-visible evidence, so held notifications read as breakage and lifecycle regressions (#1682, #1683, #1553, #1693) could ship without an end-to-end contract gate. Phase 0 of docs/ALERT_ENGINE_EVOLUTION.md now supplies the Alerts Overview delivery-diagnosis projection and an additive SQLite event log/API for notification decisions and the safe lifecycle seams. The remaining gap is the deliberately deferred firing event plus convergence of history and delivery projections onto that log before the later reducer phases.",- "owner": "project-owner",- "status": "triaged",- "recorded_at": "2026-08-26",- "lane_ids": [- "L6",- "L13"- ],- "subsystem_ids": [- "alerts",- "notifications"- ],- "proposed_resolution": "lane-expansion",- "coverage_impact": 5,- "evidence": [- {- "repo": "pulse",- "path": "docs/ALERT_ENGINE_EVOLUTION.md",- "kind": "file"- },- {- "repo": "pulse",- "path": "docs/release-control/v6/internal/records/alert-engine-suppression-observability-2026-08-26.md",- "kind": "file"- }- ]- },{"id": "alert-lifecycle-contract-coverage","summary": "Alert transition semantics (hysteresis, sustained-for delays, severity derivation, confirmations) have no deterministic engine-independent contract harness, so transition-core regressions ship undetected (#1682, #1683, #1553, #1693, #1724) and cross-family drift is invisible. Resolution is Phase 1 of docs/ALERT_ENGINE_EVOLUTION.md: a pure characterization reducer (internal/alerts/reducer) plus a parity harness driving reducer and manager through identical sequences; the first metric-family slice already surfaced and fixed a silent stale-resolve defect in checkMetric.",diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex 9921bf47eb..9f3ac9893e 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -995,6 +995,11 @@ that caller value: a request-provided limit is a row-count preference, never amemory-allocation hint. This remains defense in depth even when an authenticatedAPI handler validates the query parameter, because non-HTTP manager callers usethe same store boundary.+Alert-history reconstruction is the explicit exception to a single bounded+query: it walks every matching lifecycle event oldest-first through bounded+keyset pages, releasing the SQLite rows between pages. The public/API query cap+therefore remains intact while a noisy installation with more than 1,000+lifecycle events in the requested window cannot silently lose older history.Lifecycle events now carry a full alert snapshot and`internal/alerts/history_projection.go` can fold those snapshots into onehistory row per occurrence. Existing pre-snapshot SQLite stores upgrade in@@ -1008,14 +1013,21 @@ latest projected snapshot so acknowledgement and current values do not becomestale.`internal/alerts/history_migration.go` imports every legacy JSON entry throughthe event log's synchronous, non-droppable import path before renaming the-fixed history and backup files to their `.imported` backups. The source file's-presence is the idempotent retry marker: an import failure leaves JSON history-authoritative for the next attempt, while a successful import retires further-JSON writes. Clearing history appends a `history_cleared` tombstone rather than-deleting log rows; the projection ignores earlier lifecycle events but overlays-still-active alerts as current state. Unified-incident and system-alert-activation must emit snapshot-bearing fired events so their projected history-does not begin at acknowledgement or resolution.+fixed history and backup files to their `.imported` backups. The primary or+backup source's presence keeps migration active until both leaves retire.+Imported events are retry-idempotent by immutable alert ID, occurrence time,+and snapshot, so a committed SQLite transaction followed by a failed or+partial file rename cannot duplicate history on the next startup. An import+failure leaves JSON history authoritative for the next attempt. An unreadable+or malformed source, or any entry that cannot produce an identified complete+snapshot, blocks both retirement and further JSON writes so startup cannot+silently replace recoverable user history with an empty file. Successful+retirement stops further JSON writes. Clearing history appends a+`history_cleared` tombstone rather than deleting log rows; the projection+ignores earlier lifecycle events but overlays still-active alerts as current+state. Unified-incident and system-alert activation must emit snapshot-bearing+fired events so their projected history does not begin at acknowledgement or+resolution.The same dispatch policy owns firing-notification evidence on active alerts:any alert that passes notification suppression and enters the fired callbackfan-out must carry `LastNotified` before the callback clone is emitted. Resolveddiff --git a/internal/alerts/eventlog/eventlog.go b/internal/alerts/eventlog/eventlog.goindex 9b9155630a..eb3cb3e8e3 100644--- a/internal/alerts/eventlog/eventlog.go+++ b/internal/alerts/eventlog/eventlog.go@@ -328,6 +328,27 @@ func (s *Store) insertBatch(batch []Event) error {return err}defer stmt.Close()+ var importStmt *sql.Stmt+ for _, event := range batch {+ if event.Type != TypeHistoryImported {+ continue+ }+ importStmt, err = tx.Prepare(`+ INSERT INTO alert_events+ (occurred_at, event_type, alert_id, resource_id, resource_name, alert_type, level, reason, message, details, snapshot)+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?+ WHERE NOT EXISTS (+ SELECT 1 FROM alert_events+ WHERE event_type = ? AND alert_id = ? AND occurred_at = ? AND snapshot = ?+ )+ `)+ if err != nil {+ _ = tx.Rollback()+ return err+ }+ defer importStmt.Close()+ break+ }for _, event := range batch {details := ""if len(event.Details) > 0 {@@ -336,8 +357,10 @@ func (s *Store) insertBatch(batch []Event) error {details = string(encoded)}}- if _, err := stmt.Exec(- event.OccurredAt.UTC().Format(time.RFC3339Nano),+ occurredAt := event.OccurredAt.UTC().Format(time.RFC3339Nano)+ snapshot := string(event.Snapshot)+ args := []any{+ occurredAt,event.Type,event.AlertID,event.ResourceID,@@ -347,10 +370,22 @@ func (s *Store) insertBatch(batch []Event) error {event.Reason,event.Message,details,- string(event.Snapshot),- ); err != nil {+ snapshot,+ }+ var insertErr error+ if event.Type == TypeHistoryImported {+ _, insertErr = importStmt.Exec(append(args,+ TypeHistoryImported,+ event.AlertID,+ occurredAt,+ snapshot,+ )...)+ } else {+ _, insertErr = stmt.Exec(args...)+ }+ if insertErr != nil {_ = tx.Rollback()- return err+ return insertErr}}return tx.Commit()@@ -386,6 +421,111 @@ func (s *Store) Query(filter Filter) ([]Event, error) {return nil, nil}+ where, args := eventFilterWhere(filter)++ 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, snapshot 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()++ // Do not use the request-derived limit as an allocation hint. The SQL+ // query is capped above, but keeping the result slice allocation independent+ // of caller input makes that memory-safety boundary explicit and prevents a+ // future query refactor from turning an oversized limit into an eager+ // allocation.+ return scanEventRows(rows, defaultQueryLimit)+}++// WalkOldest visits every matching event oldest first. It uses bounded keyset+// pages so a complete history projection is not truncated by Query's public+// safety cap and does not hold the store's single database connection for the+// full scan. A positive filter Limit caps the total visits; zero walks all+// matching rows.+func (s *Store) WalkOldest(filter Filter, visit func(Event) error) error {+ if s == nil {+ return nil+ }+ if visit == nil {+ return fmt.Errorf("event visitor is required")+ }++ baseWhere, baseArgs := eventFilterWhere(filter)+ visited := 0+ cursorOccurredAt := ""+ var cursorID int64++ for {+ pageLimit := maxQueryLimit+ if filter.Limit > 0 {+ remaining := filter.Limit - visited+ if remaining <= 0 {+ return nil+ }+ if remaining < pageLimit {+ pageLimit = remaining+ }+ }++ where := append([]string(nil), baseWhere...)+ args := append([]any(nil), baseArgs...)+ if cursorOccurredAt != "" {+ where = append(where, "(occurred_at > ? OR (occurred_at = ? AND id > ?))")+ args = append(args, cursorOccurredAt, cursorOccurredAt, cursorID)+ }++ query := "SELECT id, occurred_at, event_type, alert_id, resource_id, resource_name, alert_type, level, reason, message, details, snapshot FROM alert_events"+ if len(where) > 0 {+ query += " WHERE " + strings.Join(where, " AND ")+ }+ query += " ORDER BY occurred_at ASC, id ASC LIMIT ?"+ args = append(args, pageLimit)++ rows, err := s.db.Query(query, args...)+ if err != nil {+ return fmt.Errorf("walk alert event log: %w", err)+ }+ page, scanErr := scanEventRows(rows, pageLimit)+ closeErr := rows.Close()+ if scanErr != nil {+ return scanErr+ }+ if closeErr != nil {+ return fmt.Errorf("close alert event page: %w", closeErr)+ }++ for _, event := range page {+ if err := visit(event); err != nil {+ return err+ }+ visited+++ }+ if len(page) < pageLimit {+ return nil+ }++ last := page[len(page)-1]+ cursorOccurredAt = last.OccurredAt.UTC().Format(time.RFC3339Nano)+ cursorID = last.ID+ }+}++func eventFilterWhere(filter Filter) ([]string, []any) {where := make([]string, 0, 4)args := make([]any, 0, 6)if trimmed := strings.TrimSpace(filter.AlertID); trimmed != "" {@@ -414,34 +554,14 @@ func (s *Store) Query(filter Filter) ([]Event, error) {where = append(where, "occurred_at <= ?")args = append(args, filter.Until.UTC().Format(time.RFC3339Nano))}+ return where, args+}- 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, snapshot 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)+func scanEventRows(rows *sql.Rows, capacity int) ([]Event, error) {+ if capacity < 0 || capacity > maxQueryLimit {+ capacity = maxQueryLimit}- defer rows.Close()-- // Do not use the request-derived limit as an allocation hint. The SQL- // query is capped above, but keeping the result slice allocation independent- // of caller input makes that memory-safety boundary explicit and prevents a- // future query refactor from turning an oversized limit into an eager- // allocation.- events := make([]Event, 0, defaultQueryLimit)+ events := make([]Event, 0, capacity)for rows.Next() {var event Eventvar occurredAt, details, snapshot stringdiff --git a/internal/alerts/eventlog/eventlog_test.go b/internal/alerts/eventlog/eventlog_test.goindex bac63687ee..119e009e27 100644--- a/internal/alerts/eventlog/eventlog_test.go+++ b/internal/alerts/eventlog/eventlog_test.go@@ -1,6 +1,8 @@package eventlogimport (+ "encoding/json"+ "fmt""math""testing""time"@@ -114,6 +116,75 @@ func TestQueryOversizedLimitDoesNotControlAllocation(t *testing.T) {}}+func TestWalkOldestTraversesBeyondQueryLimitInBoundedPages(t *testing.T) {+ store := newTestStore(t)+ base := time.Now().Add(-time.Hour).UTC()+ batch := make([]Event, 0, maxQueryLimit+205)+ for i := 0; i < maxQueryLimit+205; i++ {+ batch = append(batch, Event{+ // Keep every row on the same timestamp to prove the ID tie-breaker+ // crosses a page boundary without skipping or repeating rows.+ OccurredAt: base,+ Type: TypeResolved,+ AlertID: fmt.Sprintf("walk-%04d", i),+ })+ }+ if err := store.ImportEvents(batch); err != nil {+ t.Fatalf("import walk fixtures: %v", err)+ }++ visited := make([]string, 0, len(batch))+ if err := store.WalkOldest(Filter{Types: []string{TypeResolved}}, func(event Event) error {+ visited = append(visited, event.AlertID)+ return nil+ }); err != nil {+ t.Fatalf("walk: %v", err)+ }+ if len(visited) != len(batch) {+ t.Fatalf("visited %d events, want %d", len(visited), len(batch))+ }+ if visited[0] != "walk-0000" || visited[len(visited)-1] != "walk-1204" {+ t.Fatalf("walk order = %q ... %q, want oldest through newest", visited[0], visited[len(visited)-1])+ }+}++func TestImportEventsDeduplicatesLegacyHistoryRetriesOnly(t *testing.T) {+ store := newTestStore(t)+ occurred := time.Now().UTC()+ legacy := Event{+ OccurredAt: occurred,+ Type: TypeHistoryImported,+ AlertID: "legacy-alert",+ Snapshot: json.RawMessage(`{"id":"legacy-alert","startTime":"2026-08-27T08:00:00Z"}`),+ }+ if err := store.ImportEvents([]Event{legacy}); err != nil {+ t.Fatalf("first import: %v", err)+ }+ if err := store.ImportEvents([]Event{legacy}); err != nil {+ t.Fatalf("retry import: %v", err)+ }++ imported, err := store.Query(Filter{Types: []string{TypeHistoryImported}, Limit: 10})+ if err != nil {+ t.Fatalf("query imported events: %v", err)+ }+ if len(imported) != 1 {+ t.Fatalf("legacy import retry produced %d events, want 1", len(imported))+ }++ clear := Event{OccurredAt: occurred, Type: TypeHistoryCleared, AlertID: "history"}+ if err := store.ImportEvents([]Event{clear, clear}); err != nil {+ t.Fatalf("import ordinary events: %v", err)+ }+ cleared, err := store.Query(Filter{Types: []string{TypeHistoryCleared}, Limit: 10})+ if err != nil {+ t.Fatalf("query clear events: %v", err)+ }+ if len(cleared) != 2 {+ t.Fatalf("ordinary synchronous imports were deduplicated: got %d, want 2", len(cleared))+ }+}+func TestNilStoreIsSafe(t *testing.T) {var store *Storestore.Append(Event{Type: TypeResolved, AlertID: "a1"})diff --git a/internal/alerts/history.go b/internal/alerts/history.goindex 9c5c6b268c..120a24e2ec 100644--- a/internal/alerts/history.go+++ b/internal/alerts/history.go@@ -60,6 +60,10 @@ type HistoryManager struct {// storageRetired marks the JSON files migrated into the event log:// in-memory history continues, disk writes stop.storageRetired bool+ // storageLoadErr keeps an unreadable or malformed legacy source from being+ // overwritten or retired as an empty history before an operator can recover+ // it. It is immutable after construction.+ storageLoadErr error}func historyIdentityKey(alert *Alert) string {@@ -115,8 +119,9 @@ func NewHistoryManager(dataDir string) *HistoryManager {}// Load existing history- if err := hm.loadHistory(); err != nil {- log.Error().Err(err).Msg("failed to load alert history")+ hm.storageLoadErr = hm.loadHistory()+ if hm.storageLoadErr != nil {+ log.Error().Err(hm.storageLoadErr).Msg("failed to load alert history")}// Start periodic save routine@@ -274,15 +279,29 @@ func (hm *HistoryManager) RetireStorage() error {return nil}-// StorageFileExists reports whether the JSON history file is still present —-// the self-describing marker that the legacy history has not been migrated-// into the event log yet.+// StorageFileExists reports whether either JSON history source is still+// present. The backup can be the only surviving retry source after an+// interrupted save or partial retirement, so it must keep migration active+// until both fixed legacy leaves have retired.func (hm *HistoryManager) StorageFileExists() bool {- if hm.historyFile == "" {- return false+ for _, path := range []string{hm.historyFile, hm.backupFile} {+ if path == "" {+ continue+ }+ if _, err := os.Stat(path); err == nil {+ return true+ }+ }+ return false+}++// StorageLoadError reports why a present legacy source could not be loaded.+// Migration and periodic persistence must leave that source untouched.+func (hm *HistoryManager) StorageLoadError() error {+ if hm == nil {+ return nil}- _, err := os.Stat(hm.historyFile)- return err == nil+ return hm.storageLoadErr}// UpdateAlertLastSeen updates the LastSeen timestamp on the most recent@@ -466,28 +485,32 @@ func (hm *HistoryManager) GetAllHistory(limit int) []Alert {// loadHistory loads history from diskfunc (hm *HistoryManager) loadHistory() error {// Try loading from main file first- data, err := readLimitedRegularFile(hm.historyFile, maxAlertHistoryFileSizeBytes)- if err != nil {- if !os.IsNotExist(err) {- log.Warn().Err(err).Str("file", hm.historyFile).Msg("Failed to read history file")+ data, mainErr := readLimitedRegularFile(hm.historyFile, maxAlertHistoryFileSizeBytes)+ if mainErr != nil {+ if !os.IsNotExist(mainErr) {+ log.Warn().Err(mainErr).Str("file", hm.historyFile).Msg("Failed to read history file")}// Try backup file- data, err = readLimitedRegularFile(hm.backupFile, maxAlertHistoryFileSizeBytes)- if err != nil {- if os.IsNotExist(err) {- // Both files don't exist - this is normal on first startup+ var backupErr error+ data, backupErr = readLimitedRegularFile(hm.backupFile, maxAlertHistoryFileSizeBytes)+ if backupErr != nil {+ if os.IsNotExist(backupErr) && os.IsNotExist(mainErr) {+ // Both files don't exist - this is normal on first startup.log.Debug().Msg("No alert history files found, starting fresh")return nil}- if os.IsPermission(err) {+ if os.IsPermission(backupErr) {log.Warn().- Err(err).+ Err(backupErr).Str("file", hm.backupFile).Msg("Permission denied reading backup history file - check file ownership")- return nil}- return fmt.Errorf("failed to read history backup file %q: %w", hm.backupFile, err)+ if !os.IsNotExist(mainErr) {+ return fmt.Errorf("failed to read history file %q (%v); failed to read history backup file %q: %w",+ hm.historyFile, mainErr, hm.backupFile, backupErr)+ }+ return fmt.Errorf("failed to read history backup file %q: %w", hm.backupFile, backupErr)}log.Info().Msg("loaded alert history from backup file")}@@ -519,6 +542,9 @@ func (hm *HistoryManager) saveHistoryWithRetry(maxRetries int) error {if retired {return nil}+ if hm.storageLoadErr != nil {+ return fmt.Errorf("alert history storage remains read-only after load failure: %w", hm.storageLoadErr)+ }if maxRetries < 1 {maxRetries = 1}diff --git a/internal/alerts/history_lifecycle_test.go b/internal/alerts/history_lifecycle_test.goindex 2303a0d80c..e5d0fdf8a7 100644--- a/internal/alerts/history_lifecycle_test.go+++ b/internal/alerts/history_lifecycle_test.go@@ -25,6 +25,24 @@ func TestLoadHistory_BackupReadErrorReturnsError(t *testing.T) {}}+func TestLoadHistory_MainReadErrorWithoutBackupReturnsError(t *testing.T) {+ hm := newTestHistoryManager(t)++ // A present but unreadable primary is not equivalent to a clean first run+ // merely because no backup exists.+ if err := os.Mkdir(hm.historyFile, 0755); err != nil {+ t.Fatalf("failed to create primary directory: %v", err)+ }++ err := hm.loadHistory()+ if err == nil {+ t.Fatal("loadHistory should fail when the primary cannot be read and no backup exists")+ }+ if !strings.Contains(err.Error(), "failed to read history file") {+ t.Fatalf("unexpected error: %v", err)+ }+}+func TestClearAllHistory_ReturnsJoinedErrorsWhenFilesAreDirectories(t *testing.T) {hm := newTestHistoryManager(t)hm.history = []HistoryEntry{diff --git a/internal/alerts/history_migration.go b/internal/alerts/history_migration.goindex 3bbebd6904..e2c713b7ba 100644--- a/internal/alerts/history_migration.go+++ b/internal/alerts/history_migration.go@@ -2,10 +2,11 @@ package alerts// One-time migration of the legacy JSON alert history into the event log// (docs/ALERT_ENGINE_EVOLUTION.md — the log becomes the sole history-// authority). The JSON file's continued presence is the migration marker:-// import runs when the file exists, and a successful import renames it to-// *.imported, so the migration is idempotent and the original data survives-// as a backup.+// authority). Either JSON leaf's continued presence is the migration marker:+// import runs while the primary or backup exists, and successful retirement+// renames them to *.imported. The event-log import itself is idempotent, so a+// database commit followed by a rename failure can retry without duplicating+// user history.import ("encoding/json"@@ -17,7 +18,9 @@ import (// importLegacyHistoryIntoEventLog migrates the loaded JSON history entries// into the event log as history_imported events and retires the JSON files.// A failed import leaves the files in place so the next startup retries;-// history reads fall back to the in-memory entries either way.+// history reads fall back to the in-memory entries either way. A retirement+// failure also retries safely because history_imported events are inserted by+// immutable event identity.func (m *Manager) importLegacyHistoryIntoEventLog(store *eventlog.Store) {if m == nil || store == nil || m.historyManager == nil {return@@ -25,6 +28,11 @@ func (m *Manager) importLegacyHistoryIntoEventLog(store *eventlog.Store) {if !m.historyManager.StorageFileExists() {return}+ if err := m.historyManager.StorageLoadError(); err != nil {+ log.Error().Err(err).+ Msg("legacy alert history import deferred; source could not be loaded and remains untouched")+ return+ }entries := m.historyManager.SnapshotEntries()events := make([]eventlog.Event, 0, len(entries))@@ -32,11 +40,15 @@ func (m *Manager) importLegacyHistoryIntoEventLog(store *eventlog.Store) {entry := &entries[i]exported := cloneAlertForOutput(&entry.Alert)if exported == nil || exported.ID == "" {- continue+ log.Error().Int("entry", i).+ Msg("legacy alert history import deferred; entry has no alert identity")+ return}snapshot, err := json.Marshal(exported)if err != nil {- continue+ log.Error().Err(err).Int("entry", i).+ Msg("legacy alert history import deferred; entry snapshot could not be encoded")+ return}occurredAt := entry.Timestampif entry.Alert.LastSeen.After(occurredAt) {diff --git a/internal/alerts/history_migration_test.go b/internal/alerts/history_migration_test.goindex ea7c39fae5..67d1e36733 100644--- a/internal/alerts/history_migration_test.go+++ b/internal/alerts/history_migration_test.go@@ -2,11 +2,13 @@ package alerts// The one-time legacy-history migration: JSON entries become// history_imported events, the files retire to *.imported, and the-// projection serves the imported entries. The file's presence is the-// marker, so a second startup imports nothing.+// projection serves the imported entries. Either legacy file is a retry+// marker, and retry after a retirement failure must not duplicate events.import (+ "encoding/json""os"+ "path/filepath""testing""time"@@ -80,6 +82,210 @@ func TestLegacyHistoryImportRetiresJSONAndServesEntries(t *testing.T) {}}+func TestLegacyHistoryImportRetryAfterRetirementFailureIsIdempotent(t *testing.T) {+ dataDir := t.TempDir()+ m := NewManagerWithDataDir(dataDir)+ t.Cleanup(m.Stop)+ past := time.Now().Add(-time.Hour)+ m.historyManager.AddAlert(Alert{+ ID: "legacy-retry::metric-threshold:cpu",+ Type: "cpu",+ Level: AlertLevelWarning,+ ResourceID: "legacy-retry",+ ResourceName: "Legacy Retry VM",+ StartTime: past,+ LastSeen: past.Add(10 * time.Minute),+ })+ if err := m.historyManager.saveHistory(); err != nil {+ t.Fatalf("persist legacy history: %v", err)+ }++ // A directory at the retirement destination forces the post-import rename+ // to fail after the database transaction has committed.+ retirementBlocker := m.historyManager.historyFile + ".imported"+ if err := os.Mkdir(retirementBlocker, 0o700); err != nil {+ t.Fatalf("create retirement blocker: %v", err)+ }++ store, err := eventlog.Open(m.alertsDir)+ if err != nil {+ t.Fatal(err)+ }+ m.SetEventLog(store)++ m.importLegacyHistoryIntoEventLog(store)+ if !m.historyManager.StorageFileExists() {+ t.Fatal("legacy source disappeared despite retirement failure")+ }+ if got := importedHistoryEventCount(t, store); got != 1 {+ t.Fatalf("first import wrote %d events, want 1", got)+ }+ m.SetEventLog(nil)+ m.Stop()++ if err := os.Remove(retirementBlocker); err != nil {+ t.Fatalf("remove retirement blocker: %v", err)+ }++ restarted := NewManagerWithDataDir(dataDir)+ t.Cleanup(restarted.Stop)+ reopenedStore, err := eventlog.Open(restarted.alertsDir)+ if err != nil {+ t.Fatal(err)+ }+ restarted.SetEventLog(reopenedStore)+ restarted.importLegacyHistoryIntoEventLog(reopenedStore)+ if restarted.historyManager.StorageFileExists() {+ t.Fatal("legacy source still present after successful retry")+ }+ if got := importedHistoryEventCount(t, reopenedStore); got != 1 {+ t.Fatalf("retirement retry duplicated import events: got %d, want 1", got)+ }+}++func TestLegacyHistoryImportUsesBackupAsRetryMarker(t *testing.T) {+ m := newTestManager(t)+ past := time.Now().Add(-time.Hour)+ m.historyManager.AddAlert(Alert{+ ID: "legacy-backup::metric-threshold:memory",+ Type: "memory",+ Level: AlertLevelWarning,+ ResourceID: "legacy-backup",+ ResourceName: "Legacy Backup VM",+ StartTime: past,+ LastSeen: past.Add(5 * time.Minute),+ })+ if err := m.historyManager.saveHistory(); err != nil {+ t.Fatalf("persist legacy history: %v", err)+ }+ data, err := os.ReadFile(m.historyManager.historyFile)+ if err != nil {+ t.Fatalf("read legacy history: %v", err)+ }+ if err := os.WriteFile(m.historyManager.backupFile, data, 0o600); err != nil {+ t.Fatalf("seed legacy backup: %v", err)+ }+ if err := os.Rename(m.historyManager.historyFile, m.historyManager.historyFile+".imported"); err != nil {+ t.Fatalf("simulate retired primary: %v", err)+ }+ if !m.historyManager.StorageFileExists() {+ t.Fatal("backup-only legacy source was not recognized")+ }++ store, err := eventlog.OpenInMemory()+ if err != nil {+ t.Fatal(err)+ }+ m.SetEventLog(store)+ t.Cleanup(func() { m.SetEventLog(nil) })+ m.importLegacyHistoryIntoEventLog(store)++ if m.historyManager.StorageFileExists() {+ t.Fatal("backup-only legacy source still present after import")+ }+ if _, err := os.Stat(m.historyManager.backupFile + ".imported"); err != nil {+ t.Fatalf("retired backup missing: %v", err)+ }+ if got := importedHistoryEventCount(t, store); got != 1 {+ t.Fatalf("backup-only import wrote %d events, want 1", got)+ }+}++func TestLegacyHistoryImportKeepsMalformedSourceUntouched(t *testing.T) {+ dataDir := t.TempDir()+ alertsDir := filepath.Join(dataDir, "alerts")+ if err := os.MkdirAll(alertsDir, 0o700); err != nil {+ t.Fatalf("create alerts dir: %v", err)+ }+ historyFile := filepath.Join(alertsDir, HistoryFileName)+ malformed := []byte(`{"alert":`)+ if err := os.WriteFile(historyFile, malformed, 0o600); err != nil {+ t.Fatalf("seed malformed history: %v", err)+ }++ m := NewManagerWithDataDir(dataDir)+ t.Cleanup(m.Stop)+ if m.historyManager.StorageLoadError() == nil {+ t.Fatal("malformed legacy source did not retain its load error")+ }+ store, err := eventlog.OpenInMemory()+ if err != nil {+ t.Fatal(err)+ }+ m.SetEventLog(store)+ m.importLegacyHistoryIntoEventLog(store)++ if !m.historyManager.StorageFileExists() {+ t.Fatal("malformed legacy source was retired")+ }+ if got := importedHistoryEventCount(t, store); got != 0 {+ t.Fatalf("malformed legacy source imported %d events, want 0", got)+ }+ if err := m.historyManager.saveHistory(); err == nil {+ t.Fatal("periodic persistence could overwrite a malformed legacy source")+ }+ got, err := os.ReadFile(historyFile)+ if err != nil {+ t.Fatalf("read preserved malformed history: %v", err)+ }+ if string(got) != string(malformed) {+ t.Fatalf("malformed legacy source changed: got %q want %q", got, malformed)+ }+}++func TestLegacyHistoryImportKeepsUnidentifiableEntry(t *testing.T) {+ dataDir := t.TempDir()+ alertsDir := filepath.Join(dataDir, "alerts")+ if err := os.MkdirAll(alertsDir, 0o700); err != nil {+ t.Fatalf("create alerts dir: %v", err)+ }+ historyFile := filepath.Join(alertsDir, HistoryFileName)+ payload, err := json.Marshal([]HistoryEntry{{+ Alert: Alert{+ Type: "cpu",+ ResourceID: "missing-id",+ ResourceName: "Missing ID VM",+ StartTime: time.Now().Add(-time.Hour),+ LastSeen: time.Now(),+ },+ Timestamp: time.Now(),+ }})+ if err != nil {+ t.Fatalf("encode legacy history: %v", err)+ }+ if err := os.WriteFile(historyFile, payload, 0o600); err != nil {+ t.Fatalf("seed legacy history: %v", err)+ }++ m := NewManagerWithDataDir(dataDir)+ t.Cleanup(m.Stop)+ store, err := eventlog.OpenInMemory()+ if err != nil {+ t.Fatal(err)+ }+ m.SetEventLog(store)+ m.importLegacyHistoryIntoEventLog(store)++ if !m.historyManager.StorageFileExists() {+ t.Fatal("unidentifiable legacy entry was retired")+ }+ if got := importedHistoryEventCount(t, store); got != 0 {+ t.Fatalf("unidentifiable legacy entry imported %d events, want 0", got)+ }+}++func importedHistoryEventCount(t *testing.T, store *eventlog.Store) int {+ t.Helper()+ events, err := store.Query(eventlog.Filter{+ Types: []string{eventlog.TypeHistoryImported},+ Limit: 1000,+ })+ if err != nil {+ t.Fatalf("query imported history: %v", err)+ }+ return len(events)+}+func TestClearAlertHistoryTombstonesTheProjection(t *testing.T) {m := newHistoryParityManager(t)cfg := m.GetConfig()diff --git a/internal/alerts/history_projection.go b/internal/alerts/history_projection.goindex 10f8582074..1e93f15e7e 100644--- a/internal/alerts/history_projection.go+++ b/internal/alerts/history_projection.go@@ -38,7 +38,14 @@ func (m *Manager) AlertHistoryFromEvents(since time.Time, limit int) ([]Alert, breturn nil, false}store.Flush()- events, err := store.Query(eventlog.Filter{++ // Fold oldest to newest through the store's bounded-page walker. The+ // ordinary Query API intentionally caps responses at 1,000 rows, which is+ // appropriate for callers but not for reconstructing a complete history+ // window on a noisy installation.+ occurrences := make(map[string]*historyOccurrence)+ order := make([]string, 0)+ err := store.WalkOldest(eventlog.Filter{Types: []string{eventlog.TypeFired,eventlog.TypeRefired,@@ -50,31 +57,20 @@ func (m *Manager) AlertHistoryFromEvents(since time.Time, limit int) ([]Alert, beventlog.TypeHistoryCleared,},Since: since,- Limit: 1000,- })- if err != nil {- return nil, false- }-- // Query returns newest first; fold oldest first so later events- // supersede earlier snapshots of the same occurrence.- occurrences := make(map[string]*historyOccurrence)- order := make([]string, 0, len(events))- for i := len(events) - 1; i >= 0; i-- {- event := events[i]+ }, func(event eventlog.Event) error {if event.Type == eventlog.TypeHistoryCleared {// The user cleared history: everything before the tombstone// leaves the projection. The log itself stays append-only.occurrences = make(map[string]*historyOccurrence)order = order[:0]- continue+ return nil}if len(event.Snapshot) == 0 {- continue+ return nil}var snapshot Alertif err := json.Unmarshal(event.Snapshot, &snapshot); err != nil {- continue+ return nil}key := historyOccurrenceKey(event.AlertID, &snapshot)occ, exists := occurrences[key]@@ -97,6 +93,10 @@ func (m *Manager) AlertHistoryFromEvents(since time.Time, limit int) ([]Alert, b} else {occ.resolved = false}+ return nil+ })+ if err != nil {+ return nil, false}// Overlay the live active alerts: an occurrence still firing shows itsdiff --git a/internal/alerts/history_projection_parity_test.go b/internal/alerts/history_projection_parity_test.goindex a52473c9e9..ac683c310e 100644--- a/internal/alerts/history_projection_parity_test.go+++ b/internal/alerts/history_projection_parity_test.go@@ -8,6 +8,8 @@ package alerts// a history-manager defect, which is then fixed first.import (+ "encoding/json"+ "fmt""testing""time"@@ -149,3 +151,62 @@ func TestHistoryProjectionParitySecondOccurrence(t *testing.T) {contractRaiseGuestCPUAlert(t, m, "hp-vm-7", 97)assertHistoryParity(t, m)}++func TestHistoryProjectionWalksEveryLifecycleEventBeyondQueryCap(t *testing.T) {+ m := newTestManager(t)+ store, err := eventlog.OpenInMemory()+ if err != nil {+ t.Fatalf("open in-memory event log: %v", err)+ }+ m.SetEventLog(store)+ t.Cleanup(func() { m.SetEventLog(nil) })++ const occurrenceCount = 1205+ base := time.Now().Add(-occurrenceCount * time.Second).UTC()+ events := make([]eventlog.Event, 0, occurrenceCount)+ for i := 0; i < occurrenceCount; i++ {+ occurredAt := base.Add(time.Duration(i) * time.Second)+ id := fmt.Sprintf("history-cap-%04d", i)+ snapshot, marshalErr := json.Marshal(Alert{+ ID: id,+ Type: "cpu",+ Level: AlertLevelWarning,+ ResourceID: id,+ ResourceName: id,+ StartTime: occurredAt,+ LastSeen: occurredAt,+ })+ if marshalErr != nil {+ t.Fatalf("marshal fixture %d: %v", i, marshalErr)+ }+ events = append(events, eventlog.Event{+ OccurredAt: occurredAt,+ Type: eventlog.TypeHistoryImported,+ AlertID: id,+ Snapshot: snapshot,+ })+ }+ if err := store.ImportEvents(events); err != nil {+ t.Fatalf("import history fixtures: %v", err)+ }++ projected, ok := m.AlertHistoryFromEvents(time.Time{}, 0)+ if !ok {+ t.Fatal("projection unavailable")+ }+ if len(projected) != occurrenceCount {+ t.Fatalf("projection returned %d occurrences, want %d", len(projected), occurrenceCount)+ }+ if projected[0].ID != "history-cap-1204" || projected[len(projected)-1].ID != "history-cap-0000" {+ t.Fatalf("projection order = %q ... %q, want newest through oldest",+ projected[0].ID, projected[len(projected)-1].ID)+ }++ limited, ok := m.AlertHistoryFromEvents(time.Time{}, 25)+ if !ok || len(limited) != 25 {+ t.Fatalf("limited projection = %d entries, ok=%v; want 25, true", len(limited), ok)+ }+ if limited[0].ID != "history-cap-1204" || limited[24].ID != "history-cap-1180" {+ t.Fatalf("limited projection order = %q ... %q", limited[0].ID, limited[24].ID)+ }+}diff --git a/internal/alerts/history_test.go b/internal/alerts/history_test.goindex aa6ab2beaa..37c066d232 100644--- a/internal/alerts/history_test.go+++ b/internal/alerts/history_test.go@@ -1014,10 +1014,11 @@ func TestLoadHistory_PermissionError(t *testing.T) {}defer func() { _ = os.Chmod(hm.backupFile, 0644) }()- // loadHistory should return nil (continue without history) for permission errors on backup+ // An unreadable backup is still user data. Loading must fail closed so+ // startup cannot overwrite or retire it as an empty history.err := hm.loadHistory()- if err != nil {- t.Errorf("loadHistory should not return error for permission issues on backup file, got: %v", err)+ if err == nil {+ t.Fatal("loadHistory should return an error for an unreadable backup")}}