datafusion-physical-expr 56.0.0

Physical expression implementation for DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! Interval and selectivity in [`AnalysisContext`]

use std::fmt::Debug;
use std::sync::Arc;

use crate::PhysicalExpr;
use crate::expressions::Column;
use crate::intervals::cp_solver::{ExprIntervalGraph, PropagationResult};
use crate::utils::collect_columns;

use arrow::datatypes::Schema;
use datafusion_common::stats::Precision;
use datafusion_common::{
    ColumnStatistics, Result, ScalarValue, assert_or_internal_err,
    internal_datafusion_err, internal_err,
};
use datafusion_expr::interval_arithmetic::{Interval, cardinality_ratio};

/// The shared context used during the analysis of an expression. Includes
/// the boundaries for all known columns.
#[derive(Clone, Debug, PartialEq)]
pub struct AnalysisContext {
    // A list of known column boundaries, ordered by the index
    // of the column in the current schema.
    pub boundaries: Vec<ExprBoundaries>,
    /// The estimated percentage of rows that this expression would select, if
    /// it were to be used as a boolean predicate on a filter. The value will be
    /// between 0.0 (selects nothing) and 1.0 (selects everything).
    pub selectivity: Option<f64>,
}

impl AnalysisContext {
    pub fn new(boundaries: Vec<ExprBoundaries>) -> Self {
        Self {
            boundaries,
            selectivity: None,
        }
    }

    pub fn with_selectivity(mut self, selectivity: f64) -> Self {
        self.selectivity = Some(selectivity);
        self
    }

    /// Create a new analysis context from column statistics.
    pub fn try_from_statistics(
        input_schema: &Schema,
        statistics: &[ColumnStatistics],
    ) -> Result<Self> {
        statistics
            .iter()
            .enumerate()
            .map(|(idx, stats)| ExprBoundaries::try_from_column(input_schema, stats, idx))
            .collect::<Result<Vec<_>>>()
            .map(Self::new)
    }
}

/// Represents the boundaries (e.g. min and max values) of a particular column
///
/// This is used range analysis of expressions, to determine if the expression
/// limits the value of particular columns (e.g. analyzing an expression such as
/// `time < 50` would result in a boundary interval for `time` having a max
/// value of `50`).
#[derive(Clone, Debug, PartialEq)]
pub struct ExprBoundaries {
    pub column: Column,
    /// Minimum and maximum values this expression can have. A `None` value
    /// indicates that evaluating the given column results in an empty set.
    /// For example, if the column `a` has values in the range [10, 20],
    /// and there is a filter asserting that `a > 50`, then the resulting interval
    /// range of `a` will be `None`.
    pub interval: Option<Interval>,
    /// Maximum number of distinct values this expression can produce, if known.
    pub distinct_count: Precision<usize>,
}

impl ExprBoundaries {
    /// Create a new `ExprBoundaries` object from column level statistics.
    pub fn try_from_column(
        schema: &Schema,
        col_stats: &ColumnStatistics,
        col_index: usize,
    ) -> Result<Self> {
        let field = schema.fields().get(col_index).ok_or_else(|| {
            internal_datafusion_err!(
                "Could not create `ExprBoundaries`: in `try_from_column` `col_index`
                has gone out of bounds with a value of {col_index}, the schema has {} columns.",
                schema.fields.len()
            )
        })?;
        let empty_field =
            ScalarValue::try_from(field.data_type()).unwrap_or(ScalarValue::Null);
        let interval = Interval::try_new(
            col_stats
                .min_value
                .get_value()
                .cloned()
                .unwrap_or_else(|| empty_field.clone()),
            col_stats
                .max_value
                .get_value()
                .cloned()
                .unwrap_or(empty_field),
        )?;
        let column = Column::new(field.name(), col_index);
        Ok(ExprBoundaries {
            column,
            interval: Some(interval),
            distinct_count: col_stats.distinct_count,
        })
    }

    /// Create `ExprBoundaries` that represent no known bounds for all the
    /// columns in `schema`
    pub fn try_new_unbounded(schema: &Schema) -> Result<Vec<Self>> {
        schema
            .fields()
            .iter()
            .enumerate()
            .map(|(i, field)| {
                Ok(Self {
                    column: Column::new(field.name(), i),
                    interval: Some(Interval::make_unbounded(field.data_type())?),
                    distinct_count: Precision::Absent,
                })
            })
            .collect()
    }
}

