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