spark-test commented on code in PR #60119:
URL: https://github.com/apache/spark/pull/60119#discussion_r4505214076
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,20 +307,113 @@ 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 {
+ // Left out whether or not it can fail, as it may tell -0.0 from 0.0: see
+ // `canEvaluateUnconditionally`.
+ case (from, to) if tellsSignedZeros(from, to) => false
+ // TRY mode catches the errors of the cast, but not from a string, which
runs the LEGACY cast.
+ case (from, to) if hasNegativeScale(from) || hasNegativeScale(to) =>
+ c.evalMode == EvalMode.TRY && !from.isInstanceOf[StringType]
+ case (from, to) if isNumericUpCast(from, to) => true
+ // `Decimal.toDouble` and `Decimal.toFloat` round, and do not check the
range in ANSI mode.
+ case (_: DecimalType, FloatType | DoubleType) => true
+ case (TimestampType | TimestampNTZType, DateType) => true
+ // 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.
+ case (_: NumericType | BooleanType | _: StringType, 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 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) &&
Review Comment:
**Blocking (P1):** `tellsSignedZeros` finds a `FLOAT` or `DOUBLE` through
`existsRecursively`, which `UserDefinedType` does not override, so it never
sees the doubles in a UDT's `sqlType`. A `try_cast` of such a UDT to a string
then reaches the TRY catch-all on line 335 and is accepted.
`UnsafeRowUtils.isBinaryStable` does not look inside the UDT either, so
`InferFiltersFromConstraints` replaces one UDT column with an equal one under
that cast.
For example, with default configs, take two MLlib vector columns holding `a
= [0.0]` and `b = [-0.0]`:
```sql
SELECT * FROM t WHERE a = b AND try_cast(b AS STRING) = '[-0.0]'
```
`a = b` holds, since UDT equality uses the `sqlType` ordering, where `-0.0 =
0.0`, so the query should return the row. The rule infers `try_cast(a AS
STRING) = '[-0.0]'`, which renders `a` with `DenseVector.toString` as
`'[0.0]'`, so the inferred filter drops the row. An inner join on `l.a = r.b
AND try_cast(r.b AS STRING) = '[-0.0]'` drops rows of `l` the same way. The
base branch accepts no cast here and returns the row. Python UDTs over doubles
are affected too, and so are UDTs over a string of a non-binary collation,
which `isBinaryStable` cannot see either.
A UDT renders its value with its own `stringifyValue`, which nothing ties to
the equality of its `sqlType`. So rejecting every cast from a type that
contains a UDT, in every mode, closes this, for example next to the
`tellsSignedZeros` case:
```scala
// A UDT renders its value with its own `stringifyValue`, which can tell
apart values that
// compare equal, and the checks below do not look inside it.
case (from, _) if
from.existsRecursively(_.isInstanceOf[UserDefinedType[_]]) => false
```
The base branch accepted none of these casts, so nothing that worked there
changes.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60119#issuecomment-6713425247).
**Verification:**
- **Regression:** Take two vector columns holding [0.0] and [-0.0] and a
query that filters on their equality and on a try_cast of one of them to a
string. The query returns the row, and constraint inference adds no string
filter on the other column.
- **Behavior:** The check rejects a TRY, LEGACY or ANSI cast to a string of
a UDT, of an array of UDTs and of a struct containing one. The cast pairs it
accepts for types without a UDT stay accepted.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,20 +307,113 @@ 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 {
+ // Left out whether or not it can fail, as it may tell -0.0 from 0.0: see
+ // `canEvaluateUnconditionally`.
+ case (from, to) if tellsSignedZeros(from, to) => false
+ // TRY mode catches the errors of the cast, but not from a string, which
runs the LEGACY cast.
+ case (from, to) if hasNegativeScale(from) || hasNegativeScale(to) =>
Review Comment:
**Non-blocking (P2):** This case comes before the numeric up-cast case on
line 327, so outside TRY mode it also rejects the up-casts that involve a
decimal of a negative scale. With
`spark.sql.legacy.allowNegativeScaleOfDecimal` on, those are widenings between
decimals, such as `DECIMAL(3, -2)` to `DECIMAL(10, 0)`, since a decimal to an
integral type is an up-cast only with scale 0. These widenings can not fail in
any mode: the widening branch of `Decimal.changePrecision` only multiplies by a
power of ten or switches to a `BigDecimal`, and never calls `Decimal.toLong`.
On the base branch, `InferFiltersFromConstraints` stripped every numeric
up-cast before its check. So for a join `t.n = s.m`, with `n` a `DECIMAL(3,
-2)` and `m` a `DECIMAL(10, 0)`, it inferred `CAST(n AS DECIMAL(10, 0)) > 5`
for `t` from `m > 5`. This PR removes that strip, so the filter is no longer
inferred and no longer reaches the scan or the partition pruning of `t`.
`InjectRuntimeFilter` keeps its own up-cast stand-in and still accepts these
casts, so the two checks now disagree on the same expression. The migration
guide's statement that filters on widening numeric casts are still inferred
does not hold for them either.
Testing the up-cast first keeps every rejection the new tests assert, since
a `DECIMAL(3, -2)` to a `BIGINT`, a `BIGINT` to a `DECIMAL(3, -2)` and a string
to a `DECIMAL(3, -2)` are not up-casts:
```scala
case (from, to) if tellsSignedZeros(from, to) => false
// A widening between decimals never calls `Decimal.toLong`, also from a
negative scale.
case (from, to) if isNumericUpCast(from, to) => true
// TRY mode catches the errors of the cast, but not from a string, which
runs the LEGACY cast.
case (from, to) if hasNegativeScale(from) || hasNegativeScale(to) =>
c.evalMode == EvalMode.TRY && !from.isInstanceOf[StringType]
```
The Scaladoc sentence on negative scales would then keep the widenings
between decimals.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60119#issuecomment-6713425247).
**Verification:**
- **Regression:** With negative-scale decimals allowed, join a DECIMAL(3,
-2) column with a DECIMAL(10, 0) column and filter on the latter. The
corresponding filter is inferred on the other side through the widening cast,
as on the base branch.
- **Behavior:** The check accepts decimal-to-decimal widenings from or to a
negative scale in every mode. It still rejects the negative-scale casts that
can raise: to integral types, from integral types and from strings.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,20 +307,113 @@ 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 {
+ // Left out whether or not it can fail, as it may tell -0.0 from 0.0: see
+ // `canEvaluateUnconditionally`.
+ case (from, to) if tellsSignedZeros(from, to) => false
+ // TRY mode catches the errors of the cast, but not from a string, which
runs the LEGACY cast.
+ case (from, to) if hasNegativeScale(from) || hasNegativeScale(to) =>
+ c.evalMode == EvalMode.TRY && !from.isInstanceOf[StringType]
+ case (from, to) if isNumericUpCast(from, to) => true
+ // `Decimal.toDouble` and `Decimal.toFloat` round, and do not check the
range in ANSI mode.
+ case (_: DecimalType, FloatType | DoubleType) => true
+ case (TimestampType | TimestampNTZType, DateType) => true
+ // 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.
+ case (_: NumericType | BooleanType | _: StringType, 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 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)
+
+ private def hasNegativeScale(dt: DataType): Boolean = dt.existsRecursively {
+ case d: DecimalType => d.scale < 0
+ case _ => false
+ }
+
+ // Whether numeric arithmetic can not fail, in its own eval mode.
+ private def cannotFailArithmetic(b: BinaryArithmetic): Boolean = {
+ b.children.forall(isNumericOfNonNegativeScale) && (b match {
+ // Over FLOAT and DOUBLE, they do not check for an overflow, also in
ANSI mode. Divide,
+ // Remainder and Pmod raise on a zero divisor in ANSI mode, also over
them.
+ case _: Add | _: Subtract | _: Multiply if
b.children.forall(isFloatOrDouble) => true
+ case _ if b.evalMode == EvalMode.ANSI => false
+ case _: Add | _: Subtract | _: Multiply | _: Divide | _: Remainder =>
true
Review Comment:
**Non-blocking (P2):** With ANSI mode off, this line and the LEGACY cast arm
on line 341 accept arithmetic and casts that the SPARK-60702 tests in
`InjectRuntimeFilterSuite` use as keys and creation sides that can fail.
`InjectRuntimeFilter.cannotFail` builds on `canEvaluateUnconditionally`, so it
now adds bloom filters for them. The tests build these expressions from SQL in
the session's mode, and `withDppTestConf` does not set ANSI mode.
So in the scheduled non-ANSI build, which sets `SPARK_ANSI_SQL_MODE=false`,
the key `bf5part.f5 + 1` in
```sql
select * from bf5part join bf2 on bf5part.f5 + 1 = bf2.c2 where bf2.a2 = 36
```
is a LEGACY `Add`. The rule then adds the same bloom filter that "add bloom
filter for a key with a dropped dpp filter under a numeric up-cast" expects for
a key that can not fail, and `assert(bloomFilterKeys(query).isEmpty)` fails.
The int to tinyint, float to int, long to int, decimal to bigint and string to
int casts in the other SPARK-60702 tests flip the same way. The PR's CI runs
with ANSI mode on, so it does not show these failures, and no test covers the
keys and creation sides that `InjectRuntimeFilter` now accepts.
Running those tests with `SQLConf.ANSI_ENABLED.key -> "true"`, as
`WholeStageCodegenSuite` now does for its raising case, keeps their meaning in
both builds. A case where `f5 + 1` with ANSI mode off gets a bloom filter would
then cover the new behavior.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60119#issuecomment-6713425247).
**Verification:**
- **Regression:** With the ANSI default off, as in the non-ANSI build, the
bloom-filter tests for keys and creation sides that can fail still pass,
because their expressions are built in a mode where they fail.
- **Behavior:** With ANSI mode off, a join key such as `f5 + 1` on a
partition column whose DPP filter is dropped gets a bloom filter, and the query
returns the same rows as without 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]