/// Attempts to refine column boundaries and compute a selectivity value.
///
/// The function accepts boundaries of the input columns in the `context` parameter.
/// It then tries to tighten these boundaries based on the provided `expr`.
/// The resulting selectivity value is calculated by comparing the initial and final boundaries.
/// The computation assumes that the data within the column is uniformly distributed and not sorted.
///
/// # Arguments
///
/// * `context` - The context holding input column boundaries.
/// * `expr` - The expression used to shrink the column boundaries.
///
/// # Returns
///
/// * `AnalysisContext` constructed by pruned boundaries and a selectivity value.
pub fn analyze(
    expr: &Arc<dyn PhysicalExpr>,
    context: AnalysisContext,
    schema: &Schema,
) -> Result<AnalysisContext> {
    let initial_boundaries = &context.boundaries;

    if initial_boundaries
        .iter()
        .all(|bound| bound.interval.is_none())
    {
        assert_or_internal_err!(
            !initial_boundaries
                .iter()
                .any(|bound| bound.distinct_count != Precision::Exact(0)),
            "ExprBoundaries has a non-zero distinct count although it represents an empty table"
        );
        assert_or_internal_err!(
            context.selectivity.unwrap_or(0.0) == 0.0,
            "AnalysisContext has a non-zero selectivity although it represents an empty table"
        );
        Ok(context)
    } else if initial_boundaries
        .iter()
        .any(|bound| bound.interval.is_none())
    {
        internal_err!(
            "AnalysisContext is an inconsistent state. Some columns represent empty table while others don't"
        )
    } else {
        let mut target_boundaries = context.boundaries;
        let mut graph = ExprIntervalGraph::try_new(Arc::clone(expr), schema)?;
        let columns = collect_columns(expr)
            .into_iter()
            .map(|c| Arc::new(c) as _)
            .collect::<Vec<_>>();

        let target_expr_and_indices = graph.gather_node_indices(columns.as_slice());
        let mut target_indices_and_boundaries =
            Vec::with_capacity(target_expr_and_indices.len());

        for (expr, index) in &target_expr_and_indices {
            if let Some(column) = expr.downcast_ref::<Column>()
                && let Some(bound) =
                    target_boundaries.iter().find(|b| b.column == *column)
            {
                // Now, it's safe to unwrap
                target_indices_and_boundaries
                    .push((*index, bound.interval.as_ref().unwrap().clone()));
            }
        }

        match graph.update_ranges(&mut target_indices_and_boundaries, Interval::TRUE)? {
            PropagationResult::Success => {
                shrink_boundaries(&graph, target_boundaries, &target_expr_and_indices)
            }
            PropagationResult::Infeasible => {
                // If the propagation result is infeasible, set intervals to None
                for bound in &mut target_boundaries {
                    bound.interval = None;
                }
                Ok(AnalysisContext::new(target_boundaries).with_selectivity(0.0))
            }
            PropagationResult::CannotPropagate => {
                Ok(AnalysisContext::new(target_boundaries).with_selectivity(1.0))
            }
        }
    }
}

/// If the `PropagationResult` indicates success, this function calculates the
/// selectivity value by comparing the initial and final column boundaries.
/// Following this, it constructs and returns a new `AnalysisContext` with the
/// updated parameters.
fn shrink_boundaries(
    graph: &ExprIntervalGraph,
    mut target_boundaries: Vec<ExprBoundaries>,
    target_expr_and_indices: &[(Arc<dyn PhysicalExpr>, usize)],
) -> Result<AnalysisContext> {
    let initial_boundaries = target_boundaries.clone();
    for (expr, i) in target_expr_and_indices {
        if let Some(column) = expr.downcast_ref::<Column>()
            && let Some(bound) = target_boundaries
                .iter_mut()
                .find(|bound| bound.column.eq(column))
        {
            bound.interval = Some(graph.get_interval(*i));
        }
    }

    let selectivity = calculate_selectivity(&target_boundaries, &initial_boundaries)?;

    assert_or_internal_err!(
        (0.0..=1.0).contains(&selectivity),
        "Selectivity is out of limit: {selectivity}",
    );

    Ok(AnalysisContext::new(target_boundaries).with_selectivity(selectivity))
}

