Skip to main content

vortex_spatial/prune/
distance.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! `ST_Distance(geom, const) <op> radius` pruning.
5
6use geo::Rect as SpatialRect;
7use vortex_array::expr::BoundExpression;
8use vortex_array::scalar_fn::ScalarFnId;
9use vortex_array::scalar_fn::ScalarFnVTable;
10use vortex_array::scalar_fn::fns::binary::Binary;
11use vortex_array::scalar_fn::fns::literal::Literal;
12use vortex_array::scalar_fn::fns::operators::Operator;
13use vortex_array::stats::rewrite::StatsRewriteRule;
14use vortex_error::VortexResult;
15use vortex_session::VortexSession;
16
17use super::aabb_stat;
18use super::geometry_and_constant;
19use super::gt;
20use super::gt_eq;
21use super::lit;
22use super::lt;
23use super::lt_eq;
24use super::max_dist_sq;
25use super::min_dist_sq;
26use super::query_aabb;
27use crate::scalar_fn::distance::SpatialDistance;
28
29/// Prunes chunks for `ST_Distance(geom, const) <op> r` filters.
30///
31/// All four comparisons prune: `<= r` / `< r` skip a chunk whose box is wholly beyond `r` (box
32/// min-distance); `>= r` / `> r` skip one wholly within `r` (box max-distance). `==` / `!=` don't
33/// prune.
34#[derive(Debug)]
35pub struct SpatialDistancePrune;
36
37impl StatsRewriteRule for SpatialDistancePrune {
38    fn scalar_fn_id(&self) -> ScalarFnId {
39        // The predicate root is the comparison, not `SpatialDistance`, so key on `Binary`.
40        Binary.id()
41    }
42
43    fn falsify(
44        &self,
45        expr: &BoundExpression,
46        session: &VortexSession,
47    ) -> VortexResult<Option<BoundExpression>> {
48        // Only the ordered comparisons prune today. `== r` could prune in the future (a chunk is
49        // provably empty when `r` lies outside its box's [min, max] distance interval), it's just
50        // not implemented. `!= r` cannot: pruning would need every row's distance to equal `r`,
51        // which an AABB can't prove.
52        let op = *expr.as_::<Binary>();
53        if !matches!(
54            op,
55            Operator::Lte | Operator::Lt | Operator::Gte | Operator::Gt
56        ) {
57            return Ok(None);
58        }
59
60        // The left operand must be `SpatialDistance(geom, const)`; the right, the radius literal.
61        let distance = expr.child(0);
62        if distance.as_opt::<SpatialDistance>().is_none() {
63            return Ok(None);
64        }
65        let Some(radius) = expr.child(1).as_opt::<Literal>() else {
66            return Ok(None);
67        };
68        // Casts any primitive radius (filters arrive uncoerced, so integer literals are
69        // legitimate); a null or non-primitive (e.g. extension-typed) literal has no value to
70        // reason about, decline and scan, never error.
71        let Ok(radius) = f64::try_from(radius) else {
72            return Ok(None);
73        };
74        // A NaN radius has no sound proof: `distance <op> NaN` is not a total order, so the chunk
75        // must be scanned, not pruned.
76        if radius.is_nan() {
77            return Ok(None);
78        }
79
80        let Some((geom, constant)) = geometry_and_constant(distance)? else {
81            return Ok(None);
82        };
83        let Some(query) = query_aabb(constant, session)? else {
84            return Ok(None);
85        };
86        Ok(distance_prune_proof(geom, query, op, radius))
87    }
88}
89
90/// Build the prune proof for `ST_Distance(geom, const) <op> radius`, or `None` when this
91/// operator/radius cannot prune. The box-to-box distance bounds every row's true distance for any
92/// geometry types: `<=` / `<` prune a chunk whose box is wholly beyond `radius` (min
93/// box-distance); `>=` / `>` prune one wholly within it (max box-distance).
94///
95/// A distance is always `>= 0`, which decides the degenerate radii up front.
96fn distance_prune_proof(
97    geom: &BoundExpression,
98    query: SpatialRect<f64>,
99    op: Operator,
100    radius: f64,
101) -> Option<BoundExpression> {
102    // A distance is always non-negative, so degenerate radii resolve without touching the box.
103    match op {
104        // `<= r` / `< r` with a negative radius (or zero, for `<`) match nothing: prune every chunk.
105        Operator::Lte if radius < 0.0 => return Some(lit(true)),
106        Operator::Lt if radius <= 0.0 => return Some(lit(true)),
107        // `>= r` / `> r` with a negative radius (or zero, for `>=`) match all rows: never prune.
108        Operator::Gte if radius <= 0.0 => return None,
109        Operator::Gt if radius < 0.0 => return None,
110        _ => {}
111    }
112    // Compared squared to avoid a `sqrt`; all operands are `>= 0`.
113    let aabb = aabb_stat(geom);
114    let r2 = lit(radius * radius);
115    Some(match op {
116        // Beyond the threshold: even the nearest the box can be exceeds `r`.
117        Operator::Lte => gt(min_dist_sq(&aabb, query), r2),
118        Operator::Lt => gt_eq(min_dist_sq(&aabb, query), r2),
119        // Within the threshold: even the farthest the box can be is below `r`.
120        Operator::Gte => lt(max_dist_sq(&aabb, query), r2),
121        Operator::Gt => lt_eq(max_dist_sq(&aabb, query), r2),
122        _ => return None,
123    })
124}
125
126#[cfg(test)]
127mod tests {
128    use rstest::rstest;
129    use vortex_array::VortexSessionExecute;
130    use vortex_array::dtype::DType;
131    use vortex_array::dtype::Nullability;
132    use vortex_array::dtype::PType;
133    use vortex_array::expr::BoundExpression;
134    use vortex_array::expr::gt_eq;
135    use vortex_array::expr::lit;
136    use vortex_array::expr::lt_eq;
137    use vortex_array::expr::root;
138    use vortex_array::scalar::Scalar;
139    use vortex_array::scalar_fn::EmptyOptions;
140    use vortex_array::scalar_fn::ScalarFnVTableExt;
141    use vortex_array::scalar_fn::fns::binary::Binary;
142    use vortex_array::scalar_fn::fns::operators::Operator;
143    use vortex_array::stats::rewrite::StatsRewriteRule;
144    use vortex_error::VortexResult;
145
146    use super::SpatialDistancePrune;
147    use crate::prune::test_harness::aabb_zone_map;
148    use crate::prune::test_harness::empty_zone_map;
149    use crate::scalar_fn::distance::SpatialDistance;
150    use crate::test_harness::point_column;
151    use crate::test_harness::spatial_session;
152
153    /// Run the rule against `SpatialDistance(root, origin) <operator> radius`, operands swapped when
154    /// `geom_first` is false. The radius is any literal scalar, matching the uncoerced filter
155    /// expressions the rule sees in production.
156    fn falsify_distance(
157        operator: Operator,
158        geom_first: bool,
159        radius: impl Into<Scalar>,
160    ) -> VortexResult<Option<BoundExpression>> {
161        let session = spatial_session();
162        let mut ctx = session.create_execution_ctx();
163
164        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
165        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
166        let operands = if geom_first {
167            [root(), lit(origin)]
168        } else {
169            [lit(origin), root()]
170        };
171        let distance = SpatialDistance.new_expr(EmptyOptions, operands);
172        let predicate = Binary
173            .new_expr(operator, [distance, lit(radius.into())])
174            .bind(&scope)?;
175
176        SpatialDistancePrune.falsify(&predicate, &session)
177    }
178
179    /// A null geometry literal (`ST_Distance(geom, NULL) <= r`) declines cleanly instead of
180    /// erroring in the stats rewrite: the all-null predicate can never prune.
181    #[test]
182    fn null_literal_is_not_pruned() -> VortexResult<()> {
183        let session = spatial_session();
184
185        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
186        let null_query = Scalar::null(scope.as_nullable());
187        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(null_query)]);
188        let predicate = Binary
189            .new_expr(Operator::Lte, [distance, lit(0.5f64)])
190            .bind(&scope)?;
191
192        assert!(
193            SpatialDistancePrune
194                .falsify(&predicate, &session)?
195                .is_none()
196        );
197        Ok(())
198    }
199
200    /// All four distance comparisons prune (`<=`/`<` via min-distance, `>=`/`>` via max-distance);
201    /// `==`/`!=` are left to the scan.
202    #[rstest]
203    #[case(Operator::Lte, true)]
204    #[case(Operator::Lt, true)]
205    #[case(Operator::Gt, true)]
206    #[case(Operator::Gte, true)]
207    #[case(Operator::Eq, false)]
208    #[case(Operator::NotEq, false)]
209    fn prunes_distance_comparisons(
210        #[case] operator: Operator,
211        #[case] prunes: bool,
212    ) -> VortexResult<()> {
213        assert_eq!(falsify_distance(operator, true, 0.5)?.is_some(), prunes);
214        Ok(())
215    }
216
217    /// Distance is symmetric: both operand orders produce a proof.
218    #[rstest]
219    #[case(true)]
220    #[case(false)]
221    fn falsifies_either_operand_order(#[case] geom_first: bool) -> VortexResult<()> {
222        assert!(falsify_distance(Operator::Lte, geom_first, 0.5)?.is_some());
223        Ok(())
224    }
225
226    /// A NaN radius must not prune - the scan's total-order compare treats `dist <= NaN` as true.
227    #[test]
228    fn nan_radius_never_prunes() -> VortexResult<()> {
229        assert!(falsify_distance(Operator::Lte, true, f64::NAN)?.is_none());
230        Ok(())
231    }
232
233    /// A negative radius prunes every zone - vacuously sound: `distance <= r < 0` matches no row.
234    #[test]
235    fn negative_radius_prunes_vacuously() -> VortexResult<()> {
236        assert!(falsify_distance(Operator::Lte, true, -0.5)?.is_some());
237        Ok(())
238    }
239
240    /// An uncoerced integer radius is rejected while binding the comparison.
241    #[test]
242    fn uncoerced_integer_radius_fails_to_bind() -> VortexResult<()> {
243        assert!(falsify_distance(Operator::Lte, true, 10i64).is_err());
244        Ok(())
245    }
246
247    /// A null radius has no value to reason about; the rule declines and the chunk is scanned.
248    #[test]
249    fn null_radius_never_prunes() -> VortexResult<()> {
250        let radius = Scalar::null(DType::Primitive(PType::F64, Nullability::Nullable));
251        assert!(falsify_distance(Operator::Lte, true, radius)?.is_none());
252        Ok(())
253    }
254
255    /// An extension-typed radius passes `Binary`'s typecheck (extension operands are exempt) but
256    /// has no numeric value - the rule declines rather than erroring, and the chunk is scanned.
257    #[test]
258    fn extension_radius_never_prunes() -> VortexResult<()> {
259        let session = spatial_session();
260        let mut ctx = session.create_execution_ctx();
261
262        let geometry = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
263        assert!(falsify_distance(Operator::Lte, true, geometry)?.is_none());
264        Ok(())
265    }
266
267    /// A non-geometry scope is rejected while binding, before stats rewriting.
268    #[test]
269    fn unsupported_scope_is_not_pruned() -> VortexResult<()> {
270        let session = spatial_session();
271        let mut ctx = session.create_execution_ctx();
272
273        let scope = DType::Primitive(PType::F64, Nullability::NonNullable);
274        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
275        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
276        let predicate = lt_eq(distance, lit(0.5f64));
277        assert!(predicate.bind(&scope).is_err());
278        Ok(())
279    }
280
281    /// A comparison that does not wrap `SpatialDistance` is left untouched.
282    #[test]
283    fn ignores_non_distance_comparison() -> VortexResult<()> {
284        let session = spatial_session();
285        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
286
287        let predicate = lt_eq(lit(1.0f64), lit(2.0f64)).bind(&scope)?;
288        assert!(
289            SpatialDistancePrune
290                .falsify(&predicate, &session)?
291                .is_none()
292        );
293        Ok(())
294    }
295
296    /// End-to-end over a hand-built zone map: the far chunk is skipped, the near one kept.
297    #[test]
298    fn prunes_far_chunk_keeps_near() -> VortexResult<()> {
299        let session = spatial_session();
300        let mut ctx = session.create_execution_ctx();
301
302        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
303        // Chunk 0 near the origin (0,0..1,1), chunk 1 far away (100,100..101,101).
304        let zone_map = aabb_zone_map(
305            &point_dtype,
306            &[[0.0, 0.0, 1.0, 1.0], [100.0, 100.0, 101.0, 101.0]],
307        )?;
308
309        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
310        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
311        let predicate = lt_eq(distance, lit(0.5f64));
312        let proof = predicate
313            .bind(&point_dtype)?
314            .falsify(&session)?
315            .expect("distance filter should be falsifiable");
316
317        // `true` means the zone is pruned: chunk 0 (near origin) is kept, chunk 1 (far) is skipped.
318        let mask = zone_map.prune(&proof, &session)?;
319        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, true]);
320        Ok(())
321    }
322
323    /// The true-distance prune skips a chunk that is *diagonally* farther than `r`, even though
324    /// neither axis alone exceeds `r`, the case a per-axis box-overlap test would wrongly keep.
325    #[test]
326    fn prunes_diagonally_distant_chunk() -> VortexResult<()> {
327        let session = spatial_session();
328        let mut ctx = session.create_execution_ctx();
329
330        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
331        // One chunk, AABB (0.8,0.8)..(0.9,0.9): each axis is only 0.8 from the origin (<= r = 1), but
332        // the near corner is sqrt(0.8^2 + 0.8^2) ~= 1.13 away (> 1), so no point in the box is within 1.
333        let zone_map = aabb_zone_map(&point_dtype, &[[0.8, 0.8, 0.9, 0.9]])?;
334
335        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
336        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
337        let predicate = lt_eq(distance, lit(1.0f64));
338        let proof = predicate
339            .bind(&point_dtype)?
340            .falsify(&session)?
341            .expect("distance filter should be falsifiable");
342
343        assert_eq!(
344            zone_map
345                .prune(&proof, &session)?
346                .iter()
347                .collect::<Vec<bool>>(),
348            vec![true],
349        );
350        Ok(())
351    }
352
353    /// A `>= r` filter prunes a chunk lying wholly *within* `r` (every row nearer than `r`, so none
354    /// satisfy `>= r`) via the box max-distance, while a chunk beyond `r` is kept.
355    #[test]
356    fn prunes_within_chunk_for_far_filter() -> VortexResult<()> {
357        let session = spatial_session();
358        let mut ctx = session.create_execution_ctx();
359
360        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
361        // Chunk 0 (AABB 0,0..0.5,0.5, farthest corner ~= 0.707) is entirely within 2 of the origin;
362        // chunk 1 (100,100..101,101) is entirely beyond it.
363        let zone_map = aabb_zone_map(
364            &point_dtype,
365            &[[0.0, 0.0, 0.5, 0.5], [100.0, 100.0, 101.0, 101.0]],
366        )?;
367
368        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
369        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
370        let proof = gt_eq(distance, lit(2.0f64))
371            .bind(&point_dtype)?
372            .falsify(&session)?
373            .expect("distance filter should be falsifiable");
374
375        // Chunk 0 (within 2) is pruned for `>= 2`; chunk 1 (beyond 2) is kept.
376        let mask = zone_map.prune(&proof, &session)?;
377        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![true, false]);
378        Ok(())
379    }
380
381    #[test]
382    fn missing_aabb_stat_keeps_all_zones() -> VortexResult<()> {
383        let session = spatial_session();
384        let mut ctx = session.create_execution_ctx();
385
386        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
387        let zone_map = empty_zone_map(&point_dtype)?;
388
389        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
390        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
391        let proof = lt_eq(distance, lit(0.5f64))
392            .bind(&point_dtype)?
393            .falsify(&session)?
394            .expect("distance filter should be falsifiable");
395
396        let mask = zone_map.prune(&proof, &session)?;
397        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, false]);
398        Ok(())
399    }
400}