sarutak opened a new pull request, #60231:
URL: https://github.com/apache/spark/pull/60231

   ### What changes were proposed in this pull request?
   
   Backport of #60119 to branch-4.x, tailored for it: the changes to 
`InjectRuntimeFilter` and `InjectRuntimeFilterSuite` are left out, since 
SPARK-60702, which made `InjectRuntimeFilter` use 
`ExprUtils.canEvaluateUnconditionally`, is not on branch-4.x. So 
`InjectRuntimeFilter` does not call it on branch-4.x, and this PR does not 
change it.
   
   `ExprUtils.canEvaluateUnconditionally` tells whether an expression can be 
evaluated on rows it would otherwise not see, e.g. outside a short-circuited 
branch. It is an allowlist of deterministic expressions that can not fail: 
columns, literals, struct and map accessors, `AND` / `OR` / `NOT`, comparisons, 
`IS NULL`, `IN` and the like. Its callers are `FilterExec` and the `FILTER 
(WHERE ...)` clause of a code-generated aggregate, which share 
`GeneratePredicateHelper` and use it to decide whether the conjuncts after a 
NULL one have to be evaluated (SPARK-60315), `StreamedSideJoinCondition`, 
which, when the internal `spark.sql.join.splitStreamedSideJoinCondition` is 
enabled (it is off by default), hoists the streamed-side conjuncts of outer, 
anti and existence joins above the probe (SPARK-58066), 
`RewriteDistinctAggregates`, which rewrites `COUNT(DISTINCT IF(...))` with a 
guard over the filters (SPARK-56898), `CombineFilters`, which combines a 
conjunct written after a non-deterministi
 c or throwable one into the filter below only when it can not fail 
(SPARK-60980), `InferFiltersFromConstraints`, which turns a data constraint 
into a filter only when it can not fail (SPARK-60985), and 
`ConstantPropagation`, which rewrites an operand of `AND`, `OR`, `COALESCE` or 
`IN` only if no operand after it can fail, and moves the equalities ahead of 
the other conjuncts when one that can fail still refers to a propagated 
attribute or follows a rewritten one (SPARK-60983, SPARK-61033). 
`ConstantPropagation` also substitutes a constant under the operators that can 
not fail whatever the values of their children, which 
`ExprUtils.isTotalOperator` tells, and on which `canEvaluateUnconditionally` 
builds since SPARK-60983, and into other expressions only when they fold to a 
literal without an error.
   
   This PR adds the following expressions to `ExprUtils.isTotalOperator`, and 
so to the allowlist, each only when its children qualify too. Whether each of 
them can fail depends only on the types of its children, not on their values:
   - `Size`, which returns -1 or NULL for a NULL input;
   - `StartsWith`, `EndsWith` and `Contains`, which do not raise for any 
collation, unlike `LIKE` and `RLIKE`, which raise on an invalid pattern, and 
`Length` and `OctetLength`, which only count characters or bytes: 
`LikeSimplification` rewrites `LIKE 'abc%'` to a `StartsWith`, and `LIKE 
'ab%c'` to a `StartsWith` and an `EndsWith` guarded by a `Length` or an 
`OctetLength` check;
   - `Collate`, which an explicit `COLLATE` builds, and which only changes the 
collation in the type of a string, with its collation, which evaluates to its 
name;
   - the expressions marked `NoThrow`, `CreateArray` and `CreateNamedStruct`, 
which only build a value from their children, as `ConstantFolding` assumes for 
them too;
   - `Substring`, which returns an empty string for a position out of range;
   - the fields of a date or a timestamp (`GetDateField` and `GetTimeField`, 
e.g. `year`, `month`, `hour`), which only read the date or time of a valid 
value;
   - the casts that can not fail:
     - in every mode: a cast that only widens a numeric type (`Cast.canUpCast` 
over numeric types, such as the `INT` to `BIGINT` cast that type coercion adds 
to a comparison), which includes a decimal to an integral type only when every 
value fits, such as `DECIMAL(18, 0)` to `BIGINT` (SPARK-60943); a cast of a 
decimal to a `FLOAT` or `DOUBLE`, which rounds, such as the one type coercion 
adds to `amount > 1e3` over a decimal column; a cast of a timestamp to a date; 
and a cast of a number other than a `FLOAT` or `DOUBLE`, a boolean or a string 
to a `STRING` of any collation, such as the one `CollationTypeCoercion` adds to 
the other side of a comparison or a string search with an explicit `COLLATE`, 
but not to a `CHAR` or `VARCHAR`, which checks the length;
     - in LEGACY mode, i.e. with ANSI mode off, the casts that return NULL, 
