Skip to main content

promql/functions/
edge_count.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::sync::Arc;
16
17use datafusion::arrow::array::{Float64Array, TimestampMillisecondArray};
18use datafusion::common::DataFusionError;
19use datafusion::logical_expr::{ScalarUDF, Volatility};
20use datafusion::physical_plan::ColumnarValue;
21use datafusion_expr::create_udf;
22use datatypes::arrow::array::Array;
23use datatypes::arrow::datatypes::DataType;
24
25use crate::functions::extract_range_array;
26use crate::range_array::RangeArray;
27
28/// The transitions `changes` and `resets` count between consecutive samples.
29#[derive(Clone, Copy)]
30pub(crate) enum EdgeKind {
31    Changes,
32    Resets,
33}
34
35pub(super) fn scalar_udf(name: &'static str, kind: EdgeKind) -> ScalarUDF {
36    create_udf(
37        name,
38        input_type(),
39        DataType::Float64,
40        Volatility::Volatile,
41        Arc::new(
42            move |input: &[ColumnarValue]| -> Result<ColumnarValue, DataFusionError> {
43                calc(input, name, kind)
44            },
45        ) as _,
46    )
47}
48
49fn input_type() -> Vec<DataType> {
50    vec![
51        RangeArray::convert_data_type(TimestampMillisecondArray::new_null(0).data_type().clone()),
52        RangeArray::convert_data_type(Float64Array::new_null(0).data_type().clone()),
53    ]
54}
55
56fn calc(
57    input: &[ColumnarValue],
58    name: &str,
59    kind: EdgeKind,
60) -> Result<ColumnarValue, DataFusionError> {
61    assert_eq!(input.len(), 2);
62
63    let timestamp_ranges = extract_range_array(&input[0])?;
64    let value_ranges = extract_range_array(&input[1])?;
65    if timestamp_ranges.len() != value_ranges.len() {
66        return Err(DataFusionError::Execution(format!(
67            "RangeArray have different lengths in PromQL function {name}: array1={}, array2={}",
68            timestamp_ranges.len(),
69            value_ranges.len()
70        )));
71    }
72
73    timestamp_ranges
74        .values()
75        .as_any()
76        .downcast_ref::<TimestampMillisecondArray>()
77        .unwrap();
78    let values = value_ranges
79        .values()
80        .as_any()
81        .downcast_ref::<Float64Array>()
82        .unwrap();
83    let requested_edges = validate_windows(&timestamp_ranges, &value_ranges, name)?;
84    let raw_values = values.values();
85    // A NULL field value means the series has no sample at that timestamp. The prefix sums
86    // encode edges between physically adjacent slots, which no longer holds once nulls are
87    // skipped, so a null-bearing input falls back to scanning each window.
88    let has_nulls = values.null_count() > 0;
89    let direct = has_nulls || should_scan_direct(requested_edges, raw_values.len());
90    let prefix = (!direct).then(|| build_prefix(raw_values.as_ref(), kind));
91
92    let mut result = Vec::with_capacity(value_ranges.len());
93    for index in 0..value_ranges.len() {
94        let (offset, len) = range_at(&value_ranges, index, name)?;
95        let end = checked_end(offset, len, index, name)?;
96        let count = match len {
97            0 => None,
98            _ if has_nulls => count_edges_skipping_nulls(values, offset, end, kind),
99            1 => Some(0),
100            _ if direct => Some(count_edges(&raw_values[offset..end], kind)),
101            _ => {
102                let prefix = prefix.as_ref().unwrap();
103                Some(prefix[end - 1] - prefix[offset])
104            }
105        };
106        result.push(count.map(|count| count as f64));
107    }
108
109    Ok(ColumnarValue::Array(Arc::new(Float64Array::from_iter(
110        result,
111    ))))
112}
113
114fn validate_windows(
115    timestamps: &RangeArray,
116    values: &RangeArray,
117    name: &str,
118) -> Result<usize, DataFusionError> {
119    let mut requested_edges = 0usize;
120    for index in 0..values.len() {
121        let (timestamp_offset, timestamp_len) = range_at(timestamps, index, name)?;
122        let (value_offset, value_len) = range_at(values, index, name)?;
123        if timestamp_len != value_len {
124            return Err(DataFusionError::Execution(format!(
125                "RangeArray's element {index} have different lengths in PromQL function {name}: array1={timestamp_len}, array2={value_len}"
126            )));
127        }
128        checked_end(timestamp_offset, timestamp_len, index, name)?;
129        checked_end(value_offset, value_len, index, name)?;
130        requested_edges = requested_edges.saturating_add(value_len.saturating_sub(1));
131    }
132    Ok(requested_edges)
133}
134
135fn range_at(
136    ranges: &RangeArray,
137    index: usize,
138    name: &str,
139) -> Result<(usize, usize), DataFusionError> {
140    ranges.get_offset_length(index).ok_or_else(|| {
141        DataFusionError::Execution(format!(
142            "RangeArray's element {index} is unavailable in PromQL function {name}"
143        ))
144    })
145}
146
147fn checked_end(
148    offset: usize,
149    len: usize,
150    index: usize,
151    name: &str,
152) -> Result<usize, DataFusionError> {
153    offset.checked_add(len).ok_or_else(|| {
154        DataFusionError::Execution(format!(
155            "RangeArray's element {index} has an invalid range in PromQL function {name}"
156        ))
157    })
158}
159
160fn should_scan_direct(requested_edges: usize, backing_len: usize) -> bool {
161    requested_edges <= backing_len.saturating_sub(1)
162}
163
164fn build_prefix(values: &[f64], kind: EdgeKind) -> Vec<u64> {
165    let mut prefix = Vec::with_capacity(values.len());
166    prefix.push(0);
167    for index in 1..values.len() {
168        prefix.push(prefix[index - 1] + u64::from(is_edge(values[index - 1], values[index], kind)));
169    }
170    prefix
171}
172
173/// Counts `kind` edges between consecutive `values`.
174pub(crate) fn count_edges(values: &[f64], kind: EdgeKind) -> u64 {
175    let mut count = 0;
176    for index in 1..values.len() {
177        count += u64::from(is_edge(values[index - 1], values[index], kind));
178    }
179    count
180}
181
182/// Counts edges between consecutive samples in `[offset, end)`, treating null slots as
183/// absent. Returns `None` when the window holds no sample.
184fn count_edges_skipping_nulls(
185    values: &Float64Array,
186    offset: usize,
187    end: usize,
188    kind: EdgeKind,
189) -> Option<u64> {
190    let raw_values = values.values();
191    let mut count = 0;
192    let mut previous = None;
193    for index in offset..end {
194        if values.is_null(index) {
195            continue;
196        }
197        let current = raw_values[index];
198        if let Some(previous) = previous.replace(current) {
199            count += u64::from(is_edge(previous, current, kind));
200        }
201    }
202    previous.is_some().then_some(count)
203}
204
205fn is_edge(previous: f64, current: f64, kind: EdgeKind) -> bool {
206    match kind {
207        EdgeKind::Changes => previous != current && !(previous.is_nan() && current.is_nan()),
208        EdgeKind::Resets => current < previous,
209    }
210}
211
212#[cfg(test)]
213mod test {
214    use super::*;
215
216    #[test]
217    fn adaptive_gate_uses_direct_scan_at_threshold() {
218        assert!(should_scan_direct(4, 5));
219        assert!(!should_scan_direct(5, 5));
220        assert!(should_scan_direct(0, 0));
221    }
222}