sarutak commented on code in PR #60119:
URL: https://github.com/apache/spark/pull/60119#discussion_r4503859606


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,13 +295,63 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
     e.deterministic && !e.containsPattern(PLAN_EXPRESSION) &&
       canEvaluateUnconditionallyInternal(e)
 
+  // Only the numeric pairs are taken from `Cast.canUpCast`, which also covers 
e.g. DATE to
+  // TIMESTAMP, which can overflow, and casts between complex types. Among the 
numeric ones, it
+  // only takes a decimal to an integral type whose values all fit.
+  private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from, 
to) match {
+    case (_: NumericType, _: NumericType) => Cast.canUpCast(from, to)
+    case _ => false
+  }
+
+  // Whether a cast can not fail. A cast of a date to a timestamp is left out 
also in LEGACY mode,
+  // as converting a date far from the epoch to microseconds overflows there.
+  private def cannotFailCast(c: Cast): Boolean = (c.child.dataType, 
c.dataType) match {
+    case (from, to) if isNumericUpCast(from, to) => true
+    case (TimestampType | TimestampNTZType, DateType) => true
+    // A CHAR or VARCHAR target checks the length of the string.
+    case (_: NumericType | BooleanType, s: StringType) if 
StringHelper.isPlainString(s) => true
+    case _ if c.evalMode == EvalMode.TRY => true
+    // `Cast.isNoThrowLegacyCast` covers the numbers, booleans and strings. A 
string to a date or
+    // a timestamp does not raise in LEGACY mode either: the parsers catch the 
errors and return
+    // None, which becomes NULL.
+    case (_: StringType, DateType | TimestampType | TimestampNTZType)
+        if c.evalMode == EvalMode.LEGACY => true
+    case (from, to) if c.evalMode == EvalMode.LEGACY => 
Cast.isNoThrowLegacyCast(from, to)
+    case _ => false
+  }
+
+  // Whether numeric arithmetic can not fail, in its own eval mode.
+  private def cannotFailArithmetic(b: BinaryArithmetic): Boolean = {
+    val decimal = b.children.exists(_.dataType.isInstanceOf[DecimalType])
+    b.children.forall(_.dataType.isInstanceOf[NumericType]) && b.evalMode != 
EvalMode.ANSI &&
+      (b match {
+        case _: Add | _: Subtract | _: Multiply | _: Divide => true
+        // `Decimal.quot` and `Decimal.%` raise when the integral quotient is 
too long.
+        case _: Remainder => !decimal
+        // `DivModLike` and Pmod override `eval` without the catch of TRY 
mode, and IntegralDivide
+        // and Pmod check a zero divisor there as in ANSI mode.
+        case _: IntegralDivide | _: Pmod => !decimal && b.evalMode == 
EvalMode.LEGACY
+        case _ => false
+      })
+  }
+
   private def canEvaluateUnconditionallyInternal(e: Expression): Boolean = e 
