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

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


The following commit(s) were added to refs/heads/master by this push:
     new 23832a97b42a [SPARK-61552][SQL] Fix codegen failing on a foldable 
argument that no row evaluates
23832a97b42a is described below

commit 23832a97b42a6c3f7d226e648369e190fb01179f
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Thu Nov 12 12:58:19 2026 -0800

    [SPARK-61552][SQL] Fix codegen failing on a foldable argument that no row 
evaluates
    
    ### What changes were proposed in this pull request?
    
    This PR aims to fix the code generation of the following expressions so 
that a foldable argument that fails to evaluate raises its error only when a 
row evaluates it, as the interpreted path does.
    
    | Expression | SQL functions | Argument |
    |---|---|---|
    | `Like`, `RLike` | `LIKE`, `ILIKE`, `RLIKE` | pattern |
    | `TimestampFormatterHelper.formatterOption` | `date_format`, 
`from_unixtime`, `to_timestamp`, `try_to_timestamp`, `to_timestamp_ntz`, 
`to_date`, `unix_timestamp`, `to_unix_timestamp` | format |
    | `DateFormatClass.timeFormatterOption` | `date_format` over `TIME` | 
format |
    | `NextDay` | `next_day` | day of week |
    | `FromUTCTimestamp`, `ToUTCTimestamp` | `from_utc_timestamp`, 
`to_utc_timestamp` | time zone |
    | `TruncDate`, `TruncTimestamp` | `trunc`, `date_trunc` | format |
    | `GetJsonObject` | `get_json_object` | path |
    | `ArrayInsert` | `array_insert` | position |
    
    A new helper, `ExprUtils.tryEvalFoldable`, returns the value of a foldable 
expression, or `None` if the expression is not foldable or fails to evaluate. 
On `None`, these expressions use their existing code path for a non-foldable 
argument, which evaluates the argument for each row. 
`StringRegexExpression._expensivePattern` already catches `NonFatal` for the 
same kind of argument.
    
    The interpreted path keeps its behavior: `Like` and `RLike` compile a 
foldable pattern lazily, `eval` reads `formatterOption`, `timeFormatterOption` 
and `positivePos` only after it evaluated the argument for the row, and 
`TruncInstant` checks the helper only in `codeGenHelper`.
    
    ### Why are the changes needed?
    
    Since SPARK-39106 (Apache Spark 3.3.0), `ConstantFolding` keeps a foldable 
expression that fails to evaluate in a conditional branch instead of failing 
the query, because no row may reach that branch. However, the above expressions 
evaluate such a foldable argument while generating code. 
`WholeStageCodegenExec` generates the code outside of its fallback for 
compilation errors, so the query fails even if no row takes the branch.
    
    ```sql
    SET spark.sql.ansi.enabled=true;
    CREATE OR REPLACE TEMPORARY VIEW o AS SELECT id AS k FROM range(1, 3);
    
    -- It should return [1,true] and [2,true], but fails with DIVIDE_BY_ZERO.
    SELECT k, IF(k > 0, true, 'x' RLIKE CAST(10 / 0 AS STRING)) FROM o;
    
    -- It should return [1,NULL] and [2,NULL], but fails with DIVIDE_BY_ZERO.
    SELECT k, IF(k > 0, NULL, date_format(timestamp_seconds(k), CAST(10 / 0 AS 
STRING))) FROM o;
    ```
    
    ```
    [DIVIDE_BY_ZERO] Division by zero. Use `try_divide` to tolerate divisor 
being 0 and return NULL instead. If necessary set "spark.sql.ansi.enabled" to 
"false" to bypass this error. SQLSTATE: 22012
    ```
    
    The other functions fail in the same way. With 
