diff --git a/pkg/services/ngalert/api/tooling/definitions/prom.go b/pkg/services/ngalert/api/tooling/definitions/prom.go index bdbe93c9c96..59bc32e041f 100644 --- a/pkg/services/ngalert/api/tooling/definitions/prom.go +++ b/pkg/services/ngalert/api/tooling/definitions/prom.go @@ -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) } diff --git a/pkg/services/ngalert/api/tooling/definitions/prom_test.go b/pkg/services/ngalert/api/tooling/definitions/prom_test.go index 2c1e60c76a2..a2013541e2b 100644 --- a/pkg/services/ngalert/api/tooling/definitions/prom_test.go +++ b/pkg/services/ngalert/api/tooling/definitions/prom_test.go @@ -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"}},