comphead commented on code in PR #27302:
URL: https://github.com/apache/datafusion/pull/27302#discussion_r4670367283
##########
datafusion/physical-expr/src/expressions/binary.rs:
##########
@@ -981,7 +1001,7 @@ impl PhysicalExpr for BinaryExpr {
right,
fail_on_overflow,
// Derived from right, not serialized
Review Comment:
Stale after the rename:
```suggestion
// Derived from the children, not serialized
```
##########
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:
A direct recursion does the same job without the captured flag, the three
`TreeNodeRecursion` arms, the `.expect` in library code and the new `tree_node`
import. `create_physical_expr` uses the same `recursive_protection` attribute:
```suggestion
#[cfg_attr(feature = "recursive_protection", recursive::recursive)]
fn subtree_is_volatile(expr: &Arc<dyn PhysicalExpr>) -> bool {
match expr.downcast_ref::<BinaryExpr>() {
// `BinaryExpr` itself is never volatile, only its children can be
Some(BinaryExpr {
children_volatility: Some(v),
..
}) => v.left || v.right,
_ => {
expr.is_volatile_node()
|| expr.children().into_iter().any(subtree_is_volatile)
}
}
}
```
##########
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:
`rows_to_filter_before` counts this mask again right after (line 1559), so
each conjunct now pays two popcounts per batch. `has_false` ignores NULLs, so
it gives the same answer, stops at the first `false`, and skips building the
mask when nothing is decided:
```suggestion
let array = array.as_boolean();
array.has_false().then(|| not_false(array))
```
##########
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:
`col_1 < 0` is the top-level left, so evaluation stops at the `if` in
`evaluate_conjunction` and never enters the inner `AND`, the same path as
`and_rhs_not_evaluated_when_lhs_all_false`. Changing `&&` to `&` in
`for_each_conjunct` would pass. Swapping the two comparisons reaches the inner
short-circuit:
```suggestion
// col_1 >= 0 is true for every row, so the inner `AND` runs, and
// col_1 < 0 is false for every row
let expr = and(
col_1_gt_eq(0.0),
and(col_1_lt(0.0), Arc::clone(&probe) as _),
);
```
Similarly, the two `*_infallible_rhs_evaluated_at_most_once` AND tests never
fail and are not volatile, so they don't reach the new code.
`evaluate_recorded_conjunction` already asserts that each conjunct runs once,
in order, for left-deep, right-deep and balanced trees.
##########
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:
With 3 of 5 rows left by `y > 0`, the division is above
`PRE_SELECTION_THRESHOLD`, so it runs on the whole batch, fails and is retried.
Worded like the `OR` comment below:
```suggestion
# The divisions fail on the whole batch (`y = 0`), so they are retried on the
# undecided rows only (https://github.com/apache/datafusion/issues/8927)
```
Two cases here would pin what nothing tests yet:
- A `WHERE` clause, which goes through `PushDownFilter` and keeps `y@1 > 0`
first in the plan: `SELECT * FROM t WHERE y > 0 AND 1 / y < 1`. It fails on
`main`.
- A retry that still fails, because row `(4, 0)` stays undecided: a `query
error` for `SELECT x > 0 AND 1 / y < 1 FROM t`. No unit test reaches this
either, since `FailOnUnneeded` only fails on unneeded rows, so a retry that
swallowed its error would pass every test.
##########
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:
The shape from this answer, `x AND (v AND y)` with a volatile `v`, has no
test: every probe is the innermost right child. That leaves the cached `left`
flag untested, and with this PR `OR` depends on it too. Before, `OR` walked its
whole right side with `is_volatile`, so `x OR (v AND y)` was covered by
construction. Now it reads the inner `AND`'s cached `left`. Each of these would
pass the current tests:
- `left: false` in `BinaryExpr::new`
- `v.right` instead of `v.left || v.right` in `subtree_is_volatile`
- `false` instead of `binary.left_is_volatile()` in `for_each_conjunct`
A `nested_and_volatile_*` variant with the probe on the inner left,
`and(col_1_lt(s), and(probe, col_1_gt_eq(s / 2.0)))`, plus one `OR` over `AND`,
`or(col_1_gt_eq(s), and(probe, col_1_lt(s / 2.0)))`, would pin all three.
--
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]