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

   ### What changes were proposed in this pull request?
   
   `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), and 
`RewriteDistinctAggregates`, which rewrites `COUNT(DISTINCT IF(...))` with a 
guard over the filters (SPARK-56898).
   
   This PR adds the following expressions to the allowlist, each only when its 
children qualify too:
   - `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;
   - `CreateNamedStruct`, which only builds a struct from its fields;
   - `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), other than a decimal to an integral type, which 
`Cast.canUpCast` accepts but which can overflow in ANSI mode, e.g. `DECIMAL(19, 
0)` to `BIGINT`; 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;
     - in LEGACY mode, i.e. with ANSI mode off, the casts that return NULL, 
wrap or clamp for a value they can not convert: between numbers, and from a 
string to a number, a boolean, a date or a timestamp;
     - in TRY mode (`try_cast`), every 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;
   - numeric arithmetic outside ANSI mode, which returns NULL on a division by 
zero or a decimal overflow and wraps an integral overflow: `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. `IntegralDivide`, `Remainder` and `Pmod` over decimals are left out in 
every mode, since `Decimal.quot` and `Decimal.%` raise `ArithmeticException: 
Division impossible` when the integral quotient has more digits than their 
`MathContext` holds, e.g. for a `DECIMAL(38, 0)` and a `DECIMAL(3, 3)`, and so 
is arithmetic over intervals, which overflows in every mode.
   
   `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 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 this one.
   
   ### Does this PR introduce _any_ user-facing change?
   
   No change in query results. 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, 
and `RewriteDistinctAggregates` rewrites more `COUNT(DISTINCT IF(...))` 
aggregates and guards more `COUNT(DISTINCT ...) FILTER (WHERE ...)` aggregates, 
so some optimized and physical plans and some generated code change.
   
   ### How was this patch tested?
   
   New tests in `ExprUtilsSuite`:
   - each added expression accepted, and left out in ANSI mode, and each new 
case left out over a child that can fail; `IntegralDivide` and `Pmod` in TRY 
mode, `IntegralDivide`, `Remainder` and `Pmod` over decimals, interval 
arithmetic, a cast of a date to a timestamp in LEGACY mode and a cast of a 
number to a `CHAR` or `VARCHAR` left out, with a check that they do raise;
   - 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 
in ANSI mode too, and the date and time fields and `Substring`, also over 
non-ASCII and invalid UTF-8 strings, with positions and lengths at 
`Int.MinValue` and `Int.MaxValue`;
   - `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` and `WholeStageCodegenSuite`, 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, and `WholeStageCodegenSuite` that a filter with 
it has no NULL-conjunct flag.
   
   Each of these mutants fails at least one test: 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, 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`, 
accepting a decimal to an integral type, accepting `IntegralDivide`, 
`Remainder` or `Pmod` over decimals, or `Remainder` over decimals in TRY mode, 
dropping the numeric widening casts, not checking the children of arithmetic, 
`Abs`, a struct, a cast in TRY mode or `Substring`, and ignoring `failOnError` 
of `UnaryMinus`.
   
   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` and `CollationSQLRegexpSuite` 
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 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