wrap or clamp for a value they can not convert: the ones 
`Cast.isNoThrowLegacyCast` (SPARK-60868) accepts, between numbers, booleans and 
strings, except to a `CHAR` or `VARCHAR`, and from a string to a date or a 
timestamp, whose parsers catch their errors;
     - in TRY mode (`try_cast`), every other cast: it either catches the errors 
of the cast or, from a string to a fractional or datetime type, runs the LEGACY 
cast.
   
     Outside TRY mode, a cast of a date to a timestamp is left out, although 
`Cast.canUpCast` accepts it, since converting a date far from the epoch to 
microseconds overflows also in LEGACY mode, and so are the other casts, such as 
of a date or a timestamp to a string, which this PR does not check. In every 
mode, a cast of a value with a `FLOAT` or `DOUBLE` in it to a type with a 
`STRING` or `VARIANT` in it is left out, also in LEGACY and TRY mode, although 
such a cast to a `STRING` or `VARIANT` can not fail: `-0.0 = 0.0` holds, but 
`CAST(-0.0 AS STRING)` is `'-0.0'`. `InferFiltersFromConstraints` replaces `y` 
with `x` under `x = y`, and `ConstantPropagation` replaces `x` with `0.0` under 
`x = 0.0`, under the operators this check accepts, so accepting it would, for 
example, infer `CAST(x AS STRING) = '-0.0'` from `x = y AND CAST(y AS STRING) = 
'-0.0'` and drop a row with `x` = 0.0 and `y` = -0.0. SPARK-61139 tracks fixing 
this at the rules, where `ConstantPropagation` already folds `
 x = 0.0 AND CAST(x AS STRING) = '-0.0'` to false, after which this exclusion 
can go. For the same reason, every cast from or to a type with a user-defined 
type in it is left out, as a UDT renders its value with its own 
`stringifyValue`, e.g. an MLlib vector of -0.0 as `'[-0.0]'`, or a Python UDT 
as its `sqlType`, and the checks do not look inside it. Strings of a non-binary 
collation, which can also be equal but differ, are already guarded by both 
rules, which replace them only as a direct operand of a comparison. Outside TRY 
mode, and in TRY mode from a string, which runs the LEGACY cast, the casts from 
or to a decimal of a negative scale, which 
`spark.sql.legacy.allowNegativeScaleOfDecimal` allows, other than the widenings 
between decimals and the casts to a `FLOAT` or `DOUBLE`, are left out too, as 
`Decimal.toLong` raises `ArrayIndexOutOfBoundsException` for one, e.g. in a 
LEGACY cast of a `DECIMAL(3, -2)` to a `BIGINT`, and in every mode so is the 
binary arithmetic over one, as 
 `Decimal.%` raises an `ArithmeticException` for a very negative one. 
`UnaryMinus` and `Abs` only negate one and are kept;
   - numeric arithmetic outside ANSI mode, which returns NULL on a division by 
zero or a decimal overflow, and wraps an integral overflow in LEGACY mode and 
returns NULL for it in TRY mode: `Add`, `Subtract`, `Multiply`, `Divide`, 
`IntegralDivide`, `Remainder`, `Pmod`, `UnaryMinus` and `Abs` in LEGACY mode, 
and in TRY mode (`try_add` and the like) the five that do not raise there: 
`Add`, `Subtract` and `Multiply` catch their errors, and `Divide` and 
`Remainder` check a zero divisor only in ANSI mode, while `IntegralDivide` and 
`Pmod` check it in TRY mode too and do not catch the error. This includes 
`IntegralDivide`, `Remainder` and `Pmod` over decimals, which no longer raise 
`ArithmeticException: Division impossible` when the integral quotient has more 
digits than the `MathContext` of `Decimal` holds, e.g. for a `DECIMAL(38, 0)` 
and a `DECIMAL(3, 3)`, since SPARK-61050. Arithmetic over intervals is left 
out, which over a DAY TO SECOND or YEAR TO MONTH interval overflows in every mod
 e;
   - in every mode, also in ANSI mode: `Add`, `Subtract` and `Multiply` over 
`FLOAT` and `DOUBLE`, which return an infinity or NaN rather than raising, and 
`UnaryMinus` and `Abs` over `FLOAT`, `DOUBLE` and `DECIMAL`, which only check 
for an overflow over the integral types.
   
   `TryEval`, which `try_add` and the like build over non-numeric types, is 