`spark.sql.codegen.wholeStage=false`, the queries return the rows, but the 
projection falls back to the interpreter and logs `Expr codegen error and 
falling back to interpreter mode` for each partition. I checked this with 
[v4.0.5 (2026-10-21)](https://github.com/apache/spark/releases/tag/v4.0.5) and 
[v4.3.0 (2026-10-27)](https://github.com/apache/spark/releases/tag/v4.3.0).
    
    `round` and `bround` are not changed here, because their scale must be 
foldable and the result type of a `DECIMAL` input depends on its value, so 
there is no code path that evaluates the scale for each row. The variant path 
functions, e.g. `variant_get`, are not changed either, because their `eval` 
evaluates a foldable path before the null check on purpose and needs a separate 
decision.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A query no longer fails when a conditional branch that no row reaches 
has one of the above functions with a foldable argument that fails to evaluate. 
A row that reaches the function still fails with the same error.
    
    ### How was this patch tested?
    
    Pass the CIs with the newly added test cases in `RegexpExpressionsSuite`, 
`DateExpressionsSuite`, `JsonExpressionsSuite` and 
`CollectionExpressionsSuite`. Without this fix, each of them fails with 
`DIVIDE_BY_ZERO` during code generation.
    
    In addition, I verified manually on Apache Spark 4.3.0 with this patch, 
using `IF(k > 0, ..., <function>)` and `IF(k > 1, ..., <function>)` for the SQL 
functions in the table above except `date_format` over `TIME`, in both 
`spark.sql.codegen.wholeStage` modes: the first returns the rows and the second 
fails with `DIVIDE_BY_ZERO`.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    Closes #60394 from dongjoon-hyun/SPARK-61552.
    
    Authored-by: Dongjoon Hyun <[email protected]>
    Signed-off-by: Dongjoon Hyun <[email protected]>
    
    
    skip-checks: true
---
 .../spark/sql/catalyst/expressions/ExprUtils.scala | 19 ++++++++++++++++++
 .../expressions/collectionOperations.scala         | 12 +++--------
 .../catalyst/expressions/datetimeExpressions.scala | 23 ++++++++++++----------
 .../sql/catalyst/expressions/jsonExpressions.scala |  8 ++++----
 .../catalyst/expressions/regexpExpressions.scala   | 10 ++++++----
 .../expressions/CollectionExpressionsSuite.scala   | 13 ++++++++++++
 .../expressions/DateExpressionsSuite.scala         | 21 ++++++++++++++++++++
 .../expressions/JsonExpressionsSuite.scala         | 12 +++++++++++
 .../expressions/RegexpExpressionsSuite.scala       | 14 +++++++++++++
 9 files changed, 105 insertions(+), 27 deletions(-)

diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
index 0f4d617408cf..66376352ceed 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
@@ -20,6 +20,8 @@ package org.apache.spark.sql.catalyst.expressions
 import java.text.{DecimalFormat, DecimalFormatSymbols, ParsePosition}
 import java.util.Locale
 
+import scala.util.control.NonFatal
+
 import org.apache.spark.sql.catalyst.analysis._
 import org.apache.spark.sql.catalyst.analysis.TypeCheckResult
 import 
org.apache.spark.sql.catalyst.analysis.TypeCheckResult.{DataTypeMismatch, 
TypeCheckSuccess}
@@ -95,6 +97,23 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
       throw QueryCompilationErrors.nonMapFunctionNotAllowedError()
   }
 
+  /**
+   * Returns the value, possibly null, of a foldable expression, or None if 
the expression is not
+   * foldable or fails to evaluate. `ConstantFolding` keeps a foldable 
expression that fails to
+   * evaluate in a conditional branch, which no row may reach. An expression 
that uses the value
+   * of such a child once, e.g. in generated code, should evaluate the child 
for each row instead,
+   * so that the error is raised only when a row evaluates it, as in `eval`.
+   */
+  def tryEvalFoldable(exp: Expression): Option[Any] = if (exp.foldable) {
+    try {
+      Some(exp.eval())
+    } catch {
+      case NonFatal(_) => None
+    }
+  } else {
+    None
+  }
+
   /**
    * A convenient function for schema validation in datasources supporting
    * `columnNameOfCorruptRecord` as an option.
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala
index 71d9401d63ee..02c7ee82a062 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala
@@ -5632,15 +5632,9 @@ case class ArrayInsert(
     }
   }
 
-  private lazy val positivePos = if (second.foldable) {
-    val pos = second.eval().asInstanceOf[Int]
-    if (pos > 0) {
-      Some(pos)
-    } else {
-      None
-    }
-  } else {
-    None
+  private lazy val positivePos = ExprUtils.tryEvalFoldable(second) match {
+    case Some(pos: Int) if pos > 0 => Some(pos)
+    case _ => None
   }
 
   override def eval(input: InternalRow): Any = {
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/datetimeExpressions.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/datetimeExpressions.scala
index 820ddac873c5..654458ee5894 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/datetimeExpressions.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/datetimeExpressions.scala
@@ -93,9 +93,8 @@ trait TimestampFormatterHelper extends 
TimeZoneAwareExpression {
   protected def forTimestampNTZ: Boolean = false
 
   @transient final protected lazy val formatterOption: 
Option[TimestampFormatter] =
-    if (formatString.foldable) {
-      Option(formatString.eval()).map(fmt => getFormatter(fmt.toString))
-    } else None
+    ExprUtils.tryEvalFoldable(formatString).flatMap(Option(_))
+      .map(fmt => getFormatter(fmt.toString))
 
   final protected def getFormatter(fmt: String): TimestampFormatter = {
     TimestampFormatter(
@@ -1693,8 +1692,9 @@ case class DateFormatClass(left: Expression, right: 
Expression, timeZoneId: Opti
   }
 
   @transient private lazy val timeFormatterOption: Option[TimeFormatter] =
-    if (left.dataType.isInstanceOf[TimeType] && right.foldable) {
-      Option(right.eval()).map(fmt => TimeFormatter(fmt.toString, isParsing = 
false))
+    if (left.dataType.isInstanceOf[TimeType]) {
+      ExprUtils.tryEvalFoldable(right).flatMap(Option(_))
+        .map(fmt => TimeFormatter(fmt.toString, isParsing = false))
     } else None
 
   override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
@@ -2681,8 +2681,9 @@ case class NextDay(
   override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): 
ExprCode = {
     nullSafeCodeGen(ctx, ev, (sd, dowS) => {
       val dayOfWeekTerm = ctx.freshName("dayOfWeek")
-      if (dayOfWeek.foldable) {
-        val input = dayOfWeek.eval().asInstanceOf[UTF8String]
+      val foldableDayOfWeek = ExprUtils.tryEvalFoldable(dayOfWeek)
+      if (foldableDayOfWeek.isDefined) {
+        val input = foldableDayOfWeek.get.asInstanceOf[UTF8String]
         if (input eq null) {
           s"""${ev.isNull} = true;"""
         } else {
@@ -2946,8 +2947,9 @@ sealed trait UTCTimestamp extends BinaryExpression with 
ImplicitCastInputTypes {
     val tnv = classOf[TimestampNanosVal].getName
     val javaType = CodeGenerator.javaType(dataType)
     val defaultValue = CodeGenerator.defaultValue(dataType)
-    if (right.foldable) {
-      val tz = right.eval().asInstanceOf[UTF8String]
+    val foldableTz = ExprUtils.tryEvalFoldable(right)
+    if (foldableTz.isDefined) {
+      val tz = foldableTz.get.asInstanceOf[UTF8String]
       if (tz == null) {
         ev.copy(code = code"""
            |boolean ${ev.isNull} = true;
@@ -3553,7 +3555,8 @@ trait TruncInstant extends BinaryExpression with 
ImplicitCastInputTypes {
     val dtu = DateTimeUtils.getClass.getName.stripSuffix("$")
 
     val javaType = CodeGenerator.javaType(dataType)
-    if (format.foldable) {
+    // `truncLevel` evaluates the format, so use it only if the format 
evaluates without an error.
+    if (ExprUtils.tryEvalFoldable(format).isDefined) {
       if (truncLevel < minLevel) {
         ev.copy(code = code"""
           boolean ${ev.isNull} = true;
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala
index cec67b808936..6d04e45baec3 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala
@@ -101,9 +101,9 @@ case class GetJsonObject(json: Expression, path: Expression)
 
   protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
     val evaluatorClass = classOf[GetJsonObjectEvaluator].getName
-    val initEvaluator = path.foldable match {
-      case true if path.eval() != null =>
-        val cachedPath = path.eval().asInstanceOf[UTF8String]
+    val foldablePath = ExprUtils.tryEvalFoldable(path)
+    val initEvaluator = foldablePath match {
+      case Some(cachedPath) if cachedPath != null =>
         val refCachedPath = ctx.addReferenceObj("cachedPath", cachedPath)
         s"new $evaluatorClass($refCachedPath)"
       case _ => s"new $evaluatorClass()"
@@ -122,7 +122,7 @@ case class GetJsonObject(json: Expression, path: Expression)
          |  $evaluator.setJson(${jsonEval.value});
          |}
          |""".stripMargin
-    val setPath = if (!path.foldable) {
+    val setPath = if (foldablePath.isEmpty) {
       s"""
          |if (${pathEval.isNull}) {
          |  $evaluator.setPath(null);
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala
index 7d3d9249886a..e6dbac47bc39 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala
@@ -402,8 +402,9 @@ case class Like(left: Expression, right: Expression, 
escapeChar: Char)
     val patternClass = classOf[Pattern].getName
     val escapeFunc = StringUtils.getClass.getName.stripSuffix("$") + 
".escapeLikeRegex"
 
-    if (right.foldable) {
-      val rVal = right.eval()
+    val foldablePattern = ExprUtils.tryEvalFoldable(right)
+    if (foldablePattern.isDefined) {
+      val rVal = foldablePattern.get
       if (rVal != null) {
         val regexStr =
           
StringEscapeUtils.escapeJava(escape(rVal.asInstanceOf[UTF8String].toString()))
@@ -746,8 +747,9 @@ case class RLike(left: Expression, right: Expression) 
extends StringRegexExpress
   override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): 
ExprCode = {
     val patternClass = classOf[Pattern].getName
 
-    if (right.foldable) {
-      val rVal = right.eval()
+    val foldablePattern = ExprUtils.tryEvalFoldable(right)
+    if (foldablePattern.isDefined) {
+      val rVal = foldablePattern.get
       if (rVal != null) {
         val regexStr =
           
StringEscapeUtils.escapeJava(rVal.asInstanceOf[UTF8String].toString())
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CollectionExpressionsSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CollectionExpressionsSuite.scala
index c6940ea4363f..3c06747a8a6b 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CollectionExpressionsSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CollectionExpressionsSuite.scala
@@ -3738,4 +3738,17 @@ class CollectionExpressionsSuite
       checkEvaluation(ElementAt(a, Literal(Int.MinValue), None, failOnError = 
false), null)
     }
   }
+
+  test("SPARK-61552: array_insert with a foldable position that fails to 
evaluate") {
+    // `ConstantFolding` leaves such a position in a conditional branch. Only 
a row that evaluates
+    // the position should fail, also in generated code.
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      val arr = BoundReference(0, ArrayType(IntegerType), nullable = true)
+      val pos = Cast(Divide(Literal(1.0), Literal(0.0)), IntegerType)
+      val e = ArrayInsert(arr, pos, Literal(1), legacyNegativeIndex = false)
+      val expr = If(IsNull(arr), Literal.create(null, e.dataType), e)
+      checkEvaluation(expr, null, create_row(null))
+      checkExceptionInExpression[ArithmeticException](expr, 
create_row(Seq(2)), "DIVIDE_BY_ZERO")
+    }
+  }
 }
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/DateExpressionsSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/DateExpressionsSuite.scala
index bbc9ffe295c1..dfc587f1338a 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/DateExpressionsSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/DateExpressionsSuite.scala
@@ -4213,4 +4213,25 @@ class DateExpressionsSuite extends SparkFunSuite with 
ExpressionEvalHelper {
         "actualNum" -> "2",
         "docroot" -> SPARK_DOC_ROOT))
   }
+
+  test("SPARK-61552: datetime functions with a foldable argument that fails to 
evaluate") {
+    // `ConstantFolding` leaves such an argument in a conditional branch. Only 
a row that
+    // evaluates the argument should fail, also in generated code.
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      val str = Cast(Divide(Literal(1.0), Literal(0.0)), StringType)
+      val date = BoundReference(0, DateType, nullable = true)
+      val ts = BoundReference(0, TimestampType, nullable = true)
+      val time = BoundReference(0, TimeType(TimeType.DEFAULT_PRECISION), 
nullable = true)
+      Seq(
+        (date, NextDay(date, str), 0),
+        (ts, FromUTCTimestamp(ts, str), 0L),
+        (date, TruncDate(date, str), 0),
+        (ts, DateFormatClass(ts, str, UTC_OPT), 0L),
+        (time, DateFormatClass(time, str, UTC_OPT), 0L)).foreach { case 
(input, e, value) =>
+        val expr = If(IsNull(input), Literal.create(null, e.dataType), e)
+        checkEvaluation(expr, null, create_row(null))
+        checkExceptionInExpression[ArithmeticException](expr, 
create_row(value), "DIVIDE_BY_ZERO")
+      }
+    }
+  }
 }
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/JsonExpressionsSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/JsonExpressionsSuite.scala
index 814df0658648..df2eda63daf7 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/JsonExpressionsSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/JsonExpressionsSuite.scala
@@ -1138,4 +1138,16 @@ class JsonExpressionsSuite extends SparkFunSuite with 
ExpressionEvalHelper {
         StructType(StructField("f", FileType.external) :: Nil))
     }
   }
+
+  test("SPARK-61552: get_json_object with a foldable path that fails to 
evaluate") {
+    // `ConstantFolding` leaves such a path in a conditional branch. Only a 
row that evaluates
+    // the path should fail, also in generated code.
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      val json = BoundReference(0, StringType, nullable = true)
+      val path = Cast(Divide(Literal(1.0), Literal(0.0)), StringType)
+      val expr = If(IsNull(json), Literal.create(null, StringType), 
GetJsonObject(json, path))
+      checkEvaluation(expr, null, create_row(null))
+      checkExceptionInExpression[ArithmeticException](expr, create_row("{}"), 
"DIVIDE_BY_ZERO")
+    }
+  }
 }
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/RegexpExpressionsSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/RegexpExpressionsSuite.scala
index 0ba9fadd4bba..3bd468caec21 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/RegexpExpressionsSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/RegexpExpressionsSuite.scala
@@ -812,4 +812,18 @@ class RegexpExpressionsSuite extends SparkFunSuite with 
ExpressionEvalHelper {
     assert(RLike(udf, Literal("^1")).expensive)
     assert(Like(udf, Literal("1_"), '\\').expensive)
   }
+
+  test("SPARK-61552: LIKE and RLIKE with a foldable pattern that fails to 
evaluate") {
+    // `ConstantFolding` leaves such a pattern in a conditional branch. Only a 
row that evaluates
+    // the pattern should fail, also in generated code.
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      val str = $"s".string.at(0)
+      val pattern = Cast(Divide(Literal(1.0), Literal(0.0)), StringType)
+      Seq(Like(str, pattern, '\\'), RLike(str, pattern)).foreach { e =>
+        val expr = If(IsNull(str), Literal(true), e)
+        checkEvaluation(expr, true, create_row(null))
+        checkExceptionInExpression[ArithmeticException](expr, create_row("x"), 
"DIVIDE_BY_ZERO")
+      }
+    }
+  }
 }


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

Reply via email to