datafusion-optimizer 56.0.0

DataFusion Query Optimizer
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
// 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

//! Simplifies predicates by reducing redundant or overlapping conditions.
//!
//! This module provides functionality to optimize logical predicates used in query planning
//! by eliminating redundant conditions, thus reducing the number of predicates to evaluate.
//! Unlike the simplifier in `simplify_expressions/simplify_exprs.rs`, which focuses on
//! general expression simplification (e.g., constant folding and algebraic simplifications),
//! this module specifically targets predicate optimization by handling containment relationships.
//! For example, it can simplify `x > 5 AND x > 6` to just `x > 6`, as the latter condition
//! encompasses the former, resulting in fewer checks during query execution.
//! Conjunctions that no value can satisfy, such as `x > 6 AND x < 5`, are replaced with
//! `false` so that later rules can prune the plan they filter.

use super::utils::{is_false, is_null};
use datafusion_common::{Column, DataFusionError, Result, ScalarValue, internal_err};
use datafusion_expr::utils::{
    conjunction, disjunction, split_binary_owned, split_conjunction_owned,
};
use datafusion_expr::{BinaryExpr, Expr, Operator, lit};
use indexmap::IndexSet;
use std::cmp::Ordering;
use std::collections::BTreeMap;

const MAX_DISJUNCTION_WORK: usize = 4096;
const MAX_DISJUNCTION_DEPTH: usize = 32;

/// Simplifies a list of predicates by removing redundancies.
///
/// This function takes a vector of predicate expressions and groups them by the column they reference.
/// Predicates that reference a single column and are comparison operations (e.g., >, >=, <, <=, =, !=)
/// are analyzed to remove redundant conditions. For instance, `x > 5 AND x > 6` is simplified to
/// `x > 6`. Predicates that contradict each other, such as `x > 6 AND x < 5`, reduce the whole
/// conjunction to `false`. Other predicates that do not fit this pattern are retained as-is.
/// Comparisons in an enclosing conjunction also constrain each branch of an `OR`:
/// `x >= 10 AND (x < 3 OR x < 7)` cannot be true. This simplification preserves
/// which rows pass a filter, rather than Boolean values in projection expressions.
///
/// # Arguments
/// * `predicates` - A vector of `Expr` representing the predicates to simplify.
///
/// # Returns
/// A `Result` containing a vector of simplified `Expr` predicates.
pub fn simplify_predicates(predicates: Vec<Expr>) -> Result<Vec<Expr>> {
    let mut remaining = MAX_DISJUNCTION_WORK;
    simplify_with_context(predicates, &[], 0, &mut remaining)
}

/// Only descend through positive AND/OR expressions. In particular, replacing a
/// nullable, unsatisfiable predicate with false below NOT would change its truth set.
/// Keep assumptions outside the expressions they simplify, and never distribute
/// conjunctions over disjunctions. The budget bounds repeated comparison work.
fn simplify_with_context(
    predicates: Vec<Expr>,
    assumptions: &[Expr],
    depth: usize,
    remaining: &mut usize,
) -> Result<Vec<Expr>> {
    let predicates = simplify_conjunction(predicates)?;
    if predicates.iter().any(is_false) {
        return Ok(always_false());
    }
    let has_disjunction = predicates.iter().any(|expr| {
        matches!(
            expr,
            Expr::BinaryExpr(BinaryExpr {
                op: Operator::Or,
                ..
            })
        )
    });
    if assumptions.is_empty() && !has_disjunction {
        return Ok(predicates);
    }
    let cost = assumptions.len().saturating_add(predicates.len());
    if depth >= MAX_DISJUNCTION_DEPTH || cost > *remaining {
        return Ok(predicates);
    }
    *remaining -= cost;

    let context = assumptions
        .iter()
        .chain(predicates.iter().filter(|expr| is_column_comparison(expr)))
        .cloned()
        .collect();
    let context = simplify_conjunction(context)?;
    if context.iter().any(is_false) {
        return Ok(always_false());
    }

    let mut result = Vec::with_capacity(predicates.len());
    for predicate in predicates {
        let predicate = simplify_disjunction(predicate, &context, depth, remaining)?;
        if is_false(&predicate) {
            return Ok(always_false());
        }
        result.push(predicate);
    }
    Ok(result)
}

