From cdfae0117abe382787131d0bc8ac22887294a5b4 Mon Sep 17 00:00:00 2001
From: Aliaksandr Valialkin <valyala@gmail.com>
Date: Wed, 23 Jun 2021 14:18:13 +0300
Subject: [PATCH] app/vmselect/promql: return the last timestamp for the max /
 min value from `tmax_over_time()` and `tmin_over_time()` function as most
 users expect

---
 app/vmselect/promql/rollup.go | 6 ++++--
 docs/CHANGELOG.md             | 1 +
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/app/vmselect/promql/rollup.go b/app/vmselect/promql/rollup.go
index 4e9eb763f2..377b7cc7a6 100644
--- a/app/vmselect/promql/rollup.go
+++ b/app/vmselect/promql/rollup.go
@@ -1149,7 +1149,8 @@ func rollupTmin(rfa *rollupFuncArg) float64 {
 	minValue := values[0]
 	minTimestamp := timestamps[0]
 	for i, v := range values {
-		if v < minValue {
+		// Get the last timestamp for the minimum value as most users expect.
+		if v <= minValue {
 			minValue = v
 			minTimestamp = timestamps[i]
 		}
@@ -1168,7 +1169,8 @@ func rollupTmax(rfa *rollupFuncArg) float64 {
 	maxValue := values[0]
 	maxTimestamp := timestamps[0]
 	for i, v := range values {
-		if v > maxValue {
+		// Get the last timestamp for the maximum value as most users expect.
+		if v >= maxValue {
 			maxValue = v
 			maxTimestamp = timestamps[i]
 		}
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7a3ae7d871..30d7ffaaff 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -20,6 +20,7 @@ sort: 15
 * BUGFIX: prevent from adding new samples to deleted time series after the rotation of the inverted index (the rotation is performed once per `-retentionPeriod`). See [this comment](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1347#issuecomment-861232136) for details.
 * BUGFIX: vmstorage: reduce high disk write IO usage on systems with big number of CPU cores. The issue has been introduced in the release [v1.59.0](#v1590). See [this commit](aa9b56a046b6ae8083fa659df35dd5e994bf9115) and [this comment](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1338#issuecomment-863046999) for details.
 * BUGFIX: vmstorage: prevent from incorrect stats collection when multiple concurrent queries execute the same tag filter. This may help reducing CPU usage under certain workloads. See [this issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1338).
+* BUGFIX: vmselect: return the last timestamp for the max / min value from `tmax_over_time(m[d])` and `tmin_over_time(m[d])` [MetricsQL functions](https://docs.victoriametrics.com/MetricsQL.html) as most users expect. See also [this issue](https://github.com/prometheus/prometheus/issues/8966).
 
 
 ## [v1.61.1](https://github.com/VictoriaMetrics/VictoriaMetrics/releases/tag/v1.61.1)