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.

Release removed alert-history row storage after compaction

pulse-triage[bot]a15529711bbe
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index def6dc41b6..e8d8b53c07 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -15,6 +15,23 @@
## Purpose
+### Legacy alert-history compaction releases removed-row storage
+
+Expiry, duplicate-occurrence compaction and ID removal allocate backing storage
+for the surviving history rows, not the original loaded row count. Unchanged
+expiry and removal passes keep the current array. This reduces avoidable runtime
+retention after loading a mostly-expired or noisy history without changing the
+30-day cutoff, five-minute duplicate chain, earliest occurrence/latest observation,
+identity, ordering, evidence or empty-array shape.
+
+`history_retention_storage_test.go` verifies exact survivor capacity, recurrence
+and neighbour separation, detached migration snapshots, subsequent appends and
+concurrent reads/writes. Connected primary, backup and retired-JSON loads compact
+without rewriting the recovery files or changing their retirement state. JSON
+recovery and event-log authority remain unchanged. Array-capacity evidence is not
+whole-process RSS or attribution of a reported installation's memory growth.
+
+
### Webhook list changes share the editor's acknowledged writer
Enable/Disable, deletion, bulk changes and form saves cannot overlap in one
diff --git a/internal/alerts/history.go b/internal/alerts/history.go
index efefa385cb..10694ccfe2 100644
--- a/internal/alerts/history.go
+++ b/internal/alerts/history.go
@@ -795,24 +795,31 @@ func (hm *HistoryManager) cleanOldEntries() {
defer hm.mu.Unlock()
cutoff := time.Now().AddDate(0, 0, -MaxHistoryDays)
- newHistory := make([]HistoryEntry, 0, len(hm.history))
-
removed := 0
for _, entry := range hm.history {
- if entry.Timestamp.After(cutoff) {
- newHistory = append(newHistory, entry)
- } else {
+ if !entry.Timestamp.After(cutoff) {
removed++
}
}
+ if removed == 0 {
+ return
+ }
- if removed > 0 {
- hm.history = newHistory
- log.Info().
- Int("removed", removed).
- Int("remaining", len(newHistory)).
- Msg("cleaned old alert history entries")
+ // Allocate for survivors, not the loaded file's original row count. A
+ // mostly-expired history otherwise keeps its old-sized Alert array after
+ // startup cleanup, even though no expired rows remain visible.
+ newHistory := make([]HistoryEntry, 0, len(hm.history)-removed)
+ for _, entry := range hm.history {
+ if entry.Timestamp.After(cutoff) {
+ newHistory = append(newHistory, entry)
+ }
}
+
+ hm.history = newHistory
+ log.Info().
+ Int("removed", removed).
+ Int("remaining", len(newHistory)).
+ Msg("cleaned old alert history entries")
}
// historyDedupWindow is the maximum gap between consecutive same-alert entries
@@ -832,10 +839,25 @@ func (hm *HistoryManager) deduplicateHistory() {
return
}
- deduped := make([]HistoryEntry, 0, len(hm.history))
- lastIdxByKey := make(map[string]int)
lastTimeByKey := make(map[string]time.Time)
removed := 0
+ for _, entry := range hm.history {
+ key := historyIdentityKey(&entry.Alert)
+ if lastTime, ok := lastTimeByKey[key]; ok && entry.Timestamp.Sub(lastTime) <= historyDedupWindow {
+ removed++
+ }
+ lastTimeByKey[key] = entry.Timestamp
+ }
+ if removed == 0 {
+ return
+ }
+
+ // Count first so the new backing array holds only surviving occurrences.
+ // Clipping a preallocated slice's capacity would keep its original array;
+ // copying twice would instead add another full array on sparse reductions.
+ deduped := make([]HistoryEntry, 0, len(hm.history)-removed)
+ lastIdxByKey := make(map[string]int)
+ clear(lastTimeByKey)
for _, entry := range hm.history {
key := historyIdentityKey(&entry.Alert)
@@ -845,7 +867,6 @@ func (hm *HistoryManager) deduplicateHistory() {
idx := lastIdxByKey[key]
deduped[idx].Alert = mergeHistoryAlertSnapshots(deduped[idx].Alert, entry.Alert)
lastTimeByKey[key] = entry.Timestamp
- removed++
continue
}
}
@@ -855,13 +876,11 @@ func (hm *HistoryManager) deduplicateHistory() {
lastTimeByKey[key] = entry.Timestamp
}
- if removed > 0 {
- hm.history = deduped
- log.Info().
- Int("removed", removed).
- Int("remaining", len(deduped)).
- Msg("deduplicated alert history entries")
- }
+ hm.history = deduped
+ log.Info().
+ Int("removed", removed).
+ Int("remaining", len(deduped)).
+ Msg("deduplicated alert history entries")
}
// RemoveAlert removes a specific alert from history by ID
@@ -869,21 +888,25 @@ func (hm *HistoryManager) RemoveAlert(alertID string) {
hm.mu.Lock()
defer hm.mu.Unlock()
- newHistory := make([]HistoryEntry, 0, len(hm.history))
- removed := false
+ removed := 0
+ for _, entry := range hm.history {
+ if entry.Alert.ID == alertID {
+ removed++
+ }
+ }
+ if removed == 0 {
+ return
+ }
+ newHistory := make([]HistoryEntry, 0, len(hm.history)-removed)
for _, entry := range hm.history {
if entry.Alert.ID != alertID {
newHistory = append(newHistory, entry)
- } else {
- removed = true
}
}
- if removed {
- hm.history = newHistory
- log.Debug().Str("alertID", alertID).Msg("removed alert from history")
- }
+ hm.history = newHistory
+ log.Debug().Str("alertID", alertID).Msg("removed alert from history")
}
// ClearAllHistory clears all alert history
diff --git a/internal/alerts/history_retention_storage_test.go b/internal/alerts/history_retention_storage_test.go
new file mode 100644
index 0000000000..affada4416
--- /dev/null
+++ b/internal/alerts/history_retention_storage_test.go
@@ -0,0 +1,204 @@
+package alerts
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os"
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+ "unsafe"
+)
+
+func retainedHistoryEntry(id string, at time.Time) HistoryEntry {
+ return HistoryEntry{
+ Alert: Alert{
+ ID: id, CanonicalState: id, Type: "cpu", ResourceID: "guest-1",
+ Level: AlertLevelWarning, StartTime: at, LastSeen: at,
+ Metadata: map[string]interface{}{"sample": "unchanged"},
+ },
+ Timestamp: at,
+ }
+}
+
+func TestHistoryCleanupReleasesRemovedRowStorage(t *testing.T) {
+ for _, survivors := range []int{0, 3} {
+ t.Run(fmt.Sprint(survivors), func(t *testing.T) {
+ hm := newTestHistoryManager(t)
+ now := time.Now()
+ const rows = 8192
+ hm.history = make([]HistoryEntry, rows)
+ for i := range hm.history {
+ hm.history[i] = retainedHistoryEntry(fmt.Sprint(i), now.AddDate(0, 0, -31))
+ }
+ var want []HistoryEntry
+ // Survivors are interleaved with expired rows, not a sorted tail.
+ for i := 0; i < survivors; i++ {
+ entry := retainedHistoryEntry(fmt.Sprintf("live-%d", i), now.Add(-time.Duration(i+1)*time.Hour))
+ hm.history[i*100] = entry
+ want = append(want, entry)
+ }
+ hm.cleanOldEntries()
+ if len(hm.history) != survivors || cap(hm.history) != survivors {
+ t.Fatalf("retained rows/storage = %d/%d, want %d/%d", len(hm.history), cap(hm.history), survivors, survivors)
+ }
+ if hm.history == nil {
+ t.Fatal("empty history must retain its non-nil slice shape")
+ }
+ if survivors > 0 && !reflect.DeepEqual(hm.history, want) {
+ t.Fatal("cleanup changed survivor order, timestamps or alert evidence")
+ }
+ t.Logf("row_bytes=%d original_backing_bytes=%d retained_backing_bytes=%d", unsafe.Sizeof(HistoryEntry{}), rows*unsafe.Sizeof(HistoryEntry{}), cap(hm.history)*int(unsafe.Sizeof(HistoryEntry{})))
+ hm.AddAlert(Alert{ID: "after-cleanup", Type: "cpu"})
+ if len(hm.GetAllHistory(0)) != survivors+1 {
+ t.Fatal("history could not accept a new occurrence after cleanup")
+ }
+ })
+ }
+}
+
+func TestHistoryDedupReleasesRemovedRowStorage(t *testing.T) {
+ hm := newTestHistoryManager(t)
+ base := time.Now().Add(-time.Hour)
+ const rows = 8192
+ for i := 0; i < rows; i++ {
+ hm.history = append(hm.history, retainedHistoryEntry("one-chain", base.Add(time.Duration(i)*time.Millisecond)))
+ }
+ lastSeen := hm.history[rows-1].Alert.LastSeen
+ separate := retainedHistoryEntry("one-chain", lastSeen.Add(historyDedupWindow+time.Second))
+ neighbour := retainedHistoryEntry("other-identity", base)
+ hm.history = append(hm.history, separate, neighbour)
+ hm.deduplicateHistory()
+ if len(hm.history) != 3 || cap(hm.history) != 3 {
+ t.Fatalf("retained rows/storage = %d/%d, want 3/3", len(hm.history), cap(hm.history))
+ }
+ if !hm.history[0].Timestamp.Equal(base) || !hm.history[0].Alert.StartTime.Equal(base) || !hm.history[0].Alert.LastSeen.Equal(lastSeen) {
+ t.Fatal("dedup changed earliest occurrence or latest observation")
+ }
+ if !reflect.DeepEqual(hm.history[1], separate) || !reflect.DeepEqual(hm.history[2], neighbour) {
+ t.Fatal("dedup merged a separate recurrence or another identity")
+ }
+ // The migration snapshot still owns its nested evidence independently.
+ snapshot := hm.SnapshotEntries()
+ snapshot[0].Alert.Metadata["sample"] = "caller-change"
+ if hm.history[0].Alert.Metadata["sample"] != "unchanged" {
+ t.Fatal("migration snapshot aliases retained evidence")
+ }
+}
+
+func TestHistoryRemovalReleasesRemovedRowStorage(t *testing.T) {
+ for _, survivors := range []int{0, 2} {
+ t.Run(fmt.Sprint(survivors), func(t *testing.T) {
+ hm := newTestHistoryManager(t)
+ now := time.Now()
+ hm.history = make([]HistoryEntry, 8192)
+ for i := range hm.history {
+ hm.history[i] = retainedHistoryEntry("remove", now)
+ }
+ want := make([]HistoryEntry, survivors)
+ for i := range want {
+ want[i] = retainedHistoryEntry(fmt.Sprintf("keep-%d", i), now.Add(-time.Duration(i)*time.Minute))
+ hm.history[i*100] = want[i]
+ }
+ hm.RemoveAlert("remove")
+ if cap(hm.history) != survivors || !reflect.DeepEqual(hm.history, want) {
+ t.Fatalf("removal retained %d rows with capacity %d, want %d unchanged survivors", len(hm.history), cap(hm.history), survivors)
+ }
+ })
+ }
+}
+
+func TestHistoryCompactionNoOpKeepsStorage(t *testing.T) {
+ hm := newTestHistoryManager(t)
+ hm.history = []HistoryEntry{retainedHistoryEntry("current", time.Now())}
+ before := &hm.history[0]
+ hm.cleanOldEntries()
+ hm.RemoveAlert("absent")
+ hm.deduplicateHistory()
+ if &hm.history[0] != before {
+ t.Fatal("unchanged cleanup replaced the current array")
+ }
+}
+
+func TestHistoryLoadCompactsRecoverySourcesWithoutWriting(t *testing.T) {
+ for _, leaf := range []string{"primary", "backup", "retired"} {
+ t.Run(leaf, func(t *testing.T) {
+ hm := newTestHistoryManager(t)
+ path := hm.historyFile
+ if leaf == "backup" {
+ path = hm.backupFile
+ } else if leaf == "retired" {
+ path += ".imported"
+ }
+ now := time.Now()
+ entries := make([]HistoryEntry, 512)
+ for i := range entries {
+ entries[i] = retainedHistoryEntry("expired", now.AddDate(0, 0, -31))
+ }
+ first := now.Add(-time.Hour)
+ for i := 0; i < 128; i++ {
+ entries = append(entries, retainedHistoryEntry("live", first.Add(time.Duration(i)*time.Second)))
+ }
+ encoded, err := json.Marshal(entries)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, encoded, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := hm.loadHistory(); err != nil {
+ t.Fatal(err)
+ }
+ if len(hm.history) != 1 || cap(hm.history) != 1 {
+ t.Fatalf("startup retained rows/storage = %d/%d, want 1/1", len(hm.history), cap(hm.history))
+ }
+ if !hm.history[0].Timestamp.Equal(first) || !hm.history[0].Alert.LastSeen.Equal(entries[len(entries)-1].Alert.LastSeen) {
+ t.Fatal("startup changed occurrence or latest observation")
+ }
+ if hm.storageRetired != (leaf == "retired") {
+ t.Fatal("startup changed recovery-source retirement state")
+ }
+ after, err := os.ReadFile(path)
+ if err != nil || !bytes.Equal(encoded, after) {
+ t.Fatal("compaction rewrote the recovery source")
+ }
+ if len(hm.SnapshotEntries()) != 1 || len(hm.GetHistory(first.Add(-time.Second), 0)) != 1 {
+ t.Fatal("migration or fallback reads lost the surviving occurrence")
+ }
+ })
+ }
+}
+
+func TestHistoryCompactionConcurrentReadersAndWriters(t *testing.T) {
+ hm := newTestHistoryManager(t)
+ hm.history = []HistoryEntry{retainedHistoryEntry("survivor", time.Now())}
+ var wg sync.WaitGroup
+ wg.Add(3)
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 64; i++ {
+ hm.AddAlert(Alert{ID: "temporary", Type: "cpu"})
+ hm.RemoveAlert("temporary")
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 64; i++ {
+ hm.cleanOldEntries()
+ hm.deduplicateHistory()
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 64; i++ {
+ hm.GetAllHistory(0)
+ hm.SnapshotEntries()
+ }
+ }()
+ wg.Wait()
+ if len(hm.history) != 1 || hm.history[0].Alert.ID != "survivor" {
+ t.Fatal("concurrent compaction lost the surviving occurrence")
+ }
+}