viirya commented on code in PR #60469:
URL: https://github.com/apache/spark/pull/60469#discussion_r4569619240
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -564,6 +582,27 @@ trait Nondeterministic extends Expression {
protected def evalInternal(input: InternalRow): Any
}
+/**
+ * Trait to indicate the expression does not throw an exception by itself when
they are evaluated.
+ * For example, UDFs, [[AssertTrue]], etc can throw an exception when they are
executed.
+ * In such case, it is necessary to call [[Expression.eval]], and the
optimization rule should
+ * not ignore it.
+ *
+ * This trait can be used in an optimization rule such as
+ * [[org.apache.spark.sql.catalyst.optimizer.ConstantFolding]] to fold the
expressions that
+ * do not need to execute, for example, `size(array(c0, c1, c2))`. That rule
only does so for
+ * [[CreateArray]] and [[CreateNamedStruct]] for now.
+ *
+ * Mixing it in is a promise by the author of the expression that it is always
total, as
+ * [[Expression.isTotal]] defines it: it must not raise for any input of its
children, in any eval
+ * mode, and it must give equal results for equal children of a binary-stable
type. The promise
+ * covers every subclass of the expression that mixes it in. An expression
that is total only
+ * for some input types or in some eval modes overrides [[Expression.isTotal]]
instead.
+ */
+trait NoThrow extends Expression {
+ final override def isTotal: Boolean = true
Review Comment:
Good point. I took the second option: `NoThrow` is now mixed into the six
comparisons and the date and time field expressions, and no longer into
`BinaryComparison`, `GetDateField` or `GetTimeField`, so a new subclass is not
total unless it says so. I kept `final`, so that an expression marked `NoThrow`
is always total. The class scan in `ExprUtilsSuite` now also checks that no
abstract class is marked.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -564,6 +582,27 @@ trait Nondeterministic extends Expression {
protected def evalInternal(input: InternalRow): Any
}
+/**
+ * Trait to indicate the expression does not throw an exception by itself when
they are evaluated.
+ * For example, UDFs, [[AssertTrue]], etc can throw an exception when they are
executed.
+ * In such case, it is necessary to call [[Expression.eval]], and the
optimization rule should
+ * not ignore it.
+ *
+ * This trait can be used in an optimization rule such as
+ * [[org.apache.spark.sql.catalyst.optimizer.ConstantFolding]] to fold the
expressions that
+ * do not need to execute, for example, `size(array(c0, c1, c2))`. That rule
only does so for
+ * [[CreateArray]] and [[CreateNamedStruct]] for now.
+ *
+ * Mixing it in is a promise by the author of the expression that it is always
total, as
+ * [[Expression.isTotal]] defines it: it must not raise for any input of its
children, in any eval
+ * mode, and it must give equal results for equal children of a binary-stable
type. The promise
+ * covers every subclass of the expression that mixes it in. An expression
that is total only
+ * for some input types or in some eval modes overrides [[Expression.isTotal]]
instead.
+ */
+trait NoThrow extends Expression {
Review Comment:
Added a note to the PR description about both: a type that is not an
`Expression` cannot mix it in any more, and an expression outside Spark that
mixes it in is no longer skipped by `ConstantFolding`. One detail: such an
expression was already accepted by `isTotalOperator` before this PR, which
matched `_: NoThrow`, so that part is not new.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -583,6 +589,145 @@ class ExprUtilsSuite extends SparkFunSuite with SQLHelper
{
}
}
+ test("isTotalOperator: the expressions that are always total are marked
NoThrow") {
+ val s = AttributeReference("s", StringType)()
+ val b = AttributeReference("b", BooleanType)()
+ val d = AttributeReference("d", DoubleType)()
+ val date = AttributeReference("date", DateType)()
+ val ts = AttributeReference("ts", TimestampType)()
+ val field = StructField("f", LongType)
+ val struct = AttributeReference("st", StructType(Seq(field)))()
+ val arr = AttributeReference("arr", ArrayType(struct.dataType))()
+ val map = AttributeReference("m", MapType(LongType, LongType))()
+ val always = Seq[Expression](
+ GetStructField(struct, 0), GetArrayStructFields(arr, field, 0, 1,
containsNull = true),
+ GetMapValue(map, a), CreateArray(Seq(a)),
CreateNamedStruct(Seq(Literal("f"), a)),
+ Collate(s, ResolvedCollation("UNICODE_CI")),
+ And(b, b), Or(b, b), Not(b), EqualTo(a, a), EqualNullSafe(a, a),
LessThan(a, a),
+ LessThanOrEqual(a, a), GreaterThan(a, a), GreaterThanOrEqual(a, a),
+ IsNull(a), IsNotNull(a), IsNaN(d), new NullIf(a, a), Coalesce(Seq(a, a)),
+ In(a, Seq(Literal(1L))), InSet(a, Set[Any](1L)),
+ Size(arr, legacySizeOfNull = true), Size(arr, legacySizeOfNull = false),
+ StartsWith(s, s), EndsWith(s, s), Contains(s, s), Length(s),
OctetLength(s),
+ Substring(s, Literal(1), Literal(2)),
+ Year(date), YearOfWeek(date), Quarter(date), Month(date),
DayOfMonth(date),
+ DayOfYear(date), DayOfWeek(date), WeekDay(date), WeekOfYear(date),
MonthName(date),
+ DayName(date), Hour(ts, Some("UTC")), Minute(ts, Some("UTC")),
Second(ts, Some("UTC")),
+ SecondWithFraction(ts, Some("UTC")))
+ always.foreach { e =>
+ assert(e.isInstanceOf[NoThrow], e)
+ assert(e.isTotal, e)
+ assert(ExprUtils.isTotalOperator(e), e)
+ }
+ // An expression that says nothing is not total, whatever it does. Neither
are the leaves,
+ // which `canEvaluateUnconditionally` accepts by itself.
+ val undeclared = Seq[Expression](a, Literal(1L), GetArrayItem(arr,
Literal(0)),
+ ElementAt(arr, Literal(1)), CreateMap(Seq(a, a)), Like(s, s, '\\'),
RLike(s, s), Upper(s),
+ If(b, a, a), CaseWhen(Seq((b, a)), a), UnaryPositive(a), BitwiseAnd(a,
a), BitwiseOr(a, a),
+ BitwiseXor(a, a), BitwiseNot(a), Rand(Literal(0L)))
+ undeclared.foreach { e =>
+ assert(!e.isInstanceOf[NoThrow], e)
+ assert(!e.isTotal, e)
+ assert(!ExprUtils.isTotalOperator(e), e)
+ }
+ }
+
+ test("isTotalOperator: the expressions that are total in some eval modes or
over some types") {
+ val (legacyMode, ansiMode, tryCast) = (EvalMode.LEGACY, EvalMode.ANSI,
EvalMode.TRY)
+ val d = AttributeReference("d", DoubleType)()
+ val dec = AttributeReference("dec", DecimalType(10, 2))()
+ val s = AttributeReference("s", StringType)()
+ val date = AttributeReference("date", DateType)()
+ val interval = AttributeReference("i", DayTimeIntervalType())()
+ def modesOf(build: EvalMode.Value => Expression): Set[EvalMode.Value] =
+ Seq(legacyMode, ansiMode, tryCast).filter { mode =>
+ val e = build(mode)
+ assert(!e.isInstanceOf[NoThrow], e)
+ assert(ExprUtils.isTotalOperator(e) === e.isTotal, e)
+ e.isTotal
+ }.toSet
+ val all = Set(legacyMode, ansiMode, tryCast)
+ val none = Set.empty[EvalMode.Value]
+ def ctx(mode: EvalMode.Value): NumericEvalContext =
NumericEvalContext(mode)
+
+ // Add, Subtract and Multiply: outside ANSI mode, and over FLOAT and
DOUBLE in every mode.
+ Seq[(Expression, Expression, NumericEvalContext) => Expression](Add(_, _,
_),
+ Subtract(_, _, _), Multiply(_, _, _)).foreach { build =>
+ assert(modesOf(m => build(a, a, ctx(m))) === Set(legacyMode, tryCast))
+ assert(modesOf(m => build(dec, dec, ctx(m))) === Set(legacyMode,
tryCast))
+ assert(modesOf(m => build(d, d, ctx(m))) === all)
+ assert(modesOf(m => build(interval, interval, ctx(m))) === none)
+ }
+ // Divide and Remainder: outside ANSI mode, also over FLOAT and DOUBLE.
+ Seq[(Expression, Expression, NumericEvalContext) => Expression](Divide(_,
_, _),
+ Remainder(_, _, _)).foreach { build =>
+ assert(modesOf(m => build(d, d, ctx(m))) === Set(legacyMode, tryCast))
+ assert(modesOf(m => build(dec, dec, ctx(m))) === Set(legacyMode,
tryCast))
+ }
+ // IntegralDivide and Pmod: only in LEGACY mode.
+ Seq[(Expression, Expression, NumericEvalContext) =>
Expression](IntegralDivide(_, _, _),
+ Pmod(_, _, _)).foreach { build =>
+ assert(modesOf(m => build(a, a, ctx(m))) === Set(legacyMode))
+ assert(modesOf(m => build(interval, a, ctx(m))) === none)
+ }
+ // UnaryMinus and Abs: over the integral types without `failOnError`, and
over the fractional
+ // types with it too.
+ Seq[(Expression, Boolean) => Expression](UnaryMinus(_, _), Abs(_,
_)).foreach { build =>
+ assert(build(a, false).isTotal && !build(a, true).isTotal)
+ Seq(d, dec).foreach(x => assert(build(x, false).isTotal && build(x,
true).isTotal, x))
+ assert(!build(interval, false).isTotal && !build(interval, true).isTotal)
+ }
+ // Cast: by the types and the eval mode.
+ def castModes(from: Expression, to: DataType): Set[EvalMode.Value] =
+ modesOf(m => Cast(from, to, Some("UTC"), m))
+ assert(castModes(a, DecimalType(20, 0)) === all)
+ assert(castModes(dec, DoubleType) === all)
+ assert(castModes(a, StringType) === all)
+ assert(castModes(a, IntegerType) === Set(legacyMode, tryCast))
+ assert(castModes(s, LongType) === Set(legacyMode, tryCast))
+ assert(castModes(s, DateType) === Set(legacyMode, tryCast))
+ assert(castModes(date, TimestampType) === Set(tryCast))
+ assert(castModes(a, VarcharType(3)) === Set(tryCast))
+ assert(castModes(d, StringType) === none)
+ assert(castModes(AttributeReference("u", new TestUDT.MyDenseVectorUDT)(),
StringType) === none)
+ }
+
+ test("isTotalOperator: the expression classes that declare themselves
total") {
+ // Every expression class of catalyst, from its jar or its classes
directory.
+ val root = new
File(classOf[Expression].getProtectionDomain.getCodeSource.getLocation.toURI)
+ val files: Seq[String] = if (root.isDirectory) {
+ def walk(f: File): Seq[File] =
+ if (f.isDirectory) f.listFiles().toSeq.flatMap(walk) else Seq(f)
+ walk(root).map(f => root.toURI.relativize(f.toURI).getPath)
+ } else {
+ SparkErrorUtils.tryWithResource(new
JarFile(root))(_.entries().asScala.map(_.getName).toList)
+ }
+ val classes: Seq[Class[_]] = files.filter(_.endsWith(".class")).map { path
=>
+ val name = path.stripSuffix(".class").replace('/', '.')
+ Utils.classForName[Any](name, initialize = false)
Review Comment:
Done for the loading: a class that fails with a `LinkageError` or
`ClassNotFoundException` is skipped, and the test is canceled if the code
source is null. I kept the scan over all of catalyst instead of the
`expressions` package, because the test is there to notice a subclass of a
marked class wherever it is, and catalyst has expressions in other packages,
e.g. under `analysis`.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -64,7 +64,10 @@ object ConstantFolding extends Rule[LogicalPlan] {
hasNoSideEffect(c.child)
case _ => false
}
- case _: NoThrow if e.deterministic => e.children.forall(hasNoSideEffect)
+ // Only these two of the expressions marked `NoThrow`, as before the other
expressions that
Review Comment:
Filed SPARK-61667 and added the TODO here, and a note in the new test of
`ConstantFoldingSuite` that those cases become foldable with it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -268,13 +268,14 @@ 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 an allowlist of total, deterministic expressions qualifies:
+ * Only total, deterministic expressions qualify. Each expression declares
whether it is total
+ * itself, with [[Expression.isTotal]], so there is no list to keep here;
the ones that do are:
Review Comment:
Agreed. I trimmed it: the leaves are now described as accepted here without
a declaration, the rest points to `Expression.isTotal` and the class lists in
`ExprUtilsSuite`, and only the notes that are not on an expression are kept
(the look-alikes that are not total, and the equal-results requirement).
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala:
##########
@@ -174,6 +183,15 @@ case class Abs(child: Expression, failOnError: Boolean =
SQLConf.get.ansiEnabled
override def dataType: DataType = child.dataType
+ // It checks for an overflow only over the integral types, and only when
`failOnError` is set.
+ // Over a DAY TO SECOND or YEAR TO MONTH interval, it can overflow in every
mode, and intervals
+ // are left out.
+ override def isTotal: Boolean = child.dataType match {
Review Comment:
Shared the unary one in `UnaryArithmetic.isTotal`. For the binary ones I
kept one line per class over the shared `hasTotalNumericOperands` and
`hasFloatOrDoubleOperands`, so that each class still states its own condition
next to its `eval`.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -615,6 +615,108 @@ object Cast extends QueryErrorsBase {
case _ => false
}
+ /**
+ * Returns true if a cast from `from` type to `to` type in `evalMode` is
total, as
+ * [[Expression.isTotal]] defines it: it never fails at runtime, and it
gives equal results for
+ * equal values. The patterns matched reflect the current implementation in
the Cast node and
+ * must stay in sync with it.
+ *
+ * A cast of a value with a FLOAT or DOUBLE in it to a type with a STRING or
a VARIANT in it is
+ * left out whether or not it can fail, as it tells -0.0 from 0.0, which are
equal. So is every
+ * cast from or to a type with a UDT in it, which renders its value with its
own
+ * `stringifyValue`, or a Python UDT as its `sqlType`, which can tell apart
values that are
+ * equal, and the checks here do not look inside it. The target is checked
too, defensively,
+ * although only a UDT or a NULL can be cast to one.
+ *
+ * Among the other casts, the result is the union of the ones that can not
fail in any eval mode
+ * and of the ones that can not fail in `evalMode`, so it does not depend on
the order of the
+ * checks.
+ */
+ def isTotalCast(from: DataType, to: DataType, evalMode: EvalMode.Value):
Boolean =
+ !tellsSignedZeros(from, to) && !hasUserDefinedType(from) &&
!hasUserDefinedType(to) &&
+ (cannotFailInAnyMode(from, to) || cannotFailInMode(from, to, evalMode))
+
+ // Whether the source type has a FLOAT or DOUBLE and the target type a
STRING or VARIANT in it,
+ // so that the cast may keep the sign of a zero, e.g. -0.0 as '-0.0'. This
is conservative: it
+ // does not match the fields of the types.
+ private def tellsSignedZeros(from: DataType, to: DataType): Boolean =
+ from.existsRecursively(t => t == FloatType || t == DoubleType) &&
+ to.existsRecursively(t => t.isInstanceOf[StringType] || t == VariantType)
+
+ // `existsRecursively` does not look inside a UDT, so neither does this.
+ private def hasUserDefinedType(dt: DataType): Boolean =
+ dt.existsRecursively(_.isInstanceOf[UserDefinedType[_]])
+
+ /**
+ * Returns true if the type has a decimal of a negative scale in it
+ * (`spark.sql.legacy.allowNegativeScaleOfDecimal`).
+ */
+ private[expressions] def hasNegativeScale(dt: DataType): Boolean =
dt.existsRecursively {
+ case d: DecimalType => d.scale < 0
+ case _ => false
+ }
+
+ // The casts that can not fail in any eval mode, also in ANSI mode.
+ private def cannotFailInAnyMode(from: DataType, to: DataType): Boolean =
+ // A numeric up-cast holds also from or to a decimal of a negative scale,
as a widening between
+ // decimals never calls `Decimal.toLong`; a change to a negative scale
only checks that
+ // `spark.sql.legacy.allowNegativeScaleOfDecimal` is on. So does a decimal
to a FLOAT or a
+ // DOUBLE. The other ones do not: `Decimal.toLong` raises for a decimal of
a negative scale.
+ isNumericUpCast(from, to) || isDecimalToFloatOrDouble(from, to) ||
+ (!hasNegativeScale(from) && !hasNegativeScale(to) &&
+ (isTimestampToDate(from, to) || isToPlainString(from, to)))
+
+ // The casts that can not fail in the given eval mode but can in another
one: outside ANSI mode,
+ // the casts that return NULL, wrap or clamp for a value they can not
convert.
+ private def cannotFailInMode(from: DataType, to: DataType, evalMode:
EvalMode.Value): Boolean = {
+ val negativeScale = hasNegativeScale(from) || hasNegativeScale(to)
+ evalMode match {
+ // TRY mode catches the errors of the cast, but not from a string, which
runs the LEGACY
+ // cast, and that one raises for a decimal of a negative scale.
+ case EvalMode.TRY => !negativeScale || !from.isInstanceOf[StringType]
+ // 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.
+ case EvalMode.LEGACY =>
+ !negativeScale && (isStringToDatetime(from, to) ||
isNoThrowLegacyCast(from, to))
+ case EvalMode.ANSI => false
+ }
+ }
+
+ // Only the numeric pairs are taken from `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) => canUpCast(from, to)
+ case _ => false
+ }
+
+ // `Decimal.toDouble` and `Decimal.toFloat` round through a `BigDecimal`,
also for a negative
+ // scale, and do not check the range in ANSI mode.
+ private def isDecimalToFloatOrDouble(from: DataType, to: DataType): Boolean
= (from, to) match {
+ case (_: DecimalType, FloatType | DoubleType) => true
+ case _ => false
+ }
+
+ private def isTimestampToDate(from: DataType, to: DataType): Boolean =
(from, to) match {
+ case (TimestampType | TimestampNTZType, DateType) => true
+ case _ => false
+ }
+
+ // A CHAR or VARCHAR target checks the length of the string. A string to a
STRING of another
+ // collation, as `CollationTypeCoercion` adds for an explicit `COLLATE`,
keeps the value.
+ private def isToPlainString(from: DataType, to: DataType): Boolean = (from,
to) match {
Review Comment:
Done, `isNoThrowLegacyCast` reuses it.
--
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]