From dcea97eee2b3257f34fd3203cb922eedeabb42a6 Mon Sep 17 00:00:00 2001 From: Balint Zsilavecz Date: Thu, 13 Oct 2022 12:52:19 +0100 Subject: [PATCH] Fix `CumulativeCount` value of `+Inf` bucket created from exemplar (#1148) * Fix `CumulativeCount` value of `+Inf` bucket created from exemplar Signed-off-by: Balint Zsilavecz * Update prometheus/metric_test.go Co-authored-by: Bartlomiej Plotka Signed-off-by: Balint Zsilavecz * Clarify description of implicit `+Inf` bucket count Signed-off-by: Balint Zsilavecz * Fix test variables Signed-off-by: Balint Zsilavecz Signed-off-by: Balint Zsilavecz Co-authored-by: Bartlomiej Plotka --- prometheus/histogram.go | 2 +- prometheus/metric.go | 2 +- prometheus/metric_test.go | 10 +++++++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/prometheus/histogram.go b/prometheus/histogram.go index 0d47fec..73e814a 100644 --- a/prometheus/histogram.go +++ b/prometheus/histogram.go @@ -613,7 +613,7 @@ func (h *constHistogram) Write(out *dto.Metric) error { // to send it to Prometheus in the Collect method. // // buckets is a map of upper bounds to cumulative counts, excluding the +Inf -// bucket. +// bucket. The +Inf bucket is implicit, and its value is equal to the provided count. // // NewConstHistogram returns an error if the length of labelValues is not // consistent with the variable labels in Desc or if Desc is invalid. diff --git a/prometheus/metric.go b/prometheus/metric.go index f0941f6..b5119c5 100644 --- a/prometheus/metric.go +++ b/prometheus/metric.go @@ -187,7 +187,7 @@ func (m *withExemplarsMetric) Write(pb *dto.Metric) error { } else { // The +Inf bucket should be explicitly added if there is an exemplar for it, similar to non-const histogram logic in https://github.com/prometheus/client_golang/blob/main/prometheus/histogram.go#L357-L365. b := &dto.Bucket{ - CumulativeCount: proto.Uint64(pb.Histogram.Bucket[len(pb.Histogram.GetBucket())-1].GetCumulativeCount()), + CumulativeCount: proto.Uint64(pb.Histogram.GetSampleCount()), UpperBound: proto.Float64(math.Inf(1)), Exemplar: e, } diff --git a/prometheus/metric_test.go b/prometheus/metric_test.go index 2d69b08..dd7d843 100644 --- a/prometheus/metric_test.go +++ b/prometheus/metric_test.go @@ -79,10 +79,14 @@ func TestWithExemplarsMetric(t *testing.T) { } } - infBucket := metric.GetHistogram().Bucket[len(metric.GetHistogram().Bucket)-1].GetUpperBound() + infBucket := metric.GetHistogram().Bucket[len(metric.GetHistogram().Bucket)-1] - if infBucket != math.Inf(1) { - t.Errorf("want %v, got %v", math.Inf(1), infBucket) + if want, got := math.Inf(1), infBucket.GetUpperBound(); want != got { + t.Errorf("want %v, got %v", want, got) + } + + if want, got := uint64(4711), infBucket.GetCumulativeCount(); want != got { + t.Errorf("want %v, got %v", want, got) } }) }