fn simplify_disjunction(
    predicate: Expr,
    assumptions: &[Expr],
    depth: usize,
    remaining: &mut usize,
) -> Result<Expr> {
    if !matches!(
        predicate,
        Expr::BinaryExpr(BinaryExpr {
            op: Operator::Or,
            ..
        })
    ) {
        return Ok(predicate);
    }
    let mut simplify_branch = |branch| {
        let original = split_conjunction_owned(branch);
        let predicates =
            simplify_with_context(original.clone(), assumptions, depth + 1, remaining)?;
        // Grouping comparisons by column can merely permute an AND branch.
        // Preserve its evaluation order when no predicates were simplified.
        let predicates = if original.len() == predicates.len()
            && original != predicates
            && original.iter().collect::<IndexSet<_>>()
                == predicates.iter().collect::<IndexSet<_>>()
        {
            original
        } else {
            predicates
        };
        Ok::<_, DataFusionError>(conjunction(predicates).unwrap_or_else(|| lit(true)))
    };
    // Flatten OR chains so the depth limit counts AND/OR nesting, not disjuncts.
    let mut branches = Vec::new();
    for branch in split_binary_owned(predicate, Operator::Or) {
        let branch = simplify_branch(branch)?;
        if !is_false(&branch) {
            branches.push(branch);
        }
    }
    Ok(disjunction(branches).unwrap_or_else(|| lit(false)))
}

fn is_column_comparison(expr: &Expr) -> bool {
    matches!(expr,
        Expr::BinaryExpr(BinaryExpr { left, op, right })
            if matches!(op, Operator::Eq | Operator::NotEq | Operator::Lt
                | Operator::LtEq | Operator::Gt | Operator::GtEq)
            && ((matches!(left.as_ref(), Expr::Column(_)) && right.as_literal().is_some())
                || (matches!(right.as_ref(), Expr::Column(_)) && left.as_literal().is_some()))
    )
}

fn simplify_conjunction(predicates: Vec<Expr>) -> Result<Vec<Expr>> {
    // Early return for simple cases
    if predicates.len() <= 1 {
        return Ok(predicates);
    }

    // Group predicates by their column reference
    let mut column_predicates: BTreeMap<Column, Vec<Expr>> = BTreeMap::new();
    let mut other_predicates = Vec::with_capacity(predicates.len());

    for pred in predicates {
        match pred {
            Expr::BinaryExpr(BinaryExpr { left, op, right })
                if matches!(
                    op,
                    Operator::Gt
                        | Operator::GtEq
                        | Operator::Lt
                        | Operator::LtEq
                        | Operator::Eq
                        | Operator::NotEq
                ) && !is_null(&left)
                    && !is_null(&right)
                    && right
                        .as_literal()
                        .or_else(|| left.as_literal())
                        .is_some_and(|literal| !literal.data_type().is_nested()) =>
            {
                if let (Some(col), Some(_)) =
                    (extract_column_from_expr(&left), right.as_literal())
                {
                    let mut right = right;
                    normalize_literal(right.as_mut());
                    column_predicates
                        .entry(col)
                        .or_default()
                        .push(Expr::BinaryExpr(BinaryExpr { left, op, right }));
                } else if let (Some(_), Some(col), Some(swapped_op)) = (
                    left.as_literal(),
                    extract_column_from_expr(&right),
                    op.swap(),
                ) {
                    // Put the literal on the right so that predicates differing only in
                    // operand order compare equal below
                    let mut left = left;
                    normalize_literal(left.as_mut());
                    column_predicates
                        .entry(col)
                        .or_default()
                        .push(Expr::BinaryExpr(BinaryExpr {
                            left: right,
                            op: swapped_op,
                            right: left,
                        }));
                } else {
                    other_predicates.push(Expr::BinaryExpr(BinaryExpr {
                        left,
                        op,
                        right,
                    }));
                }
            }
            _ => other_predicates.push(pred),
        }
    }

    // Process each column's predicates to remove redundancies
    let mut result = other_predicates;
    for (_, preds) in column_predicates {
        // Literals of one column that cannot be ordered against each other carry no
        // information we can use, so keep the predicates as they were written
        let simplified = match simplify_column_predicates(preds.clone()) {
            Ok(simplified) => simplified,
            Err(_) => preds,
        };
        if simplified.iter().any(is_false) {
            return Ok(always_false());
        }
        result.extend(simplified);
    }

    Ok(result)
}

