This is an automated email from the ASF dual-hosted git repository.

dongjoon-hyun pushed a commit to branch branch-4.3
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.3 by this push:
     new 46899dd47baf [SPARK-61131][SQL] Fix wrong results of decimal `div` in 
ANSI mode when the quotient overflows `BIGINT`
46899dd47baf is described below

commit 46899dd47baf05a2fd0b23eb84819c6129ee7a8e
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Mon Nov 9 07:38:55 2026 -0800

    [SPARK-61131][SQL] Fix wrong results of decimal `div` in ANSI mode when the 
quotient overflows `BIGINT`
    
    ### What changes were proposed in this pull request?
    
    This PR fixes a correctness issue. In ANSI mode, decimal `div` returns a 
silently wrapped `BIGINT` when the integral quotient fits its intermediate 
`DECIMAL(p, 0)` type but not `BIGINT`. After this PR, it fails with 
`ARITHMETIC_OVERFLOW`, which `div` on `BIGINT` already raises for 
`Long.MinValue div -1`.
    
    ```sql
    -- spark.sql.ansi.enabled=true (default)
    
    -- Issue 1: It should fail with ARITHMETIC_OVERFLOW, but returns 
687399551400672280.
    SELECT CAST(repeat('9', 35) AS DECIMAL(35, 0)) div 0.001BD;
    
    -- Issue 2: It should fail with ARITHMETIC_OVERFLOW, but returns 
-9223372036854775808.
    SELECT 9223372036854775808BD div 1;
    ```
    
    `IntegralDivide` computes the decimal quotient, checks it against 
`DECIMAL(p1 - s1 + s2, 0)`, and then converts it with `Decimal.toLong`. That 
conversion uses `BigDecimal.longValue` and keeps only the low 64 bits. When the 
decimal result type has more than 18 digits, a quotient can fit the decimal 
type but not a long.
    
    - The interpreted path (`integral.toLong(res)`) and codegen 
(`$decimalValue.toLong()`) now check that the quotient fits a long. They raise 
`QueryExecutionErrors.overflowInIntegralDivideError` with the query context 
when it does not.
    - The check runs only when `failOnError` is true (ANSI and TRY) and the 
decimal result type has more than 18 digits. Smaller types always fit a long, 
so their generated code does not change.
    - `DivModLike.decimalToDataTypeCodeGen` now returns the assignment 
statement and receives the error context code, so that `IntegralDivide` can add 
the check. `Divide` and `Remainder` keep the same generated code.
    - LEGACY mode keeps returning the wrapped value. It is the same as 
`CAST(decimal AS BIGINT)` and `BIGINT` `div` in LEGACY mode.
    
    ### Why are the changes needed?
    
    This is a correctness issue. ANSI mode documents that Spark throws an 
arithmetic exception at runtime for numeric overflow, but decimal `div` 
returned a wrong value without any error. ANSI mode is the default since Spark 
4.0.0, so the default configuration returns wrong results.
    
    The wrap was known when decimal support was added to `div` in SPARK-28322 
