Skip to main content

vortex_spatial/scalar_fn/
collect.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Per-row scalar `ST_Collect` over homogeneous native geometry lists.
5//!
6//! One `List<Point>`, `List<LineString>`, or `List<Polygon>` row in; one `MultiPoint`,
7//! `MultiLineString`, or `MultiPolygon` row out. This is not an aggregate: it never combines
8//! geometries from different rows, so a query over individual geometry rows must group them
9//! first with `ARRAY_AGG` or `list`.
10
11use std::sync::Arc;
12
13use vortex_array::ArrayRef;
14use vortex_array::ExecutionCtx;
15use vortex_array::IntoArray;
16use vortex_array::arrays::ConstantArray;
17use vortex_array::arrays::ExtensionArray;
18use vortex_array::arrays::ListViewArray;
19use vortex_array::arrays::ScalarFnArray;
20use vortex_array::arrays::extension::ExtensionArrayExt;
21use vortex_array::arrays::listview::ListViewArraySlotsExt;
22use vortex_array::arrays::listview::ListViewRebuildMode;
23use vortex_array::builtins::ArrayBuiltins;
24use vortex_array::dtype::DType;
25use vortex_array::dtype::Nullability;
26use vortex_array::dtype::PType;
27use vortex_array::dtype::extension::ExtDType;
28use vortex_array::dtype::extension::ExtDTypeRef;
29use vortex_array::scalar_fn::Arity;
30use vortex_array::scalar_fn::ChildName;
31use vortex_array::scalar_fn::EmptyOptions;
32use vortex_array::scalar_fn::ExecutionArgs;
33use vortex_array::scalar_fn::ScalarFnId;
34use vortex_array::scalar_fn::ScalarFnVTable;
35use vortex_array::scalar_fn::TypedScalarFnInstance;
36use vortex_array::validity::Validity;
37use vortex_buffer::Buffer;
38use vortex_buffer::BufferMut;
39use vortex_error::VortexExpect;
40use vortex_error::VortexResult;
41use vortex_error::vortex_bail;
42use vortex_error::vortex_ensure_eq;
43use vortex_error::vortex_err;
44use vortex_mask::AllOr;
45use vortex_mask::Mask;
46use vortex_session::VortexSession;
47use vortex_session::registry::CachedId;
48
49use crate::extension::LineString;
50use crate::extension::MultiLineString;
51use crate::extension::MultiPoint;
52use crate::extension::MultiPolygon;
53use crate::extension::Point;
54use crate::extension::Polygon;
55use crate::scalar_fn::execute::Execution;
56use crate::scalar_fn::execute::Operand;
57use crate::scalar_fn::execute::dispatch_unary;
58
59/// Resolve the strict homogeneous `ST_Collect` overload for one list operand.
60fn collect_dtype(dtypes: &[DType]) -> VortexResult<ExtDTypeRef> {
61    vortex_ensure_eq!(
62        dtypes.len(),
63        1,
64        "spatial: collect requires exactly one list operand"
65    );
66    let DType::List(element_dtype, nullability) = &dtypes[0] else {
67        vortex_bail!("spatial: collect operand {} is not a list", dtypes[0]);
68    };
69    // Execution ignores null list elements, so the result's element storage is non-nullable.
70    let multi_storage = |element: &ExtDTypeRef| {
71        DType::List(
72            Arc::new(element.storage_dtype().as_nonnullable()),
73            *nullability,
74        )
75    };
76    match element_dtype.as_extension_opt() {
77        Some(element) if element.is::<Point>() => Ok(ExtDType::<MultiPoint>::try_new(
78            element.metadata::<Point>().clone(),
79            multi_storage(element),
80        )?
81        .erased()),
82        Some(element) if element.is::<LineString>() => Ok(ExtDType::<MultiLineString>::try_new(
83            element.metadata::<LineString>().clone(),
84            multi_storage(element),
85        )?
86        .erased()),
87        Some(element) if element.is::<Polygon>() => Ok(ExtDType::<MultiPolygon>::try_new(
88            element.metadata::<Polygon>().clone(),
89            multi_storage(element),
90        )?
91        .erased()),
92        _ => vortex_bail!(
93            "spatial: collect list element {element_dtype} is not a native Point, LineString, \
94             or Polygon"
95        ),
96    }
97}
98
99/// Count valid elements in `start..end` with one range popcount, not per-element lookups.
100fn count_valid(element_mask: &Mask, start: usize, end: usize) -> usize {
101    match element_mask.bit_buffer() {
102        AllOr::All => end - start,
103        AllOr::None => 0,
104        AllOr::Some(bits) => bits.count_range(start, end),
105    }
106}
107
108/// Re-address the rows once null elements are filtered out of the payload.
109///
110/// Takes the `row_sizes` of an exact list view and the mask over its elements; returns the new
111/// `(offsets, sizes)`. The old offsets are redundant: `MakeExact` leaves the views a gapless
112/// in-order cover, so each row starts where the previous one ended. Neither running sum can
113/// exceed the element count.
114fn compact_row_views(
115    row_sizes: &ArrayRef,
116    element_mask: &Mask,
117    ctx: &mut ExecutionCtx,
118) -> VortexResult<(ArrayRef, ArrayRef)> {
119    let sizes = row_sizes
120        .cast(DType::Primitive(PType::U64, Nullability::NonNullable))?
121        .execute::<Buffer<u64>>(ctx)?;
122    let mut compact_offsets = BufferMut::<u64>::with_capacity(sizes.len());
123    let mut compact_sizes = BufferMut::<u64>::with_capacity(sizes.len());
124    let mut start = 0usize;
125    let mut offset = 0_u64;
126
127    for &size in sizes.iter() {
128        let end = usize::try_from(size)
129            .ok()
130            .and_then(|row_len| start.checked_add(row_len))
131            .filter(|end| *end <= element_mask.len())
132            .ok_or_else(|| {
133                vortex_err!(
134                    "spatial: collect row at element {start} exceeds the {} list elements",
135                    element_mask.len()
136                )
137            })?;
138        let valid = u64::try_from(count_valid(element_mask, start, end))
139            .map_err(|_| vortex_err!("spatial: collect valid element count exceeds u64"))?;
140        compact_offsets.push(offset);
141        compact_sizes.push(valid);
142        offset += valid;
143        start = end;
144    }
145    Ok((compact_offsets.into_array(), compact_sizes.into_array()))
146}
147
148/// Rewrap each geometry-list row as one multi-geometry row.
149///
150/// All-valid rows reuse the payload and views untouched. Null elements must be ignored (DuckDB
151/// semantics), so that path makes the views exact, filters the payload, and re-addresses the rows.
152/// Both paths forward the input's zero-copy-to-list flag.
153fn collect_list_rows(
154    mut lists: ListViewArray,
155    validity: Validity,
156    output_dtype: &ExtDTypeRef,
157    ctx: &mut ExecutionCtx,
158) -> VortexResult<ArrayRef> {
159    let mut element_mask = lists
160        .elements()
161        .validity()?
162        .execute_mask(lists.elements().len(), ctx)?;
163    if !element_mask.all_true() {
164        // Filtering addresses elements by position, so make the views exact first. `MakeExact`
165        // re-gathers the elements, so the mask must be taken again.
166        lists = lists.rebuild(ListViewRebuildMode::MakeExact, ctx)?;
167        element_mask = lists
168            .elements()
169            .validity()?
170            .execute_mask(lists.elements().len(), ctx)?;
171    }
172
173    // Both paths keep the views exact — one forwards them, the other rebuilds them as a running
174    // sum in the same element order — so the output is zero-copy to a `ListArray` whenever the
175    // input is.
176    let zero_copy_to_list = lists.is_zero_copy_to_list();
177    let parts = lists.into_data_parts();
178    let elements = parts.elements.execute::<ExtensionArray>(ctx)?;
179
180    let (element_storage, offsets, sizes) = if element_mask.all_true() {
181        (elements.storage_array().clone(), parts.offsets, parts.sizes)
182    } else {
183        let (offsets, sizes) = compact_row_views(&parts.sizes, &element_mask, ctx)?;
184        (
185            elements.storage_array().filter(element_mask)?,
186            offsets,
187            sizes,
188        )
189    };
190
191    let output_element_dtype = output_dtype
192        .storage_dtype()
193        .as_list_element_opt()
194        .vortex_expect("collect output storage is always a list")
195        .as_ref()
196        .clone();
197    let storage = ListViewArray::try_new(
198        element_storage.cast(output_element_dtype)?,
199        offsets,
200        sizes,
201        validity,
202    )?;
203    // SAFETY: the views were either forwarded unchanged or rebuilt as a gapless, non-overlapping
204    // running sum over the same elements, so the flag still holds. Forwarding it matters:
205    // `list_from_list_view` re-gathers the whole payload when it reads `false`.
206    let storage = unsafe { storage.with_zero_copy_to_list(zero_copy_to_list) }.into_array();
207    Ok(ExtensionArray::try_new(output_dtype.clone(), storage)?.into_array())
208}
209
210/// Apply [`collect_list_rows`] to a constant or column, after shared unary null dispatch.
211fn execute_collect(
212    execution: Execution<1, Validity>,
213    output_dtype: &ExtDTypeRef,
214    ctx: &mut ExecutionCtx,
215) -> VortexResult<ArrayRef> {
216    match execution.operands {
217        [Operand::Constant(scalar)] => {
218            let one_list = ConstantArray::new(scalar, 1)
219                .into_array()
220                .execute::<ListViewArray>(ctx)?;
221            let collected = collect_list_rows(
222                one_list,
223                Validity::from_mask(Mask::new_true(1), execution.nullability),
224                output_dtype,
225                ctx,
226            )?;
227            Ok(ConstantArray::new(collected.execute_scalar(0, ctx)?, execution.len).into_array())
228        }
229        [Operand::Column(geometry_lists)] => {
230            let valid = execution.valid.execute_mask(execution.len, ctx)?;
231            collect_list_rows(
232                geometry_lists.execute::<ListViewArray>(ctx)?,
233                Validity::from_mask(valid, execution.nullability),
234                output_dtype,
235                ctx,
236            )
237        }
238    }
239}
240
241/// Scalar `ST_Collect`: one `List<Point>`, `List<LineString>`, or `List<Polygon>` row in, one
242/// `MultiPoint`, `MultiLineString`, or `MultiPolygon` row out.
243///
244/// Not an aggregate — it never combines rows. Null elements are ignored, and mixed geometry lists
245/// are rejected by the element dtype rather than widened to a union.
246#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
247pub struct SpatialCollect;
248
249impl SpatialCollect {
250    /// Create a lazy scalar array that converts each geometry-list row to one multi-geometry row.
251    pub fn try_new(geometry_lists: ArrayRef) -> VortexResult<ScalarFnArray> {
252        ScalarFnArray::try_new(
253            TypedScalarFnInstance::new(SpatialCollect, EmptyOptions).erased(),
254            vec![geometry_lists],
255        )
256    }
257}
258
259impl ScalarFnVTable for SpatialCollect {
260    type Options = EmptyOptions;
261
262    fn id(&self) -> ScalarFnId {
263        static ID: CachedId = CachedId::new("vortex.st.collect");
264        *ID
265    }
266
267    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
268        Ok(Some(vec![]))
269    }
270
271    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
272        Ok(EmptyOptions)
273    }
274
275    fn arity(&self, _: &Self::Options) -> Arity {
276        Arity::Exact(1)
277    }
278
279    fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName {
280        match child_idx {
281            0 => ChildName::from("geometry_list"),
282            _ => unreachable!("collect has exactly one child"),
283        }
284    }
285
286    fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult<DType> {
287        Ok(DType::Extension(collect_dtype(dtypes)?))
288    }
289
290    fn execute(
291        &self,
292        _: &Self::Options,
293        args: &dyn ExecutionArgs,
294        ctx: &mut ExecutionCtx,
295    ) -> VortexResult<ArrayRef> {
296        let geometry_lists = args.get(0)?;
297        let output_dtype = collect_dtype(std::slice::from_ref(geometry_lists.dtype()))?;
298        dispatch_unary(
299            &geometry_lists,
300            DType::Extension(output_dtype.clone()),
301            |execution, ctx| execute_collect(execution, &output_dtype, ctx),
302            ctx,
303        )
304    }
305
306    fn is_strict(&self, _: &Self::Options) -> bool {
307        true
308    }
309
310    fn is_infallible(&self, _: &Self::Options) -> bool {
311        true
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use rstest::rstest;
318    use vortex_array::ArrayRef;
319    use vortex_array::Columnar;
320    use vortex_array::IntoArray;
321    use vortex_array::VortexSessionExecute;
322    use vortex_array::array_session;
323    use vortex_array::arrays::ConstantArray;
324    use vortex_array::arrays::ExtensionArray;
325    use vortex_array::arrays::ListArray;
326    use vortex_array::arrays::ListViewArray;
327    use vortex_array::arrays::MaskedArray;
328    use vortex_array::arrays::PrimitiveArray;
329    use vortex_array::arrays::extension::ExtensionArrayExt;
330    use vortex_array::arrays::listview::ListViewArraySlotsExt;
331    use vortex_array::assert_arrays_eq;
332    use vortex_array::dtype::DType;
333    use vortex_array::dtype::Nullability;
334    use vortex_array::dtype::PType;
335    use vortex_array::scalar_fn::EmptyOptions;
336    use vortex_array::scalar_fn::ScalarFnVTable;
337    use vortex_array::validity::Validity;
338    use vortex_error::VortexResult;
339    use vortex_error::vortex_err;
340
341    use super::SpatialCollect;
342    use crate::test_harness::linestring_column;
343    use crate::test_harness::multilinestring_column;
344    use crate::test_harness::multipoint_column;
345    use crate::test_harness::multipolygon_column;
346    use crate::test_harness::nullable_point_column;
347    use crate::test_harness::point_column;
348    use crate::test_harness::polygon_column;
349
350    fn list_with_validity(
351        elements: ArrayRef,
352        offsets: &[u32],
353        validity: Validity,
354    ) -> VortexResult<ArrayRef> {
355        Ok(ListArray::try_new(
356            elements,
357            PrimitiveArray::from_iter(offsets.iter().copied()).into_array(),
358            validity,
359        )?
360        .into_array())
361    }
362
363    fn list(elements: ArrayRef, offsets: &[u32]) -> VortexResult<ArrayRef> {
364        list_with_validity(elements, offsets, Validity::NonNullable)
365    }
366
367    /// Assert that `ST_Collect` of `input` equals `expected`.
368    fn assert_collects(input: ArrayRef, expected: ArrayRef) -> VortexResult<()> {
369        let mut ctx = array_session().create_execution_ctx();
370        let result = SpatialCollect::try_new(input)?.into_array();
371
372        assert_arrays_eq!(result, expected, &mut ctx);
373        Ok(())
374    }
375
376    #[test]
377    fn collects_points_into_multipoints() -> VortexResult<()> {
378        let points = point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?;
379        let input = list(points, &[0, 2, 3])?;
380        let expected = multipoint_column(vec![vec![(0.0, 3.0), (1.0, 4.0)], vec![(2.0, 5.0)]])?;
381
382        assert_collects(input, expected)
383    }
384
385    /// Out-of-order rows make the view non-exact. `compact_row_views` derives offsets from `sizes`
386    /// alone, which only holds after `MakeExact` reorders the elements.
387    #[test]
388    fn collects_out_of_order_list_views() -> VortexResult<()> {
389        let points = nullable_point_column(vec![
390            Some((0.0, 4.0)),
391            None,
392            Some((2.0, 6.0)),
393            Some((3.0, 7.0)),
394        ])?;
395        let views = ListViewArray::try_new(
396            points,
397            PrimitiveArray::from_iter([2u32, 0]).into_array(),
398            PrimitiveArray::from_iter([2u32, 2]).into_array(),
399            Validity::NonNullable,
400        )?;
401        assert!(
402            !views.is_zero_copy_to_list(),
403            "out-of-order row views are not zero-copy to a list"
404        );
405        let expected = multipoint_column(vec![vec![(2.0, 6.0), (3.0, 7.0)], vec![(0.0, 4.0)]])?;
406
407        assert_collects(views.into_array(), expected)
408    }
409
410    #[test]
411    fn all_valid_collect_reuses_geometry_storage() -> VortexResult<()> {
412        let points = point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?;
413        let mut ctx = array_session().create_execution_ctx();
414        let point_storage = points
415            .clone()
416            .execute::<ExtensionArray>(&mut ctx)?
417            .storage_array()
418            .clone();
419        let input = list(points, &[0, 2, 3])?;
420
421        let result = SpatialCollect::try_new(input)?
422            .into_array()
423            .execute::<ExtensionArray>(&mut ctx)?;
424        let result_storage = result
425            .storage_array()
426            .clone()
427            .execute::<ListViewArray>(&mut ctx)?;
428
429        assert!(ArrayRef::ptr_eq(&point_storage, result_storage.elements()));
430        Ok(())
431    }
432
433    /// A list view that forgets it is zero-copy to a list makes the next
434    /// `list_from_list_view` re-gather the payload that collect just reused.
435    #[rstest]
436    #[case::reused_elements(false)]
437    #[case::compacted_elements(true)]
438    fn output_stays_zero_copy_to_list(#[case] null_elements: bool) -> VortexResult<()> {
439        let points = if null_elements {
440            nullable_point_column(vec![Some((0.0, 3.0)), None, Some((2.0, 5.0))])?
441        } else {
442            point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?
443        };
444        let mut ctx = array_session().create_execution_ctx();
445        let input = list(points, &[0, 2, 3])?;
446        assert!(
447            input
448                .clone()
449                .execute::<ListViewArray>(&mut ctx)?
450                .is_zero_copy_to_list(),
451            "a list column reaches collect as an exact list view"
452        );
453
454        let storage = SpatialCollect::try_new(input)?
455            .into_array()
456            .execute::<ExtensionArray>(&mut ctx)?
457            .storage_array()
458            .clone()
459            .execute::<ListViewArray>(&mut ctx)?;
460
461        assert!(storage.is_zero_copy_to_list());
462        Ok(())
463    }
464
465    #[test]
466    fn collects_linestrings_into_multilinestrings() -> VortexResult<()> {
467        let line_a = vec![(0.0, 0.0), (1.0, 1.0)];
468        let line_b = vec![(2.0, 2.0), (3.0, 3.0)];
469        let line_c = vec![(4.0, 4.0), (5.0, 5.0)];
470        let input = list(
471            linestring_column(vec![line_a.clone(), line_b.clone(), line_c.clone()])?,
472            &[0, 2, 3],
473        )?;
474        let expected = multilinestring_column(vec![vec![line_a, line_b], vec![line_c]])?;
475
476        assert_collects(input, expected)
477    }
478
479    #[test]
480    fn collects_polygons_into_multipolygons() -> VortexResult<()> {
481        let polygon_a = vec![vec![(0.0, 0.0), (2.0, 0.0), (0.0, 2.0), (0.0, 0.0)]];
482        let polygon_b = vec![vec![(3.0, 0.0), (5.0, 0.0), (3.0, 2.0), (3.0, 0.0)]];
483        let polygon_c = vec![vec![(6.0, 0.0), (8.0, 0.0), (6.0, 2.0), (6.0, 0.0)]];
484        let input = list(
485            polygon_column(vec![
486                polygon_a.clone(),
487                polygon_b.clone(),
488                polygon_c.clone(),
489            ])?,
490            &[0, 2, 3],
491        )?;
492        let expected = multipolygon_column(vec![vec![polygon_a, polygon_b], vec![polygon_c]])?;
493
494        assert_collects(input, expected)
495    }
496
497    #[test]
498    fn constant_list_remains_constant() -> VortexResult<()> {
499        let input = list(
500            nullable_point_column(vec![Some((0.0, 2.0)), None, Some((1.0, 3.0))])?,
501            &[0, 3],
502        )?;
503        let mut ctx = array_session().create_execution_ctx();
504        let scalar = input.execute_scalar(0, &mut ctx)?;
505        let input = ConstantArray::new(scalar, 3).into_array();
506
507        let result = SpatialCollect::try_new(input)?.into_array();
508        let Columnar::Constant(constant) = result.clone().execute::<Columnar>(&mut ctx)? else {
509            return Err(vortex_err!(
510                "collect of a constant list should remain constant"
511            ));
512        };
513        assert_eq!(constant.len(), 3);
514        let expected = multipoint_column(vec![
515            vec![(0.0, 2.0), (1.0, 3.0)],
516            vec![(0.0, 2.0), (1.0, 3.0)],
517            vec![(0.0, 2.0), (1.0, 3.0)],
518        ])?;
519        assert_arrays_eq!(result, expected, &mut ctx);
520        Ok(())
521    }
522
523    #[test]
524    fn ignores_null_geometry_elements() -> VortexResult<()> {
525        let points = nullable_point_column(vec![Some((0.0, 2.0)), None, Some((1.0, 3.0)), None])?;
526        let input = list(points, &[0, 2, 4])?;
527        let expected = multipoint_column(vec![vec![(0.0, 2.0)], vec![(1.0, 3.0)]])?;
528
529        assert_collects(input, expected)
530    }
531
532    #[test]
533    fn all_null_geometry_elements_produce_empty_multi_geometry() -> VortexResult<()> {
534        let input = list(nullable_point_column(vec![None, None])?, &[0, 2])?;
535        let expected = multipoint_column(vec![vec![]])?;
536
537        assert_collects(input, expected)
538    }
539
540    #[test]
541    fn propagates_null_list_rows() -> VortexResult<()> {
542        let mut ctx = array_session().create_execution_ctx();
543        let input = list_with_validity(
544            point_column(vec![0.0, 1.0], vec![2.0, 3.0])?,
545            &[0, 1, 2],
546            Validity::from_iter([true, false]),
547        )?;
548        let expected = MaskedArray::try_new(
549            multipoint_column(vec![vec![(0.0, 2.0)], vec![(1.0, 3.0)]])?,
550            Validity::from_iter([true, false]),
551            &mut ctx,
552        )?
553        .into_array();
554
555        assert_collects(input, expected)
556    }
557
558    #[test]
559    fn rejects_unsupported_inputs() -> VortexResult<()> {
560        let point = point_column(vec![0.0], vec![0.0])?;
561        assert!(SpatialCollect::try_new(point).is_err());
562
563        let multipoints = multipoint_column(vec![vec![(0.0, 0.0)]])?;
564        assert!(SpatialCollect::try_new(list(multipoints, &[0, 1])?).is_err());
565
566        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
567        assert!(
568            SpatialCollect
569                .return_dtype(
570                    &EmptyOptions,
571                    &[DType::List(primitive.into(), Nullability::NonNullable)]
572                )
573                .is_err()
574        );
575        Ok(())
576    }
577}