left out: its child can be a UDF, which `FilterExec` must not evaluate on more 
rows, and subexpression elimination does not stop at it, so it can move a part 
of the child that raises out of the `try`. With its child checked, accepting it 
would accept nothing that its child does not already.
   
   ### Why are the changes needed?
   
   The allowlist rejects these expressions although they can not fail, so its 
callers handle them as if they could: `FilterExec` keeps the NULL-conjunct flag 
for them, and `StreamedSideJoinCondition`, when enabled, does not hoist e.g. `a 
+ 1 > 0` with ANSI mode off, `price * 1.1 > 100` over a `DOUBLE` column or 
`substr(s, 1, 4) = '2024'`. PR #59940 (SPARK-60730) uses the same check to 
decide which filter conditions written after an expensive one may still be 
pushed below a projection; there it keeps conditions such as `year(dt) = 2024` 
or, with ANSI mode off, `a + 1 > 0` above the projection, which then lose their 
pushdown to the scan and their partition pruning, with no gain. The additions 
of `Size`, `StartsWith`, `EndsWith`, `Contains`, `Length`, `OctetLength`, the 
struct and the numeric widening casts come from that PR, which will be rebased 
on #60119. SPARK-60985 also notes that `InferFiltersFromConstraints` no longer 
infers some filters that can not fail, such as `LIKE 'a%'`, `y
 ear(d) = 2024` and arithmetic with ANSI mode off, and that widening 
`canEvaluateUnconditionally` brings them back; this PR does so.
   
   ### Does this PR introduce _any_ user-facing change?
   
   No change in the results of deterministic queries that do not fail. The 
callers above apply their optimizations to more expressions: `FilterExec` and 
the `FILTER` clause of a code-generated aggregate generate the code without the 
NULL-conjunct flag, and keep the lazy placement of the `IS NOT NULL` checks, 
for more conditions, `StreamedSideJoinCondition`, when enabled, hoists more 
streamed-side conjuncts, which it then evaluates once per streamed row, also on 
rows without a match, `RewriteDistinctAggregates` rewrites more `COUNT(DISTINCT 
IF(...))` aggregates and guards more `COUNT(DISTINCT ...) FILTER (WHERE ...)` 
aggregates, `InferFiltersFromConstraints` infers more filters, such as `year(d) 
= 2024` or `LIKE 'a%'`, also on the other side of a join, where they can reach 
a data source or partition pruning, `ConstantPropagation` substitutes constants 
into more expressions, e.g. `y = 5 AND x > z + y` with ANSI mode off becomes `y 
= 5 AND x > z + 5`, rewrites more operands of `AND`, `O
 R`, `COALESCE` and `IN`, and moves the equalities first in fewer conditions, 
as fewer conjuncts can fail, and `CombineFilters` combines more conjuncts 
written after a non-deterministic or throwable one into the filter below, so 
that one is evaluated on fewer rows: a seeded `rand()` can then pick other 
rows, and a `raise_error` that only the rows the moved conjunct drops reached 
no longer raises, as SPARK-60980 intends for the conjuncts that can not fail. 
So some optimized and physical plans and some generated code change. The 
migration guide entry of SPARK-60985 and the doc of 
`spark.sql.legacy.inferFailableFiltersFromConstraints` now give `upper(s) = 
'A'` as a filter that can not fail but is not inferred, instead of `LIKE 'a%'`, 
`year(d) = 2024` and arithmetic with ANSI mode off, which are inferred again, 
and the migration guide entry and the doc qualify their examples of filters 
that can fail, such as `10 / x > 0`, with ANSI mode, since numeric arithmetic 
is inferred with ANSI mod
 e off, and `+`, `-` and `*` over `FLOAT` and `DOUBLE` in ANSI mode too. With 
this PR, `InferFiltersFromConstraints` no longer needs its own case for the 
numeric widening casts, so this PR removes it.
   
   ### How was this patch tested?
   
   New tests in `ExprUtilsSuite`:
   - each added expression accepted, the arithmetic and the casts that can fail 
