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