Skip to main content

datafusion_physical_expr/
analysis.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Interval and selectivity in [`AnalysisContext`]
6
7use std::fmt::Debug;
8use std::sync::Arc;
9
10use crate::PhysicalExpr;
11use crate::expressions::Column;
12use crate::intervals::cp_solver::{ExprIntervalGraph, PropagationResult};
13use crate::utils::collect_columns;
14
15use arrow::datatypes::Schema;
16use datafusion_common::stats::Precision;
17use datafusion_common::{
18    ColumnStatistics, Result, ScalarValue, assert_or_internal_err,
19    internal_datafusion_err, internal_err,
20};
21use datafusion_expr::interval_arithmetic::{Interval, cardinality_ratio};
22
23/// The shared context used during the analysis of an expression. Includes
24/// the boundaries for all known columns.
25#[derive(Clone, Debug, PartialEq)]
26pub struct AnalysisContext {
27    // A list of known column boundaries, ordered by the index
28    // of the column in the current schema.
29    pub boundaries: Vec<ExprBoundaries>,
30    /// The estimated percentage of rows that this expression would select, if
31    /// it were to be used as a boolean predicate on a filter. The value will be
32    /// between 0.0 (selects nothing) and 1.0 (selects everything).
33    pub selectivity: Option<f64>,
34}
35
36impl AnalysisContext {
37    pub fn new(boundaries: Vec<ExprBoundaries>) -> Self {
38        Self {
39            boundaries,
40            selectivity: None,
41        }
42    }
43
44    pub fn with_selectivity(mut self, selectivity: f64) -> Self {
45        self.selectivity = Some(selectivity);
46        self
47    }
48
49    /// Create a new analysis context from column statistics.
50    pub fn try_from_statistics(
51        input_schema: &Schema,
52        statistics: &[ColumnStatistics],
53    ) -> Result<Self> {
54        statistics
55            .iter()
56            .enumerate()
57            .map(|(idx, stats)| ExprBoundaries::try_from_column(input_schema, stats, idx))
58            .collect::<Result<Vec<_>>>()
59            .map(Self::new)
60    }
61}
62
63/// Represents the boundaries (e.g. min and max values) of a particular column
64///
65/// This is used range analysis of expressions, to determine if the expression
66/// limits the value of particular columns (e.g. analyzing an expression such as
67/// `time < 50` would result in a boundary interval for `time` having a max
68/// value of `50`).
69#[derive(Clone, Debug, PartialEq)]
70pub struct ExprBoundaries {
71    pub column: Column,
72    /// Minimum and maximum values this expression can have. A `None` value
73    /// indicates that evaluating the given column results in an empty set.
74    /// For example, if the column `a` has values in the range [10, 20],
75    /// and there is a filter asserting that `a > 50`, then the resulting interval
76    /// range of `a` will be `None`.
77    pub interval: Option<Interval>,
78    /// Maximum number of distinct values this expression can produce, if known.
79    pub distinct_count: Precision<usize>,
80}
81
82impl ExprBoundaries {
83    /// Create a new `ExprBoundaries` object from column level statistics.
84    pub fn try_from_column(
85        schema: &Schema,
86        col_stats: &ColumnStatistics,
87        col_index: usize,
88    ) -> Result<Self> {
89        let field = schema.fields().get(col_index).ok_or_else(|| {
90            internal_datafusion_err!(
91                "Could not create `ExprBoundaries`: in `try_from_column` `col_index`
92                has gone out of bounds with a value of {col_index}, the schema has {} columns.",
93                schema.fields.len()
94            )
95        })?;
96        let empty_field =
97            ScalarValue::try_from(field.data_type()).unwrap_or(ScalarValue::Null);
98        let interval = Interval::try_new(
99            col_stats
100                .min_value
101                .get_value()
102                .cloned()
103                .unwrap_or_else(|| empty_field.clone()),
104            col_stats
105                .max_value
106                .get_value()
107                .cloned()
108                .unwrap_or(empty_field),
109        )?;
110        let column = Column::new(field.name(), col_index);
111        Ok(ExprBoundaries {
112            column,
113            interval: Some(interval),
114            distinct_count: col_stats.distinct_count,
115        })
116    }
117
118    /// Create `ExprBoundaries` that represent no known bounds for all the
119    /// columns in `schema`
120    pub fn try_new_unbounded(schema: &Schema) -> Result<Vec<Self>> {
121        schema
122            .fields()
123            .iter()
124            .enumerate()
125            .map(|(i, field)| {
126                Ok(Self {
127                    column: Column::new(field.name(), i),
128                    interval: Some(Interval::make_unbounded(field.data_type())?),
129                    distinct_count: Precision::Absent,
130                })
131            })
132            .collect()
133    }
134}
135
136/// Attempts to refine column boundaries and compute a selectivity value.
137///
138/// The function accepts boundaries of the input columns in the `context` parameter.
139/// It then tries to tighten these boundaries based on the provided `expr`.
140/// The resulting selectivity value is calculated by comparing the initial and final boundaries.
141/// The computation assumes that the data within the column is uniformly distributed and not sorted.
142///
143/// # Arguments
144///
145/// * `context` - The context holding input column boundaries.
146/// * `expr` - The expression used to shrink the column boundaries.
147///
148/// # Returns
149///
150/// * `AnalysisContext` constructed by pruned boundaries and a selectivity value.
151pub fn analyze(
152    expr: &Arc<dyn PhysicalExpr>,
153    context: AnalysisContext,
154    schema: &Schema,
155) -> Result<AnalysisContext> {
156    let initial_boundaries = &context.boundaries;
157
158    if initial_boundaries
159        .iter()
160        .all(|bound| bound.interval.is_none())
161    {
162        assert_or_internal_err!(
163            !initial_boundaries
164                .iter()
165                .any(|bound| bound.distinct_count != Precision::Exact(0)),
166            "ExprBoundaries has a non-zero distinct count although it represents an empty table"
167        );
168        assert_or_internal_err!(
169            context.selectivity.unwrap_or(0.0) == 0.0,
170            "AnalysisContext has a non-zero selectivity although it represents an empty table"
171        );
172        Ok(context)
173    } else if initial_boundaries
174        .iter()
175        .any(|bound| bound.interval.is_none())
176    {
177        internal_err!(
178            "AnalysisContext is an inconsistent state. Some columns represent empty table while others don't"
179        )
180    } else {
181        let mut target_boundaries = context.boundaries;
182        let mut graph = ExprIntervalGraph::try_new(Arc::clone(expr), schema)?;
183        let columns = collect_columns(expr)
184            .into_iter()
185            .map(|c| Arc::new(c) as _)
186            .collect::<Vec<_>>();
187
188        let target_expr_and_indices = graph.gather_node_indices(columns.as_slice());
189        let mut target_indices_and_boundaries =
190            Vec::with_capacity(target_expr_and_indices.len());
191
192        for (expr, index) in &target_expr_and_indices {
193            if let Some(column) = expr.downcast_ref::<Column>()
194                && let Some(bound) =
195                    target_boundaries.iter().find(|b| b.column == *column)
196            {
197                // Now, it's safe to unwrap
198                target_indices_and_boundaries
199                    .push((*index, bound.interval.as_ref().unwrap().clone()));
200            }
201        }
202
203        match graph.update_ranges(&mut target_indices_and_boundaries, Interval::TRUE)? {
204            PropagationResult::Success => {
205                shrink_boundaries(&graph, target_boundaries, &target_expr_and_indices)
206            }
207            PropagationResult::Infeasible => {
208                // If the propagation result is infeasible, set intervals to None
209                for bound in &mut target_boundaries {
210                    bound.interval = None;
211                }
212                Ok(AnalysisContext::new(target_boundaries).with_selectivity(0.0))
213            }
214            PropagationResult::CannotPropagate => {
215                Ok(AnalysisContext::new(target_boundaries).with_selectivity(1.0))
216            }
217        }
218    }
219}
220
221/// If the `PropagationResult` indicates success, this function calculates the
222/// selectivity value by comparing the initial and final column boundaries.
223/// Following this, it constructs and returns a new `AnalysisContext` with the
224/// updated parameters.
225fn shrink_boundaries(
226    graph: &ExprIntervalGraph,
227    mut target_boundaries: Vec<ExprBoundaries>,
228    target_expr_and_indices: &[(Arc<dyn PhysicalExpr>, usize)],
229) -> Result<AnalysisContext> {
230    let initial_boundaries = target_boundaries.clone();
231    for (expr, i) in target_expr_and_indices {
232        if let Some(column) = expr.downcast_ref::<Column>()
233            && let Some(bound) = target_boundaries
234                .iter_mut()
235                .find(|bound| bound.column.eq(column))
236        {
237            bound.interval = Some(graph.get_interval(*i));
238        }
239    }
240
241    let selectivity = calculate_selectivity(&target_boundaries, &initial_boundaries)?;
242
243    assert_or_internal_err!(
244        (0.0..=1.0).contains(&selectivity),
245        "Selectivity is out of limit: {selectivity}",
246    );
247
248    Ok(AnalysisContext::new(target_boundaries).with_selectivity(selectivity))
249}
250
251/// Returns `Some(1.0 / distinct_count)` when the filter demonstrably collapsed
252/// a non-singleton interval down to a single point, i.e. an equality predicate
253/// was applied.  Returns `None` in all other cases, signalling that the caller
254/// should fall back to [`cardinality_ratio`].
255///
256/// The `initial_interval` guard prevents double-counting selectivity when the
257/// column statistics already described a singleton before any filter was
258/// applied: if the initial interval was already the same single point, no
259/// additional selectivity has been gained and the `1 / NDV` shortcut must not
260/// fire.
261fn singleton_selectivity(
262    initial_interval: &Interval,
263    target_interval: &Interval,
264    distinct_count: usize,
265) -> Option<f64> {
266    // The target must have collapsed to a single non-null value.
267    if distinct_count == 0
268        || target_interval.lower().is_null()
269        || target_interval.lower() != target_interval.upper()
270    {
271        return None;
272    }
273
274    // Only treat this as a newly-applied equality filter when the initial
275    // interval was not already that same singleton.  If it was, the stats
276    // already encoded this restriction and applying 1/NDV again would
277    // under-estimate the row count.
278    let initial_is_same_singleton = !initial_interval.lower().is_null()
279        && initial_interval.lower() == initial_interval.upper()
280        && initial_interval.lower() == target_interval.lower();
281
282    if initial_is_same_singleton {
283        return None;
284    }
285
286    Some(1.0 / distinct_count as f64)
287}
288
289/// This function calculates the filter predicate's selectivity by comparing
290/// the initial and pruned column boundaries. Selectivity is defined as the
291/// ratio of rows in a table that satisfy the filter's predicate.
292fn calculate_selectivity(
293    target_boundaries: &[ExprBoundaries],
294    initial_boundaries: &[ExprBoundaries],
295) -> Result<f64> {
296    // Since the intervals are assumed uniform and the values
297    // are not correlated, we need to multiply the selectivities
298    // of multiple columns to get the overall selectivity.
299    if target_boundaries.len() != initial_boundaries.len() {
300        return Err(internal_datafusion_err!(
301            "The number of columns in the initial and target boundaries should be the same"
302        ));
303    }
304    let mut acc: f64 = 1.0;
305    for (initial, target) in initial_boundaries.iter().zip(target_boundaries) {
306        match (initial.interval.as_ref(), target.interval.as_ref()) {
307            (Some(initial_interval), Some(target_interval)) => {
308                if let Precision::Exact(distinct_count)
309                | Precision::Inexact(distinct_count) = target.distinct_count
310                    && let Some(s) = singleton_selectivity(
311                        initial_interval,
312                        target_interval,
313                        distinct_count,
314                    )
315                {
316                    acc *= s;
317                    continue;
318                }
319                acc *= cardinality_ratio(initial_interval, target_interval);
320            }
321            (None, Some(_)) => {
322                return internal_err!(
323                    "Initial boundary cannot be None while having a Some() target boundary"
324                );
325            }
326            _ => return Ok(0.0),
327        }
328    }
329
330    Ok(acc)
331}
332
333#[cfg(test)]
334mod tests {
335    use std::ops::Not;
336    use std::sync::Arc;
337
338    use arrow::datatypes::{DataType, Field, Schema};
339    use datafusion_common::{DFSchema, ScalarValue, assert_contains, stats::Precision};
340    use datafusion_expr::{
341        Expr, col, execution_props::ExecutionProps, interval_arithmetic::Interval, lit,
342        physical_planning_context::PhysicalPlanningContext,
343    };
344
345    use crate::{AnalysisContext, create_physical_expr, expressions::Column};
346
347    use super::{ExprBoundaries, analyze, calculate_selectivity, singleton_selectivity};
348
349    fn make_field(name: &str, data_type: DataType) -> Field {
350        let nullable = false;
351        Field::new(name, data_type, nullable)
352    }
353
354    #[test]
355    fn test_analyze_boundary_exprs() {
356        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Int32)]));
357
358        /// Test case containing (expression tree, lower bound, upper bound)
359        type TestCase = (Expr, Option<i32>, Option<i32>);
360
361        let test_cases: Vec<TestCase> = vec![
362            // a > 10
363            (col("a").gt(lit(10)), Some(11), None),
364            // a < 20
365            (col("a").lt(lit(20)), None, Some(19)),
366            // a > 10 AND a < 20
367            (
368                col("a").gt(lit(10)).and(col("a").lt(lit(20))),
369                Some(11),
370                Some(19),
371            ),
372            // a >= 10
373            (col("a").gt_eq(lit(10)), Some(10), None),
374            // a <= 20
375            (col("a").lt_eq(lit(20)), None, Some(20)),
376            // a >= 10 AND a <= 20
377            (
378                col("a").gt_eq(lit(10)).and(col("a").lt_eq(lit(20))),
379                Some(10),
380                Some(20),
381            ),
382            // a > 10 AND a < 20 AND a < 15
383            (
384                col("a")
385                    .gt(lit(10))
386                    .and(col("a").lt(lit(20)))
387                    .and(col("a").lt(lit(15))),
388                Some(11),
389                Some(14),
390            ),
391            // (a > 10 AND a < 20) AND (a > 15 AND a < 25)
392            (
393                col("a")
394                    .gt(lit(10))
395                    .and(col("a").lt(lit(20)))
396                    .and(col("a").gt(lit(15)))
397                    .and(col("a").lt(lit(25))),
398                Some(16),
399                Some(19),
400            ),
401        ];
402        for (expr, lower, upper) in test_cases {
403            let boundaries = ExprBoundaries::try_new_unbounded(&schema).unwrap();
404            let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
405            let physical_expr = create_physical_expr(
406                &expr,
407                &df_schema,
408                &ExecutionProps::new(),
409                &PhysicalPlanningContext::default(),
410            )
411            .unwrap();
412            let analysis_result = analyze(
413                &physical_expr,
414                AnalysisContext::new(boundaries),
415                df_schema.as_ref(),
416            )
417            .unwrap();
418            let Some(actual) = &analysis_result.boundaries[0].interval else {
419                panic!(
420                    "The analysis result should contain non-empty intervals for all columns"
421                );
422            };
423            let expected = Interval::make(lower, upper).unwrap();
424            assert_eq!(
425                &expected, actual,
426                "did not get correct interval for SQL expression: {expr:?}"
427            );
428        }
429    }
430
431    #[test]
432    fn test_analyze_empty_set_boundary_exprs() {
433        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Int32)]));
434
435        let test_cases: Vec<Expr> = vec![
436            // a > 10 AND a < 10
437            col("a").gt(lit(10)).and(col("a").lt(lit(10))),
438            // a > 5 AND (a < 20 OR a > 20)
439            // a > 10 AND a < 20
440            // (a > 10 AND a < 20) AND (a > 20 AND a < 30)
441            col("a")
442                .gt(lit(10))
443                .and(col("a").lt(lit(20)))
444                .and(col("a").gt(lit(20)))
445                .and(col("a").lt(lit(30))),
446        ];
447
448        for expr in test_cases {
449            let boundaries = ExprBoundaries::try_new_unbounded(&schema).unwrap();
450            let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
451            let physical_expr = create_physical_expr(
452                &expr,
453                &df_schema,
454                &ExecutionProps::new(),
455                &PhysicalPlanningContext::default(),
456            )
457            .unwrap();
458            let analysis_result = analyze(
459                &physical_expr,
460                AnalysisContext::new(boundaries),
461                df_schema.as_ref(),
462            )
463            .unwrap();
464
465            for boundary in analysis_result.boundaries {
466                assert!(boundary.interval.is_none());
467            }
468        }
469    }
470
471    #[test]
472    fn test_analyze_invalid_boundary_exprs() {
473        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Int32)]));
474        let expr = col("a").lt(lit(10)).or(col("a").gt(lit(20)));
475        let expected_error = "OR operator cannot yet propagate true intervals";
476        let boundaries = ExprBoundaries::try_new_unbounded(&schema).unwrap();
477        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
478        let physical_expr = create_physical_expr(
479            &expr,
480            &df_schema,
481            &ExecutionProps::new(),
482            &PhysicalPlanningContext::default(),
483        )
484        .unwrap();
485        let analysis_error = analyze(
486            &physical_expr,
487            AnalysisContext::new(boundaries),
488            df_schema.as_ref(),
489        )
490        .unwrap_err();
491        assert_contains!(analysis_error.to_string(), expected_error);
492    }
493
494    // ---------------------------------------------------------------------------
495    // Unit tests for singleton_selectivity and calculate_selectivity
496    // ---------------------------------------------------------------------------
497
498    fn make_boundary(lower: i32, upper: i32, distinct_count: usize) -> ExprBoundaries {
499        ExprBoundaries {
500            column: Column::new("a", 0),
501            interval: Some(
502                Interval::try_new(
503                    ScalarValue::Int32(Some(lower)),
504                    ScalarValue::Int32(Some(upper)),
505                )
506                .unwrap(),
507            ),
508            distinct_count: Precision::Exact(distinct_count),
509        }
510    }
511
512    /// When the initial interval is already the same singleton as the target,
513    /// `singleton_selectivity` must return `None` so we do not double-apply
514    /// 1/NDV selectivity.
515    #[test]
516    fn test_singleton_selectivity_skipped_when_initial_is_same_singleton() {
517        let singleton =
518            Interval::try_new(ScalarValue::Int32(Some(5)), ScalarValue::Int32(Some(5)))
519                .unwrap();
520        // Both initial and target are [5, 5] — no new equality filter was applied.
521        assert_eq!(
522            singleton_selectivity(&singleton, &singleton, 10),
523            None,
524            "shortcut must not fire when initial interval was already the same singleton"
525        );
526    }
527
528    /// When the initial interval is a broader range and the target collapses to
529    /// a singleton, `singleton_selectivity` must return `Some(1/NDV)`.
530    #[test]
531    fn test_singleton_selectivity_applied_when_range_collapses() {
532        let initial =
533            Interval::try_new(ScalarValue::Int32(Some(1)), ScalarValue::Int32(Some(100)))
534                .unwrap();
535        let target =
536            Interval::try_new(ScalarValue::Int32(Some(5)), ScalarValue::Int32(Some(5)))
537                .unwrap();
538        let result = singleton_selectivity(&initial, &target, 10);
539        assert_eq!(
540            result,
541            Some(0.1),
542            "shortcut must return 1/NDV when a range collapses to a singleton"
543        );
544    }
545
546    /// Regression test: `calculate_selectivity` must not apply the `1/NDV`
547    /// shortcut when the column statistics already describe a singleton interval
548    /// (i.e. before the filter, the column only ever held one value).  In that
549    /// case the target and initial intervals are the same singleton, so the
550    /// cardinality ratio is 1.0 and the overall selectivity should remain 1.0.
551    #[test]
552    fn test_calculate_selectivity_already_singleton_initial_interval() {
553        let already_singleton = make_boundary(7, 7, 1);
554
555        let selectivity = calculate_selectivity(
556            std::slice::from_ref(&already_singleton),
557            std::slice::from_ref(&already_singleton),
558        )
559        .unwrap();
560
561        let wide_initial = make_boundary(1, 100, 50);
562        let same_singleton_target = make_boundary(7, 7, 50);
563        let selectivity_new =
564            calculate_selectivity(&[same_singleton_target], &[wide_initial]).unwrap();
565        assert!(
566            (selectivity_new - 0.02).abs() < 1e-10,
567            "expected selectivity 1/NDV = 0.02, got {selectivity_new}"
568        );
569
570        let singleton_initial = make_boundary(7, 7, 50);
571        let singleton_target = make_boundary(7, 7, 50);
572        let selectivity_no_new_filter =
573            calculate_selectivity(&[singleton_target], &[singleton_initial]).unwrap();
574        assert!(
575            (selectivity_no_new_filter - 1.0).abs() < 1e-10,
576            "expected selectivity 1.0 when initial was already the same singleton, got {selectivity_no_new_filter}"
577        );
578
579        let _ = selectivity; // silence unused warning
580    }
581
582    // Regression tests for #19264.
583    //
584    // `analyze` propagates constraints through `NotExpr::propagate_constraints`,
585    // which hands the underlying `Eq` node a `FALSE` parent interval. When the
586    // input domain contains `0.0` but is not equal to it, `NOT (a = 0.0)` is
587    // satisfiable, so `analyze` reports the input domain. `None` is reserved
588    // for an empty set, as documented on `ExprBoundaries::interval`.
589    fn analyze_not_eq_helper(
590        lower: f32,
591        upper: f32,
592    ) -> datafusion_common::Result<Option<Interval>> {
593        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Float32)]));
594        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
595
596        // Input column bounds: [lower, upper]
597        let boundaries = vec![ExprBoundaries {
598            column: Column::new("a", 0),
599            interval: Some(Interval::try_new(
600                ScalarValue::Float32(Some(lower)),
601                ScalarValue::Float32(Some(upper)),
602            )?),
603            distinct_count: Precision::Inexact(100),
604        }];
605        let ctx = AnalysisContext::new(boundaries);
606
607        // Predicate: NOT (a = 0.0)
608        let pred_not_eq = col("a").eq(lit(0.0f32)).not();
609        let phys_not = create_physical_expr(
610            &pred_not_eq,
611            &df_schema,
612            &ExecutionProps::new(),
613            &PhysicalPlanningContext::default(),
614        )?;
615        let out = analyze(&phys_not, ctx, df_schema.as_ref())?;
616        Ok(out.boundaries[0].interval.clone())
617    }
618
619    #[test]
620    fn test_analyze_not_eq_around_zero() -> datafusion_common::Result<()> {
621        // Input domain [-1, 1] contains 0.0.
622        // `NOT (a = 0.0)` can be true everywhere except at 0.0, so the output
623        // interval should be the full input domain [-1, 1], NOT None.
624        let out = analyze_not_eq_helper(-1.0, 1.0)?;
625        let expected = Some(Interval::try_new(
626            ScalarValue::Float32(Some(-1.0)),
627            ScalarValue::Float32(Some(1.0)),
628        )?);
629        assert_eq!(
630            out, expected,
631            "NOT (a = 0.0) over [-1, 1] should yield [-1, 1], got {out:?}"
632        );
633        Ok(())
634    }
635
636    #[test]
637    fn test_analyze_not_eq_clamped_at_zero() -> datafusion_common::Result<()> {
638        // Input domain [0, 0] is exactly the point where a = 0.0 is true.
639        // `NOT (a = 0.0)` is always false here, so the output interval should be None.
640        let out = analyze_not_eq_helper(0.0, 0.0)?;
641        assert_eq!(
642            out, None,
643            "NOT (a = 0.0) over [0, 0] should yield None (infeasible), got {out:?}"
644        );
645        Ok(())
646    }
647
648    fn analyze_not_eq_f64_helper(
649        lower: f64,
650        upper: f64,
651    ) -> datafusion_common::Result<Option<Interval>> {
652        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Float64)]));
653        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
654
655        let boundaries = vec![ExprBoundaries {
656            column: Column::new("a", 0),
657            interval: Some(Interval::try_new(
658                ScalarValue::Float64(Some(lower)),
659                ScalarValue::Float64(Some(upper)),
660            )?),
661            distinct_count: Precision::Inexact(100),
662        }];
663        let ctx = AnalysisContext::new(boundaries);
664
665        let pred_not_eq = col("a").eq(lit(0.0f64)).not();
666        let phys_not = create_physical_expr(
667            &pred_not_eq,
668            &df_schema,
669            &ExecutionProps::new(),
670            &PhysicalPlanningContext::default(),
671        )?;
672        let out = analyze(&phys_not, ctx, df_schema.as_ref())?;
673        Ok(out.boundaries[0].interval.clone())
674    }
675
676    // Regression test for the signed-zero singleton case.
677    //
678    // `Interval::try_new` orders endpoints with `total_cmp`, so
679    // `[-0.0, +0.0]` is a valid input domain. Its endpoints differ bit-wise
680    // but denote a single value under `Eq` comparison semantics, so
681    // `a = 0.0` is certainly true over it and `NOT (a = 0.0)` is infeasible.
682    // A bit-wise singleton check in `propagate_comparison` would instead
683    // report the input domain, i.e. a false-feasibility result on the public
684    // `analyze` path.
685    #[test]
686    fn test_analyze_not_eq_signed_zero_span_infeasible() -> datafusion_common::Result<()>
687    {
688        let out = analyze_not_eq_helper(-0.0, 0.0)?;
689        assert_eq!(
690            out, None,
691            "NOT (a = 0.0) over Float32 [-0.0, +0.0] should yield None (infeasible), got {out:?}"
692        );
693
694        let out = analyze_not_eq_f64_helper(-0.0, 0.0)?;
695        assert_eq!(
696            out, None,
697            "NOT (a = 0.0) over Float64 [-0.0, +0.0] should yield None (infeasible), got {out:?}"
698        );
699        Ok(())
700    }
701
702    fn analyze_between_helper(
703        lower: f32,
704        upper: f32,
705        negated: bool,
706        explicit_not: bool,
707    ) -> datafusion_common::Result<Option<Interval>> {
708        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Float32)]));
709        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
710        let boundaries = vec![ExprBoundaries {
711            column: Column::new("a", 0),
712            interval: Some(Interval::try_new(
713                ScalarValue::Float32(Some(lower)),
714                ScalarValue::Float32(Some(upper)),
715            )?),
716            distinct_count: Precision::Inexact(100),
717        }];
718
719        let between = col("a").between(lit(-1.0f32), lit(1.0f32));
720        let predicate = if explicit_not {
721            between.not()
722        } else if negated {
723            col("a").not_between(lit(-1.0f32), lit(1.0f32))
724        } else {
725            between
726        };
727        let physical_expr = create_physical_expr(
728            &predicate,
729            &df_schema,
730            &ExecutionProps::new(),
731            &PhysicalPlanningContext::default(),
732        )?;
733        let output = analyze(
734            &physical_expr,
735            AnalysisContext::new(boundaries),
736            df_schema.as_ref(),
737        )?;
738        Ok(output.boundaries[0].interval.clone())
739    }
740
741    #[test]
742    fn test_analyze_not_between_clamped() -> datafusion_common::Result<()> {
743        let expected = Some(Interval::try_new(
744            ScalarValue::Float32(Some(-1.0)),
745            ScalarValue::Float32(Some(1.0)),
746        )?);
747        assert_eq!(analyze_between_helper(-1.0, 1.0, false, false)?, expected);
748        assert_eq!(analyze_between_helper(-1.0, 1.0, true, false)?, None);
749        assert_eq!(analyze_between_helper(-1.0, 1.0, false, true)?, None);
750        Ok(())
751    }
752
753    #[test]
754    fn test_analyze_not_between_containing() -> datafusion_common::Result<()> {
755        let between = Some(Interval::try_new(
756            ScalarValue::Float32(Some(-1.0)),
757            ScalarValue::Float32(Some(1.0)),
758        )?);
759        let containing = Some(Interval::try_new(
760            ScalarValue::Float32(Some(-2.0)),
761            ScalarValue::Float32(Some(2.0)),
762        )?);
763        assert_eq!(analyze_between_helper(-2.0, 2.0, false, false)?, between);
764        assert_eq!(analyze_between_helper(-2.0, 2.0, true, false)?, containing);
765        assert_eq!(analyze_between_helper(-2.0, 2.0, false, true)?, containing);
766        Ok(())
767    }
768
769    // Regression test for the nested signed-zero case.
770    //
771    // `NOT(a = +0.0) AND b` with `a ∈ [-0.0,-0.0]`, `b ∈ [false,true]`:
772    // `a = +0.0` is TRUE (IEEE 754), so the whole predicate is infeasible.
773    //
774    // This defeats the case-(1) short-circuit in `update_ranges`: bottom-up
775    // evaluates `a = +0.0` over `[-0.0,-0.0]` as FALSE (structural equality),
776    // so `NOT` becomes TRUE, the root becomes `TRUE_OR_FALSE`, and top-down
777    // propagation forces `a = +0.0` to FALSE, reaching
778    // `propagate_comparison(Eq, FALSE, [-0.0,-0.0], [+0.0,+0.0])`. The guard
779    // must normalize signed zero to report infeasible here.
780    #[test]
781    fn test_analyze_not_eq_nested_signed_zero_infeasible() -> datafusion_common::Result<()>
782    {
783        let schema = Arc::new(Schema::new(vec![
784            make_field("a", DataType::Float32),
785            make_field("b", DataType::Boolean),
786        ]));
787        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
788
789        let boundaries = vec![
790            ExprBoundaries {
791                column: Column::new("a", 0),
792                interval: Some(Interval::try_new(
793                    ScalarValue::Float32(Some(-0.0f32)),
794                    ScalarValue::Float32(Some(-0.0f32)),
795                )?),
796                distinct_count: Precision::Inexact(1),
797            },
798            ExprBoundaries {
799                column: Column::new("b", 1),
800                interval: Some(Interval::try_new(
801                    ScalarValue::Boolean(Some(false)),
802                    ScalarValue::Boolean(Some(true)),
803                )?),
804                distinct_count: Precision::Inexact(2),
805            },
806        ];
807        let ctx = AnalysisContext::new(boundaries);
808
809        // NOT(a = +0.0) AND b
810        let pred = col("a").eq(lit(0.0f32)).not().and(col("b"));
811        let phys = create_physical_expr(
812            &pred,
813            &df_schema,
814            &ExecutionProps::new(),
815            &PhysicalPlanningContext::default(),
816        )?;
817        let out = analyze(&phys, ctx, df_schema.as_ref())?;
818
819        // Infeasible: a = +0.0 is TRUE (signed zero), NOT is FALSE,
820        // FALSE AND b = FALSE. All column intervals must be None.
821        assert!(
822            out.boundaries.iter().all(|b| b.interval.is_none()),
823            "NOT(a = +0.0) AND b over a=[-0.0,-0.0] should be infeasible (all boundaries None), got {:?}",
824            out.boundaries
825        );
826        assert_eq!(
827            out.selectivity,
828            Some(0.0),
829            "selectivity should be 0.0 for an infeasible predicate, got {:?}",
830            out.selectivity
831        );
832        Ok(())
833    }
834}