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


##########
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:
   **Blocking (P1):** This guard declines a lone literal and any chain with two 
or more non-literal operands, and the TRY branches then return the root 
unchanged. That also drops two rewrites master applied to TRY chains that are 
exact for every input:
   
   - Identity steps (SPARK-49915, released in 4.0.0): master rewrites 
`try_add(a, 0)`, `try_add(0, a)` and `try_multiply(b, 1)` to `a` or `b`, and 
`try_add(try_add(a, 0), b)` to `try_add(a, b)`. Here `foldTryChain` gets `[a, 
0]` (one literal) or `[a, 0, b]` (two non-literal operands) and every step 
stays; `try_add(try_add(a, 0), 0)` only becomes `try_add(a, 0)`.
   - Literal tails above a multi-operand sub-chain: master folds 
`try_add(try_add(try_add(a, b), 1), 2)` to `try_add(try_add(a, b), 3)`, which 
is exact because every intermediate value lies between `X = try_add(a, b)` and 
`X + 3`. Here the flattened chain `[a, b, 1, 2]` has two non-literal operands, 
so nothing folds. `try_multiply(try_multiply(try_multiply(a, b), 2), 3)` is the 
same.
   
   These inputs already gave correct results on master, so this is a regression 
outside the bug being fixed. Each kept step adds a TRY add or multiply per row. 
A filter such as `try_add(col, 0) > 5` was `col > 5` on master and can no 
longer be pushed to Parquet, ORC or DSv2 sources, because filter translation 
only accepts a bare column. A join key such as `try_add(bucket_col, 0)` no 
longer matches the bucket partitioning, so a shuffle is added. The result also 
becomes nullable where master's was not, so a stateful streaming query keyed on 
such an expression over a non-nullable column fails the state schema check on 
restart when its checkpoint predates always-nullable stateful output. No test 
covers these shapes; the existing zero/one test uses non-TRY operators.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59954#discussion_r4444272141).
   
   **Recommended change:** In the TRY branches of ReorderAssociativeOperator, 
restore the two exact rewrites the base branch applied to TRY chains. First, 
replace a TRY Add step whose literal operand is 0, or a TRY Multiply step whose 
literal operand is 1, with its other operand. Second, collect literals by 
descending only through same-mode TRY steps that have a literal operand, 
stopping at grouping expressions and at the first step whose two operands are 
both non-literal. Fold the collected literals under the existing conditions 
(non-null, moving away from zero, fitting the result type) into one TRY step 
over the remaining sub-expression, or into the sub-expression itself when the 
folded literal is 0 for Add or 1 for Multiply. Update the comment above the 
flatten helpers, which names one exact shape, to describe these rewrites, and 
add associative-reordering optimizer plan tests for them.
   
   **Why this works:** Each rewrite keeps every written step's overflow 
outcome. A step that adds 0 or multiplies by 1 never overflows and propagates 
NULL like its operand, so removing it changes nothing. When literals sit only 
on the path from the root to one sub-expression X and all move away from zero, 
every intermediate result lies between X and X combined with the folded 
literal. The written chain therefore returns NULL exactly when the folded step 
does. Stopping the descent at the first step with two non-literal operands 
keeps literals that sit between operands, where regrouping is not exact, out of 
the fold.
   
   **Scope:** Restore exact identity-step removal and literal-tail folding for 
TRY-mode Add and Multiply in ReorderAssociativeOperator, with optimizer plan 
tests.
   
   **Risks:** Optimized plans change only for TRY chains whose base-branch 
optimized form was exact, and they return to that form. Because the rewrites 
drop only operations that cannot change results, they can be taken out again 
without affecting query results.
   
   **Constraints:** Keep every condition under which a TRY chain must stay as 
written: mixed-sign or below-1 literals, a NULL literal, a folded literal that 
does not fit the result type, and literals that sit between two non-literal 
operands. Leave the ANSI and LEGACY branches of the rule unchanged.
   
   **Exclusions:**
   - Same-mode ANSI regrouping, which can move an overflow error and which the 
earlier review left as a separate decision, stays as on the base branch.
   
   **Success:** try_add(x, 0), try_add(0, x) and try_multiply(x, 1) over a 
