Skip to main content

promql/functions/
aggr_over_time.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
15use std::collections::VecDeque;
16use std::sync::Arc;
17
18use common_macro::range_fn;
19use datafusion::arrow::array::{Float64Array, TimestampMillisecondArray};
20use datafusion::common::DataFusionError;
21use datafusion::logical_expr::{ScalarUDF, Volatility};
22use datafusion::physical_plan::ColumnarValue;
23use datatypes::arrow::array::Array;
24use datatypes::arrow::compute;
25use datatypes::arrow::datatypes::{DataType, TimeUnit};
26
27use crate::functions::{compensated_sum_inc, extract_array, extract_range_dict};
28use crate::range_array::{RangeArray, unpack};
29
30#[derive(Clone, Copy)]
31enum PresenceEvaluator {
32    Count,
33    Last,
34    Absent,
35    Present,
36}
37
38fn count_over_time_evaluator(
39    input: &[ColumnarValue],
40    name: &str,
41) -> Result<ColumnarValue, DataFusionError> {
42    evaluate_presence(input, name, PresenceEvaluator::Count)
43}
44
45fn last_over_time_evaluator(
46    input: &[ColumnarValue],
47    name: &str,
48) -> Result<ColumnarValue, DataFusionError> {
49    evaluate_presence(input, name, PresenceEvaluator::Last)
50}
51
52fn absent_over_time_evaluator(
53    input: &[ColumnarValue],
54    name: &str,
55) -> Result<ColumnarValue, DataFusionError> {
56    evaluate_presence(input, name, PresenceEvaluator::Absent)
57}
58
59fn present_over_time_evaluator(
60    input: &[ColumnarValue],
61    name: &str,
62) -> Result<ColumnarValue, DataFusionError> {
63    evaluate_presence(input, name, PresenceEvaluator::Present)
64}
65
66fn evaluate_presence(
67    input: &[ColumnarValue],
68    name: &str,
69    operation: PresenceEvaluator,
70) -> Result<ColumnarValue, DataFusionError> {
71    assert_eq!(input.len(), 2);
72
73    let timestamp_ranges = RangeArray::try_new(extract_array(&input[0])?.to_data().into())?;
74    let value_ranges = RangeArray::try_new(extract_array(&input[1])?.to_data().into())?;
75    let len = timestamp_ranges.len();
76    if len != value_ranges.len() {
77        return Err(DataFusionError::Execution(format!(
78            "RangeArray have different lengths in PromQL function {name}: array1={len}, array2={}",
79            value_ranges.len()
80        )));
81    }
82
83    if timestamp_ranges.is_empty() {
84        return Ok(ColumnarValue::Array(Arc::new(Float64Array::from_iter(
85            std::iter::empty::<Option<f64>>(),
86        ))));
87    }
88
89    // The generic range-function wrapper downcasts both arrays for each window.
90    // Do it once after retaining its zero-window behavior above.
91    assert!(
92        timestamp_ranges
93            .values()
94            .as_any()
95            .is::<TimestampMillisecondArray>()
96    );
97    let values = value_ranges
98        .values()
99        .as_any()
100        .downcast_ref::<Float64Array>()
101        .unwrap();
102    let evaluator: fn(&Float64Array, usize, usize) -> Option<f64> = if values.null_count() == 0 {
103        match operation {
104            PresenceEvaluator::Count => |_, _, length| (length != 0).then_some(length as f64),
105            PresenceEvaluator::Last => {
106                |values, offset, length| (length != 0).then(|| values.value(offset + length - 1))
107            }
108            PresenceEvaluator::Absent => |_, _, length| (length == 0).then_some(1.0),
109            PresenceEvaluator::Present => |_, _, length| (length != 0).then_some(1.0),
110        }
111    } else {
112        match operation {
113            PresenceEvaluator::Count => |values, offset, length| {
114                let count = (offset..offset + length)
115                    .filter(|&index| values.is_valid(index))
116                    .count();
117                (count != 0).then_some(count as f64)
118            },
119            PresenceEvaluator::Last => |values, offset, length| {
120                (offset..offset + length)
121                    .rev()
122                    .find(|&index| values.is_valid(index))
123                    .map(|index| values.value(index))
124            },
125            PresenceEvaluator::Absent => |values, offset, length| {
126                (!(offset..offset + length).any(|index| values.is_valid(index))).then_some(1.0)
127            },
128            PresenceEvaluator::Present => |values, offset, length| {
129                (offset..offset + length)
130                    .any(|index| values.is_valid(index))
131                    .then_some(1.0)
132            },
133        }
134    };
135
136    let mut result = Vec::with_capacity(len);
137    for index in 0..len {
138        let (_, timestamp_length) = timestamp_ranges.get_offset_length(index).unwrap();
139        let (value_offset, value_length) = value_ranges.get_offset_length(index).unwrap();
140        if timestamp_length != value_length {
141            return Err(DataFusionError::Execution(format!(
142                "RangeArray's element {index} have different lengths in PromQL function {name}: array1={timestamp_length}, array2={value_length}"
143            )));
144        }
145        result.push(evaluator(values, value_offset, value_length));
146    }
147
148    Ok(ColumnarValue::Array(Arc::new(Float64Array::from_iter(
149        result,
150    ))))
151}
152
153/// The average value of all points in the specified interval.
154#[range_fn(
155    name = AvgOverTime,
156    ret = Float64Array,
157    display_name = prom_avg_over_time
158)]
159pub fn avg_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
160    // `sum` already skips null slots and yields `None` for an all-null window, so only the
161    // divisor needs to count samples instead of slots.
162    let sample_count = values.len() - values.null_count();
163    compute::sum(values).map(|result| result / sample_count as f64)
164}
165
166/// The minimum value of all points in the specified interval.
167#[derive(Debug)]
168pub struct MinOverTime {}
169
170impl MinOverTime {
171    pub const fn name() -> &'static str {
172        "prom_min_over_time"
173    }
174
175    pub fn scalar_udf() -> ScalarUDF {
176        datafusion_expr::create_udf(
177            Self::name(),
178            Self::input_type(),
179            Self::return_type(),
180            Volatility::Volatile,
181            Arc::new(Self::calc) as _,
182        )
183    }
184
185    fn input_type() -> Vec<DataType> {
186        min_max_input_type()
187    }
188
189    fn return_type() -> DataType {
190        Float64Array::new_null(0).data_type().clone()
191    }
192
193    fn calc(input: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
194        min_max_over_time_batch(input, true, Self::name())
195    }
196}
197
198/// The maximum value of all points in the specified interval.
199#[derive(Debug)]
200pub struct MaxOverTime {}
201
202impl MaxOverTime {
203    pub const fn name() -> &'static str {
204        "prom_max_over_time"
205    }
206
207    pub fn scalar_udf() -> ScalarUDF {
208        datafusion_expr::create_udf(
209            Self::name(),
210            Self::input_type(),
211            Self::return_type(),
212            Volatility::Volatile,
213            Arc::new(Self::calc) as _,
214        )
215    }
216
217    fn input_type() -> Vec<DataType> {
218        min_max_input_type()
219    }
220
221    fn return_type() -> DataType {
222        Float64Array::new_null(0).data_type().clone()
223    }
224
225    fn calc(input: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
226        min_max_over_time_batch(input, false, Self::name())
227    }
228}
229
230fn min_max_input_type() -> Vec<DataType> {
231    vec![
232        RangeArray::convert_data_type(DataType::Timestamp(TimeUnit::Millisecond, None)),
233        RangeArray::convert_data_type(DataType::Float64),
234    ]
235}
236
237/// Batches with fewer windows than this have too little repeated work to reclaim.
238const MIN_SLIDING_WINDOWS: usize = 4;
239/// Below this average window length the per-sample bookkeeping is comparable to the
240/// scan it would replace.
241const MIN_SLIDING_WINDOW_LENGTH: u64 = 32;
242/// Reuse is taken only when a step advances at most this fraction of the window.
243const MAX_SLIDING_STEP_FRACTION: u64 = 4;
244
245/// Whether reusing candidates across windows is expected to beat rescanning each one.
246///
247/// Reuse pays off in proportion to how much consecutive windows overlap, and loses to
248/// a plain scan on wide windows that barely overlap: maintaining the deque then costs
249/// more than the rescan it replaces.
250///
251/// The shape is read from the whole batch rather than from its leading windows.
252/// `RangeManipulate` holds the window duration and the evaluation step fixed, but the
253/// sample counts still vary: a series that starts inside the query range gets a first
254/// window covering roughly one step. Averages survive that; the first two windows do not.
255///
256/// A wrong answer costs time, not correctness — both evaluators return the same bits.
257fn reuses_candidates(window_keys: &[i64]) -> bool {
258    if window_keys.len() < MIN_SLIDING_WINDOWS {
259        return false;
260    }
261
262    let windows = window_keys.len() as u64;
263    let mut total_length = 0u64;
264    let mut lowest_offset = u32::MAX;
265    let mut highest_offset = 0u32;
266    for &key in window_keys {
267        let (offset, length) = unpack(key);
268        // `RangeManipulate` emits a window covering no sample as `(0, 0)`, including
269        // the trailing one a query gets when its last evaluation lands exactly one
270        // window past the last sample. Its offset says nothing about the batch.
271        if length == 0 {
272            continue;
273        }
274        total_length += u64::from(length);
275        lowest_offset = lowest_offset.min(offset);
276        highest_offset = highest_offset.max(offset);
277    }
278    // What reuse skips re-reading: the distance the left bound travels over the batch.
279    let total_advance = u64::from(highest_offset.saturating_sub(lowest_offset));
280
281    // `total_length / windows >= MIN_SLIDING_WINDOW_LENGTH` and
282    // `total_advance / (windows - 1) <= (total_length / windows) / MAX_SLIDING_STEP_FRACTION`,
283    // cross-multiplied to keep the averages exact. Empty windows stay in the window
284    // count, which only makes both conditions stricter.
285    total_length >= windows * MIN_SLIDING_WINDOW_LENGTH
286        && total_advance * MAX_SLIDING_STEP_FRACTION * windows <= total_length * (windows - 1)
287}
288
289fn is_better(value: f64, current: f64, is_min: bool) -> bool {
290    if is_min {
291        value < current
292    } else {
293        value > current
294    }
295}
296
297fn min_max_over_time_batch(
298    input: &[ColumnarValue],
299    is_min: bool,
300    func_name: &str,
301) -> Result<ColumnarValue, DataFusionError> {
302    if input.len() != 2 {
303        return Err(DataFusionError::Execution(format!(
304            "{func_name}: expected 2 inputs, found {}",
305            input.len()
306        )));
307    }
308
309    let timestamps = extract_range_dict(
310        &input[0],
311        func_name,
312        "timestamp range vector",
313        &DataType::Timestamp(TimeUnit::Millisecond, None),
314    )?;
315    let values = extract_range_dict(
316        &input[1],
317        func_name,
318        "value range vector",
319        &DataType::Float64,
320    )?;
321
322    let timestamp_keys = timestamps.keys().values();
323    let value_keys = values.keys().values();
324    if timestamp_keys.len() != value_keys.len() {
325        return Err(DataFusionError::Execution(format!(
326            "{func_name}: timestamp and value ranges should have the same number of windows, found {} and {}",
327            timestamp_keys.len(),
328            value_keys.len()
329        )));
330    }
331
332    let values = values
333        .values()
334        .as_any()
335        .downcast_ref::<Float64Array>()
336        .ok_or_else(|| {
337            DataFusionError::Execution(format!(
338                "{func_name}: expect value range vector values of type Float64"
339            ))
340        })?;
341    let mut sliding = reuses_candidates(value_keys).then(|| SlidingExtrema::new(is_min));
342    let mut result = Vec::with_capacity(value_keys.len());
343
344    for index in 0..value_keys.len() {
345        let (_, timestamp_length) = unpack(timestamp_keys[index]);
346        let (value_offset, value_length) = unpack(value_keys[index]);
347        if timestamp_length != value_length {
348            return Err(DataFusionError::Execution(format!(
349                "{func_name}: timestamp and value ranges have different lengths at window {index}: {timestamp_length} and {value_length}"
350            )));
351        }
352
353        let start = value_offset as usize;
354        let end = start + value_length as usize;
355        result.push(match sliding.as_mut() {
356            Some(sliding) => sliding.evaluate(values, start, end),
357            None => scan_extremum(values, start, end, is_min),
358        });
359    }
360
361    Ok(ColumnarValue::Array(Arc::new(Float64Array::from_iter(
362        result,
363    ))))
364}
365
366/// Reuses extrema candidates across windows whose bounds do not retreat.
367struct SlidingExtrema {
368    is_min: bool,
369    /// Indices of the samples that can still become the extremum, in arrival order.
370    /// A strictly better sample evicts the ones queued before it, so the front is the
371    /// extremum of the current window and tied values keep their arrival order — and
372    /// with it the sign of tied zeros.
373    candidates: VecDeque<usize>,
374    /// Backs the all-NaN window, which keeps the last NaN of the window.
375    latest_nan: Option<usize>,
376    previous_window: Option<(usize, usize)>,
377}
378
379impl SlidingExtrema {
380    fn new(is_min: bool) -> Self {
381        Self {
382            is_min,
383            candidates: VecDeque::new(),
384            latest_nan: None,
385            previous_window: None,
386        }
387    }
388
389    fn evaluate(&mut self, values: &Float64Array, start: usize, end: usize) -> Option<f64> {
390        let append_start = match self.previous_window {
391            Some((previous_start, previous_end))
392                if start >= previous_start && end >= previous_end =>
393            {
394                while self.candidates.front().is_some_and(|&index| index < start) {
395                    self.candidates.pop_front();
396                }
397                if self.latest_nan.is_some_and(|index| index < start) {
398                    self.latest_nan = None;
399                }
400                // Samples between two disjoint windows belong to neither, and later
401                // windows only move right, so skipping them keeps the state exact.
402                previous_end.max(start)
403            }
404            // A retreating bound can bring back samples that are no longer tracked.
405            Some(_) | None => {
406                self.candidates.clear();
407                self.latest_nan = None;
408                start
409            }
410        };
411        self.append(values, append_start, end);
412        self.previous_window = Some((start, end));
413
414        self.candidates
415            .front()
416            .or(self.latest_nan.as_ref())
417            .map(|&index| values.value(index))
418    }
419
420    fn append(&mut self, values: &Float64Array, start: usize, end: usize) {
421        for index in start..end {
422            if values.is_null(index) {
423                continue;
424            }
425
426            let value = values.value(index);
427            if value.is_nan() {
428                // Keep the latest payload while no non-NaN value is in the window.
429                self.latest_nan = Some(index);
430                continue;
431            }
432
433            while let Some(&tail_index) = self.candidates.back() {
434                if !is_better(value, values.value(tail_index), self.is_min) {
435                    break;
436                }
437                self.candidates.pop_back();
438            }
439            self.candidates.push_back(index);
440        }
441    }
442}
443
444/// Folds one window on its own, the way the per-window scan used to.
445fn scan_extremum(values: &Float64Array, start: usize, end: usize, is_min: bool) -> Option<f64> {
446    extremum(
447        (start..end)
448            .filter(|&index| values.is_valid(index))
449            .map(|index| values.value(index)),
450        is_min,
451    )
452}
453
454/// The minimum (`is_min`) or maximum of `values`, `None` when there are none.
455pub(crate) fn extremum(values: impl IntoIterator<Item = f64>, is_min: bool) -> Option<f64> {
456    let mut extremum: Option<f64> = None;
457    for value in values {
458        let replace = match extremum {
459            None => true,
460            // A NaN only holds the slot until any other sample arrives.
461            Some(current) => current.is_nan() || is_better(value, current, is_min),
462        };
463        if replace {
464            extremum = Some(value);
465        }
466    }
467    extremum
468}
469
470#[cfg(test)]
471fn min_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
472    let mut valid_values = values.iter().flatten();
473    let mut min = valid_values.next()?;
474    for value in valid_values {
475        if value < min || min.is_nan() {
476            min = value;
477        }
478    }
479    Some(min)
480}
481
482#[cfg(test)]
483fn max_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
484    let mut valid_values = values.iter().flatten();
485    let mut max = valid_values.next()?;
486    for value in valid_values {
487        if value > max || max.is_nan() {
488            max = value;
489        }
490    }
491    Some(max)
492}
493
494/// The sum of all values in the specified interval.
495#[range_fn(
496    name = SumOverTime,
497    ret = Float64Array,
498    display_name = prom_sum_over_time
499)]
500pub fn sum_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
501    compute::sum(values)
502}
503
504/// The count of all values in the specified interval.
505#[range_fn(
506    name = CountOverTime,
507    ret = Float64Array,
508    display_name = prom_count_over_time,
509    evaluator = count_over_time_evaluator
510)]
511pub fn count_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
512    let count = values.iter().flatten().count();
513    (count != 0).then_some(count as f64)
514}
515
516/// The most recent point value in specified interval.
517#[range_fn(
518    name = LastOverTime,
519    ret = Float64Array,
520    display_name = prom_last_over_time,
521    evaluator = last_over_time_evaluator
522)]
523pub fn last_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
524    values.iter().flatten().last()
525}
526
527/// absent_over_time returns an empty vector if the range vector passed to it has any
528/// elements (floats or native histograms) and a 1-element vector with the value 1 if
529/// the range vector passed to it has no elements.
530#[range_fn(
531    name = AbsentOverTime,
532    ret = Float64Array,
533    display_name = prom_absent_over_time,
534    evaluator = absent_over_time_evaluator
535)]
536pub fn absent_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
537    values.iter().flatten().next().is_none().then_some(1.0)
538}
539
540/// the value 1 for any series in the specified interval.
541#[range_fn(
542    name = PresentOverTime,
543    ret = Float64Array,
544    display_name = prom_present_over_time,
545    evaluator = present_over_time_evaluator
546)]
547pub fn present_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
548    values.iter().flatten().next().is_some().then_some(1.0)
549}
550
551/// the population standard variance of the values in the specified interval.
552/// DataFusion's implementation:
553/// <https://github.com/apache/arrow-datafusion/blob/292eb954fc0bad3a1febc597233ba26cb60bda3e/datafusion/physical-expr/src/aggregate/variance.rs#L224-#L241>
554#[range_fn(
555    name = StdvarOverTime,
556    ret = Float64Array,
557    display_name = prom_stdvar_over_time
558)]
559pub fn stdvar_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
560    let mut count = 0;
561    let mut mean: f64 = 0.0;
562    let mut result: f64 = 0.0;
563    for value in values.iter().flatten() {
564        let new_count = count + 1;
565        let delta1 = value - mean;
566        let new_mean = delta1 / new_count as f64 + mean;
567        let delta2 = value - new_mean;
568        let new_result = result + delta1 * delta2;
569
570        count = new_count;
571        mean = new_mean;
572        result = new_result;
573    }
574    (count > 0).then(|| result / count as f64)
575}
576
577/// the population standard deviation of the values in the specified interval.
578/// Prometheus's implementation: <https://github.com/prometheus/prometheus/blob/f55ab2217984770aa1eecd0f2d5f54580029b1c0/promql/functions.go#L556-L569>
579#[range_fn(
580    name = StddevOverTime,
581    ret = Float64Array,
582    display_name = prom_stddev_over_time
583)]
584pub fn stddev_over_time(_: &TimestampMillisecondArray, values: &Float64Array) -> Option<f64> {
585    let mut count = 0.0;
586    let mut mean = 0.0;
587    let mut comp_mean = 0.0;
588    let mut deviations_sum_sq = 0.0;
589    let mut comp_deviations_sum_sq = 0.0;
590    for current_value in values.iter().flatten() {
591        count += 1.0;
592        let delta = current_value - (mean + comp_mean);
593        let (new_mean, new_comp_mean) = compensated_sum_inc(delta / count, mean, comp_mean);
594        mean = new_mean;
595        comp_mean = new_comp_mean;
596        let (new_deviations_sum_sq, new_comp_deviations_sum_sq) = compensated_sum_inc(
597            delta * (current_value - (mean + comp_mean)),
598            deviations_sum_sq,
599            comp_deviations_sum_sq,
600        );
601        deviations_sum_sq = new_deviations_sum_sq;
602        comp_deviations_sum_sq = new_comp_deviations_sum_sq;
603    }
604    (count > 0.0).then(|| ((deviations_sum_sq + comp_deviations_sum_sq) / count).sqrt())
605}
606
607#[cfg(test)]
608mod test {
609    use datafusion::arrow::buffer::NullBuffer;
610
611    use super::*;
612    use crate::functions::test_util::{invoke_range_udf, simple_range_udf_runner};
613
614    fn assert_option_bits(actual: &[Option<f64>], expected: &[Option<f64>]) {
615        assert_eq!(actual.len(), expected.len());
616        for (actual, expected) in actual.iter().zip(expected) {
617            match (actual, expected) {
618                (Some(actual), Some(expected)) => assert_eq!(actual.to_bits(), expected.to_bits()),
619                (None, None) => {}
620                (actual, expected) => panic!("expected {expected:?}, got {actual:?}"),
621            }
622        }
623    }
624
625    fn old_min_max_over_windows(
626        values: &Float64Array,
627        ranges: &[(u32, u32)],
628        is_min: bool,
629    ) -> Vec<Option<f64>> {
630        ranges
631            .iter()
632            .map(|&(offset, length)| {
633                let values = values.slice(offset as usize, length as usize);
634                let values = values.as_any().downcast_ref::<Float64Array>().unwrap();
635                let timestamps = TimestampMillisecondArray::new_null(values.len());
636                if is_min {
637                    min_over_time(&timestamps, values)
638                } else {
639                    max_over_time(&timestamps, values)
640                }
641            })
642            .collect()
643    }
644
645    fn run_min_max_udf(
646        udf: ScalarUDF,
647        timestamps: RangeArray,
648        values: RangeArray,
649    ) -> Vec<Option<f64>> {
650        let result = invoke_range_udf(udf, timestamps, values).unwrap();
651        extract_array(&result)
652            .unwrap()
653            .as_any()
654            .downcast_ref::<Float64Array>()
655            .unwrap()
656            .iter()
657            .collect()
658    }
659
660    fn slice_range_array(range: RangeArray, offset: usize, length: usize) -> RangeArray {
661        RangeArray::try_new(range.into_dict().slice(offset, length).to_data().into()).unwrap()
662    }
663
664    fn sliced_float_values(values: Vec<Option<f64>>) -> Float64Array {
665        let mut backing = vec![Some(1234.0)];
666        backing.extend(values);
667        let length = backing.len() - 1;
668        let backing = Float64Array::from(backing);
669        backing
670            .slice(1, length)
671            .as_any()
672            .downcast_ref::<Float64Array>()
673            .unwrap()
674            .clone()
675    }
676
677    fn min_max_range_inputs(
678        timestamps: &TimestampMillisecondArray,
679        values: &Float64Array,
680        timestamp_ranges: &[(u32, u32)],
681        value_ranges: &[(u32, u32)],
682    ) -> (RangeArray, RangeArray) {
683        let timestamp_prefix = [(0, 1)];
684        let value_prefix = [(0, 1)];
685        let timestamps = RangeArray::from_ranges(
686            Arc::new(timestamps.clone()),
687            timestamp_prefix
688                .into_iter()
689                .chain(timestamp_ranges.iter().copied()),
690        )
691        .unwrap();
692        let values = RangeArray::from_ranges(
693            Arc::new(values.clone()),
694            value_prefix.into_iter().chain(value_ranges.iter().copied()),
695        )
696        .unwrap();
697        (
698            slice_range_array(timestamps, 1, timestamp_ranges.len()),
699            slice_range_array(values, 1, value_ranges.len()),
700        )
701    }
702
703    fn window_keys(ranges: &[(u32, u32)]) -> Vec<i64> {
704        let length = ranges
705            .iter()
706            .map(|&(offset, length)| (offset + length) as usize)
707            .max()
708            .unwrap_or_default();
709        RangeArray::from_ranges(
710            Arc::new(Float64Array::from(vec![0.0; length])),
711            ranges.iter().copied(),
712        )
713        .unwrap()
714        .into_dict()
715        .keys()
716        .values()
717        .to_vec()
718    }
719
720    fn assert_min_max_udfs_match_oracle(
721        timestamp_values: &TimestampMillisecondArray,
722        all_values: &Float64Array,
723        timestamp_ranges: &[(u32, u32)],
724        value_ranges: &[(u32, u32)],
725    ) {
726        let expected_min = old_min_max_over_windows(all_values, value_ranges, true);
727        let expected_max = old_min_max_over_windows(all_values, value_ranges, false);
728        let (timestamps, values) =
729            min_max_range_inputs(timestamp_values, all_values, timestamp_ranges, value_ranges);
730        assert_option_bits(
731            &run_min_max_udf(MinOverTime::scalar_udf(), timestamps, values),
732            &expected_min,
733        );
734        let (timestamps, values) =
735            min_max_range_inputs(timestamp_values, all_values, timestamp_ranges, value_ranges);
736        assert_option_bits(
737            &run_min_max_udf(MaxOverTime::scalar_udf(), timestamps, values),
738            &expected_max,
739        );
740    }
741
742    #[test]
743    fn min_max_over_time_batch_preserves_bits_across_irregular_windows() {
744        let first_nan = f64::from_bits(0x7ff8_0000_0000_00a1);
745        let second_nan = f64::from_bits(0x7ff8_0000_0000_00b2);
746        let third_nan = f64::from_bits(0x7ff8_0000_0000_00c3);
747        let values = sliced_float_values(vec![
748            None,
749            Some(first_nan),
750            Some(-0.0),
751            Some(0.0),
752            Some(2.0),
753            Some(2.0),
754            Some(f64::INFINITY),
755            Some(f64::NEG_INFINITY),
756            Some(second_nan),
757            None,
758            Some(3.0),
759            Some(third_nan),
760        ]);
761        let timestamps = TimestampMillisecondArray::from_iter((0..16).map(Some));
762        let value_ranges = [
763            (0, 0),
764            (0, 2),
765            (0, 4),
766            (1, 4),
767            (4, 4),
768            (4, 4),
769            (8, 2),
770            (5, 2),
771            (3, 3),
772            (11, 1),
773        ];
774        let timestamp_ranges = [
775            (8, 0),
776            (7, 2),
777            (6, 4),
778            (5, 4),
779            (4, 4),
780            (4, 4),
781            (3, 2),
782            (2, 2),
783            (1, 3),
784            (0, 1),
785        ];
786
787        assert_min_max_udfs_match_oracle(&timestamps, &values, &timestamp_ranges, &value_ranges);
788    }
789
790    #[test]
791    fn min_max_over_time_batch_preserves_first_signed_zero_in_both_orders() {
792        let timestamps = TimestampMillisecondArray::from(vec![0, 1, 2, 3]);
793        for (values, expected) in [
794            (Float64Array::from(vec![-0.0, 0.0]), -0.0),
795            (Float64Array::from(vec![0.0, -0.0]), 0.0),
796        ] {
797            let (timestamp_ranges, value_ranges) =
798                min_max_range_inputs(&timestamps, &values, &[(2, 2)], &[(0, 2)]);
799            assert_option_bits(
800                &run_min_max_udf(MinOverTime::scalar_udf(), timestamp_ranges, value_ranges),
801                &[Some(expected)],
802            );
803            let (timestamp_ranges, value_ranges) =
804                min_max_range_inputs(&timestamps, &values, &[(2, 2)], &[(0, 2)]);
805            assert_option_bits(
806                &run_min_max_udf(MaxOverTime::scalar_udf(), timestamp_ranges, value_ranges),
807                &[Some(expected)],
808            );
809        }
810    }
811
812    #[test]
813    fn min_max_over_time_batch_rebuilds_after_right_bound_retreat() {
814        let timestamps = TimestampMillisecondArray::from(vec![0, 1, 2]);
815        let ranges = [(0, 3), (0, 2)];
816        assert_min_max_udfs_match_oracle(
817            &timestamps,
818            &Float64Array::from(vec![3.0, 2.0, 1.0]),
819            &ranges,
820            &ranges,
821        );
822        assert_min_max_udfs_match_oracle(
823            &timestamps,
824            &Float64Array::from(vec![1.0, 2.0, 3.0]),
825            &ranges,
826            &ranges,
827        );
828    }
829
830    #[test]
831    fn min_max_over_time_batch_returns_null_after_expiring_last_nan() {
832        let nan = f64::from_bits(0x7ff8_0000_0000_00d4);
833        let timestamps = TimestampMillisecondArray::from(vec![0, 1]);
834        let values = Float64Array::from(vec![Some(nan), None]);
835        let ranges = [(0, 1), (1, 1)];
836        let (timestamp_ranges, value_ranges) =
837            min_max_range_inputs(&timestamps, &values, &ranges, &ranges);
838        assert_option_bits(
839            &run_min_max_udf(MinOverTime::scalar_udf(), timestamp_ranges, value_ranges),
840            &[Some(nan), None],
841        );
842        let (timestamp_ranges, value_ranges) =
843            min_max_range_inputs(&timestamps, &values, &ranges, &ranges);
844        assert_option_bits(
845            &run_min_max_udf(MaxOverTime::scalar_udf(), timestamp_ranges, value_ranges),
846            &[Some(nan), None],
847        );
848    }
849
850    #[test]
851    fn min_max_over_time_batch_matches_scalar_oracle_for_random_windows() {
852        let values = sliced_float_values(
853            (0..64)
854                .map(|index| match index % 11 {
855                    0 => None,
856                    1 => Some(f64::from_bits(0x7ff8_0000_0000_0100 + index)),
857                    2 => Some(-0.0),
858                    3 => Some(0.0),
859                    4 => Some(f64::INFINITY),
860                    5 => Some(f64::NEG_INFINITY),
861                    _ => Some((index as f64 * 17.0).sin()),
862                })
863                .collect(),
864        );
865        let timestamps = TimestampMillisecondArray::from_iter((0..128).map(Some));
866        let mut seed = 0x5eed_u64;
867        let mut value_ranges = Vec::new();
868        let mut timestamp_ranges = Vec::new();
869        for _ in 0..256 {
870            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
871            let start = (seed as usize) % values.len();
872            let length = ((seed >> 32) as usize) % (values.len() - start + 1);
873            value_ranges.push((start as u32, length as u32));
874            timestamp_ranges.push(((values.len() - start) as u32, length as u32));
875        }
876
877        assert_min_max_udfs_match_oracle(&timestamps, &values, &timestamp_ranges, &value_ranges);
878    }
879
880    #[test]
881    fn min_max_over_time_batch_validates_inputs() {
882        let error = MinOverTime::calc(&[]).unwrap_err();
883        assert!(error.to_string().contains("expected 2 inputs, found 0"));
884
885        let timestamps =
886            RangeArray::from_ranges(Arc::new(TimestampMillisecondArray::from(vec![0])), [(0, 1)])
887                .unwrap();
888        let error = MaxOverTime::calc(&[
889            ColumnarValue::Array(Arc::new(timestamps.into_dict())),
890            ColumnarValue::Array(Arc::new(datatypes::arrow::array::Int64Array::from(vec![1]))),
891        ])
892        .unwrap_err();
893        assert!(
894            error
895                .to_string()
896                .contains("expect value range vector as DictionaryArray<Int64>")
897        );
898
899        let null_keys = datatypes::arrow::array::Int64Array::from_iter([Some(0), None]);
900        let null_key_dict = datatypes::arrow::array::DictionaryArray::<
901            datatypes::arrow::datatypes::Int64Type,
902        >::try_new(
903            null_keys,
904            Arc::new(TimestampMillisecondArray::from(vec![0, 1])),
905        )
906        .unwrap();
907        let error = MinOverTime::calc(&[
908            ColumnarValue::Array(Arc::new(null_key_dict)),
909            ColumnarValue::Array(Arc::new(datatypes::arrow::array::Int64Array::from(vec![1]))),
910        ])
911        .unwrap_err();
912        assert!(error.to_string().contains("Empty range is not expected"));
913    }
914
915    #[test]
916    fn min_max_over_time_batch_rejects_mismatched_windows() {
917        let timestamps = Arc::new(TimestampMillisecondArray::from(vec![0, 1, 2]));
918        let values = Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0]));
919        let timestamp_ranges = RangeArray::from_ranges(timestamps.clone(), [(0, 1)]).unwrap();
920        let value_ranges = RangeArray::from_ranges(values.clone(), [(0, 1), (1, 1)]).unwrap();
921        let error = invoke_range_udf(MinOverTime::scalar_udf(), timestamp_ranges, value_ranges)
922            .unwrap_err();
923        assert!(error.to_string().contains("same number of windows"));
924
925        let timestamp_ranges = RangeArray::from_ranges(timestamps, [(0, 1)]).unwrap();
926        let value_ranges = RangeArray::from_ranges(values, [(1, 2)]).unwrap();
927        let error = invoke_range_udf(MaxOverTime::scalar_udf(), timestamp_ranges, value_ranges)
928            .unwrap_err();
929        assert!(error.to_string().contains("different lengths at window 0"));
930    }
931
932    #[test]
933    fn sliding_evaluator_is_selected_only_for_overlapping_window_batches() {
934        // Enough windows, long enough, advancing by at most a quarter of the window.
935        assert!(reuses_candidates(&window_keys(&[
936            (0, 32),
937            (8, 32),
938            (16, 32),
939            (24, 32)
940        ])));
941
942        // One window too few.
943        assert!(!reuses_candidates(&window_keys(&[
944            (0, 32),
945            (8, 32),
946            (16, 32)
947        ])));
948        // One sample per window too short.
949        assert!(!reuses_candidates(&window_keys(&[
950            (0, 31),
951            (7, 31),
952            (14, 31),
953            (21, 31)
954        ])));
955        // One sample per step too far apart.
956        assert!(!reuses_candidates(&window_keys(&[
957            (0, 32),
958            (9, 32),
959            (18, 32),
960            (27, 32)
961        ])));
962    }
963
964    #[test]
965    fn sliding_evaluator_survives_an_unrepresentative_leading_window() {
966        // `RangeManipulate` gives a series that starts inside the query range a first
967        // window covering roughly one step, and emits a window covering no sample at
968        // all as (0, 0). Reading either one as the batch shape hides the overlap that
969        // the twenty windows behind it do have.
970        let overlapping = (0..20u32).map(|index| (index * 8, 40));
971        for leading in [(0, 1), (0, 0)] {
972            let ranges = std::iter::once(leading)
973                .chain(overlapping.clone())
974                .collect::<Vec<_>>();
975            assert!(reuses_candidates(&window_keys(&ranges)));
976        }
977    }
978
979    #[test]
980    fn empty_windows_do_not_shorten_the_measured_advance() {
981        // A query whose last evaluation lands one window past the last sample ends on
982        // a (0, 0) window. Its zero offset must not read as a batch that never moved,
983        // which would put disjoint windows on the evaluator built for overlap.
984        let disjoint = (0..4u32)
985            .map(|index| (index * 240, 240))
986            .collect::<Vec<_>>();
987        assert!(!reuses_candidates(&window_keys(&disjoint)));
988        let with_trailing_empty = [disjoint.as_slice(), &[(0, 0)]].concat();
989        assert!(!reuses_candidates(&window_keys(&with_trailing_empty)));
990    }
991
992    #[test]
993    fn min_max_over_time_batch_matches_oracle_on_overlapping_window_batches() {
994        let values = sliced_float_values(
995            (0..96)
996                .map(|index| match index % 13 {
997                    0 => None,
998                    1 => Some(f64::from_bits(0x7ff8_0000_0000_0200 + index as u64)),
999                    2 => Some(-0.0),
1000                    3 => Some(0.0),
1001                    4 => Some(f64::INFINITY),
1002                    5 => Some(f64::NEG_INFINITY),
1003                    6 | 7 => Some(5.0),
1004                    _ => Some(((index * 37) % 23) as f64),
1005                })
1006                .collect(),
1007        );
1008        let timestamps = TimestampMillisecondArray::from_iter((0..96).map(Some));
1009        // The first two windows open the sliding path; the rest then grow, repeat,
1010        // jump over a gap, collapse to empty, retreat, and rebuild from scratch.
1011        let ranges = [
1012            (0, 32),
1013            (4, 32),
1014            (8, 32),
1015            (12, 32),
1016            (16, 40),
1017            (20, 36),
1018            (20, 36),
1019            (64, 32),
1020            (64, 0),
1021            (60, 20),
1022            (0, 96),
1023        ];
1024        assert!(reuses_candidates(&window_keys(&ranges)));
1025
1026        assert_min_max_udfs_match_oracle(&timestamps, &values, &ranges, &ranges);
1027    }
1028
1029    #[test]
1030    fn both_extrema_paths_match_the_scalar_oracle_on_every_four_sample_window() {
1031        let alphabet = [
1032            None,
1033            Some(-0.0),
1034            Some(0.0),
1035            Some(-3.0),
1036            Some(2.0),
1037            Some(f64::INFINITY),
1038            Some(f64::NEG_INFINITY),
1039            Some(f64::from_bits(0x7ff8_0000_0000_0042)),
1040            Some(f64::from_bits(0xfff8_0000_0000_0066)),
1041        ];
1042        // Every window of a four-sample array, walked forwards and then backwards, so
1043        // the evaluator sees growing, shrinking, disjoint, empty and retreating bounds.
1044        let windows = (0..=4)
1045            .flat_map(|start| (0..=4 - start).map(move |length| (start, start + length)))
1046            .collect::<Vec<_>>();
1047
1048        for encoded in 0..alphabet.len().pow(4) {
1049            let mut remaining = encoded;
1050            let values = Float64Array::from(
1051                (0..4)
1052                    .map(|_| {
1053                        let value = alphabet[remaining % alphabet.len()];
1054                        remaining /= alphabet.len();
1055                        value
1056                    })
1057                    .collect::<Vec<_>>(),
1058            );
1059            let mut sliding_min = SlidingExtrema::new(true);
1060            let mut sliding_max = SlidingExtrema::new(false);
1061
1062            for &(start, end) in windows.iter().chain(windows.iter().rev()) {
1063                let window = values.slice(start, end - start);
1064                let timestamps = TimestampMillisecondArray::new_null(window.len());
1065
1066                let expected = min_over_time(&timestamps, &window).map(f64::to_bits);
1067                assert_eq!(
1068                    sliding_min.evaluate(&values, start, end).map(f64::to_bits),
1069                    expected,
1070                    "sliding min, values {encoded}, window {start}..{end}"
1071                );
1072                assert_eq!(
1073                    scan_extremum(&values, start, end, true).map(f64::to_bits),
1074                    expected,
1075                    "scanned min, values {encoded}, window {start}..{end}"
1076                );
1077
1078                let expected = max_over_time(&timestamps, &window).map(f64::to_bits);
1079                assert_eq!(
1080                    sliding_max.evaluate(&values, start, end).map(f64::to_bits),
1081                    expected,
1082                    "sliding max, values {encoded}, window {start}..{end}"
1083                );
1084                assert_eq!(
1085                    scan_extremum(&values, start, end, false).map(f64::to_bits),
1086                    expected,
1087                    "scanned max, values {encoded}, window {start}..{end}"
1088                );
1089            }
1090        }
1091    }
1092
1093    fn assert_over_time_value(actual: Option<f64>, expected: Option<f64>) {
1094        match (actual, expected) {
1095            (Some(actual), Some(expected)) if expected.is_nan() => assert!(actual.is_nan()),
1096            (Some(actual), Some(expected)) => assert_eq!(actual, expected),
1097            (None, None) => {}
1098            (actual, expected) => panic!("expected {expected:?}, got {actual:?}"),
1099        }
1100    }
1101
1102    fn assert_min_max(
1103        values: Vec<Option<f64>>,
1104        expected_min: Option<f64>,
1105        expected_max: Option<f64>,
1106    ) {
1107        let timestamps = TimestampMillisecondArray::from(vec![0; values.len()]);
1108        let values = Float64Array::from(values);
1109
1110        assert_over_time_value(min_over_time(&timestamps, &values), expected_min);
1111        assert_over_time_value(max_over_time(&timestamps, &values), expected_max);
1112    }
1113
1114    fn special_ranges() -> (RangeArray, RangeArray) {
1115        use datafusion::arrow::buffer::NullBuffer;
1116
1117        let timestamps = Arc::new(TimestampMillisecondArray::from_iter_values(0..10)).slice(1, 8);
1118        let values = Arc::new(Float64Array::new(
1119            vec![
1120                99.0,
1121                -0.0,
1122                0.0,
1123                f64::INFINITY,
1124                f64::NEG_INFINITY,
1125                f64::from_bits(0x7ff8_0000_0000_0042),
1126                f64::from_bits(0x7ff8_0000_0000_0066),
1127                3.0,
1128                -7.0,
1129                42.0,
1130            ]
1131            .into(),
1132            Some(NullBuffer::from(vec![
1133                true, true, true, true, true, false, true, true, true, true,
1134            ])),
1135        ))
1136        .slice(1, 8);
1137        // Empty, singleton, overlapping, disjoint, repeated, and backward windows use
1138        // independent timestamp and value offsets.
1139        let timestamp_ranges = [
1140            (0, 0),
1141            (1, 1),
1142            (2, 1),
1143            (3, 1),
1144            (4, 1),
1145            (5, 1),
1146            (6, 1),
1147            (0, 3),
1148            (3, 2),
1149            (4, 2),
1150            (6, 2),
1151            (5, 1),
1152            (2, 1),
1153        ];
1154        let value_ranges = [
1155            (7, 0),
1156            (0, 1),
1157            (1, 1),
1158            (2, 1),
1159            (3, 1),
1160            (4, 1),
1161            (5, 1),
1162            (0, 3),
1163            (3, 2),
1164            (4, 2),
1165            (1, 2),
1166            (5, 1),
1167            (1, 1),
1168        ];
1169
1170        let timestamp_ranges = RangeArray::from_ranges(
1171            Arc::new(timestamps),
1172            std::iter::once((0, 0)).chain(timestamp_ranges),
1173        )
1174        .unwrap()
1175        .into_dict()
1176        .slice(1, timestamp_ranges.len());
1177        let value_ranges = RangeArray::from_ranges(
1178            Arc::new(values),
1179            std::iter::once((0, 0)).chain(value_ranges),
1180        )
1181        .unwrap()
1182        .into_dict()
1183        .slice(1, value_ranges.len());
1184
1185        (
1186            RangeArray::try_new(timestamp_ranges).unwrap(),
1187            RangeArray::try_new(value_ranges).unwrap(),
1188        )
1189    }
1190
1191    fn assert_specialized_matches_oracle(
1192        udf: ScalarUDF,
1193        kernel: fn(&TimestampMillisecondArray, &Float64Array) -> Option<f64>,
1194    ) {
1195        use crate::functions::test_util::invoke_range_udf;
1196
1197        let (timestamps, values) = special_ranges();
1198        let expected = (0..timestamps.len())
1199            .map(|index| {
1200                let timestamps = timestamps.get(index).unwrap();
1201                let values = values.get(index).unwrap();
1202                kernel(
1203                    timestamps
1204                        .as_any()
1205                        .downcast_ref::<TimestampMillisecondArray>()
1206                        .unwrap(),
1207                    values.as_any().downcast_ref::<Float64Array>().unwrap(),
1208                )
1209            })
1210            .collect::<Vec<_>>();
1211        let (timestamps, values) = special_ranges();
1212        let output = invoke_range_udf(udf, timestamps, values).unwrap();
1213        let output_array = extract_array(&output).unwrap();
1214        let output = output_array
1215            .as_any()
1216            .downcast_ref::<Float64Array>()
1217            .unwrap();
1218
1219        assert_eq!(output.len(), expected.len());
1220        for (index, expected) in expected.into_iter().enumerate() {
1221            assert_eq!(output.is_null(index), expected.is_none());
1222            if let Some(expected) = expected {
1223                assert_eq!(output.value(index).to_bits(), expected.to_bits());
1224            }
1225        }
1226    }
1227
1228    #[test]
1229    fn specialized_presence_range_udfs_match_slice_oracles() {
1230        assert_specialized_matches_oracle(CountOverTime::scalar_udf(), count_over_time);
1231        assert_specialized_matches_oracle(LastOverTime::scalar_udf(), last_over_time);
1232        assert_specialized_matches_oracle(AbsentOverTime::scalar_udf(), absent_over_time);
1233        assert_specialized_matches_oracle(PresentOverTime::scalar_udf(), present_over_time);
1234    }
1235
1236    #[test]
1237    fn specialized_presence_range_udfs_ignore_null_samples() {
1238        use datafusion::arrow::buffer::NullBuffer;
1239
1240        let make_ranges = || {
1241            let timestamps =
1242                Arc::new(TimestampMillisecondArray::from_iter_values(0..9)).slice(1, 7);
1243            let values = Arc::new(Float64Array::new(
1244                vec![99.0, 1.0, 0.0, 0.0, 4.0, f64::NAN, 0.0, -0.0, 42.0].into(),
1245                Some(NullBuffer::from(vec![
1246                    true, true, false, false, true, true, true, true, true,
1247                ])),
1248            ))
1249            .slice(1, 7);
1250            let ranges = [(0, 4), (0, 3), (1, 2), (4, 1), (5, 2), (7, 0)];
1251
1252            (
1253                RangeArray::from_ranges(Arc::new(timestamps), ranges).unwrap(),
1254                RangeArray::from_ranges(Arc::new(values), ranges).unwrap(),
1255            )
1256        };
1257        // The first window is [1, NULL, NULL, 4]; the old physical-length evaluator
1258        // incorrectly returned 4 for count_over_time.
1259        let cases = [
1260            (
1261                CountOverTime::scalar_udf(),
1262                [Some(2.0), Some(1.0), None, Some(1.0), Some(2.0), None],
1263            ),
1264            (
1265                LastOverTime::scalar_udf(),
1266                [Some(4.0), Some(1.0), None, Some(f64::NAN), Some(-0.0), None],
1267            ),
1268            (
1269                AbsentOverTime::scalar_udf(),
1270                [None, None, Some(1.0), None, None, Some(1.0)],
1271            ),
1272            (
1273                PresentOverTime::scalar_udf(),
1274                [Some(1.0), Some(1.0), None, Some(1.0), Some(1.0), None],
1275            ),
1276        ];
1277
1278        for (udf, expected) in cases {
1279            let (timestamps, values) = make_ranges();
1280            let output =
1281                crate::functions::test_util::invoke_range_udf(udf, timestamps, values).unwrap();
1282            let output_array = extract_array(&output).unwrap();
1283            let output = output_array
1284                .as_any()
1285                .downcast_ref::<Float64Array>()
1286                .unwrap();
1287
1288            for (index, expected) in expected.into_iter().enumerate() {
1289                assert_eq!(output.is_valid(index), expected.is_some());
1290                if let Some(expected) = expected {
1291                    assert_eq!(output.value(index).to_bits(), expected.to_bits());
1292                }
1293            }
1294        }
1295    }
1296
1297    #[test]
1298    fn specialized_presence_range_udfs_preserve_errors_and_metadata() {
1299        use datafusion::arrow::array::{DictionaryArray, Int64Array};
1300        use datafusion::arrow::datatypes::{Field, Int64Type};
1301        use datafusion_common::config::ConfigOptions;
1302        use datafusion_expr::ScalarFunctionArgs;
1303
1304        use crate::functions::test_util::{assert_execution_error, invoke_range_udf};
1305
1306        for (udf, name) in [
1307            (CountOverTime::scalar_udf(), "prom_count_over_time"),
1308            (LastOverTime::scalar_udf(), "prom_last_over_time"),
1309            (AbsentOverTime::scalar_udf(), "prom_absent_over_time"),
1310            (PresentOverTime::scalar_udf(), "prom_present_over_time"),
1311        ] {
1312            assert_eq!(udf.name(), name);
1313            assert_eq!(udf.signature().volatility, Volatility::Volatile);
1314        }
1315
1316        let timestamps = Arc::new(TimestampMillisecondArray::from_iter_values(0..3));
1317        let values = Arc::new(Float64Array::from_iter_values([1.0, 2.0, 3.0]));
1318        let error = invoke_range_udf(
1319            CountOverTime::scalar_udf(),
1320            RangeArray::from_ranges(timestamps.clone(), [(0, 1), (1, 1)]).unwrap(),
1321            RangeArray::from_ranges(values.clone(), [(0, 1)]).unwrap(),
1322        )
1323        .unwrap_err();
1324        assert_execution_error(
1325            error,
1326            "RangeArray have different lengths in PromQL function prom_count_over_time: array1=2, array2=1",
1327        );
1328
1329        let error = invoke_range_udf(
1330            CountOverTime::scalar_udf(),
1331            RangeArray::from_ranges(timestamps.clone(), [(0, 1), (1, 2)]).unwrap(),
1332            RangeArray::from_ranges(values.clone(), [(0, 1), (1, 1)]).unwrap(),
1333        )
1334        .unwrap_err();
1335        assert_execution_error(
1336            error,
1337            "RangeArray's element 1 have different lengths in PromQL function prom_count_over_time: array1=2, array2=1",
1338        );
1339
1340        let invoke_dict = |timestamps: DictionaryArray<Int64Type>,
1341                           values: DictionaryArray<Int64Type>| {
1342            let args = vec![
1343                ColumnarValue::Array(Arc::new(timestamps)),
1344                ColumnarValue::Array(Arc::new(values)),
1345            ];
1346            CountOverTime::scalar_udf().invoke_with_args(ScalarFunctionArgs {
1347                arg_fields: args
1348                    .iter()
1349                    .enumerate()
1350                    .map(|(index, value)| {
1351                        Arc::new(Field::new(
1352                            format!("c{index}"),
1353                            value.data_type().clone(),
1354                            true,
1355                        ))
1356                    })
1357                    .collect(),
1358                args,
1359                number_rows: 1,
1360                return_field: Arc::new(Field::new("out", DataType::Float64, true)),
1361                config_options: Arc::new(ConfigOptions::default()),
1362            })
1363        };
1364        let empty = invoke_dict(
1365            DictionaryArray::new(
1366                Int64Array::from(Vec::<i64>::new()),
1367                Arc::new(Float64Array::from_iter_values([1.0])),
1368            ),
1369            DictionaryArray::new(
1370                Int64Array::from(Vec::<i64>::new()),
1371                Arc::new(TimestampMillisecondArray::from_iter_values([0])),
1372            ),
1373        )
1374        .unwrap();
1375        assert!(extract_array(&empty).unwrap().is_empty());
1376
1377        let null_keys = DictionaryArray::new(
1378            Int64Array::from(vec![None]),
1379            Arc::new(TimestampMillisecondArray::from_iter_values([0])),
1380        );
1381        let values_range = RangeArray::from_ranges(values.clone(), [(0, 1)]).unwrap();
1382        assert_eq!(
1383            invoke_dict(null_keys, values_range.into_dict())
1384                .unwrap_err()
1385                .to_string(),
1386            "External error: Empty range is not expected"
1387        );
1388
1389        let timestamps_range = RangeArray::from_ranges(timestamps, [(0, 1)]).unwrap();
1390        let invalid_values = unsafe { RangeArray::from_ranges_unchecked(values, [(2, 2)]) };
1391        assert_eq!(
1392            invoke_dict(timestamps_range.into_dict(), invalid_values.into_dict())
1393                .unwrap_err()
1394                .to_string(),
1395            "External error: Illegal range: offset 2, length 2, array len 3"
1396        );
1397
1398        let output = invoke_range_udf(
1399            SumOverTime::scalar_udf(),
1400            RangeArray::from_ranges(
1401                Arc::new(TimestampMillisecondArray::from_iter_values([0, 1])),
1402                [(0, 2)],
1403            )
1404            .unwrap(),
1405            RangeArray::from_ranges(
1406                Arc::new(Float64Array::from_iter_values([1.0, 2.0])),
1407                [(0, 2)],
1408            )
1409            .unwrap(),
1410        )
1411        .unwrap();
1412        assert_eq!(
1413            extract_array(&output)
1414                .unwrap()
1415                .as_any()
1416                .downcast_ref::<Float64Array>()
1417                .unwrap()
1418                .value(0),
1419            3.0
1420        );
1421    }
1422
1423    #[test]
1424    fn min_max_over_time_ignore_ordinary_nan_when_finite_values_exist() {
1425        let ordinary_nan = f64::from_bits(0x7ff8_0000_0000_0000);
1426
1427        assert_min_max(
1428            vec![Some(ordinary_nan), Some(3.0), Some(-2.0)],
1429            Some(-2.0),
1430            Some(3.0),
1431        );
1432        assert_min_max(
1433            vec![Some(3.0), Some(ordinary_nan), Some(-2.0)],
1434            Some(-2.0),
1435            Some(3.0),
1436        );
1437        assert_min_max(
1438            vec![Some(-2.0), Some(3.0), Some(ordinary_nan)],
1439            Some(-2.0),
1440            Some(3.0),
1441        );
1442        assert_min_max(
1443            vec![Some(ordinary_nan), Some(ordinary_nan)],
1444            Some(ordinary_nan),
1445            Some(ordinary_nan),
1446        );
1447        assert_min_max(
1448            vec![Some(3.0), Some(-2.0), Some(1.0)],
1449            Some(-2.0),
1450            Some(3.0),
1451        );
1452        assert_min_max(vec![], None, None);
1453        assert_min_max(vec![None, None], None, None);
1454    }
1455
1456    // build timestamp range and value range arrays for test
1457    fn build_test_range_arrays() -> (RangeArray, RangeArray) {
1458        let ts_array = Arc::new(TimestampMillisecondArray::from_iter(
1459            [
1460                1000i64, 3000, 5000, 7000, 9000, 11000, 13000, 15000, 17000, 200000, 500000,
1461            ]
1462            .into_iter()
1463            .map(Some),
1464        ));
1465        let ranges = [
1466            (0, 2),
1467            (0, 5),
1468            (1, 1), // only 1 element
1469            (2, 0), // empty range
1470            (2, 0), // empty range
1471            (3, 3),
1472            (4, 3),
1473            (5, 3),
1474            (8, 1), // only 1 element
1475            (9, 0), // empty range
1476        ];
1477
1478        let values_array = Arc::new(Float64Array::from_iter([
1479            12.345678, 87.654321, 31.415927, 27.182818, 70.710678, 41.421356, 57.735027, 69.314718,
1480            98.019802, 1.98019802, 61.803399,
1481        ]));
1482
1483        let ts_range_array = RangeArray::from_ranges(ts_array, ranges).unwrap();
1484        let value_range_array = RangeArray::from_ranges(values_array, ranges).unwrap();
1485
1486        (ts_range_array, value_range_array)
1487    }
1488
1489    #[test]
1490    fn calculate_avg_over_time() {
1491        let (ts_array, value_array) = build_test_range_arrays();
1492        simple_range_udf_runner(
1493            AvgOverTime::scalar_udf(),
1494            ts_array,
1495            value_array,
1496            vec![],
1497            vec![
1498                Some(49.9999995),
1499                Some(45.8618844),
1500                Some(87.654321),
1501                None,
1502                None,
1503                Some(46.438284),
1504                Some(56.62235366666667),
1505                Some(56.15703366666667),
1506                Some(98.019802),
1507                None,
1508            ],
1509        );
1510    }
1511
1512    #[test]
1513    fn calculate_min_over_time() {
1514        let (ts_array, value_array) = build_test_range_arrays();
1515        simple_range_udf_runner(
1516            MinOverTime::scalar_udf(),
1517            ts_array,
1518            value_array,
1519            vec![],
1520            vec![
1521                Some(12.345678),
1522                Some(12.345678),
1523                Some(87.654321),
1524                None,
1525                None,
1526                Some(27.182818),
1527                Some(41.421356),
1528                Some(41.421356),
1529                Some(98.019802),
1530                None,
1531            ],
1532        );
1533    }
1534
1535    #[test]
1536    fn calculate_max_over_time() {
1537        let (ts_array, value_array) = build_test_range_arrays();
1538        simple_range_udf_runner(
1539            MaxOverTime::scalar_udf(),
1540            ts_array,
1541            value_array,
1542            vec![],
1543            vec![
1544                Some(87.654321),
1545                Some(87.654321),
1546                Some(87.654321),
1547                None,
1548                None,
1549                Some(70.710678),
1550                Some(70.710678),
1551                Some(69.314718),
1552                Some(98.019802),
1553                None,
1554            ],
1555        );
1556    }
1557
1558    #[test]
1559    fn calculate_sum_over_time() {
1560        let (ts_array, value_array) = build_test_range_arrays();
1561        simple_range_udf_runner(
1562            SumOverTime::scalar_udf(),
1563            ts_array,
1564            value_array,
1565            vec![],
1566            vec![
1567                Some(99.999999),
1568                Some(229.309422),
1569                Some(87.654321),
1570                None,
1571                None,
1572                Some(139.314852),
1573                Some(169.867061),
1574                Some(168.471101),
1575                Some(98.019802),
1576                None,
1577            ],
1578        );
1579    }
1580
1581    #[test]
1582    fn calculate_count_over_time() {
1583        let (ts_array, value_array) = build_test_range_arrays();
1584        simple_range_udf_runner(
1585            CountOverTime::scalar_udf(),
1586            ts_array,
1587            value_array,
1588            vec![],
1589            vec![
1590                Some(2.0),
1591                Some(5.0),
1592                Some(1.0),
1593                None,
1594                None,
1595                Some(3.0),
1596                Some(3.0),
1597                Some(3.0),
1598                Some(1.0),
1599                None,
1600            ],
1601        );
1602    }
1603
1604    #[test]
1605    fn calculate_last_over_time() {
1606        let (ts_array, value_array) = build_test_range_arrays();
1607        simple_range_udf_runner(
1608            LastOverTime::scalar_udf(),
1609            ts_array,
1610            value_array,
1611            vec![],
1612            vec![
1613                Some(87.654321),
1614                Some(70.710678),
1615                Some(87.654321),
1616                None,
1617                None,
1618                Some(41.421356),
1619                Some(57.735027),
1620                Some(69.314718),
1621                Some(98.019802),
1622                None,
1623            ],
1624        );
1625    }
1626
1627    #[test]
1628    fn calculate_absent_over_time() {
1629        let (ts_array, value_array) = build_test_range_arrays();
1630        simple_range_udf_runner(
1631            AbsentOverTime::scalar_udf(),
1632            ts_array,
1633            value_array,
1634            vec![],
1635            vec![
1636                None,
1637                None,
1638                None,
1639                Some(1.0),
1640                Some(1.0),
1641                None,
1642                None,
1643                None,
1644                None,
1645                Some(1.0),
1646            ],
1647        );
1648    }
1649
1650    #[test]
1651    fn calculate_present_over_time() {
1652        let (ts_array, value_array) = build_test_range_arrays();
1653        simple_range_udf_runner(
1654            PresentOverTime::scalar_udf(),
1655            ts_array,
1656            value_array,
1657            vec![],
1658            vec![
1659                Some(1.0),
1660                Some(1.0),
1661                Some(1.0),
1662                None,
1663                None,
1664                Some(1.0),
1665                Some(1.0),
1666                Some(1.0),
1667                Some(1.0),
1668                None,
1669            ],
1670        );
1671    }
1672
1673    #[test]
1674    fn calculate_stdvar_over_time() {
1675        let (ts_array, value_array) = build_test_range_arrays();
1676        simple_range_udf_runner(
1677            StdvarOverTime::scalar_udf(),
1678            ts_array,
1679            value_array,
1680            vec![],
1681            vec![
1682                Some(1417.8479276253622),
1683                Some(808.999919713209),
1684                Some(0.0),
1685                None,
1686                None,
1687                Some(328.3638826418587),
1688                Some(143.5964181766362),
1689                Some(130.91830542386285),
1690                Some(0.0),
1691                None,
1692            ],
1693        );
1694
1695        // add more assertions
1696        let ts_array = Arc::new(TimestampMillisecondArray::from_iter(
1697            [1000i64, 3000, 5000, 7000, 9000, 11000, 13000, 15000]
1698                .into_iter()
1699                .map(Some),
1700        ));
1701        let values_array = Arc::new(Float64Array::from_iter([
1702            1.5990505637277868,
1703            1.5990505637277868,
1704            1.5990505637277868,
1705            0.0,
1706            8.0,
1707            8.0,
1708            2.0,
1709            3.0,
1710        ]));
1711        let ranges = [(0, 3), (3, 5)];
1712        simple_range_udf_runner(
1713            StdvarOverTime::scalar_udf(),
1714            RangeArray::from_ranges(ts_array, ranges).unwrap(),
1715            RangeArray::from_ranges(values_array, ranges).unwrap(),
1716            vec![],
1717            vec![Some(0.0), Some(10.559999999999999)],
1718        );
1719    }
1720
1721    #[test]
1722    fn calculate_std_dev_over_time() {
1723        let (ts_array, value_array) = build_test_range_arrays();
1724        simple_range_udf_runner(
1725            StddevOverTime::scalar_udf(),
1726            ts_array,
1727            value_array,
1728            vec![],
1729            vec![
1730                Some(37.6543215),
1731                Some(28.442923895289123),
1732                Some(0.0),
1733                None,
1734                None,
1735                Some(18.12081352042062),
1736                Some(11.983172291869804),
1737                Some(11.441953741554055),
1738                Some(0.0),
1739                None,
1740            ],
1741        );
1742
1743        // add more assertions
1744        let ts_array = Arc::new(TimestampMillisecondArray::from_iter(
1745            [1000i64, 3000, 5000, 7000, 9000, 11000, 13000, 15000]
1746                .into_iter()
1747                .map(Some),
1748        ));
1749        let values_array = Arc::new(Float64Array::from_iter([
1750            1.5990505637277868,
1751            1.5990505637277868,
1752            1.5990505637277868,
1753            0.0,
1754            8.0,
1755            8.0,
1756            2.0,
1757            3.0,
1758        ]));
1759        let ranges = [(0, 3), (3, 5)];
1760        simple_range_udf_runner(
1761            StddevOverTime::scalar_udf(),
1762            RangeArray::from_ranges(ts_array, ranges).unwrap(),
1763            RangeArray::from_ranges(values_array, ranges).unwrap(),
1764            vec![],
1765            vec![Some(0.0), Some(3.249615361854384)],
1766        );
1767    }
1768
1769    /// Timestamps and value ranges shared by the null-sample assertions below.
1770    fn null_sample_range_arrays() -> (RangeArray, RangeArray) {
1771        let ts_array = Arc::new(TimestampMillisecondArray::from_iter_values([
1772            0i64, 1000, 2000, 3000,
1773        ]));
1774        // Samples are 2.0@0 and 8.0@3000; the null slots keep a payload that would skew every
1775        // aggregate if it were read.
1776        let values_array = Arc::new(Float64Array::new(
1777            vec![2.0, 1000.0, -1000.0, 8.0].into(),
1778            Some(NullBuffer::from_iter([true, false, false, true])),
1779        ));
1780        // The second window holds no sample at all.
1781        let ranges = [(0, 4), (1, 2)];
1782
1783        (
1784            RangeArray::from_ranges(ts_array, ranges).unwrap(),
1785            RangeArray::from_ranges(values_array, ranges).unwrap(),
1786        )
1787    }
1788
1789    #[test]
1790    fn avg_over_time_divides_by_sample_count() {
1791        let (ts_array, value_array) = null_sample_range_arrays();
1792        simple_range_udf_runner(
1793            AvgOverTime::scalar_udf(),
1794            ts_array,
1795            value_array,
1796            vec![],
1797            vec![Some(5.0), None],
1798        );
1799    }
1800
1801    #[test]
1802    fn stdvar_and_stddev_over_time_skip_null_samples() {
1803        let (ts_array, value_array) = null_sample_range_arrays();
1804        simple_range_udf_runner(
1805            StdvarOverTime::scalar_udf(),
1806            ts_array,
1807            value_array,
1808            vec![],
1809            vec![Some(9.0), None],
1810        );
1811
1812        let (ts_array, value_array) = null_sample_range_arrays();
1813        simple_range_udf_runner(
1814            StddevOverTime::scalar_udf(),
1815            ts_array,
1816            value_array,
1817            vec![],
1818            vec![Some(3.0), None],
1819        );
1820    }
1821}