match {
     case _: AttributeReference | _: Literal => true
-    case _: GetStructField | _: GetArrayStructFields | _: GetMapValue =>
+    case _: GetStructField | _: GetArrayStructFields | _: GetMapValue | _: 
NoThrow =>
       e.children.forall(canEvaluateUnconditionallyInternal)
     case _: And | _: Or | _: Not | _: BinaryComparison | _: IsNull | _: 
IsNotNull |
-         _: IsNaN | _: NullIf | _: Coalesce | _: In | _: InSet =>
+         _: IsNaN | _: NullIf | _: Coalesce | _: In | _: InSet | _: Size | _: 
StartsWith |

Review Comment:
   Done: the check now passes `Collate` through to its child, and takes a cast 
of a string to a plain STRING of any collation in every mode, so `contains(a 
COLLATE UNICODE_CI, b)` with the cast that `CollationTypeCoercion` adds is 
accepted. `ExprUtilsSuite` checks that, that a `Collate` over a child that can 
fail is rejected, and that a cast of a string to a `CHAR` or `VARCHAR` is still 
rejected and raises in ANSI mode, and evaluates `Collate` and the casts of a 
string, a `VARCHAR` and a `CHAR` to a STRING of another collation in every 
mode. The `CombineFilters` test in `FilterPushdownSuite` now also has a 
`Contains` over a `COLLATE` whose other side gets that cast in analysis. With 
`spark.sql.join.splitStreamedSideJoinCondition` enabled, this also hoists 
`contains(l.name COLLATE UNICODE_CI, 'x')`, which the earlier bot review noted 
was not hoisted; it now follows the cost policy of the hoist discussed in 
https://github.com/apache/spark/pull/60119#issuecomment-6679140888.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,13 +295,63 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
     e.deterministic && !e.containsPattern(PLAN_EXPRESSION) &&
       canEvaluateUnconditionallyInternal(e)
 
+  // Only the numeric pairs are taken from `Cast.canUpCast`, which also covers 
e.g. DATE to
+  // TIMESTAMP, which can overflow, and casts between complex types. Among the 
numeric ones, it
+  // only takes a decimal to an integral type whose values all fit.
+  private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from, 
to) match {
+    case (_: NumericType, _: NumericType) => Cast.canUpCast(from, to)
+    case _ => false
+  }
+
+  // Whether a cast can not fail. A cast of a date to a timestamp is left out 
also in LEGACY mode,
+  // as converting a date far from the epoch to microseconds overflows there.
+  private def cannotFailCast(c: Cast): Boolean = (c.child.dataType, 
c.dataType) match {
+    case (from, to) if isNumericUpCast(from, to) => true
+    case (TimestampType | TimestampNTZType, DateType) => true
+    // A CHAR or VARCHAR target checks the length of the string.
+    case (_: NumericType | BooleanType, s: StringType) if 
StringHelper.isPlainString(s) => true
+    case _ if c.evalMode == EvalMode.TRY => true
+    // `Cast.isNoThrowLegacyCast` covers the numbers, booleans and strings. A 
string to a date or
+    // a timestamp does not raise in LEGACY mode either: the parsers catch the 
errors and return
+    // None, which becomes NULL.
+    case (_: StringType, DateType | TimestampType | TimestampNTZType)
+        if c.evalMode == EvalMode.LEGACY => true
+    case (from, to) if c.evalMode == EvalMode.LEGACY => 
Cast.isNoThrowLegacyCast(from, to)
+    case _ => false
+  }
+
+  // Whether numeric arithmetic can not fail, in its own eval mode.
+  private def cannotFailArithmetic(b: BinaryArithmetic): Boolean = {
+    val decimal = b.children.exists(_.dataType.isInstanceOf[DecimalType])
+    b.children.forall(_.dataType.isInstanceOf[NumericType]) && b.evalMode != 
EvalMode.ANSI &&

Review Comment:
   Done, thanks: `Add`, `Subtract` and `Multiply` over `FLOAT` and `DOUBLE`, 
`UnaryMinus` and `Abs` over `FLOAT`, `DOUBLE` and `DECIMAL`, and a cast of a 
`DECIMAL` to a `FLOAT` or `DOUBLE` are now accepted in every mode. 
`ExprUtilsSuite` checks that they are accepted in ANSI mode, and that `Divide`, 
`Remainder` and `Pmod` over doubles, `Add` over decimals and over `INT`, 
`SMALLINT` and `TINYINT`, `UnaryMinus` over the integral types, and a cast of a 
decimal to a narrower decimal are still rejected there. It evaluates the 
accepted ones, the arithmetic built in ANSI mode and `UnaryMinus` and `Abs` 
with `failOnError` set, on infinities, NaN, the largest values and the largest 
and smallest decimals. The `CombineFilters` test now also has `CAST(a AS 
DOUBLE) * 1.1 > 100` built in ANSI mode.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -39,17 +64,359 @@ class ExprUtilsSuite extends SparkFunSuite {
   test("canEvaluateUnconditionally: expressions that can throw are excluded") {
     // Arithmetic can throw (overflow, div-by-zero in ANSI mode) even though 
it does not
     // override `throwable` and inherits false from its non-throwing children, 
which is
-    // why the whitelist is used instead of the throwable flag.
-    val arithmetic = LessThan(Add(a, Literal(1L)), Literal(5L))
+    // why the allowlist is used instead of the throwable flag.
+    val arithmetic = LessThan(Add(a, Literal(1L), ansi), Literal(5L))
     assert(!arithmetic.throwable)
     assert(!ExprUtils.canEvaluateUnconditionally(arithmetic))
-    assert(!ExprUtils.canEvaluateUnconditionally(EqualTo(Remainder(a, 
Literal(3L)), Literal(0L))))
-    assert(!ExprUtils.canEvaluateUnconditionally(Cast(a, StringType)))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      EqualTo(Remainder(a, Literal(3L), ansi), Literal(0L))))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      Cast(AttributeReference("s", StringType)(), IntegerType, evalMode = 
EvalMode.ANSI)))
     // GetArrayItem/ElementAt can throw on invalid ordinals in ANSI mode.
     val arr = AttributeReference("arr", ArrayType(IntegerType))()
     assert(!ExprUtils.canEvaluateUnconditionally(GetArrayItem(arr, 
Literal(0))))
-    // A whitelisted predicate over a non-whitelisted child is still excluded.
-    assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a, 
Literal(1L)))))
+    // An allowlisted predicate over a child that is not allowlisted is still 
excluded.
+    assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a, Literal(1L), 
ansi))))
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: size and numeric up-casts are 
included") {
+    val arr = AttributeReference("arr", ArrayType(IntegerType))()
+    val i = AttributeReference("i", IntegerType)()
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(Size(arr), 
Literal(0))))
+    assert(ExprUtils.canEvaluateUnconditionally(
+      EqualTo(Cast(i, LongType, evalMode = EvalMode.ANSI), a)))
+    assert(ExprUtils.canEvaluateUnconditionally(Cast(i, DoubleType, evalMode = 
EvalMode.ANSI)))
+    assert(ExprUtils.canEvaluateUnconditionally(
+      Cast(i, DecimalType(20, 0), evalMode = EvalMode.ANSI)))
+    // A decimal to an integral type is an up-cast only when every value fits: 
DECIMAL(18, 0) to
+    // BIGINT, but not DECIMAL(19, 0), which can overflow in ANSI mode.
+    assert(ExprUtils.canEvaluateUnconditionally(Cast(AttributeReference("d", 
DecimalType(18, 0))(),
+      LongType, evalMode = EvalMode.ANSI)))
+    for ((precision, to) <- Seq((18, LongType), (9, IntegerType), (4, 
ShortType), (2, ByteType))) {

Review Comment:
   Done: the loop now also checks each cast with `canEvaluateUnconditionally`, 
which replaces the separate check of `DECIMAL(18, 0)` to `BIGINT`.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -39,17 +64,359 @@ class ExprUtilsSuite extends SparkFunSuite {
   test("canEvaluateUnconditionally: expressions that can throw are excluded") {
     // Arithmetic can throw (overflow, div-by-zero in ANSI mode) even though 
it does not
     // override `throwable` and inherits false from its non-throwing children, 
which is
-    // why the whitelist is used instead of the throwable flag.
-    val arithmetic = LessThan(Add(a, Literal(1L)), Literal(5L))
+    // why the allowlist is used instead of the throwable flag.
+    val arithmetic = LessThan(Add(a, Literal(1L), ansi), Literal(5L))
     assert(!arithmetic.throwable)
     assert(!ExprUtils.canEvaluateUnconditionally(arithmetic))
-    assert(!ExprUtils.canEvaluateUnconditionally(EqualTo(Remainder(a, 
Literal(3L)), Literal(0L))))
-    assert(!ExprUtils.canEvaluateUnconditionally(Cast(a, StringType)))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      EqualTo(Remainder(a, Literal(3L), ansi), Literal(0L))))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      Cast(AttributeReference("s", StringType)(), IntegerType, evalMode = 
EvalMode.ANSI)))
     // GetArrayItem/ElementAt can throw on invalid ordinals in ANSI mode.
     val arr = AttributeReference("arr", ArrayType(IntegerType))()
     assert(!ExprUtils.canEvaluateUnconditionally(GetArrayItem(arr, 
Literal(0))))
-    // A whitelisted predicate over a non-whitelisted child is still excluded.
-    assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a, 
Literal(1L)))))
+    // An allowlisted predicate over a child that is not allowlisted is still 
excluded.
+    assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a, Literal(1L), 
ansi))))
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: size and numeric up-casts are 
included") {
+    val arr = AttributeReference("arr", ArrayType(IntegerType))()
+    val i = AttributeReference("i", IntegerType)()
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(Size(arr), 
Literal(0))))
+    assert(ExprUtils.canEvaluateUnconditionally(
+      EqualTo(Cast(i, LongType, evalMode = EvalMode.ANSI), a)))
+    assert(ExprUtils.canEvaluateUnconditionally(Cast(i, DoubleType, evalMode = 
EvalMode.ANSI)))
+    assert(ExprUtils.canEvaluateUnconditionally(
+      Cast(i, DecimalType(20, 0), evalMode = EvalMode.ANSI)))
+    // A decimal to an integral type is an up-cast only when every value fits: 
DECIMAL(18, 0) to
+    // BIGINT, but not DECIMAL(19, 0), which can overflow in ANSI mode.
+    assert(ExprUtils.canEvaluateUnconditionally(Cast(AttributeReference("d", 
DecimalType(18, 0))(),
+      LongType, evalMode = EvalMode.ANSI)))
+    for ((precision, to) <- Seq((18, LongType), (9, IntegerType), (4, 
ShortType), (2, ByteType))) {
+      assert(Cast.canUpCast(DecimalType(precision, 0), to), to)
+      evalEach(DecimalType(precision, 0),
+        Seq("-" + "9" * precision, "9" * precision).map(d => 
Decimal(BigDecimal(d))))(
+        Cast(_, to, evalMode = EvalMode.ANSI))
+    }
+    assert(!Cast.canUpCast(DecimalType(19, 0), LongType))
+    assert(!ExprUtils.canEvaluateUnconditionally(Cast(AttributeReference("d", 
DecimalType(19, 0))(),
+      LongType, evalMode = EvalMode.ANSI)))
+    intercept[ArithmeticException](Cast(Literal(Decimal(BigDecimal("9" * 19)), 
DecimalType(19, 0)),
+      LongType, evalMode = EvalMode.ANSI).eval())
+    // Narrowing casts can fail in ANSI mode. LONG to TIMESTAMP is an up-cast 
too, but only the
+    // numeric ones are taken.
+    assert(!ExprUtils.canEvaluateUnconditionally(Cast(a, IntegerType, evalMode 
= EvalMode.ANSI)))
+    assert(Cast.canUpCast(LongType, TimestampType))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      Cast(a, TimestampType, evalMode = EvalMode.ANSI)))
+    // A size over an expression that can fail is still excluded.
+    assert(!ExprUtils.canEvaluateUnconditionally(Size(ElementAt(
+      AttributeReference("nested", ArrayType(ArrayType(IntegerType)))(), 
Literal(1)))))
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: string prefix, suffix, 
containment and " +
+    "length checks and a field of a struct built from plain values are 
included") {
+    val s = AttributeReference("s", StringType)()
+    // `LIKE 'ab%c'` becomes the last one.
+    Seq(StartsWith(s, Literal("abc")), EndsWith(s, Literal("abc")), 
Contains(s, s),
+        GreaterThan(Length(s), Literal(1)),
+        And(GreaterThanOrEqual(OctetLength(s), Literal(3)),
+          And(StartsWith(s, Literal("ab")), EndsWith(s, 
Literal("c"))))).foreach {
+      p => assert(ExprUtils.canEvaluateUnconditionally(p), p)
+    }
+    val bin = AttributeReference("bin", BinaryType)()
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(Length(bin), 
Literal(1))))
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(OctetLength(bin), 
Literal(1))))
+    // They do not raise for any collation, also on empty, ignorable and 
invalid UTF-8 strings,
+    // which ICU can not search for: a combining accent after a letter and 
alone, a zero-width
+    // space, NUL, U+FFFD, a bad lead byte, a truncated sequence and one above 
U+10FFFF.
+    val ignorable = Seq(Seq('a', 0x0301), Seq(0x0301), Seq(0x200B), 
Seq(0x0000), Seq(0xFFFD))
+      .map(_.map(_.toChar).mkString)
+    val invalid = Seq(Array(0xFF, 'a'), Array('a', 0xE2), Array(0xF4, 0xBF, 
0xBF, 0xBF))
+      .map(b => UTF8String.fromBytes(b.map(_.toByte)))
+    val values = (Seq("", " ", "a", "abc") ++ 
ignorable).map(UTF8String.fromString) ++ invalid
+    Seq("UTF8_BINARY", "UTF8_LCASE", "UNICODE", "UNICODE_CI", "UNICODE_AI", 
"UNICODE_CI_AI",
+        "UTF8_BINARY_RTRIM", "UNICODE_RTRIM", "UTF8_LCASE_RTRIM", 
"sr_CI_AI").foreach {
+      collation =>
+        val collated = StringType(collation)
+        evalEach(collated, values)(Length(_))
+        evalEach(collated, values)(OctetLength(_))
+        Seq[(Expression, Expression) => Expression](StartsWith(_, _), 
EndsWith(_, _),
+          Contains(_, _)).foreach(evalPairs(collated, values))
+    }
+    // LIKE and RLIKE raise on an invalid pattern.
+    assert(!ExprUtils.canEvaluateUnconditionally(Like(s, Literal("abc%"), 
'\\')))
+    assert(!ExprUtils.canEvaluateUnconditionally(RLike(s, Literal("abc"))))
+    assert(!ExprUtils.canEvaluateUnconditionally(StartsWith(Upper(s), 
Literal("abc"))))
+    assert(!ExprUtils.canEvaluateUnconditionally(Length(Upper(s))))
+
+    // A struct built from plain values, and a field of it, but not when 
another field can fail.
+    def field(values: Expression*): Expression = 
GetStructField(CreateNamedStruct(
+      values.zipWithIndex.flatMap { case (v, i) => Seq(Literal(s"f$i"), v) }), 
0)
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(field(a, s), 
Literal(1L))))
+    assert(!ExprUtils.canEvaluateUnconditionally(GreaterThan(field(a, Add(a, 
Literal(1L), ansi)),
+      Literal(1L))))
+    
assert(ExprUtils.canEvaluateUnconditionally(CreateNamedStruct(Seq(Literal("f0"),
 a))))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      CreateNamedStruct(Seq(Literal("f0"), Add(a, Literal(1L), ansi)))))
