Skip to main content

promql/
histogram_eval.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//! Histogram functions over evaluated series: `histogram_quantile` and `histogram_fraction` over
16//! classic and native histograms (Prometheus `funcHistogramQuantile`, `funcHistogramFraction`
17//! and `resetHistograms`), and `histogram_count`, `histogram_sum`, `histogram_avg`,
18//! `histogram_stddev` and `histogram_stdvar` over native histograms.
19
20mod aggregate;
21mod bounds;
22mod classic;
23// `sub`, `copy_to_schema`, `detect_reset` and `equals` are for the native histogram range
24// functions and binary operators, which build on other branches.
25#[cfg_attr(not(test), allow(dead_code))]
26pub(crate) mod float_histogram;
27pub(crate) mod legacy_bridge;
28mod native;
29#[cfg(test)]
30mod tests;
31
32use std::collections::HashMap;
33use std::sync::Arc;
34
35use common_query::promql_annotations::PromqlAnnotationCollector;
36use datafusion::error::{DataFusionError, Result};
37use datatypes::series::SeriesLabels;
38use datatypes::series::histogram::HistogramView;
39use datatypes::series::samples::{DenseSamplesRef, RowCursor, SampleRef, Series, SeriesSchema};
40use datatypes::series::time::{TimeAxis, union_positions};
41
42pub(crate) use aggregate::{HistogramAggregate, sum_or_avg};
43
44use crate::go_format::format_open_metrics_float;
45use crate::go_sort;
46use crate::grid_series::{
47    GridSeriesBuilder, LabelSet, METADATA_LABELS, external, label_set, merge_same_labelset,
48};
49use crate::map::validate_grid_series;
50
51pub(crate) const BUCKET_LABEL: &str = "le";
52
53/// Histogram inputs that can produce the same output must meet at one partition. The kernel
54/// still groups by metadata before removing it, so distinct histograms are not mixed together.
55pub(crate) const HISTOGRAM_ROUTING_EXCLUDED_LABELS: [&str; 4] =
56    [BUCKET_LABEL, "__name__", "__type__", "__unit__"];
57
58/// `histogram_quantile` or `histogram_fraction` with its constant arguments.
59#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
60pub enum HistogramFunction {
61    /// `histogram_quantile(q, v)`.
62    Quantile(f64),
63    /// `histogram_fraction(lower, upper, v)`.
64    Fraction { lower: f64, upper: f64 },
65}
66
67/// `histogram_quantiles(v, label, q...)`: [`evaluate_histograms`] with `Quantile(q)` for each
68/// `q`, each result labelled with `label` set to `q` as Prometheus' `FormatOpenMetricsFloat`
69/// writes it. Results that then share a label set merge as [`merge_same_labelset`] does, so a
70/// repeated `q`, or a `label` that overwrites the label telling two histograms apart, fails at a
71/// point both hold.
72///
73/// Each `q` is a constant. Prometheus evaluates the quantile arguments at every step, so a
74/// quantile that varies over time is not this kernel's to evaluate.
75pub fn histogram_quantiles(
76    label: &str,
77    quantiles: &[f64],
78    schema: &Arc<SeriesSchema>,
79    series: &[Series],
80) -> Result<Vec<Series>> {
81    let mut output = Vec::new();
82    for &quantile in quantiles {
83        let value: Arc<str> = Arc::from(format_open_metrics_float(quantile));
84        for mut result in
85            evaluate_histograms(HistogramFunction::Quantile(quantile), schema, series)?
86        {
87            result.metric.set(label, value.clone()).map_err(external)?;
88            output.push(result);
89        }
90    }
91    merge_same_labelset(schema, output)
92}
93
94/// Evaluates `function` over the classic and native histograms in `series`.
95///
96/// Float series with the same labels other than `le` form a classic histogram; a float series
97/// whose `le` does not parse is ignored. Native histogram samples are evaluated one by one. At a
98/// point where a native histogram and classic buckets with the same labels (`le` aside) are both
99/// present, neither is evaluated. Each field is evaluated on its own. Classic results drop
100/// `le`; all results drop `__name__`, `__type__` and `__unit__`. Series that then share a label
101/// set are merged as [`merge_same_labelset`] does.
102pub fn evaluate_histograms(
103    function: HistogramFunction,
104    schema: &Arc<SeriesSchema>,
105    series: &[Series],
106) -> Result<Vec<Series>> {
107    evaluate_histograms_with_annotations(function, schema, series, None, None)
108}
109
110/// Per-grid-point arguments to a classic or native histogram function.
111#[derive(Debug, Clone, Copy)]
112pub struct HistogramParameters<'a> {
113    pub quantile: Option<&'a [Option<f64>]>,
114    pub lower: Option<&'a [Option<f64>]>,
115    pub upper: Option<&'a [Option<f64>]>,
116}
117
118/// Evaluates `function` with optional per-point scalar arguments, reporting what it drops to
119/// `collector`. A missing parameter value suppresses the output at that point, matching aggregate
120/// quantile's missing-q behavior.
121pub(crate) fn evaluate_histograms_with_annotations(
122    function: HistogramFunction,
123    schema: &Arc<SeriesSchema>,
124    series: &[Series],
125    parameters: Option<HistogramParameters<'_>>,
126    collector: Option<&PromqlAnnotationCollector>,
127) -> Result<Vec<Series>> {
128    // The groups in the order their first member arrived, so the result is in one order on every
129    // run, as `merge_same_labelset` keeps it.
130    let mut index: HashMap<LabelSet, usize> = HashMap::new();
131    let mut groups: Vec<Group<'_>> = Vec::new();
132    let mut group_of = |metric: SeriesLabels| {
133        *index.entry(label_set(&metric)).or_insert_with(|| {
134            groups.push(Group::new(metric));
135            groups.len() - 1
136        })
137    };
138    let mut members: Vec<(usize, Option<f64>, &Series)> = Vec::new();
139    for series in series {
140        grid_axis(series)?;
141        if let Some(upper_bound) = series
142            .metric
143            .get(BUCKET_LABEL)
144            .and_then(classic::parse_bound)
145        {
146            let mut metric = series.metric.clone();
147            metric.remove(BUCKET_LABEL);
148            members.push((group_of(metric), Some(upper_bound), series));
149        }
150        if has_histograms(series) {
151            members.push((group_of(series.metric.clone()), None, series));
152        }
153    }
154    for (slot, upper_bound, series) in members {
155        let group = &mut groups[slot];
156        match upper_bound {
157            Some(upper_bound) => group.classic.push((upper_bound, series)),
158            None => {
159                // A label set carries at most one native histogram series: a second one would
160                // overwrite the first and drop it from the result.
161                debug_assert!(
162                    group.native.is_none(),
163                    "one label set carries at most one native histogram series; a second one for \
164                     the same label set means the input handed one label set over as several \
165                     series, which a gap in the axis is there to avoid"
166                );
167                group.native = Some(series);
168            }
169        }
170    }
171
172    let mut output = Vec::with_capacity(groups.len());
173    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
174    let mut classic_buckets = Vec::new();
175    let mut native_buckets = Vec::new();
176    let mut values = vec![None; schema.fields.len()];
177    for mut group in groups {
178        // One builder serves every group, so each result series starts explicitly.
179        builder.begin_series();
180        // The positions any member carries, merged once: the holes no member holds are never
181        // visited, so a group of sparse series costs its rows and not its envelope.
182        let axes = group
183            .classic
184            .iter()
185            .map(|member| &member.1.time)
186            .chain(group.native.map(|native| &native.time));
187        // One forward cursor per member and field. The merged positions only increase, so each
188        // member's rows do too: reading them costs one pass over the field, not a chunk scan per
189        // row. The classic members come first, then the native one.
190        let members = group
191            .classic
192            .iter()
193            .map(|&(_, series)| series)
194            .chain(group.native);
195        let mut cursors: Vec<Vec<RowCursor<'_>>> = members
196            .map(|series| series.fields.iter().map(|field| field.cursor()).collect())
197            .collect();
198        let classic_members = group.classic.len();
199        for point in union_positions(axes) {
200            for (field, value) in values.iter_mut().enumerate() {
201                classic_buckets.clear();
202                for (member, &(upper_bound, series)) in group.classic.iter().enumerate() {
203                    let count = series.time.row_of(point).and_then(|row| {
204                        match cursors[member][field]
205                            .at(row)
206                            .expect("a row never goes back")
207                        {
208                            SampleRef::Float(count) => Some(count),
209                            _ => None,
210                        }
211                    });
212                    if let Some(count) = count {
213                        classic_buckets.push(classic::Bucket { upper_bound, count });
214                    }
215                }
216                // Go sorts the buckets present at each point by `<`: +0 and -0 tie and NaN
217                // ties with everything, so which of them coalescing keeps and where a NaN
218                // bound lands follow its sort algorithm.
219                go_sort::sort_by(&mut classic_buckets, |a, b| a.upper_bound < b.upper_bound);
220                let native = group.native.and_then(|series| {
221                    let row = series.time.row_of(point)?;
222                    match cursors[classic_members][field]
223                        .at(row)
224                        .expect("a row never goes back")
225                    {
226                        SampleRef::Histogram(h) => Some(h),
227                        _ => None,
228                    }
229                });
230                let argument = |values: Option<&[Option<f64>]>, bound: f64| -> Option<f64> {
231                    match values {
232                        Some(values) => values.get(point).copied().flatten(),
233                        None => Some(bound),
234                    }
235                };
236                let function = match function {
237                    HistogramFunction::Quantile(q) => {
238                        let Some(q) = argument(parameters.and_then(|p| p.quantile), q) else {
239                            *value = None;
240                            continue;
241                        };
242                        HistogramFunction::Quantile(q)
243                    }
244                    HistogramFunction::Fraction { lower, upper } => {
245                        let (Some(lower), Some(upper)) = (
246                            argument(parameters.and_then(|p| p.lower), lower),
247                            argument(parameters.and_then(|p| p.upper), upper),
248                        ) else {
249                            *value = None;
250                            continue;
251                        };
252                        HistogramFunction::Fraction { lower, upper }
253                    }
254                };
255                // A native histogram and classic buckets of one label set conflict.
256                *value = match (native, classic_buckets.is_empty()) {
257                    (Some(_), false) => {
258                        if let Some(collector) = collector {
259                            collector.record_warning(format!("{}: native histogram and classic buckets both present; dropping both", match function {
260                                HistogramFunction::Quantile(_) => "histogram_quantile",
261                                HistogramFunction::Fraction { .. } => "histogram_fraction",
262                            }));
263                        }
264                        None
265                    }
266                    (None, true) => None,
267                    (Some(h), true) => Some(match function {
268                        HistogramFunction::Quantile(q) => {
269                            native::quantile(q, &h, &mut native_buckets)?
270                        }
271                        HistogramFunction::Fraction { lower, upper } => {
272                            native::fraction(lower, upper, &h, &mut native_buckets)?
273                        }
274                    }),
275                    (None, false) => Some(match function {
276                        HistogramFunction::Quantile(q) => {
277                            classic::bucket_quantile(q, &mut classic_buckets)
278                        }
279                        HistogramFunction::Fraction { lower, upper } => {
280                            classic::bucket_fraction(lower, upper, &mut classic_buckets)
281                        }
282                    }),
283                };
284            }
285            builder.push(point, &values)?;
286        }
287        group.metric.remove_all(&METADATA_LABELS);
288        output.extend(builder.finish(group.metric)?);
289    }
290    merge_same_labelset(schema, output)
291}
292
293/// The series of one label set (`le` aside): classic buckets, and the series of exactly that
294/// label set when it holds native histograms.
295struct Group<'a> {
296    metric: SeriesLabels,
297    classic: Vec<(f64, &'a Series)>,
298    native: Option<&'a Series>,
299}
300
301impl Group<'_> {
302    fn new(metric: SeriesLabels) -> Self {
303        Self {
304            metric,
305            classic: Vec::new(),
306            native: None,
307        }
308    }
309}
310
311/// Checks that `series` is addressed on a grid, which is what a position lookup needs.
312fn grid_axis(series: &Series) -> Result<&TimeAxis> {
313    if series.time.grid().is_none() {
314        return Err(DataFusionError::Execution(
315            "histogram functions require evaluated series".into(),
316        ));
317    }
318    Ok(&series.time)
319}
320
321fn has_histograms(series: &Series) -> bool {
322    series.fields.iter().any(|samples| {
323        samples
324            .segments()
325            .iter()
326            .any(|segment| !matches!(segment.dense(), Some(DenseSamplesRef::Float(_))))
327    })
328}
329
330/// A native histogram as Go's `FloatHistogram.String` writes it, the label value `count_values`
331/// gives a histogram sample.
332pub(crate) fn histogram_string(h: &HistogramView<'_>) -> Result<String> {
333    native::go_string(h)
334}
335
336/// A function of one native histogram.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
338pub enum NativeHistogramFunction {
339    Count,
340    Sum,
341    Avg,
342    StdDev,
343    StdVar,
344}
345
346/// Applies `function` to the native histogram samples of `series`; float samples are dropped and
347/// so is `__name__`. `None` when the series has no histogram sample.
348///
349/// Histogram samples may leave holes, but the holes only skip positions: the result is one series
350/// over the runs of consecutive positions that hold a value.
351///
352/// Series that share a label set once their names are dropped must then go through
353/// [`merge_same_labelset`].
354pub fn map_native_histogram(
355    function: NativeHistogramFunction,
356    schema: &Arc<SeriesSchema>,
357    series: &Series,
358) -> Result<Option<Series>> {
359    validate_grid_series(schema, series)?;
360    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
361    let mut buckets = Vec::new();
362    let mut values = vec![None; schema.fields.len()];
363    // One cursor per field, driven by the positions the axis carries: a series of several runs
364    // costs its rows, and the positions it skips are never visited.
365    let mut cursors = series
366        .fields
367        .iter()
368        .map(|field| field.cursor())
369        .collect::<Vec<_>>();
370    for (point, row) in series.time.positions() {
371        for (field, value) in values.iter_mut().enumerate() {
372            *value = match cursors[field]
373                .at(row)
374                .expect("the axis and the fields are aligned")
375            {
376                SampleRef::Histogram(h) => Some(function.apply(&h, &mut buckets)?),
377                _ => None,
378            };
379        }
380        builder.push(point, &values)?;
381    }
382    let mut metric = series.metric.clone();
383    // Prometheus `simpleHistogramFunc` drops only `__name__`, unlike `histogram_quantile`.
384    metric.remove("__name__");
385    builder.finish(metric)
386}
387
388impl NativeHistogramFunction {
389    /// The PromQL name of the function.
390    pub fn name(self) -> &'static str {
391        match self {
392            Self::Count => "histogram_count",
393            Self::Sum => "histogram_sum",
394            Self::Avg => "histogram_avg",
395            Self::StdDev => "histogram_stddev",
396            Self::StdVar => "histogram_stdvar",
397        }
398    }
399
400    fn apply(self, h: &HistogramView<'_>, buckets: &mut Vec<native::NativeBucket>) -> Result<f64> {
401        Ok(match self {
402            Self::Count => h.count,
403            Self::Sum => h.sum,
404            Self::Avg => h.sum / h.count,
405            Self::StdDev => native::variance(h, buckets)?.sqrt(),
406            Self::StdVar => native::variance(h, buckets)?,
407        })
408    }
409}
410
411impl PartialEq for HistogramFunction {
412    fn eq(&self, o: &Self) -> bool {
413        match (self, o) {
414            (Self::Quantile(a), Self::Quantile(b)) => a.to_bits() == b.to_bits(),
415            (Self::Fraction { lower: a, upper: b }, Self::Fraction { lower: c, upper: d }) => {
416                a.to_bits() == c.to_bits() && b.to_bits() == d.to_bits()
417            }
418            _ => false,
419        }
420    }
421}
422impl Eq for HistogramFunction {}
423impl std::hash::Hash for HistogramFunction {
424    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
425        match self {
426            Self::Quantile(x) => {
427                0u8.hash(h);
428                x.to_bits().hash(h)
429            }
430            Self::Fraction { lower, upper } => {
431                1u8.hash(h);
432                lower.to_bits().hash(h);
433                upper.to_bits().hash(h)
434            }
435        }
436    }
437}