/// Simplifies predicates related to a single column.
///
/// This function processes a list of predicates that all reference the same column and
/// simplifies them based on their operators. It groups predicates into greater-than (>, >=),
/// less-than (<, <=), equality (=) and inequality (!=) categories, then selects the most
/// restrictive condition in each category to reduce redundancy. For example, among `x > 5`
/// and `x > 6`, only `x > 6` is retained as it is more restrictive.
///
/// The reduced conditions are then compared with each other. An equality subsumes every
/// other condition it satisfies, an inequality is dropped once a bound already excludes its
/// value, and conditions that cannot hold at the same time, such as `x > 6 AND x < 5`,
/// reduce the whole list to a single `false` literal.
///
/// # Arguments
/// * `predicates` - A vector of `Expr` representing predicates for a single column.
///
/// # Returns
/// A `Result` containing a vector of simplified `Expr` predicates for the column.
fn simplify_column_predicates(predicates: Vec<Expr>) -> Result<Vec<Expr>> {
    if predicates.len() <= 1 {
        return Ok(predicates);
    }

    // Group by operator type, but combining similar operators
    let mut greater_predicates = Vec::new(); // Combines > and >=
    let mut less_predicates = Vec::new(); // Combines < and <=
    let mut eq_predicates = Vec::new();
    let mut not_eq_predicates = Vec::new();

    for pred in predicates {
        match &pred {
            Expr::BinaryExpr(BinaryExpr { op, .. }) => match op {
                Operator::Gt | Operator::GtEq => greater_predicates.push(pred),
                Operator::Lt | Operator::LtEq => less_predicates.push(pred),
                Operator::Eq => eq_predicates.push(pred),
                Operator::NotEq => not_eq_predicates.push(pred),
                _ => unreachable!("Unexpected operator: {}", op),
            },
            _ => unreachable!("Unexpected predicate {}", pred.to_string()),
        }
    }

    // Reduce each direction to its most restrictive bound: the highest value for the
    // greater-than-style predicates and the lowest value for the less-than-style ones.
    let lower_bound = find_most_restrictive_predicate(&greater_predicates, true)?;
    let upper_bound = find_most_restrictive_predicate(&less_predicates, false)?;

    if let Some(eq_predicate) = eq_predicates.pop() {
        let (_, value) = op_and_literal(&eq_predicate)?;

        // An equality pins the column to a single value, so it subsumes every other
        // predicate on that column: either the value satisfies them, which makes them
        // redundant, or it does not and no row can pass the conjunction.
        if !satisfies_all(
            value,
            eq_predicates
                .iter()
                .chain(not_eq_predicates.iter())
                .chain(lower_bound.iter())
                .chain(upper_bound.iter()),
        )? {
            return Ok(always_false());
        }
        return Ok(vec![eq_predicate]);
    }

    // Bounds that leave no room for any value cannot be satisfied together
    if let (Some(lower), Some(upper)) = (&lower_bound, &upper_bound)
        && is_empty_range(lower, upper)?
    {
        return Ok(always_false());
    }

    // An inequality is redundant once a bound already excludes the value it rules out
    let mut result = Vec::new();
    for not_eq_predicate in not_eq_predicates {
        let (_, value) = op_and_literal(&not_eq_predicate)?;
        if satisfies_all(value, lower_bound.iter().chain(upper_bound.iter()))? {
            result.push(not_eq_predicate);
        }
    }

    result.extend(lower_bound);
    result.extend(upper_bound);

    Ok(result)
}

