Skip to main content

promql/range_eval/
function.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//! Float range-vector functions as window kernels. Each kernel follows the Prometheus function
16//! of the same name, including its floating point operation order.
17
18use crate::functions::{EdgeKind, count_edges, extremum, instant_delta, kahan_inc};
19use crate::go_sort;
20use crate::range_eval::{BatchKernel, FloatWindow, FloatWindows, RangeModifier, WindowKernel};
21
22/// A PromQL range-vector function over float and native histogram samples.
23#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
24pub enum RangeFunction {
25    Rate,
26    Increase,
27    Delta,
28    Irate,
29    Idelta,
30    AvgOverTime,
31    MinOverTime,
32    MaxOverTime,
33    SumOverTime,
34    CountOverTime,
35    LastOverTime,
36    PresentOverTime,
37    StddevOverTime,
38    StdvarOverTime,
39    /// `quantile_over_time` with a constant quantile.
40    QuantileOverTime(f64),
41    Resets,
42    Changes,
43    Deriv,
44    /// `predict_linear` with a constant horizon in seconds.
45    PredictLinear(f64),
46    /// Experimental in Prometheus: `double_exponential_smoothing` (`holt_winters`) with constant
47    /// factors in `(0, 1)`.
48    DoubleExponentialSmoothing {
49        smoothing: f64,
50        trend: f64,
51    },
52    FirstOverTime,
53    /// Experimental in Prometheus.
54    MadOverTime,
55    /// Experimental in Prometheus.
56    TsOfFirstOverTime,
57    /// Experimental in Prometheus.
58    TsOfLastOverTime,
59    /// Experimental in Prometheus.
60    TsOfMinOverTime,
61    /// Experimental in Prometheus.
62    TsOfMaxOverTime,
63}
64
65impl RangeFunction {
66    /// Whether the result drops the metric name, as Prometheus does for every range function
67    /// except `last_over_time` and `first_over_time`.
68    pub fn drops_metric_name(self) -> bool {
69        !matches!(self, Self::LastOverTime | Self::FirstOverTime)
70    }
71
72    /// The PromQL name of this function.
73    pub(crate) fn name(self) -> &'static str {
74        match self {
75            Self::Rate => "rate",
76            Self::Increase => "increase",
77            Self::Delta => "delta",
78            Self::Irate => "irate",
79            Self::Idelta => "idelta",
80            Self::AvgOverTime => "avg_over_time",
81            Self::MinOverTime => "min_over_time",
82            Self::MaxOverTime => "max_over_time",
83            Self::SumOverTime => "sum_over_time",
84            Self::CountOverTime => "count_over_time",
85            Self::LastOverTime => "last_over_time",
86            Self::PresentOverTime => "present_over_time",
87            Self::StddevOverTime => "stddev_over_time",
88            Self::StdvarOverTime => "stdvar_over_time",
89            Self::QuantileOverTime(_) => "quantile_over_time",
90            Self::Resets => "resets",
91            Self::Changes => "changes",
92            Self::Deriv => "deriv",
93            Self::PredictLinear(_) => "predict_linear",
94            Self::DoubleExponentialSmoothing { .. } => "double_exponential_smoothing",
95            Self::FirstOverTime => "first_over_time",
96            Self::MadOverTime => "mad_over_time",
97            Self::TsOfFirstOverTime => "ts_of_first_over_time",
98            Self::TsOfLastOverTime => "ts_of_last_over_time",
99            Self::TsOfMinOverTime => "ts_of_min_over_time",
100            Self::TsOfMaxOverTime => "ts_of_max_over_time",
101        }
102    }
103
104    /// The function `name` denotes when it takes no argument besides the range vector.
105    pub fn without_arguments(name: &str) -> Option<Self> {
106        [
107            Self::Rate,
108            Self::Increase,
109            Self::Delta,
110            Self::Irate,
111            Self::Idelta,
112            Self::AvgOverTime,
113            Self::MinOverTime,
114            Self::MaxOverTime,
115            Self::SumOverTime,
116            Self::CountOverTime,
117            Self::LastOverTime,
118            Self::PresentOverTime,
119            Self::StddevOverTime,
120            Self::StdvarOverTime,
121            Self::Resets,
122            Self::Changes,
123            Self::Deriv,
124            Self::FirstOverTime,
125            Self::MadOverTime,
126            Self::TsOfFirstOverTime,
127            Self::TsOfLastOverTime,
128            Self::TsOfMinOverTime,
129            Self::TsOfMaxOverTime,
130        ]
131        .into_iter()
132        .find(|function| function.name() == name)
133    }
134
135    /// Whether a window holding native histograms can answer with one; every other function
136    /// reduces it to a float.
137    pub(crate) fn yields_histograms(self) -> bool {
138        matches!(
139            self,
140            Self::Rate
141                | Self::Increase
142                | Self::Delta
143                | Self::Irate
144                | Self::Idelta
145                | Self::AvgOverTime
146                | Self::SumOverTime
147                | Self::LastOverTime
148                | Self::FirstOverTime
149        )
150    }
151
152    /// Whether the evaluator has to index counter resets for this function. Must hold for
153    /// exactly the kernels that read [`FloatWindow::counter_resets`] or
154    /// [`FloatWindows::resets_of`]; otherwise they see no resets and silently skip corrections.
155    pub(crate) fn indexes_counter_resets(self) -> bool {
156        matches!(self, Self::Rate | Self::Increase)
157    }
158
159    /// The batch form of this function, when it has one; otherwise the evaluator uses
160    /// [`Self::kernel`] per window.
161    pub(crate) fn batch_kernel(self) -> Option<BatchKernel> {
162        match self {
163            Self::Rate => Some(Box::new(extrapolated_rate_batch::<true, true>)),
164            Self::Increase => Some(Box::new(extrapolated_rate_batch::<true, false>)),
165            _ => None,
166        }
167    }
168
169    /// The kernel of this function over a series of OTLP delta increments, as the existing plan
170    /// computes it: `increase` sums the window's samples and `rate` divides that sum by the range in
171    /// seconds. `None` for a function that reads a delta series like any other.
172    pub(crate) fn delta_temporality_kernel(self, range_ms: i64) -> Option<WindowKernel> {
173        let range_seconds = range_ms as f64 / 1000.0;
174        match self {
175            Self::Rate => Some(Box::new(move |window| {
176                Some(sum(window.values) / range_seconds)
177            })),
178            Self::Increase => Some(Box::new(|window| Some(sum(window.values)))),
179            _ => None,
180        }
181    }
182
183    /// Returns the kernel computing this function over windows read with `offset_ms`.
184    pub(crate) fn kernel(self, offset_ms: i64) -> WindowKernel {
185        match self {
186            Self::Rate => Box::new(extrapolated_rate::<true, true>),
187            Self::Increase => Box::new(extrapolated_rate::<true, false>),
188            Self::Delta => Box::new(extrapolated_rate::<false, false>),
189            Self::Irate => Box::new(last_two::<true>),
190            Self::Idelta => Box::new(last_two::<false>),
191            Self::AvgOverTime => Box::new(|window| Some(avg(window.values))),
192            Self::MinOverTime => Box::new(|window| extremum(window.values.iter().copied(), true)),
193            Self::MaxOverTime => Box::new(|window| extremum(window.values.iter().copied(), false)),
194            Self::SumOverTime => Box::new(|window| Some(sum(window.values))),
195            Self::CountOverTime => Box::new(|window| Some(window.values.len() as f64)),
196            Self::LastOverTime => Box::new(|window| window.values.last().copied()),
197            Self::PresentOverTime => Box::new(|_| Some(1.0)),
198            Self::StddevOverTime => Box::new(|window| Some(variance(window.values).sqrt())),
199            Self::StdvarOverTime => Box::new(|window| Some(variance(window.values))),
200            Self::QuantileOverTime(q) => {
201                let mut scratch = Vec::new();
202                Box::new(move |window| Some(quantile(q, window.values, &mut scratch)))
203            }
204            Self::Resets => {
205                Box::new(|window| Some(count_edges(window.values, EdgeKind::Resets) as f64))
206            }
207            Self::Changes => {
208                Box::new(|window| Some(count_edges(window.values, EdgeKind::Changes) as f64))
209            }
210            Self::Deriv => Box::new(|window| {
211                (window.values.len() >= 2)
212                    .then(|| linear_regression(&window, i128::from(window.timestamps[0])).0)
213            }),
214            // Prometheus regresses the unshifted samples around the evaluation time, which on the
215            // shifted timeline is `eval_ts + offset`, taken widened: only differences are read.
216            Self::PredictLinear(duration) => Box::new(move |window| {
217                if window.values.len() < 2 {
218                    return None;
219                }
220                let intercept_time = i128::from(window.eval_ts) + i128::from(offset_ms);
221                let (slope, intercept) = linear_regression(&window, intercept_time);
222                Some(slope * duration + intercept)
223            }),
224            Self::DoubleExponentialSmoothing { smoothing, trend } => Box::new(move |window| {
225                double_exponential_smoothing(window.values, smoothing, trend)
226            }),
227            Self::FirstOverTime => Box::new(|window| window.values.first().copied()),
228            Self::MadOverTime => {
229                let (mut deviations, mut scratch) = (Vec::new(), Vec::new());
230                Box::new(move |window| {
231                    Some(median_absolute_deviation(
232                        window.values,
233                        &mut deviations,
234                        &mut scratch,
235                    ))
236                })
237            }
238            // Window timestamps are shifted by the offset; Prometheus reports the sample's own.
239            Self::TsOfFirstOverTime => {
240                Box::new(move |window| Some(seconds(window.timestamps[0] - offset_ms)))
241            }
242            // Prometheus takes the max with the histogram timestamp, 0 when there is none, so a
243            // negative timestamp reports 0.
244            Self::TsOfLastOverTime => Box::new(move |window| {
245                let last = window.timestamps[window.timestamps.len() - 1] - offset_ms;
246                Some(seconds(last.max(0)))
247            }),
248            Self::TsOfMinOverTime => Box::new(move |window| {
249                Some(seconds(timestamp_of_extremum(&window, false) - offset_ms))
250            }),
251            Self::TsOfMaxOverTime => Box::new(move |window| {
252                Some(seconds(timestamp_of_extremum(&window, true) - offset_ms))
253            }),
254        }
255    }
256}
257
258impl RangeFunction {
259    /// Returns the kernel computing this function over windows read with `modifier`, for the
260    /// functions the modifier is allowed with (`RangeEvaluator::try_new` checks that). The window
261    /// also holds the samples the modifier reads around `(eval_ts - range_ms, eval_ts]`.
262    pub(crate) fn modified_kernel(self, modifier: RangeModifier) -> WindowKernel {
263        let smoothed = matches!(modifier, RangeModifier::Smoothed { .. });
264        match self {
265            Self::Rate => Box::new(move |window| extended_rate(&window, smoothed, true, true)),
266            Self::Increase => Box::new(move |window| extended_rate(&window, smoothed, true, false)),
267            Self::Delta => Box::new(move |window| extended_rate(&window, smoothed, false, false)),
268            Self::Resets => Box::new(|window| {
269                anchored_values(&window).map(|values| count_edges(values, EdgeKind::Resets) as f64)
270            }),
271            Self::Changes => Box::new(|window| {
272                anchored_values(&window).map(|values| count_edges(values, EdgeKind::Changes) as f64)
273            }),
274            _ => unreachable!("RangeEvaluator::try_new rejects {self:?} with a range modifier"),
275        }
276    }
277}
278
279/// Go `sort.Search(n, predicate)`: the first index in `[0, n)` the predicate holds at, or `n`.
280fn search(n: usize, predicate: impl Fn(usize) -> bool) -> usize {
281    (0..n).find(|&i| predicate(i)).unwrap_or(n)
282}
283
284/// Prometheus `extendedRate`: `rate`, `increase` or `delta` over an `anchored` or `smoothed`
285/// window. The value at the window start is the last sample at or before it, or for `smoothed`
286/// the interpolation between it and the next one; the end is picked or interpolated the same way.
287/// Nothing is extrapolated.
288fn extended_rate(
289    window: &FloatWindow<'_>,
290    smoothed: bool,
291    is_counter: bool,
292    is_rate: bool,
293) -> Option<f64> {
294    let (timestamps, values) = (window.timestamps, window.values);
295    let range_start = window.eval_ts - window.range_ms;
296    let range_end = window.eval_ts;
297    let mut last = timestamps.len() - 1;
298    let first = search(last, |i| timestamps[i] > range_start).saturating_sub(1);
299    if smoothed {
300        last = search(last, |i| timestamps[i] >= range_end);
301    }
302    if timestamps[last] <= range_start || (smoothed && timestamps[first] > range_end) {
303        return None;
304    }
305    let left = if smoothed && timestamps[first] < range_start {
306        interpolate(window, first, range_start, is_counter)
307    } else {
308        values[first]
309    };
310    let right = if smoothed && last > 0 && timestamps[last] > range_end {
311        interpolate(window, last - 1, range_end, is_counter)
312    } else {
313        values[last]
314    };
315    let mut result = right - left;
316    if is_counter {
317        // Prometheus `correctForCounterResets` over the samples strictly inside the window; the
318        // boundary values already account for the resets at the edges.
319        let inner_start = first + usize::from(timestamps[first] <= range_start);
320        let inner_end = last + 1 - usize::from(timestamps[last] >= range_end);
321        let mut correction = 0.0;
322        let mut previous = left;
323        for &value in &values[inner_start..inner_end] {
324            if value < previous {
325                correction += previous;
326            }
327            previous = value;
328        }
329        if right < previous {
330            correction += previous;
331        }
332        result += correction;
333    }
334    if is_rate {
335        result /= window.range_ms as f64 / 1000.0;
336    }
337    Some(result)
338}
339
340/// Prometheus `interpolate` between the samples at `index` and `index + 1`, at `t`: a counter
341/// that reset between them restarts from zero.
342fn interpolate(window: &FloatWindow<'_>, index: usize, t: i64, is_counter: bool) -> f64 {
343    let (t1, t2) = (window.timestamps[index], window.timestamps[index + 1]);
344    let (mut y1, y2) = (window.values[index], window.values[index + 1]);
345    if is_counter && y2 < y1 {
346        y1 = 0.0;
347    }
348    y1 + (y2 - y1) * (t - t1) as f64 / (t2 - t1) as f64
349}
350
351/// Prometheus `pickFirstSampleIndices` for an `anchored` window of floats: the values from the
352/// last sample at or before the window start on, or `None` when no sample lies after the start.
353fn anchored_values<'a>(window: &FloatWindow<'a>) -> Option<&'a [f64]> {
354    let range_start = window.eval_ts - window.range_ms;
355    let after = window
356        .timestamps
357        .partition_point(|&timestamp| timestamp <= range_start);
358    if after >= window.timestamps.len() {
359        return None;
360    }
361    Some(&window.values[after.saturating_sub(1)..])
362}
363
364/// Prometheus `funcSumOverTime`.
365fn sum(values: &[f64]) -> f64 {
366    let (sum, c) = values
367        .iter()
368        .fold((0.0, 0.0), |(sum, c), &value| kahan_inc(value, sum, c));
369    sum + c
370}
371
372/// Prometheus `funcAvgOverTime`: the Kahan sum divided by the count, switching to an
373/// incremental mean once the sum would overflow.
374fn avg(values: &[f64]) -> f64 {
375    let (mut sum, mut count) = (values[0], 1.0);
376    let (mut mean, mut kahan_c) = (0.0, 0.0);
377    let mut incremental_mean = false;
378    for (i, &value) in values[1..].iter().enumerate() {
379        count = (i + 2) as f64;
380        if !incremental_mean {
381            let (new_sum, new_c) = kahan_inc(value, sum, kahan_c);
382            if !new_sum.is_infinite() {
383                (sum, kahan_c) = (new_sum, new_c);
384                continue;
385            }
386            incremental_mean = true;
387            mean = sum / (count - 1.0);
388            kahan_c /= count - 1.0;
389        }
390        let q = (count - 1.0) / count;
391        (mean, kahan_c) = kahan_inc(value / count, q * mean, q * kahan_c);
392    }
393    if incremental_mean {
394        mean + kahan_c
395    } else {
396        sum / count + kahan_c / count
397    }
398}
399
400/// Prometheus `varianceOverTime`, the population variance.
401fn variance(values: &[f64]) -> f64 {
402    let mut count = 0.0;
403    let (mut mean, mut c_mean) = (0.0, 0.0);
404    let (mut aux, mut c_aux) = (0.0, 0.0);
405    for &value in values {
406        count += 1.0;
407        let delta = value - (mean + c_mean);
408        (mean, c_mean) = kahan_inc(delta / count, mean, c_mean);
409        (aux, c_aux) = kahan_inc(delta * (value - (mean + c_mean)), aux, c_aux);
410    }
411    (aux + c_aux) / count
412}
413
414/// Prometheus `quantile`, which sorts NaN before every number.
415pub(crate) fn quantile(q: f64, values: &[f64], sorted: &mut Vec<f64>) -> f64 {
416    if q.is_nan() {
417        return f64::NAN;
418    }
419    if q < 0.0 {
420        return f64::NEG_INFINITY;
421    }
422    if q > 1.0 {
423        return f64::INFINITY;
424    }
425    sorted.clear();
426    sorted.extend_from_slice(values);
427    // `sort.Sort` with `vectorByValueHeap.Less`: NaN first, +0 and -0 tie, and which zero
428    // lands at the rank decides the sign of the result.
429    go_sort::sort_by(sorted, |a, b| a.is_nan() || a < b);
430    let n = sorted.len() as f64;
431    let rank = q * (n - 1.0);
432    let lower = rank.floor().max(0.0);
433    let upper = (n - 1.0).min(lower + 1.0);
434    let weight = rank - rank.floor();
435    sorted[lower as usize] * (1.0 - weight) + sorted[upper as usize] * weight
436}
437
438/// Prometheus `extrapolatedRate` over floats.
439fn extrapolated_rate<const IS_COUNTER: bool, const IS_RATE: bool>(
440    window: FloatWindow<'_>,
441) -> Option<f64> {
442    let FloatWindow {
443        timestamps,
444        values,
445        counter_resets,
446        eval_ts,
447        range_ms,
448    } = window;
449    let end = values.len().checked_sub(1).filter(|n| *n > 0)?;
450    extrapolated_rate_of(
451        (timestamps[0], timestamps[end]),
452        (values[0], values[end]),
453        end,
454        counter_resets.iter().map(|reset| reset.previous_value),
455        eval_ts,
456        range_ms,
457        (IS_COUNTER, IS_RATE),
458    )
459}
460
461/// The arithmetic of [`extrapolated_rate`], over a window's endpoints and the previous values of
462/// its resets. Shared by the per-window and batch forms so their results stay equal.
463fn extrapolated_rate_of(
464    (first_t, last_t): (i64, i64),
465    (first, last): (f64, f64),
466    samples_minus_one: usize,
467    resets: impl Iterator<Item = f64>,
468    eval_ts: i64,
469    range_ms: i64,
470    (is_counter, is_rate): (bool, bool),
471) -> Option<f64> {
472    let mut result = last - first;
473    if is_counter {
474        // Same additions in the same order as scanning the window for resets.
475        result = resets.fold(result, |result, previous_value| result + previous_value);
476    }
477    let zero_point = (is_counter && result > 0.0 && first >= 0.0).then(|| first / result);
478    let factor = extrapolation_factor(
479        ExtrapolationSpan {
480            // A float sample carries no start timestamp, so both intervals start at the first
481            // sample.
482            sampled_from: first_t,
483            average_from: first_t,
484            last: last_t,
485            samples_minus_one,
486        },
487        eval_ts,
488        range_ms,
489        is_counter,
490        is_rate,
491        zero_point,
492    );
493    Some(result * factor)
494}
495
496/// The batch form of [`extrapolated_rate`] over consecutive windows of one field; bit-identical
497/// to calling the per-window form once per point.
498pub(crate) fn extrapolated_rate_batch<const IS_COUNTER: bool, const IS_RATE: bool>(
499    batch: &FloatWindows<'_>,
500    out: &mut Vec<Option<f64>>,
501) {
502    out.clear();
503    out.reserve(batch.windows.len());
504    for (index, span) in batch.windows.iter().enumerate() {
505        let Some(samples_minus_one) = span.len().checked_sub(1).filter(|n| *n > 0) else {
506            out.push(None);
507            continue;
508        };
509        let (start, last) = (span.start, span.end - 1);
510        out.push(extrapolated_rate_of(
511            (batch.timestamps[start], batch.timestamps[last]),
512            (batch.values[start], batch.values[last]),
513            samples_minus_one,
514            batch
515                .resets_of(index)
516                .iter()
517                .map(|reset| reset.previous_value),
518            batch.eval_ts[index],
519            batch.range_ms,
520            (IS_COUNTER, IS_RATE),
521        ));
522    }
523}
524
525/// The span one window's extrapolation factor is measured over. A float window starts both
526/// intervals at its first sample; a native histogram counter with a `start_timestamp` inside the
527/// window starts the sampled interval at that synthetic zero instead.
528pub(super) struct ExtrapolationSpan {
529    /// The first sample, or a native histogram's synthetic zero.
530    pub sampled_from: i64,
531    /// The first sample, always.
532    pub average_from: i64,
533    /// The last sample.
534    pub last: i64,
535    /// Intervals between samples, i.e. the sample count minus one; `0` when the window has a
536    /// single sample and so no average interval to measure.
537    pub samples_minus_one: usize,
538}
539
540/// The factor `extrapolatedRate` scales the sampled increase by, for floats and native
541/// histograms alike. `zero_point` is the first value over the increase, given only when a counter
542/// is extrapolated to zero; `0` puts the zero point at `span.sampled_from`, as a synthetic zero
543/// does. A zero sampled interval answers `1.0` (`1 / range` for a rate).
544pub(super) fn extrapolation_factor(
545    span: ExtrapolationSpan,
546    eval_ts: i64,
547    range_ms: i64,
548    is_counter: bool,
549    is_rate: bool,
550    zero_point: Option<f64>,
551) -> f64 {
552    let ExtrapolationSpan {
553        sampled_from,
554        average_from,
555        last,
556        samples_minus_one,
557    } = span;
558    // Wrapping i64 arithmetic matches Go's int64 and avoids the slow i128-to-f64 conversion.
559    let range_start = eval_ts.wrapping_sub(range_ms);
560    let mut duration_to_start = average_from.wrapping_sub(range_start) as f64 / 1000.0;
561    let mut duration_to_end = eval_ts.wrapping_sub(last) as f64 / 1000.0;
562    let sampled_interval = last.wrapping_sub(sampled_from) as f64 / 1000.0;
563    let average_interval = if samples_minus_one == 0 {
564        0.0
565    } else {
566        last.wrapping_sub(average_from) as f64 / 1000.0 / samples_minus_one as f64
567    };
568    let threshold = average_interval * 1.1;
569    if duration_to_start >= threshold {
570        duration_to_start = average_interval / 2.0;
571    }
572    if is_counter {
573        let mut duration_to_zero = duration_to_start;
574        if let Some(zero_point) = zero_point {
575            duration_to_zero = sampled_interval * zero_point;
576        }
577        if duration_to_zero < duration_to_start {
578            duration_to_start = duration_to_zero;
579        }
580    }
581    if duration_to_end >= threshold {
582        duration_to_end = average_interval / 2.0;
583    }
584    let mut factor = 1.0;
585    if sampled_interval != 0.0 {
586        factor = (sampled_interval + duration_to_start + duration_to_end) / sampled_interval;
587    }
588    if is_rate {
589        factor /= range_ms as f64 / 1000.0;
590    }
591    factor
592}
593
594fn last_two<const IS_RATE: bool>(window: FloatWindow<'_>) -> Option<f64> {
595    let [.., prev_ts, last_ts] = window.timestamps else {
596        return None;
597    };
598    let [.., prev, last] = window.values else {
599        return None;
600    };
601    instant_delta::<IS_RATE>((*prev_ts, *prev), (*last_ts, *last))
602}
603
604/// Prometheus `linearRegression`: `(slope, intercept)` with `x` in seconds from
605/// `intercept_time`. Needs at least two samples.
606fn linear_regression(window: &FloatWindow<'_>, intercept_time: i128) -> (f64, f64) {
607    let init_y = window.values[0];
608    let mut const_y = true;
609    let mut n = 0.0;
610    let (mut sum_x, mut c_x) = (0.0, 0.0);
611    let (mut sum_y, mut c_y) = (0.0, 0.0);
612    let (mut sum_xy, mut c_xy) = (0.0, 0.0);
613    let (mut sum_x2, mut c_x2) = (0.0, 0.0);
614    for (i, (&t, &y)) in window.timestamps.iter().zip(window.values).enumerate() {
615        if const_y && i > 0 && y != init_y {
616            const_y = false;
617        }
618        n += 1.0;
619        let x = (i128::from(t) - intercept_time) as f64 / 1e3;
620        (sum_x, c_x) = kahan_inc(x, sum_x, c_x);
621        (sum_y, c_y) = kahan_inc(y, sum_y, c_y);
622        (sum_xy, c_xy) = kahan_inc(x * y, sum_xy, c_xy);
623        (sum_x2, c_x2) = kahan_inc(x * x, sum_x2, c_x2);
624    }
625    if const_y {
626        if init_y.is_infinite() {
627            return (f64::NAN, f64::NAN);
628        }
629        return (0.0, init_y);
630    }
631    sum_x += c_x;
632    sum_y += c_y;
633    sum_xy += c_xy;
634    sum_x2 += c_x2;
635    let cov_xy = sum_xy - sum_x * sum_y / n;
636    let var_x = sum_x2 - sum_x * sum_x / n;
637    let slope = cov_xy / var_x;
638    let intercept = sum_y / n - slope * sum_x / n;
639    (slope, intercept)
640}
641
642/// Prometheus `funcDoubleExponentialSmoothing`; `RangeEvaluator` checks the factors.
643fn double_exponential_smoothing(values: &[f64], sf: f64, tf: f64) -> Option<f64> {
644    if values.len() < 2 {
645        return None;
646    }
647    let (mut s0, mut s1) = (0.0, values[0]);
648    let mut b = values[1] - values[0];
649    for (i, &value) in values.iter().enumerate().skip(1) {
650        let x = sf * value;
651        b = if i == 1 {
652            b
653        } else {
654            tf * (s1 - s0) + (1.0 - tf) * b
655        };
656        let y = (1.0 - sf) * (s1 + b);
657        (s0, s1) = (s1, x + y);
658    }
659    Some(s1)
660}
661
662pub(super) fn seconds(timestamp_ms: i64) -> f64 {
663    timestamp_ms as f64 / 1000.0
664}
665
666/// Prometheus `compareOverTime` returning the timestamp: the last sample holding the maximum
667/// (or minimum), where a NaN so far is replaced by any later sample.
668fn timestamp_of_extremum(window: &FloatWindow<'_>, max: bool) -> i64 {
669    let (mut best, mut timestamp) = (window.values[0], window.timestamps[0]);
670    for (&value, &ts) in window.values.iter().zip(window.timestamps) {
671        let replace = if max { value >= best } else { value <= best };
672        if replace || best.is_nan() {
673            (best, timestamp) = (value, ts);
674        }
675    }
676    timestamp
677}
678
679/// Prometheus `funcMadOverTime`: the median of the absolute deviations from the median; NaN
680/// when any sample is NaN.
681fn median_absolute_deviation(
682    values: &[f64],
683    deviations: &mut Vec<f64>,
684    sorted: &mut Vec<f64>,
685) -> f64 {
686    if values.iter().any(|value| value.is_nan()) {
687        return f64::NAN;
688    }
689    let median = quantile(0.5, values, sorted);
690    deviations.clear();
691    deviations.extend(values.iter().map(|value| (value - median).abs()));
692    quantile(0.5, deviations, sorted)
693}
694
695impl PartialEq for RangeFunction {
696    fn eq(&self, o: &Self) -> bool {
697        match (self, o) {
698            (Self::QuantileOverTime(a), Self::QuantileOverTime(b))
699            | (Self::PredictLinear(a), Self::PredictLinear(b)) => a.to_bits() == b.to_bits(),
700            (
701                Self::DoubleExponentialSmoothing {
702                    smoothing: a,
703                    trend: b,
704                },
705                Self::DoubleExponentialSmoothing {
706                    smoothing: c,
707                    trend: d,
708                },
709            ) => a.to_bits() == c.to_bits() && b.to_bits() == d.to_bits(),
710            _ => std::mem::discriminant(self) == std::mem::discriminant(o),
711        }
712    }
713}
714impl Eq for RangeFunction {}
715impl std::hash::Hash for RangeFunction {
716    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
717        std::mem::discriminant(self).hash(h);
718        match self {
719            Self::QuantileOverTime(x) | Self::PredictLinear(x) => x.to_bits().hash(h),
720            Self::DoubleExponentialSmoothing { smoothing, trend } => {
721                smoothing.to_bits().hash(h);
722                trend.to_bits().hash(h)
723            }
724            _ => (),
725        }
726    }
727}
728
729#[cfg(test)]
730mod tests {
731    use super::{ExtrapolationSpan, extrapolation_factor};
732
733    #[derive(Clone, Copy, Debug)]
734    struct Window {
735        sampled_from: i64,
736        average_from: i64,
737        last: i64,
738        samples_minus_one: usize,
739        eval_ts: i64,
740        range_ms: i64,
741        is_counter: bool,
742        is_rate: bool,
743        zero_point: Option<f64>,
744    }
745
746    impl Window {
747        /// The float route ignores `sampled_from`: it has no start timestamp.
748        fn as_float(self) -> f64 {
749            extrapolation_factor(
750                ExtrapolationSpan {
751                    sampled_from: self.average_from,
752                    average_from: self.average_from,
753                    last: self.last,
754                    samples_minus_one: self.samples_minus_one,
755                },
756                self.eval_ts,
757                self.range_ms,
758                self.is_counter,
759                self.is_rate,
760                self.zero_point,
761            )
762        }
763
764        fn as_histogram(self) -> f64 {
765            extrapolation_factor(
766                ExtrapolationSpan {
767                    sampled_from: self.sampled_from,
768                    average_from: self.average_from,
769                    last: self.last,
770                    samples_minus_one: self.samples_minus_one,
771                },
772                self.eval_ts,
773                self.range_ms,
774                self.is_counter,
775                self.is_rate,
776                self.zero_point,
777            )
778        }
779    }
780
781    #[test]
782    fn both_routes_compute_one_extrapolation_factor() {
783        let windows = [
784            Window {
785                sampled_from: 2_000,
786                average_from: 2_000,
787                last: 5_000,
788                samples_minus_one: 1,
789                eval_ts: 6_500,
790                range_ms: 6_000,
791                is_counter: true,
792                is_rate: false,
793                zero_point: None,
794            },
795            Window {
796                sampled_from: 2_000,
797                average_from: 2_000,
798                last: 5_000,
799                samples_minus_one: 2,
800                eval_ts: 6_500,
801                range_ms: 6_000,
802                is_counter: true,
803                is_rate: true,
804                zero_point: None,
805            },
806            Window {
807                sampled_from: 2_000,
808                average_from: 2_000,
809                last: 5_000,
810                samples_minus_one: 2,
811                eval_ts: 6_500,
812                range_ms: 6_000,
813                is_counter: false,
814                is_rate: false,
815                zero_point: None,
816            },
817            // The last sample further in than the average interval allows, so both ends fall back
818            // to half of it.
819            Window {
820                sampled_from: 4_000,
821                average_from: 4_000,
822                last: 4_500,
823                samples_minus_one: 1,
824                eval_ts: 6_500,
825                range_ms: 6_000,
826                is_counter: true,
827                is_rate: true,
828                zero_point: None,
829            },
830            // A single sample holds no average interval to measure.
831            Window {
832                sampled_from: 5_000,
833                average_from: 5_000,
834                last: 5_000,
835                samples_minus_one: 0,
836                eval_ts: 6_500,
837                range_ms: 6_000,
838                is_counter: true,
839                is_rate: false,
840                zero_point: None,
841            },
842        ];
843        for window in windows {
844            for zero_point in [None, Some(0.0), Some(0.25), Some(1.5)] {
845                let window = Window {
846                    zero_point,
847                    ..window
848                };
849                assert_eq!(
850                    window.as_float().to_bits(),
851                    window.as_histogram().to_bits(),
852                    "{window:?}"
853                );
854            }
855        }
856
857        // Synthetic zero at 2000ms, samples at 2500ms and 4500ms: the end falls back to half the
858        // 2000ms average interval and the zero point takes the start to 0, so the histogram route
859        // answers (2500 + 0 + 1000) / 2500 = 1.4 and the float route (2000 + 0 + 1000) / 2000.
860        let two_anchor = Window {
861            sampled_from: 2_000,
862            average_from: 2_500,
863            last: 4_500,
864            samples_minus_one: 1,
865            eval_ts: 7_000,
866            range_ms: 6_000,
867            is_counter: true,
868            is_rate: false,
869            zero_point: Some(0.0),
870        };
871        assert_eq!(two_anchor.as_histogram().to_bits(), 1.4f64.to_bits());
872        assert_eq!(two_anchor.as_float().to_bits(), 1.5f64.to_bits());
873        // Each swapped anchor gives a distinct answer: 1.5 with the average anchor read for the
874        // sampled one, 2.0 the other way round (the end stays inside the wider threshold).
875        assert_eq!(
876            Window {
877                sampled_from: two_anchor.average_from,
878                ..two_anchor
879            }
880            .as_histogram()
881            .to_bits(),
882            1.5f64.to_bits()
883        );
884        assert_eq!(
885            Window {
886                average_from: two_anchor.sampled_from,
887                ..two_anchor
888            }
889            .as_histogram()
890            .to_bits(),
891            2.0f64.to_bits()
892        );
893    }
894
895    #[test]
896    fn a_synthetic_zero_moves_only_the_sampled_anchor() {
897        // Zero at 1000ms, samples at 2000ms and 3000ms: both ends fall back to half the 1000ms
898        // average interval and the zero point takes the start to 0: (2000 + 0 + 500) / 2000.
899        // Averaging from the zero instead gives (2000 + 0 + 1500) / 2000 = 1.75.
900        let window = Window {
901            sampled_from: 1_000,
902            average_from: 2_000,
903            last: 3_000,
904            samples_minus_one: 1,
905            eval_ts: 4_500,
906            range_ms: 4_000,
907            is_counter: true,
908            is_rate: false,
909            zero_point: Some(0.0),
910        };
911        assert_eq!(window.as_histogram().to_bits(), 1.25f64.to_bits());
912        assert_eq!(
913            Window {
914                is_rate: true,
915                ..window
916            }
917            .as_histogram()
918            .to_bits(),
919            (1.25f64 / 4.0).to_bits()
920        );
921        assert_eq!(
922            Window {
923                average_from: 1_000,
924                ..window
925            }
926            .as_histogram()
927            .to_bits(),
928            1.75f64.to_bits()
929        );
930        assert_eq!(window.as_float().to_bits(), 1.5f64.to_bits());
931
932        // One real sample leaves no average interval: the factor is the identity.
933        let single = Window {
934            sampled_from: 1_000,
935            average_from: 2_000,
936            last: 2_000,
937            samples_minus_one: 0,
938            ..window
939        };
940        assert_eq!(single.as_histogram().to_bits(), 1.0f64.to_bits());
941        assert_eq!(
942            Window {
943                is_rate: true,
944                ..single
945            }
946            .as_histogram()
947            .to_bits(),
948            (1.0f64 / 4.0).to_bits()
949        );
950    }
951}