Repository navigation
Conversation
circut for violotile expression
|
run benchmark binary_op |
|
Benchmark for this request failed before finishing (Kubernetes reason: Benchmarks requested: Runner log (last 40 lines)Kubernetes messageFile an issue against this benchmark runner |
|
run benchmark binary_op |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing short-circut-and-or-not-case-when-coalesce (0ee36d2) to 9e0a08f (merge-base) diff Run configurationrun benchmark binary_opResults will be posted here when complete File an issue against this benchmark runner |
|
run benchmark binary_op |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing short-circut-and-or-not-case-when-coalesce (1f9b6c6) to 9e0a08f (merge-base) diff Run configurationrun benchmark binary_opResults will be posted here when complete File an issue against this benchmark runner |
This comment was marked as outdated.
This comment was marked as outdated.
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing short-circut-and-or-not-case-when-coalesce (1f9b6c6) to 9e0a08f (merge-base) diff Run configurationrun benchmark binary_opCPU Details (lscpu)Details
Resource Usagebinary_op — base (merge-base)
binary_op — branch
File an issue against this benchmark runner |
|
|
||
| // Check if we can apply short-circuit evaluation. | ||
| match check_short_circuit(&lhs, &self.op) { | ||
| match check_short_circuit(&lhs, &self.op, || self.children_volatility().right) { |
There was a problem hiding this comment.
just init the oncelock don't pass a closure
There was a problem hiding this comment.
BinaryExpression is used in many operators, Eq, NotEq, Lt, Divide, Mul, etc... so no need to calculate that for everything
There was a problem hiding this comment.
it's just very small, and will only happen once, I really don't see a reason for this.
There was a problem hiding this comment.
changed to be cached in new
| ) -> Result<ColumnarValue> { | ||
| // Use `filter_record_batch` directly because `evaluate_selection` | ||
| // scatters the RHS back to the original batch length. | ||
| let selection_batch = filter_record_batch(batch, mask)?; |
There was a problem hiding this comment.
Can this be made to only use the required columns? wide batches can pay a huge cost here
There was a problem hiding this comment.
yes, already started it in a different pr, they are not dependent however
| /// Lazily computed on first use, so walking the children is not repeated | ||
| /// for every batch. Children never change after construction, and every | ||
| /// constructor starts with an empty cache, so it never goes stale. | ||
| children_volatility: OnceLock<ChildrenVolatility>, |
There was a problem hiding this comment.
Not convinced this is worth it.
I get that reoptimization etc, but this feels like a small price.
There was a problem hiding this comment.
this physical expression is not only for AND and OR, but many many Binary Expr so adding the calculation for volatility in every one is not needed
also running many optimization before this actually needed will cause the entire expression tree every time while only needed for actual evaluation
There was a problem hiding this comment.
changed to Option and only evaluate for AND and OR
| fn check_short_circuit( | ||
| lhs: &ColumnarValue, | ||
| op: &Operator, | ||
| rhs_is_volatile: impl FnOnce() -> bool, |
There was a problem hiding this comment.
as mentioned, just make this a bool
There was a problem hiding this comment.
commented in the other review comment
|
|
||
| fn children_volatility(&self) -> ChildrenVolatility { | ||
| *self.children_volatility.get_or_init(|| ChildrenVolatility { | ||
| left: is_volatile(&self.left), |
There was a problem hiding this comment.
Why is left needed?
in nested cases, each one will handle it for itself, no?
There was a problem hiding this comment.
Nested ANDs don't each handle it themselves: evaluate_conjunction flattens the whole chain and the top node evaluates every conjunct, so the inner AND's evaluate never runs. In x AND (v AND y), v is evaluated after x has decided some rows, and whether to pre-select it depends on v's volatility, which is the inner AND's left. OR isn't flattened, so for OR only right matters.
There was a problem hiding this 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: falseinBinaryExpr::newv.rightinstead ofv.left || v.rightinsubtree_is_volatilefalseinstead ofbinary.left_is_volatile()infor_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.
There was a problem hiding this comment.
Added both tests, each of the three changes now fails at least one of them
| } | ||
|
|
||
| /// Whether the left child (or anything under it) is volatile | ||
| fn left_is_volatile(&self) -> bool { |
There was a problem hiding this comment.
when can this ever be needed? if we already set it in new
There was a problem hiding this comment.
children_volatility is an option, so we have this just to be safe that if for some reason this was called when it was not an option
| } | ||
|
|
||
| /// Whether the right child (or anything under it) is volatile | ||
| fn right_is_volatile(&self) -> bool { |
| if *op != Operator::Or || lhs.data_type() != DataType::Boolean { | ||
| return None; | ||
| } | ||
| let ColumnarValue::Array(array) = lhs else { |
There was a problem hiding this comment.
Maybe add a comment that Scalars were already handled
There was a problem hiding this comment.
added assertion for getting true and comment
|
run benchmark binary_op |
|
run benchmarks |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing short-circut-and-or-not-case-when-coalesce (1c26c64) to 9e0a08f (merge-base) diff Run configurationrun benchmark tpchResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing short-circut-and-or-not-case-when-coalesce (1c26c64) to 9e0a08f (merge-base) diff Run configurationrun benchmark tpcdsResults will be posted here when complete File an issue against this benchmark runner |
|
Thanks @rluvaton thats a nice initiative, just wondering if that makes sense to split the PR into 2 and address AND/OR separately? |
|
@comphead, Extracted once that merge will update this to only have can you please review? |
…27471) Extracted from: - #27302 as requested by @comphead ## Which issue does this PR close? - Related to #8927. ## Rationale for this change `OR` only skip the right side for rows the left side already decided when few rows are left (`PRE_SELECTION_THRESHOLD`). Otherwise the right side runs on the whole batch, so: - `x = 0 OR 1 / x > 1` can fail with division by zero, depending on how many rows match - volatile expressions run on rows they shouldn't - `OR` doesn't short-circuit at all when the left side has any `NULL` ## What changes are included in this PR? - Volatile right side: always evaluated only on the undecided rows - Deterministic right side: keeps the current heuristic, but if evaluating on the whole batch fails, retry on the undecided rows only - `OR` handles `NULL` on the left side per row instead of giving up on the whole batch `AND` doesn't follow these rules yet, #27302 does the same for it. The one difference left after that is that `AND` skips filtering when the conjunct is just a column, aligning that can be a follow-up. ## What is the testing strategy for this PR? - Unit tests in `binary.rs` (`short_circuit` module) for `OR`, nested `OR` and nullable left side, across selectivities on both sides of the threshold - Updated `select.slt` queries that were expected to fail with division by zero ## Are there any user-facing changes? Queries like `x = 0 OR 1 / x > 1` no longer fail. ------- Follow up: - add benchmarks for: - LHS have NULLs, <= 20% of rows undecided - Volatile RHS, 90% undecided
…-not-case-when-coalesce # Conflicts: # datafusion/physical-expr/src/expressions/binary.rs # datafusion/sqllogictest/test_files/select.slt
|
run benchmark binary_op |
|
run benchmarks |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark binary_opResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark tpcdsResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark clickbench_partitionedResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark tpchResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark tpchCPU Details (lscpu)Details
Resource Usagetpch — base (merge-base)
tpch — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark tpcdsCPU Details (lscpu)Details
Resource Usagetpcds — base (merge-base)
tpcds — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark clickbench_partitionedCPU Details (lscpu)Details
Resource Usageclickbench_partitioned — base (merge-base)
clickbench_partitioned — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark binary_opCPU Details (lscpu)Details
Resource Usagebinary_op — base (merge-base)
binary_op — branch
File an issue against this benchmark runner |
|
run benchmark clickbench_partitioned |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark clickbench_partitionedResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing short-circut-and-or-not-case-when-coalesce (1133558) to 665eca4 (merge-base) diff Run configurationrun benchmark clickbench_partitionedCPU Details (lscpu)Details
Resource Usageclickbench_partitioned — base (merge-base)
clickbench_partitioned — branch
File an issue against this benchmark runner |
|
@comphead can you please review this now? |
comphead
left a comment
There was a problem hiding this comment.
Thanks @rluvaton. The AND half reads well next to #27471, and retrying on error is the right trade-off against classifying fallibility up front: it costs nothing until a conjunct fails. My main question is how far the user-facing promise reaches.
The guard order does not survive PushDownFilter. The two rules it runs on a WHERE clause can move a conjunct ahead of its guard before it reaches evaluate_conjunction, and a first conjunct has no decided rows to retry on. On a main build:
WHERE |
FilterExec |
result |
|---|---|---|
x <> 0 AND 10 / x > 1 AND y > 1 AND y > 2 |
10 / CAST(x@0 AS Int64) > 1 AND x@0 != 0 AND y@1 > 2 |
divide by zero |
s ~ '^[0-9]+$' AND CAST(s AS INT) > 10 |
CAST(s@0 AS Int32) > 10 AND s@0 ~ ^[0-9]+$ |
cast error |
a > 1 AND a > 2 AND random() < 2 |
random() < 2 AND a@0 > 2 |
volatile call on every row |
- Rows 1 and 3 come from
simplify_predicates. As soon as it simplifies anything, it puts every non-comparison conjunct first, volatile ones included, whichreorder_predicatesrefuses to move. - Row 2 comes from
reorder_predicates. It countsCAST,/and%as cheap and LIKE, regex and UDFs as expensive, whileis_cheap_and_infallibletreats/and narrowing casts as fallible. - The optimizer already says so in
expr_simplifier.rs: "Unlike CASE, AND/OR do not guarantee branch-local evaluation".
So I would word the user-facing change as best effort (the guard has to reach the evaluator first, and CASE stays the guaranteed form), and add a WHERE case (inline on select.slt). Keeping conjunct positions in simplify_predicates, and letting only cheap-and-infallible conjuncts move forward in reorder_predicates, would fit a follow-up issue. The volatile reorder looks like a bug of its own.
Smaller points:
- The
evaluate_conjunctiondoc still describes only the threshold rule. It now also covers volatile conjuncts and the retry. - Follow-up: alternating
AND/ORstacks the two retries, also on queries that succeed. Ina > 0 AND (b > 0 OR (c > 0 AND 10 / x > 1)), with onlya > 0rejecting thex = 0rows and no level pre-filtering, each batch can evaluate the division 5 times, 4 of them failing. This extends the right-nestedORnote on #27471 and could join the cases in #27671. Rust (fork)found no run on the fork for this head, so the new tests have no CI result yet.
| @@ -981,7 +1001,7 @@ impl PhysicalExpr for BinaryExpr { | |||
| right, | |||
| fail_on_overflow, | |||
| // Derived from right, not serialized | |||
There was a problem hiding this comment.
Stale after the rename:
| // Derived from right, not serialized | |
| // Derived from the children, not serialized |
| 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 | ||
| } |
There was a problem hiding this 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:
| 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 | |
| } | |
| #[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) | |
| } | |
| } | |
| } |
| 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) |
There was a problem hiding this 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:
| 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) | |
| let array = array.as_boolean(); | |
| array.has_false().then(|| not_false(array)) |
| // 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 _), | ||
| ); |
There was a problem hiding this 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:
| // 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 _), | |
| ); | |
| // 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.
There was a problem hiding this comment.
Swapped the comparisons and removed the two AND infallible tests
| # `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) |
There was a problem hiding this 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:
| # `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) | |
| # 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
WHEREclause, which goes throughPushDownFilterand keepsy@1 > 0first in the plan:SELECT * FROM t WHERE y > 0 AND 1 / y < 1. It fails onmain. - A retry that still fails, because row
(4, 0)stays undecided: aquery errorforSELECT x > 0 AND 1 / y < 1 FROM t. No unit test reaches this either, sinceFailOnUnneededonly fails on unneeded rows, so a retry that swallowed its error would pass every test.
There was a problem hiding this 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
mbutrovich
left a comment
There was a problem hiding this comment.
Thanks @rluvaton, the AND half lines up well with the OR change.
The 55.0.0 upgrade guide already tells users not to rely on short-circuit evaluation of AND or OR, and to use CASE when a predicate can fail. That backs the best-effort wording that @comphead suggested in #27302 (review). Could the "Are there any user-facing changes?" section say that per-row evaluation is best effort and link that section of the guide? As written, "Queries like x != 0 AND 1 / x > 1 no longer fail" promises more than the guide does, and WHERE x <> 0 AND 10 / x > 1 AND y > 1 AND y > 2 still fails with divide by zero at this commit.
|
@mbutrovich Thanks! Updated the section to say it's best effort and link the upgrade guide |
ORwas done in #27471, this PR is theANDpart.Which issue does this PR close?
Rationale for this change
ANDonly filters out the rows earlier conjuncts already decided when few rows are left (PRE_SELECTION_THRESHOLD) and the conjunct is not just a column. Otherwise the conjunct runs on the whole batch, so:x != 0 AND 1 / x > 1can fail with division by zero, depending on how many rows matchWhat changes are included in this PR?
Same rules as #27471, for
AND:Volatility is computed once in
BinaryExpr::newfor bothANDandOR(it was only the right side forOR).ANDneeds the left side too, because nestedANDs are flattened and each conjunct's volatility is stored on its parent.What is the testing strategy for this PR?
binary.rs(short_circuitmodule) forAND, nestedANDand nullable left side, across selectivities on both sides of the thresholdselect.sltANDquery that was expected to fail with division by zerovolatile_evaluations.slt:BETWEENnow evaluates the volatile call 18 times instead of 20, sincex <= highonly runs on the rows wherex >= lowshort_circuitbenchmarks for nullable left side and volatile right side #27671Are there any user-facing changes?
Best effort:
ANDevaluates a conjunct only on the rows that still need it when the conjunct is volatile, or when evaluating it on all rows fails.When the physical expression is built and evaluated directly,
x != 0 AND 1 / x > 1no longer fails. In a query the optimizer may reorder conjuncts first, so useCASEwhen a guard is required (see the upgrade guide).