/// Determines whether a lower and an upper bound leave no value that satisfies both.
///
/// For example `x > 5 AND x < 3` can never be true, and neither can `x > 1 AND x < 1`
/// because both comparisons are strict. `x >= 1 AND x <= 1` on the other hand is
/// satisfied by `x = 1`.
///
/// # Arguments
/// * `lower` - A predicate using `>` or `>=`.
/// * `upper` - A predicate using `<` or `<=`.
///
/// # Returns
/// A `Result` containing `true` if the two bounds contradict each other.
fn is_empty_range(lower: &Expr, upper: &Expr) -> Result<bool> {
    let (lower_op, lower_value) = op_and_literal(lower)?;
    let (upper_op, upper_value) = op_and_literal(upper)?;

    Ok(match lower_value.try_cmp(upper_value)? {
        Ordering::Less => false,
        Ordering::Greater => true,
        Ordering::Equal => lower_op == Operator::Gt || upper_op == Operator::Lt,
    })
}

/// Determines whether a row whose column equals `value` passes all of `predicates`.
///
/// # Arguments
/// * `value` - The literal the column is known to be equal to.
/// * `predicates` - Predicates on that same column, each of the form `column <op> literal`.
///
/// # Returns
/// A `Result` containing `false` as soon as one of the predicates rejects `value`.
fn satisfies_all<'a>(
    value: &ScalarValue,
    predicates: impl IntoIterator<Item = &'a Expr>,
) -> Result<bool> {
    for predicate in predicates {
        let (op, bound) = op_and_literal(predicate)?;
        let ordering = value.try_cmp(bound)?;
        let satisfied = match op {
            Operator::Gt => ordering == Ordering::Greater,
            Operator::GtEq => ordering != Ordering::Less,
            Operator::Lt => ordering == Ordering::Less,
            Operator::LtEq => ordering != Ordering::Greater,
            Operator::Eq => ordering == Ordering::Equal,
            Operator::NotEq => ordering != Ordering::Equal,
            _ => return internal_err!("Unexpected operator: {op}"),
        };
        if !satisfied {
            return Ok(false);
        }
    }

    Ok(true)
}

/// Extracts the operator and the literal of a `column <op> literal` predicate.
///
/// [`simplify_predicates`] normalizes the predicates it groups by column so that the
/// literal is always the right operand, so any other shape is an internal error.
///
/// # Arguments
/// * `predicate` - A reference to an `Expr` to destructure.
///
/// # Returns
/// A `Result` holding the operator and the literal the predicate compares against.
fn op_and_literal(predicate: &Expr) -> Result<(Operator, &ScalarValue)> {
    if let Expr::BinaryExpr(BinaryExpr { op, right, .. }) = predicate
        && let Some(literal) = right.as_literal()
    {
        Ok((*op, literal))
    } else {
        internal_err!("Unexpected predicate {predicate}")
    }
}

/// The executor folds `-0.0` into `0.0` before comparing floats (see
/// `datafusion_physical_expr_common::datum::apply_cmp`), while
/// [`ScalarValue::try_cmp`] orders `-0.0` below `0.0`. Fold it here too so the
/// decisions in this module match what the filter will evaluate.
fn normalize_literal(expr: &mut Expr) {
    if let Expr::Literal(value, _) = expr {
        let original = std::mem::replace(value, ScalarValue::Null);
        *value = original.normalize();
    }
}

/// Builds the predicate list of a conjunction that no row can satisfy.
fn always_false() -> Vec<Expr> {
    vec![lit(false)]
}