non-foldable integral column x optimize to x, try_add(try_add(a, 0), b) 
optimizes to try_add(a, b), and try_add(try_add(a, 0), 0) optimizes to a. 
try_add(try_add(try_add(a, b), 1), 2) optimizes to try_add(try_add(a, b), 3), 
and try_multiply(try_multiply(try_multiply(a, b), 2), 3) optimizes to 
try_multiply(try_multiply(a, b), 6). Every TRY chain the PR's tests keep as 
written, such as try_add(try_add(a, -5), b), try_add(try_add(a, 5), -3) and 
try_add(try_add(a, 2147483647), 1), still optimizes unchanged. A filter such as 
try_add(a, 0) > 5 over a file source optimizes to a > 5 and is eligible for 
pushdown.
   
   **Verification:**
   - **Regression:** Under both ANSI settings, plan tests show try_add(x, 0), 
try_add(0, x), try_multiply(x, 1), try_add(try_add(a, 0), b) and 
try_add(try_add(a, 0), 0) losing their identity steps, and the Add and Multiply 
literal-tail chains folding to one TRY step above the multi-operand sub-chain.
   - **Compatibility:** TRY chains that must keep their written form 
(mixed-sign literals, literals between two non-literal operands, multipliers of 
-1 or 0, a folded literal that overflows its type, a NULL literal) still 
optimize unchanged, and the exact folds the PR already performs keep their 
current plans.
   - **Behavior:** For literal-tail chains such as try_add(try_add(try_add(a, 
b), 1), 2), query results over rows where a + b, a + b + 1 and a + b + 3 
overflow at different points match evaluating each written step, returning NULL 
exactly when a written step overflows.



##########
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:
   **Non-blocking (P2):** This keeps the written nesting only for TRY roots, 
but the reason given in the comment above, that each step returns NULL only 
when its own operation overflows, also holds for decimal `Add` and `Multiply` 
in LEGACY mode (ANSI off): `checkDecimalOverflow` passes `nullOnOverflow = 
!failOnError`, and `nullable` notes that non-ANSI decimal arithmetic can return 
NULL for non-null inputs. Such chains are still gathered across every nesting 
level.
   
   For example, with `spark.sql.ansi.enabled=false` and `DECIMAL(38,0)` columns 
holding `a = 99999999999999999999999999999999999999, b = 1, c = -5`, `(a + b) + 
c` is NULL because `a + b` overflows, while `(a + c) + b` is 
`99999999999999999999999999999999999995`. Every step's type is `DECIMAL(38,0)`, 
so the result-type fallback does not apply and the two chains canonicalize as 
equal. Reading the code, `SELECT (a + c) + b FROM d GROUP BY (a + b) + c` 
passes analysis and returns the grouping value NULL, and in `SELECT (a + b) + 
c, (a + c) + b FROM d` subexpression elimination can evaluate one chain for 
both columns. Unlike `try_add`, a regular `+` is a raw `Add` during analysis, 
so GROUP BY validation sees the flattened form. The behavior is the same as on 
master; it is the sibling case of the TRY fix. ANSI decimal chains raise on 
overflow instead, and integral LEGACY chains wrap, so they are unaffected.
   
   **Recommended change:** In Add.canonicalized and Multiply.canonicalized, 
gather a nested same-context LEGACY step with a decimal result only when that 
step can neither overflow nor round: its exact result precision, computed from 
its operands' precisions and scales, must fit DecimalType.MAX_PRECISION. 
Otherwise keep the step as one operand, canonicalized on its own, as TRY steps 
already are; the root still orders its own two operands. Add canonicalization 
tests and a non-ANSI SQL test for decimal chains.
   
   **Why this works:** A LEGACY decimal step whose exact result fits the 
maximum precision computes its exact value, so regrouping steps like it cannot 
change the result. A step that can exceed that precision depends on its own 
operands: it returns NULL on overflow, or rounds under precision loss. Keeping 
such steps nested means two chains share a canonical form only when every 
gathered nested step is exact. That restores the value equality that 
semantic-equality consumers assume, while small-precision chains keep matching.
   
   **Scope:** Stop Add and Multiply canonicalization from regrouping non-ANSI 
decimal steps that can overflow or round, with canonicalization and SQL tests.
   
   **Risks:** Differently grouped non-ANSI decimal chains that contain a step 
able to overflow or round stop matching in GROUP BY validation, subexpression 
elimination and reuse. A query that selects such a regrouped copy of a GROUP BY 
chain then fails analysis with MISSING_AGGREGATION, where the base branch 
returned the grouping value, which is wrong only for rows on which a step 
overflows or rounds. Users with such queries lose them, so the change warrants 
a SQL migration-guide entry.
   
   **Constraints:** Keep TRY nesting, and ANSI and LEGACY integral 