in ANSI mode left out there, and each new case left out over a child that can 
fail; `IntegralDivide` and `Pmod` in TRY mode, interval arithmetic, also 
`UnaryMinus` and `Abs` over intervals, a cast of a date to a timestamp in 
LEGACY mode, a cast of a number to a `CHAR` or `VARCHAR` and a cast of a 
`DECIMAL(19, 0)` to a `BIGINT` left out, with a check that they do raise, and 
`IntegralDivide`, `Remainder` and `Pmod` over a `DECIMAL(38, 0)` and a 
`DECIMAL(3, 3)`, the casts of a decimal to an integral type whose values all 
fit, such as `DECIMAL(18, 0)` to `BIGINT`, and an array accepted, but not a 
map, which raises on a NULL key or, by default, a duplicate key; in ANSI mode, 
`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` accepted, but not `Divide`, `Remainder` and `Pmod` over 
doubles, `Add
 ` over decimals or over the integral types, and `UnaryMinus` over the integral 
types, or a cast of a decimal to a narrower decimal, which raises; a `Collate` 
and a cast of a string to a `STRING` of another collation accepted, but not a 
`Collate` over a child that can fail, or a cast of a string to a `CHAR` or 
`VARCHAR` in ANSI mode, which raises; a cast of a `FLOAT` or `DOUBLE`, also in 
an array, a struct or a map, to a string, a collated string, an array or a 
struct or a map of strings, or a variant, left out in every mode, with a check 
that `-0.0 = 0.0` holds while their strings differ, but a cast of a `DOUBLE` to 
a number or a boolean accepted in LEGACY and TRY mode; a cast from or to a 
decimal of a negative scale left out outside TRY mode and from a string in TRY 
mode, and `Remainder` over one left out also in TRY mode, with a check that a 
cast of a `DECIMAL(3, -2)` to a `BIGINT` and `Remainder` over a `DECIMAL(1, 
-2147483000)` raise, but a widening of one to a `DECIMAL(10, 0)`,
  a `DECIMAL(3, -3)` to a `DECIMAL(5, -2)`, a `DECIMAL(1, -36)` to a 
`DECIMAL(38, 0)` and a cast of one to a `FLOAT` or `DOUBLE` accepted and 
evaluated in every mode, and `UnaryMinus` and `Abs` over one accepted; a cast 
from or to a UDT, also in an array or a struct, left out in every mode;
   - each accepted arithmetic expression and cast evaluated without an error, 
with and without code generation, over nullable and non-nullable input columns 
of every numeric type, on NULL and on the values that raise in ANSI mode: zero 
divisors, `Long.MinValue` and `-1`, the largest decimals and a small one that 
makes a quotient overflow, also between decimals of different precisions and 
scales and without precision loss, NaN and infinities, invalid and out-of-range 
strings, such as exponents of `1e-2147483647` and `1e2147483647`, also for a 
`try_cast` to a time, a timestamp with nanoseconds, a `CHAR` or a `VARCHAR`, 
and the ends of the ranges of dates and timestamps; the numeric widening casts, 
`Add`, `Subtract` and `Multiply` over `FLOAT` and `DOUBLE`, `UnaryMinus` and 
`Abs` over `FLOAT`, `DOUBLE` and `DECIMAL`, and the casts of decimals to 
`FLOAT` and `DOUBLE` and of strings, `VARCHAR`s and `CHAR`s to a `STRING` of 
another collation in ANSI mode too, `Collate`, and the date and ti
 me fields and `Substring`, also over non-ASCII and invalid UTF-8 strings, with 
positions and lengths at `Int.MinValue`, `Int.MaxValue` and NULL;
   - `StartsWith`, `EndsWith`, `Contains`, `Length` and `OctetLength` evaluated 
without an error, with and without code generation, over binary, lowercase, ICU 
and trim collations on empty, ignorable and invalid UTF-8 strings.
   
   Existing tests that used arithmetic or a cast as an expression that can 
fail, in `RewriteDistinctAggregatesSuite`, 
`SplitStreamedSideJoinConditionSuite`, `WholeStageCodegenSuite` and the 
SPARK-60980 test of `FilterPushdownSuite`, now set ANSI mode, or use a cast 
that can fail, since the expression is accepted with ANSI mode off; one of them 
used a cast of an integer to a string, which can not fail. 
`SplitStreamedSideJoinConditionSuite` now also checks that an addition with 
ANSI mode off is hoisted, `WholeStageCodegenSuite` that a filter with it has no 
NULL-conjunct flag, `FilterPushdownSuite` that `CombineFilters` combines an 
addition or a division with ANSI mode off, a multiplication of doubles in ANSI 
mode, a substring and a `Contains` over a `COLLATE`, with the cast to the 
collation that analysis adds to the other side, written after a 
non-deterministic or throwable conjunct, `RewriteDistinctAggregatesSuite` that 
such an addition and a substring are rewritten as bases, `InferFi
 ltersFromConstraintsSuite` that a `year`, a `LIKE 'a%'` simplified to a 
