spark-test commented on code in PR #59984:
URL: https://github.com/apache/spark/pull/59984#discussion_r4514173144


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala:
##########
@@ -2333,10 +2344,98 @@ class CodegenContext extends Logging {
     // We need to make sure that we do not reuse stateful expressions. This is 
needed for codegen
     // as well because some expressions may implement `CodegenFallback`.
     val cleanedExpressions = 
expressions.map(_.freshCopyIfContainsStatefulExpression())
-    if (doSubexpressionElimination) 
subexpressionElimination(cleanedExpressions)
+    if (doSubexpressionElimination) {
+      subexprFunctions ++= 
subexpressionElimination(cleanedExpressions).map(_._2)
+    }
     cleanedExpressions.map(e => e.genCode(this))
   }
 
+  /**
+   * Returns the index of the first of `expressions` that references the 
common subexpression
+   * `subexpr`, or -1. When the expressions are evaluated in order and one of 
them can stop the
+   * evaluation, such as a FALSE conjunct of a predicate, the subexpression is 
evaluated right
+   * before that expression instead of before all of them (SPARK-56032, 
SPARK-60332). An
+   * occurrence in a conditionally evaluated part of an expression, such as a 
branch of CASE WHEN,
+   * counts as a reference, so the subexpression is still evaluated before 
such an expression.
+   */
+  def firstReferencingExpression(expressions: Seq[Expression], subexpr: 
ExpressionEquals): Int = {
+    expressions.indexWhere(_.exists(e => ExpressionEquals(e) == subexpr))
+  }
+
+  /**
+   * Generates the code of the top-level conjuncts of `predicate` with 
subexpression elimination,
+   * for a predicate whose conjuncts are evaluated in order and whose 
evaluation stops at a FALSE
+   * conjunct, as `And.eval` does.
+   *
+   * The common subexpressions are found in the whole predicate, as 
`generateExpressions` finds
+   * them, so that the same subexpressions are eliminated: none inside a task 
for a predicate that
+   * holds a plan expression, and only those of the first conjunct with
+   * `spark.sql.subexpressionElimination.skipForShortcutExpr`. The predicate 
is then split into
+   * its conjuncts, keeping an AND of the top-level chain that is itself a 
common subexpression as
+   * one conjunct, which reads the state of the subexpression. The common 
subexpressions that a
+   * conjunct contains are evaluated by functions called just before the first 
conjunct that
+   * references them, instead of before the whole predicate (SPARK-60332); any 
other AND of the
+   * chain is not, since the conjuncts are generated one by one. Returns, per 
conjunct, the code
+   * of the calls to put before it and the code of the conjunct, or None, 
generating nothing, when
+   * no subexpression is eliminated: the caller then generates the predicate 
as a whole.
+   *
+   * The function of a subexpression that contains an eliminated subexpression 
reads the state
+   * of the latter, so the calls are ordered by their dependencies: a 
contained subexpression is
+   * called before the conjunct that first references the containing one, even 
when its own first
+   * reference is later. A conjunct can contain a copy of the containing 
subexpression that lacks
+   * the contained one, e.g. `(a + c) + b` for `(a + b) + c` under the 
canonicalization of a
+   * commutative operator.
+   *
+   * This must be the only subexpression elimination on this context.
+   */
+  def generateConjunctsWithSubexprCodes(predicate: Expression): 
Option[Seq[(String, ExprCode)]] = {
+    val cleanedPredicate = predicate.freshCopyIfContainsStatefulExpression()
+    equivalentExpressions.addExprTree(cleanedPredicate)
+    val allCommonExprs = equivalentExpressions.getCommonSubexpressions
+    val commonEqs = allCommonExprs.map(ExpressionEquals(_)).toSet
+    def split(e: Expression): Seq[Expression] = e match {
+      case And(left, right) if !commonEqs.contains(ExpressionEquals(e)) =>

Review Comment:
   Agreed that this is not a regression: the base branch fails on this shape 
too, and thanks for opening SPARK-61197. It is still the same failure this PR 
removes for other AND chains, and neither the PR description nor the new 
migration-guide entry says that such queries still fail, so this review keeps 
it open as an incomplete fix. Here is an example with default configs, traced 
through the source but not run: `SELECT b FROM VALUES (1, 2147483647) AS t(b, 
y) WHERE b < 0 AND y + 1 > 0 AND IF(b < 0 AND y + 1 > 0, b > 0, b < 0) AND y + 
1 > -1`. The parser groups the first two conjuncts into one AND node, and the 
IF repeats it, so the node stays one conjunct. When the optimizer filters the 
VALUES rows, `y + 1` overflows before `b < 0` is checked, while the flattened 
`b < 0 AND y + 1 > 0 AND y + 1 > -1` returns no rows. The parquet-table example 
above likely does not reproduce: the scan rebuilds the condition from its 
conjuncts with the inferred IS NOT NULL filters first, so the repeate
 d pair is no longer one AND node. Splitting such a node for placement, and 
setting its state from its operands' checks, would cover these inputs in this 
PR.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4505510516","thread_id":"inline:4505510516","verdict_sha256":"ed1cffc09b8334f9f7af95e45a6073570b7363252a24e3329e5f74fd64b74370"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala:
##########
@@ -2385,10 +2397,99 @@ class CodegenContext extends Logging {
     // We need to make sure that we do not reuse stateful expressions. This is 
needed for codegen
     // as well because some expressions may implement `CodegenFallback`.
     val cleanedExpressions = 
expressions.map(_.freshCopyIfContainsStatefulExpression())
-    if (doSubexpressionElimination) 
subexpressionElimination(cleanedExpressions)
+    if (doSubexpressionElimination) {
+      subexprFunctions ++= subexpressionElimination(cleanedExpressions)
+    }
     cleanedExpressions.map(e => e.genCode(this))
   }
 
+  /**
+   * Returns the index of the first of `expressions` that references the 
common subexpression
+   * `subexpr`, or -1. When the expressions are evaluated in order and one of 
them can stop the
+   * evaluation, such as a FALSE conjunct of a predicate, the subexpression is 
evaluated right
+   * before that expression instead of before all of them (SPARK-56032, 
SPARK-60332). An
+   * occurrence in a conditionally evaluated part of an expression, such as a 
branch of CASE WHEN,
+   * counts as a reference, so the subexpression is still evaluated before 
such an expression.
+   */
+  def firstReferencingExpression(expressions: Seq[Expression], subexpr: 
ExpressionEquals): Int = {
+    expressions.indexWhere(_.exists(e => ExpressionEquals(e) == subexpr))
+  }
+
+  /**
+   * Generates the code of the top-level conjuncts of `predicate` with 
subexpression elimination,
+   * for a predicate whose conjuncts are evaluated in order and whose 
evaluation stops at a FALSE
+   * conjunct, as `And.eval` does.
+   *
+   * The common subexpressions are found in the whole predicate, as 
`generateExpressions` finds
+   * them, so that the same subexpressions are eliminated: none inside a task 
for a predicate that
+   * holds a plan expression, and only those of the first conjunct with
+   * `spark.sql.subexpressionElimination.skipForShortcutExpr`. The predicate 
is then split into
+   * its conjuncts, keeping an AND of the top-level chain that is itself a 
common subexpression as
+   * one conjunct, which reads the state of the subexpression. The common 
subexpressions that a
+   * conjunct contains are evaluated by functions called just before the first 
conjunct that
+   * references them, instead of before the whole predicate (SPARK-60332). The 
other ANDs of the
+   * chain are not generated themselves; only the conjuncts they join are, one 
by one. Returns,
+   * per conjunct, the code of the calls to put before it and the code of the 
conjunct, or None,
+   * generating nothing, when no subexpression is eliminated: the caller then 
generates the
+   * predicate as a whole.
+   *
+   * The function of a subexpression that contains an eliminated subexpression 
reads the state
+   * of the latter, so the calls are ordered by their dependencies: a 
contained subexpression is
+   * called before the conjunct that first references the containing one, even 
when its own first
+   * reference is later. A conjunct can contain a copy of the containing 
subexpression that lacks
+   * the contained one, e.g. `(a + c) + b` for `(a + b) + c` under the 
canonicalization of a
+   * commutative operator.
+   *
+   * This must be the only subexpression elimination on this context.
+   */
+  def generateConjunctsWithSubexprCodes(predicate: Expression): 
Option[Seq[(String, ExprCode)]] = {
+    val cleanedPredicate = predicate.freshCopyIfContainsStatefulExpression()
+    equivalentExpressions.addExprTree(cleanedPredicate)
+    val allCommonExprs = equivalentExpressions.getCommonSubexpressions
+    val commonEqs = allCommonExprs.map(ExpressionEquals(_)).toSet
+    def split(e: Expression): Seq[Expression] = e match {
+      case And(left, right) if !commonEqs.contains(ExpressionEquals(e)) =>
+        split(left) ++ split(right)
+      case _ => Seq(e)
+    }
+    if (allCommonExprs.isEmpty) {
+      None
+    } else {
+      // Every common subexpression is a conjunct or lies inside one, since 
only the ANDs that are
+      // not common are split. A contained one comes before the ones that 
contain it.
+      val conjuncts = split(cleanedPredicate)
+      val calls =
+        allCommonExprs.map(expr => ExpressionEquals(expr) -> 
generateSubexprFunction(expr))
+      val codes = conjuncts.map(e => e.genCode(this))
+      val callOf = calls.toMap
+      val eliminated = calls.map(_._1)
+      // The eliminated subexpressions that `expr` contains, other than itself.
+      def dependencies(expr: Expression): Seq[ExpressionEquals] = 
eliminated.filter { dep =>
+        expr.children.exists(_.exists(e => ExpressionEquals(e) == dep))
+      }
+      // The eliminated subexpressions by the conjunct that first references 
them, found once.
+      val byFirstReference = eliminated.groupBy(e => 
firstReferencingExpression(conjuncts, e))

Review Comment:
   **Nit (P3):** Each `firstReferencingExpression(conjuncts, e)` call here 
still walks the conjuncts from the first one until it meets `e`, so grouping S 
eliminated subexpressions costs about S times the size of the predicate. 
`dependencies` just above likewise filters every eliminated key and walks the 
subexpression's children once per key. Both run in every `Predicate.create` of 
an AND predicate with an eliminated subexpression outside whole-stage codegen, 
once per partition for a filter, and the base branch ran neither. The cached 
height check keeps most comparisons cheap, so the cost is small for typical 
predicates, but it grows quadratically for wide filters such as the 400-column 
case measured in the review discussion. One ordered walk of the conjuncts that 
records the first index of each eliminated `ExpressionEquals` key, and one walk 
of each subexpression's children that collects the keys it contains, give the 
same groups and the same call order, since `ExpressionEquals.hashC
 ode` agrees with its equality.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59984#discussion_r4481087414).
   
   **Verification:**
   - **Compatibility:** For the existing placement predicates (nested, 
contained, commutatively reordered and branch-first subexpressions, the 
many-subexpressions case and the kept common AND), the calls placed before each 
conjunct, the evaluation counts and the predicate results are unchanged.
   - **Inspection:** The first-reference grouping and the dependency lookup no 
longer call a per-key scan over the conjuncts or over a subexpression's tree 
once for each eliminated subexpression.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodegenSubexpressionEliminationSuite.scala:
##########
@@ -56,18 +58,168 @@ class CodegenSubexpressionEliminationSuite extends 
SparkFunSuite {
     }
   }
 
+  test("SPARK-60332: GeneratePredicate evaluates a common subexpression of 
later conjuncts " +

Review Comment:
   **Nit (P3):** The migration-guide entry and the comment in 
`GeneratePredicate.create` both say that a subexpression one conjunct repeats 
is now evaluated just before that conjunct, but every new SPARK-60332 case here 
and in `WholeStageCodegenSuite` shares its subexpression across two or more 
conjuncts. If a later change limited the conjunct path to subexpressions shared 
by several conjuncts, `SELECT a FROM t WHERE b < 0 AND (y + 1) * (y + 1) > 0` 
would again fail with ARITHMETIC_OVERFLOW with whole-stage codegen off on a row 
with `b = 1` and `y = 2147483647`, and no test would fail. A 
generated-predicate case whose only common subexpression is repeated within the 
second conjunct, with evaluation counts for a FALSE and a TRUE first conjunct, 
plus that query in the filter tests, which turn Parquet filter pushdown off, 
would cover it.
   
   **Verification:**
   - **Regression:** With elimination on, a predicate whose only common 
subexpression is repeated within its second conjunct evaluates it zero times 
when the first conjunct is FALSE and once when it is TRUE. In ANSI mode, with 
Parquet filter pushdown off so that row-group statistics do not skip the row 
before the filter, `b < 0 AND (y + 1) * (y + 1) > 0` returns no rows for a row 
with b = 1 and y = 2147483647 instead of failing with ARITHMETIC_OVERFLOW, with 
whole-stage codegen on and off.



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