canonicalization, unchanged. Keep two chains that differ only by swapping the 
operands of a step semantically equal.
   
   **Exclusions:**
   - ANSI-mode decimal chains, which raise on overflow rather than return NULL, 
keep their current canonicalization.
   
   **Success:** With ANSI off and DECIMAL(38,0) columns holding 
(99999999999999999999999999999999999999, 1, -5), SELECT (a + c) + b FROM d 
GROUP BY (a + b) + c fails analysis with MISSING_AGGREGATION, and SELECT (a + 
b) + c, (a + c) + b FROM d returns NULL and 
99999999999999999999999999999999999995. Differently grouped LEGACY decimal 
chains whose nested steps all fit the maximum precision exactly, such as sums 
of DECIMAL(10,2) columns, remain semantically equal. TRY chains and integral 
chains in every mode canonicalize as they do with the PR.
   
   **Verification:**
   - **Regression:** With ANSI off, the GROUP BY query and the two-column 
projection over DECIMAL(38,0) columns described in the postconditions fail 
analysis and return NULL and 99999999999999999999999999999999999995 
respectively, instead of returning the grouping value or NULL twice.
   - **Behavior:** Canonicalization tests show (a + b) + c and (a + c) + b over 
DECIMAL(38,0) LEGACY Add, and an analogous LEGACY decimal Multiply chain, are 
not semantically equal, both below and above the multi-operand canonicalization 
threshold, while swaps within a step still match.
   - **Compatibility:** Small-precision LEGACY decimal chains, ANSI decimal 
chains, and integral chains in every mode keep their current semantic equality.



##########
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:
   **Nit (P3):** Only the `IntegerType` case here is pinned by a test 
(`Int.MaxValue + 1` and `65536 * 32768`): `testRelation` has only INT columns 
and every new SQL query uses INT. If the `isValidLong`, `isValidShort` or 
`isValidByte` check were dropped or wrong, `toLong`, `toShort` or `toByte` 
would wrap, so `try_add(try_add(bigint_col, 9223372036854775807), 1)` would 
return a wrong non-NULL value and nothing would fail. BIGINT is the width most 
queries reach, since int literals are widened for a BIGINT column. The NULL 
check on line 422 matters too: `FoldablePropagation` runs after 
`NullPropagation` and before this rule, so a typed NULL from a subquery alias 
can arrive as a literal operand, and without the check line 423 throws a 
NullPointerException.
   
   Could you add plan tests for a BIGINT and a TINYINT (or SMALLINT) TRY chain 
whose literals overflow the type, with the literals typed to the column's width 
so the chain keeps that type, one in-range BIGINT fold, and a TRY chain with a 
typed NULL literal, such as `Add(Add(a, Literal(null, IntegerType), 
EvalMode.TRY), 1, EvalMode.TRY)`, that must stay unfolded?
   
   **Verification:**
   - **Regression:** Dropping or weakening the BIGINT or TINYINT fit check 
makes the corresponding overflow case fail by folding the chain into a wrapped 
literal.
   - **Regression:** Removing the NULL-literal check makes the NULL-literal 
