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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -39,17 +64,342 @@ 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 too, but can overflow in 
ANSI mode.
+    assert(Cast.canUpCast(DecimalType(19, 0), LongType))

Review Comment:
   Right, thanks. The test now asserts `!Cast.canUpCast(DecimalType(19, 0), 
LongType)`, keeps the check that the cast is rejected and raises in ANSI mode, 
and, with item 3, that `DECIMAL(18, 0)` to `BIGINT`, and likewise `DECIMAL(9, 
0)` to `INT`, `DECIMAL(4, 0)` to `SMALLINT` and `DECIMAL(2, 0)` to `TINYINT`, 
are accepted and evaluated without an error at their largest and smallest 
values.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,13 +294,71 @@ 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, a
+  // decimal to an integral type can overflow in ANSI mode, e.g. DECIMAL(19, 
0) to BIGINT, as
+  // `Cast.nullable` notes.
+  private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from, 
to) match {
+    case (_: DecimalType, _: IntegralType) => false
+    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.left.dataType.isInstanceOf[DecimalType]
+    b.children.forall(_.dataType.isInstanceOf[NumericType]) && (b.evalMode 
match {
+      case EvalMode.LEGACY => b match {
+        case _: Add | _: Subtract | _: Multiply | _: Divide => true

Review Comment:
   Right, done: the two divisions of the SPARK-60980 test are now `Divide(..., 
NumericEvalContext(EvalMode.ANSI))`, so it keeps its meaning in the non-ANSI 
build. `FilterPushdownSuite` passes with `SPARK_ANSI_SQL_MODE=false` too.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,13 +294,71 @@ 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, a
+  // decimal to an integral type can overflow in ANSI mode, e.g. DECIMAL(19, 
0) to BIGINT, as
+  // `Cast.nullable` notes.
+  private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from, 
to) match {
+    case (_: DecimalType, _: IntegralType) => false

Review Comment:
   Done: the decimal to integral exclusion is gone, so the numeric pairs use 
`Cast.canUpCast` as is. The comment, the Scaladoc and the description now say 
that it takes a decimal to an integral type only when every value fits, such as 
`DECIMAL(18, 0)` to `BIGINT`, and the test checks both sides.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,13 +294,71 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
     e.deterministic && !e.containsPattern(PLAN_EXPRESSION) &&

Review Comment:
   Done: the description lists `CombineFilters` among the callers and says that 
it now combines more conjuncts written after a non-deterministic or throwable 
one. A new `FilterPushdownSuite` test checks that an addition and a division 
with ANSI mode off, and a substring, written after `rand(0) > 0.1` or a 
throwable conjunct, are combined into the filter below.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,13 +294,71 @@ 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, a
+  // decimal to an integral type can overflow in ANSI mode, e.g. DECIMAL(19, 
0) to BIGINT, as
+  // `Cast.nullable` notes.
+  private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from, 
to) match {
+    case (_: DecimalType, _: IntegralType) => false
+    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.left.dataType.isInstanceOf[DecimalType]
+    b.children.forall(_.dataType.isInstanceOf[NumericType]) && (b.evalMode 
match {
+      case EvalMode.LEGACY => b match {
+        case _: Add | _: Subtract | _: Multiply | _: Divide => true
+        // `Decimal.quot` and `Decimal.%` raise when the integral quotient is 
too long.
+        case _: IntegralDivide | _: Remainder | _: Pmod => !decimal
+        case _ => false
+      }
+      // `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 EvalMode.TRY => b match {
+        case _: Add | _: Subtract | _: Multiply | _: Divide => true
+        case _: Remainder => !decimal
+        case _ => false
+      }
+      case _ => false
+    })
+  }
+
   private def canEvaluateUnconditionallyInternal(e: Expression): Boolean = e 
match {
     case _: AttributeReference | _: Literal => true
-    case _: GetStructField | _: GetArrayStructFields | _: GetMapValue =>
+    case _: GetStructField | _: GetArrayStructFields | _: GetMapValue | _: 
CreateNamedStruct =>

Review Comment:
   Done: the check now accepts `NoThrow`, so `CreateArray` too, and the special 
case of `CreateNamedStruct` is gone. `ExprUtilsSuite` checks an array 
comparison, and that an array over a child that can fail is rejected. As the 
check now relies on the marker, the test also pins that `CreateMap`, which lost 
it in SPARK-60849, is rejected and raises on a duplicate key, and the `NoThrow` 
doc says that `canEvaluateUnconditionally` relies on it, so that it must not 
raise for any input.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,13 +294,71 @@ 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, a
+  // decimal to an integral type can overflow in ANSI mode, e.g. DECIMAL(19, 
0) to BIGINT, as
+  // `Cast.nullable` notes.
+  private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from, 
to) match {
+    case (_: DecimalType, _: IntegralType) => false
+    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.left.dataType.isInstanceOf[DecimalType]
+    b.children.forall(_.dataType.isInstanceOf[NumericType]) && (b.evalMode 
match {
+      case EvalMode.LEGACY => b match {
+        case _: Add | _: Subtract | _: Multiply | _: Divide => true
+        // `Decimal.quot` and `Decimal.%` raise when the integral quotient is 
too long.
+        case _: IntegralDivide | _: Remainder | _: Pmod => !decimal
+        case _ => false
+      }
+      // `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 EvalMode.TRY => b match {
+        case _: Add | _: Subtract | _: Multiply | _: Divide => true
+        case _: Remainder => !decimal
+        case _ => false
+      }
+      case _ => false
+    })
+  }
+
   private def canEvaluateUnconditionallyInternal(e: Expression): Boolean = e 
match {
     case _: AttributeReference | _: Literal => true
-    case _: GetStructField | _: GetArrayStructFields | _: GetMapValue =>
+    case _: GetStructField | _: GetArrayStructFields | _: GetMapValue | _: 
CreateNamedStruct =>
       e.children.forall(canEvaluateUnconditionallyInternal)
     case _: And | _: Or | _: Not | _: BinaryComparison | _: IsNull | _: 
IsNotNull |
-         _: IsNaN | _: NullIf | _: Coalesce | _: In | _: InSet =>
+         _: IsNaN | _: NullIf | _: Coalesce | _: In | _: InSet | _: Size | _: 
StartsWith |
+         _: EndsWith | _: Contains | _: Length | _: OctetLength | _: Substring 
| _: GetDateField |

Review Comment:
   Agreed that keeping the contract next to the implementations would be 
better, both for the marked expressions and for the eval mode details of the 
arithmetic, such as `DivModLike` and `Pmod` not catching their errors in TRY 
mode. Marking more expressions `NoThrow` would also let 
`ConstantFolding.hasNoSideEffect` fold more, though, so I would like to do both 
in a follow-up, where that can be reviewed on its own.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala:
##########
@@ -805,10 +806,10 @@ class RewriteDistinctAggregatesSuite extends PlanTest {
     val unsafeBases = Seq(
       // Division may throw (e.g. divide-by-zero under ANSI mode) on rows 
where the
       // original IF branch is not taken.
-      Symbol("c") / Symbol("b"),
+      Divide(Symbol("c"), Symbol("b"), NumericEvalContext(EvalMode.ANSI)),
       // Cast may throw under ANSI mode.
-      Cast(Symbol("c"), StringType),
-      // String functions are not in the branch-safe whitelist.
+      Cast(Symbol("d"), IntegerType, evalMode = EvalMode.ANSI),
+      // Lower is not in the branch-safe allowlist.

Review Comment:
   Added: `conditional: rewrite branch-safe expression bases` now also checks a 
LEGACY `Add` and a `Substring` as bases.



-- 
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