rluvaton commented on code in PR #27302:
URL: https://github.com/apache/datafusion/pull/27302#discussion_r4680795112


##########
datafusion/physical-expr/src/expressions/binary.rs:
##########
@@ -1319,6 +1346,38 @@ enum ShortCircuitStrategy {
 /// Maximum share of rows still needing evaluation before filtering.
 const PRE_SELECTION_THRESHOLD: f32 = 0.2;
 
+/// Whether `expr` or anything under it is volatile, like
+/// 
[`is_volatile`](datafusion_physical_expr_common::physical_expr::is_volatile),
+/// but reuses the volatility already computed for `AND` / `OR` nodes (at any
+/// depth) instead of walking their children again, so building a long
+/// `AND` / `OR` chain stays linear.
+fn subtree_is_volatile(expr: &Arc<dyn PhysicalExpr>) -> bool {
+    let mut volatile = false;
+    expr.apply(|e| {
+        if let Some(BinaryExpr {
+            children_volatility: Some(v),
+            ..
+        }) = e.downcast_ref::<BinaryExpr>()
+        {
+            // `BinaryExpr` itself is never volatile, only its children can be
+            return Ok(if v.left || v.right {
+                volatile = true;
+                TreeNodeRecursion::Stop
+            } else {
+                TreeNodeRecursion::Jump
+            });
+        }
+        Ok(if e.is_volatile_node() {
+            volatile = true;
+            TreeNodeRecursion::Stop
+        } else {
+            TreeNodeRecursion::Continue
+        })
+    })
+    .expect("infallible closure should not fail");
+    volatile
+}

Review Comment:
   Done, thanks



##########
datafusion/physical-expr/src/expressions/binary.rs:
##########
@@ -1485,25 +1544,53 @@ fn pre_selection_scatter(
     Ok(ColumnarValue::Array(Arc::new(boolean_result)))
 }
 
-/// Selects undecided rows when some are false, at most
-/// [`PRE_SELECTION_THRESHOLD`] of the original batch remain, and evaluating
+/// Selects undecided rows when some are false and either `conjunct` is
+/// volatile (it must never be evaluated on rows that don't need it), or at
+/// most [`PRE_SELECTION_THRESHOLD`] of the original batch remain and 
evaluating
 /// `conjunct` on all rows is not cheap and infallible.
 fn rows_to_filter_before(
     conjunct: &Arc<dyn PhysicalExpr>,
+    is_volatile: bool,
     result: &ColumnarValue,
     schema: &Schema,
     num_rows: usize,
 ) -> Option<BooleanArray> {
+    let undecided = undecided_rows(result)?;
+    let undecided_count = undecided.true_count();
+    // Classify last: it walks the whole conjunct.
+    (is_volatile
+        || (undecided_count as f32 / num_rows as f32 <= PRE_SELECTION_THRESHOLD
+            && !is_cheap_and_infallible(conjunct, schema)))
+    .then_some(undecided)
+}
+
+/// The rows of the `AND` result so far that are not `false`, if any are 
`false`.
+fn undecided_rows(result: &ColumnarValue) -> Option<BooleanArray> {
     let ColumnarValue::Array(array) = result else {
         return None;
     };
     let undecided = not_false(array.as_boolean());
-    let undecided_count = undecided.true_count();
-    // Classify last: it walks the whole conjunct.
-    (undecided_count < array.len()
-        && undecided_count as f32 / num_rows as f32 <= PRE_SELECTION_THRESHOLD
-        && !is_cheap_and_infallible(conjunct, schema))
-    .then_some(undecided)
+    (undecided.true_count() < array.len()).then_some(undecided)

Review Comment:
   Done



##########
datafusion/physical-expr/src/expressions/binary.rs:
##########
@@ -7771,6 +8145,33 @@ mod tests {
         // 4. the LHS decides every row: the RHS is never called
         // -------------------------------------------------------------------
 
+        #[test]
+        fn and_rhs_not_evaluated_when_lhs_all_false() {
+            let batch = batch();
+            let probe = Probe::new(Mode::Infallible, 0.0..0.0);
+            // col_1 < 0 is false for every row
+            let expr = and(col_1_lt(0.0), Arc::clone(&probe) as _);
+
+            evaluate(&expr, &batch).unwrap();
+
+            assert_eq!(probe.calls.load(Relaxed), 0);
+        }
+
+        #[test]
+        fn nested_and_rhs_not_evaluated_when_lhs_all_false() {
+            let batch = batch();
+            let probe = Probe::new(Mode::Infallible, 0.0..0.0);
+            // col_1 < 0 is false for every row
+            let expr = and(
+                col_1_lt(0.0),
+                and(col_1_gt_eq(0.0), Arc::clone(&probe) as _),
+            );

Review Comment:
   Swapped the comparisons and removed the two `AND` infallible tests



##########
datafusion/sqllogictest/test_files/select.slt:
##########
@@ -1743,10 +1743,16 @@ select coalesce(1, y/x), coalesce(2, y/x) from t;
 1 2
 1 2
 
-# due to the reason describe in 
https://github.com/apache/datafusion/issues/8927,
-# the following queries will fail
-query error
+# `1 / y` and `1 / x` are only evaluated on the rows that need them, so the
+# division by zero is short-circuited 
(https://github.com/apache/datafusion/issues/8927)

Review Comment:
   Updated the comment and added both, the `WHERE` case with an `EXPLAIN` so a 
plan change that moves the division first shows up there



##########
datafusion/physical-expr/src/expressions/binary.rs:
##########
@@ -93,9 +118,17 @@ impl BinaryExpr {
             op: self.op,
             right: self.right,
             fail_on_overflow,
+            children_volatility: OnceLock::new(),
         }
     }
 
+    fn children_volatility(&self) -> ChildrenVolatility {
+        *self.children_volatility.get_or_init(|| ChildrenVolatility {
+            left: is_volatile(&self.left),

Review Comment:
   Added both tests, each of the three changes now fails at least one of them



-- 
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