+    // So is an array, as both are marked `NoThrow`, but not a map, which 
raises on a NULL or, by

Review Comment:
   Fixed here and in the description, thanks.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -39,17 +64,359 @@ class ExprUtilsSuite extends SparkFunSuite {
   test("canEvaluateUnconditionally: expressions that can throw are excluded") {
     // Arithmetic can throw (overflow, div-by-zero in ANSI mode) even though 
it does not
     // override `throwable` and inherits false from its non-throwing children, 
which is
-    // why the whitelist is used instead of the throwable flag.
-    val arithmetic = LessThan(Add(a, Literal(1L)), Literal(5L))
+    // why the allowlist is used instead of the throwable flag.
+    val arithmetic = LessThan(Add(a, Literal(1L), ansi), Literal(5L))
     assert(!arithmetic.throwable)
     assert(!ExprUtils.canEvaluateUnconditionally(arithmetic))
-    assert(!ExprUtils.canEvaluateUnconditionally(EqualTo(Remainder(a, 
Literal(3L)), Literal(0L))))
-    assert(!ExprUtils.canEvaluateUnconditionally(Cast(a, StringType)))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      EqualTo(Remainder(a, Literal(3L), ansi), Literal(0L))))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      Cast(AttributeReference("s", StringType)(), IntegerType, evalMode = 
EvalMode.ANSI)))
     // GetArrayItem/ElementAt can throw on invalid ordinals in ANSI mode.
     val arr = AttributeReference("arr", ArrayType(IntegerType))()
     assert(!ExprUtils.canEvaluateUnconditionally(GetArrayItem(arr, 
Literal(0))))
-    // A whitelisted predicate over a non-whitelisted child is still excluded.
-    assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a, 
Literal(1L)))))
+    // An allowlisted predicate over a child that is not allowlisted is still 
excluded.
+    assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a, Literal(1L), 
ansi))))
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: size and numeric up-casts are 
included") {
+    val arr = AttributeReference("arr", ArrayType(IntegerType))()
+    val i = AttributeReference("i", IntegerType)()
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(Size(arr), 
Literal(0))))
+    assert(ExprUtils.canEvaluateUnconditionally(
+      EqualTo(Cast(i, LongType, evalMode = EvalMode.ANSI), a)))
+    assert(ExprUtils.canEvaluateUnconditionally(Cast(i, DoubleType, evalMode = 
EvalMode.ANSI)))
+    assert(ExprUtils.canEvaluateUnconditionally(
+      Cast(i, DecimalType(20, 0), evalMode = EvalMode.ANSI)))
+    // A decimal to an integral type is an up-cast only when every value fits: 
DECIMAL(18, 0) to
+    // BIGINT, but not DECIMAL(19, 0), which can overflow in ANSI mode.
+    assert(ExprUtils.canEvaluateUnconditionally(Cast(AttributeReference("d", 
DecimalType(18, 0))(),
+      LongType, evalMode = EvalMode.ANSI)))
+    for ((precision, to) <- Seq((18, LongType), (9, IntegerType), (4, 
ShortType), (2, ByteType))) {
+      assert(Cast.canUpCast(DecimalType(precision, 0), to), to)
+      evalEach(DecimalType(precision, 0),
+        Seq("-" + "9" * precision, "9" * precision).map(d => 
Decimal(BigDecimal(d))))(
+        Cast(_, to, evalMode = EvalMode.ANSI))
+    }
+    assert(!Cast.canUpCast(DecimalType(19, 0), LongType))
+    assert(!ExprUtils.canEvaluateUnconditionally(Cast(AttributeReference("d", 
DecimalType(19, 0))(),
+      LongType, evalMode = EvalMode.ANSI)))
+    intercept[ArithmeticException](Cast(Literal(Decimal(BigDecimal("9" * 19)), 
DecimalType(19, 0)),
+      LongType, evalMode = EvalMode.ANSI).eval())
+    // Narrowing casts can fail in ANSI mode. LONG to TIMESTAMP is an up-cast 
too, but only the
+    // numeric ones are taken.
+    assert(!ExprUtils.canEvaluateUnconditionally(Cast(a, IntegerType, evalMode 
= EvalMode.ANSI)))
+    assert(Cast.canUpCast(LongType, TimestampType))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      Cast(a, TimestampType, evalMode = EvalMode.ANSI)))
+    // A size over an expression that can fail is still excluded.
+    assert(!ExprUtils.canEvaluateUnconditionally(Size(ElementAt(
+      AttributeReference("nested", ArrayType(ArrayType(IntegerType)))(), 
Literal(1)))))
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: string prefix, suffix, 
containment and " +
+    "length checks and a field of a struct built from plain values are 
included") {
+    val s = AttributeReference("s", StringType)()
+    // `LIKE 'ab%c'` becomes the last one.
+    Seq(StartsWith(s, Literal("abc")), EndsWith(s, Literal("abc")), 
Contains(s, s),
+        GreaterThan(Length(s), Literal(1)),
+        And(GreaterThanOrEqual(OctetLength(s), Literal(3)),
+          And(StartsWith(s, Literal("ab")), EndsWith(s, 
Literal("c"))))).foreach {
+      p => assert(ExprUtils.canEvaluateUnconditionally(p), p)
+    }
+    val bin = AttributeReference("bin", BinaryType)()
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(Length(bin), 
Literal(1))))
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(OctetLength(bin), 
Literal(1))))
+    // They do not raise for any collation, also on empty, ignorable and 
invalid UTF-8 strings,
+    // which ICU can not search for: a combining accent after a letter and 
alone, a zero-width
+    // space, NUL, U+FFFD, a bad lead byte, a truncated sequence and one above 
U+10FFFF.
+    val ignorable = Seq(Seq('a', 0x0301), Seq(0x0301), Seq(0x200B), 
Seq(0x0000), Seq(0xFFFD))
+      .map(_.map(_.toChar).mkString)
+    val invalid = Seq(Array(0xFF, 'a'), Array('a', 0xE2), Array(0xF4, 0xBF, 
0xBF, 0xBF))
+      .map(b => UTF8String.fromBytes(b.map(_.toByte)))
+    val values = (Seq("", " ", "a", "abc") ++ 
ignorable).map(UTF8String.fromString) ++ invalid
+    Seq("UTF8_BINARY", "UTF8_LCASE", "UNICODE", "UNICODE_CI", "UNICODE_AI", 
"UNICODE_CI_AI",
+        "UTF8_BINARY_RTRIM", "UNICODE_RTRIM", "UTF8_LCASE_RTRIM", 
"sr_CI_AI").foreach {
+      collation =>
+        val collated = StringType(collation)
+        evalEach(collated, values)(Length(_))
+        evalEach(collated, values)(OctetLength(_))
+        Seq[(Expression, Expression) => Expression](StartsWith(_, _), 
EndsWith(_, _),
+          Contains(_, _)).foreach(evalPairs(collated, values))
+    }
+    // LIKE and RLIKE raise on an invalid pattern.
+    assert(!ExprUtils.canEvaluateUnconditionally(Like(s, Literal("abc%"), 
'\\')))
+    assert(!ExprUtils.canEvaluateUnconditionally(RLike(s, Literal("abc"))))
+    assert(!ExprUtils.canEvaluateUnconditionally(StartsWith(Upper(s), 
Literal("abc"))))
+    assert(!ExprUtils.canEvaluateUnconditionally(Length(Upper(s))))
+
+    // A struct built from plain values, and a field of it, but not when 
another field can fail.
+    def field(values: Expression*): Expression = 
GetStructField(CreateNamedStruct(
+      values.zipWithIndex.flatMap { case (v, i) => Seq(Literal(s"f$i"), v) }), 
0)
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(field(a, s), 
Literal(1L))))
+    assert(!ExprUtils.canEvaluateUnconditionally(GreaterThan(field(a, Add(a, 
Literal(1L), ansi)),
+      Literal(1L))))
+    
assert(ExprUtils.canEvaluateUnconditionally(CreateNamedStruct(Seq(Literal("f0"),
 a))))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      CreateNamedStruct(Seq(Literal("f0"), Add(a, Literal(1L), ansi)))))