([v3.0.0](https://github.com/apache/spark/releases/tag/v3.0.0), 2020-06-06). 
Its test pins it with the comment "overflows long and so returns a wrong 
result", and the review noted that the long overflow "is yet to be handled in a 
different PR" 
(https://github.com/apache/spark/pull/25136#discussion_r312702907). SPARK-35152 
([v3.2.0](https://github.com/apache/spark/releases/tag/v3.2.0), 2021-10-06) 
later added the [...]
    
    MySQL's `DIV` also converts a decimal quotient to `BIGINT` and raises an 
error when the result exceeds the `BIGINT` range.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. In ANSI mode (the default), decimal `div` whose quotient is outside 
the `BIGINT` range now fails with `ARITHMETIC_OVERFLOW` instead of returning a 
wrong value.
    
    ```
    [ARITHMETIC_OVERFLOW] Overflow in integral divide. Use 'try_divide' to 
tolerate overflow and return NULL instead. If necessary set 
"spark.sql.ansi.enabled" to "false" to bypass this error. SQLSTATE: 22003
    ```
    
    This is the existing error of `Long.MinValue div -1`. Its `try_divide` hint 
came from SPARK-37149 (Spark 3.3.0), and this PR doesn't change it.
    
    LEGACY mode is unchanged. All released versions since Spark 3.0.0 are 
affected, including 
[v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27).
    
    This PR doesn't add a migration guide entry. It makes `div` follow the 
documented ANSI behavior, only the queries that returned a wrong value are 
affected, and there is no configuration to get the old result back.
    
    ### How was this patch tested?
    
    Pass the CIs with a new test case in `ArithmeticExpressionSuite`. It checks 
the `DECIMAL(19, 0)` boundaries `Long.MaxValue` and `Long.MinValue` and one 
past each. `checkEvaluation` and `checkExceptionInExpression` cover the 
interpreted and codegen paths.
    
    Two existing tests pinned the wrapped value in the default ANSI mode, and 
this PR updates them:
    - `SPARK-28322: IntegralDivide supports decimal type` now runs the wrapped 
case in LEGACY mode.
    - The random oracle of `SPARK-45786: Decimal multiply, divide, remainder, 
quot` used `quotExpected.toLong`. It now expects `ARITHMETIC_OVERFLOW` in ANSI 
mode when the exact quotient is outside the long range.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    Closes #60210 from dongjoon-hyun/SPARK-61131.
    
    Authored-by: Dongjoon Hyun <[email protected]>
    Signed-off-by: Dongjoon Hyun <[email protected]>
    
    (cherry picked from commit 5f62e55e668606c2144e49908eb514038f225df9)
    Signed-off-by: Dongjoon Hyun <[email protected]>
---
 .../sql/catalyst/expressions/arithmetic.scala      | 34 +++++++++++++++++++---
 .../expressions/ArithmeticExpressionSuite.scala    | 24 ++++++++++++---
 2 files changed, 50 insertions(+), 8 deletions(-)

diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala
index d0d7507e3250..b63541310b72 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala
@@ -677,7 +677,10 @@ object Multiply {
 // Common base trait for Divide and Remainder, since these two classes are 
almost identical
 trait DivModLike extends BinaryArithmetic {
 
-  protected def decimalToDataTypeCodeGen(decimalResult: String): String = 
decimalResult
+  /** Java code assigning the checked decimal result to `value`. */
+  protected def decimalToDataTypeCodeGen(
+      decimalResult: String, value: String, errorContextCode: String): String =
+    s"$value = $decimalResult;"
 
   // Whether we should check overflow or not in ANSI mode.
   protected def checkDivideOverflow: Boolean = false
@@ -766,14 +769,14 @@ trait DivModLike extends BinaryArithmetic {
              |Decimal $decimalValue = $castUtils.changePrecisionExact(
              |  ${decimalOperation(eval1.value, eval2.value, scale)}, 
$precision, $scale,
              |  $errorContextCode);
-             |${ev.value} = ${decimalToDataTypeCodeGen(s"$decimalValue")};
+             |${decimalToDataTypeCodeGen(decimalValue, ev.value, 
errorContextCode)}
              |""".stripMargin
         } else {
           s"""
              |Decimal $decimalValue = $castUtils.changePrecisionOrNull(
              |  ${decimalOperation(eval1.value, eval2.value, scale)}, 
$precision, $scale);
              |if ($decimalValue != null) {
-             |  ${ev.value} = ${decimalToDataTypeCodeGen(s"$decimalValue")};
+             |  ${decimalToDataTypeCodeGen(decimalValue, ev.value, 
errorContextCode)}
              |} else {
              |  ${ev.isNull} = true;
              |}
@@ -974,7 +977,26 @@ case class IntegralDivide(
 
   override def symbol: String = "/"
   override def decimalMethod: String = "quot"
-  override def decimalToDataTypeCodeGen(decimalResult: String): String = 
s"$decimalResult.toLong()"
+
+  // A decimal quotient that fits the decimal result type can still overflow a 
long when the
+  // type has more digits than a long can always hold.
+  private lazy val checkDecimalToLongOverflow: Boolean = failOnError && 
(super.dataType match {
+    case DecimalType.Fixed(precision, _) => precision > Decimal.MAX_LONG_DIGITS
+    case _ => false
+  })
+
+  override def decimalToDataTypeCodeGen(
+      decimalResult: String, value: String, errorContextCode: String): String 
= {
+    val checkLongOverflow = if (checkDecimalToLongOverflow) {
+      s"""
+         |if ($decimalResult.toJavaBigInteger().bitLength() > 63) {
+         |  throw 
QueryExecutionErrors.overflowInIntegralDivideError($errorContextCode);
+         |}""".stripMargin
+    } else {
+      ""
+    }
+    s"$checkLongOverflow\n$value = $decimalResult.toLong();"
+  }
 
   override def resultDecimalType(p1: Int, s1: Int, p2: Int, s2: Int): 
DecimalType = {
     // This follows division rule
@@ -1007,6 +1029,10 @@ case class IntegralDivide(
       if (res == null) {
         null
       } else {
+        if (checkDecimalToLongOverflow &&
+            res.asInstanceOf[Decimal].toJavaBigInteger.bitLength > 63) {
+          throw 
QueryExecutionErrors.overflowInIntegralDivideError(getContextOrNull())
+        }
         integral.toLong(res)
       }
     }
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ArithmeticExpressionSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ArithmeticExpressionSuite.scala
index ceb5e96971db..bd4a8227d330 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ArithmeticExpressionSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ArithmeticExpressionSuite.scala
@@ -336,8 +336,13 @@ class ArithmeticExpressionSuite extends SparkFunSuite with 
ExpressionEvalHelper
           val quotResult = Decimal(quotExact.setScale(quotType.scale, 
RoundingMode.HALF_UP))
           val quotExpected =
             if (quotResult.precision > DecimalType.MAX_PRECISION) null else 
quotResult
-          checkEvaluationOrException(quotActual,
-            if (quotExpected == null) null else quotExpected.toLong)
+          if (SQLConf.get.ansiEnabled && quotExpected != null &&
+              !BigInt(quotExact.toBigInteger).isValidLong) {
+            checkExceptionInExpression[SparkArithmeticException](quotActual, 
"ARITHMETIC_OVERFLOW")
+          } else {
+            checkEvaluationOrException(quotActual,
+              if (quotExpected == null) null else quotExpected.toLong)
+          }
         }
       }
 
@@ -744,9 +749,10 @@ class ArithmeticExpressionSuite extends SparkFunSuite with 
ExpressionEvalHelper
       checkExceptionInExpression[ArithmeticException](
         IntegralDivide(Literal(Decimal(0.2)), Literal(Decimal(0.0))), 
"Division by zero")
     }
-    // overflows long and so returns a wrong result
+    // overflows long and so returns a wrong result in LEGACY mode
     checkEvaluation(IntegralDivide(
-      Literal(Decimal("99999999999999999999999999999999999")), 
Literal(Decimal(0.001))),
+      Literal(Decimal("99999999999999999999999999999999999")), 
Literal(Decimal(0.001)),
+      EvalMode.LEGACY),
       687399551400672280L)
     // overflow during promote precision
     withSQLConf(SQLConf.ANSI_ENABLED.key -> "false") {
@@ -756,6 +762,16 @@ class ArithmeticExpressionSuite extends SparkFunSuite with 
ExpressionEvalHelper
     }
   }
 
+  test("SPARK-61131: IntegralDivide of decimals fails when the quotient 
overflows long") {
+    val one = Literal(Decimal(1), DecimalType(1, 0))
+    def dividend(v: BigInt): Literal = Literal(Decimal(BigDecimal(v)), 
DecimalType(19, 0))
+    Seq(BigInt(Long.MaxValue), BigInt(Long.MinValue)).foreach { bound =>
+      checkEvaluation(IntegralDivide(dividend(bound), one, EvalMode.ANSI), 
bound.toLong)
+      checkExceptionInExpression[SparkArithmeticException](
+        IntegralDivide(dividend(bound + bound.signum), one, EvalMode.ANSI), 
"ARITHMETIC_OVERFLOW")
+    }
+  }
+
   test("SPARK-61050: decimal Remainder, Pmod and IntegralDivide with a 40- or 
76-digit quotient") {
     val left = Literal(Decimal(BigDecimal("9" * 38)), DecimalType(38, 0))
     Seq(("0.07", 2, "0.02"), ("7E-38", 38, "2E-38")).foreach { case (divisor, 
scale, rem) =>


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to