Skip to main content

datafusion_physical_expr/simplifier/
mod.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//! Simplifier for Physical Expressions
6
7use arrow::datatypes::Schema;
8use datafusion_common::{Result, tree_node::TreeNode};
9use std::sync::Arc;
10
11use crate::{
12    PhysicalExpr,
13    simplifier::{
14        const_evaluator::create_dummy_batch, unwrap_cast::unwrap_cast_in_comparison,
15    },
16};
17
18pub mod const_evaluator;
19pub mod not;
20pub mod unwrap_cast;
21
22const MAX_LOOP_COUNT: usize = 5;
23
24/// Simplifies physical expressions by applying various optimizations
25///
26/// This can be useful after adapting expressions from a table schema
27/// to a file schema. For example, casts added to match the types may
28/// potentially be unwrapped.
29pub struct PhysicalExprSimplifier<'a> {
30    schema: &'a Schema,
31}
32
33impl<'a> PhysicalExprSimplifier<'a> {
34    /// Create a new physical expression simplifier
35    pub fn new(schema: &'a Schema) -> Self {
36        Self { schema }
37    }
38
39    /// Simplify a physical expression
40    pub fn simplify(&self, expr: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {
41        let mut current_expr = expr;
42        let mut count = 0;
43        let schema = self.schema;
44
45        let batch = create_dummy_batch()?;
46
47        while count < MAX_LOOP_COUNT {
48            count += 1;
49            let result = current_expr.transform(|node| {
50                #[cfg(debug_assertions)]
51                let original_type = node.data_type(schema).unwrap();
52
53                // Apply NOT expression simplification first, then unwrap cast optimization,
54                // then constant expression evaluation
55                #[expect(deprecated, reason = "`simplify_not_expr` is marked as deprecated until it's made private.")]
56                let rewritten = not::simplify_not_expr(node, schema)?
57                    .transform_data(|node| unwrap_cast_in_comparison(node, schema))?
58                    .transform_data(|node| {
59                        const_evaluator::simplify_const_expr_immediate(node, batch)
60                    })?;
61
62                #[cfg(debug_assertions)]
63                assert_eq!(
64                    rewritten.data.data_type(schema).unwrap(),
65                    original_type,
66                    "Simplified expression should have the same data type as the original"
67                );
68
69                Ok(rewritten)
70            })?;
71
72            if !result.transformed {
73                return Ok(result.data);
74            }
75            current_expr = result.data;
76        }
77        Ok(current_expr)
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    use crate::ScalarFunctionExpr;
85    use crate::expressions::{
86        BinaryExpr, CastExpr, Literal, NotExpr, TryCastExpr, col, in_list, lit,
87    };
88    use arrow::datatypes::{DataType, Field};
89    use datafusion_common::ScalarValue;
90    use datafusion_common::config::ConfigOptions;
91    use datafusion_expr::{
92        Operator, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, Volatility,
93    };
94    use datafusion_expr_common::columnar_value::ColumnarValue;
95    use datafusion_functions::regex::regexp_like;
96
97    fn test_schema() -> Schema {
98        Schema::new(vec![
99            Field::new("c1", DataType::Int32, false),
100            Field::new("c2", DataType::Int64, false),
101            Field::new("c3", DataType::Utf8, false),
102        ])
103    }
104
105    fn not_test_schema() -> Schema {
106        Schema::new(vec![
107            Field::new("a", DataType::Boolean, false),
108            Field::new("b", DataType::Boolean, false),
109            Field::new("c", DataType::Int32, false),
110        ])
111    }
112
113    /// Helper function to extract a Literal from a PhysicalExpr
114    fn as_literal(expr: &Arc<dyn PhysicalExpr>) -> &Literal {
115        expr.downcast_ref::<Literal>()
116            .unwrap_or_else(|| panic!("Expected Literal, got: {expr}"))
117    }
118
119    /// Helper function to extract a BinaryExpr from a PhysicalExpr
120    fn as_binary(expr: &Arc<dyn PhysicalExpr>) -> &BinaryExpr {
121        expr.downcast_ref::<BinaryExpr>()
122            .unwrap_or_else(|| panic!("Expected BinaryExpr, got: {expr}"))
123    }
124
125    /// Assert that simplifying `input` produces `expected`
126    fn assert_not_simplify(
127        simplifier: &PhysicalExprSimplifier,
128        input: Arc<dyn PhysicalExpr>,
129        expected: Arc<dyn PhysicalExpr>,
130    ) {
131        let result = simplifier.simplify(Arc::clone(&input)).unwrap();
132        assert_eq!(
133            &result, &expected,
134            "Simplification should transform:\n  input: {input}\n  to:    {expected}\n  got:   {result}"
135        );
136    }
137
138    #[test]
139    fn test_simplify() {
140        let schema = test_schema();
141        let simplifier = PhysicalExprSimplifier::new(&schema);
142
143        // Create: cast(c2 as INT32) != INT32(99)
144        // c2 is Int64 → Int64→Int32 is narrowing → blocked by family gate.
145        // The cast should stay.
146        let column_expr = col("c2", &schema).unwrap();
147        let cast_expr = Arc::new(CastExpr::new(column_expr, DataType::Int32, None));
148        let literal_expr = lit(ScalarValue::Int32(Some(99)));
149        let binary_expr =
150            Arc::new(BinaryExpr::new(cast_expr, Operator::NotEq, literal_expr));
151
152        // Apply full simplification (uses TreeNodeRewriter)
153        let optimized = simplifier.simplify(binary_expr).unwrap();
154
155        // With the family gate, Int64→Int32 is blocked and the cast remains.
156        let result_binary = as_binary(&optimized);
157        let result_left = result_binary.left();
158        assert!(
159            result_left.downcast_ref::<CastExpr>().is_some()
160                || result_left.downcast_ref::<TryCastExpr>().is_some(),
161            "CAST(c2 AS Int32) should remain as Int64→Int32 is narrowing"
162        );
163    }
164
165    #[test]
166    fn test_nested_expression_simplification() {
167        let schema = test_schema();
168        let simplifier = PhysicalExprSimplifier::new(&schema);
169
170        // Create nested expression: (cast(c1 as INT64) > INT64(5)) OR (cast(c2 as INT32) <= INT32(10))
171        let c1_expr = col("c1", &schema).unwrap();
172        let c1_cast = Arc::new(CastExpr::new(c1_expr, DataType::Int64, None));
173        let c1_literal = lit(ScalarValue::Int64(Some(5)));
174        let c1_binary = Arc::new(BinaryExpr::new(c1_cast, Operator::Gt, c1_literal));
175
176        let c2_expr = col("c2", &schema).unwrap();
177        let c2_cast = Arc::new(CastExpr::new(c2_expr, DataType::Int32, None));
178        let c2_literal = lit(ScalarValue::Int32(Some(10)));
179        let c2_binary = Arc::new(BinaryExpr::new(c2_cast, Operator::LtEq, c2_literal));
180
181        let or_expr = Arc::new(BinaryExpr::new(c1_binary, Operator::Or, c2_binary));
182
183        // Apply simplification
184        let optimized = simplifier.simplify(or_expr).unwrap();
185
186        let or_binary = as_binary(&optimized);
187
188        // Verify left side: c1 > INT32(5)  (Int32→Int64 widening, unwrapped)
189        let left_binary = as_binary(or_binary.left());
190        let left_left_expr = left_binary.left();
191        assert!(
192            left_left_expr.downcast_ref::<CastExpr>().is_none()
193                && left_left_expr.downcast_ref::<TryCastExpr>().is_none()
194        );
195        let left_literal = as_literal(left_binary.right());
196        assert_eq!(left_literal.value(), &ScalarValue::Int32(Some(5)));
197
198        // Verify right side: CAST(c2 AS Int32) <= 10  — Int64→Int32 is
199        // narrowing, blocked by the family gate, so the cast stays.
200        let right_binary = as_binary(or_binary.right());
201        let right_left_expr = right_binary.left();
202        assert!(
203            right_left_expr.downcast_ref::<CastExpr>().is_some()
204                || right_left_expr.downcast_ref::<TryCastExpr>().is_some(),
205            "CAST(c2 AS Int32) should remain as Int64→Int32 is narrowing"
206        );
207    }
208
209    #[test]
210    fn test_double_negation_elimination() -> Result<()> {
211        let schema = not_test_schema();
212        let simplifier = PhysicalExprSimplifier::new(&schema);
213
214        // NOT(NOT(c > 5)) -> c > 5
215        let inner_expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
216            col("c", &schema)?,
217            Operator::Gt,
218            lit(ScalarValue::Int32(Some(5))),
219        ));
220        let inner_not = Arc::new(NotExpr::new(Arc::clone(&inner_expr)));
221        let double_not: Arc<dyn PhysicalExpr> = Arc::new(NotExpr::new(inner_not));
222
223        let expected = inner_expr;
224        assert_not_simplify(&simplifier, double_not, expected);
225        Ok(())
226    }
227
228    #[test]
229    fn test_not_literal() -> Result<()> {
230        let schema = not_test_schema();
231        let simplifier = PhysicalExprSimplifier::new(&schema);
232
233        // NOT(TRUE) -> FALSE
234        let not_true = Arc::new(NotExpr::new(lit(ScalarValue::Boolean(Some(true)))));
235        let expected = lit(ScalarValue::Boolean(Some(false)));
236        assert_not_simplify(&simplifier, not_true, expected);
237
238        // NOT(FALSE) -> TRUE
239        let not_false = Arc::new(NotExpr::new(lit(ScalarValue::Boolean(Some(false)))));
240        let expected = lit(ScalarValue::Boolean(Some(true)));
241        assert_not_simplify(&simplifier, not_false, expected);
242
243        Ok(())
244    }
245
246    #[test]
247    fn test_negate_comparison() -> Result<()> {
248        let schema = not_test_schema();
249        let simplifier = PhysicalExprSimplifier::new(&schema);
250
251        // NOT(c = 5) -> c != 5
252        let not_eq = Arc::new(NotExpr::new(Arc::new(BinaryExpr::new(
253            col("c", &schema)?,
254            Operator::Eq,
255            lit(ScalarValue::Int32(Some(5))),
256        ))));
257        let expected = Arc::new(BinaryExpr::new(
258            col("c", &schema)?,
259            Operator::NotEq,
260            lit(ScalarValue::Int32(Some(5))),
261        ));
262        assert_not_simplify(&simplifier, not_eq, expected);
263
264        Ok(())
265    }
266
267    #[test]
268    fn test_demorgans_law_and() -> Result<()> {
269        let schema = not_test_schema();
270        let simplifier = PhysicalExprSimplifier::new(&schema);
271
272        // NOT(a AND b) -> NOT a OR NOT b
273        let and_expr = Arc::new(BinaryExpr::new(
274            col("a", &schema)?,
275            Operator::And,
276            col("b", &schema)?,
277        ));
278        let not_and: Arc<dyn PhysicalExpr> = Arc::new(NotExpr::new(and_expr));
279
280        let expected: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
281            Arc::new(NotExpr::new(col("a", &schema)?)),
282            Operator::Or,
283            Arc::new(NotExpr::new(col("b", &schema)?)),
284        ));
285        assert_not_simplify(&simplifier, not_and, expected);
286
287        Ok(())
288    }
289
290    #[test]
291    fn test_demorgans_law_or() -> Result<()> {
292        let schema = not_test_schema();
293        let simplifier = PhysicalExprSimplifier::new(&schema);
294
295        // NOT(a OR b) -> NOT a AND NOT b
296        let or_expr = Arc::new(BinaryExpr::new(
297            col("a", &schema)?,
298            Operator::Or,
299            col("b", &schema)?,
300        ));
301        let not_or: Arc<dyn PhysicalExpr> = Arc::new(NotExpr::new(or_expr));
302
303        let expected: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
304            Arc::new(NotExpr::new(col("a", &schema)?)),
305            Operator::And,
306            Arc::new(NotExpr::new(col("b", &schema)?)),
307        ));
308        assert_not_simplify(&simplifier, not_or, expected);
309
310        Ok(())
311    }
312
313    #[test]
314    fn test_demorgans_with_comparison_simplification() -> Result<()> {
315        let schema = not_test_schema();
316        let simplifier = PhysicalExprSimplifier::new(&schema);
317
318        // NOT(c = 1 AND c = 2) -> c != 1 OR c != 2
319        let eq1 = Arc::new(BinaryExpr::new(
320            col("c", &schema)?,
321            Operator::Eq,
322            lit(ScalarValue::Int32(Some(1))),
323        ));
324        let eq2 = Arc::new(BinaryExpr::new(
325            col("c", &schema)?,
326            Operator::Eq,
327            lit(ScalarValue::Int32(Some(2))),
328        ));
329        let and_expr = Arc::new(BinaryExpr::new(eq1, Operator::And, eq2));
330        let not_and: Arc<dyn PhysicalExpr> = Arc::new(NotExpr::new(and_expr));
331
332        let expected: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
333            Arc::new(BinaryExpr::new(
334                col("c", &schema)?,
335                Operator::NotEq,
336                lit(ScalarValue::Int32(Some(1))),
337            )),
338            Operator::Or,
339            Arc::new(BinaryExpr::new(
340                col("c", &schema)?,
341                Operator::NotEq,
342                lit(ScalarValue::Int32(Some(2))),
343            )),
344        ));
345        assert_not_simplify(&simplifier, not_and, expected);
346
347        Ok(())
348    }
349
350    #[test]
351    fn test_not_of_not_and_not() -> Result<()> {
352        let schema = not_test_schema();
353        let simplifier = PhysicalExprSimplifier::new(&schema);
354
355        // NOT(NOT(a) AND NOT(b)) -> a OR b
356        let not_a = Arc::new(NotExpr::new(col("a", &schema)?));
357        let not_b = Arc::new(NotExpr::new(col("b", &schema)?));
358        let and_expr = Arc::new(BinaryExpr::new(not_a, Operator::And, not_b));
359        let not_and: Arc<dyn PhysicalExpr> = Arc::new(NotExpr::new(and_expr));
360
361        let expected: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
362            col("a", &schema)?,
363            Operator::Or,
364            col("b", &schema)?,
365        ));
366        assert_not_simplify(&simplifier, not_and, expected);
367
368        Ok(())
369    }
370
371    #[test]
372    fn test_not_in_list() -> Result<()> {
373        let schema = not_test_schema();
374        let simplifier = PhysicalExprSimplifier::new(&schema);
375
376        // NOT(c IN (1, 2, 3)) -> c NOT IN (1, 2, 3)
377        let list = vec![
378            lit(ScalarValue::Int32(Some(1))),
379            lit(ScalarValue::Int32(Some(2))),
380            lit(ScalarValue::Int32(Some(3))),
381        ];
382        let in_list_expr = in_list(col("c", &schema)?, list.clone(), &false, &schema)?;
383        let not_in: Arc<dyn PhysicalExpr> = Arc::new(NotExpr::new(in_list_expr));
384
385        let expected = in_list(col("c", &schema)?, list, &true, &schema)?;
386        assert_not_simplify(&simplifier, not_in, expected);
387
388        Ok(())
389    }
390
391    #[test]
392    fn test_not_not_in_list() -> Result<()> {
393        let schema = not_test_schema();
394        let simplifier = PhysicalExprSimplifier::new(&schema);
395
396        // NOT(c NOT IN (1, 2, 3)) -> c IN (1, 2, 3)
397        let list = vec![
398            lit(ScalarValue::Int32(Some(1))),
399            lit(ScalarValue::Int32(Some(2))),
400            lit(ScalarValue::Int32(Some(3))),
401        ];
402        let not_in_list_expr = in_list(col("c", &schema)?, list.clone(), &true, &schema)?;
403        let not_not_in: Arc<dyn PhysicalExpr> = Arc::new(NotExpr::new(not_in_list_expr));
404
405        let expected = in_list(col("c", &schema)?, list, &false, &schema)?;
406        assert_not_simplify(&simplifier, not_not_in, expected);
407
408        Ok(())
409    }
410
411    #[test]
412    fn test_double_not_in_list() -> Result<()> {
413        let schema = not_test_schema();
414        let simplifier = PhysicalExprSimplifier::new(&schema);
415
416        // NOT(NOT(c IN (1, 2, 3))) -> c IN (1, 2, 3)
417        let list = vec![
418            lit(ScalarValue::Int32(Some(1))),
419            lit(ScalarValue::Int32(Some(2))),
420            lit(ScalarValue::Int32(Some(3))),
421        ];
422        let in_list_expr = in_list(col("c", &schema)?, list.clone(), &false, &schema)?;
423        let not_in = Arc::new(NotExpr::new(in_list_expr));
424        let double_not: Arc<dyn PhysicalExpr> = Arc::new(NotExpr::new(not_in));
425
426        let expected = in_list(col("c", &schema)?, list, &false, &schema)?;
427        assert_not_simplify(&simplifier, double_not, expected);
428
429        Ok(())
430    }
431
432    #[test]
433    fn test_deeply_nested_not() -> Result<()> {
434        let schema = not_test_schema();
435        let simplifier = PhysicalExprSimplifier::new(&schema);
436
437        // Create a deeply nested NOT expression: NOT(NOT(NOT(...NOT(c > 5)...)))
438        // This tests that we don't get stack overflow with many nested NOTs.
439        // With recursive_protection enabled (default), this should work by
440        // automatically growing the stack as needed.
441        let inner_expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
442            col("c", &schema)?,
443            Operator::Gt,
444            lit(ScalarValue::Int32(Some(5))),
445        ));
446
447        let mut expr = Arc::clone(&inner_expr);
448        // Create 200 layers of NOT to test deep recursion handling
449        for _ in 0..200 {
450            expr = Arc::new(NotExpr::new(expr));
451        }
452
453        // With 200 NOTs (even number), should simplify back to the original expression
454        let expected = inner_expr;
455        assert_not_simplify(&simplifier, Arc::clone(&expr), expected);
456
457        // Manually dismantle the deep input expression to avoid Stack Overflow on Drop
458        // If we just let `expr` go out of scope, Rust's recursive Drop will blow the stack
459        // even with recursive_protection, because Drop doesn't use the #[recursive] attribute.
460        // We peel off layers one by one to avoid deep recursion in Drop.
461        while let Some(not_expr) = expr.downcast_ref::<NotExpr>() {
462            // Clone the child (Arc increment).
463            // Now child has 2 refs: one in parent, one in `child`.
464            let child = Arc::clone(not_expr.arg());
465
466            // Reassign `expr` to `child`.
467            // This drops the old `expr` (Parent).
468            // Parent refcount -> 0, Parent is dropped.
469            // Parent drops its reference to Child.
470            // Child refcount decrements 2 -> 1.
471            // Child is NOT dropped recursively because we still hold it in `expr`
472            expr = child;
473        }
474
475        Ok(())
476    }
477
478    #[test]
479    fn test_simplify_literal_binary_expr() {
480        let schema = Schema::empty();
481        let simplifier = PhysicalExprSimplifier::new(&schema);
482
483        // 1 + 2 -> 3
484        let expr: Arc<dyn PhysicalExpr> =
485            Arc::new(BinaryExpr::new(lit(1i32), Operator::Plus, lit(2i32)));
486        let result = simplifier.simplify(expr).unwrap();
487        let literal = as_literal(&result);
488        assert_eq!(literal.value(), &ScalarValue::Int32(Some(3)));
489    }
490
491    #[test]
492    fn test_simplify_literal_comparison() {
493        let schema = Schema::empty();
494        let simplifier = PhysicalExprSimplifier::new(&schema);
495
496        // 5 > 3 -> true
497        let expr: Arc<dyn PhysicalExpr> =
498            Arc::new(BinaryExpr::new(lit(5i32), Operator::Gt, lit(3i32)));
499        let result = simplifier.simplify(expr).unwrap();
500        let literal = as_literal(&result);
501        assert_eq!(literal.value(), &ScalarValue::Boolean(Some(true)));
502
503        // 2 > 3 -> false
504        let expr: Arc<dyn PhysicalExpr> =
505            Arc::new(BinaryExpr::new(lit(2i32), Operator::Gt, lit(3i32)));
506        let result = simplifier.simplify(expr).unwrap();
507        let literal = as_literal(&result);
508        assert_eq!(literal.value(), &ScalarValue::Boolean(Some(false)));
509    }
510
511    #[test]
512    fn test_constant_regex_respects_planning_budget() {
513        let schema = Schema::empty();
514        let simplifier = PhysicalExprSimplifier::new(&schema);
515
516        let ordinary: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
517            lit("aaaaa"),
518            Operator::RegexMatch,
519            lit("^a+$"),
520        ));
521        let result = simplifier.simplify(ordinary).unwrap();
522        assert_eq!(
523            as_literal(&result).value(),
524            &ScalarValue::Boolean(Some(true))
525        );
526
527        // This pattern is valid under the runtime limit, but is deliberately
528        // too large for constant evaluation during physical simplification.
529        let pattern = "a{5}{5}{5}{5}{5}{5}";
530        let binary: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
531            lit("aaaaa"),
532            Operator::RegexMatch,
533            lit(pattern),
534        ));
535        let result = simplifier.simplify(Arc::clone(&binary)).unwrap();
536        assert_eq!(&result, &binary);
537
538        // A regexp_like call with non-operator flags exercises the physical
539        // scalar-UDF path used after literal substitution.
540        let function = Arc::new(
541            ScalarFunctionExpr::try_new(
542                regexp_like(),
543                vec![lit("aaaaa"), lit(pattern), lit("m")],
544                &schema,
545                Arc::new(ConfigOptions::default()),
546            )
547            .unwrap(),
548        ) as Arc<dyn PhysicalExpr>;
549        let result = simplifier.simplify(Arc::clone(&function)).unwrap();
550        assert_eq!(&result, &function);
551
552        #[derive(Debug, PartialEq, Eq, Hash)]
553        struct PanickingConstHook {
554            signature: Signature,
555        }
556
557        impl ScalarUDFImpl for PanickingConstHook {
558            fn name(&self) -> &str {
559                "panicking_const_hook"
560            }
561
562            fn signature(&self) -> &Signature {
563                &self.signature
564            }
565
566            fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
567                Ok(DataType::Boolean)
568            }
569
570            fn invoke_with_args(
571                &self,
572                _args: ScalarFunctionArgs,
573            ) -> Result<ColumnarValue> {
574                panic!("non-constant UDF must not be evaluated during planning")
575            }
576
577            fn should_evaluate_const(&self, _args: &[&ScalarValue]) -> bool {
578                panic!("constant-evaluation hook must only inspect literal arguments")
579            }
580        }
581
582        // Non-constant expressions must skip the UDF hook entirely. In
583        // particular, regexp_like(column, pattern) must not compile its
584        // pattern just to discover that the expression cannot be folded.
585        let input_schema = test_schema();
586        let non_constant = Arc::new(
587            ScalarFunctionExpr::try_new(
588                Arc::new(ScalarUDF::new_from_impl(PanickingConstHook {
589                    signature: Signature::exact(
590                        vec![DataType::Utf8, DataType::Utf8],
591                        Volatility::Immutable,
592                    ),
593                })),
594                vec![col("c3", &input_schema).unwrap(), lit(pattern)],
595                &input_schema,
596                Arc::new(ConfigOptions::default()),
597            )
598            .unwrap(),
599        ) as Arc<dyn PhysicalExpr>;
600        let result = PhysicalExprSimplifier::new(&input_schema)
601            .simplify(Arc::clone(&non_constant))
602            .unwrap();
603        assert_eq!(&result, &non_constant);
604    }
605
606    #[test]
607    fn test_simplify_nested_literal_expr() {
608        let schema = Schema::empty();
609        let simplifier = PhysicalExprSimplifier::new(&schema);
610
611        // (1 + 2) * 3 -> 9
612        let inner: Arc<dyn PhysicalExpr> =
613            Arc::new(BinaryExpr::new(lit(1i32), Operator::Plus, lit(2i32)));
614        let expr: Arc<dyn PhysicalExpr> =
615            Arc::new(BinaryExpr::new(inner, Operator::Multiply, lit(3i32)));
616        let result = simplifier.simplify(expr).unwrap();
617        let literal = as_literal(&result);
618        assert_eq!(literal.value(), &ScalarValue::Int32(Some(9)));
619    }
620
621    #[test]
622    fn test_simplify_deeply_nested_literals() {
623        let schema = Schema::empty();
624        let simplifier = PhysicalExprSimplifier::new(&schema);
625
626        // ((1 + 2) * 3) + ((4 - 1) * 2) -> 9 + 6 -> 15
627        let left: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
628            Arc::new(BinaryExpr::new(lit(1i32), Operator::Plus, lit(2i32))),
629            Operator::Multiply,
630            lit(3i32),
631        ));
632        let right: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
633            Arc::new(BinaryExpr::new(lit(4i32), Operator::Minus, lit(1i32))),
634            Operator::Multiply,
635            lit(2i32),
636        ));
637        let expr: Arc<dyn PhysicalExpr> =
638            Arc::new(BinaryExpr::new(left, Operator::Plus, right));
639        let result = simplifier.simplify(expr).unwrap();
640        let literal = as_literal(&result);
641        assert_eq!(literal.value(), &ScalarValue::Int32(Some(15)));
642    }
643
644    #[test]
645    fn test_no_simplify_with_column() {
646        let schema = test_schema();
647        let simplifier = PhysicalExprSimplifier::new(&schema);
648
649        // c1 + 2 should NOT be simplified (has column reference)
650        let expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
651            col("c1", &schema).unwrap(),
652            Operator::Plus,
653            lit(2i32),
654        ));
655        let result = simplifier.simplify(expr).unwrap();
656        // Should remain a BinaryExpr, not become a Literal
657        assert!(result.downcast_ref::<BinaryExpr>().is_some());
658    }
659
660    #[test]
661    fn test_partial_simplify_with_column() {
662        let schema = test_schema();
663        let simplifier = PhysicalExprSimplifier::new(&schema);
664
665        // (1 + 2) + c1 should simplify the literal part: 3 + c1
666        let literal_part: Arc<dyn PhysicalExpr> =
667            Arc::new(BinaryExpr::new(lit(1i32), Operator::Plus, lit(2i32)));
668        let expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
669            literal_part,
670            Operator::Plus,
671            col("c1", &schema).unwrap(),
672        ));
673        let result = simplifier.simplify(expr).unwrap();
674
675        // Should be a BinaryExpr with a Literal(3) on the left
676        let binary = as_binary(&result);
677        let left_literal = as_literal(binary.left());
678        assert_eq!(left_literal.value(), &ScalarValue::Int32(Some(3)));
679    }
680
681    /// Regression test for https://github.com/apache/datafusion/issues/22367.
682    ///
683    /// A leaf `PhysicalExpr` that is neither a `Literal` nor a `Column`
684    /// (nor volatile) must not be const-folded: it has no children to
685    /// derive constness from, and evaluating it against the dummy batch
686    /// produces a value unrelated to its real runtime semantics. Without
687    /// the zero-children guard, `all(empty)` would vacuously hold and the
688    /// node would be replaced with whatever scalar fell out of the dummy
689    /// evaluation. Verify the node is left untouched.
690    #[test]
691    fn test_no_simplify_opaque_leaf_expr() {
692        use arrow::array::ArrayRef;
693        use arrow::array::Int32Array;
694        use arrow::record_batch::RecordBatch;
695        use datafusion_expr_common::columnar_value::ColumnarValue;
696        use datafusion_physical_expr_common::physical_expr::PhysicalExpr as PhysicalExprTrait;
697        use std::fmt;
698
699        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
700        struct OpaqueLeaf;
701
702        impl fmt::Display for OpaqueLeaf {
703            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704                write!(f, "OpaqueLeaf")
705            }
706        }
707
708        impl PhysicalExprTrait for OpaqueLeaf {
709            fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
710                Ok(DataType::Int32)
711            }
712            fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
713                Ok(true)
714            }
715            fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
716                // Simulate the broken FFI Column path: when handed a dummy
717                // batch, return whatever scalar happens to materialize. If
718                // the simplifier ever reaches this branch for a leaf node,
719                // the predicate has already been silently corrupted.
720                let arr: ArrayRef = Arc::new(Int32Array::from(vec![0; batch.num_rows()]));
721                Ok(ColumnarValue::Array(arr))
722            }
723            fn children(&self) -> Vec<&Arc<dyn PhysicalExprTrait>> {
724                vec![]
725            }
726            fn with_new_children(
727                self: Arc<Self>,
728                _children: Vec<Arc<dyn PhysicalExprTrait>>,
729            ) -> Result<Arc<dyn PhysicalExprTrait>> {
730                Ok(self)
731            }
732            fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
733                write!(f, "OpaqueLeaf")
734            }
735        }
736
737        let schema = Schema::empty();
738        let simplifier = PhysicalExprSimplifier::new(&schema);
739
740        let opaque: Arc<dyn PhysicalExpr> = Arc::new(OpaqueLeaf);
741        let result = simplifier.simplify(Arc::clone(&opaque)).unwrap();
742
743        assert!(
744            result.downcast_ref::<Literal>().is_none(),
745            "opaque leaf must not be rewritten to a Literal, got: {result}"
746        );
747        assert_eq!(&result, &opaque);
748    }
749
750    #[test]
751    fn test_simplify_literal_string_concat() {
752        let schema = Schema::empty();
753        let simplifier = PhysicalExprSimplifier::new(&schema);
754
755        // 'hello' || ' world' -> 'hello world'
756        let expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
757            lit("hello"),
758            Operator::StringConcat,
759            lit(" world"),
760        ));
761        let result = simplifier.simplify(expr).unwrap();
762        let literal = as_literal(&result);
763        assert_eq!(
764            literal.value(),
765            &ScalarValue::Utf8(Some("hello world".to_string()))
766        );
767    }
768}