jayzhan211 commented on code in PR #26967:
URL: https://github.com/apache/datafusion/pull/26967#discussion_r4571928154


##########
datafusion/physical-expr/src/equivalence/class.rs:
##########
@@ -213,6 +213,35 @@ impl EquivalenceClass {
             }
         }
         self.exprs.insert(expr);
+        self.promote_sub_expressions();
+    }
+
+    /// Makes sure the canonical expression does not contain another expression
+    /// of this class. Otherwise, with `a + b` as the canonical expression of a
+    /// class that also holds `a`, normalization would replace the `a` inside
+    /// `a + b` and turn `a + b` into `(a + b) + b`.
+    fn promote_sub_expressions(&mut self) {
+        // Each promoted expression is inside the previous canonical
+        // expression, so there are at most as many rounds as members.
+        for _ in 0..self.exprs.len() {

Review Comment:
   Optional: no test needs a second round of this loop. With `for _ in 0..1` 
every test still passes. A second round happens when `extend` brings in `a + b` 
and `a` behind an unrelated canonical expression. This test passes here and 
fails with one round:
   
   ```rs
   #[test]
   fn test_sub_expression_promotion_takes_several_rounds() -> Result<()> {
       let schema = abc_schema();
       let (a, b, c) = (col("a", &schema)?, col("b", &schema)?, col("c", 
&schema)?);
       let a_plus_b = binary(Arc::clone(&a), Operator::Plus, Arc::clone(&b), 
&schema)?;
       let a_plus_b_plus_c = binary(
           Arc::clone(&a_plus_b),
           Operator::Plus,
           Arc::clone(&c),
           &schema,
       )?;
   
       // `b * c` is canonical in `other`, so `a + b` stays ahead of `a` there
       let b_times_c = binary(b, Operator::Multiply, c, &schema)?;
       let other = EquivalenceClass::new([b_times_c, a_plus_b, Arc::clone(&a)]);
       let mut class = EquivalenceClass::new([a_plus_b_plus_c]);
       class.extend(other);
       assert!(class.canonical_expr().unwrap().eq(&a));
       Ok(())
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to