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