/// Finds the most restrictive predicate from a list based on literal values.
///
/// This function iterates through a list of predicates to identify the most restrictive one
/// by comparing their literal values. For greater-than predicates, the highest value is most
/// restrictive, while for less-than predicates, the lowest value is most restrictive.
///
/// # Arguments
/// * `predicates` - A slice of `Expr` representing predicates to compare.
/// * `find_greater` - A boolean indicating whether to find the highest value (true for >, >=)
///   or the lowest value (false for <, <=).
///
/// # Returns
/// A `Result` containing an `Option<Expr>` with the most restrictive predicate, if any.
fn find_most_restrictive_predicate(
    predicates: &[Expr],
    find_greater: bool,
) -> Result<Option<Expr>> {
    if predicates.is_empty() {
        return Ok(None);
    }

    let mut most_restrictive_idx = 0;
    let mut best_value: Option<&ScalarValue> = None;

    for (idx, pred) in predicates.iter().enumerate() {
        if let Expr::BinaryExpr(BinaryExpr { left, op, right }) = pred {
            // Extract the literal value based on which side has it
            let scalar_value = match (right.as_literal(), left.as_literal()) {
                (Some(scalar), _) => Some(scalar),
                (_, Some(scalar)) => Some(scalar),
                _ => None,
            };

            if let Some(scalar) = scalar_value {
                if let Some(current_best) = best_value {
                    let comparison = scalar.try_cmp(current_best)?;
                    let is_better = if find_greater {
                        comparison == Ordering::Greater
                            || (comparison == Ordering::Equal && op == &Operator::Gt)
                    } else {
                        comparison == Ordering::Less
                            || (comparison == Ordering::Equal && op == &Operator::Lt)
                    };

                    if is_better {
                        best_value = Some(scalar);
                        most_restrictive_idx = idx;
                    }
                } else {
                    best_value = Some(scalar);
                    most_restrictive_idx = idx;
                }
            }
        }
    }

    Ok(Some(predicates[most_restrictive_idx].clone()))
}

