Skip to main content

vortex_spatial/scalar_fn/
envelope.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! `envelope`: the per-row 2-D axis-aligned bounding box (AABB) of a native geometry column.
5//!
6//! A row-oriented consumer (e.g. bulk-loading an in-memory R-tree in a spatial-join operator)
7//! reads the resulting box column back row by row.
8
9use vortex_array::ArrayRef;
10use vortex_array::ExecutionCtx;
11use vortex_array::IntoArray;
12use vortex_array::arrays::ConstantArray;
13use vortex_array::arrays::ExtensionArray;
14use vortex_array::arrays::ScalarFnArray;
15use vortex_array::arrays::StructArray;
16use vortex_array::arrays::extension::ExtensionArrayExt;
17use vortex_array::arrays::struct_::StructArrayExt;
18use vortex_array::dtype::DType;
19use vortex_array::dtype::Nullability;
20use vortex_array::dtype::extension::ExtDType;
21use vortex_array::expr::Expression;
22use vortex_array::scalar::Scalar;
23use vortex_array::scalar_fn::Arity;
24use vortex_array::scalar_fn::ChildName;
25use vortex_array::scalar_fn::EmptyOptions;
26use vortex_array::scalar_fn::ExecutionArgs;
27use vortex_array::scalar_fn::ScalarFnId;
28use vortex_array::scalar_fn::ScalarFnVTable;
29use vortex_array::scalar_fn::TypedScalarFnInstance;
30use vortex_array::validity::Validity;
31use vortex_buffer::BitBuffer;
32use vortex_buffer::BufferMut;
33use vortex_error::VortexResult;
34use vortex_error::vortex_ensure;
35use vortex_error::vortex_err;
36use vortex_mask::Mask;
37use vortex_session::VortexSession;
38use vortex_session::registry::CachedId;
39
40use crate::extension::Rect;
41use crate::extension::SpatialMetadata;
42use crate::extension::box_field_names;
43use crate::extension::box_storage_dtype;
44use crate::extension::build_rect_array;
45use crate::extension::coordinate::Dimension;
46use crate::extension::coordinate::box_corners;
47use crate::extension::coordinate::ordinates;
48use crate::extension::flatten_row_offsets;
49use crate::extension::is_native_geometry;
50use crate::scalar_fn::execute::Execution;
51use crate::scalar_fn::execute::Operand;
52use crate::scalar_fn::execute::dispatch_unary;
53
54/// Validate the native geometry operand accepted by `envelope`.
55fn validate_envelope_operands(dtypes: &[DType]) -> VortexResult<()> {
56    vortex_ensure!(
57        dtypes.len() == 1,
58        "spatial: envelope requires exactly one geometry operand, got {}",
59        dtypes.len()
60    );
61    vortex_ensure!(
62        is_native_geometry(&dtypes[0]),
63        "spatial: envelope operand {} is not a native geometry type",
64        dtypes[0]
65    );
66    Ok(())
67}
68
69/// `envelope`: the axis-aligned bounding box of each geometry in a native geometry operand (a column
70/// or a constant literal), as a native 2-D `geoarrow.box` ([`Rect`]) column.
71///
72/// 2-D only: only the `x`/`y` leaf ordinates are read, so any `z`/`m` are ignored and each box is
73/// the XY extent — matching the [`GeometryAabb`](crate::aggregate_fn::GeometryAabb) aggregate.
74#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
75pub struct SpatialEnvelope;
76
77impl SpatialEnvelope {
78    /// A lazy `ScalarFnArray` computing the per-row bounding box of geometry operand `a`, which may
79    /// be constant. The output length is taken from `a`.
80    pub fn try_new(a: ArrayRef) -> VortexResult<ScalarFnArray> {
81        ScalarFnArray::try_new(
82            TypedScalarFnInstance::new(SpatialEnvelope, EmptyOptions).erased(),
83            vec![a],
84        )
85    }
86}
87
88/// The output dtype: a nullable native 2-D box ([`Rect`], `geoarrow.box`) column. Nullable
89/// because rows without a box — null or empty geometries — are null. Metadata is defaulted.
90fn output_box_dtype() -> VortexResult<ExtDType<Rect>> {
91    ExtDType::<Rect>::try_new(
92        SpatialMetadata::default(),
93        box_storage_dtype(Dimension::Xy, Nullability::Nullable),
94    )
95}
96
97/// Compute each row's 2-D bounding box: the smallest rectangle covering all of the row's
98/// coordinates.
99fn row_boxes(
100    storage: ArrayRef,
101    valid: &Mask,
102    ctx: &mut ExecutionCtx,
103) -> VortexResult<(Vec<ArrayRef>, Validity)> {
104    let len = storage.len();
105    let (row_offsets, coords) = flatten_row_offsets(storage, ctx)?;
106
107    // A row has a box iff it is valid and owns at least one coordinate (an empty geometry has
108    // no box). Two masks combined word-at-a-time: folding `valid` into the closure instead —
109    // per-index or via `Mask::iter` — benches 6-33% slower end-to-end.
110    let non_empty = Mask::from(BitBuffer::collect_bool(len, |r| {
111        row_offsets[r] < row_offsets[r + 1]
112    }));
113    let xs = ordinates(&coords, "x", ctx)?;
114    let ys = ordinates(&coords, "y", ctx)?;
115
116    // The output's four corner columns.
117    let mut xmins = BufferMut::zeroed(len);
118    let mut ymins = BufferMut::zeroed(len);
119    let mut xmaxs = BufferMut::zeroed(len);
120    let mut ymaxs = BufferMut::zeroed(len);
121
122    for (r, (&start, &end)) in row_offsets.iter().zip(&row_offsets[1..]).enumerate() {
123        let [xmin, ymin, xmax, ymax] = box_corners(&xs[start..end], &ys[start..end]);
124        xmins[r] = xmin;
125        ymins[r] = ymin;
126        xmaxs[r] = xmax;
127        ymaxs[r] = ymax;
128    }
129
130    Ok((
131        vec![
132            xmins.freeze().into_array(),
133            ymins.freeze().into_array(),
134            xmaxs.freeze().into_array(),
135            ymaxs.freeze().into_array(),
136        ],
137        Validity::from_mask(valid & &non_empty, Nullability::Nullable),
138    ))
139}
140
141/// Compute boxes directly over a non-constant native geometry column.
142fn envelope_array(
143    array: ArrayRef,
144    validity: Validity,
145    output_dtype: &ExtDType<Rect>,
146    ctx: &mut ExecutionCtx,
147) -> VortexResult<ArrayRef> {
148    let len = array.len();
149    let is_rect = array
150        .dtype()
151        .as_extension_opt()
152        .ok_or_else(|| vortex_err!("spatial: envelope operand is not a geometry extension type"))?
153        .is::<Rect>();
154    let storage = array
155        .execute::<ExtensionArray>(ctx)?
156        .storage_array()
157        .clone();
158
159    let (corners, output_validity) = if is_rect {
160        // A box is its own envelope: project the 2-D corner fields straight out of storage
161        // (dropping any z/m bounds). A stored box cannot be empty.
162        let coords = storage.execute::<StructArray>(ctx)?;
163        let corners = box_field_names(Dimension::Xy)
164            .iter()
165            .map(|name| coords.unmasked_field_by_name(name).cloned())
166            .collect::<VortexResult<Vec<_>>>()?;
167        (corners, validity.into_nullable())
168    } else if !storage.dtype().is_list() {
169        // Point storage is the coordinate `Struct` itself: every row owns exactly one
170        // coordinate, so its box is degenerate and the corner columns are zero-copy projections.
171        let coords = storage.execute::<StructArray>(ctx)?;
172        let x = coords.unmasked_field_by_name("x")?.clone();
173        let y = coords.unmasked_field_by_name("y")?.clone();
174        (vec![x.clone(), y.clone(), x, y], validity.into_nullable())
175    } else {
176        let valid = validity.execute_mask(len, ctx)?;
177        if len != 0 && valid.all_false() {
178            return Ok(ConstantArray::new(
179                Scalar::null(DType::Extension(output_dtype.clone().erased())),
180                len,
181            )
182            .into_array());
183        }
184        row_boxes(storage, &valid, ctx)?
185    };
186
187    build_rect_array(output_dtype, corners, len, output_validity)
188}
189
190/// Execute `envelope` after shared constant/column and null dispatch.
191fn execute_envelope(
192    execution: Execution<1, Validity>,
193    output_dtype: &ExtDType<Rect>,
194    ctx: &mut ExecutionCtx,
195) -> VortexResult<ArrayRef> {
196    match execution.operands {
197        [Operand::Constant(scalar)] => {
198            let one = ConstantArray::new(scalar, 1).into_array();
199            let output = envelope_array(one, Validity::AllValid, output_dtype, ctx)?;
200            Ok(ConstantArray::new(output.execute_scalar(0, ctx)?, execution.len).into_array())
201        }
202        [Operand::Column(array)] => envelope_array(array, execution.valid, output_dtype, ctx),
203    }
204}
205
206impl ScalarFnVTable for SpatialEnvelope {
207    type Options = EmptyOptions;
208
209    fn id(&self) -> ScalarFnId {
210        static ID: CachedId = CachedId::new("vortex.st.envelope");
211        *ID
212    }
213
214    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
215        Ok(Some(vec![]))
216    }
217
218    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
219        Ok(EmptyOptions)
220    }
221
222    fn arity(&self, _: &Self::Options) -> Arity {
223        Arity::Exact(1)
224    }
225
226    fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName {
227        match child_idx {
228            0 => ChildName::from("geometry"),
229            _ => unreachable!("envelope has exactly one child"),
230        }
231    }
232
233    fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult<DType> {
234        validate_envelope_operands(dtypes)?;
235        // Always nullable: an empty geometry has no box, so nulls can appear even over a
236        // non-nullable operand.
237        Ok(DType::Extension(output_box_dtype()?.erased()))
238    }
239
240    /// Compute each row's box directly over the native coordinate storage — no decode to
241    /// `geo_types`, no Arrow round-trip. A null row, or a valid row that owns no coordinate (an
242    /// empty geometry), yields a null box.
243    fn execute(
244        &self,
245        _: &Self::Options,
246        args: &dyn ExecutionArgs,
247        ctx: &mut ExecutionCtx,
248    ) -> VortexResult<ArrayRef> {
249        let array = args.get(0)?;
250        let output_dtype = output_box_dtype()?;
251        dispatch_unary(
252            &array,
253            DType::Extension(output_dtype.clone().erased()),
254            |execution, ctx| execute_envelope(execution, &output_dtype, ctx),
255            ctx,
256        )
257    }
258
259    fn validity(&self, _: &Self::Options, _: &Expression) -> VortexResult<Option<Expression>> {
260        // The output null mask is not derivable from the operand's validity alone: an empty
261        // geometry yields a null box even where the operand is valid. Let the planner execute.
262        Ok(None)
263    }
264
265    fn is_strict(&self, _: &Self::Options) -> bool {
266        true
267    }
268
269    fn is_infallible(&self, _: &Self::Options) -> bool {
270        true
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use vortex_array::ArrayRef;
277    use vortex_array::Columnar;
278    use vortex_array::IntoArray;
279    use vortex_array::VortexSessionExecute;
280    use vortex_array::arrays::ConstantArray;
281    use vortex_array::arrays::ExtensionArray;
282    use vortex_array::arrays::PrimitiveArray;
283    use vortex_array::arrays::StructArray;
284    use vortex_array::assert_arrays_eq;
285    use vortex_array::dtype::DType;
286    use vortex_array::dtype::Nullability;
287    use vortex_array::dtype::PType;
288    use vortex_array::dtype::extension::ExtDType;
289    use vortex_array::scalar::Scalar;
290    use vortex_array::scalar_fn::EmptyOptions;
291    use vortex_array::scalar_fn::ScalarFnVTable;
292    use vortex_error::VortexResult;
293    use vortex_error::vortex_err;
294
295    use super::SpatialEnvelope;
296    use crate::extension::Rect;
297    use crate::extension::SpatialMetadata;
298    use crate::extension::box_storage_dtype;
299    use crate::extension::coordinate::Dimension;
300    use crate::test_harness::linestring_column;
301    use crate::test_harness::multilinestring_column;
302    use crate::test_harness::multipoint_column;
303    use crate::test_harness::multipolygon_column;
304    use crate::test_harness::nullable_multipolygon_column;
305    use crate::test_harness::nullable_point_column;
306    use crate::test_harness::nullable_rect_column;
307    use crate::test_harness::point_column;
308    use crate::test_harness::polygon_column;
309    use crate::test_harness::rect_column;
310
311    /// Execute a `SpatialEnvelope` over `array`, returning the lazy box column.
312    fn boxes(array: ArrayRef) -> VortexResult<ArrayRef> {
313        Ok(SpatialEnvelope::try_new(array)?.into_array())
314    }
315
316    /// A point's box is degenerate: both corners are the point itself.
317    #[test]
318    fn point_box_is_degenerate() -> VortexResult<()> {
319        let session = crate::test_harness::spatial_session();
320        let mut ctx = session.create_execution_ctx();
321
322        let points = point_column(vec![1.0, 3.0], vec![2.0, 4.0])?;
323        let expected =
324            nullable_rect_column(vec![Some((1.0, 2.0, 1.0, 2.0)), Some((3.0, 4.0, 3.0, 4.0))])?;
325        assert_arrays_eq!(boxes(points)?, expected, &mut ctx);
326        Ok(())
327    }
328
329    /// A polygon's box is its extent: the min/max over every ring vertex, one box per row.
330    #[test]
331    fn polygon_box_is_extent() -> VortexResult<()> {
332        let session = crate::test_harness::spatial_session();
333        let mut ctx = session.create_execution_ctx();
334
335        let polygons = polygon_column(vec![
336            vec![vec![(0.0, 0.0), (4.0, 0.0), (2.0, 5.0)]],
337            vec![vec![(-3.0, 7.0), (-2.0, 7.0), (-2.0, 9.0), (-3.0, 9.0)]],
338        ])?;
339        let expected = nullable_rect_column(vec![
340            Some((0.0, 0.0, 4.0, 5.0)),
341            Some((-3.0, 7.0, -2.0, 9.0)),
342        ])?;
343        assert_arrays_eq!(boxes(polygons)?, expected, &mut ctx);
344        Ok(())
345    }
346
347    /// A `Rect` row is its own bounding box.
348    #[test]
349    fn rect_box_is_itself() -> VortexResult<()> {
350        let session = crate::test_harness::spatial_session();
351        let mut ctx = session.create_execution_ctx();
352
353        let rects = rect_column(vec![(0.0, 0.0, 2.0, 3.0), (-1.0, -1.0, 1.0, 1.0)])?;
354        let expected = nullable_rect_column(vec![
355            Some((0.0, 0.0, 2.0, 3.0)),
356            Some((-1.0, -1.0, 1.0, 1.0)),
357        ])?;
358        assert_arrays_eq!(boxes(rects)?, expected, &mut ctx);
359        Ok(())
360    }
361
362    /// The `Rect` fast path projects the 2-D corners by name, so a 3-D box — whose `zmin`/`zmax`
363    /// fields are interleaved between them in storage — yields its XY extent as a 2-D box.
364    #[test]
365    fn xyz_rect_drops_z_bounds() -> VortexResult<()> {
366        let session = crate::test_harness::spatial_session();
367        let mut ctx = session.create_execution_ctx();
368
369        let ordinate = |value: f64| PrimitiveArray::from_iter([value]).into_array();
370        let storage = StructArray::from_fields(&[
371            ("xmin", ordinate(0.0)),
372            ("ymin", ordinate(1.0)),
373            ("zmin", ordinate(-9.0)),
374            ("xmax", ordinate(2.0)),
375            ("ymax", ordinate(3.0)),
376            ("zmax", ordinate(9.0)),
377        ])?
378        .into_array();
379        let ext = ExtDType::<Rect>::try_new(
380            SpatialMetadata::default(),
381            box_storage_dtype(Dimension::Xyz, Nullability::NonNullable),
382        )?;
383        let rects = ExtensionArray::try_new(ext.erased(), storage)?.into_array();
384
385        let expected = nullable_rect_column(vec![Some((0.0, 1.0, 2.0, 3.0))])?;
386        assert_arrays_eq!(boxes(rects)?, expected, &mut ctx);
387        Ok(())
388    }
389
390    /// Every multi-vertex native type over the same vertex set yields that set's box, so the whole
391    /// type family is covered (`Point` has its own degenerate-box test above).
392    #[test]
393    fn covers_every_native_geometry_type() -> VortexResult<()> {
394        let session = crate::test_harness::spatial_session();
395        let mut ctx = session.create_execution_ctx();
396
397        let vertices = vec![(1.0, 2.0), (-1.0, 5.0), (3.0, 4.0)];
398        let columns = vec![
399            linestring_column(vec![vertices.clone()])?,
400            multipoint_column(vec![vertices.clone()])?,
401            polygon_column(vec![vec![vertices.clone()]])?,
402            multilinestring_column(vec![vec![vertices.clone()]])?,
403            multipolygon_column(vec![vec![vec![vertices]]])?,
404        ];
405        let expected = nullable_rect_column(vec![Some((-1.0, 2.0, 3.0, 5.0))])?;
406        for column in columns {
407            assert_arrays_eq!(boxes(column)?, expected.clone(), &mut ctx);
408        }
409        Ok(())
410    }
411
412    /// Intermediate list levels with more than one part per row keep coordinates attributed to
413    /// the right rows: row 0 owns two polygons (the first with two rings) whose extremes live in
414    /// the second polygon, so composed bounds diverging from loop positions shows up here.
415    #[test]
416    fn uneven_nesting_keeps_rows_aligned() -> VortexResult<()> {
417        let session = crate::test_harness::spatial_session();
418        let mut ctx = session.create_execution_ctx();
419
420        let multipolygons = multipolygon_column(vec![
421            vec![
422                vec![vec![(0.0, 0.0), (1.0, 1.0)], vec![(0.2, 0.2), (0.8, 0.8)]],
423                vec![vec![(5.0, -3.0), (6.0, 7.0)]],
424            ],
425            vec![vec![vec![(10.0, 10.0), (11.0, 12.0)]]],
426        ])?;
427        let expected = nullable_rect_column(vec![
428            Some((0.0, -3.0, 6.0, 7.0)),
429            Some((10.0, 10.0, 11.0, 12.0)),
430        ])?;
431        assert_arrays_eq!(boxes(multipolygons)?, expected, &mut ctx);
432        Ok(())
433    }
434
435    /// An empty geometry (here a zero-part multipolygon) has no extent and yields a null box; other
436    /// rows keep their boxes.
437    #[test]
438    fn empty_geometry_has_no_box() -> VortexResult<()> {
439        let session = crate::test_harness::spatial_session();
440        let mut ctx = session.create_execution_ctx();
441
442        let multipolygons = multipolygon_column(vec![
443            vec![vec![vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]]],
444            vec![],
445        ])?;
446        let expected = nullable_rect_column(vec![Some((0.0, 0.0, 1.0, 1.0)), None])?;
447        assert_arrays_eq!(boxes(multipolygons)?, expected, &mut ctx);
448        Ok(())
449    }
450
451    /// A geometry empty only at an inner level — here a polygon whose single ring has zero
452    /// vertices, in the first row — has no box, exactly like one empty at the outer level.
453    #[test]
454    fn inner_empty_ring_yields_null_box() -> VortexResult<()> {
455        let session = crate::test_harness::spatial_session();
456        let mut ctx = session.create_execution_ctx();
457
458        let polygons = polygon_column(vec![
459            vec![vec![]],
460            vec![vec![(1.0, 2.0), (3.0, 4.0), (1.0, 4.0)]],
461        ])?;
462        let expected = nullable_rect_column(vec![None, Some((1.0, 2.0, 3.0, 4.0))])?;
463        assert_arrays_eq!(boxes(polygons)?, expected, &mut ctx);
464        Ok(())
465    }
466
467    /// A sliced operand keeps per-row boxes aligned: coordinates outside the slice window (still
468    /// present in the sliced list's element buffer) must not leak into any row's box.
469    #[test]
470    fn sliced_operand_ignores_out_of_slice_coordinates() -> VortexResult<()> {
471        let session = crate::test_harness::spatial_session();
472        let mut ctx = session.create_execution_ctx();
473
474        let multipoints = multipoint_column(vec![
475            vec![(-100.0, -100.0), (100.0, 100.0)],
476            vec![(1.0, 2.0), (3.0, 4.0)],
477            vec![(5.0, 6.0)],
478        ])?;
479        let expected =
480            nullable_rect_column(vec![Some((1.0, 2.0, 3.0, 4.0)), Some((5.0, 6.0, 5.0, 6.0))])?;
481        assert_arrays_eq!(boxes(multipoints.slice(1..3)?)?, expected, &mut ctx);
482        Ok(())
483    }
484
485    /// The zero-copy point fast path respects slicing: corners come from the slice window only.
486    #[test]
487    fn sliced_point_column_keeps_rows_aligned() -> VortexResult<()> {
488        let session = crate::test_harness::spatial_session();
489        let mut ctx = session.create_execution_ctx();
490
491        let points = point_column(vec![9.0, 1.0, 3.0], vec![8.0, 2.0, 4.0])?;
492        let expected =
493            nullable_rect_column(vec![Some((1.0, 2.0, 1.0, 2.0)), Some((3.0, 4.0, 3.0, 4.0))])?;
494        assert_arrays_eq!(boxes(points.slice(1..3)?)?, expected, &mut ctx);
495        Ok(())
496    }
497
498    /// A null geometry row yields a null box, just like an empty geometry; valid rows keep theirs.
499    #[test]
500    fn null_row_yields_null_box() -> VortexResult<()> {
501        let session = crate::test_harness::spatial_session();
502        let mut ctx = session.create_execution_ctx();
503
504        let points = nullable_point_column(vec![Some((1.0, 2.0)), None, Some((3.0, 4.0))])?;
505        let expected = nullable_rect_column(vec![
506            Some((1.0, 2.0, 1.0, 2.0)),
507            None,
508            Some((3.0, 4.0, 3.0, 4.0)),
509        ])?;
510        assert_arrays_eq!(boxes(points)?, expected, &mut ctx);
511        Ok(())
512    }
513
514    /// Valid, empty, and null rows stay positionally aligned: the valid row keeps its box, and the
515    /// empty and null rows are both null.
516    #[test]
517    fn mixed_valid_empty_null_rows_align() -> VortexResult<()> {
518        let session = crate::test_harness::spatial_session();
519        let mut ctx = session.create_execution_ctx();
520
521        let multipolygons = nullable_multipolygon_column(vec![
522            Some(vec![vec![vec![
523                (0.0, 0.0),
524                (1.0, 0.0),
525                (1.0, 1.0),
526                (0.0, 1.0),
527            ]]]),
528            Some(vec![]),
529            None,
530        ])?;
531        let expected = nullable_rect_column(vec![Some((0.0, 0.0, 1.0, 1.0)), None, None])?;
532        assert_arrays_eq!(boxes(multipolygons)?, expected, &mut ctx);
533        Ok(())
534    }
535
536    /// A constant-null operand yields an all-null box column.
537    #[test]
538    fn constant_null_is_all_null() -> VortexResult<()> {
539        let session = crate::test_harness::spatial_session();
540        let mut ctx = session.create_execution_ctx();
541
542        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
543        let null_const = ConstantArray::new(Scalar::null(point_dtype), 2).into_array();
544        let expected = nullable_rect_column(vec![None, None])?;
545        assert_arrays_eq!(boxes(null_const)?, expected, &mut ctx);
546        Ok(())
547    }
548
549    /// A non-null constant is boxed once and retained as a constant output.
550    #[test]
551    fn constant_point_remains_constant() -> VortexResult<()> {
552        let session = crate::test_harness::spatial_session();
553        let mut ctx = session.create_execution_ctx();
554
555        let scalar = point_column(vec![1.0], vec![2.0])?.execute_scalar(0, &mut ctx)?;
556        let points = ConstantArray::new(scalar, 3).into_array();
557        let result = boxes(points)?.execute::<Columnar>(&mut ctx)?;
558        let Columnar::Constant(boxes) = result else {
559            return Err(vortex_err!("envelope of a constant should remain constant"));
560        };
561        assert_eq!(boxes.len(), 3);
562
563        let expected = nullable_rect_column(vec![Some((1.0, 2.0, 1.0, 2.0)); 3])?;
564        assert_arrays_eq!(boxes.into_array(), expected, &mut ctx);
565        Ok(())
566    }
567
568    /// Output is always nullable, even over a non-nullable operand, since an empty geometry has no
569    /// box.
570    #[test]
571    fn output_is_always_nullable() -> VortexResult<()> {
572        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
573        assert!(!dtype.is_nullable());
574        let out = SpatialEnvelope.return_dtype(&EmptyOptions, &[dtype])?;
575        assert!(out.is_nullable());
576        Ok(())
577    }
578
579    /// A non-geometry operand dtype is rejected up front, before execution.
580    #[test]
581    fn non_geometry_operand_is_rejected() -> VortexResult<()> {
582        let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
583        assert!(
584            SpatialEnvelope
585                .return_dtype(&EmptyOptions, &[numeric])
586                .is_err()
587        );
588        Ok(())
589    }
590}