/// Returns `Some(1.0 / distinct_count)` when the filter demonstrably collapsed
/// a non-singleton interval down to a single point, i.e. an equality predicate
/// was applied.  Returns `None` in all other cases, signalling that the caller
/// should fall back to [`cardinality_ratio`].
///
/// The `initial_interval` guard prevents double-counting selectivity when the
/// column statistics already described a singleton before any filter was
/// applied: if the initial interval was already the same single point, no
/// additional selectivity has been gained and the `1 / NDV` shortcut must not
/// fire.
fn singleton_selectivity(
    initial_interval: &Interval,
    target_interval: &Interval,
    distinct_count: usize,
) -> Option<f64> {
    // The target must have collapsed to a single non-null value.
    if distinct_count == 0
        || target_interval.lower().is_null()
        || target_interval.lower() != target_interval.upper()
    {
        return None;
    }

    // Only treat this as a newly-applied equality filter when the initial
    // interval was not already that same singleton.  If it was, the stats
    // already encoded this restriction and applying 1/NDV again would
    // under-estimate the row count.
    let initial_is_same_singleton = !initial_interval.lower().is_null()
        && initial_interval.lower() == initial_interval.upper()
        && initial_interval.lower() == target_interval.lower();

    if initial_is_same_singleton {
        return None;
    }

    Some(1.0 / distinct_count as f64)
}

/// This function calculates the filter predicate's selectivity by comparing
/// the initial and pruned column boundaries. Selectivity is defined as the
/// ratio of rows in a table that satisfy the filter's predicate.
fn calculate_selectivity(
    target_boundaries: &[ExprBoundaries],
    initial_boundaries: &[ExprBoundaries],
) -> Result<f64> {
    // Since the intervals are assumed uniform and the values
    // are not correlated, we need to multiply the selectivities
    // of multiple columns to get the overall selectivity.
    if target_boundaries.len() != initial_boundaries.len() {
        return Err(internal_datafusion_err!(
            "The number of columns in the initial and target boundaries should be the same"
        ));
    }
    let mut acc: f64 = 1.0;
    for (initial, target) in initial_boundaries.iter().zip(target_boundaries) {
        match (initial.interval.as_ref(), target.interval.as_ref()) {
            (Some(initial_interval), Some(target_interval)) => {
                if let Precision::Exact(distinct_count)
                | Precision::Inexact(distinct_count) = target.distinct_count
                    && let Some(s) = singleton_selectivity(
                        initial_interval,
                        target_interval,
                        distinct_count,
                    )
                {
                    acc *= s;
                    continue;
                }
                acc *= cardinality_ratio(initial_interval, target_interval);
            }
            (None, Some(_)) => {
                return internal_err!(
                    "Initial boundary cannot be None while having a Some() target boundary"
                );
            }
            _ => return Ok(0.0),
        }
    }

    Ok(acc)
}

#[cfg(test)]
mod tests {
    use std::ops::Not;
    use std::sync::Arc;

    use arrow::datatypes::{DataType, Field, Schema};
    use datafusion_common::{DFSchema, ScalarValue, assert_contains, stats::Precision};
    use datafusion_expr::{
        Expr, col, execution_props::ExecutionProps, interval_arithmetic::Interval, lit,
        physical_planning_context::PhysicalPlanningContext,
    };

    use crate::{AnalysisContext, create_physical_expr, expressions::Column};

    use super::{ExprBoundaries, analyze, calculate_selectivity, singleton_selectivity};

    fn make_field(name: &str, data_type: DataType) -> Field {
        let nullable = false;
        Field::new(name, data_type, nullable)
    }