case fail.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -273,19 +273,23 @@ object ConstantPropagation extends Rule[LogicalPlan] {
  * 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
+  // Multiply (try_add, try_multiply) in the enclosing mode would change its 
overflow behavior.
   private def flattenAdd(
     expression: Expression,
-    groupSet: ExpressionSet): Seq[Expression] = expression match {
-    case expr @ Add(l, r, _) if !groupSet.contains(expr) =>
-      flattenAdd(l, groupSet) ++ flattenAdd(r, groupSet)
+    groupSet: ExpressionSet,
+    evalContext: NumericEvalContext): Seq[Expression] = expression match {
+    case expr @ Add(l, r, c) if c == evalContext && !groupSet.contains(expr) =>

Review Comment:
   Thanks, this fixes it. TRY roots now keep their written grouping, and the 
one shape that still folds is exact: with a single non-literal operand and 
literals that all move away from zero, every intermediate result lies between 
the operand and the folded result, so a written step overflows exactly when the 
folded step does. My earlier suggestion to leave TRY chains exactly as written 
went too far, though: this review raises that some exact simplifications master 
applied to TRY chains are no longer made.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4444272141","thread_id":"inline:4444272141","verdict_sha256":"73dea33e570c4ccc8d3695022e03bb3ca2ab8d83684629a174ca2d75af059d8e"}
 -->



##########
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:
   **Nit (P3):** The scaladoc just above (line 370) still says the rule will 
"fold all constants into one". With this change the rule keeps an operator of 
another mode whole, so in `Add(Add(a, 1, EvalMode.TRY), 2)` the TRY literal 1 
is not folded with the outer 2, and it leaves both literals in 
`try_add(try_add(a, 5), -3)`. Could you reword it to match this comment, for 
example: 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 rewrites that cannot change the result?
   
   **Verification:**
   - **Inspection:** The scaladoc and the comment above the flatten helpers 
describe the same behavior as the rule's TRY and non-TRY branches, including 
different-mode operands kept whole and TRY chains folded only by rewrites that 
cannot change the result.



##########
sql/core/src/test/resources/sql-tests/inputs/try_arithmetic.sql:
##########
@@ -111,3 +111,26 @@ SELECT try_multiply(interval 2 year, 0);
 SELECT try_multiply(interval 2 second, 0);
 SELECT try_multiply(interval 2147483647 month, 2);
 SELECT try_multiply(interval 106751991 day, 2);
+
+-- try_add and try_multiply chains over non-foldable inputs keep their written 
grouping, both at
+-- the top level and nested in regular arithmetic.
+CREATE TABLE try_arithmetic_chains(a INT, b INT) USING parquet;
+INSERT INTO try_arithmetic_chains VALUES (2147483647, 1), (-10, 0), 
(2147483643, 0), (1073741824, 2);
+SELECT try_add(try_add(a, -5), b) FROM try_arithmetic_chains WHERE a = 
2147483647;
+SELECT try_add(try_add(a, -5), b) + 1 FROM try_arithmetic_chains WHERE a = 
2147483647;
+SELECT try_add(try_add(a, 2147483647), 1) FROM try_arithmetic_chains WHERE a = 
-10;
+SELECT -5 + try_add(try_add(a, 2147483647), 1) FROM try_arithmetic_chains 
WHERE a = -10;
+SELECT try_add(try_add(a, 5), -3) FROM try_arithmetic_chains WHERE a = 
2147483643;
+SELECT try_multiply(try_multiply(a, -1), b) FROM try_arithmetic_chains WHERE a 
= 1073741824;
+SELECT try_multiply(try_multiply(a, -1), b) * 3 FROM try_arithmetic_chains 
WHERE a = 1073741824;
+-- Chains with one column operand and literals that move away from zero fold 
exactly.
+SELECT try_add(try_add(a, 1), 2) FROM try_arithmetic_chains WHERE a = 
2147483643;
+SELECT try_add(try_add(a, 2), 3) FROM try_arithmetic_chains WHERE a = 
2147483643;
+SELECT try_multiply(try_multiply(a, 2), 3) FROM try_arithmetic_chains WHERE a 
= -10;
+SELECT try_multiply(try_multiply(a, 2), 2) FROM try_arithmetic_chains WHERE a 
= 1073741824;
+-- A differently grouped TRY chain is not the grouping expression.
+SELECT try_add(try_add(a, -5), b) FROM try_arithmetic_chains WHERE a = 
2147483647

Review Comment:
   **Nit (P3):** Reading the code, this query and the try_multiply one below it 
already fail with `MISSING_AGGREGATION` on master. During analysis `try_add` is 
still a `TryAdd` wrapper whose canonical form is its replacement's, and that 
replacement's operand is the inner `TryAdd`, not an `Add`, so 
`gatherCommutative` stops there and master already keeps the nesting. Reverting 
the `Add`/`Multiply` canonicalization change therefore leaves these golden 
results and the `TryAdd`/`TryMultiply` not-equal assertions in 
`CanonicalizeSuite` passing; only the raw TRY-mode assertions fail.
   
   The canonicalization change only matters after `ReplaceExpressions` removes 
the wrappers, where two differently grouped TRY chains in one projection could 
otherwise be merged by subexpression elimination. Could you add queries that 
select both groupings, such as `SELECT try_add(try_add(a, -5), b), 
try_add(try_add(a, b), -5) FROM try_arithmetic_chains WHERE a = 2147483647` 
(expected `2147483643` and `NULL`) and the try_multiply analogue, and drop or 
relabel these GROUP BY queries? The GROUP BY example and bullet in the PR 
description have the same problem.
   
   **Verification:**
   - **Regression:** With Add and Multiply canonicalization flattening raw TRY 
chains, as on the base branch, the new projection queries return the same value 
in both columns, so their golden comparison fails.
   - **Behavior:** With the PR's canonicalization, the queries return 
2147483643 and NULL for try_add and -2147483648 and NULL for try_multiply, with 
and without ANSI.



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