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


##########
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),
+      // String functions are not in the branch-safe allowlist.

Review Comment:
   Done, thanks.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -247,15 +247,42 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
    * branch of an If/CaseWhen, or hoisting a streamed-side join conjunct above 
the probe
    * so it also runs for streamed rows that have no match.
    *
-   * Only a whitelist of total, deterministic expressions qualifies:
+   * Only an allowlist of total, deterministic expressions qualifies:
    *   - leaves: attribute references and literals;
    *   - total accessors: GetStructField, GetArrayStructFields and GetMapValue 
never throw.
    *     Note that GetArrayItem/ElementAt are NOT included: they throw on 
invalid ordinals
    *     when ANSI mode is on;
+   *   - CreateNamedStruct, which only builds a struct from its fields;
    *   - logic/predicates: And, Or, Not, comparisons, IsNull, IsNotNull, 
IsNaN, NullIf,
-   *     Coalesce, In and InSet are total boolean functions.
-   * Anything else (arithmetic, casts, string functions, UDFs, nested IF/CASE 
WHEN, ...)
-   * conservatively returns false. On top of the whitelist, the expression 
must be
+   *     Coalesce, In and InSet are total boolean functions;
+   *   - Size, which returns -1 or NULL for a NULL input rather than raising;
+   *   - StartsWith, EndsWith and Contains, which are total for every 
collation, unlike Like
+   *     and RLike, which raise on an invalid pattern;
+   *   - Length and OctetLength, which only count the characters or bytes of a 
string or binary,
+   *     and with which `LikeSimplification` guards a StartsWith and an 
EndsWith;
+   *   - Substring, which returns an empty string for a position out of range;
+   *   - the fields of a date or a timestamp, such as Year and Hour 
(GetDateField and
+   *     GetTimeField), which only read the date or time of a valid value;
+   *   - in every mode: a cast that widens a numeric type to another one 
(`Cast.canUpCast`),
+   *     such as the INT to BIGINT cast that type coercion adds to a 
comparison, other than a
+   *     decimal to an integral type, which can overflow; a cast of a 
timestamp to a date; and a
+   *     cast of a number or a boolean to a STRING, not to a CHAR or VARCHAR, 
which checks the
+   *     length;
+   *   - outside ANSI mode, the casts that return NULL, wrap or clamp for a 
value they can not
+   *     convert: in LEGACY mode, between numbers and from a string to a 
number, a boolean, a
+   *     date or a timestamp; in TRY mode (`try_cast`), every cast, which 
either catches the
+   *     errors of the cast or, from a string to a fractional or datetime 
type, runs the LEGACY
+   *     cast;
+   *   - outside ANSI mode, numeric arithmetic, which returns NULL on a 
division by zero or a
+   *     decimal overflow and wraps an integral overflow: in LEGACY mode, Add, 
Subtract,

Review Comment:
   Right, done: the scaladoc and the description now say that an integral 
overflow wraps in LEGACY mode and returns NULL in TRY mode.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -39,17 +64,321 @@ 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))
+    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)))))
+  }
+
+  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)))

Review Comment:
   Added: `UnaryMinus` and `Abs` with `failOnError = false` over a `DAY TO 
SECOND` and a `YEAR TO MONTH` interval are rejected, and raise on the minimum 
value. Dropping either numeric check now fails the suite.



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