    #[test]
    fn test_analyze_boundary_exprs() {
        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Int32)]));

        /// Test case containing (expression tree, lower bound, upper bound)
        type TestCase = (Expr, Option<i32>, Option<i32>);

        let test_cases: Vec<TestCase> = vec![
            // a > 10
            (col("a").gt(lit(10)), Some(11), None),
            // a < 20
            (col("a").lt(lit(20)), None, Some(19)),
            // a > 10 AND a < 20
            (
                col("a").gt(lit(10)).and(col("a").lt(lit(20))),
                Some(11),
                Some(19),
            ),
            // a >= 10
            (col("a").gt_eq(lit(10)), Some(10), None),
            // a <= 20
            (col("a").lt_eq(lit(20)), None, Some(20)),
            // a >= 10 AND a <= 20
            (
                col("a").gt_eq(lit(10)).and(col("a").lt_eq(lit(20))),
                Some(10),
                Some(20),
            ),
            // a > 10 AND a < 20 AND a < 15
            (
                col("a")
                    .gt(lit(10))
                    .and(col("a").lt(lit(20)))
                    .and(col("a").lt(lit(15))),
                Some(11),
                Some(14),
            ),
            // (a > 10 AND a < 20) AND (a > 15 AND a < 25)
            (
                col("a")
                    .gt(lit(10))
                    .and(col("a").lt(lit(20)))
                    .and(col("a").gt(lit(15)))
                    .and(col("a").lt(lit(25))),
                Some(16),
                Some(19),
            ),
        ];
        for (expr, lower, upper) in test_cases {
            let boundaries = ExprBoundaries::try_new_unbounded(&schema).unwrap();
            let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
            let physical_expr = create_physical_expr(
                &expr,
                &df_schema,
                &ExecutionProps::new(),
                &PhysicalPlanningContext::default(),
            )
            .unwrap();
            let analysis_result = analyze(
                &physical_expr,
                AnalysisContext::new(boundaries),
                df_schema.as_ref(),
            )
            .unwrap();
            let Some(actual) = &analysis_result.boundaries[0].interval else {
                panic!(
                    "The analysis result should contain non-empty intervals for all columns"
                );
            };
            let expected = Interval::make(lower, upper).unwrap();
            assert_eq!(
                &expected, actual,
                "did not get correct interval for SQL expression: {expr:?}"
            );
        }
    }

    #[test]
    fn test_analyze_empty_set_boundary_exprs() {
        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Int32)]));

        let test_cases: Vec<Expr> = vec![
            // a > 10 AND a < 10
            col("a").gt(lit(10)).and(col("a").lt(lit(10))),
            // a > 5 AND (a < 20 OR a > 20)
            // a > 10 AND a < 20
            // (a > 10 AND a < 20) AND (a > 20 AND a < 30)
            col("a")
                .gt(lit(10))
                .and(col("a").lt(lit(20)))
                .and(col("a").gt(lit(20)))
                .and(col("a").lt(lit(30))),
        ];

        for expr in test_cases {
            let boundaries = ExprBoundaries::try_new_unbounded(&schema).unwrap();
            let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
            let physical_expr = create_physical_expr(
                &expr,
                &df_schema,
                &ExecutionProps::new(),
                &PhysicalPlanningContext::default(),
            )
            .unwrap();
            let analysis_result = analyze(
                &physical_expr,
                AnalysisContext::new(boundaries),
                df_schema.as_ref(),
            )
            .unwrap();

            for boundary in analysis_result.boundaries {
                assert!(boundary.interval.is_none());
            }
        }
    }

    #[test]
    fn test_analyze_invalid_boundary_exprs() {
        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Int32)]));
        let expr = col("a").lt(lit(10)).or(col("a").gt(lit(20)));
        let expected_error = "OR operator cannot yet propagate true intervals";
        let boundaries = ExprBoundaries::try_new_unbounded(&schema).unwrap();
        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
        let physical_expr = create_physical_expr(
            &expr,
            &df_schema,
            &ExecutionProps::new(),
            &PhysicalPlanningContext::default(),
        )
        .unwrap();
        let analysis_error = analyze(
            &physical_expr,
            AnalysisContext::new(boundaries),
            df_schema.as_ref(),
        )
        .unwrap_err();
        assert_contains!(analysis_error.to_string(), expected_error);
    }

    // ---------------------------------------------------------------------------
    // Unit tests for singleton_selectivity and calculate_selectivity
    // ---------------------------------------------------------------------------

    fn make_boundary(lower: i32, upper: i32, distinct_count: usize) -> ExprBoundaries {
        ExprBoundaries {
            column: Column::new("a", 0),
            interval: Some(
                Interval::try_new(
                    ScalarValue::Int32(Some(lower)),
                    ScalarValue::Int32(Some(upper)),
                )
                .unwrap(),
            ),
            distinct_count: Precision::Exact(distinct_count),
        }
    }

    /// When the initial interval is already the same singleton as the target,
    /// `singleton_selectivity` must return `None` so we do not double-apply
    /// 1/NDV selectivity.
    #[test]
    fn test_singleton_selectivity_skipped_when_initial_is_same_singleton() {
        let singleton =
            Interval::try_new(ScalarValue::Int32(Some(5)), ScalarValue::Int32(Some(5)))
                .unwrap();
        // Both initial and target are [5, 5] — no new equality filter was applied.
        assert_eq!(
            singleton_selectivity(&singleton, &singleton, 10),
            None,
            "shortcut must not fire when initial interval was already the same singleton"
        );
    }

    /// When the initial interval is a broader range and the target collapses to
    /// a singleton, `singleton_selectivity` must return `Some(1/NDV)`.
    #[test]
    fn test_singleton_selectivity_applied_when_range_collapses() {
        let initial =
            Interval::try_new(ScalarValue::Int32(Some(1)), ScalarValue::Int32(Some(100)))
                .unwrap();
        let target =
            Interval::try_new(ScalarValue::Int32(Some(5)), ScalarValue::Int32(Some(5)))
                .unwrap();
        let result = singleton_selectivity(&initial, &target, 10);
        assert_eq!(
            result,
            Some(0.1),
            "shortcut must return 1/NDV when a range collapses to a singleton"
        );
    }

    /// Regression test: `calculate_selectivity` must not apply the `1/NDV`
    /// shortcut when the column statistics already describe a singleton interval
    /// (i.e. before the filter, the column only ever held one value).  In that
    /// case the target and initial intervals are the same singleton, so the
    /// cardinality ratio is 1.0 and the overall selectivity should remain 1.0.
    #[test]
    fn test_calculate_selectivity_already_singleton_initial_interval() {
        let already_singleton = make_boundary(7, 7, 1);

        let selectivity = calculate_selectivity(
            std::slice::from_ref(&already_singleton),
            std::slice::from_ref(&already_singleton),
        )
        .unwrap();

        let wide_initial = make_boundary(1, 100, 50);
        let same_singleton_target = make_boundary(7, 7, 50);
        let selectivity_new =
            calculate_selectivity(&[same_singleton_target], &[wide_initial]).unwrap();
        assert!(
            (selectivity_new - 0.02).abs() < 1e-10,
            "expected selectivity 1/NDV = 0.02, got {selectivity_new}"
        );

        let singleton_initial = make_boundary(7, 7, 50);
        let singleton_target = make_boundary(7, 7, 50);
        let selectivity_no_new_filter =
            calculate_selectivity(&[singleton_target], &[singleton_initial]).unwrap();
        assert!(
            (selectivity_no_new_filter - 1.0).abs() < 1e-10,
            "expected selectivity 1.0 when initial was already the same singleton, got {selectivity_no_new_filter}"
        );

        let _ = selectivity; // silence unused warning
    }

    // Regression tests for #19264.
    //
    // `analyze` propagates constraints through `NotExpr::propagate_constraints`,
    // which hands the underlying `Eq` node a `FALSE` parent interval. When the
    // input domain contains `0.0` but is not equal to it, `NOT (a = 0.0)` is
    // satisfiable, so `analyze` reports the input domain. `None` is reserved
    // for an empty set, as documented on `ExprBoundaries::interval`.
    fn analyze_not_eq_helper(
        lower: f32,
        upper: f32,
    ) -> datafusion_common::Result<Option<Interval>> {
        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Float32)]));
        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();

        // Input column bounds: [lower, upper]
        let boundaries = vec![ExprBoundaries {
            column: Column::new("a", 0),
            interval: Some(Interval::try_new(
                ScalarValue::Float32(Some(lower)),
                ScalarValue::Float32(Some(upper)),
            )?),
            distinct_count: Precision::Inexact(100),
        }];
        let ctx = AnalysisContext::new(boundaries);

        // Predicate: NOT (a = 0.0)
        let pred_not_eq = col("a").eq(lit(0.0f32)).not();
        let phys_not = create_physical_expr(
            &pred_not_eq,
            &df_schema,
            &ExecutionProps::new(),
            &PhysicalPlanningContext::default(),
        )?;
        let out = analyze(&phys_not, ctx, df_schema.as_ref())?;
        Ok(out.boundaries[0].interval.clone())
    }

    #[test]
    fn test_analyze_not_eq_around_zero() -> datafusion_common::Result<()> {
        // Input domain [-1, 1] contains 0.0.
        // `NOT (a = 0.0)` can be true everywhere except at 0.0, so the output
        // interval should be the full input domain [-1, 1], NOT None.
        let out = analyze_not_eq_helper(-1.0, 1.0)?;
        let expected = Some(Interval::try_new(
            ScalarValue::Float32(Some(-1.0)),
            ScalarValue::Float32(Some(1.0)),
        )?);
        assert_eq!(
            out, expected,
            "NOT (a = 0.0) over [-1, 1] should yield [-1, 1], got {out:?}"
        );
        Ok(())
    }

    #[test]
    fn test_analyze_not_eq_clamped_at_zero() -> datafusion_common::Result<()> {
        // Input domain [0, 0] is exactly the point where a = 0.0 is true.
        // `NOT (a = 0.0)` is always false here, so the output interval should be None.
        let out = analyze_not_eq_helper(0.0, 0.0)?;
        assert_eq!(
            out, None,
            "NOT (a = 0.0) over [0, 0] should yield None (infeasible), got {out:?}"
        );
        Ok(())
    }

    fn analyze_not_eq_f64_helper(
        lower: f64,
        upper: f64,
    ) -> datafusion_common::Result<Option<Interval>> {
        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Float64)]));
        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();

        let boundaries = vec![ExprBoundaries {
            column: Column::new("a", 0),
            interval: Some(Interval::try_new(
                ScalarValue::Float64(Some(lower)),
                ScalarValue::Float64(Some(upper)),
            )?),
            distinct_count: Precision::Inexact(100),
        }];
        let ctx = AnalysisContext::new(boundaries);

        let pred_not_eq = col("a").eq(lit(0.0f64)).not();
        let phys_not = create_physical_expr(
            &pred_not_eq,
            &df_schema,
            &ExecutionProps::new(),
            &PhysicalPlanningContext::default(),
        )?;
        let out = analyze(&phys_not, ctx, df_schema.as_ref())?;
        Ok(out.boundaries[0].interval.clone())
    }

    // Regression test for the signed-zero singleton case.
    //
    // `Interval::try_new` orders endpoints with `total_cmp`, so
    // `[-0.0, +0.0]` is a valid input domain. Its endpoints differ bit-wise
    // but denote a single value under `Eq` comparison semantics, so
    // `a = 0.0` is certainly true over it and `NOT (a = 0.0)` is infeasible.
    // A bit-wise singleton check in `propagate_comparison` would instead
    // report the input domain, i.e. a false-feasibility result on the public
    // `analyze` path.
    #[test]
    fn test_analyze_not_eq_signed_zero_span_infeasible() -> datafusion_common::Result<()>
    {
        let out = analyze_not_eq_helper(-0.0, 0.0)?;
        assert_eq!(
            out, None,
            "NOT (a = 0.0) over Float32 [-0.0, +0.0] should yield None (infeasible), got {out:?}"
        );

        let out = analyze_not_eq_f64_helper(-0.0, 0.0)?;
        assert_eq!(
            out, None,
            "NOT (a = 0.0) over Float64 [-0.0, +0.0] should yield None (infeasible), got {out:?}"
        );
        Ok(())
    }

    fn analyze_between_helper(
        lower: f32,
        upper: f32,
        negated: bool,
        explicit_not: bool,
    ) -> datafusion_common::Result<Option<Interval>> {
        let schema = Arc::new(Schema::new(vec![make_field("a", DataType::Float32)]));
        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();
        let boundaries = vec![ExprBoundaries {
            column: Column::new("a", 0),
            interval: Some(Interval::try_new(
                ScalarValue::Float32(Some(lower)),
                ScalarValue::Float32(Some(upper)),
            )?),
            distinct_count: Precision::Inexact(100),
        }];

        let between = col("a").between(lit(-1.0f32), lit(1.0f32));
        let predicate = if explicit_not {
            between.not()
        } else if negated {
            col("a").not_between(lit(-1.0f32), lit(1.0f32))
        } else {
            between
        };
        let physical_expr = create_physical_expr(
            &predicate,
            &df_schema,
            &ExecutionProps::new(),
            &PhysicalPlanningContext::default(),
        )?;
        let output = analyze(
            &physical_expr,
            AnalysisContext::new(boundaries),
            df_schema.as_ref(),
        )?;
        Ok(output.boundaries[0].interval.clone())
    }

    #[test]
    fn test_analyze_not_between_clamped() -> datafusion_common::Result<()> {
        let expected = Some(Interval::try_new(
            ScalarValue::Float32(Some(-1.0)),
            ScalarValue::Float32(Some(1.0)),
        )?);
        assert_eq!(analyze_between_helper(-1.0, 1.0, false, false)?, expected);
        assert_eq!(analyze_between_helper(-1.0, 1.0, true, false)?, None);
        assert_eq!(analyze_between_helper(-1.0, 1.0, false, true)?, None);
        Ok(())
    }

    #[test]
    fn test_analyze_not_between_containing() -> datafusion_common::Result<()> {
        let between = Some(Interval::try_new(
            ScalarValue::Float32(Some(-1.0)),
            ScalarValue::Float32(Some(1.0)),
        )?);
        let containing = Some(Interval::try_new(
            ScalarValue::Float32(Some(-2.0)),
            ScalarValue::Float32(Some(2.0)),
        )?);
        assert_eq!(analyze_between_helper(-2.0, 2.0, false, false)?, between);
        assert_eq!(analyze_between_helper(-2.0, 2.0, true, false)?, containing);
        assert_eq!(analyze_between_helper(-2.0, 2.0, false, true)?, containing);
        Ok(())
    }

    // Regression test for the nested signed-zero case.
    //
    // `NOT(a = +0.0) AND b` with `a ∈ [-0.0,-0.0]`, `b ∈ [false,true]`:
    // `a = +0.0` is TRUE (IEEE 754), so the whole predicate is infeasible.
    //
    // This defeats the case-(1) short-circuit in `update_ranges`: bottom-up
    // evaluates `a = +0.0` over `[-0.0,-0.0]` as FALSE (structural equality),
    // so `NOT` becomes TRUE, the root becomes `TRUE_OR_FALSE`, and top-down
    // propagation forces `a = +0.0` to FALSE, reaching
    // `propagate_comparison(Eq, FALSE, [-0.0,-0.0], [+0.0,+0.0])`. The guard
    // must normalize signed zero to report infeasible here.
    #[test]
    fn test_analyze_not_eq_nested_signed_zero_infeasible() -> datafusion_common::Result<()>
    {
        let schema = Arc::new(Schema::new(vec![
            make_field("a", DataType::Float32),
            make_field("b", DataType::Boolean),
        ]));
        let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap();

        let boundaries = vec![
            ExprBoundaries {
                column: Column::new("a", 0),
                interval: Some(Interval::try_new(
                    ScalarValue::Float32(Some(-0.0f32)),
                    ScalarValue::Float32(Some(-0.0f32)),
                )?),
                distinct_count: Precision::Inexact(1),
            },
            ExprBoundaries {
                column: Column::new("b", 1),
                interval: Some(Interval::try_new(
                    ScalarValue::Boolean(Some(false)),
                    ScalarValue::Boolean(Some(true)),
                )?),
                distinct_count: Precision::Inexact(2),
            },
        ];
        let ctx = AnalysisContext::new(boundaries);

        // NOT(a = +0.0) AND b
        let pred = col("a").eq(lit(0.0f32)).not().and(col("b"));
        let phys = create_physical_expr(
            &pred,
            &df_schema,
            &ExecutionProps::new(),
            &PhysicalPlanningContext::default(),
        )?;
        let out = analyze(&phys, ctx, df_schema.as_ref())?;

        // Infeasible: a = +0.0 is TRUE (signed zero), NOT is FALSE,
        // FALSE AND b = FALSE. All column intervals must be None.
        assert!(
            out.boundaries.iter().all(|b| b.interval.is_none()),
            "NOT(a = +0.0) AND b over a=[-0.0,-0.0] should be infeasible (all boundaries None), got {:?}",
            out.boundaries
        );
        assert_eq!(
            out.selectivity,
            Some(0.0),
            "selectivity should be 0.0 for an infeasible predicate, got {:?}",
            out.selectivity
        );
        Ok(())
    }
}