+    // So is an array, as both are marked `NoThrow`, but not a map, which 
raises on a NULL or, by
+    // default, a duplicate key (SPARK-60849).
+    assert(!ExprUtils.canEvaluateUnconditionally(CreateMap(Seq(a, 
Literal(1)))))
+    intercept[SparkRuntimeException](
+      CreateMap(Seq(Literal(1L), Literal(1), Literal(1L), Literal(2))).eval())
+    assert(ExprUtils.canEvaluateUnconditionally(
+      EqualTo(CreateArray(Seq(a, Literal(1L))), CreateArray(Seq(Literal(1L), 
Literal(2L))))))
+    assert(!ExprUtils.canEvaluateUnconditionally(CreateArray(Seq(a, Add(a, 
Literal(1L), ansi)))))
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: numeric arithmetic outside 
ANSI mode") {
+    val i = AttributeReference("i", IntegerType)()
+    def binary(ctx: NumericEvalContext): Seq[Expression] = Seq(Add(a, a, ctx),
+      Subtract(a, a, ctx), Multiply(a, a, ctx), Divide(Cast(a, DoubleType), 
Literal(0.0), ctx),
+      IntegralDivide(a, a, ctx), Remainder(a, a, ctx), Pmod(i, i, ctx))
+    binary(legacy).foreach(e => 
assert(ExprUtils.canEvaluateUnconditionally(e), e))
+    binary(ansi).foreach(e => assert(!ExprUtils.canEvaluateUnconditionally(e), 
e))
+    assert(ExprUtils.canEvaluateUnconditionally(UnaryMinus(a, failOnError = 
false)))
+    assert(ExprUtils.canEvaluateUnconditionally(Abs(a, failOnError = false)))
+    assert(!ExprUtils.canEvaluateUnconditionally(UnaryMinus(a, failOnError = 
true)))
+    assert(!ExprUtils.canEvaluateUnconditionally(Abs(a, failOnError = true)))
+    // Not over a child that can fail.
+    val failing = Add(a, a, ansi)
+    assert(!ExprUtils.canEvaluateUnconditionally(Add(failing, a, legacy)))
+    assert(!ExprUtils.canEvaluateUnconditionally(UnaryMinus(failing, 
failOnError = false)))
+    assert(!ExprUtils.canEvaluateUnconditionally(Abs(failing, failOnError = 
false)))
+    // TRY mode catches the errors of Add, Subtract and Multiply, and Divide 
and Remainder only
+    // check a zero divisor in ANSI mode, but IntegralDivide and Pmod raise 
there.
+    Seq(Add(a, a, tryMode), Subtract(a, a, tryMode), Multiply(a, a, tryMode),
+        Divide(Cast(a, DoubleType), Literal(0.0), tryMode), Remainder(a, a, 
tryMode))
+      .foreach(e => assert(ExprUtils.canEvaluateUnconditionally(e), e))
+    Seq(IntegralDivide(Literal(1L), Literal(0L), tryMode), Pmod(Literal(1), 
Literal(0), tryMode))
+      .foreach { e =>
+        assert(!ExprUtils.canEvaluateUnconditionally(e), e)
+        intercept[ArithmeticException](e.eval())
+      }
+    // IntegralDivide, Remainder and Pmod over decimals raise when the 
integral quotient has more
+    // digits than the MathContext of `Decimal` holds.
+    val big = Literal(Decimal(BigDecimal("9" * 38)), DecimalType(38, 0))
+    val small = Literal(Decimal(BigDecimal("0.007"), 3, 3), DecimalType(3, 3))
+    Seq(IntegralDivide(big, small, legacy), Remainder(big, small, legacy),
+        Remainder(big, small, tryMode), Pmod(big, small, legacy)).foreach { e 
=>
+      assert(!ExprUtils.canEvaluateUnconditionally(e), e)
+      intercept[ArithmeticException](e.eval())
+    }
+    assert(ExprUtils.canEvaluateUnconditionally(Divide(big, small, legacy)))
+    // Divide and the other arithmetic over decimals of different scales do 
not raise.
+    Seq(legacy, tryMode).foreach { ctx =>
+      assert(Divide(big, small, ctx).eval() == null)
+    }
+    // Arithmetic over intervals overflows in every mode, also UnaryMinus and 
Abs.
+    val maxInterval = Literal(Long.MaxValue, DayTimeIntervalType())
+    val intervalAdd = Add(maxInterval, maxInterval, legacy)
+    assert(!ExprUtils.canEvaluateUnconditionally(intervalAdd))
+    intercept[ArithmeticException](intervalAdd.eval())
+    Seq(Literal(Long.MinValue, DayTimeIntervalType()),
+        Literal(Int.MinValue, YearMonthIntervalType())).foreach { minInterval 
=>
+      Seq(UnaryMinus(minInterval, failOnError = false), Abs(minInterval, 
failOnError = false))
+        .foreach { e =>
+          assert(!ExprUtils.canEvaluateUnconditionally(e), e)
+          intercept[ArithmeticException](e.eval())
+        }
+    }
+
+    // None of the accepted ones raises, also on the values that do in ANSI 
mode.
+    val longs = (LongType, Seq(Long.MinValue, -1L, 0L, 1L, Long.MaxValue))
+    val ints = (IntegerType, Seq(Int.MinValue, -1, 0, 1, Int.MaxValue))
+    val shorts = (ShortType, Seq(Short.MinValue, -1.toShort, 0.toShort, 
Short.MaxValue))
+    val bytes = (ByteType, Seq(Byte.MinValue, -1.toByte, 0.toByte, 
Byte.MaxValue))
+    val floats = (FloatType, Seq(Float.NegativeInfinity, -1.0f, 0.0f, 
Float.NaN, Float.MaxValue))
+    val doubles =
+      (DoubleType, Seq(Double.NegativeInfinity, -1.0, 0.0, Double.NaN, 
Double.MaxValue))
+    val decimals = (DecimalType(38, 0),
+      Seq("-" + "9" * 38, "0", "1", "9" * 38).map(d => Decimal(BigDecimal(d))))
+    // A small divisor makes the quotient overflow.
+    val smallDecimals = (DecimalType(38, 37),
+      Seq("-1", "0", "1E-37", "9." + "9" * 37).map(d => Decimal(BigDecimal(d), 
38, 37)))
+    val nonDecimals = Seq(longs, ints, shorts, bytes, floats, doubles)
+    for ((t, values) <- nonDecimals ++ Seq(decimals, smallDecimals)) {
+      Seq(legacy, tryMode).foreach { ctx =>
+        Seq[(Expression, Expression) => Expression](Add(_, _, ctx), 
Subtract(_, _, ctx),
+          Multiply(_, _, ctx)).foreach(evalPairs(t, values))
+      }
+      evalPairs(t, values)((l, _) => UnaryMinus(l, failOnError = false))
+      evalPairs(t, values)((l, _) => Abs(l, failOnError = false))
+    }
+    for ((t, values) <- nonDecimals) {
+      Seq(legacy, tryMode).foreach(ctx => evalPairs(t, values)(Remainder(_, _, 
ctx)))
+      evalPairs(t, values)(Pmod(_, _, legacy))
+    }
+    evalPairs(longs._1, longs._2)(IntegralDivide(_, _, legacy))
+    for ((t, values) <- Seq(doubles, decimals, smallDecimals); ctx <- 
Seq(legacy, tryMode)) {
+      evalPairs(t, values)(Divide(_, _, ctx))
+    }
+    // Decimals of different precisions and scales, also without precision 
loss.

