cloud-fan commented on code in PR #59954:
URL: https://github.com/apache/spark/pull/59954#discussion_r4549313861


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala:
##########
@@ -481,7 +500,9 @@ case class Add(
 
   override lazy val canonicalized: Expression = {
     val reorderResult = buildCanonicalizedPlan(
-      { case Add(l, r, em) if em == evalContext => Seq(l, r) },
+      // A nested step that cannot be regrouped stays one operand, 
canonicalized on its own.
+      { case a @ Add(l, r, em) if em == evalContext && ((a eq this) || 
a.canBeRegrouped) =>

Review Comment:
   **Non-blocking (P2):** The top step is always gathered here (`a eq this`), 
and so are its exact nested steps, even when the top step itself can overflow 
or round. At the default threshold of 3, a gathered list of three or more 
operands becomes a `MultiCommutativeOp`, so it cannot equal a chain that keeps 
a bounded nested step whole. With 
`spark.sql.analyzer.canonicalization.multiCommutativeOpMemoryOptThreshold` 
raised above 3, as the PR's own tests do, the list is instead reduced into a 
binary tree in hash order, and that tree can be the same one.
   
   For example, take ANSI off, `p` and `q` of type `DECIMAL(37,0)`, `r` of type 
`DECIMAL(38,0)`, and the threshold at 100. In `(p + q) + r` the nested `p + q` 
fits 38 digits and is gathered, so when the hash order of the operands is `p, 
r, q`, they reduce to `Add(Add(p, r), q)`. In `(p + r) + q` the nested `p + r` 
can overflow and stays one operand, `Add(p, r)`, and when it sorts before `q` 
this chain also canonicalizes to `Add(Add(p, r), q)`. Both chains have type 
`DECIMAL(38,0)`, so the result-type fallback accepts both. Reading the code, 
for `p = 5E36`, `q = -5E36` and `r = 10^38 - 1`, `(p + q) + r` is `10^38 - 1` 
while `(p + r) + q` is NULL, yet the two are `semanticEquals`. Whether they 
match depends on the internal threshold and on attribute hash order, which 
follows expression IDs.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59954#discussion_r4508963490).
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -397,17 +405,95 @@ object ReorderAssociativeOperator extends 
Rule[LogicalPlan] {
     case _ => false
   }
 
+  /**
+   * Rewrites a TRY-mode chain only where that cannot change its result. A TRY 
step returns NULL
+   * exactly when its own operation overflows, so regrouping the chain can 
change which step
+   * overflows. Two rewrites are exact:
+   *  - A step whose literal operand is the `identity` never overflows, so it 
is replaced by its
+   *    other operand.
+   *  - The literals on the path from the top of the chain through steps with 
one literal and one
+   *    non-literal operand are folded into one step above the sub-expression 
X where the path ends,
+   *    for example a step with two non-literal operands. If these literals 
are not NULL, satisfy
+   *    `literalsMoveAwayFromZero`, and fold to a value that fits the result 
type, every written
+   *    partial result lies between X and the final result, so some written 
step overflows exactly
+   *    when the folded step does.
+   * As in `flattenAdd`, steps that are grouping expressions are kept.
+   */
+  private def rewriteTryChain(
+      root: Expression,
+      groupSet: ExpressionSet,
+      tryStepOperands: PartialFunction[Expression, (Expression, Expression)],
+      identity: Int,
+      literalsMoveAwayFromZero: Seq[BigInt] => Boolean,
+      combine: (BigInt, BigInt) => BigInt,
+      build: (Expression, Expression) => Expression): Expression = {
+    def operands(e: Expression): Option[(Expression, Expression)] =
+      if (groupSet.contains(e)) None else tryStepOperands.lift(e)

Review Comment:
   **Nit (P3):** This `groupSet` check is what keeps a TRY chain in an 
`Aggregate` derivable from its grouping expressions. For `SELECT 
try_add(try_add(a, 1), 2) FROM t GROUP BY try_add(a, 1)`, it stops the literal 
path at the grouping step, so only one literal is collected and the chain stays 
as written. Without the check, the path would continue to `a` and fold `1` and 
`2`, turning the aggregate expression into `try_add(a, 3)`, which no longer 
derives from the grouping expression and fails at planning. No test exercises 
it: every new TRY test in `ReorderAssociativeOperatorSuite` runs on a `Project` 
or a `Filter`, and the only `Aggregate` test, "nested expression with aggregate 
operator", uses default-mode `Add` and reaches `flattenAdd`'s guard instead. 
Could you add a plan test with an `Aggregate` that groups by a TRY step and 
selects a TRY chain built on it, for both `try_add` and `try_multiply`?
   
   **Verification:**
   - **Regression:** An optimizer plan test over an Aggregate that groups by a 
TRY step and selects a TRY chain built on that step keeps the aggregate 
expression as written for try_add and try_multiply under both ANSI settings, 
and fails when the TRY rewrite no longer stops at grouping expressions.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala:
##########
@@ -442,14 +442,33 @@ case class Add(
   // scalastyle:on
   override def resultDecimalType(p1: Int, s1: Int, p2: Int, s2: Int): 
DecimalType = {
     val resultScale = max(s1, s2)
-    val resultPrecision = max(p1 - s1, p2 - s2) + resultScale + 1
+    val resultPrecision = unboundedResultPrecision(p1, s1, p2, s2)
     if (allowPrecisionLoss) {
       DecimalType.adjustPrecisionScale(resultPrecision, resultScale)
     } else {
       DecimalType.bounded(resultPrecision, resultScale)
     }
   }
 
+  // The result precision before it is bounded by the maximum precision. A 
result type of this
+  // precision holds every exact sum.
+  private def unboundedResultPrecision(p1: Int, s1: Int, p2: Int, s2: Int): 
Int =
+    max(p1 - s1, p2 - s2) + max(s1, s2) + 1
+
+  // Whether canonicalization can regroup this step with an enclosing Add of 
the same evaluation
+  // context. A TRY step returns NULL exactly when its own operation 
overflows. So does a non-ANSI
+  // decimal step whose result type is bounded by the maximum precision, which 
can also round under
+  // precision loss. Regrouping such a step can change the result.
+  private def canBeRegrouped: Boolean = evalMode match {
+    case EvalMode.TRY => false
+    case EvalMode.LEGACY if childrenResolved => (left.dataType, 
right.dataType) match {

Review Comment:
   **Non-blocking (P2):** This gate keeps a nested decimal step whole only in 
LEGACY mode, so every ANSI step falls through to `case _ => true` and is still 
gathered. But ANSI decimal steps also round silently. With 
`spark.sql.decimalOperations.allowPrecisionLoss=true`, the default, 
`adjustPrecisionScale` lowers the scale of a step whose unbounded precision 
exceeds 38 and whose scale exceeds 6, and `checkDecimalOverflow` rounds with 
`ROUND_HALF_UP` and raises only when the precision overflows. The comment above 
names rounding under precision loss as a reason a step cannot be regrouped, but 
the gate applies that reason only to LEGACY steps.
   
   For example, take ANSI on and `DECIMAL(38,10)` columns with `a = 
0.0000000044`, `b = 0.0000000001` and `c = 0`. By Spark's decimal type rules, 
`a + b` has type `DECIMAL(38,9)` and rounds 0.0000000045 to 0.000000005, so `(a 
+ b) + c` is `0.00000001` as `DECIMAL(38,8)`. `a + c` rounds to 0.000000004, so 
`(a + c) + b` is 0.0000000041, which rounds to `0.00000000`. Both chains have 
type `DECIMAL(38,8)`, so the SPARK-40903 fallback does not separate them, and 
both canonicalize to the operand list `[a, b, c]`. Reading the code, `SELECT (a 
+ c) + b FROM t GROUP BY (a + b) + c` passes analysis and returns the grouping 
value, and subexpression elimination can evaluate one chain for both columns of 
`SELECT (a + b) + c, (a + c) + b`. Multiply behaves the same way: for 
`DECIMAL(38,10)` columns with `x = 0.0000005`, `y = 1` and `z = 3`, `(x * y) * 
z` is 0.000003 and `(x * z) * y` is 0.000002, both `DECIMAL(38,6)`.
   
   This is the wrong result the PR fixes for non-ANSI steps, and it reaches 
every nested ANSI decimal Add or Multiply step whose result scale is below its 
exact scale. My earlier suggestion to leave ANSI chains unchanged considered 
only overflow, which raises under ANSI, and missed rounding. The new tests 
cannot catch it, because the ANSI assertion and every decimal operand in 
`CanonicalizeSuite` use scale 0.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59954#discussion_r4508963490).
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -397,17 +404,62 @@ object ReorderAssociativeOperator extends 
Rule[LogicalPlan] {
     case _ => false
   }
 
+  /**
+   * Folds the literals of a flattened TRY chain into one TRY operation only 
when that cannot change
+   * the result: the chain has exactly one non-literal operand, 
`literalsMoveAwayFromZero` holds for
+   * its literals, and the folded literal fits the result type. The partial 
results then move
+   * monotonically from the operand to the final value, so a written step 
overflows exactly when the
+   * folded one does.
+   */
+  private def foldTryChain(
+      operands: Seq[Expression],
+      dataType: DataType,
+      literalsMoveAwayFromZero: Seq[BigInt] => Boolean,
+      combine: (BigInt, BigInt) => BigInt,
+      build: (Expression, Expression) => Expression): Option[Expression] = {
+    val (literals, others) = operands.partition(_.isInstanceOf[Literal])
+    val values = literals.map(_.asInstanceOf[Literal].value)
+    if (others.length != 1 || literals.length < 2 || values.contains(null)) 
return None

Review Comment:
   Thanks, this restores both exact rewrites. Identity steps are dropped, and a 
literal tail above a step with two non-literal operands folds into one TRY 
step. Mixed-sign, NULL or out-of-range literals keep the chain as written, and 
a literal between two non-literal operands stays where it is. The new plan 
tests, including the filter case, cover these shapes.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4508963480","thread_id":"inline:4508963480","verdict_sha256":"5325b866645fcb0f755faccee11ebfcdbaed6125016524dc7a70702f23778c42"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala:
##########
@@ -481,7 +481,10 @@ case class Add(
 
   override lazy val canonicalized: Expression = {
     val reorderResult = buildCanonicalizedPlan(
-      { case Add(l, r, em) if em == evalContext => Seq(l, r) },
+      // TRY arithmetic is commutative but not associative: each step returns 
NULL only when its
+      // own operation overflows. Keep the written nesting and order only the 
direct operands.
+      { case a @ Add(l, r, em) if em == evalContext && (evalMode != 
EvalMode.TRY || (a eq this)) =>

Review Comment:
   Thanks, the LEGACY gate and its tests look right: a nested non-ANSI decimal 
step now stays one operand when its exact result can exceed 38 digits, while 
swaps within a step and exact small-precision chains still match. This review 
separately raises two related cases: ANSI decimal steps that round when 
precision loss lowers their scale, which my earlier exclusion of ANSI chains 
overlooked, and chains whose top step can overflow or round while their nested 
steps are exact, which can still match another grouping when the multi-operand 
canonicalization threshold is raised.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4508963490","thread_id":"inline:4508963490","verdict_sha256":"5325b866645fcb0f755faccee11ebfcdbaed6125016524dc7a70702f23778c42"}
 -->



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