You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "jiangxt2 (via GitHub)" <gi...@apache.org> on 2026/08/16 07:22:39 UTC

[PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

jiangxt2 opened a new pull request, #58029:
URL: https://github.com/apache/spark/pull/58029

   ### What changes were proposed in this pull request?
   
   CAST(decimal AS TIMESTAMP) scales the decimal value by 1,000,000 and truncates the result with BigDecimal.longValue(). When the scaled product exceeds the Long range, longValue() silently drops the high bits and produces an incorrect timestamp that still looks valid. This PR checks the exact BigDecimal product against the closed interval [Long.MinValue, Long.MaxValue] before narrowing, in both the interpreted and whole-stage codegen paths. On overflow, non-ANSI mode returns NULL and ANSI mode raises CAST_OVERFLOW through the existing cast overflow handling. In-range values keep the existing truncation of sub-microsecond fractions. Decimal-to-Timestamp casts are marked nullable through Cast.forceNullable so the plan reflects that the result can be NULL.
   
   ### Why are the changes needed?
   
   The current behavior silently returns incorrect data: for example, CAST(99999999999999999999BD AS TIMESTAMP) previously returned a value that looks like a valid timestamp, so the failure is invisible to users and hard to trace in downstream pipelines.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes. For decimal values whose product with 1,000,000 exceeds the Long range, CAST(decimal AS TIMESTAMP) now returns NULL in non-ANSI mode and raises CAST_OVERFLOW in ANSI mode, instead of silently returning an incorrect timestamp. The behavior change is documented in the "Upgrading from Spark SQL 4.3 to 4.4" section of the SQL migration guide.
   
   ### How was this patch tested?
   
   New test cases were added in CastWithAnsiOffSuite and CastWithAnsiOnSuite covering positive and negative overflow, the exact Long boundaries, boundary-adjacent values with sub-microsecond fractions, and the CAST_OVERFLOW error parameters. TryCastSuite asserts that try_cast(decimal AS TIMESTAMP) is nullable. A new DecimalTimestampCastSuite covers SQL execution with whole-stage codegen enabled and disabled. The 413 targeted Catalyst tests and the SQL core execution tests pass. The Catalyst module full suite passed before the final test additions and was not rerun afterward. The full sql/test module run remains blocked by a timeout in an unmodified SQLQuerySuite test case ("run sql directly on files"), which reproduces when the suite runs alone and does not involve any code changed by this PR.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Codex and Claude AI
   


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5636600043

   > Thank you @jiangxt2 and @stevomitric! Please resolve conflicts to unblock merge
   
   Resolved the conflict with master in 67bafcd0f70.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3995592983


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionSuite.scala:
##########
@@ -376,6 +376,8 @@ class VariantExpressionSuite extends SparkFunSuite with ExpressionEvalHelper {
     testVariantGet("2147483647.999", "$", IntegerType, 2147483647)
     testInvalidVariantGet("9223372036854775808", "$", LongType)
     testVariantGet("-9223372036854775808.0", "$", LongType, -9223372036854775808L)
+    testVariantGet("9223372036854.7758075", "$", TimestampType, Long.MaxValue)
+    testVariantGet("-9223372036854.7758085", "$", TimestampType, Long.MinValue)

Review Comment:
   Variant gained in-range fractional bounds (…7758075 / …7758085) but not an invalid decimal overflow such as 9223372036854.7758085.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5775434945

   @cloud-fan Could you also PTAL at this PR?


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3995590619


##########
sql/core/src/test/scala/org/apache/spark/sql/DecimalTimestampCastSuite.scala:
##########
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import org.apache.spark.SparkArithmeticException
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DecimalType, StructField, StructType}
+
+class DecimalTimestampCastSuite extends QueryTest with SharedSparkSession {
+
+  private val codegenModes = Seq(
+    Seq(
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true",
+      SQLConf.CODEGEN_FACTORY_MODE.key -> "CODEGEN_ONLY"),
+    Seq(
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false",
+      SQLConf.CODEGEN_FACTORY_MODE.key -> "NO_CODEGEN"))
+
+  private def decimalDataFrame(
+      values: Seq[String],
+      dataType: DecimalType = DecimalType(20, 0)): DataFrame = {
+    val rows = values.map(value => Row(new java.math.BigDecimal(value)))
+    val schema = StructType(StructField("value", dataType, nullable = false) :: Nil)
+    spark.createDataFrame(spark.sparkContext.parallelize(rows), schema)
+  }
+
+  test("SPARK-58217: decimal to timestamp overflow in SQL execution") {
+    withTempView("decimal_values") {
+      decimalDataFrame(Seq("99999999999999999999", "-99999999999999999999", "1"))
+        .createOrReplaceTempView("decimal_values")
+
+      codegenModes.foreach { mode =>
+        withSQLConf((Seq(SQLConf.ANSI_ENABLED.key -> "false") ++ mode): _*) {
+          checkAnswer(
+            spark.sql("""
+              SELECT
+                CAST(value AS TIMESTAMP) IS NULL AS is_null,
+                CAST(CAST(value AS TIMESTAMP) AS LONG) AS seconds
+              FROM decimal_values
+            """),
+            Row(true, null) :: Row(true, null) :: Row(false, 1L) :: Nil)
+        }
+      }
+    }
+  }
+
+  test("SPARK-58217: decimal to timestamp overflow in ANSI SQL execution") {
+    withTempView("decimal_values") {
+      decimalDataFrame(Seq("99999999999999999999", "-99999999999999999999"))
+        .createOrReplaceTempView("decimal_values")
+
+      codegenModes.foreach { mode =>
+        withSQLConf((Seq(SQLConf.ANSI_ENABLED.key -> "true") ++ mode): _*) {
+          Seq(
+            "99999999999999999999" -> "99999999999999999999BD",
+            "-99999999999999999999" -> "-99999999999999999999BD").foreach {
+            case (value, formattedValue) =>
+              val exception = intercept[SparkArithmeticException] {
+                spark.sql(s"""
+                  SELECT CAST(value AS TIMESTAMP)
+                  FROM decimal_values
+                  WHERE value = CAST($value AS DECIMAL(20, 0))
+                """).collect()
+              }
+              checkError(
+                exception = exception,
+                condition = "CAST_OVERFLOW",
+                parameters = Map(
+                  "value" -> formattedValue,
+                  "sourceType" -> "\"DECIMAL(20,0)\"",
+                  "targetType" -> "\"TIMESTAMP\"",
+                  "ansiConfig" -> "\"spark.sql.ansi.enabled\""),
+                sqlState = "22003")
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-58217: decimal to timestamp fractional Long boundaries") {
+    withTempView("decimal_boundaries") {
+      decimalDataFrame(
+        Seq(
+          "9223372036854.7758075",
+          "-9223372036854.7758085",
+          "9223372036854.7758080",
+          "-9223372036854.7758090"),
+        DecimalType(20, 7)).createOrReplaceTempView("decimal_boundaries")
+
+      codegenModes.foreach { mode =>
+        withSQLConf((Seq(SQLConf.ANSI_ENABLED.key -> "false") ++ mode): _*) {
+          checkAnswer(
+            spark.sql("""
+              SELECT unix_micros(CAST(value AS TIMESTAMP))
+              FROM decimal_boundaries
+            """),
+            Row(Long.MaxValue) :: Row(Long.MinValue) :: Row(null) :: Row(null) :: Nil)
+        }
+      }
+    }
+  }
+}

Review Comment:
   Let's please also add relevant testing coverage for TRY_CAST as well



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3877474899


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -79,6 +81,15 @@ object DateTimeUtils extends SparkDateTimeUtils {
     }
   }
 
+  /**
+   * Converts seconds stored as a decimal to microseconds since the epoch. Sub-microsecond digits
+   * are truncated towards zero, and an [[ArithmeticException]] is thrown if the truncated result
+   * does not fit in a Long.
+   */
+  def decimalToTimestamp(d: Decimal): Long = {
+    d.toJavaBigDecimal.multiply(microsPerSecondBD).toBigInteger.longValueExact()

Review Comment:
   Thanks for catching this. I updated decimalToTimestamp to special-case zero and short-circuit using the microsecond digit count, so only the 19-digit boundary materializes a BigInteger and extreme scales fail before allocation.
   
   Added DECIMAL(1,-500000000) regression coverage for ANSI, non-ANSI, TRY_CAST, interpreted, and codegen paths; 413 Catalyst tests and 3 SQL tests passed.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3797009135


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -1014,8 +1019,13 @@ case class Cast(
         DateTimeUtils.makeTimestampNTZNanos(currentDate(zoneId), nanos, precision))
   }
 
-  private[this] def decimalToTimestamp(d: Decimal): Long = {
-    (d.toBigDecimal * MICROS_PER_SECOND).longValue
+  private[this] def decimalToTimestamp(d: Decimal): Any = {
+    val result = d.toJavaBigDecimal.multiply(MICROS_PER_SECOND_BD)
+    if (result.compareTo(LONG_MAX_BD) > 0 || result.compareTo(LONG_MIN_BD) < 0) {

Review Comment:
   I changed the conversion order to scale the decimal value to microseconds, truncate toward zero with toBigInteger, and only then call longValueExact() for the range check. As a result, `9223372036854.7758075BD` converts to Long.MaxValue microseconds, and the corresponding negative value converts to Long.MinValue. Only values whose truncated result is actually out of range now return NULL or raise CAST_OVERFLOW. I also added positive and negative boundary tests covering both interpreted and codegen execution.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "stevomitric (via GitHub)" <gi...@apache.org>.
stevomitric commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3795551232


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -1014,8 +1019,13 @@ case class Cast(
         DateTimeUtils.makeTimestampNTZNanos(currentDate(zoneId), nanos, precision))
   }
 
-  private[this] def decimalToTimestamp(d: Decimal): Long = {
-    (d.toBigDecimal * MICROS_PER_SECOND).longValue
+  private[this] def decimalToTimestamp(d: Decimal): Any = {
+    val result = d.toJavaBigDecimal.multiply(MICROS_PER_SECOND_BD)
+    if (result.compareTo(LONG_MAX_BD) > 0 || result.compareTo(LONG_MIN_BD) < 0) {

Review Comment:
   what happens at the boundary, i.e. `CAST(9223372036854.7758075BD AS TIMESTAMP)`? truncation towards zero would produce exactly `Long.MaxValue` but it will throw an exception here



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -684,6 +685,10 @@ case class Cast(
   with ToStringBase
   with SupportQueryContext
   with QueryErrorsBase {
+  private val MICROS_PER_SECOND_BD = java.math.BigDecimal.valueOf(MICROS_PER_SECOND)
+  private val LONG_MAX_BD = java.math.BigDecimal.valueOf(Long.MaxValue)
+  private val LONG_MIN_BD = java.math.BigDecimal.valueOf(Long.MinValue)

Review Comment:
   is this the best place for max/min value constants (not related to the cast class)? I'm surprised these are not defined at some other place already



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5658558519

   > forceNullable(DecimalType, TimestampType) is now true for types that can overflow (DECIMAL(20,0), DECIMAL(13,0), …). That is the right Cast model, but it is a second user-facing change that should be pointed out properly:
   > 
   > * MAP<DECIMAL(20,0), T> → MAP<TIMESTAMP, T> is now rejected (map keys cannot be null).
   > * ARRAY/STRUCT casts into a non-nullable timestamp element/field are now rejected.
   > 
   > Safe types such as DECIMAL(10,0) and DECIMAL(12,0) stay non-nullable and keep those complex casts. The tests cover the map-key case; the migration guide only mentions overflow NULL / CAST_OVERFLOW. A brief sentence on the analysis failure would help, for example, something like:
   > 
   > > Casting a decimal type that can overflow to timestamp is now treated as nullable. Casts into map keys, or into non-nullable array elements / struct fields, that used to analyze successfully may now fail type checking.
   
   Thanks, agreed. I updated the migration guide to document that, for non-ANSI CAST and TRY_CAST, decimal-to-timestamp casts that may overflow are nullable; casts into map keys or non-nullable array elements and struct fields may now fail analysis, while safe decimal types retain the previous behavior. I also added Array/Struct nullability coverage.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5563874245

   > One more important issue that we need to address ^^
   
   All done. ^ ^


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5389987179

   Hi @uros-b, if you have some time, could you please let me know whether it is ready to merge? Thanks!


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5324835439

   > Thank you @stevomitric! Also, @jiangxt2 please re-run the CI.
   
   All checks have passed now. @uros-b Thanks.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "spark-test (via GitHub) via reviews" <re...@spark.apache.org>.
spark-test commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r4480630447


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -79,6 +83,29 @@ object DateTimeUtils extends SparkDateTimeUtils {
     }
   }
 
+  /**
+   * Converts seconds stored as a decimal to microseconds since the epoch. Sub-microsecond digits
+   * are truncated towards zero, and an [[ArithmeticException]] is thrown if the truncated result
+   * does not fit in a Long.
+   */
+  def decimalToTimestamp(d: Decimal): Long = {
+    if (d.isZero) {
+      0L
+    } else {
+      val value = d.toJavaBigDecimal
+      val microsDigits = value.precision().toLong - value.scale().toLong + microsPerSecondDigits
+      if (microsDigits <= 0) {
+        0L
+      } else if (microsDigits < maxLongDigits) {
+        value.multiply(microsPerSecondBD).longValue()
+      } else if (microsDigits > maxLongDigits) {
+        throw new ArithmeticException("overflow")

Review Comment:
   **Nit (P3):** Every overflowing row now pays for a stack-trace-filled exception that each caller immediately discards. Legacy `CAST` catches it to return NULL. `TRY_CAST` evaluates decimal-to-timestamp with ANSI semantics, because `canUseLegacyCastForTryCast` only covers string sources, so it also builds a formatted `CAST_OVERFLOW` exception per row that its try/catch wrapper throws away. The base branch did no exception work on these paths, and the NULL result needs only the digit-count comparison this method already makes. Overflow-heavy inputs, such as epoch microseconds stored as decimal seconds or dirty data under `TRY_CAST`, therefore pay for exception construction on every row with no change in results. In-range rows and ANSI `CAST` are unaffected.
   
   A same-result fix: add `(DecimalType, TimestampType)` to `canUseLegacyCastForTryCast`, so `TRY_CAST` takes the legacy NULL path without the wrapper, and signal overflow here with an exception that skips stack-trace capture, such as `new ArithmeticException("overflow") with scala.util.control.NoStackTrace`. Use it both for more than 19 digits and, after comparing the truncated value against the Long bounds, in the 19-digit band instead of relying on `longValueExact`.
   
   **Verification:**
   - **Behavior:** Overflowing decimals, including the fractional Long boundaries and extreme legacy negative scales, still yield NULL under legacy CAST and TRY_CAST and CAST_OVERFLOW under ANSI CAST, in both interpreted and generated evaluation.
   - **Compatibility:** For overflowing decimal Variant values, including values read through shredded Parquet, variant_get still raises INVALID_VARIANT_CAST and try_variant_get still returns NULL.
   - **Inspection:** Overflow, beyond 19 digits and in the 19-digit band, is signalled without stack-trace construction, and TRY_CAST of DECIMAL to TIMESTAMP evaluates through the legacy path, without the try/catch wrapper or a CAST_OVERFLOW error.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub) via reviews" <re...@spark.apache.org>.
jiangxt2 commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-6675870984

   Thanks for catching the ANSI nullability regression. The fix in `a2f4c51` makes ANSI decimal-to-timestamp `CAST` preserve the input’s nullability. Overflow still raises `CAST_OVERFLOW`. The new `Dataset.to` regression test covers both nullable and non-nullable inputs.
   
   The complex-type restriction is intentional. Non-ANSI `CAST` and `TRY_CAST` can return `NULL` on overflow, so a cast from a decimal type that can overflow is rejected when the target is a timestamp map key or a non-nullable timestamp array element or struct field. The Spark 5.0 migration guide now also explains when this nullability change can prevent a stateful streaming query from restarting from an older checkpoint.
   
   I’ve deferred the per-row exception allocation optimization. All 476 tests in the five targeted Catalyst and SQL suites passed on Java 21.
   


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5441009876

   Left just one more comment, otherwise conversion boundaries, ANSI/non-ANSI/TRY behavior, codegen, and Variant integration look consistent!


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3873401611


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -540,6 +540,18 @@ object Cast extends QueryErrorsBase {
     case _ => false  // overflow
   }
 
+  private def decimalToTimestampMayOverflow(from: DecimalType): Boolean = {
+    val maxUnscaled = java.math.BigInteger.TEN.pow(from.precision)
+      .subtract(java.math.BigInteger.ONE)
+    val scaleDifference = from.scale - 6

Review Comment:
   Thanks for catching this. Fixed in b59dfb1e3ac by using Long arithmetic for the scale difference and short-circuiting based on the decimal digit count before exponentiation. BigInteger.pow is now only used for the 19-digit boundary case, and I added regression coverage for scale -2147483642.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r4001999989


##########
sql/core/src/test/scala/org/apache/spark/sql/DecimalTimestampCastSuite.scala:
##########
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import org.apache.spark.SparkArithmeticException
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DecimalType, StructField, StructType}
+
+class DecimalTimestampCastSuite extends QueryTest with SharedSparkSession {
+
+  private val codegenModes = Seq(
+    Seq(
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true",
+      SQLConf.CODEGEN_FACTORY_MODE.key -> "CODEGEN_ONLY"),
+    Seq(
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false",
+      SQLConf.CODEGEN_FACTORY_MODE.key -> "NO_CODEGEN"))
+
+  private def decimalDataFrame(
+      values: Seq[String],
+      dataType: DecimalType = DecimalType(20, 0)): DataFrame = {
+    val rows = values.map(value => Row(new java.math.BigDecimal(value)))
+    val schema = StructType(StructField("value", dataType, nullable = false) :: Nil)
+    spark.createDataFrame(spark.sparkContext.parallelize(rows), schema)
+  }
+
+  test("SPARK-58217: decimal to timestamp overflow in SQL execution") {
+    withTempView("decimal_values") {
+      decimalDataFrame(Seq("99999999999999999999", "-99999999999999999999", "1"))
+        .createOrReplaceTempView("decimal_values")
+
+      codegenModes.foreach { mode =>
+        withSQLConf((Seq(SQLConf.ANSI_ENABLED.key -> "false") ++ mode): _*) {
+          checkAnswer(
+            spark.sql("""
+              SELECT
+                CAST(value AS TIMESTAMP) IS NULL AS is_null,
+                CAST(CAST(value AS TIMESTAMP) AS LONG) AS seconds
+              FROM decimal_values
+            """),
+            Row(true, null) :: Row(true, null) :: Row(false, 1L) :: Nil)
+        }
+      }
+    }
+  }
+
+  test("SPARK-58217: decimal to timestamp overflow in ANSI SQL execution") {
+    withTempView("decimal_values") {
+      decimalDataFrame(Seq("99999999999999999999", "-99999999999999999999"))
+        .createOrReplaceTempView("decimal_values")
+
+      codegenModes.foreach { mode =>
+        withSQLConf((Seq(SQLConf.ANSI_ENABLED.key -> "true") ++ mode): _*) {
+          Seq(
+            "99999999999999999999" -> "99999999999999999999BD",
+            "-99999999999999999999" -> "-99999999999999999999BD").foreach {
+            case (value, formattedValue) =>
+              val exception = intercept[SparkArithmeticException] {
+                spark.sql(s"""
+                  SELECT CAST(value AS TIMESTAMP)
+                  FROM decimal_values
+                  WHERE value = CAST($value AS DECIMAL(20, 0))
+                """).collect()
+              }
+              checkError(
+                exception = exception,
+                condition = "CAST_OVERFLOW",
+                parameters = Map(
+                  "value" -> formattedValue,
+                  "sourceType" -> "\"DECIMAL(20,0)\"",
+                  "targetType" -> "\"TIMESTAMP\"",
+                  "ansiConfig" -> "\"spark.sql.ansi.enabled\""),
+                sqlState = "22003")
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-58217: decimal to timestamp fractional Long boundaries") {
+    withTempView("decimal_boundaries") {
+      decimalDataFrame(
+        Seq(
+          "9223372036854.7758075",
+          "-9223372036854.7758085",
+          "9223372036854.7758080",
+          "-9223372036854.7758090"),
+        DecimalType(20, 7)).createOrReplaceTempView("decimal_boundaries")
+
+      codegenModes.foreach { mode =>
+        withSQLConf((Seq(SQLConf.ANSI_ENABLED.key -> "false") ++ mode): _*) {
+          checkAnswer(
+            spark.sql("""
+              SELECT unix_micros(CAST(value AS TIMESTAMP))
+              FROM decimal_boundaries
+            """),
+            Row(Long.MaxValue) :: Row(Long.MinValue) :: Row(null) :: Row(null) :: Nil)
+        }
+      }
+    }
+  }
+}

Review Comment:
   Added SQL-level TRY_CAST coverage in DecimalTimestampCastSuite, including valid fractional boundaries and positive/negative post-truncation overflow under CODEGEN_ONLY and NO_CODEGEN. The existing TryCastSuite continues to cover expression-level behavior.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionSuite.scala:
##########
@@ -376,6 +376,8 @@ class VariantExpressionSuite extends SparkFunSuite with ExpressionEvalHelper {
     testVariantGet("2147483647.999", "$", IntegerType, 2147483647)
     testInvalidVariantGet("9223372036854775808", "$", LongType)
     testVariantGet("-9223372036854775808.0", "$", LongType, -9223372036854775808L)
+    testVariantGet("9223372036854.7758075", "$", TimestampType, Long.MaxValue)
+    testVariantGet("-9223372036854.7758085", "$", TimestampType, Long.MinValue)

Review Comment:
   Added positive and negative invalid fractional-overflow cases to VariantExpressionSuite. The test verifies that variant_get raises INVALID_VARIANT_CAST and try_variant_get returns NULL.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5306723700

   cc @stevomitric @MaxGekk 


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3797025944


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -684,6 +685,10 @@ case class Cast(
   with ToStringBase
   with SupportQueryContext
   with QueryErrorsBase {
+  private val MICROS_PER_SECOND_BD = java.math.BigDecimal.valueOf(MICROS_PER_SECOND)
+  private val LONG_MAX_BD = java.math.BigDecimal.valueOf(Long.MaxValue)
+  private val LONG_MIN_BD = java.math.BigDecimal.valueOf(Long.MinValue)

Review Comment:
   I had checked for an existing shared definition for these BigDecimal boundary constants before adding them, but could not find one, so I intentionally kept them local to Cast at first. To address the placement concern, I removed the need for boundary constants altogether: the shared decimal-to-timestamp arithmetic is now centralized in DateTimeUtils.decimalToTimestamp, which scales the value to microseconds, truncates toward zero with toBigInteger, and performs an exact Long conversion with longValueExact(). Both the interpreted and codegen Cast paths, as well as VariantGet, use this helper, so no Cast-specific boundary constants remain.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5324740186

   Thank you @stevomitric! Also, @jiangxt2 please re-run the CI.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3872967106


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -540,6 +540,18 @@ object Cast extends QueryErrorsBase {
     case _ => false  // overflow
   }
 
+  private def decimalToTimestampMayOverflow(from: DecimalType): Boolean = {
+    val maxUnscaled = java.math.BigInteger.TEN.pow(from.precision)
+      .subtract(java.math.BigInteger.ONE)
+    val scaleDifference = from.scale - 6

Review Comment:
   negative decimal scales are unbounded under the legacy configuration. Integer arithmetic can overflow before BigInteger.pow; for example, scale -2147483642 causes a negative exponent and fails during nullability analysis. Extreme scales can also trigger huge allocations. Use Long arithmetic and short-circuit based on digit count before exponentiation.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "jiangxt2 (via GitHub)" <gi...@apache.org>.
jiangxt2 commented on PR #58029:
URL: https://github.com/apache/spark/pull/58029#issuecomment-5441691261

   > Left just one more comment, otherwise conversion boundaries, ANSI/non-ANSI/TRY behavior, codegen, and Variant integration look consistent!
   
   Thanks. Fixed and pushed in b59dfb1e3ac.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3876514786


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -79,6 +81,15 @@ object DateTimeUtils extends SparkDateTimeUtils {
     }
   }
 
+  /**
+   * Converts seconds stored as a decimal to microseconds since the epoch. Sub-microsecond digits
+   * are truncated towards zero, and an [[ArithmeticException]] is thrown if the truncated result
+   * does not fit in a Long.
+   */
+  def decimalToTimestamp(d: Decimal): Long = {
+    d.toJavaBigDecimal.multiply(microsPerSecondBD).toBigInteger.longValueExact()

Review Comment:
   Not sure what would be the best way to handle this, but seems like we could short-circuit using digit count before constructing powers of ten, special-case zero, and materialize only the 19-digit boundary case. Something like:
   
   ```
   if (d.isZero) {
     0L
   } else {
     val value = d.toJavaBigDecimal
     val microsDigits = value.precision.toLong - value.scale.toLong + 6L
   
     if (microsDigits <= 0) 0L
     else if (microsDigits < 19) value.multiply(microsPerSecondBD).longValue()
     else if (microsDigits > 19) throw new ArithmeticException("overflow")
     else value.multiply(microsPerSecondBD).toBigInteger.longValueExact()
   }
   ```
   
   The Cast handlers only catch ArithmeticException, so all cast modes can fail instead of returning NULL/CAST_OVERFLOW.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58217][SQL] Fix silent garbage timestamps on decimal-to-timestamp overflow [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #58029:
URL: https://github.com/apache/spark/pull/58029#discussion_r3876503465


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -79,6 +81,15 @@ object DateTimeUtils extends SparkDateTimeUtils {
     }
   }
 
+  /**
+   * Converts seconds stored as a decimal to microseconds since the epoch. Sub-microsecond digits
+   * are truncated towards zero, and an [[ArithmeticException]] is thrown if the truncated result
+   * does not fit in a Long.
+   */
+  def decimalToTimestamp(d: Decimal): Long = {
+    d.toJavaBigDecimal.multiply(microsPerSecondBD).toBigInteger.longValueExact()

Review Comment:
   decimalToTimestamp calls toBigInteger before checking overflow...



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -79,6 +81,15 @@ object DateTimeUtils extends SparkDateTimeUtils {
     }
   }
 
+  /**
+   * Converts seconds stored as a decimal to microseconds since the epoch. Sub-microsecond digits
+   * are truncated towards zero, and an [[ArithmeticException]] is thrown if the truncated result
+   * does not fit in a Long.
+   */
+  def decimalToTimestamp(d: Decimal): Long = {
+    d.toJavaBigDecimal.multiply(microsPerSecondBD).toBigInteger.longValueExact()

Review Comment:
   A valid legacy DECIMAL(1,-500000000) can materialize roughly 200 MB per conversion and OOM the executor.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org