Alerting: Fix panic when limit_alerts=0. (#86640)

Oversight in the TopK function meant if k=0, then we'd panic when checking
element zero in the heap, because no items are ever allowed into the heap.
This commit is contained in:
Steve Simpson 2024-04-22 10:14:19 +02:00 committed by GitHub
parent 45a7f649fe
commit f07f48616a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 10 additions and 0 deletions

View File

@ -250,6 +250,11 @@ func (by AlertsBy) TopK(alerts []Alert, k int) []Alert {
// which is important for sorting alerts, as the comparison function is
// very expensive.
// If k is zero or less, return nothing.
if k < 1 {
return []Alert{}
}
// The heap must be in ascending order, so that the root of the heap is
// the current smallest element.
byAscending := func(a1, a2 *Alert) bool { return by(a2, a1) }

View File

@ -113,6 +113,11 @@ func TestTopKAlertsByImportance(t *testing.T) {
input []Alert
expected []Alert
}{{
name: "no alerts are returned (k=0)",
k: 0,
input: []Alert{{State: "normal"}, {State: "nodata"}, {State: "error"}, {State: "pending"}, {State: "alerting"}},
expected: []Alert{},
}, {
name: "alerts are ordered in expected importance (k=1)",
k: 1,
input: []Alert{{State: "normal"}, {State: "nodata"}, {State: "error"}, {State: "pending"}, {State: "alerting"}},