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