Skip to main content

promql/range_eval/
histogram.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//! Range functions over windows that hold native histogram samples, following the histogram
16//! branches of Prometheus' range functions. Windows of floats alone never get here.
17
18use std::borrow::Cow;
19
20use common_query::promql_annotations::PromqlAnnotationCollector;
21use datafusion::error::Result;
22use datatypes::series::histogram::CounterResetHint;
23
24use crate::functions::{EdgeKind, count_edges, instant_delta};
25use crate::grid_series::GridSample;
26use crate::histogram_eval::HistogramAggregate;
27use crate::histogram_eval::float_histogram::FloatHistogram;
28use crate::histogram_eval::sum_or_avg;
29use crate::range_eval::function::{ExtrapolationSpan, extrapolation_factor, seconds};
30use crate::range_eval::{FloatWindow, RangeFunction, WindowKernel};
31
32/// Histogram samples of one window at their shifted timestamps, in time order.
33type Histograms = [(i64, FloatHistogram)];
34
35/// The window of one field at `eval_ts`, holding `histograms` (not empty) and `floats` when it
36/// has any float sample.
37#[allow(clippy::too_many_arguments)]
38pub(super) fn evaluate(
39    function: RangeFunction,
40    floats: Option<FloatWindow<'_>>,
41    histograms: &Histograms,
42    eval_ts: i64,
43    range_ms: i64,
44    offset_ms: i64,
45    kernel: &mut WindowKernel,
46    collector: Option<&PromqlAnnotationCollector>,
47) -> Result<Option<GridSample>> {
48    use RangeFunction::*;
49    if floats.is_some()
50        && !matches!(
51            function,
52            MinOverTime
53                | MaxOverTime
54                | StddevOverTime
55                | StdvarOverTime
56                | QuantileOverTime(_)
57                | Deriv
58                | PredictLinear(_)
59                | DoubleExponentialSmoothing { .. }
60                | MadOverTime
61                | TsOfMinOverTime
62                | TsOfMaxOverTime
63                | CountOverTime
64                | PresentOverTime
65                | LastOverTime
66                | FirstOverTime
67                | TsOfFirstOverTime
68                | TsOfLastOverTime
69                | Resets
70                | Changes
71                | Irate
72                | Idelta
73        )
74    {
75        record_warning(
76            collector,
77            format!(
78                "{}: encountered a mix of float and native histogram samples",
79                function_name(function)
80            ),
81        );
82    }
83    // The functions that read only the floats of a mixed window ignore its histograms, which is
84    // what the existing planner tells the client with an info. The set is the one that path lists
85    // as `FloatOnly`; the experimental functions this crate also has carry no message there, so
86    // they stay silent rather than inventing one.
87    if floats.is_some()
88        && matches!(
89            function,
90            MinOverTime
91                | MaxOverTime
92                | StddevOverTime
93                | StdvarOverTime
94                | QuantileOverTime(_)
95                | Deriv
96                | PredictLinear(_)
97                | DoubleExponentialSmoothing { .. }
98        )
99    {
100        record_info(
101            collector,
102            format!(
103                "{}: ignored native histogram samples",
104                function_name(function)
105            ),
106        );
107    }
108    let float = |value: f64| Some(GridSample::Float(value));
109    let (last_ts, last) = &histograms[histograms.len() - 1];
110    let (first_ts, first) = &histograms[0];
111    Ok(match function {
112        // Prometheus reads only the floats of these.
113        MinOverTime
114        | MaxOverTime
115        | StddevOverTime
116        | StdvarOverTime
117        | QuantileOverTime(_)
118        | Deriv
119        | PredictLinear(_)
120        | DoubleExponentialSmoothing { .. }
121        | MadOverTime
122        | TsOfMinOverTime
123        | TsOfMaxOverTime => floats.and_then(kernel).map(GridSample::Float),
124        CountOverTime => {
125            float((floats.map_or(0, |window| window.values.len()) + histograms.len()) as f64)
126        }
127        PresentOverTime => float(1.0),
128        LastOverTime => match floats {
129            Some(window) if last_ts < window.timestamps.last().expect("not empty") => {
130                float(window.values[window.values.len() - 1])
131            }
132            _ => Some(GridSample::Histogram(Box::new(last.clone()))),
133        },
134        FirstOverTime => match floats {
135            Some(window) if window.timestamps[0] < *first_ts => float(window.values[0]),
136            _ => Some(GridSample::Histogram(Box::new(first.clone()))),
137        },
138        TsOfFirstOverTime => {
139            let ts = floats.map_or(*first_ts, |window| window.timestamps[0].min(*first_ts));
140            float(seconds(ts - offset_ms))
141        }
142        // Go takes the max with 0 for a kind of sample the window does not have.
143        TsOfLastOverTime => {
144            let histogram_ts = last_ts - offset_ms;
145            let ts = match floats {
146                Some(window) => {
147                    (window.timestamps.last().expect("not empty") - offset_ms).max(histogram_ts)
148                }
149                None => histogram_ts.max(0),
150            };
151            float(seconds(ts))
152        }
153        Resets => float(edges(floats, histograms, EdgeKind::Resets, offset_ms)? as f64),
154        Changes => float(edges(floats, histograms, EdgeKind::Changes, offset_ms)? as f64),
155        SumOverTime | AvgOverTime if floats.is_none() => {
156            let op = if function == SumOverTime {
157                HistogramAggregate::Sum
158            } else {
159                HistogramAggregate::Avg
160            };
161            // The hints are read from the window's own histograms, so nothing is cloned for the
162            // check; the fold below copies each histogram in turn and folds it into the
163            // accumulator it keeps.
164            if has_contradictory_reset_hints(histograms.iter().map(|(_, h)| h)) {
165                record_warning(
166                    collector,
167                    format!(
168                        "{}: native histogram counter reset hints contradict",
169                        function_name(function)
170                    ),
171                );
172            }
173            // The fold reports both answers itself: a `None` is the mixed-bucket drop, and the
174            // flag is the reconciliation its own adds already observed. Re-walking the pairs to
175            // learn either would double the histogram work of every window.
176            let (result, custom_reconciled) =
177                sum_or_avg(op, histograms.iter().map(|(_, h)| Ok(h.clone())))?;
178            if result.is_none() {
179                record_warning(
180                    collector,
181                    format!(
182                        "{}: dropped native histogram range with incompatible schemas",
183                        function_name(function)
184                    ),
185                );
186            }
187            if custom_reconciled {
188                record_info(
189                    collector,
190                    format!(
191                        "{}: reconciled native histograms with different custom buckets",
192                        function_name(function)
193                    ),
194                );
195            }
196            result.map(|h| GridSample::Histogram(Box::new(h)))
197        }
198        Rate | Increase if floats.is_none() && histograms.len() == 1 => {
199            let (first_ts, first) = &histograms[0];
200            let range_start = eval_ts - range_ms;
201            if first.start_timestamp.is_some_and(|start| {
202                start != 0
203                    && start.checked_add(offset_ms).is_some_and(|shifted_start| {
204                        range_start < shifted_start && shifted_start < *first_ts
205                    })
206            }) {
207                record_histogram_flavor_warning(collector, function, histograms);
208                let mut result = first.clone();
209                let factor = if function == Rate {
210                    1.0 / seconds(range_ms)
211                } else {
212                    1.0
213                };
214                result.mul(factor);
215                result.reset_hint = CounterResetHint::Gauge;
216                Some(GridSample::Histogram(Box::new(result)))
217            } else {
218                None
219            }
220        }
221        Rate | Increase | Delta if floats.is_none() && histograms.len() > 1 => {
222            let is_counter = function != Delta;
223            record_histogram_flavor_warning(collector, function, histograms);
224            record_histogram_pair_annotations(collector, function, histograms);
225            let range_start = eval_ts - range_ms;
226            let synthetic_zero = is_counter
227                .then_some(first.start_timestamp)
228                .flatten()
229                .and_then(|start| start.checked_add(offset_ms).map(|shifted| (start, shifted)))
230                .filter(|(start, shifted)| {
231                    *start != 0 && range_start < *shifted && *shifted < *first_ts
232                })
233                .map(|(_, shifted)| shifted);
234            let Some(mut result) = histogram_rate(histograms, is_counter, offset_ms)? else {
235                record_warning(
236                    collector,
237                    format!(
238                        "{}: dropped native histogram range with incompatible schemas",
239                        function_name(function)
240                    ),
241                );
242                return Ok(None);
243            };
244            let effective_first_ts = synthetic_zero.unwrap_or(*first_ts);
245            if *last_ts <= effective_first_ts {
246                return Ok(None);
247            }
248            // A synthetic zero *is* the counter's zero point, so nothing is extrapolated before it
249            // and `zero_point` says so with `0`; the counter instead extrapolates towards zero from
250            // its first real sample, and only when that sample is not itself negative.
251            let zero_point = if synthetic_zero.is_some() {
252                Some(0.0)
253            } else {
254                (is_counter && result.count > 0.0 && first.count >= 0.0)
255                    .then(|| first.count / result.count)
256            };
257            // The sampled interval runs from the synthetic zero while the average interval is
258            // measured between the real samples, as `native_extrapolated_rate` does: they are two
259            // different spans, and taking one for the other shifts the average by a whole sample
260            // interval.
261            let factor = extrapolation_factor(
262                ExtrapolationSpan {
263                    sampled_from: effective_first_ts,
264                    average_from: *first_ts,
265                    last: *last_ts,
266                    samples_minus_one: histograms.len() - 1,
267                },
268                eval_ts,
269                range_ms,
270                is_counter,
271                function == Rate,
272                zero_point,
273            );
274            if synthetic_zero.is_some() && result.add(first).is_err() {
275                record_warning(
276                    collector,
277                    format!(
278                        "{}: dropped native histogram range with incompatible schemas",
279                        function_name(function)
280                    ),
281                );
282                return Ok(None);
283            }
284            result.mul(factor);
285            Some(GridSample::Histogram(Box::new(result)))
286        }
287        Irate | Idelta => {
288            // The annotations read the window before `last_two` consumes it.
289            let had_floats = floats.is_some();
290            record_mixed_last_two(collector, function, floats.as_ref(), histograms);
291            let tail_histograms = &histograms[histograms.len().saturating_sub(2)..];
292            if tail_histograms.len() == 2 {
293                record_histogram_flavor_warning(collector, function, tail_histograms);
294                if tail_histograms[1].0 > tail_histograms[0].0 {
295                    record_histogram_pair_annotations(collector, function, tail_histograms);
296                }
297            }
298            let result = if function == Irate {
299                last_two::<true>(floats, histograms, offset_ms)?
300            } else {
301                last_two::<false>(floats, histograms, offset_ms)?
302            };
303            if result.is_none() && !had_floats && tail_histograms.len() == 2 {
304                record_warning(
305                    collector,
306                    format!(
307                        "{}: dropped native histogram range with incompatible schemas",
308                        function_name(function)
309                    ),
310                );
311            }
312            result
313        }
314        // Mixed windows, and rates over fewer than two histograms. The mixed warning was already
315        // recorded above for every function that reaches here, so this branch only answers.
316        SumOverTime | AvgOverTime | Rate | Increase | Delta => None,
317    })
318}
319
320fn function_name(function: RangeFunction) -> &'static str {
321    use RangeFunction::*;
322    match function {
323        Rate => "rate",
324        Increase => "increase",
325        Delta => "delta",
326        Irate => "irate",
327        Idelta => "idelta",
328        AvgOverTime => "avg_over_time",
329        MinOverTime => "min_over_time",
330        MaxOverTime => "max_over_time",
331        SumOverTime => "sum_over_time",
332        CountOverTime => "count_over_time",
333        LastOverTime => "last_over_time",
334        PresentOverTime => "present_over_time",
335        StddevOverTime => "stddev_over_time",
336        StdvarOverTime => "stdvar_over_time",
337        QuantileOverTime(_) => "quantile_over_time",
338        Resets => "resets",
339        Changes => "changes",
340        Deriv => "deriv",
341        PredictLinear(_) => "predict_linear",
342        DoubleExponentialSmoothing { .. } => "double_exponential_smoothing",
343        FirstOverTime => "first_over_time",
344        MadOverTime => "mad_over_time",
345        TsOfFirstOverTime => "ts_of_first_over_time",
346        TsOfLastOverTime => "ts_of_last_over_time",
347        TsOfMinOverTime => "ts_of_min_over_time",
348        TsOfMaxOverTime => "ts_of_max_over_time",
349    }
350}
351
352fn record_warning(collector: Option<&PromqlAnnotationCollector>, message: String) {
353    if let Some(collector) = collector {
354        collector.record_warning(message);
355    }
356}
357fn record_info(collector: Option<&PromqlAnnotationCollector>, message: String) {
358    if let Some(collector) = collector {
359        collector.record_info(message);
360    }
361}
362fn has_contradictory_reset_hints<'a>(
363    samples: impl IntoIterator<Item = &'a FloatHistogram>,
364) -> bool {
365    let mut saw_counter = false;
366    let mut saw_not_counter = false;
367    for histogram in samples {
368        saw_counter |= histogram.reset_hint == CounterResetHint::CounterReset;
369        saw_not_counter |= histogram.reset_hint == CounterResetHint::NotCounterReset;
370    }
371    saw_counter && saw_not_counter
372}
373
374/// The info a `rate`/`increase`/`delta` window owes when adjacent histograms carry different
375/// custom bucket bounds and the fold has to reconcile them.
376///
377/// The check compares bounds; it does not add the pair. The fold that follows does that work, and
378/// repeating it here would double the histogram arithmetic of every window. This is the same
379/// per-pair check the existing planner's counter UDF makes.
380fn record_histogram_flavor_warning(
381    collector: Option<&PromqlAnnotationCollector>,
382    function: RangeFunction,
383    histograms: &Histograms,
384) {
385    let is_counter = matches!(
386        function,
387        RangeFunction::Rate | RangeFunction::Increase | RangeFunction::Irate
388    );
389    let wrong_flavor = if is_counter {
390        histograms
391            .iter()
392            .any(|(_, histogram)| histogram.reset_hint == CounterResetHint::Gauge)
393    } else {
394        histograms
395            .first()
396            .is_some_and(|(_, histogram)| histogram.reset_hint != CounterResetHint::Gauge)
397            || histograms
398                .last()
399                .is_some_and(|(_, histogram)| histogram.reset_hint != CounterResetHint::Gauge)
400    };
401    if wrong_flavor {
402        let expected = if is_counter { "counter" } else { "gauge" };
403        record_warning(
404            collector,
405            format!(
406                "{}: native histogram input should be a {expected} histogram",
407                function_name(function)
408            ),
409        );
410    }
411}
412
413fn record_histogram_pair_annotations(
414    collector: Option<&PromqlAnnotationCollector>,
415    function: RangeFunction,
416    histograms: &Histograms,
417) {
418    let reconciled = histograms.windows(2).any(|pair| {
419        pair[0].1.uses_custom_buckets()
420            && pair[1].1.uses_custom_buckets()
421            && pair[0].1.custom_values != pair[1].1.custom_values
422    });
423    if reconciled {
424        record_info(
425            collector,
426            format!(
427                "{}: reconciled native histograms with different custom buckets",
428                function_name(function)
429            ),
430        );
431    }
432}
433
434fn record_mixed_last_two(
435    collector: Option<&PromqlAnnotationCollector>,
436    function: RangeFunction,
437    floats: Option<&FloatWindow<'_>>,
438    histograms: &Histograms,
439) {
440    // Nothing is recorded without a collector, and the walk below exists only to decide whether
441    // something would be.
442    if collector.is_none() {
443        return;
444    }
445    let Some(floats) = floats else {
446        return;
447    };
448    let mut float_index = floats.values.len();
449    let mut histogram_index = histograms.len();
450    let mut last = None;
451    let mut previous = None;
452    for _ in 0..2 {
453        let sample = match (float_index.checked_sub(1), histogram_index.checked_sub(1)) {
454            (Some(fi), Some(hi)) if floats.timestamps[fi] >= histograms[hi].0 => {
455                float_index = fi;
456                Some(Sample::Float(floats.values[fi]))
457            }
458            (Some(_), Some(hi)) => {
459                histogram_index = hi;
460                Some(Sample::Histogram(&histograms[hi].1))
461            }
462            (Some(fi), None) => {
463                float_index = fi;
464                Some(Sample::Float(floats.values[fi]))
465            }
466            (None, Some(hi)) => {
467                histogram_index = hi;
468                Some(Sample::Histogram(&histograms[hi].1))
469            }
470            (None, None) => None,
471        };
472        let Some(sample) = sample else { break };
473        previous = last;
474        last = Some(sample);
475    }
476    if matches!(
477        (previous, last),
478        (Some(Sample::Float(_)), Some(Sample::Histogram(_)))
479            | (Some(Sample::Histogram(_)), Some(Sample::Float(_)))
480    ) {
481        record_warning(
482            collector,
483            format!(
484                "{}: encountered a mix of float and native histogram samples in the last two points",
485                function_name(function)
486            ),
487        );
488    }
489}
490
491/// One sample of a window, in the order Prometheus merges floats and histograms.
492#[derive(Clone, Copy)]
493enum Sample<'a> {
494    Float(f64),
495    Histogram(&'a FloatHistogram),
496}
497
498/// The samples of both kinds in time order.
499fn merged<'a>(
500    floats: Option<FloatWindow<'a>>,
501    histograms: &'a Histograms,
502) -> impl Iterator<Item = (i64, Sample<'a>)> {
503    let mut floats = floats
504        .into_iter()
505        .flat_map(|window| window.timestamps.iter().zip(window.values))
506        .map(|(&ts, &value)| (ts, Sample::Float(value)))
507        .peekable();
508    let mut histograms = histograms
509        .iter()
510        .map(|(ts, h)| (*ts, Sample::Histogram(h)))
511        .peekable();
512    std::iter::from_fn(move || match (floats.peek(), histograms.peek()) {
513        (Some((float_ts, _)), Some((histogram_ts, _))) if float_ts < histogram_ts => floats.next(),
514        (_, Some(_)) => histograms.next(),
515        (Some(_), None) => floats.next(),
516        (None, None) => None,
517    })
518}
519
520/// Prometheus `funcResets` and `funcChanges` over floats and histograms: a change of kind
521/// counts as one edge.
522fn edges(
523    floats: Option<FloatWindow<'_>>,
524    histograms: &Histograms,
525    kind: EdgeKind,
526    offset_ms: i64,
527) -> Result<u64> {
528    let mut count = 0;
529    let mut previous: Option<(i64, Sample<'_>)> = None;
530    for (timestamp, current) in merged(floats, histograms) {
531        if let Some((previous_ts, previous)) = previous {
532            count += match (previous, current) {
533                (Sample::Float(a), Sample::Float(b)) => count_edges(&[a, b], kind),
534                (Sample::Histogram(a), Sample::Histogram(b)) => u64::from(match kind {
535                    // `resets` counts the restarts the payload alone does not show. A start
536                    // timestamp inside the window witnesses a counter that began again, whose
537                    // counts may have grown across the restart, which is the rule `rate` and
538                    // `increase` already read.
539                    //
540                    // A gauge-to-counter edge is deliberately NOT counted, although the existing
541                    // planner counts one (`NativeHistogramRangeFloatKind::Resets`). Prometheus
542                    // does not: the golden case `resets 25000 0` in `histogram_cases.txt` holds a
543                    // gauge sample followed by a counter sample with identical payloads and
544                    // expects 0. Where the two disagree the golden wins, because the existing
545                    // planner's count there is not a behaviour this route can reproduce and stay
546                    // correct.
547                    EdgeKind::Resets => {
548                        b.detect_counter_reset_shifted(a, previous_ts, timestamp, offset_ms)
549                    }
550                    EdgeKind::Changes => !b.equals(a),
551                }),
552                _ => 1,
553            };
554        }
555        previous = Some((timestamp, current));
556    }
557    Ok(count)
558}
559
560/// Prometheus `instantValue` over the last two samples of either kind; a float and a histogram
561/// give nothing.
562fn last_two<const IS_RATE: bool>(
563    floats: Option<FloatWindow<'_>>,
564    histograms: &Histograms,
565    offset_ms: i64,
566) -> Result<Option<GridSample>> {
567    let floats = floats.map(|window| {
568        let from = window.values.len().saturating_sub(2);
569        FloatWindow {
570            timestamps: &window.timestamps[from..],
571            values: &window.values[from..],
572            ..window
573        }
574    });
575    let histograms = &histograms[histograms.len().saturating_sub(2)..];
576    let tail: Vec<_> = merged(floats, histograms).collect();
577    let [.., (prev_ts, prev), (last_ts, last)] = tail[..] else {
578        return Ok(None);
579    };
580    Ok(match (prev, last) {
581        (Sample::Float(prev), Sample::Float(last)) => {
582            instant_delta::<IS_RATE>((prev_ts, prev), (last_ts, last)).map(GridSample::Float)
583        }
584        (Sample::Histogram(prev), Sample::Histogram(last)) => {
585            let interval = last_ts - prev_ts;
586            let mut result = last.clone();
587            // `irate` drops the counter's accumulations on a reset the way the existing planner's
588            // `idelta_value` does, start timestamp included; `idelta` is a plain difference and
589            // reads no reset at all.
590            if !IS_RATE || !last.detect_counter_reset_shifted(prev, prev_ts, last_ts, offset_ms) {
591                if result.uses_custom_buckets() != prev.uses_custom_buckets() {
592                    return Ok(None);
593                }
594                result.sub(prev)?;
595            }
596            result.reset_hint = CounterResetHint::Gauge;
597            result.compact();
598            if IS_RATE {
599                result.div(interval as f64 / 1000.0);
600            }
601            Some(GridSample::Histogram(Box::new(result)))
602        }
603        _ => None,
604    })
605}
606
607/// Prometheus `histogramRate`: the increase from the first to the last histogram, adding back
608/// what counter resets dropped. `None` when the histograms mix exponential and custom buckets.
609fn histogram_rate(
610    points: &Histograms,
611    is_counter: bool,
612    offset_ms: i64,
613) -> Result<Option<FloatHistogram>> {
614    let last = &points[points.len() - 1].1;
615    let mut prev = Cow::Borrowed(&points[0].1);
616    let mut uses_custom_buckets = prev.uses_custom_buckets();
617    // A reset between the first two samples makes the first one irrelevant, layout included.
618    // The start timestamps witness a reset the counts alone do not, which is what a restarted
619    // counter looks like when it is already above the previous value.
620    if is_counter {
621        let (second_ts, second) = &points[1];
622        if second.detect_counter_reset_shifted(&prev, points[0].0, *second_ts, offset_ms) {
623            prev = Cow::Owned(second.empty_like());
624            uses_custom_buckets = second.uses_custom_buckets();
625        }
626    }
627    if last.uses_custom_buckets() != uses_custom_buckets {
628        return Ok(None);
629    }
630    let mut min_schema = last.schema.min(prev.schema);
631    if is_counter {
632        for (_, current) in &points[1..points.len() - 1] {
633            min_schema = min_schema.min(current.schema);
634            if current.uses_custom_buckets() != uses_custom_buckets {
635                return Ok(None);
636            }
637        }
638    }
639    let mut result = last.copy_to_schema(min_schema)?;
640    result.sub(&prev)?;
641    if is_counter {
642        for (index, (current_ts, current)) in points.iter().enumerate().skip(1) {
643            if current.detect_counter_reset_shifted(
644                &prev,
645                points[index - 1].0,
646                *current_ts,
647                offset_ms,
648            ) {
649                result.add(&prev)?;
650            }
651            prev = Cow::Borrowed(current);
652        }
653    }
654    result.reset_hint = CounterResetHint::Gauge;
655    result.compact();
656    Ok(Some(result))
657}