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        ctx,
203    )?;
204    // SAFETY: the views were either forwarded unchanged or rebuilt as a gapless, non-overlapping
205    // running sum over the same elements, so the flag still holds. Forwarding it matters:
206    // `list_from_list_view` re-gathers the whole payload when it reads `false`.
207    let storage = unsafe { storage.with_zero_copy_to_list(zero_copy_to_list) }.into_array();
208    Ok(ExtensionArray::try_new(output_dtype.clone(), storage)?.into_array())
209}
210
211/// Apply [`collect_list_rows`] to a constant or column, after shared unary null dispatch.
212fn execute_collect(
213    execution: Execution<1, Validity>,
214    output_dtype: &ExtDTypeRef,
215    ctx: &mut ExecutionCtx,
216) -> VortexResult<ArrayRef> {
217    match execution.operands {
218        [Operand::Constant(scalar)] => {
219            let one_list = ConstantArray::new(scalar, 1)
220                .into_array()
221                .execute::<ListViewArray>(ctx)?;
222            let collected = collect_list_rows(
223                one_list,
224                Validity::from_mask(Mask::new_true(1), execution.nullability),
225                output_dtype,
226                ctx,
227            )?;
228            Ok(ConstantArray::new(collected.execute_scalar(0, ctx)?, execution.len).into_array())
229        }
230        [Operand::Column(geometry_lists)] => {
231            let valid = execution.valid.execute_mask(execution.len, ctx)?;
232            collect_list_rows(
233                geometry_lists.execute::<ListViewArray>(ctx)?,
234                Validity::from_mask(valid, execution.nullability),
235                output_dtype,
236                ctx,
237            )
238        }
239    }
240}
241
242/// Scalar `ST_Collect`: one `List<Point>`, `List<LineString>`, or `List<Polygon>` row in, one
243/// `MultiPoint`, `MultiLineString`, or `MultiPolygon` row out.
244///
245/// Not an aggregate — it never combines rows. Null elements are ignored, and mixed geometry lists
246/// are rejected by the element dtype rather than widened to a union.
247#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
248pub struct SpatialCollect;
249
250impl SpatialCollect {
251    /// Create a lazy scalar array that converts each geometry-list row to one multi-geometry row.
252    pub fn try_new(geometry_lists: ArrayRef) -> VortexResult<ScalarFnArray> {
253        ScalarFnArray::try_new(
254            TypedScalarFnInstance::new(SpatialCollect, EmptyOptions).erased(),
255            vec![geometry_lists],
256        )
257    }
258}
259
260impl ScalarFnVTable for SpatialCollect {
261    type Options = EmptyOptions;
262
263    fn id(&self) -> ScalarFnId {
264        static ID: CachedId = CachedId::new("vortex.st.collect");
265        *ID
266    }
267
268    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
269        Ok(Some(vec![]))
270    }
271
272    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
273        Ok(EmptyOptions)
274    }
275
276    fn arity(&self, _: &Self::Options) -> Arity {
277        Arity::Exact(1)
278    }
279
280    fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName {
281        match child_idx {
282            0 => ChildName::from("geometry_list"),
283            _ => unreachable!("collect has exactly one child"),
284        }
285    }
286
287    fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult<DType> {
288        Ok(DType::Extension(collect_dtype(dtypes)?))
289    }
290
291    fn execute(
292        &self,
293        _: &Self::Options,
294        args: &dyn ExecutionArgs,
295        ctx: &mut ExecutionCtx,
296    ) -> VortexResult<ArrayRef> {
297        let geometry_lists = args.get(0)?;
298        let output_dtype = collect_dtype(std::slice::from_ref(geometry_lists.dtype()))?;
299        dispatch_unary(
300            &geometry_lists,
301            DType::Extension(output_dtype.clone()),
302            |execution, ctx| execute_collect(execution, &output_dtype, ctx),
303            ctx,
304        )
305    }
306
307    fn is_strict(&self, _: &Self::Options) -> bool {
308        true
309    }
310
311    fn is_infallible(&self, _: &Self::Options) -> bool {
312        true
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use rstest::rstest;
319    use vortex_array::ArrayRef;
320    use vortex_array::Columnar;
321    use vortex_array::IntoArray;
322    use vortex_array::VortexSessionExecute;
323    use vortex_array::array_session;
324    use vortex_array::arrays::ConstantArray;
325    use vortex_array::arrays::ExtensionArray;
326    use vortex_array::arrays::ListArray;
327    use vortex_array::arrays::ListViewArray;
328    use vortex_array::arrays::MaskedArray;
329    use vortex_array::arrays::PrimitiveArray;
330    use vortex_array::arrays::extension::ExtensionArrayExt;
331    use vortex_array::arrays::listview::ListViewArraySlotsExt;
332    use vortex_array::assert_arrays_eq;
333    use vortex_array::dtype::DType;
334    use vortex_array::dtype::Nullability;
335    use vortex_array::dtype::PType;
336    use vortex_array::scalar_fn::EmptyOptions;
337    use vortex_array::scalar_fn::ScalarFnVTable;
338    use vortex_array::validity::Validity;
339    use vortex_error::VortexResult;
340    use vortex_error::vortex_err;
341
342    use super::SpatialCollect;
343    use crate::test_harness::linestring_column;
344    use crate::test_harness::multilinestring_column;
345    use crate::test_harness::multipoint_column;
346    use crate::test_harness::multipolygon_column;
347    use crate::test_harness::nullable_point_column;
348    use crate::test_harness::point_column;
349    use crate::test_harness::polygon_column;
350
351    fn list_with_validity(
352        elements: ArrayRef,
353        offsets: &[u32],
354        validity: Validity,
355    ) -> VortexResult<ArrayRef> {
356        let mut ctx = array_session().create_execution_ctx();
357        Ok(ListArray::try_new(
358            elements,
359            PrimitiveArray::from_iter(offsets.iter().copied()).into_array(),
360            validity,
361            &mut ctx,
362        )?
363        .into_array())
364    }
365
366    fn list(elements: ArrayRef, offsets: &[u32]) -> VortexResult<ArrayRef> {
367        list_with_validity(elements, offsets, Validity::NonNullable)
368    }
369
370    /// Assert that `ST_Collect` of `input` equals `expected`.
371    fn assert_collects(input: ArrayRef, expected: ArrayRef) -> VortexResult<()> {
372        let mut ctx = array_session().create_execution_ctx();
373        let result = SpatialCollect::try_new(input)?.into_array();
374
375        assert_arrays_eq!(result, expected, &mut ctx);
376        Ok(())
377    }
378
379    #[test]
380    fn collects_points_into_multipoints() -> VortexResult<()> {
381        let points = point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?;
382        let input = list(points, &[0, 2, 3])?;
383        let expected = multipoint_column(vec![vec![(0.0, 3.0), (1.0, 4.0)], vec![(2.0, 5.0)]])?;
384
385        assert_collects(input, expected)
386    }
387
388    /// Out-of-order rows make the view non-exact. `compact_row_views` derives offsets from `sizes`
389    /// alone, which only holds after `MakeExact` reorders the elements.
390    #[test]
391    fn collects_out_of_order_list_views() -> VortexResult<()> {
392        let mut ctx = array_session().create_execution_ctx();
393        let points = nullable_point_column(vec![
394            Some((0.0, 4.0)),
395            None,
396            Some((2.0, 6.0)),
397            Some((3.0, 7.0)),
398        ])?;
399        let views = ListViewArray::try_new(
400            points,
401            PrimitiveArray::from_iter([2u32, 0]).into_array(),
402            PrimitiveArray::from_iter([2u32, 2]).into_array(),
403            Validity::NonNullable,
404            &mut ctx,
405        )?;
406        assert!(
407            !views.is_zero_copy_to_list(),
408            "out-of-order row views are not zero-copy to a list"
409        );
410        let expected = multipoint_column(vec![vec![(2.0, 6.0), (3.0, 7.0)], vec![(0.0, 4.0)]])?;
411
412        assert_collects(views.into_array(), expected)
413    }
414
415    #[test]
416    fn all_valid_collect_reuses_geometry_storage() -> VortexResult<()> {
417        let points = point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?;
418        let mut ctx = array_session().create_execution_ctx();
419        let point_storage = points
420            .clone()
421            .execute::<ExtensionArray>(&mut ctx)?
422            .storage_array()
423            .clone();
424        let input = list(points, &[0, 2, 3])?;
425
426        let result = SpatialCollect::try_new(input)?
427            .into_array()
428            .execute::<ExtensionArray>(&mut ctx)?;
429        let result_storage = result
430            .storage_array()
431            .clone()
432            .execute::<ListViewArray>(&mut ctx)?;
433
434        assert!(ArrayRef::ptr_eq(&point_storage, result_storage.elements()));
435        Ok(())
436    }
437
438    /// A list view that forgets it is zero-copy to a list makes the next
439    /// `list_from_list_view` re-gather the payload that collect just reused.
440    #[rstest]
441    #[case::reused_elements(false)]
442    #[case::compacted_elements(true)]
443    fn output_stays_zero_copy_to_list(#[case] null_elements: bool) -> VortexResult<()> {
444        let points = if null_elements {
445            nullable_point_column(vec![Some((0.0, 3.0)), None, Some((2.0, 5.0))])?
446        } else {
447            point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?
448        };
449        let mut ctx = array_session().create_execution_ctx();
450        let input = list(points, &[0, 2, 3])?;
451        assert!(
452            input
453                .clone()
454                .execute::<ListViewArray>(&mut ctx)?
455                .is_zero_copy_to_list(),
456            "a list column reaches collect as an exact list view"
457        );
458
459        let storage = SpatialCollect::try_new(input)?
460            .into_array()
461            .execute::<ExtensionArray>(&mut ctx)?
462            .storage_array()
463            .clone()
464            .execute::<ListViewArray>(&mut ctx)?;
465
466        assert!(storage.is_zero_copy_to_list());
467        Ok(())
468    }
469
470    #[test]
471    fn collects_linestrings_into_multilinestrings() -> VortexResult<()> {
472        let line_a = vec![(0.0, 0.0), (1.0, 1.0)];
473        let line_b = vec![(2.0, 2.0), (3.0, 3.0)];
474        let line_c = vec![(4.0, 4.0), (5.0, 5.0)];
475        let input = list(
476            linestring_column(vec![line_a.clone(), line_b.clone(), line_c.clone()])?,
477            &[0, 2, 3],
478        )?;
479        let expected = multilinestring_column(vec![vec![line_a, line_b], vec![line_c]])?;
480
481        assert_collects(input, expected)
482    }
483
484    #[test]
485    fn collects_polygons_into_multipolygons() -> VortexResult<()> {
486        let polygon_a = vec![vec![(0.0, 0.0), (2.0, 0.0), (0.0, 2.0), (0.0, 0.0)]];
487        let polygon_b = vec![vec![(3.0, 0.0), (5.0, 0.0), (3.0, 2.0), (3.0, 0.0)]];
488        let polygon_c = vec![vec![(6.0, 0.0), (8.0, 0.0), (6.0, 2.0), (6.0, 0.0)]];
489        let input = list(
490            polygon_column(vec![
491                polygon_a.clone(),
492                polygon_b.clone(),
493                polygon_c.clone(),
494            ])?,
495            &[0, 2, 3],
496        )?;
497        let expected = multipolygon_column(vec![vec![polygon_a, polygon_b], vec![polygon_c]])?;
498
499        assert_collects(input, expected)
500    }
501
502    #[test]
503    fn constant_list_remains_constant() -> VortexResult<()> {
504        let input = list(
505            nullable_point_column(vec![Some((0.0, 2.0)), None, Some((1.0, 3.0))])?,
506            &[0, 3],
507        )?;
508        let mut ctx = array_session().create_execution_ctx();
509        let scalar = input.execute_scalar(0, &mut ctx)?;
510        let input = ConstantArray::new(scalar, 3).into_array();
511
512        let result = SpatialCollect::try_new(input)?.into_array();
513        let Columnar::Constant(constant) = result.clone().execute::<Columnar>(&mut ctx)? else {
514            return Err(vortex_err!(
515                "collect of a constant list should remain constant"
516            ));
517        };
518        assert_eq!(constant.len(), 3);
519        let expected = multipoint_column(vec![
520            vec![(0.0, 2.0), (1.0, 3.0)],
521            vec![(0.0, 2.0), (1.0, 3.0)],
522            vec![(0.0, 2.0), (1.0, 3.0)],
523        ])?;
524        assert_arrays_eq!(result, expected, &mut ctx);
525        Ok(())
526    }
527
528    #[test]
529    fn ignores_null_geometry_elements() -> VortexResult<()> {
530        let points = nullable_point_column(vec![Some((0.0, 2.0)), None, Some((1.0, 3.0)), None])?;
531        let input = list(points, &[0, 2, 4])?;
532        let expected = multipoint_column(vec![vec![(0.0, 2.0)], vec![(1.0, 3.0)]])?;
533
534        assert_collects(input, expected)
535    }
536
537    #[test]
538    fn all_null_geometry_elements_produce_empty_multi_geometry() -> VortexResult<()> {
539        let input = list(nullable_point_column(vec![None, None])?, &[0, 2])?;
540        let expected = multipoint_column(vec![vec![]])?;
541
542        assert_collects(input, expected)
543    }
544
545    #[test]
546    fn propagates_null_list_rows() -> VortexResult<()> {
547        let mut ctx = array_session().create_execution_ctx();
548        let input = list_with_validity(
549            point_column(vec![0.0, 1.0], vec![2.0, 3.0])?,
550            &[0, 1, 2],
551            Validity::from_iter([true, false]),
552        )?;
553        let expected = MaskedArray::try_new(
554            multipoint_column(vec![vec![(0.0, 2.0)], vec![(1.0, 3.0)]])?,
555            Validity::from_iter([true, false]),
556            &mut ctx,
557        )?
558        .into_array();
559
560        assert_collects(input, expected)
561    }
562
563    #[test]
564    fn rejects_unsupported_inputs() -> VortexResult<()> {
565        let point = point_column(vec![0.0], vec![0.0])?;
566        assert!(SpatialCollect::try_new(point).is_err());
567
568        let multipoints = multipoint_column(vec![vec![(0.0, 0.0)]])?;
569        assert!(SpatialCollect::try_new(list(multipoints, &[0, 1])?).is_err());
570
571        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
572        assert!(
573            SpatialCollect
574                .return_dtype(
575                    &EmptyOptions,
576                    &[DType::List(primitive.into(), Nullability::NonNullable)]
577                )
578                .is_err()
579        );
580        Ok(())
581    }
582}