Review Comment:
   Done: a new helper, `evalRows`, takes a type and values for each column and 
evaluates every combination of them. `evalPairs` and `evalEach` call it, and 
the decimal loop uses it directly, so it now covers non-nullable decimals too.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -39,17 +64,359 @@ class ExprUtilsSuite extends SparkFunSuite {
   test("canEvaluateUnconditionally: expressions that can throw are excluded") {
     // Arithmetic can throw (overflow, div-by-zero in ANSI mode) even though 
it does not
     // override `throwable` and inherits false from its non-throwing children, 
which is
-    // why the whitelist is used instead of the throwable flag.
-    val arithmetic = LessThan(Add(a, Literal(1L)), Literal(5L))
+    // why the allowlist is used instead of the throwable flag.
+    val arithmetic = LessThan(Add(a, Literal(1L), ansi), Literal(5L))
     assert(!arithmetic.throwable)
     assert(!ExprUtils.canEvaluateUnconditionally(arithmetic))
-    assert(!ExprUtils.canEvaluateUnconditionally(EqualTo(Remainder(a, 
Literal(3L)), Literal(0L))))
-    assert(!ExprUtils.canEvaluateUnconditionally(Cast(a, StringType)))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      EqualTo(Remainder(a, Literal(3L), ansi), Literal(0L))))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      Cast(AttributeReference("s", StringType)(), IntegerType, evalMode = 
EvalMode.ANSI)))
     // GetArrayItem/ElementAt can throw on invalid ordinals in ANSI mode.
     val arr = AttributeReference("arr", ArrayType(IntegerType))()
     assert(!ExprUtils.canEvaluateUnconditionally(GetArrayItem(arr, 
Literal(0))))
-    // A whitelisted predicate over a non-whitelisted child is still excluded.
-    assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a, 
Literal(1L)))))
+    // An allowlisted predicate over a child that is not allowlisted is still 
excluded.
+    assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a, Literal(1L), 
ansi))))
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: size and numeric up-casts are 
included") {
+    val arr = AttributeReference("arr", ArrayType(IntegerType))()
+    val i = AttributeReference("i", IntegerType)()
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(Size(arr), 
Literal(0))))
+    assert(ExprUtils.canEvaluateUnconditionally(
+      EqualTo(Cast(i, LongType, evalMode = EvalMode.ANSI), a)))
+    assert(ExprUtils.canEvaluateUnconditionally(Cast(i, DoubleType, evalMode = 
EvalMode.ANSI)))
+    assert(ExprUtils.canEvaluateUnconditionally(
+      Cast(i, DecimalType(20, 0), evalMode = EvalMode.ANSI)))
+    // A decimal to an integral type is an up-cast only when every value fits: 
DECIMAL(18, 0) to
+    // BIGINT, but not DECIMAL(19, 0), which can overflow in ANSI mode.
+    assert(ExprUtils.canEvaluateUnconditionally(Cast(AttributeReference("d", 
DecimalType(18, 0))(),
+      LongType, evalMode = EvalMode.ANSI)))
+    for ((precision, to) <- Seq((18, LongType), (9, IntegerType), (4, 
ShortType), (2, ByteType))) {
+      assert(Cast.canUpCast(DecimalType(precision, 0), to), to)
+      evalEach(DecimalType(precision, 0),
+        Seq("-" + "9" * precision, "9" * precision).map(d => 
Decimal(BigDecimal(d))))(
+        Cast(_, to, evalMode = EvalMode.ANSI))
+    }
+    assert(!Cast.canUpCast(DecimalType(19, 0), LongType))
+    assert(!ExprUtils.canEvaluateUnconditionally(Cast(AttributeReference("d", 
DecimalType(19, 0))(),
+      LongType, evalMode = EvalMode.ANSI)))
+    intercept[ArithmeticException](Cast(Literal(Decimal(BigDecimal("9" * 19)), 
DecimalType(19, 0)),
+      LongType, evalMode = EvalMode.ANSI).eval())
+    // Narrowing casts can fail in ANSI mode. LONG to TIMESTAMP is an up-cast 
too, but only the
+    // numeric ones are taken.
+    assert(!ExprUtils.canEvaluateUnconditionally(Cast(a, IntegerType, evalMode 
= EvalMode.ANSI)))
+    assert(Cast.canUpCast(LongType, TimestampType))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      Cast(a, TimestampType, evalMode = EvalMode.ANSI)))
+    // A size over an expression that can fail is still excluded.
+    assert(!ExprUtils.canEvaluateUnconditionally(Size(ElementAt(
+      AttributeReference("nested", ArrayType(ArrayType(IntegerType)))(), 
Literal(1)))))
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: string prefix, suffix, 
containment and " +
+    "length checks and a field of a struct built from plain values are 
included") {
+    val s = AttributeReference("s", StringType)()
+    // `LIKE 'ab%c'` becomes the last one.
+    Seq(StartsWith(s, Literal("abc")), EndsWith(s, Literal("abc")), 
Contains(s, s),
+        GreaterThan(Length(s), Literal(1)),
+        And(GreaterThanOrEqual(OctetLength(s), Literal(3)),
+          And(StartsWith(s, Literal("ab")), EndsWith(s, 
Literal("c"))))).foreach {
+      p => assert(ExprUtils.canEvaluateUnconditionally(p), p)
+    }
+    val bin = AttributeReference("bin", BinaryType)()
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(Length(bin), 
Literal(1))))
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(OctetLength(bin), 
Literal(1))))
+    // They do not raise for any collation, also on empty, ignorable and 
invalid UTF-8 strings,
+    // which ICU can not search for: a combining accent after a letter and 
alone, a zero-width
+    // space, NUL, U+FFFD, a bad lead byte, a truncated sequence and one above 
U+10FFFF.
+    val ignorable = Seq(Seq('a', 0x0301), Seq(0x0301), Seq(0x200B), 
Seq(0x0000), Seq(0xFFFD))
+      .map(_.map(_.toChar).mkString)
+    val invalid = Seq(Array(0xFF, 'a'), Array('a', 0xE2), Array(0xF4, 0xBF, 
0xBF, 0xBF))
+      .map(b => UTF8String.fromBytes(b.map(_.toByte)))
+    val values = (Seq("", " ", "a", "abc") ++ 
ignorable).map(UTF8String.fromString) ++ invalid
+    Seq("UTF8_BINARY", "UTF8_LCASE", "UNICODE", "UNICODE_CI", "UNICODE_AI", 
"UNICODE_CI_AI",
+        "UTF8_BINARY_RTRIM", "UNICODE_RTRIM", "UTF8_LCASE_RTRIM", 
"sr_CI_AI").foreach {
+      collation =>
+        val collated = StringType(collation)
+        evalEach(collated, values)(Length(_))
+        evalEach(collated, values)(OctetLength(_))
+        Seq[(Expression, Expression) => Expression](StartsWith(_, _), 
EndsWith(_, _),
+          Contains(_, _)).foreach(evalPairs(collated, values))
+    }
+    // LIKE and RLIKE raise on an invalid pattern.
+    assert(!ExprUtils.canEvaluateUnconditionally(Like(s, Literal("abc%"), 
'\\')))
+    assert(!ExprUtils.canEvaluateUnconditionally(RLike(s, Literal("abc"))))
+    assert(!ExprUtils.canEvaluateUnconditionally(StartsWith(Upper(s), 
Literal("abc"))))
+    assert(!ExprUtils.canEvaluateUnconditionally(Length(Upper(s))))
+
+    // A struct built from plain values, and a field of it, but not when 
another field can fail.
+    def field(values: Expression*): Expression = 
GetStructField(CreateNamedStruct(
+      values.zipWithIndex.flatMap { case (v, i) => Seq(Literal(s"f$i"), v) }), 
0)
+    assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(field(a, s), 
Literal(1L))))
+    assert(!ExprUtils.canEvaluateUnconditionally(GreaterThan(field(a, Add(a, 
Literal(1L), ansi)),
+      Literal(1L))))
+    
assert(ExprUtils.canEvaluateUnconditionally(CreateNamedStruct(Seq(Literal("f0"),
 a))))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      CreateNamedStruct(Seq(Literal("f0"), Add(a, Literal(1L), ansi)))))
