Skip to main content

promql/
range_array.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//! An extended "array" based on [DictionaryArray].
16
17use datafusion::arrow::datatypes::Field;
18use datatypes::arrow::array::{Array, ArrayData, ArrayRef, DictionaryArray, Int64Array};
19use datatypes::arrow::datatypes::{DataType, Int64Type};
20use snafu::{OptionExt, ensure};
21
22use crate::error::{EmptyRangeSnafu, IllegalRangeSnafu, Result};
23
24pub type RangeTuple = (u32, u32);
25
26/// A compound logical "array" type representing several ranges (slices) of one array, used for
27/// sliding windows such as PromQL range selectors.
28///
29/// It's built on top of Arrow's [DictionaryArray], which holds a key array and a value array.
30/// The value array can be any type; the key array is fixed to i64.
31///
32/// ```text
33///             │ ┌─────┬─────┬─────┬─────┐
34///      Two    │ │ i64 │ i64 │ i64 │ i64 │      Keys
35///    Arrays   │ └─────┴─────┴─────┴─────┘     (Fixed to i64)
36///      In     │
37///   Arrow's   │ ┌────────────────────────────┐
38/// Dictionary  │ │                            │ Values
39///    Array    │ └────────────────────────────┘(Any Type)
40/// ```
41///
42/// Because the i64 key array is reinterpreted into two u32 for offset and length
43/// in [RangeArray] to represent a "range":
44///
45/// ```text
46/// 63            32│31             0
47/// ┌───────────────┼───────────────┐
48/// │  offset (u32) │  length (u32) │
49/// └───────────────┼───────────────┘
50/// ```
51///
52/// Then the [DictionaryArray] can be expanded to several ranges like this:
53///
54/// ```text
55/// Keys
56/// ┌───────┬───────┬───────┐      ┌───────┐
57/// │ (0,2) │ (1,2) │ (2,2) │ ─┐   │[A,B,C]│ values.slice(0,2)
58/// └───────┴───────┴───────┘  │   ├───────┤
59///  Values                    ├─► │[B,C,D]│ values.slice(1,2)
60/// ┌───┬───┬───┬───┬───┐      │   ├───────┤
61/// │ A │ B │ C │ D │ E │     ─┘   │[C,D,E]│ values.slice(2,2)
62/// └───┴───┴───┴───┴───┘          └───────┘
63/// ```
64pub struct RangeArray {
65    array: DictionaryArray<Int64Type>,
66}
67
68impl RangeArray {
69    pub const fn key_type() -> DataType {
70        DataType::Int64
71    }
72
73    pub fn value_type(&self) -> DataType {
74        self.array.value_type()
75    }
76
77    pub fn try_new(dict: DictionaryArray<Int64Type>) -> Result<Self> {
78        let ranges_iter = dict
79            .keys()
80            .iter()
81            .map(|compound_key| compound_key.map(unpack))
82            .collect::<Option<Vec<_>>>()
83            .context(EmptyRangeSnafu)?;
84        Self::check_ranges(dict.values().len(), ranges_iter)?;
85
86        Ok(Self { array: dict })
87    }
88
89    pub fn from_ranges<R>(values: ArrayRef, ranges: R) -> Result<Self>
90    where
91        R: IntoIterator<Item = RangeTuple> + Clone,
92    {
93        Self::check_ranges(values.len(), ranges.clone())?;
94
95        unsafe { Ok(Self::from_ranges_unchecked(values, ranges)) }
96    }
97
98    /// Construct [RangeArray] from given range without checking its validity.
99    ///
100    /// # Safety
101    ///
102    /// Caller should ensure the given range are valid. Otherwise use [`from_ranges`]
103    /// instead.
104    ///
105    /// [`from_ranges`]: crate::range_array::RangeArray#method.from_ranges
106    pub unsafe fn from_ranges_unchecked<R>(values: ArrayRef, ranges: R) -> Self
107    where
108        R: IntoIterator<Item = RangeTuple>,
109    {
110        let key_array = Int64Array::from_iter(
111            ranges
112                .into_iter()
113                .map(|(offset, length)| pack(offset, length)),
114        );
115
116        // Build from ArrayData to bypass the "offset" checker. Because
117        // we are not using "keys" as-is.
118        // This paragraph is copied from arrow-rs dictionary_array.rs `try_new()`.
119        let mut data = ArrayData::builder(DataType::Dictionary(
120            Box::new(Self::key_type()),
121            Box::new(values.data_type().clone()),
122        ))
123        .len(key_array.len())
124        .add_buffer(key_array.to_data().buffers()[0].clone())
125        .add_child_data(values.to_data());
126        match key_array.to_data().nulls() {
127            Some(buffer) if key_array.to_data().null_count() > 0 => {
128                data = data
129                    .nulls(Some(buffer.clone()))
130                    .null_count(key_array.to_data().null_count());
131            }
132            _ => data = data.null_count(0),
133        }
134        let array_data = unsafe { data.build_unchecked() };
135
136        Self {
137            array: array_data.into(),
138        }
139    }
140
141    pub fn len(&self) -> usize {
142        self.array.keys().len()
143    }
144
145    pub fn is_empty(&self) -> bool {
146        self.array.keys().is_empty()
147    }
148
149    pub fn get(&self, index: usize) -> Option<ArrayRef> {
150        if index >= self.len() {
151            return None;
152        }
153
154        let compound_key = self.array.keys().value(index);
155        let (offset, length) = unpack(compound_key);
156        let array = self.array.values().slice(offset as usize, length as usize);
157
158        Some(array)
159    }
160
161    pub fn get_offset_length(&self, index: usize) -> Option<(usize, usize)> {
162        if index >= self.len() {
163            return None;
164        }
165
166        let compound_key = self.array.keys().value(index);
167        let (offset, length) = unpack(compound_key);
168
169        Some((offset as usize, length as usize))
170    }
171
172    /// Return the underlying Arrow's [DictionaryArray]. Notes the dictionary array might be
173    /// invalid from Arrow's definition. Be care if try to access this dictionary through
174    /// Arrow's API.
175    pub fn into_dict(self) -> DictionaryArray<Int64Type> {
176        self.array
177    }
178
179    fn check_ranges<R>(value_len: usize, ranges: R) -> Result<()>
180    where
181        R: IntoIterator<Item = RangeTuple>,
182    {
183        for (offset, length) in ranges.into_iter() {
184            ensure!(
185                offset as usize + length as usize <= value_len,
186                IllegalRangeSnafu {
187                    offset,
188                    length,
189                    len: value_len
190                }
191            );
192        }
193        Ok(())
194    }
195
196    /// Change the field's datatype to the type after processed by [RangeArray].
197    /// Like `Utf8` will become `Dictionary<Int64, Utf8>`.
198    pub fn convert_field(field: &Field) -> Field {
199        let value_type = Box::new(field.data_type().clone());
200        Field::new(
201            field.name(),
202            Self::convert_data_type(*value_type),
203            field.is_nullable(),
204        )
205    }
206
207    /// Build datatype of wrapped [RangeArray] on given value type.
208    pub fn convert_data_type(value_type: DataType) -> DataType {
209        DataType::Dictionary(Box::new(Self::key_type()), Box::new(value_type))
210    }
211
212    pub fn values(&self) -> &ArrayRef {
213        self.array.values()
214    }
215
216    pub fn ranges(&self) -> impl Iterator<Item = Option<RangeTuple>> + '_ {
217        self.array
218            .keys()
219            .into_iter()
220            .map(|compound| compound.map(unpack))
221    }
222}
223
224impl std::fmt::Debug for RangeArray {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        let ranges = self
227            .array
228            .keys()
229            .iter()
230            .map(|compound_key| {
231                compound_key.map(|key| {
232                    let (offset, length) = unpack(key);
233                    offset..(offset + length)
234                })
235            })
236            .collect::<Vec<_>>();
237        f.debug_struct("RangeArray")
238            .field("base array", self.array.values())
239            .field("ranges", &ranges)
240            .finish()
241    }
242}
243
244fn pack(offset: u32, length: u32) -> i64 {
245    bytemuck::cast::<[u32; 2], i64>([offset, length])
246}
247
248pub(crate) fn unpack(compound: i64) -> (u32, u32) {
249    let [offset, length] = bytemuck::cast::<i64, [u32; 2]>(compound);
250    (offset, length)
251}
252
253#[cfg(test)]
254mod test {
255    use std::fmt::Write;
256    use std::sync::Arc;
257
258    use datatypes::arrow::array::UInt64Array;
259
260    use super::*;
261
262    fn expand_format(range_array: &RangeArray) -> String {
263        let mut result = String::new();
264        for i in 0..range_array.len() {
265            writeln!(result, "{:?}", range_array.get(i)).unwrap();
266        }
267        result
268    }
269
270    #[test]
271    fn construct_from_ranges() {
272        let values_array = Arc::new(UInt64Array::from_iter([1, 2, 3, 4, 5, 6, 7, 8, 9]));
273        let ranges = [(0, 2), (0, 5), (1, 1), (3, 3), (8, 1), (9, 0)];
274
275        let range_array = RangeArray::from_ranges(values_array, ranges).unwrap();
276        assert_eq!(range_array.len(), 6);
277
278        let expected = String::from(
279            "Some(PrimitiveArray<UInt64>\
280            \n[\
281            \n  1,\
282            \n  2,\
283            \n])\
284            \nSome(PrimitiveArray<UInt64>\
285            \n[\
286            \n  1,\
287            \n  2,\
288            \n  3,\
289            \n  4,\
290            \n  5,\
291            \n])\
292            \nSome(PrimitiveArray<UInt64>\
293            \n[\
294            \n  2,\
295            \n])\
296            \
297            \nSome(PrimitiveArray<UInt64>\
298            \n[\
299            \n  4,\
300            \n  5,\
301            \n  6,\
302            \n])\
303            \nSome(PrimitiveArray<UInt64>\
304            \n[\
305            \n  9,\
306            \n])\
307            \nSome(PrimitiveArray<UInt64>\
308            \n[\
309            \n])\
310            \n",
311        );
312
313        let formatted = expand_format(&range_array);
314        assert_eq!(formatted, expected);
315    }
316
317    #[test]
318    fn illegal_range() {
319        let values_array = Arc::new(UInt64Array::from_iter([1, 2, 3, 4, 5, 6, 7, 8, 9]));
320        let ranges = [(9, 1)];
321        assert!(RangeArray::from_ranges(values_array, ranges).is_err());
322    }
323
324    #[test]
325    fn dict_array_round_trip() {
326        let values_array = Arc::new(UInt64Array::from_iter([1, 2, 3, 4, 5, 6, 7, 8, 9]));
327        let ranges = [(0, 4), (1, 4), (2, 4), (3, 4), (4, 4), (5, 4)];
328        let expected = String::from(
329            "Some(PrimitiveArray<UInt64>\
330            \n[\
331            \n  1,\
332            \n  2,\
333            \n  3,\
334            \n  4,\
335            \n])\
336            \nSome(PrimitiveArray<UInt64>\
337            \n[\
338            \n  2,\
339            \n  3,\
340            \n  4,\
341            \n  5,\
342            \n])\
343            \nSome(PrimitiveArray<UInt64>\
344            \n[\
345            \n  3,\
346            \n  4,\
347            \n  5,\
348            \n  6,\
349            \n])\
350            \nSome(PrimitiveArray<UInt64>\
351            \n[\
352            \n  4,\
353            \n  5,\
354            \n  6,\
355            \n  7,\
356            \n])\
357            \nSome(PrimitiveArray<UInt64>\
358            \n[\
359            \n  5,\
360            \n  6,\
361            \n  7,\
362            \n  8,\
363            \n])\
364            \nSome(PrimitiveArray<UInt64>\
365            \n[\
366            \n  6,\
367            \n  7,\
368            \n  8,\
369            \n  9,\
370            \n])\
371            \n",
372        );
373
374        let range_array = RangeArray::from_ranges(values_array, ranges).unwrap();
375        assert_eq!(range_array.len(), 6);
376        let formatted = expand_format(&range_array);
377        assert_eq!(formatted, expected);
378
379        // this dict array is invalid from Arrow's definition
380        let dict_array = range_array.into_dict();
381        let rounded_range_array = RangeArray::try_new(dict_array).unwrap();
382        let formatted = expand_format(&rounded_range_array);
383        assert_eq!(formatted, expected);
384    }
385
386    #[test]
387    fn empty_range_array() {
388        let values_array = Arc::new(UInt64Array::from_iter([1, 2, 3, 4, 5, 6, 7, 8, 9]));
389        let ranges = [];
390        let range_array = RangeArray::from_ranges(values_array, ranges).unwrap();
391        assert!(range_array.is_empty());
392    }
393}