/// Extracts a column reference from an expression, if present.
///
/// This function checks if the given expression is a column reference or contains one,
/// such as within a cast operation. It returns the `Column` if found.
///
/// # Arguments
/// * `expr` - A reference to an `Expr` to inspect for a column reference.
///
/// # Returns
/// An `Option<Column>` containing the column reference if found, otherwise `None`.
fn extract_column_from_expr(expr: &Expr) -> Option<Column> {
    match expr {
        Expr::Column(col) => Some(col.clone()),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::datatypes::DataType;
    use datafusion_expr::{cast, col, lit};

    #[test]
    fn test_context_budget_exhaustion_is_conservative() -> Result<()> {
        let bound = col("x").gt_eq(lit(10));
        let disjunction = col("x").lt(lit(3)).or(col("x").lt(lit(7)));
        let predicates = vec![bound.clone(), disjunction.clone()];
        let result = simplify_with_context(predicates.clone(), &[], 0, &mut 0)?;
        assert_eq!(result.len(), 2);
        assert!(result.contains(&bound));
        assert!(result.contains(&disjunction));
        assert_eq!(simplify_predicates(predicates)?, vec![lit(false)]);
        Ok(())
    }

    #[test]
    fn test_context_depth_limit_is_conservative() -> Result<()> {
        let disjunction = col("x").lt(lit(3)).or(col("x").lt(lit(7)));
        let mut remaining = MAX_DISJUNCTION_WORK;
        let result = simplify_with_context(
            vec![disjunction.clone()],
            &[col("x").gt_eq(lit(10))],
            MAX_DISJUNCTION_DEPTH,
            &mut remaining,
        )?;
        assert_eq!(result, vec![disjunction]);
        Ok(())
    }

    #[test]
    fn test_simplify_predicates_with_cast() {
        // Test that predicates on cast expressions are not grouped with predicates on the raw column
        // a < 5 AND CAST(a AS varchar) < 'abc' AND a < 6
        // Should simplify to:
        // a < 5 AND CAST(a AS varchar) < 'abc'

        let predicates = vec![
            col("a").lt(lit(5i32)),
            cast(col("a"), DataType::Utf8).lt(lit("abc")),
            col("a").lt(lit(6i32)),
        ];

        let result = simplify_predicates(predicates).unwrap();

        // Should have 2 predicates: a < 5 and CAST(a AS varchar) < 'abc'
        assert_eq!(result.len(), 2);

        // Check that the cast predicate is preserved
        let has_cast_predicate = result.iter().any(|p| {
            matches!(p, Expr::BinaryExpr(BinaryExpr { 
                left, 
                op: Operator::Lt, 
                right 
            }) if matches!(left.as_ref(), Expr::Cast(_)) && right == &Box::new(lit("abc")))
        });
        assert!(has_cast_predicate, "Cast predicate should be preserved");

        // Check that we have the more restrictive column predicate (a < 5)
        let has_column_predicate = result.iter().any(|p| {
            matches!(p, Expr::BinaryExpr(BinaryExpr { 
                left, 
                op: Operator::Lt, 
                right 
            }) if left == &Box::new(col("a")) && right == &Box::new(lit(5i32)))
        });
        assert!(has_column_predicate, "Should have a < 5 predicate");
    }

    #[test]
    fn test_extract_column_ignores_cast() {
        // Test that extract_column_from_expr does not extract columns from cast expressions
        let cast_expr = cast(col("a"), DataType::Utf8);
        assert_eq!(extract_column_from_expr(&cast_expr), None);

        // Test that it still extracts from direct column references
        let col_expr = col("a");
        assert_eq!(extract_column_from_expr(&col_expr), Some(Column::from("a")));
    }

    #[test]
    fn test_eq_predicates_are_matched_regardless_of_operand_order() {
        // a = 5 AND 5 = a is a single condition, not a contradiction
        let predicates = vec![col("a").eq(lit(5i32)), lit(5i32).eq(col("a"))];

        let result = simplify_predicates(predicates).unwrap();

        assert_eq!(result, vec![col("a").eq(lit(5i32))]);
    }

    #[test]
    fn test_strict_bound_wins_when_literal_is_on_the_left() {
        // a >= 5 AND 5 < a is a > 5; keeping a >= 5 would let a = 5 through
        let predicates = vec![col("a").gt_eq(lit(5i32)), lit(5i32).lt(col("a"))];

        let result = simplify_predicates(predicates).unwrap();

        assert_eq!(result, vec![col("a").gt(lit(5i32))]);
    }

    #[test]
    fn test_simplify_predicates_direct_columns_only() {
        // Test that only predicates on direct columns are simplified together
        let predicates = vec![
            col("a").lt(lit(5i32)),
            col("a").lt(lit(3i32)),
            col("b").gt(lit(10i32)),
            col("b").gt(lit(20i32)),
        ];

        let result = simplify_predicates(predicates).unwrap();

        // Should have 2 predicates: a < 3 and b > 20 (most restrictive for each column)
        assert_eq!(result.len(), 2);

        // Check for a < 3
        let has_a_predicate = result.iter().any(|p| {
            matches!(p, Expr::BinaryExpr(BinaryExpr { 
                left, 
                op: Operator::Lt, 
                right 
            }) if left == &Box::new(col("a")) && right == &Box::new(lit(3i32)))
        });
        assert!(has_a_predicate, "Should have a < 3 predicate");

        // Check for b > 20
        let has_b_predicate = result.iter().any(|p| {
            matches!(p, Expr::BinaryExpr(BinaryExpr { 
                left, 
                op: Operator::Gt, 
                right 
            }) if left == &Box::new(col("b")) && right == &Box::new(lit(20i32)))
        });
        assert!(has_b_predicate, "Should have b > 20 predicate");
    }

    #[test]
    fn test_equality_subsumes_predicates_it_satisfies() {
        // The value a is pinned to passes every other predicate, so only a = 5 is left
        for predicates in [
            vec![
                col("a").eq(lit(5i32)),
                col("a").gt(lit(3i32)),
                col("a").lt_eq(lit(5i32)),
                col("a").not_eq(lit(6i32)),
            ],
            vec![col("a").eq(lit(5i32)), col("a").gt_eq(lit(5i32))],
        ] {
            let result = simplify_predicates(predicates.clone()).unwrap();

            assert_eq!(result, vec![col("a").eq(lit(5i32))], "for {predicates:?}");
        }
    }

    #[test]
    fn test_equality_rejected_by_another_predicate_is_unsatisfiable() {
        // Each of these pins a to a value that the other predicate excludes
        for predicates in [
            vec![col("a").eq(lit(5i32)), col("a").eq(lit(6i32))],
            vec![col("a").eq(lit(5i32)), col("a").not_eq(lit(5i32))],
            vec![col("a").eq(lit(5i32)), col("a").gt(lit(5i32))],
            vec![col("a").eq(lit(5i32)), col("a").gt_eq(lit(6i32))],
            vec![col("a").eq(lit(5i32)), col("a").lt(lit(3i32))],
            vec![col("a").eq(lit(5i32)), col("a").lt_eq(lit(3i32))],
        ] {
            let result = simplify_predicates(predicates.clone()).unwrap();

            assert_eq!(result, vec![lit(false)], "for {predicates:?}");
        }
    }

    #[test]
    fn test_disjoint_bounds_are_unsatisfiable() {
        // The strict bounds exclude the value they share, so none of these can hold
        for predicates in [
            vec![col("a").gt(lit(5i32)), col("a").lt(lit(3i32))],
            vec![col("a").gt(lit(1i32)), col("a").lt(lit(1i32))],
            vec![col("a").gt_eq(lit(1i32)), col("a").lt(lit(1i32))],
            vec![col("a").gt(lit(1i32)), col("a").lt_eq(lit(1i32))],
        ] {
            let result = simplify_predicates(predicates.clone()).unwrap();

            assert_eq!(result, vec![lit(false)], "for {predicates:?}");
        }
    }

    #[test]
    fn test_satisfiable_bounds_are_kept() {
        // The second case only leaves a = 1, but both bounds are inclusive so it holds
        for predicates in [
            vec![col("a").gt(lit(1i32)), col("a").lt(lit(9i32))],
            vec![col("a").gt_eq(lit(1i32)), col("a").lt_eq(lit(1i32))],
        ] {
            let result = simplify_predicates(predicates.clone()).unwrap();

            assert_eq!(result, predicates, "for {predicates:?}");
        }
    }

    #[test]
    fn test_unsatisfiable_column_discards_other_predicates() {
        // Nothing can make the conjunction true once one column contradicts itself
        let predicates = vec![
            col("b").gt(lit(0i32)),
            col("a").gt(lit(5i32)),
            col("a").lt(lit(3i32)),
        ];

        let result = simplify_predicates(predicates).unwrap();

        assert_eq!(result, vec![lit(false)]);
    }

    #[test]
    fn test_not_eq_excluded_by_a_bound_is_removed() {
        // a > 10 already rules out a = 5
        let predicates = vec![col("a").gt(lit(10i32)), col("a").not_eq(lit(5i32))];

        let result = simplify_predicates(predicates).unwrap();

        assert_eq!(result, vec![col("a").gt(lit(10i32))]);
    }

    #[test]
    fn test_not_eq_inside_the_bounds_is_kept() {
        // 5 is within a > 1, so the inequality still filters rows
        let predicates = vec![col("a").gt(lit(1i32)), col("a").not_eq(lit(5i32))];

        let result = simplify_predicates(predicates).unwrap();

        assert_eq!(
            result,
            vec![col("a").not_eq(lit(5i32)), col("a").gt(lit(1i32))]
        );
    }

    #[test]
    fn test_signed_zero_literals_are_normalized() {
        let predicates = vec![col("f").eq(lit(-0.0_f64)), col("f").gt_eq(lit(0.0_f64))];

        let result = simplify_predicates(predicates).unwrap();

        assert_eq!(result, vec![col("f").eq(lit(0.0_f64))]);
    }

    #[test]
    fn test_null_comparisons_are_left_alone() {
        // Comparisons with NULL are never true, so they carry no bound to reason
        // about. Treating NULL as an ordinary value would drop `a > NULL` for being
        // less restrictive than `a > 5`, or drop `a != NULL` for being excluded by
        // `a > 5`, and either would let rows through that must be filtered out.
        for predicates in [
            vec![
                col("a").gt(lit(ScalarValue::Int32(None))),
                col("a").gt(lit(5i32)),
            ],
            vec![
                col("a").not_eq(lit(ScalarValue::Int32(None))),
                col("a").gt(lit(5i32)),
            ],
            vec![
                col("a").gt(lit(ScalarValue::Int32(None))),
                col("a").lt(lit(3i32)),
            ],
            vec![
                col("a").gt(lit(ScalarValue::Int32(None))),
                col("a").lt(lit(ScalarValue::Int32(None))),
            ],
        ] {
            let result = simplify_predicates(predicates.clone()).unwrap();

            assert_eq!(result, predicates, "for {predicates:?}");
        }
    }
}