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 std::sync::LazyLock;
319
320    use rstest::rstest;
321    use vortex_array::ArrayRef;
322    use vortex_array::Columnar;
323    use vortex_array::IntoArray;
324    use vortex_array::VortexSessionExecute;
325    use vortex_array::arrays::ConstantArray;
326    use vortex_array::arrays::ExtensionArray;
327    use vortex_array::arrays::ListArray;
328    use vortex_array::arrays::ListViewArray;
329    use vortex_array::arrays::MaskedArray;
330    use vortex_array::arrays::PrimitiveArray;
331    use vortex_array::arrays::extension::ExtensionArrayExt;
332    use vortex_array::arrays::listview::ListViewArraySlotsExt;
333    use vortex_array::assert_arrays_eq;
334    use vortex_array::dtype::DType;
335    use vortex_array::dtype::Nullability;
336    use vortex_array::dtype::PType;
337    use vortex_array::scalar_fn::EmptyOptions;
338    use vortex_array::scalar_fn::ScalarFnVTable;
339    use vortex_array::validity::Validity;
340    use vortex_error::VortexResult;
341    use vortex_error::vortex_err;
342    use vortex_session::VortexSession;
343
344    use super::SpatialCollect;
345    use crate::test_harness::linestring_column;
346    use crate::test_harness::multilinestring_column;
347    use crate::test_harness::multipoint_column;
348    use crate::test_harness::multipolygon_column;
349    use crate::test_harness::nullable_point_column;
350    use crate::test_harness::point_column;
351    use crate::test_harness::polygon_column;
352
353    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
354
355    fn list_with_validity(
356        elements: ArrayRef,
357        offsets: &[u32],
358        validity: Validity,
359    ) -> VortexResult<ArrayRef> {
360        let mut ctx = SESSION.create_execution_ctx();
361        Ok(ListArray::try_new(
362            elements,
363            PrimitiveArray::from_iter(offsets.iter().copied()).into_array(),
364            validity,
365            &mut ctx,
366        )?
367        .into_array())
368    }
369
370    fn list(elements: ArrayRef, offsets: &[u32]) -> VortexResult<ArrayRef> {
371        list_with_validity(elements, offsets, Validity::NonNullable)
372    }
373
374    /// Assert that `ST_Collect` of `input` equals `expected`.
375    fn assert_collects(input: ArrayRef, expected: ArrayRef) -> VortexResult<()> {
376        let mut ctx = SESSION.create_execution_ctx();
377        let result = SpatialCollect::try_new(input)?.into_array();
378
379        assert_arrays_eq!(result, expected, &mut ctx);
380        Ok(())
381    }
382
383    #[test]
384    fn collects_points_into_multipoints() -> VortexResult<()> {
385        let points = point_column(vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0])?;
386        let input = list(points, &[0, 2, 3])?;
387        let expected = multipoint_column(vec![vec![(0.0, 3.0), (1.0, 4.0)], vec![(2.0, 5.0)]])?;
388
389        assert_collects(input, expected)
390    }
391
392    /// Out-of-order rows make the view non-exact. `compact_row_views` derives offsets from `sizes`
393    /// alone, which only holds after `MakeExact` reorders the elements.
394    #[test]
395    fn collects_out_of_order_list_views() -> VortexResult<()> {
396        let mut ctx = SESSION.create_execution_ctx();
397        let points = nullable_point_column(vec![
398            Some((0.0, 4.0)),
399            None,
400            Some((2.0, 6.0)),
401            Some((3.0, 7.0)),
402        ])?;
403        let views = ListViewArray::try_new(
404            points,
405            PrimitiveArray::from_iter([2u32, 0]).into_array(),
406            PrimitiveArray::from_iter([2u32, 2]).into_array(),
407            Validity::NonNullable,
408            &mut ctx,
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 = 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 = 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 = 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 mut ctx = SESSION.create_execution_ctx();
552        let input = list_with_validity(
553            point_column(vec![0.0, 1.0], vec![2.0, 3.0])?,
554            &[0, 1, 2],
555            Validity::from_iter([true, false]),
556        )?;
557        let expected = MaskedArray::try_new(
558            multipoint_column(vec![vec![(0.0, 2.0)], vec![(1.0, 3.0)]])?,
559            Validity::from_iter([true, false]),
560            &mut ctx,
561        )?
562        .into_array();
563
564        assert_collects(input, expected)
565    }
566
567    #[test]
568    fn rejects_unsupported_inputs() -> VortexResult<()> {
569        let point = point_column(vec![0.0], vec![0.0])?;
570        assert!(SpatialCollect::try_new(point).is_err());
571
572        let multipoints = multipoint_column(vec![vec![(0.0, 0.0)]])?;
573        assert!(SpatialCollect::try_new(list(multipoints, &[0, 1])?).is_err());
574
575        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
576        assert!(
577            SpatialCollect
578                .return_dtype(
579                    &EmptyOptions,
580                    &[DType::List(primitive.into(), Nullability::NonNullable)]
581                )
582                .is_err()
583        );
584        Ok(())
585    }
586}