Skip to main content

promql/histogram_eval/
aggregate.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The compensated `sum` and `avg` fold of native histograms, following the histogram paths of
16//! Prometheus `aggregation`. The range functions `sum_over_time` and `avg_over_time` fold a window
17//! with it, and the aggregate node runs the same steps per point through
18//! `crate::aggregate::HistogramAccumulator`.
19
20use datafusion::error::Result;
21
22use crate::histogram_eval::float_histogram::FloatHistogram;
23
24/// A native histogram aggregation.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub(crate) enum HistogramAggregate {
27    Sum,
28    Avg,
29}
30
31/// The Kahan sum or the mean of `histograms` in order, without compaction; `None` when there is
32/// none or they mix exponential and custom buckets. Prometheus `sum_over_time` and
33/// `avg_over_time` run the same steps as the aggregations. Histograms are consumed one at a
34/// time, so the first error ends the fold. The result is derived, so it carries no start
35/// timestamp.
36///
37/// The flag reports whether any add had to reconcile two different custom-bucket sets, which is
38/// what Prometheus annotates with an info. It is carried out of the fold rather than recomputed:
39/// the fold already calls [`FloatHistogram::kahan_add`] and receives that outcome.
40pub(crate) fn sum_or_avg(
41    op: HistogramAggregate,
42    histograms: impl IntoIterator<Item = Result<FloatHistogram>>,
43) -> Result<(Option<FloatHistogram>, bool)> {
44    let mut value: Option<FloatHistogram> = None;
45    let mut compensation: Option<FloatHistogram> = None;
46    let mut mean: Option<FloatHistogram> = None;
47    let mut count = 0.0;
48    let mut custom_reconciled = false;
49    for h in histograms {
50        let h = h?;
51        count += 1.0;
52        let Some(current) = value.as_mut() else {
53            value = Some(h);
54            continue;
55        };
56        // Go drops the result with a warning for this addition error only; others propagate.
57        if current.uses_custom_buckets() != h.uses_custom_buckets() {
58            return Ok((None, custom_reconciled));
59        }
60        match op {
61            HistogramAggregate::Sum => {
62                let (c, outcome) = current.kahan_add(&h, compensation.take())?;
63                custom_reconciled |= outcome.custom_bounds_reconciled;
64                compensation = Some(c);
65            }
66            HistogramAggregate::Avg => {
67                if mean.is_none() {
68                    let mut sum = current.clone();
69                    let (c, outcome) = sum.kahan_add(&h, compensation.clone())?;
70                    custom_reconciled |= outcome.custom_bounds_reconciled;
71                    if !sum.has_overflow() {
72                        *current = sum;
73                        compensation = Some(c);
74                        continue;
75                    }
76                    let mut started = current.clone();
77                    started.div(count - 1.0);
78                    if let Some(c) = compensation.as_mut() {
79                        c.div(count - 1.0);
80                    }
81                    mean = Some(started);
82                }
83                // Go switches to an incremental mean once the plain sum overflows.
84                let q = (count - 1.0) / count;
85                if let Some(c) = compensation.as_mut() {
86                    c.mul(q);
87                }
88                let mut to_add = h;
89                to_add.div(count);
90                let mean = mean.as_mut().expect("set above");
91                mean.mul(q);
92                let (c, outcome) = mean.kahan_add(&to_add, compensation.take())?;
93                custom_reconciled |= outcome.custom_bounds_reconciled;
94                compensation = Some(c);
95            }
96        }
97    }
98    let Some(mut value) = value else {
99        return Ok((None, custom_reconciled));
100    };
101    match op {
102        HistogramAggregate::Sum => {
103            if let Some(c) = compensation {
104                value.add(&c)?;
105            }
106        }
107        HistogramAggregate::Avg => match mean {
108            Some(mut mean) => {
109                if let Some(c) = compensation {
110                    mean.add(&c)?;
111                }
112                value = mean;
113            }
114            None => {
115                value.div(count);
116                if let Some(mut c) = compensation {
117                    c.div(count);
118                    value.add(&c)?;
119                }
120            }
121        },
122    }
123    // The result was derived from its inputs, so it carries no start timestamp of its own, like
124    // every other operation that builds one. Clearing it here covers the fold that added nothing:
125    // the first histogram of a window becomes the result as it arrived, and the adds above are
126    // what drop the field otherwise, which would make the payload depend on the sample count.
127    // The bucket layout is left as the fold built it -- compaction belongs to the caller.
128    value.start_timestamp = None;
129    Ok((Some(value), custom_reconciled))
130}