diff --git a/app/vmselect/promql/aggr.go b/app/vmselect/promql/aggr.go index 46ebc43231..2555ad75f5 100644 --- a/app/vmselect/promql/aggr.go +++ b/app/vmselect/promql/aggr.go @@ -618,7 +618,9 @@ func newAggrFuncTopK(isReverse bool) aggrFunc { }) fillNaNsAtIdx(n, ks[n], tss) } - return removeNaNs(tss) + tss = removeNaNs(tss) + reverseSeries(tss) + return tss } return aggrFuncExt(afe, args[1], &afa.ae.Modifier, afa.ae.Limit, true) } @@ -683,7 +685,17 @@ func getRangeTopKTimeseries(tss []*timeseries, modifier *metricsql.ModifierExpr, if remainingSumTS != nil { tss = append(tss, remainingSumTS) } - return removeNaNs(tss) + tss = removeNaNs(tss) + reverseSeries(tss) + return tss +} + +func reverseSeries(tss []*timeseries) { + j := len(tss) + for i := 0; i < len(tss)/2; i++ { + j-- + tss[i], tss[j] = tss[j], tss[i] + } } func getRemainingSumTimeseries(tss []*timeseries, modifier *metricsql.ModifierExpr, ks []float64, remainingSumTagName string) *timeseries { diff --git a/app/vmselect/promql/exec.go b/app/vmselect/promql/exec.go index ae8f3794a5..ee1bc2e5c7 100644 --- a/app/vmselect/promql/exec.go +++ b/app/vmselect/promql/exec.go @@ -86,21 +86,22 @@ func Exec(ec *EvalConfig, q string, isFirstPointOnly bool) ([]netstorage.Result, } func maySortResults(e metricsql.Expr, tss []*timeseries) bool { - fe, ok := e.(*metricsql.FuncExpr) - if !ok { - return true - } - switch fe.Name { - case "sort", "sort_desc", - "sort_by_label", "sort_by_label_desc", - "topk", "bottomk", - "topk_max", "topk_min", "topk_avg", "topk_median", - "bottomk_max", "bottomk_min", "bottomk_avg", "bottomk_median", - "outliersk": - return false - default: - return true + switch v := e.(type) { + case *metricsql.FuncExpr: + switch strings.ToLower(v.Name) { + case "sort", "sort_desc", + "sort_by_label", "sort_by_label_desc": + return false + } + case *metricsql.AggrFuncExpr: + switch strings.ToLower(v.Name) { + case "topk", "bottomk", "outliersk", + "topk_max", "topk_min", "topk_avg", "topk_median", + "bottomk_max", "bottomk_min", "bottomk_avg", "bottomk_median": + return false + } } + return true } func timeseriesToResult(tss []*timeseries, maySort bool) ([]netstorage.Result, error) {