You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/10/05 21:34:01 UTC

(datafusion-comet) branch gh-readonly-queue/main/pr-6249-4362dcd9f6be408f1db1e6ccaa6e44ca1f35dc44 created (now 6f1c3c2661)

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

github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-6249-4362dcd9f6be408f1db1e6ccaa6e44ca1f35dc44
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git


      at 6f1c3c2661 fix: match Spark ANSI integral overflow errors (#6217) (#6249)

This branch includes the following new commits:

     new 6f1c3c2661 fix: match Spark ANSI integral overflow errors (#6217) (#6249)

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org


(datafusion-comet) 01/01: fix: match Spark ANSI integral overflow errors (#6217) (#6249)

Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-6249-4362dcd9f6be408f1db1e6ccaa6e44ca1f35dc44
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git

commit 6f1c3c2661b6cd42d7ac6617d1c6e1d13fa5e378
Author: LinSimon-901101 <bc...@gm.ntcu.edu.tw>
AuthorDate: Mon Oct 5 17:32:56 2026 +0000

    fix: match Spark ANSI integral overflow errors (#6217) (#6249)
    
    Co-authored-by: Andy Grove <ag...@apache.org>
---
 .../user-guide/latest/compatibility/index.md       |   4 -
 native/common/src/error.rs                         |  38 ++-
 native/spark-expr/src/lib.rs                       |   1 +
 native/spark-expr/src/math_funcs/abs.rs            |   2 +-
 .../src/math_funcs/checked_arithmetic.rs           | 266 ++++++++++++++++++++-
 native/spark-expr/src/math_funcs/negative.rs       |   3 +-
 .../sql/comet/shims/ShimSparkErrorConverter.scala  |   3 +-
 .../sql/comet/shims/ShimSparkErrorConverter.scala  |   3 +-
 .../sql/comet/shims/ShimSparkErrorConverter.scala  |   6 +-
 .../org/apache/comet/CometExpressionSuite.scala    | 117 ++++++++-
 .../apache/comet/SparkErrorConverterSuite.scala    |  32 +++
 11 files changed, 449 insertions(+), 26 deletions(-)

diff --git a/docs/source/user-guide/latest/compatibility/index.md b/docs/source/user-guide/latest/compatibility/index.md
index 017140b14d..a74daf64f7 100644
--- a/docs/source/user-guide/latest/compatibility/index.md
+++ b/docs/source/user-guide/latest/compatibility/index.md
@@ -112,10 +112,6 @@ Code that catches `SparkException` and only asserts on message substrings is una
 inspects the exception class, `getCondition()`, or the parameterised error class will observe
 divergence:
 
-- Byte / Short `Add`, `Subtract`, and `Multiply` overflow raises `ARITHMETIC_OVERFLOW` (for
-  example `byte overflow`) where Spark raises `BINARY_ARITHMETIC_OVERFLOW`, and integral
-  `ARITHMETIC_OVERFLOW` messages omit Spark's `try_` suggestion
-  ([#6217](https://github.com/apache/datafusion-comet/issues/6217)).
 - Spark 4.2 introduced additional ANSI arithmetic overflow behavior differences that Comet does
   not yet track ([#4967](https://github.com/apache/datafusion-comet/issues/4967)).
 
diff --git a/native/common/src/error.rs b/native/common/src/error.rs
index 77716e5414..1346b39806 100644
--- a/native/common/src/error.rs
+++ b/native/common/src/error.rs
@@ -71,8 +71,14 @@ pub enum SparkError {
     #[error("[CANNOT_PARSE_DECIMAL] Cannot parse decimal.")]
     CannotParseDecimal,
 
-    #[error("[ARITHMETIC_OVERFLOW] {from_type} overflow. If necessary set \"spark.sql.ansi.enabled\" to \"false\" to bypass this error.")]
-    ArithmeticOverflow { from_type: String },
+    #[error("[ARITHMETIC_OVERFLOW] {from_type} overflow.{suggestion} If necessary set \"spark.sql.ansi.enabled\" to \"false\" to bypass this error.",
+        suggestion = if function_name.is_empty() { String::new() } else {
+            format!(" Use '{function_name}' to tolerate overflow and return NULL instead.")
+        })]
+    ArithmeticOverflow {
+        from_type: String,
+        function_name: String,
+    },
 
     #[error("[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.")]
     IntegralDivideOverflow,
@@ -440,9 +446,13 @@ impl SparkError {
                     "toType": to_type,
                 })
             }
-            SparkError::ArithmeticOverflow { from_type } => {
+            SparkError::ArithmeticOverflow {
+                from_type,
+                function_name,
+            } => {
                 serde_json::json!({
                     "fromType": from_type,
+                    "functionName": function_name,
                 })
             }
             SparkError::DecimalSumOverflow { function_name } => {
@@ -1020,6 +1030,28 @@ mod tests {
         assert!(json.contains("\"errorClass\":\"REMAINDER_BY_ZERO\""));
     }
 
+    #[test]
+    fn test_arithmetic_overflow_suggestion_json_and_display() {
+        for function in ["", "try_add", "try_subtract", "try_multiply"] {
+            let error = SparkError::ArithmeticOverflow {
+                from_type: "long".to_string(),
+                function_name: function.to_string(),
+            };
+            let parsed: serde_json::Value = serde_json::from_str(&error.to_json()).unwrap();
+            assert_eq!(parsed["errorClass"], "ARITHMETIC_OVERFLOW");
+            assert_eq!(parsed["params"]["fromType"], "long");
+            assert_eq!(parsed["params"]["functionName"], function);
+            let hint = if function.is_empty() {
+                String::new()
+            } else {
+                format!(" Use '{function}' to tolerate overflow and return NULL instead.")
+            };
+            assert_eq!(error.to_string(), format!(
+                "[ARITHMETIC_OVERFLOW] long overflow.{hint} If necessary set \"spark.sql.ansi.enabled\" to \"false\" to bypass this error."
+            ));
+        }
+    }
+
     #[test]
     fn test_binary_overflow_json() {
         let error = SparkError::BinaryArithmeticOverflow {
diff --git a/native/spark-expr/src/lib.rs b/native/spark-expr/src/lib.rs
index 4dec32c725..6d07ce1324 100644
--- a/native/spark-expr/src/lib.rs
+++ b/native/spark-expr/src/lib.rs
@@ -136,6 +136,7 @@ pub enum BinaryOutputStyle {
 pub(crate) fn arithmetic_overflow_error(from_type: &str) -> SparkError {
     SparkError::ArithmeticOverflow {
         from_type: from_type.to_string(),
+        function_name: String::new(),
     }
 }
 
diff --git a/native/spark-expr/src/math_funcs/abs.rs b/native/spark-expr/src/math_funcs/abs.rs
index 7b79a15727..13306b45aa 100644
--- a/native/spark-expr/src/math_funcs/abs.rs
+++ b/native/spark-expr/src/math_funcs/abs.rs
@@ -327,7 +327,7 @@ mod tests {
 
     fn assert_spark_overflow(err: DataFusionError, expected_from_type: &str) {
         if let DataFusionError::External(ref e) = err {
-            if let Some(SparkError::ArithmeticOverflow { from_type }) =
+            if let Some(SparkError::ArithmeticOverflow { from_type, .. }) =
                 e.downcast_ref::<SparkError>()
             {
                 assert_eq!(from_type, expected_from_type);
diff --git a/native/spark-expr/src/math_funcs/checked_arithmetic.rs b/native/spark-expr/src/math_funcs/checked_arithmetic.rs
index 85150ce5ef..d70c062987 100644
--- a/native/spark-expr/src/math_funcs/checked_arithmetic.rs
+++ b/native/spark-expr/src/math_funcs/checked_arithmetic.rs
@@ -41,6 +41,59 @@ enum MathOp {
     Div,
 }
 
+impl MathOp {
+    fn function_name(self) -> &'static str {
+        match self {
+            Self::Add => "try_add",
+            Self::Sub => "try_subtract",
+            Self::Mul => "try_multiply",
+            Self::Div => "try_divide",
+        }
+    }
+}
+
+/// Arrow's error does not carry the failing row. Only after its fast kernel reports an
+/// overflow, recover the first non-null overflowing pair for Spark's Byte/Short error.
+/// Keep scalar broadcasting and array offsets intact; never inspect values beneath NULLs.
+fn binary_overflow_error<T: ArrowPrimitiveType>(
+    left: &dyn Datum,
+    right: &dyn Datum,
+    op: MathOp,
+) -> Option<SparkError>
+where
+    T::Native: std::fmt::Display,
+{
+    let (left, left_scalar) = left.get();
+    let (right, right_scalar) = right.get();
+    let left = left.as_primitive::<T>();
+    let right = right.as_primitive::<T>();
+    let len = if left_scalar { right.len() } else { left.len() };
+    for row in 0..len {
+        let l = if left_scalar { 0 } else { row };
+        let r = if right_scalar { 0 } else { row };
+        if left.is_null(l) || right.is_null(r) {
+            continue;
+        }
+        let l = left.value(l);
+        let r = right.value(r);
+        let (result, symbol) = match op {
+            MathOp::Add => (l.add_checked(r), "+"),
+            MathOp::Sub => (l.sub_checked(r), "-"),
+            MathOp::Mul => (l.mul_checked(r), "*"),
+            MathOp::Div => return None,
+        };
+        if result.is_err() {
+            return Some(SparkError::BinaryArithmeticOverflow {
+                value1: l.to_string(),
+                symbol: symbol.to_string(),
+                value2: r.to_string(),
+                function_name: op.function_name().to_string(),
+            });
+        }
+    }
+    None
+}
+
 fn try_arithmetic_kernel<T>(
     left: &PrimitiveArray<T>,
     right: &PrimitiveArray<T>,
@@ -87,11 +140,35 @@ fn ansi_arithmetic_kernel(
     op: MathOp,
     data_type: &DataType,
 ) -> Result<ColumnarValue, DataFusionError> {
-    let run_kernel = |l: &dyn Datum, r: &dyn Datum| match op {
-        MathOp::Add => numeric::add(l, r),
-        MathOp::Sub => numeric::sub(l, r),
-        MathOp::Mul => numeric::mul(l, r),
-        MathOp::Div => numeric::div(l, r),
+    let from_type = integer_type_name(data_type)?;
+    let run_kernel = |l: &dyn Datum, r: &dyn Datum| {
+        let result = match op {
+            MathOp::Add => numeric::add(l, r),
+            MathOp::Sub => numeric::sub(l, r),
+            MathOp::Mul => numeric::mul(l, r),
+            MathOp::Div => numeric::div(l, r),
+        };
+        result.map_err(|error| match error {
+            ArrowError::DivideByZero => divide_by_zero_error().into(),
+            ArrowError::ArithmeticOverflow(_) => {
+                let binary_error = if op != MathOp::Div {
+                    match data_type {
+                        DataType::Int8 => binary_overflow_error::<Int8Type>(l, r, op),
+                        DataType::Int16 => binary_overflow_error::<Int16Type>(l, r, op),
+                        _ => None,
+                    }
+                } else {
+                    None
+                };
+                DataFusionError::from(binary_error.unwrap_or_else(|| {
+                    SparkError::ArithmeticOverflow {
+                        from_type: from_type.to_string(),
+                        function_name: op.function_name().to_string(),
+                    }
+                }))
+            }
+            _ => error.into(),
+        })
     };
 
     let is_scalars = matches!(
@@ -120,14 +197,7 @@ fn ansi_arithmetic_kernel(
         }
     };
 
-    let from_type = integer_type_name(data_type)?;
-
-    let array = result_array.map_err(|e| match e {
-        ArrowError::DivideByZero => divide_by_zero_error().into(),
-        _ => DataFusionError::from(SparkError::ArithmeticOverflow {
-            from_type: String::from(from_type),
-        }),
-    })?;
+    let array = result_array?;
 
     if is_scalars {
         let scalar_val = ScalarValue::try_from_array(array.as_ref(), 0)?;
@@ -151,6 +221,7 @@ where
             ArrowError::DivideByZero => divide_by_zero_error().into(),
             _ => DataFusionError::from(SparkError::ArithmeticOverflow {
                 from_type: String::from(from_type),
+                function_name: String::new(),
             }),
         })
 }
@@ -512,4 +583,173 @@ mod tests {
             _ => panic!("Expected scalar result"),
         }
     }
+
+    fn overflow_json(error: DataFusionError) -> serde_json::Value {
+        let DataFusionError::External(error) = error else {
+            panic!("Expected structured Spark error, got {error:?}")
+        };
+        let error = error.downcast_ref::<SparkError>().unwrap();
+        serde_json::from_str(&error.to_json()).unwrap()
+    }
+
+    #[test]
+    fn test_ansi_integral_overflow_payloads() {
+        // Both overflow signs and all scalar/array shapes. In particular, subtraction must
+        // preserve operand order when the scalar is on the left.
+        for (data_type, min, max) in [
+            (DataType::Int8, i8::MIN as i64, i8::MAX as i64),
+            (DataType::Int16, i16::MIN as i64, i16::MAX as i64),
+            (DataType::Int32, i32::MIN as i64, i32::MAX as i64),
+            (DataType::Int64, i64::MIN, i64::MAX),
+        ] {
+            let value = |v| match data_type {
+                DataType::Int8 => ScalarValue::Int8(Some(v as i8)),
+                DataType::Int16 => ScalarValue::Int16(Some(v as i16)),
+                DataType::Int32 => ScalarValue::Int32(Some(v as i32)),
+                DataType::Int64 => ScalarValue::Int64(Some(v)),
+                _ => unreachable!(),
+            };
+            for (op, symbol, function, pairs) in [
+                (MathOp::Add, "+", "try_add", [(max, 1), (min, -1)]),
+                (MathOp::Sub, "-", "try_subtract", [(min, 1), (max, -1)]),
+                (MathOp::Mul, "*", "try_multiply", [(max, 2), (min, -1)]),
+            ] {
+                for (l, r) in pairs {
+                    for (left_scalar, right_scalar) in
+                        [(false, false), (true, false), (false, true), (true, true)]
+                    {
+                        let operand = |v: ScalarValue, scalar| {
+                            if scalar {
+                                ColumnarValue::Scalar(v)
+                            } else {
+                                ColumnarValue::Array(v.to_array().unwrap())
+                            }
+                        };
+                        let args = [
+                            operand(value(l), left_scalar),
+                            operand(value(r), right_scalar),
+                        ];
+                        let error = overflow_json(
+                            checked_arithmetic_internal(&args, &data_type, op, EvalMode::Ansi)
+                                .unwrap_err(),
+                        );
+                        let expected = if matches!(data_type, DataType::Int8 | DataType::Int16) {
+                            serde_json::json!({
+                                "value1": l.to_string(), "symbol": symbol,
+                                "value2": r.to_string(), "functionName": function
+                            })
+                        } else {
+                            serde_json::json!({
+                                "fromType": integer_type_name(&data_type).unwrap(),
+                                "functionName": function
+                            })
+                        };
+                        let class = if matches!(data_type, DataType::Int8 | DataType::Int16) {
+                            "BINARY_ARITHMETIC_OVERFLOW"
+                        } else {
+                            "ARITHMETIC_OVERFLOW"
+                        };
+                        assert_eq!(error["errorClass"], class, "{data_type:?} {op:?}");
+                        assert_eq!(error["params"], expected, "{data_type:?} {op:?}");
+                        // TRY must still return a typed NULL for the identical inputs.
+                        let result =
+                            checked_arithmetic_internal(&args, &data_type, op, EvalMode::Try)
+                                .unwrap();
+                        assert_eq!(result.into_array(1).unwrap().null_count(), 1);
+                    }
+                }
+            }
+        }
+    }
+
+    #[test]
+    fn test_ansi_wide_integer_overflow_suggestion() {
+        // A separate regression so the baseline also demonstrates the missing suggestion.
+        let args = int32_args(vec![Some(i32::MAX)], vec![Some(1)]);
+        let error =
+            overflow_json(checked_add(&args, &DataType::Int32, EvalMode::Ansi).unwrap_err());
+        assert_eq!(error["params"]["functionName"], "try_add");
+    }
+
+    #[test]
+    fn test_ansi_small_integer_overflow_skips_nulls_and_respects_slices() {
+        macro_rules! check {
+            ($ty:ty, $native:ty) => {{
+                // Ignore both the row before the slice and overflowing garbage beneath NULLs.
+                let left = PrimitiveArray::<$ty>::new(
+                    vec![<$native>::MAX, <$native>::MAX, 1, <$native>::MAX].into(),
+                    Some(NullBuffer::from(vec![true, false, true, true])),
+                )
+                .slice(1, 3);
+                let right = PrimitiveArray::<$ty>::from_iter_values([1, 1, 2]);
+                let args = [
+                    ColumnarValue::Array(Arc::new(left.clone())),
+                    ColumnarValue::Array(Arc::new(right)),
+                ];
+                let error = overflow_json(
+                    checked_add(&args, left.data_type(), EvalMode::Ansi).unwrap_err(),
+                );
+                assert_eq!(error["params"]["value1"], <$native>::MAX.to_string());
+                assert_eq!(error["params"]["value2"], "2");
+
+                let args = [
+                    ColumnarValue::Array(Arc::new(left.slice(0, 2))),
+                    ColumnarValue::Array(Arc::new(PrimitiveArray::<$ty>::from_iter_values([1, 1]))),
+                ];
+                let result = checked_add(&args, left.data_type(), EvalMode::Ansi)
+                    .unwrap()
+                    .into_array(2)
+                    .unwrap();
+                assert_eq!(
+                    result.as_primitive::<$ty>(),
+                    &PrimitiveArray::<$ty>::from_iter([None, Some(2)])
+                );
+            }};
+        }
+        check!(Int8Type, i8);
+        check!(Int16Type, i16);
+    }
+
+    #[test]
+    fn test_ansi_small_integer_null_and_empty_scalar_broadcasts() {
+        for data_type in [DataType::Int8, DataType::Int16] {
+            let null = ScalarValue::try_from(&data_type).unwrap();
+            let max = if data_type == DataType::Int8 {
+                ScalarValue::Int8(Some(i8::MAX))
+            } else {
+                ScalarValue::Int16(Some(i16::MAX))
+            };
+            for op in [MathOp::Add, MathOp::Sub, MathOp::Mul] {
+                for args in [
+                    [
+                        ColumnarValue::Scalar(null.clone()),
+                        ColumnarValue::Array(max.to_array_of_size(3).unwrap()),
+                    ],
+                    [
+                        ColumnarValue::Array(max.to_array_of_size(3).unwrap()),
+                        ColumnarValue::Scalar(null.clone()),
+                    ],
+                    [
+                        ColumnarValue::Scalar(max.clone()),
+                        ColumnarValue::Array(max.to_array_of_size(0).unwrap()),
+                    ],
+                    [
+                        ColumnarValue::Array(max.to_array_of_size(0).unwrap()),
+                        ColumnarValue::Scalar(max.clone()),
+                    ],
+                    [
+                        ColumnarValue::Scalar(null.clone()),
+                        ColumnarValue::Scalar(max.clone()),
+                    ],
+                ] {
+                    let result =
+                        checked_arithmetic_internal(&args, &data_type, op, EvalMode::Ansi).unwrap();
+                    match result {
+                        ColumnarValue::Array(array) => assert_eq!(array.len(), array.null_count()),
+                        ColumnarValue::Scalar(value) => assert!(value.is_null()),
+                    }
+                }
+            }
+        }
+    }
 }
diff --git a/native/spark-expr/src/math_funcs/negative.rs b/native/spark-expr/src/math_funcs/negative.rs
index a0da6f52fb..0ff06bb00b 100644
--- a/native/spark-expr/src/math_funcs/negative.rs
+++ b/native/spark-expr/src/math_funcs/negative.rs
@@ -209,6 +209,7 @@ impl PhysicalExpr for NegativeExpr {
         {
             return Err(SparkError::ArithmeticOverflow {
                 from_type: "long".to_string(),
+                function_name: String::new(),
             }
             .into());
         }
@@ -260,7 +261,7 @@ mod tests {
 
     fn assert_spark_overflow(err: DataFusionError, expected_from_type: &str) {
         if let DataFusionError::External(ref e) = err {
-            if let Some(SparkError::ArithmeticOverflow { from_type }) =
+            if let Some(SparkError::ArithmeticOverflow { from_type, .. }) =
                 e.downcast_ref::<SparkError>()
             {
                 assert_eq!(from_type, expected_from_type);
diff --git a/spark/src/main/spark-3.4/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala b/spark/src/main/spark-3.4/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
index 001b327956..4fd3606203 100644
--- a/spark/src/main/spark-3.4/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
+++ b/spark/src/main/spark-3.4/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
@@ -93,9 +93,10 @@ trait ShimSparkErrorConverter {
 
       case "ArithmeticOverflow" =>
         val fromType = params("fromType").toString
+        val functionName = params.get("functionName").map(_.toString).getOrElse("")
         Some(
           QueryExecutionErrors
-            .arithmeticOverflowError(fromType + " overflow", "", sqlCtx(context)))
+            .arithmeticOverflowError(fromType + " overflow", functionName, sqlCtx(context)))
 
       case "IntegralDivideOverflow" =>
         Some(QueryExecutionErrors.overflowInIntegralDivideError(sqlCtx(context)))
diff --git a/spark/src/main/spark-3.5/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala b/spark/src/main/spark-3.5/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
index 6658b420bb..39a76f386c 100644
--- a/spark/src/main/spark-3.5/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
+++ b/spark/src/main/spark-3.5/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
@@ -93,9 +93,10 @@ trait ShimSparkErrorConverter {
 
       case "ArithmeticOverflow" =>
         val fromType = params("fromType").toString
+        val functionName = params.get("functionName").map(_.toString).getOrElse("")
         Some(
           QueryExecutionErrors
-            .arithmeticOverflowError(fromType + " overflow", "", sqlCtx(context)))
+            .arithmeticOverflowError(fromType + " overflow", functionName, sqlCtx(context)))
 
       case "IntegralDivideOverflow" =>
         Some(QueryExecutionErrors.overflowInIntegralDivideError(sqlCtx(context)))
diff --git a/spark/src/main/spark-4.x/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala b/spark/src/main/spark-4.x/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
index 70d7a6a313..67a4363870 100644
--- a/spark/src/main/spark-4.x/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
+++ b/spark/src/main/spark-4.x/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
@@ -112,9 +112,13 @@ trait ShimSparkErrorConverter {
 
       case "ArithmeticOverflow" =>
         val fromType = params("fromType").toString
+        val functionName = params.get("functionName").map(_.toString).getOrElse("")
         Some(
           QueryExecutionErrors
-            .arithmeticOverflowError(fromType + " overflow", "", context.headOption.orNull))
+            .arithmeticOverflowError(
+              fromType + " overflow",
+              functionName,
+              context.headOption.orNull))
 
       case "IntegralDivideOverflow" =>
         Some(QueryExecutionErrors.overflowInIntegralDivideError(context.headOption.orNull))
diff --git a/spark/src/test/scala/org/apache/comet/CometExpressionSuite.scala b/spark/src/test/scala/org/apache/comet/CometExpressionSuite.scala
index 04af0d8505..098b8dd387 100644
--- a/spark/src/test/scala/org/apache/comet/CometExpressionSuite.scala
+++ b/spark/src/test/scala/org/apache/comet/CometExpressionSuite.scala
@@ -34,7 +34,7 @@ import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.internal.SQLConf.SESSION_LOCAL_TIMEZONE
 import org.apache.spark.sql.types._
 
-import org.apache.comet.CometSparkSessionExtensions.{isSpark40Plus, isSpark41Plus, isSpark42Plus}
+import org.apache.comet.CometSparkSessionExtensions.{isSpark35Plus, isSpark40Plus, isSpark41Plus, isSpark42Plus}
 import org.apache.comet.testing.{DataGenOptions, FuzzDataGenerator}
 
 class CometExpressionSuite extends CometTestBase with AdaptiveSparkPlanHelper {
@@ -3411,6 +3411,121 @@ class CometExpressionSuite extends CometTestBase with AdaptiveSparkPlanHelper {
     }
   }
 
+  for ((sqlType, min, max, errorClass) <- Seq(
+      ("TINYINT", Byte.MinValue.toLong, Byte.MaxValue.toLong, "BINARY_ARITHMETIC_OVERFLOW"),
+      ("SMALLINT", Short.MinValue.toLong, Short.MaxValue.toLong, "BINARY_ARITHMETIC_OVERFLOW"),
+      ("INT", Int.MinValue.toLong, Int.MaxValue.toLong, "ARITHMETIC_OVERFLOW"),
+      ("BIGINT", Long.MinValue, Long.MaxValue, "ARITHMETIC_OVERFLOW"))) {
+    test(s"ANSI integral overflow fidelity - $sqlType") {
+      val expectedErrorClass =
+        if (errorClass == "BINARY_ARITHMETIC_OVERFLOW" && !isSpark35Plus) {
+          "_LEGACY_ERROR_TEMP_2044"
+        } else {
+          errorClass
+        }
+      val cases = Seq(
+        ("+", "try_add", max, 1L),
+        ("+", "try_add", min, -1L),
+        ("-", "try_subtract", min, 1L),
+        ("-", "try_subtract", max, -1L),
+        ("*", "try_multiply", max, 2L),
+        ("*", "try_multiply", min, -1L))
+      withSQLConf(
+        SQLConf.ANSI_ENABLED.key -> "true",
+        CometConf.COMET_SCALA_UDF_CODEGEN_ENABLED.key -> "false") {
+        // Read operands from Parquet: literal-only arithmetic is folded by Spark before Comet.
+        withParquetTable(
+          cases.zipWithIndex.map { case ((_, _, l, r), id) =>
+            (id, l, r)
+          },
+          "overflow_input") {
+          for (((symbol, function, l, r), id) <- cases.zipWithIndex;
+            (lhs, rhs) <- Seq(("_2", "_3"), (l.toString, "_3"), ("_2", r.toString))) {
+            val query = s"SELECT CAST($lhs AS $sqlType) $symbol CAST($rhs AS $sqlType) " +
+              s"FROM overflow_input WHERE _1 = $id"
+            val df = sql(query)
+            assert(df.schema.head.dataType == DataType.fromDDL(sqlType))
+            checkCometOperators(stripAQEPlan(df.queryExecution.executedPlan))
+            val (sparkError, cometError) = checkSparkAnswerMaybeThrows(df)
+            def structured(error: Option[Throwable]): SparkThrowable with Throwable = {
+              val failure = error.getOrElse(fail(s"Expected overflow: $query"))
+              causeChain(failure)
+                .collect { case e: SparkThrowable with Throwable =>
+                  e
+                }
+                .lastOption
+                .getOrElse(fail(s"Expected SparkThrowable: $failure"))
+            }
+            val expected = structured(sparkError)
+            val actual = structured(cometError)
+            assert(expected.getErrorClass == expectedErrorClass, query)
+            assert(actual.getClass == expected.getClass, query)
+            assert(actual.getErrorClass == expected.getErrorClass, query)
+            assert(actual.getSqlState == expected.getSqlState, query)
+            assert(actual.getMessageParameters == expected.getMessageParameters, query)
+            // Spark 3.x's Byte/Short error has no functionName parameter; the shim must
+            // preserve that version's contract rather than imposing the Spark 4.x message.
+            if (errorClass == "ARITHMETIC_OVERFLOW" || isSpark40Plus) {
+              assert(actual.getMessage.contains(function), query)
+            }
+          }
+        }
+      }
+    }
+  }
+
+  test("ANSI integral overflow fidelity - unary operations have no try suggestion") {
+    withSQLConf(
+      SQLConf.ANSI_ENABLED.key -> "true",
+      CometConf.COMET_SCALA_UDF_CODEGEN_ENABLED.key -> "false") {
+      withParquetTable(Seq((Int.MinValue, Long.MinValue)), "overflow_input") {
+        for (expr <- Seq("abs(_1)", "abs(_2)", "-_1", "-_2")) {
+          val actual =
+            checkSparkError(sql(s"SELECT $expr FROM overflow_input"), "ARITHMETIC_OVERFLOW")
+          assert(!actual.getMessage.contains("try_"))
+        }
+      }
+    }
+  }
+
+  test("ANSI integral overflow fidelity - valid, NULL, TRY and legacy results") {
+    withSQLConf(CometConf.COMET_SCALA_UDF_CODEGEN_ENABLED.key -> "false") {
+      withParquetTable(
+        Seq((Option(1), Option(2)), (None, Option(2)), (Option(1), None)),
+        "overflow_input") {
+        for (sqlType <- Seq("TINYINT", "SMALLINT", "INT", "BIGINT");
+          ansi <- Seq("true", "false")) {
+          withSQLConf(SQLConf.ANSI_ENABLED.key -> ansi) {
+            val l = s"CAST(_1 AS $sqlType)"
+            val r = s"CAST(_2 AS $sqlType)"
+            checkSparkAnswerAndOperator(s"SELECT $l + $r, $l - $r, $l * $r FROM overflow_input")
+          }
+        }
+      }
+      for ((sqlType, max) <- Seq(
+          ("TINYINT", Byte.MaxValue.toLong),
+          ("SMALLINT", Short.MaxValue.toLong),
+          ("INT", Int.MaxValue.toLong),
+          ("BIGINT", Long.MaxValue))) {
+        withParquetTable(Seq((max, 1L)), "overflow_input") {
+          val l = s"CAST(_1 AS $sqlType)"
+          val r = s"CAST(_2 AS $sqlType)"
+          withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+            checkSparkAnswerAndOperator(
+              s"SELECT try_add($l, $r), " +
+                s"try_subtract(-$l, CAST(2 AS $sqlType)), " +
+                s"try_multiply($l, CAST(2 AS $sqlType)) FROM overflow_input")
+          }
+          withSQLConf(SQLConf.ANSI_ENABLED.key -> "false") {
+            checkSparkAnswerAndOperator(
+              s"SELECT $l + $r, " +
+                s"-$l - CAST(2 AS $sqlType), $l * CAST(2 AS $sqlType) FROM overflow_input")
+          }
+        }
+      }
+    }
+  }
+
   test("ANSI support for add") {
     assume(!isSpark42Plus, "https://github.com/apache/datafusion-comet/issues/4967")
     val data = Seq((Integer.MAX_VALUE, 1), (Integer.MIN_VALUE, -1))
diff --git a/spark/src/test/scala/org/apache/comet/SparkErrorConverterSuite.scala b/spark/src/test/scala/org/apache/comet/SparkErrorConverterSuite.scala
index 9d72432043..d8e316c65e 100644
--- a/spark/src/test/scala/org/apache/comet/SparkErrorConverterSuite.scala
+++ b/spark/src/test/scala/org/apache/comet/SparkErrorConverterSuite.scala
@@ -25,6 +25,38 @@ import org.apache.spark.SparkThrowable
 
 class SparkErrorConverterSuite extends AnyFunSuite {
 
+  test("ArithmeticOverflow preserves the suggested function") {
+    for (function <- Seq("try_add", "try_subtract", "try_multiply")) {
+      val error = SparkErrorConverter
+        .convertErrorType(
+          "ArithmeticOverflow",
+          "ARITHMETIC_OVERFLOW",
+          Map("fromType" -> "long", "functionName" -> function),
+          Array.empty,
+          null)
+        .getOrElse(fail("Expected arithmetic overflow"))
+      assert(error.isInstanceOf[ArithmeticException])
+      assert(error.asInstanceOf[SparkThrowable].getErrorClass == "ARITHMETIC_OVERFLOW")
+      assert(
+        error.getMessage.contains(
+          s"Use '$function' to tolerate overflow and return NULL instead."))
+    }
+  }
+
+  test("ArithmeticOverflow without a suggested function remains compatible") {
+    // Accept both older payloads without the key and unary errors with an empty function.
+    for (params <- Seq(
+        Map("fromType" -> "integer"),
+        Map("fromType" -> "integer", "functionName" -> ""))) {
+      val error = SparkErrorConverter
+        .convertErrorType("ArithmeticOverflow", "ARITHMETIC_OVERFLOW", params, Array.empty, null)
+        .getOrElse(fail("Expected arithmetic overflow"))
+      assert(error.asInstanceOf[SparkThrowable].getErrorClass == "ARITHMETIC_OVERFLOW")
+      assert(error.asInstanceOf[SparkThrowable].getMessageParameters.get("alternative") == "")
+      assert(!error.getMessage.contains("try_"))
+    }
+  }
+
   test("CannotReadFile converts to a FAILED_READ_FILE SparkException naming the file") {
     val ex = SparkErrorConverter
       .convertErrorType(


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org