joelrobin18 commented on code in PR #59954:
URL: https://github.com/apache/spark/pull/59954#discussion_r4540937632


##########
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:
   Restored both exact rewrites in `rewriteTryChain`, which replaces 
`foldTryChain`:
   - A TRY step whose literal operand is 0 (Add) or 1 (Multiply) is replaced by 
its other operand.
   - The literals on the path from the top of the chain through steps with one 
literal operand are folded into one TRY step above the sub-expression where the 
path ends. The path stops at grouping expressions and at a step with two 
non-literal operands, so literals between two operands stay. Folding still 
requires non-NULL literals that move away from zero and a folded value that 
fits the type.
   
   New plan tests under both ANSI settings: `try_add(a, 0)`, `try_add(0, a)`, 
`try_multiply(b, 1)` and `try_multiply(1, b)` become the column; 
`try_add(try_add(a, 0), b)` becomes `try_add(a, b)`; `try_add(try_add(a, 0), 
0)` becomes `a`; `try_add(try_add(try_add(a, 5), -3), 0)` drops only the outer 
step; `try_add(try_add(try_add(a, b), 1), 2)` and the Multiply analogue fold to 
`try_add(try_add(a, b), 3)` and `try_multiply(try_multiply(a, b), 6)`; 
`try_add(try_add(try_add(try_add(a, 1), b), 2), 3)` keeps the 1 and folds the 
rest; and a filter `try_add(a, 0) > 5` becomes `a > 5`. Every chain the earlier 
tests keep as written still stays unchanged. `try_arithmetic.sql` also checks 
literal-tail chains over rows where different steps overflow. Updated the 
comments above the flatten helpers and on the rule.
   
   Addressed in c94ab88ce0f.



##########
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:
   `Add` and `Multiply` canonicalization now gathers a nested same-context 
LEGACY decimal step only when its result precision before bounding fits 
`DecimalType.MAX_PRECISION`, so the step can neither overflow nor round. Any 
other such step stays one operand, canonicalized on its own like a TRY step, 
and the root still orders its own two operands. The precision formula is shared 
with `resultDecimalType`.
   
   `CanonicalizeSuite`, below and above the multi-operand threshold: `(a + b) + 
c` and `(a + c) + b` over LEGACY `DECIMAL(38,0)` are not equal, and neither is 
the Multiply analogue; swapping the operands of a step still matches; 
`DECIMAL(37,0)` Add and `DECIMAL(18,0)`/`DECIMAL(19,0)` Multiply chains at the 
precision boundary still match; ANSI chains are unchanged. 
`decimalArithmeticOperations.sql` (both ANSI settings): with ANSI off, `SELECT 
(a + b) + c, (a + c) + b` returns `NULL` and 
`99999999999999999999999999999999999995`, the GROUP BY query fails with 
`MISSING_AGGREGATION`, and a small-precision chain still matches its GROUP BY. 
With the base branch's canonicalization, the projection returns `NULL` twice 
and the GROUP BY passes analysis, so these golden results fail. Added a SQL 
migration-guide entry.
   
   Addressed in c94ab88ce0f.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -370,19 +370,26 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
  * Reorder associative integral-type operators and fold all constants into one.
  */
 object ReorderAssociativeOperator extends Rule[LogicalPlan] {
+  // Flatten only operators evaluated in the same mode as the root: rebuilding 
a TRY-mode Add or

Review Comment:
   Reworded the scaladoc: the rule reorders and folds the literals of integral 
`Add` and `Multiply` chains whose operators share an evaluation mode, keeps an 
operator of another mode as one operand, and leaves TRY chains in their written 
grouping apart from the exact rewrites in `rewriteTryChain`.
   
   Addressed in c94ab88ce0f.



##########
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
+    val integers = values.map(v => BigInt(v.asInstanceOf[Number].longValue))
+    if (!literalsMoveAwayFromZero(integers)) return None
+    val folded = integers.reduce(combine)
+    val foldedLiteral = dataType match {
+      case ByteType if folded.isValidByte => Some(Literal(folded.toByte))

Review Comment:
   Added plan tests over a BIGINT/SMALLINT/TINYINT relation: 
`try_add(try_add(l, Long.MaxValue), 1L)`, `try_multiply(try_multiply(l, 1L << 
32), 1L << 31)`, and SMALLINT and TINYINT chains whose literals are typed to 
the column and overflow its type all stay as written. The in-range BIGINT fold 
`try_add(try_add(l, Int.MaxValue.toLong), 1L)` becomes `try_add(l, 
2147483648L)`. The typed NULL chain `try_add(try_add(a, CAST(NULL AS INT)), 1)` 
stays unfolded. Verified that dropping the BIGINT, SMALLINT or TINYINT fit 
check folds those chains into wrapped literals (for example `l + 
-9223372036854775808` and `t + 127`) and fails the test, and that removing the 
NULL check fails it with a NullPointerException.
   
   Addressed in c94ab88ce0f.



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