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::arrays::ConstantArray;
323    use vortex_array::arrays::ExtensionArray;
324    use vortex_array::arrays::ListArray;
325    use vortex_array::arrays::ListViewArray;
326    use vortex_array::arrays::MaskedArray;
327    use vortex_array::arrays::PrimitiveArray;
328    use vortex_array::arrays::extension::ExtensionArrayExt;
329    use vortex_array::arrays::listview::ListViewArraySlotsExt;
330    use vortex_array::assert_arrays_eq;
331    use vortex_array::dtype::DType;
332    use vortex_array::dtype::Nullability;
333    use vortex_array::dtype::PType;
334    use vortex_array::scalar_fn::EmptyOptions;
335    use vortex_array::scalar_fn::ScalarFnVTable;
336    use vortex_array::validity::Validity;
337    use vortex_error::VortexResult;
338    use vortex_error::vortex_err;
339
340    use super::SpatialCollect;
341    use crate::test_harness::linestring_column;
342    use crate::test_harness::multilinestring_column;
343    use crate::test_harness::multipoint_column;
344    use crate::test_harness::multipolygon_column;
345    use crate::test_harness::nullable_point_column;
346    use crate::test_harness::point_column;
347    use crate::test_harness::polygon_column;
348
349    fn list_with_validity(
350        elements: ArrayRef,
351        offsets: &[u32],
352        validity: Validity,
353    ) -> VortexResult<ArrayRef> {
354        Ok(ListArray::try_new(
355            elements,
356            PrimitiveArray::from_iter(offsets.iter().copied()).into_array(),
357            validity,
358        )?
359        .into_array())
360    }
361
362    fn list(elements: ArrayRef, offsets: &[u32]) -> VortexResult<ArrayRef> {
363        list_with_validity(elements, offsets, Validity::NonNullable)
364    }
365
366    /// Assert that `ST_Collect` of `input` equals `expected`.
367    fn assert_collects(input: ArrayRef, expected: ArrayRef) -> VortexResult<()> {
368        let mut ctx = vortex_array::array_session().create_execution_ctx();
369        let result = SpatialCollect::try_new(input)?.into_array();
370
371        assert_arrays_eq!(result, expected, &mut ctx);
372        Ok(())
373    }
374
375    #[test]
376    fn collects_points_into_multipoints() -> VortexResult<()> {
377        let points = point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?;
378        let input = list(points, &[0, 2, 3])?;
379        let expected = multipoint_column(vec![vec![(0.0, 3.0), (1.0, 4.0)], vec![(2.0, 5.0)]])?;
380
381        assert_collects(input, expected)
382    }
383
384    /// Out-of-order rows make the view non-exact. `compact_row_views` derives offsets from `sizes`
385    /// alone, which only holds after `MakeExact` reorders the elements.
386    #[test]
387    fn collects_out_of_order_list_views() -> VortexResult<()> {
388        let points = nullable_point_column(vec![
389            Some((0.0, 4.0)),
390            None,
391            Some((2.0, 6.0)),
392            Some((3.0, 7.0)),
393        ])?;
394        let views = ListViewArray::try_new(
395            points,
396            PrimitiveArray::from_iter([2u32, 0]).into_array(),
397            PrimitiveArray::from_iter([2u32, 2]).into_array(),
398            Validity::NonNullable,
399        )?;
400        assert!(
401            !views.is_zero_copy_to_list(),
402            "out-of-order row views are not zero-copy to a list"
403        );
404        let expected = multipoint_column(vec![vec![(2.0, 6.0), (3.0, 7.0)], vec![(0.0, 4.0)]])?;
405
406        assert_collects(views.into_array(), expected)
407    }
408
409    #[test]
410    fn all_valid_collect_reuses_geometry_storage() -> VortexResult<()> {
411        let points = point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?;
412        let mut ctx = vortex_array::array_session().create_execution_ctx();
413        let point_storage = points
414            .clone()
415            .execute::<ExtensionArray>(&mut ctx)?
416            .storage_array()
417            .clone();
418        let input = list(points, &[0, 2, 3])?;
419
420        let result = SpatialCollect::try_new(input)?
421            .into_array()
422            .execute::<ExtensionArray>(&mut ctx)?;
423        let result_storage = result
424            .storage_array()
425            .clone()
426            .execute::<ListViewArray>(&mut ctx)?;
427
428        assert!(ArrayRef::ptr_eq(&point_storage, result_storage.elements()));
429        Ok(())
430    }
431
432    /// A list view that forgets it is zero-copy to a list makes the next
433    /// `list_from_list_view` re-gather the payload that collect just reused.
434    #[rstest]
435    #[case::reused_elements(false)]
436    #[case::compacted_elements(true)]
437    fn output_stays_zero_copy_to_list(#[case] null_elements: bool) -> VortexResult<()> {
438        let points = if null_elements {
439            nullable_point_column(vec![Some((0.0, 3.0)), None, Some((2.0, 5.0))])?
440        } else {
441            point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?
442        };
443        let mut ctx = vortex_array::array_session().create_execution_ctx();
444        let input = list(points, &[0, 2, 3])?;
445        assert!(
446            input
447                .clone()
448                .execute::<ListViewArray>(&mut ctx)?
449                .is_zero_copy_to_list(),
450            "a list column reaches collect as an exact list view"
451        );
452
453        let storage = SpatialCollect::try_new(input)?
454            .into_array()
455            .execute::<ExtensionArray>(&mut ctx)?
456            .storage_array()
457            .clone()
458            .execute::<ListViewArray>(&mut ctx)?;
459
460        assert!(storage.is_zero_copy_to_list());
461        Ok(())
462    }
463
464    #[test]
465    fn collects_linestrings_into_multilinestrings() -> VortexResult<()> {
466        let line_a = vec![(0.0, 0.0), (1.0, 1.0)];
467        let line_b = vec![(2.0, 2.0), (3.0, 3.0)];
468        let line_c = vec![(4.0, 4.0), (5.0, 5.0)];
469        let input = list(
470            linestring_column(vec![line_a.clone(), line_b.clone(), line_c.clone()])?,
471            &[0, 2, 3],
472        )?;
473        let expected = multilinestring_column(vec![vec![line_a, line_b], vec![line_c]])?;
474
475        assert_collects(input, expected)
476    }
477
478    #[test]
479    fn collects_polygons_into_multipolygons() -> VortexResult<()> {
480        let polygon_a = vec![vec![(0.0, 0.0), (2.0, 0.0), (0.0, 2.0), (0.0, 0.0)]];
481        let polygon_b = vec![vec![(3.0, 0.0), (5.0, 0.0), (3.0, 2.0), (3.0, 0.0)]];
482        let polygon_c = vec![vec![(6.0, 0.0), (8.0, 0.0), (6.0, 2.0), (6.0, 0.0)]];
483        let input = list(
484            polygon_column(vec![
485                polygon_a.clone(),
486                polygon_b.clone(),
487                polygon_c.clone(),
488            ])?,
489            &[0, 2, 3],
490        )?;
491        let expected = multipolygon_column(vec![vec![polygon_a, polygon_b], vec![polygon_c]])?;
492
493        assert_collects(input, expected)
494    }
495
496    #[test]
497    fn constant_list_remains_constant() -> VortexResult<()> {
498        let input = list(
499            nullable_point_column(vec![Some((0.0, 2.0)), None, Some((1.0, 3.0))])?,
500            &[0, 3],
501        )?;
502        let mut ctx = vortex_array::array_session().create_execution_ctx();
503        let scalar = input.execute_scalar(0, &mut ctx)?;
504        let input = ConstantArray::new(scalar, 3).into_array();
505
506        let result = SpatialCollect::try_new(input)?.into_array();
507        let Columnar::Constant(constant) = result.clone().execute::<Columnar>(&mut ctx)? else {
508            return Err(vortex_err!(
509                "collect of a constant list should remain constant"
510            ));
511        };
512        assert_eq!(constant.len(), 3);
513        let expected = multipoint_column(vec![
514            vec![(0.0, 2.0), (1.0, 3.0)],
515            vec![(0.0, 2.0), (1.0, 3.0)],
516            vec![(0.0, 2.0), (1.0, 3.0)],
517        ])?;
518        assert_arrays_eq!(result, expected, &mut ctx);
519        Ok(())
520    }
521
522    #[test]
523    fn ignores_null_geometry_elements() -> VortexResult<()> {
524        let points = nullable_point_column(vec![Some((0.0, 2.0)), None, Some((1.0, 3.0)), None])?;
525        let input = list(points, &[0, 2, 4])?;
526        let expected = multipoint_column(vec![vec![(0.0, 2.0)], vec![(1.0, 3.0)]])?;
527
528        assert_collects(input, expected)
529    }
530
531    #[test]
532    fn all_null_geometry_elements_produce_empty_multi_geometry() -> VortexResult<()> {
533        let input = list(nullable_point_column(vec![None, None])?, &[0, 2])?;
534        let expected = multipoint_column(vec![vec![]])?;
535
536        assert_collects(input, expected)
537    }
538
539    #[test]
540    fn propagates_null_list_rows() -> VortexResult<()> {
541        let input = list_with_validity(
542            point_column(vec![0.0, 1.0], vec![2.0, 3.0])?,
543            &[0, 1, 2],
544            Validity::from_iter([true, false]),
545        )?;
546        let expected = MaskedArray::try_new(
547            multipoint_column(vec![vec![(0.0, 2.0)], vec![(1.0, 3.0)]])?,
548            Validity::from_iter([true, false]),
549        )?
550        .into_array();
551
552        assert_collects(input, expected)
553    }
554
555    #[test]
556    fn rejects_unsupported_inputs() -> VortexResult<()> {
557        let point = point_column(vec![0.0], vec![0.0])?;
558        assert!(SpatialCollect::try_new(point).is_err());
559
560        let multipoints = multipoint_column(vec![vec![(0.0, 0.0)]])?;
561        assert!(SpatialCollect::try_new(list(multipoints, &[0, 1])?).is_err());
562
563        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
564        assert!(
565            SpatialCollect
566                .return_dtype(
567                    &EmptyOptions,
568                    &[DType::List(primitive.into(), Nullability::NonNullable)]
569                )
570                .is_err()
571        );
572        Ok(())
573    }
574}