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_ensure_eq;
37use vortex_error::vortex_err;
38use vortex_mask::Mask;
39use vortex_session::VortexSession;
40use vortex_session::registry::CachedId;
41
42use crate::extension::Rect;
43use crate::extension::SpatialMetadata;
44use crate::extension::box_field_names;
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_eq!(
58        dtypes.len(),
59        1,
60        "spatial: envelope requires exactly one geometry operand"
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, unreferenced 2D box ([`Rect`], `geoarrow.box`). Rows with null or
90/// empty geometries produce null boxes.
91fn output_box_dtype() -> VortexResult<ExtDType<Rect>> {
92    ExtDType::<Rect>::try_new(
93        SpatialMetadata::default().with_dimension(Dimension::Xy),
94        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::coordinate::Dimension;
304    use crate::test_harness::linestring_column;
305    use crate::test_harness::multilinestring_column;
306    use crate::test_harness::multipoint_column;
307    use crate::test_harness::multipolygon_column;
308    use crate::test_harness::nullable_multipolygon_column;
309    use crate::test_harness::nullable_point_column;
310    use crate::test_harness::nullable_rect_column;
311    use crate::test_harness::point_column;
312    use crate::test_harness::polygon_column;
313    use crate::test_harness::rect_column;
314
315    /// Execute a `SpatialEnvelope` over `array`, returning the lazy box column.
316    fn boxes(array: ArrayRef) -> VortexResult<ArrayRef> {
317        Ok(SpatialEnvelope::try_new(array)?.into_array())
318    }
319
320    /// A point's box is degenerate: both corners are the point itself.
321    #[test]
322    fn point_box_is_degenerate() -> VortexResult<()> {
323        let session = crate::test_harness::spatial_session();
324        let mut ctx = session.create_execution_ctx();
325
326        let points = point_column(vec![1.0, 3.0], vec![2.0, 4.0])?;
327        let expected =
328            nullable_rect_column(vec![Some((1.0, 2.0, 1.0, 2.0)), Some((3.0, 4.0, 3.0, 4.0))])?;
329        assert_arrays_eq!(boxes(points)?, expected, &mut ctx);
330        Ok(())
331    }
332
333    /// A polygon's box is its extent: the min/max over every ring vertex, one box per row.
334    #[test]
335    fn polygon_box_is_extent() -> VortexResult<()> {
336        let session = crate::test_harness::spatial_session();
337        let mut ctx = session.create_execution_ctx();
338
339        let polygons = polygon_column(vec![
340            vec![vec![(0.0, 0.0), (4.0, 0.0), (2.0, 5.0)]],
341            vec![vec![(-3.0, 7.0), (-2.0, 7.0), (-2.0, 9.0), (-3.0, 9.0)]],
342        ])?;
343        let expected = nullable_rect_column(vec![
344            Some((0.0, 0.0, 4.0, 5.0)),
345            Some((-3.0, 7.0, -2.0, 9.0)),
346        ])?;
347        assert_arrays_eq!(boxes(polygons)?, expected, &mut ctx);
348        Ok(())
349    }
350
351    /// A `Rect` row is its own bounding box.
352    #[test]
353    fn rect_box_is_itself() -> VortexResult<()> {
354        let session = crate::test_harness::spatial_session();
355        let mut ctx = session.create_execution_ctx();
356
357        let rects = rect_column(vec![(0.0, 0.0, 2.0, 3.0), (-1.0, -1.0, 1.0, 1.0)])?;
358        let expected = nullable_rect_column(vec![
359            Some((0.0, 0.0, 2.0, 3.0)),
360            Some((-1.0, -1.0, 1.0, 1.0)),
361        ])?;
362        assert_arrays_eq!(boxes(rects)?, expected, &mut ctx);
363        Ok(())
364    }
365
366    /// The `Rect` fast path projects the 2-D corners by name, so a 3-D box — whose `zmin`/`zmax`
367    /// fields are interleaved between them in storage — yields its XY extent as a 2-D box.
368    #[test]
369    fn xyz_rect_drops_z_bounds() -> VortexResult<()> {
370        let session = crate::test_harness::spatial_session();
371        let mut ctx = session.create_execution_ctx();
372
373        let ordinate = |value: f64| PrimitiveArray::from_iter([value]).into_array();
374        let storage = StructArray::from_fields(&[
375            ("xmin", ordinate(0.0)),
376            ("ymin", ordinate(1.0)),
377            ("zmin", ordinate(-9.0)),
378            ("xmax", ordinate(2.0)),
379            ("ymax", ordinate(3.0)),
380            ("zmax", ordinate(9.0)),
381        ])?
382        .into_array();
383        let ext = ExtDType::<Rect>::try_new(
384            SpatialMetadata::default().with_dimension(Dimension::Xyz),
385            Nullability::NonNullable,
386        )?;
387        let rects = ExtensionArray::try_new(ext.erased(), storage)?.into_array();
388
389        let expected = nullable_rect_column(vec![Some((0.0, 1.0, 2.0, 3.0))])?;
390        assert_arrays_eq!(boxes(rects)?, expected, &mut ctx);
391        Ok(())
392    }
393
394    /// Every multi-vertex native type over the same vertex set yields that set's box, so the whole
395    /// type family is covered (`Point` has its own degenerate-box test above).
396    #[test]
397    fn covers_every_native_geometry_type() -> VortexResult<()> {
398        let session = crate::test_harness::spatial_session();
399        let mut ctx = session.create_execution_ctx();
400
401        let vertices = vec![(1.0, 2.0), (-1.0, 5.0), (3.0, 4.0)];
402        let columns = vec![
403            linestring_column(vec![vertices.clone()])?,
404            multipoint_column(vec![vertices.clone()])?,
405            polygon_column(vec![vec![vertices.clone()]])?,
406            multilinestring_column(vec![vec![vertices.clone()]])?,
407            multipolygon_column(vec![vec![vec![vertices]]])?,
408        ];
409        let expected = nullable_rect_column(vec![Some((-1.0, 2.0, 3.0, 5.0))])?;
410        for column in columns {
411            assert_arrays_eq!(boxes(column)?, expected.clone(), &mut ctx);
412        }
413        Ok(())
414    }
415
416    /// Intermediate list levels with more than one part per row keep coordinates attributed to
417    /// the right rows: row 0 owns two polygons (the first with two rings) whose extremes live in
418    /// the second polygon, so composed bounds diverging from loop positions shows up here.
419    #[test]
420    fn uneven_nesting_keeps_rows_aligned() -> VortexResult<()> {
421        let session = crate::test_harness::spatial_session();
422        let mut ctx = session.create_execution_ctx();
423
424        let multipolygons = multipolygon_column(vec![
425            vec![
426                vec![vec![(0.0, 0.0), (1.0, 1.0)], vec![(0.2, 0.2), (0.8, 0.8)]],
427                vec![vec![(5.0, -3.0), (6.0, 7.0)]],
428            ],
429            vec![vec![vec![(10.0, 10.0), (11.0, 12.0)]]],
430        ])?;
431        let expected = nullable_rect_column(vec![
432            Some((0.0, -3.0, 6.0, 7.0)),
433            Some((10.0, 10.0, 11.0, 12.0)),
434        ])?;
435        assert_arrays_eq!(boxes(multipolygons)?, expected, &mut ctx);
436        Ok(())
437    }
438
439    /// An empty geometry (here a zero-part multipolygon) has no extent and yields a null box; other
440    /// rows keep their boxes.
441    #[test]
442    fn empty_geometry_has_no_box() -> VortexResult<()> {
443        let session = crate::test_harness::spatial_session();
444        let mut ctx = session.create_execution_ctx();
445
446        let multipolygons = multipolygon_column(vec![
447            vec![vec![vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]]],
448            vec![],
449        ])?;
450        let expected = nullable_rect_column(vec![Some((0.0, 0.0, 1.0, 1.0)), None])?;
451        assert_arrays_eq!(boxes(multipolygons)?, expected, &mut ctx);
452        Ok(())
453    }
454
455    /// A geometry empty only at an inner level — here a polygon whose single ring has zero
456    /// vertices, in the first row — has no box, exactly like one empty at the outer level.
457    #[test]
458    fn inner_empty_ring_yields_null_box() -> VortexResult<()> {
459        let session = crate::test_harness::spatial_session();
460        let mut ctx = session.create_execution_ctx();
461
462        let polygons = polygon_column(vec![
463            vec![vec![]],
464            vec![vec![(1.0, 2.0), (3.0, 4.0), (1.0, 4.0)]],
465        ])?;
466        let expected = nullable_rect_column(vec![None, Some((1.0, 2.0, 3.0, 4.0))])?;
467        assert_arrays_eq!(boxes(polygons)?, expected, &mut ctx);
468        Ok(())
469    }
470
471    /// A sliced operand keeps per-row boxes aligned: coordinates outside the slice window (still
472    /// present in the sliced list's element buffer) must not leak into any row's box.
473    #[test]
474    fn sliced_operand_ignores_out_of_slice_coordinates() -> VortexResult<()> {
475        let session = crate::test_harness::spatial_session();
476        let mut ctx = session.create_execution_ctx();
477
478        let multipoints = multipoint_column(vec![
479            vec![(-100.0, -100.0), (100.0, 100.0)],
480            vec![(1.0, 2.0), (3.0, 4.0)],
481            vec![(5.0, 6.0)],
482        ])?;
483        let expected =
484            nullable_rect_column(vec![Some((1.0, 2.0, 3.0, 4.0)), Some((5.0, 6.0, 5.0, 6.0))])?;
485        assert_arrays_eq!(boxes(multipoints.slice(1..3)?)?, expected, &mut ctx);
486        Ok(())
487    }
488
489    /// The zero-copy point fast path respects slicing: corners come from the slice window only.
490    #[test]
491    fn sliced_point_column_keeps_rows_aligned() -> VortexResult<()> {
492        let session = crate::test_harness::spatial_session();
493        let mut ctx = session.create_execution_ctx();
494
495        let points = point_column(vec![9.0, 1.0, 3.0], vec![8.0, 2.0, 4.0])?;
496        let expected =
497            nullable_rect_column(vec![Some((1.0, 2.0, 1.0, 2.0)), Some((3.0, 4.0, 3.0, 4.0))])?;
498        assert_arrays_eq!(boxes(points.slice(1..3)?)?, expected, &mut ctx);
499        Ok(())
500    }
501
502    /// A null geometry row yields a null box, just like an empty geometry; valid rows keep theirs.
503    #[test]
504    fn null_row_yields_null_box() -> VortexResult<()> {
505        let session = crate::test_harness::spatial_session();
506        let mut ctx = session.create_execution_ctx();
507
508        let points = nullable_point_column(vec![Some((1.0, 2.0)), None, Some((3.0, 4.0))])?;
509        let expected = nullable_rect_column(vec![
510            Some((1.0, 2.0, 1.0, 2.0)),
511            None,
512            Some((3.0, 4.0, 3.0, 4.0)),
513        ])?;
514        assert_arrays_eq!(boxes(points)?, expected, &mut ctx);
515        Ok(())
516    }
517
518    /// Valid, empty, and null rows stay positionally aligned: the valid row keeps its box, and the
519    /// empty and null rows are both null.
520    #[test]
521    fn mixed_valid_empty_null_rows_align() -> VortexResult<()> {
522        let session = crate::test_harness::spatial_session();
523        let mut ctx = session.create_execution_ctx();
524
525        let multipolygons = nullable_multipolygon_column(vec![
526            Some(vec![vec![vec![
527                (0.0, 0.0),
528                (1.0, 0.0),
529                (1.0, 1.0),
530                (0.0, 1.0),
531            ]]]),
532            Some(vec![]),
533            None,
534        ])?;
535        let expected = nullable_rect_column(vec![Some((0.0, 0.0, 1.0, 1.0)), None, None])?;
536        assert_arrays_eq!(boxes(multipolygons)?, expected, &mut ctx);
537        Ok(())
538    }
539
540    /// A constant-null operand yields an all-null box column.
541    #[test]
542    fn constant_null_is_all_null() -> VortexResult<()> {
543        let session = crate::test_harness::spatial_session();
544        let mut ctx = session.create_execution_ctx();
545
546        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
547        let null_const = ConstantArray::new(Scalar::null(point_dtype), 2).into_array();
548        let expected = nullable_rect_column(vec![None, None])?;
549        assert_arrays_eq!(boxes(null_const)?, expected, &mut ctx);
550        Ok(())
551    }
552
553    /// A non-null constant is boxed once and retained as a constant output.
554    #[test]
555    fn constant_point_remains_constant() -> VortexResult<()> {
556        let session = crate::test_harness::spatial_session();
557        let mut ctx = session.create_execution_ctx();
558
559        let scalar = point_column(vec![1.0], vec![2.0])?.execute_scalar(0, &mut ctx)?;
560        let points = ConstantArray::new(scalar, 3).into_array();
561        let result = boxes(points)?.execute::<Columnar>(&mut ctx)?;
562        let Columnar::Constant(boxes) = result else {
563            return Err(vortex_err!("envelope of a constant should remain constant"));
564        };
565        assert_eq!(boxes.len(), 3);
566
567        let expected = nullable_rect_column(vec![Some((1.0, 2.0, 1.0, 2.0)); 3])?;
568        assert_arrays_eq!(boxes.into_array(), expected, &mut ctx);
569        Ok(())
570    }
571
572    /// Output is always nullable, even over a non-nullable operand, since an empty geometry has no
573    /// box.
574    #[test]
575    fn output_is_always_nullable() -> VortexResult<()> {
576        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
577        assert!(!dtype.is_nullable());
578        let out = SpatialEnvelope.return_dtype(&EmptyOptions, &[dtype])?;
579        assert!(out.is_nullable());
580        Ok(())
581    }
582
583    /// A non-geometry operand dtype is rejected up front, before execution.
584    #[test]
585    fn non_geometry_operand_is_rejected() -> VortexResult<()> {
586        let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
587        assert!(
588            SpatialEnvelope
589                .return_dtype(&EmptyOptions, &[numeric])
590                .is_err()
591        );
592        Ok(())
593    }
594}