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