`StartsWith`, an addition with ANSI mode off and a multiplication of doubles in 
ANSI mode are inferred as filters, and a `year` also on the other side of a 
join, and a comparison through the widening of a `DECIMAL(3, -2)` to a 
`DECIMAL(10, 0)` with negative scales allowed, but not an `upper`, an addition 
in ANSI mode, a cast of a `DOUBLE` to a string, a `try_cast` of a UDT to a 
string or a `length` of a string of a trim collation, and 
`ConstantPropagationSuite` that a constant is substituted into an addition with 
ANSI mode off and under a `COLLATE`, but not into an addition with ANSI mode 
on, where the equality goes first, or into a cast of a `DOUBLE` to a string or 
a `length` of a string of a trim collation.
   
   Each of these mutants fails at least one test, run on master, whose tests of 
this change are the same apart from `InjectRuntimeFilterSuite`, which none of 
them needs: accepting `IntegralDivide` and `Pmod` in TRY mode, accepting 
arithmetic over non-numeric types or in ANSI mode, accepting a cast of a date 
to a timestamp in LEGACY mode or every cast in LEGACY mode, dropping the casts 
of `Cast.isNoThrowLegacyCast` or of a string to a date or a timestamp in LEGACY 
mode, accepting the LEGACY casts in ANSI mode, accepting a cast of a number to 
a string only in LEGACY mode or also to a `CHAR` or `VARCHAR`, rejecting a 
decimal to an integral type that `Cast.canUpCast` accepts, accepting only 
`CreateNamedStruct` of the `NoThrow` expressions, rejecting `Remainder`, or 
`IntegralDivide` and `Pmod`, over decimals, dropping the numeric widening 
casts, not checking the children of arithmetic, `Abs`, a struct, a cast in TRY 
mode or `Substring`, ignoring `failOnError` of `UnaryMinus` and `Abs` ove
 r integral types, or honoring it over fractional types, accepting `UnaryMinus` 
or `Abs` over a non-numeric type, not checking the child of `Collate`, 
accepting a cast of a string to a `STRING` only outside ANSI mode, dropping the 
casts of a decimal to a `FLOAT` or `DOUBLE` or the arithmetic over `FLOAT` and 
`DOUBLE` in ANSI mode, and, in ANSI mode, accepting other arithmetic over them 
or arithmetic over decimals too, accepting a cast of a decimal to any 
fractional type, including a narrower decimal, dropping `Collate` or the 
collation as a leaf, dropping the exclusion of the casts of a `FLOAT` or 
`DOUBLE` to a string or a variant, or applying it only to the top-level types 
or not to a variant, keeping the operators from before this change in the 
`isTotalOperator` case of `ConstantPropagation`, dropping the date fields, 
which `InferFiltersFromConstraintsSuite` also catches, dropping the exclusion 
of decimals of a negative scale from the casts, applying it only to the source 
type, or 
 before the widenings or the casts to a `FLOAT` or `DOUBLE`, or not to a string 
in TRY mode, or dropping it from the arithmetic, accepting the casts of a UDT, 
and dropping the collation guards of `ConstantPropagation` or 
`InferFiltersFromConstraints`.
   
   On branch-4.x, with ANSI mode on and with `SPARK_ANSI_SQL_MODE=false`, all 
tests in `org.apache.spark.sql.catalyst.optimizer` and `ExprUtilsSuite`, and 
`PlanStabilitySuite`s, `SplitStreamedSideJoinConditionSuite`, 
`ExistenceJoinSuite`, `OuterJoinSuite`, `WholeStageCodegenSuite`, 
`DataFrameAggregateSuite`, `DataFrameSuite`, 
`RewriteDistinctAggregatesConditionalQuerySuite`, the `MergeIntoTableSuite`s, 
`CollationSuite`, `CollationSQLFunctionsSuite`, `CollationSQLRegexpSuite`, 
`SubquerySuite`, `JoinSuite`, `ExplainSuite`, `InjectRuntimeFilterSuite`, 
`AdaptiveQueryExecSuite`, `DatasetSuite`, `KeyGroupedPartitioningSuite`, 
`ColumnarDataSourceSuite`, the `StreamingV2ScanPushDown` suites and 
`SQLQueryTestSuite` pass, with no golden plan changes, except one 
`WholeStageCodegenSuite` test with ANSI mode off, `SPARK-60403: MergeRows 
compiles with its function spilled to a nested class`, which also fails on 
branch-4.x without this change.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Kiro CLI
   


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