diff --git a/pkg/query-service/app/limit.go b/pkg/query-service/app/limit.go index 55dd56a31c1..3ace3c687ca 100644 --- a/pkg/query-service/app/limit.go +++ b/pkg/query-service/app/limit.go @@ -40,7 +40,7 @@ func applyMetricLimit(results []*v3.Result, queryRangeParams *v3.QueryRangeParam } } - ithSum, jthSum, ithCount, jthCount := 0.0, 0.0, 1.0, 1.0 + ithSum, jthSum, ithCount, jthCount := 0.0, 0.0, 0.0, 0.0 for _, point := range result.Series[i].Points { if math.IsNaN(point.Value) || math.IsInf(point.Value, 0) { continue @@ -57,6 +57,10 @@ func applyMetricLimit(results []*v3.Result, queryRangeParams *v3.QueryRangeParam jthCount++ } + // avoid division by zero + ithCount = math.Max(ithCount, 1) + jthCount = math.Max(jthCount, 1) + if orderBy.Order == "asc" { return ithSum/ithCount < jthSum/jthCount } else if orderBy.Order == "desc" {