Skip to main content

vortex_functions/
list_length.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use num_traits::AsPrimitive;
5use vortex_array::ArrayRef;
6use vortex_array::ArrayView;
7use vortex_array::ExecutionCtx;
8use vortex_array::IntoArray;
9use vortex_array::arrays::ConstantArray;
10use vortex_array::arrays::FixedSizeList;
11use vortex_array::arrays::List;
12use vortex_array::arrays::ListView;
13use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt;
14use vortex_array::arrays::list::ListArrayExt;
15use vortex_array::arrays::list::ListArraySlotsExt;
16use vortex_array::arrays::listview::ListViewArrayExt;
17use vortex_array::arrays::listview::ListViewArraySlotsExt;
18use vortex_array::builtins::ArrayBuiltins;
19use vortex_array::dtype::DType;
20use vortex_array::dtype::Nullability;
21use vortex_array::dtype::PType;
22use vortex_array::matcher::Matcher;
23use vortex_array::scalar::NumericOperator;
24use vortex_array::scalar::Scalar;
25use vortex_array::scalar_fn::Arity;
26use vortex_array::scalar_fn::ChildName;
27use vortex_array::scalar_fn::EmptyOptions;
28use vortex_array::scalar_fn::ExecutionArgs;
29use vortex_array::scalar_fn::ScalarFnId;
30use vortex_array::scalar_fn::ScalarFnVTable;
31use vortex_error::VortexResult;
32use vortex_error::vortex_bail;
33use vortex_session::VortexSession;
34use vortex_session::registry::CachedId;
35
36/// Number of elements in each list of a `List` or `FixedSizeList` typed array.
37///
38/// This is computed purely from the list's offsets (`ListArray`), sizes (`ListViewArray`), or
39/// dtype (`FixedSizeListArray`) without reading the element *values*. Validity is carried over
40/// from the original array.
41#[derive(Clone)]
42pub struct ListLength;
43
44impl ScalarFnVTable for ListLength {
45    type Options = EmptyOptions;
46
47    fn id(&self) -> ScalarFnId {
48        static ID: CachedId = CachedId::new("vortex.list.length");
49        *ID
50    }
51
52    fn serialize(&self, _instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
53        Ok(Some(vec![]))
54    }
55
56    fn deserialize(
57        &self,
58        _metadata: &[u8],
59        _session: &VortexSession,
60    ) -> VortexResult<Self::Options> {
61        Ok(EmptyOptions)
62    }
63
64    fn arity(&self, _options: &Self::Options) -> Arity {
65        Arity::Exact(1)
66    }
67
68    fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
69        match child_idx {
70            0 => ChildName::from("input"),
71            _ => unreachable!("Invalid child index {child_idx} for list_length()"),
72        }
73    }
74
75    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
76        match &arg_dtypes[0] {
77            DType::List(_, nullable) | DType::FixedSizeList(_, _, nullable) => {
78                Ok(DType::Primitive(PType::U64, *nullable))
79            }
80            other => {
81                vortex_bail!("list_length() requires List or FixedSizeList, got {other}")
82            }
83        }
84    }
85
86    fn execute(
87        &self,
88        _options: &Self::Options,
89        args: &dyn ExecutionArgs,
90        ctx: &mut ExecutionCtx,
91    ) -> VortexResult<ArrayRef> {
92        let input = args.get(0)?;
93        let nullability = input.dtype().nullability();
94
95        if let Some(scalar) = input.as_constant() {
96            let len_scalar = scalar_list_length(scalar, nullability)?;
97            return Ok(ConstantArray::new(len_scalar, args.row_count()).into_array());
98        }
99
100        list_length(&input, nullability, ctx)
101    }
102
103    fn is_strict(&self, _options: &Self::Options) -> bool {
104        // A null list has a null length, and the length of a valid list is a non-null value
105        // determined by that list alone, with `return_dtype` carrying over the input nullability.
106        true
107    }
108
109    fn is_infallible(&self, _options: &Self::Options) -> bool {
110        true
111    }
112}
113
114fn scalar_list_length(scalar: &Scalar, nullability: Nullability) -> VortexResult<Scalar> {
115    if scalar.is_null() {
116        let dtype = DType::Primitive(PType::U64, Nullability::Nullable);
117        return Ok(Scalar::null(dtype));
118    }
119    let len: u64 = scalar.as_list().len().as_();
120    Ok(Scalar::primitive(len, nullability))
121}
122
123pub(crate) fn list_length(
124    array: &ArrayRef,
125    nullability: Nullability,
126    ctx: &mut ExecutionCtx,
127) -> VortexResult<ArrayRef> {
128    let any_list = array.clone().execute_until::<AnyList>(ctx)?;
129
130    let (lengths, validity) = if let Some(fsl) = any_list.as_opt::<FixedSizeList>() {
131        // The length of fixed-size list is constant, so just need to carry over validity
132        let size = fsl.list_size() as u64;
133        let lengths =
134            ConstantArray::new(Scalar::primitive(size, Nullability::NonNullable), fsl.len())
135                .into_array();
136        (lengths, fsl.validity()?)
137    } else if let Some(lv) = any_list.as_opt::<ListView>() {
138        // Length array is exactly the sizes child
139        (lv.sizes().clone(), lv.listview_validity())
140    } else if let Some(l) = any_list.as_opt::<List>() {
141        let lengths = list_length_from_offsets(l)?;
142        (lengths, l.list_validity())
143    } else {
144        let dtype = any_list.dtype();
145        vortex_bail!("list_length() requires List, ListView, or FixedSizeList but got {dtype}")
146    };
147
148    // Cast to `U64`
149    let len = lengths.len();
150    let lengths = lengths.cast(DType::Primitive(PType::U64, nullability))?;
151
152    // Carry over validity mask for nullable arrays
153    if matches!(nullability, Nullability::Nullable) {
154        lengths.mask(validity.to_array(len))
155    } else {
156        Ok(lengths)
157    }
158}
159
160/// Calculate the lengths of `ListArray` elements via the `offsets` child:
161/// `length[i] = offsets[i + 1] - offsets[i]`.
162fn list_length_from_offsets(list: ArrayView<'_, List>) -> VortexResult<ArrayRef> {
163    let offsets = list.offsets();
164    let n = offsets.len().saturating_sub(1);
165
166    offsets
167        .slice(1..offsets.len())?
168        .numeric(offsets.slice(0..n)?, NumericOperator::Sub)
169}
170
171/// Matches an `Array<List>`, `Array<ListView>`, or `Array<FixedSizeList>`
172struct AnyList;
173
174impl Matcher for AnyList {
175    type Match<'a> = ();
176
177    fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
178        (array.as_opt::<List>().is_some()
179            || array.as_opt::<ListView>().is_some()
180            || array.as_opt::<FixedSizeList>().is_some())
181        .then_some(())
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use std::sync::Arc;
188    use std::sync::LazyLock;
189
190    use rstest::rstest;
191    use vortex_array::ArrayRef;
192    use vortex_array::IntoArray;
193    use vortex_array::VortexSessionExecute;
194    use vortex_array::arrays::BoolArray;
195    use vortex_array::arrays::ConstantArray;
196    use vortex_array::arrays::FixedSizeListArray;
197    use vortex_array::arrays::ListArray;
198    use vortex_array::arrays::ListViewArray;
199    use vortex_array::arrays::PrimitiveArray;
200    use vortex_array::assert_arrays_eq;
201    use vortex_array::dtype::DType;
202    use vortex_array::dtype::Nullability;
203    use vortex_array::dtype::PType;
204    use vortex_array::scalar::Scalar;
205    use vortex_array::validity::Validity;
206    use vortex_buffer::buffer;
207    use vortex_error::VortexResult;
208    use vortex_expr::ArrayExprExt;
209    use vortex_expr::cast;
210    use vortex_expr::root;
211    use vortex_session::VortexSession;
212
213    use crate::expr::list_length;
214
215    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
216        let session = VortexSession::empty();
217
218        vortex_array::initialize(&session);
219
220        crate::initialize(&session);
221
222        session
223    });
224
225    fn create_list_elements() -> ArrayRef {
226        PrimitiveArray::from_option_iter::<i32, _>([
227            Some(1),
228            Some(2),
229            Some(3),
230            Some(4),
231            Some(5),
232            Some(6),
233            None,
234        ])
235        .into_array()
236    }
237
238    #[rstest]
239    #[case(buffer![0u32, 2, 5, 5, 7].into_array())]
240    #[case(buffer![0u64, 2, 5, 5, 7].into_array())]
241    fn test_list_length(#[case] offsets: ArrayRef) -> VortexResult<()> {
242        let mut ctx = SESSION.create_execution_ctx();
243        let elements = create_list_elements();
244        let list =
245            ListArray::try_new(elements, offsets, Validity::NonNullable, &mut ctx)?.into_array();
246        let result = list.apply(&list_length(root()))?;
247        let mut ctx = SESSION.create_execution_ctx();
248        assert_arrays_eq!(result, PrimitiveArray::from_iter([2u64, 3, 0, 2]), &mut ctx);
249        Ok(())
250    }
251
252    #[rstest]
253    #[case(buffer![0u32, 2, 5, 5, 7].into_array())]
254    #[case(buffer![0u64, 2, 5, 5, 7].into_array())]
255    fn test_nullable_list_length(#[case] offsets: ArrayRef) -> VortexResult<()> {
256        let mut ctx = SESSION.create_execution_ctx();
257        let elements = create_list_elements();
258        let list = ListArray::try_new(
259            elements,
260            offsets,
261            Validity::Array(BoolArray::from_iter([true, false, true, false]).into_array()),
262            &mut ctx,
263        )?
264        .into_array();
265        let result = list.apply(&list_length(root()))?;
266
267        let mut ctx = SESSION.create_execution_ctx();
268
269        let expected = PrimitiveArray::from_option_iter::<u64, _>([Some(2), None, Some(0), None]);
270
271        assert_arrays_eq!(result, expected, &mut ctx);
272
273        Ok(())
274    }
275
276    #[test]
277    fn test_null_scalar_list_length() -> VortexResult<()> {
278        let null_scalar = Scalar::null(DType::List(
279            Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)),
280            Nullability::Nullable,
281        ));
282        let array = ConstantArray::new(null_scalar, 2).into_array();
283        let result = array.apply(&list_length(root()))?;
284
285        let mut ctx = SESSION.create_execution_ctx();
286        assert!(!result.is_valid(0, &mut ctx)?);
287        assert!(!result.is_valid(1, &mut ctx)?);
288        assert_arrays_eq!(
289            result,
290            PrimitiveArray::from_option_iter([None::<u64>, None]),
291            &mut ctx
292        );
293        Ok(())
294    }
295
296    #[test]
297    fn test_listview_length() -> VortexResult<()> {
298        let mut ctx = SESSION.create_execution_ctx();
299        let elements = create_list_elements();
300        let lv = ListViewArray::new(
301            elements,
302            buffer![5u32, 0, 4, 1].into_array(),
303            buffer![2u32, 3, 0, 2].into_array(),
304            Validity::NonNullable,
305            &mut ctx,
306        )
307        .into_array();
308        let result = lv.apply(&list_length(root()))?;
309        let mut ctx = SESSION.create_execution_ctx();
310        assert_arrays_eq!(result, PrimitiveArray::from_iter([2u64, 3, 0, 2]), &mut ctx);
311        Ok(())
312    }
313
314    #[test]
315    fn test_listview_length_nullable() -> VortexResult<()> {
316        let mut ctx = SESSION.create_execution_ctx();
317        let elements = create_list_elements();
318        let lv = ListViewArray::new(
319            elements,
320            buffer![5u32, 0, 4, 1].into_array(),
321            buffer![2u32, 3, 0, 2].into_array(),
322            Validity::Array(BoolArray::from_iter([true, false, true, false]).into_array()),
323            &mut ctx,
324        )
325        .into_array();
326        let result = lv.apply(&list_length(root()))?;
327
328        let mut ctx = SESSION.create_execution_ctx();
329
330        let expected = PrimitiveArray::from_option_iter::<u64, _>([Some(2), None, Some(0), None]);
331        assert_arrays_eq!(result, expected, &mut ctx);
332        Ok(())
333    }
334
335    #[test]
336    fn test_list_length_take() -> VortexResult<()> {
337        let mut ctx = SESSION.create_execution_ctx();
338        let elements = create_list_elements();
339        let list = ListArray::try_new(
340            elements,
341            buffer![0u32, 2, 5, 5, 7].into_array(),
342            Validity::NonNullable,
343            &mut ctx,
344        )?
345        .into_array();
346        let taken = list.take(buffer![3u64, 0, 2].into_array())?;
347
348        let result = taken.apply(&list_length(root()))?;
349        let mut ctx = SESSION.create_execution_ctx();
350        assert_arrays_eq!(result, PrimitiveArray::from_iter([2u64, 2, 0]), &mut ctx);
351        Ok(())
352    }
353
354    fn create_fixed_size_list(validity: Validity) -> ArrayRef {
355        // 4 lists of size 2 over 8 primitive elements.
356        let elements = PrimitiveArray::from_iter([1i32, 2, 3, 4, 5, 6, 7, 8]).into_array();
357        FixedSizeListArray::new(elements, 2, validity, 4).into_array()
358    }
359
360    #[test]
361    fn test_fixed_size_list_length() -> VortexResult<()> {
362        let fsl = create_fixed_size_list(Validity::NonNullable);
363        let result = fsl.apply(&list_length(root()))?;
364
365        let mut ctx = SESSION.create_execution_ctx();
366        assert_arrays_eq!(result, PrimitiveArray::from_iter([2u64, 2, 2, 2]), &mut ctx);
367        Ok(())
368    }
369
370    #[test]
371    fn test_fixed_size_list_length_nullable() -> VortexResult<()> {
372        let fsl = create_fixed_size_list(Validity::Array(
373            BoolArray::from_iter([true, false, true, false]).into_array(),
374        ));
375        let result = fsl.apply(&list_length(root()))?;
376
377        let mut ctx = SESSION.create_execution_ctx();
378
379        let expected = PrimitiveArray::from_option_iter::<u64, _>([Some(2), None, Some(2), None]);
380        assert_arrays_eq!(result, expected, &mut ctx);
381        Ok(())
382    }
383
384    #[test]
385    fn test_fallible_child_expression_fails() -> VortexResult<()> {
386        let fsl = create_fixed_size_list(Validity::Array(
387            BoolArray::from_iter([true, false, true, false]).into_array(),
388        ));
389        let failing_cast_dtype = DType::FixedSizeList(
390            Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)),
391            2,
392            Nullability::NonNullable,
393        );
394
395        let lengths = fsl.apply(&list_length(cast(root(), failing_cast_dtype)))?;
396
397        let mut ctx = SESSION.create_execution_ctx();
398        let result = lengths.execute::<ArrayRef>(&mut ctx);
399
400        assert!(result.is_err());
401
402        let err_message = result.unwrap_err().to_string();
403
404        assert!(
405            err_message.contains("Cannot cast array with invalid values to non-nullable type.")
406        );
407
408        Ok(())
409    }
410
411    #[test]
412    fn test_display() {
413        let expr = list_length(root());
414        assert_eq!(expr.to_string(), "vortex.list.length($)");
415    }
416}