+    // So is an array, as both are marked `NoThrow`, but not a map, which 
raises on a NULL or, by
+    // default, a duplicate key (SPARK-60849).
+    assert(!ExprUtils.canEvaluateUnconditionally(CreateMap(Seq(a, 
Literal(1)))))
+    intercept[SparkRuntimeException](
+      CreateMap(Seq(Literal(1L), Literal(1), Literal(1L), Literal(2))).eval())
+    assert(ExprUtils.canEvaluateUnconditionally(
+      EqualTo(CreateArray(Seq(a, Literal(1L))), CreateArray(Seq(Literal(1L), 
Literal(2L))))))
+    assert(!ExprUtils.canEvaluateUnconditionally(CreateArray(Seq(a, Add(a, 
Literal(1L), ansi)))))
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: numeric arithmetic outside 
ANSI mode") {
+    val i = AttributeReference("i", IntegerType)()
+    def binary(ctx: NumericEvalContext): Seq[Expression] = Seq(Add(a, a, ctx),
+      Subtract(a, a, ctx), Multiply(a, a, ctx), Divide(Cast(a, DoubleType), 
Literal(0.0), ctx),
+      IntegralDivide(a, a, ctx), Remainder(a, a, ctx), Pmod(i, i, ctx))
+    binary(legacy).foreach(e => 
assert(ExprUtils.canEvaluateUnconditionally(e), e))
+    binary(ansi).foreach(e => assert(!ExprUtils.canEvaluateUnconditionally(e), 
e))
+    assert(ExprUtils.canEvaluateUnconditionally(UnaryMinus(a, failOnError = 
false)))
+    assert(ExprUtils.canEvaluateUnconditionally(Abs(a, failOnError = false)))
+    assert(!ExprUtils.canEvaluateUnconditionally(UnaryMinus(a, failOnError = 
true)))
+    assert(!ExprUtils.canEvaluateUnconditionally(Abs(a, failOnError = true)))
+    // Not over a child that can fail.
+    val failing = Add(a, a, ansi)
+    assert(!ExprUtils.canEvaluateUnconditionally(Add(failing, a, legacy)))
+    assert(!ExprUtils.canEvaluateUnconditionally(UnaryMinus(failing, 
failOnError = false)))
+    assert(!ExprUtils.canEvaluateUnconditionally(Abs(failing, failOnError = 
false)))
+    // TRY mode catches the errors of Add, Subtract and Multiply, and Divide 
and Remainder only
+    // check a zero divisor in ANSI mode, but IntegralDivide and Pmod raise 
there.
+    Seq(Add(a, a, tryMode), Subtract(a, a, tryMode), Multiply(a, a, tryMode),
+        Divide(Cast(a, DoubleType), Literal(0.0), tryMode), Remainder(a, a, 
tryMode))
+      .foreach(e => assert(ExprUtils.canEvaluateUnconditionally(e), e))
+    Seq(IntegralDivide(Literal(1L), Literal(0L), tryMode), Pmod(Literal(1), 
Literal(0), tryMode))
+      .foreach { e =>
+        assert(!ExprUtils.canEvaluateUnconditionally(e), e)
+        intercept[ArithmeticException](e.eval())
+      }
+    // IntegralDivide, Remainder and Pmod over decimals raise when the 
integral quotient has more
+    // digits than the MathContext of `Decimal` holds.
+    val big = Literal(Decimal(BigDecimal("9" * 38)), DecimalType(38, 0))
+    val small = Literal(Decimal(BigDecimal("0.007"), 3, 3), DecimalType(3, 3))
+    Seq(IntegralDivide(big, small, legacy), Remainder(big, small, legacy),
+        Remainder(big, small, tryMode), Pmod(big, small, legacy)).foreach { e 
=>
+      assert(!ExprUtils.canEvaluateUnconditionally(e), e)
+      intercept[ArithmeticException](e.eval())
+    }
+    assert(ExprUtils.canEvaluateUnconditionally(Divide(big, small, legacy)))
+    // Divide and the other arithmetic over decimals of different scales do 
not raise.
+    Seq(legacy, tryMode).foreach { ctx =>
+      assert(Divide(big, small, ctx).eval() == null)
+    }
+    // Arithmetic over intervals overflows in every mode, also UnaryMinus and 
Abs.
+    val maxInterval = Literal(Long.MaxValue, DayTimeIntervalType())
+    val intervalAdd = Add(maxInterval, maxInterval, legacy)
+    assert(!ExprUtils.canEvaluateUnconditionally(intervalAdd))
+    intercept[ArithmeticException](intervalAdd.eval())
+    Seq(Literal(Long.MinValue, DayTimeIntervalType()),
+        Literal(Int.MinValue, YearMonthIntervalType())).foreach { minInterval 
=>
+      Seq(UnaryMinus(minInterval, failOnError = false), Abs(minInterval, 
failOnError = false))
+        .foreach { e =>
+          assert(!ExprUtils.canEvaluateUnconditionally(e), e)
+          intercept[ArithmeticException](e.eval())
+        }
+    }
+
+    // None of the accepted ones raises, also on the values that do in ANSI 
mode.
+    val longs = (LongType, Seq(Long.MinValue, -1L, 0L, 1L, Long.MaxValue))
+    val ints = (IntegerType, Seq(Int.MinValue, -1, 0, 1, Int.MaxValue))
+    val shorts = (ShortType, Seq(Short.MinValue, -1.toShort, 0.toShort, 
Short.MaxValue))
+    val bytes = (ByteType, Seq(Byte.MinValue, -1.toByte, 0.toByte, 
Byte.MaxValue))
+    val floats = (FloatType, Seq(Float.NegativeInfinity, -1.0f, 0.0f, 
Float.NaN, Float.MaxValue))
+    val doubles =
+      (DoubleType, Seq(Double.NegativeInfinity, -1.0, 0.0, Double.NaN, 
Double.MaxValue))
+    val decimals = (DecimalType(38, 0),
+      Seq("-" + "9" * 38, "0", "1", "9" * 38).map(d => Decimal(BigDecimal(d))))
+    // A small divisor makes the quotient overflow.
+    val smallDecimals = (DecimalType(38, 37),
+      Seq("-1", "0", "1E-37", "9." + "9" * 37).map(d => Decimal(BigDecimal(d), 
38, 37)))
+    val nonDecimals = Seq(longs, ints, shorts, bytes, floats, doubles)
+    for ((t, values) <- nonDecimals ++ Seq(decimals, smallDecimals)) {
+      Seq(legacy, tryMode).foreach { ctx =>
+        Seq[(Expression, Expression) => Expression](Add(_, _, ctx), 
Subtract(_, _, ctx),
+          Multiply(_, _, ctx)).foreach(evalPairs(t, values))
+      }
+      evalPairs(t, values)((l, _) => UnaryMinus(l, failOnError = false))
+      evalPairs(t, values)((l, _) => Abs(l, failOnError = false))
+    }
+    for ((t, values) <- nonDecimals) {
+      Seq(legacy, tryMode).foreach(ctx => evalPairs(t, values)(Remainder(_, _, 
ctx)))
+      evalPairs(t, values)(Pmod(_, _, legacy))
+    }
+    evalPairs(longs._1, longs._2)(IntegralDivide(_, _, legacy))
+    for ((t, values) <- Seq(doubles, decimals, smallDecimals); ctx <- 
Seq(legacy, tryMode)) {
+      evalPairs(t, values)(Divide(_, _, ctx))
+    }
+    // Decimals of different precisions and scales, also without precision 
loss.
+    for (allowLoss <- Seq(true, false); mode <- Seq(EvalMode.LEGACY, 
EvalMode.TRY);
+        (l, r) <- Seq((decimals, smallDecimals), (smallDecimals, decimals),
+          (decimals, (DecimalType(3, 3), Seq(Decimal(BigDecimal("0.007"), 3, 
3)))))) {
+      val ctx = NumericEvalContext(mode, allowLoss)
+      Seq[(Expression, Expression) => Expression](Add(_, _, ctx), Subtract(_, 
_, ctx),
+        Multiply(_, _, ctx), Divide(_, _, ctx)).foreach { build =>
+        val e = build(BoundReference(0, l._1, nullable = true), 
BoundReference(1, r._1,
+          nullable = true))
+        val projection = GenerateUnsafeProjection.generate(Seq(e))
+        for (lv <- l._2 :+ null; rv <- r._2 :+ null) {
+          val row = InternalRow(lv, rv)
+          e.eval(row)
+          projection(row)
+        }
+      }
+    }
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: casts that can not fail") {
+    val s = AttributeReference("s", StringType)()
+    val ts = AttributeReference("ts", TimestampType)()
+    val date = AttributeReference("date", DateType)()
+    def cast(e: Expression, to: DataType, mode: EvalMode.Value): Cast =
+      Cast(e, to, Some("America/Los_Angeles"), mode)
+    // In every mode: a timestamp to a date, and a number or a boolean to a 
string.
+    Seq(EvalMode.ANSI, EvalMode.LEGACY, EvalMode.TRY).foreach { mode =>
+      Seq[(Expression, DataType)]((ts, DateType),
+          (AttributeReference("ntz", TimestampNTZType)(), DateType), (a, 
StringType),
+          (AttributeReference("d", DecimalType(10, 2))(), StringType),
+          (AttributeReference("b", BooleanType)(), StringType)).foreach { case 
(e, to) =>
+        assert(ExprUtils.canEvaluateUnconditionally(cast(e, to, mode)), (e, 
to, mode))
+      }
+    }
+    // Not to a CHAR or VARCHAR, which checks the length.
+    Seq[DataType](CharType(3), VarcharType(3)).foreach { to =>
+      assert(!ExprUtils.canEvaluateUnconditionally(cast(a, to, 
EvalMode.LEGACY)), to)
+      intercept[SparkRuntimeException](cast(Literal(12345L), to, 
EvalMode.LEGACY).eval())
+    }
+    // In LEGACY mode, the casts that return NULL or wrap for a value they can 
not convert.
+    Seq[(Expression, DataType)]((a, IntegerType), (a, ByteType), (a, 
DecimalType(5, 2)),
+        (s, IntegerType), (s, DoubleType), (s, DecimalType(5, 2)), (s, 
BooleanType),
+        (s, DateType), (s, TimestampType), (s, TimestampNTZType)).foreach { 
case (e, to) =>
+      assert(ExprUtils.canEvaluateUnconditionally(cast(e, to, 
EvalMode.LEGACY)), (e, to))
+      assert(!ExprUtils.canEvaluateUnconditionally(cast(e, to, 
EvalMode.ANSI)), (e, to))
+    }
+    // And the other casts `Cast.isNoThrowLegacyCast` accepts.
+    Seq[(Expression, DataType)]((AttributeReference("b", BooleanType)(), 
IntegerType),
+        (a, BooleanType), (s, StringType("UNICODE_CI"))).foreach { case (e, 
to) =>
+      assert(Cast.isNoThrowLegacyCast(e.dataType, to), (e, to))
+      assert(ExprUtils.canEvaluateUnconditionally(cast(e, to, 
EvalMode.LEGACY)), (e, to))
+    }
+    // A date to a timestamp can overflow for a date far from the epoch, also 
in LEGACY mode,
+    // although it is an up-cast.
+    assert(Cast.canUpCast(DateType, TimestampType))
+    val farDate = cast(Literal(Int.MaxValue, DateType), TimestampType, 
EvalMode.LEGACY)
+    assert(!ExprUtils.canEvaluateUnconditionally(cast(date, TimestampType, 
EvalMode.LEGACY)))
+    intercept[ArithmeticException](farDate.eval())
+    // A try_cast to a CHAR or VARCHAR returns NULL for a string that is too 
long.
+    assert(ExprUtils.canEvaluateUnconditionally(cast(a, VarcharType(3), 
EvalMode.TRY)))
+    assert(cast(Literal(12345L), CharType(3), EvalMode.TRY).eval() == null)
+    Seq[DataType](CharType(3), VarcharType(3)).foreach { to =>
+      evalEach(LongType, Seq(12345L, Long.MinValue))(cast(_, to, EvalMode.TRY))
+    }
+    // Not over a child that can fail, in LEGACY mode either.
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      cast(Add(a, a, ansi), IntegerType, EvalMode.LEGACY)))
+    // TRY mode returns NULL for any error of the cast itself, but not of its 
input.
+    assert(ExprUtils.canEvaluateUnconditionally(cast(date, TimestampType, 
EvalMode.TRY)))
+    assert(cast(Literal(Int.MaxValue, DateType), TimestampType, 
EvalMode.TRY).eval() == null)
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      cast(Add(a, a, ansi), IntegerType, EvalMode.TRY)))
+
+    // None of the accepted ones raises.
+    val strings = Seq("", " ", "x", "1e400", "-9" * 30, "9999-99-99", 
"+294247-01-10 04:00:54",
+      "-290308-12-21 19:59:05", "25:61:61", "true", "1e-2147483647", 
"1e2147483647",
+      "-1e-600000000", "0e-600000000").map(UTF8String.fromString)
+    val numbers = Seq[(DataType, Seq[Any])]((LongType, Seq(Long.MinValue, 
Long.MaxValue)),
+      (DoubleType, Seq(Double.NaN, Double.NegativeInfinity, Double.MaxValue)),
+      (FloatType, Seq(Float.NaN, Float.MaxValue)),
+      (DecimalType(38, 0), Seq(Decimal(BigDecimal("9" * 38)))))
+    val integrals = Seq[(DataType, Seq[Any])]((IntegerType, Seq(Int.MinValue, 
Int.MaxValue)),
+      (ShortType, Seq(Short.MinValue, Short.MaxValue)), (ByteType, 
Seq(Byte.MinValue)))
+    for (mode <- Seq(EvalMode.LEGACY, EvalMode.TRY)) {
+      for (to <- Seq(IntegerType, LongType, ShortType, ByteType, FloatType, 
DoubleType,
+          DecimalType(5, 2), DecimalType(38, 0), BooleanType, DateType, 
TimestampType,
+          TimestampNTZType)) {
+        evalEach(StringType, strings)(cast(_, to, mode))
+      }
+      for ((from, values) <- numbers ++ integrals :+ ((BooleanType, Seq(true, 
false)));
+          to <- Seq(ByteType, ShortType, IntegerType, LongType, FloatType, 
DoubleType,
+            DecimalType(5, 2), DecimalType(1, 1), BooleanType)) {
+        evalEach(from, values)(cast(_, to, mode))
+      }
+      // From and to strings of other collations and from a VARCHAR.
+      evalEach(StringType, strings)(cast(_, StringType("UNICODE_CI"), mode))
+      for (from <- Seq(StringType("UTF8_LCASE"), VarcharType(3)); to <- 
Seq(IntegerType,
+          DateType, StringType)) {
+        evalEach(from, strings)(cast(_, to, mode))
+      }
+    }
+    // The numeric widening casts in ANSI mode.
+    for ((from, values) <- integrals :+ ((LongType, Seq(Long.MinValue, 
Long.MaxValue)));
+        to <- Seq(LongType, DoubleType, DecimalType(20, 0)) if 
Cast.canUpCast(from, to)) {
+      evalEach(from, values)(cast(_, to, EvalMode.ANSI))
+    }
+    evalEach(DecimalType(10, 2), Seq(Decimal(BigDecimal("-99999999.99"), 10, 
2)))(
+      cast(_, DecimalType(20, 4), EvalMode.ANSI))
+    // A try_cast of a string to a time or a timestamp with nanoseconds takes 
the LEGACY path.
+    for (to <- Seq(TimeType(6), TimestampNTZNanosType(9), 
TimestampLTZNanosType(9))) {
+      evalEach(StringType, strings)(cast(_, to, EvalMode.TRY))
+    }
+    for (mode <- Seq(EvalMode.ANSI, EvalMode.LEGACY, EvalMode.TRY)) {
+      for ((from, values) <- numbers :+ (BooleanType, Seq(true, false))) {
+        evalEach(from, values)(cast(_, StringType, mode))
+      }
+      for (from <- Seq(TimestampType, TimestampNTZType)) {
+        evalEach(from, Seq(Long.MinValue, 0L, Long.MaxValue))(cast(_, 
DateType, mode))
+      }
+    }
+  }
+
+  test("SPARK-60882: canEvaluateUnconditionally: substring and date and time 
fields") {
+    val s = AttributeReference("s", StringType)()
+    assert(ExprUtils.canEvaluateUnconditionally(Substring(s, Literal(2), 
Literal(3))))
+    assert(!ExprUtils.canEvaluateUnconditionally(Substring(s, Cast(a, 
IntegerType,
+      evalMode = EvalMode.ANSI), Literal(3))))
+    val date = AttributeReference("date", DateType)()
+    val ts = AttributeReference("ts", TimestampType)()
+    val ntz = AttributeReference("ntz", TimestampNTZType)()
+    def dateFields(d: Expression): Seq[Expression] = Seq(Year(d), 
YearOfWeek(d), Quarter(d),
+      Month(d), DayOfMonth(d), DayOfYear(d), DayOfWeek(d), WeekDay(d), 
WeekOfYear(d),
+      MonthName(d), DayName(d))
+    def timeFields(t: Expression): Seq[Expression] = Seq(Hour(t, Some("UTC")),
+      Minute(t, Some("Asia/Tokyo")), Second(t, Some("America/Los_Angeles")),
+      SecondWithFraction(t, Some("UTC")))
+    (dateFields(date) ++ timeFields(ts) ++ timeFields(ntz)).foreach { e =>
+      assert(ExprUtils.canEvaluateUnconditionally(e), e)
+    }
+    // `year(ts)` reads the date of a timestamp, but `year(s)` casts a string 
to a date, which
+    // can fail in ANSI mode.
+    assert(ExprUtils.canEvaluateUnconditionally(
+      EqualTo(Year(Cast(ts, DateType, Some("UTC"), EvalMode.ANSI)), 
Literal(2024))))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      Year(Cast(s, DateType, Some("UTC"), EvalMode.ANSI))))
+    assert(!ExprUtils.canEvaluateUnconditionally(
+      Hour(Cast(s, TimestampType, Some("UTC"), EvalMode.ANSI), Some("UTC"))))
+
+    // None of them raises, also at the ends of the ranges of dates and 
timestamps.
+    dateFields(date).indices.foreach { idx =>
+      evalEach(DateType, Seq(Int.MinValue, 0, Int.MaxValue))(d => 
dateFields(d)(idx))
+    }
+    for (t <- Seq(TimestampType, TimestampNTZType); idx <- 
timeFields(ts).indices) {
+      evalEach(t, Seq(Long.MinValue, 0L, Long.MaxValue))(v => 
timeFields(v)(idx))
+    }
+    val positions = Seq(Int.MinValue, -1, 0, 1, Int.MaxValue)
+    // Also non-ASCII strings, which take another path, and invalid UTF-8.
+    val nonAscii = Seq(0xE9, 'a', 0x4E2D).map(_.toChar).mkString
+    val strings = Seq("", "abc", nonAscii).map(UTF8String.fromString) ++
+      Seq(Array(0xFF, 'a'), Array('a', 0xE2)).map(b => 
UTF8String.fromBytes(b.map(_.toByte)))
+    for (pos <- positions; len <- positions) {

Review Comment:
   Done: the positions and lengths are now input columns, so the loop compiles 
4 projections, and it also covers NULL positions and lengths.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to