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

   ### What changes were proposed in this pull request?
   
   Backport of #60363 and its follow-up #60557 to `branch-4.2`.
   
   The master commit does not cherry-pick: on master the fix goes into 
`GeneratePredicateHelper.generatePredicateCode`, which SPARK-61556 made the 
single implementation of the predicate code with and without subexpression 
elimination (CSE). `branch-4.2` has neither SPARK-61556 nor SPARK-60332 (which 
moved each common subexpression's evaluation to the first conjunct that 
references it). On `branch-4.2` the CSE branch of `FilterExec.doConsume` still 
generates the conditions in its own loop, so this PR applies the same approach 
to that loop:
   
   - The eager evaluation of every input column that the conditions read, at 
the top of the row loop (`inputVarsEvalCode`), is removed.
   - The CSE states are generated with `ctx.currentVars` swapped for copies of 
`input` whose code is blank (restored in a `finally`), as master's 
`subExprStatesToEliminate` does, so no state takes a column's code into its own 
code or into `exprCodesNeedEvaluate`, and `input` keeps its code for the loads 
below. As #60557 does on master, `exprCodesNeedEvaluate`, which is then always 
empty, is asserted to be empty and is not emitted, so the slot where 
`inputVarsEvalCode` was is removed. The assertion message does not point to 
`subExprStatesToEliminate`, which `branch-4.2` does not have, and the comment 
next to it names only `ProjectExec` as evaluating its states up front, since 
`ExpandExec` on `branch-4.2` does not eliminate common subexpressions.
   - In the CSE loop, each condition now loads the columns it references with 
`evaluateRequiredVariables`, after its `IsNotNull` checks and before the CSE 
states it first references, the same place `generatePredicateCode` loads them. 
A state first referenced by a condition is part of that condition, so it reads 
a subset of the condition's columns. A column already loaded by an earlier 
check or condition is not loaded again, since `evaluateRequiredVariables` 
clears the code it emits.
   
   The common subexpressions themselves, and where each is evaluated, do not 
change. The CSE gate (take the CSE branch only with a non-cheap common 
subexpression) is kept. As on master, the comment on the gate, the doc of the 
internal config `spark.sql.subexpressionElimination.filterExec.enabled`, and 
the test comments no longer justify the gate by the eager evaluation; the gate 
comment now names the cost of the states instead, with the wording #60557 
corrected it to (an inline state adds no local variable; only the split adds a 
method and up to two mutable fields per common subexpression). The comments 
describing the order of the checks, the column loads and the states in the CSE 
loop and in `generatePredicateCode` are updated for the column loads.
   
   ### Why are the changes needed?
   
   With whole-stage codegen and the default configs, a filter whose conditions 
share a non-cheap common subexpression can fail where the same filter with 
`spark.sql.subexpressionElimination.filterExec.enabled=false` returns rows: 
when an input column that the child computes lazily raises on a row that an 
earlier check or condition drops. Reproducer:
   
   ```scala
   import org.apache.spark.sql.functions._
   val f = udf((x: Long) => x)
   val r = udf((x: Long) => { if (x <= 5) throw new 
IllegalStateException(s"r($x)"); x })
   spark.range(10).select(f($"id").as("f"), r($"id").as("r"))
     .where("f >= 0 AND f + 1 > 6 AND f + 1 < 100 AND r > 0").collect()
   // before: [FAILED_EXECUTE_UDF] ... java.lang.IllegalStateException: r(0)
   // after:  6, 7, 8, 9
   // before, with spark.sql.subexpressionElimination.filterExec.enabled=false: 
6, 7, 8, 9
   ```
   
   The filter stays above the projection because its conditions read the UDF 
aliases (`spark.sql.optimizer.avoidDoubleFilterEval`, on by default since 
4.2.0), and the common `f + 1` makes it take the CSE branch, which computed `r` 
up front, before `f + 1 > 6` dropped the rows with `id <= 5`. Unlike master, 
`branch-4.2` has no `spark.sql.optimizer.splitProjectionForExpensiveFilters`, 
so this happens with the default configs. It was measured on the 4.2.1 release 
(`local[1]`). The eager evaluation was added by SPARK-56032 (4.2.0); 4.0 and 
4.1 do not have the CSE branch and return `6, 7, 8, 9`.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes, a bug fix. With whole-stage codegen, 
`spark.sql.subexpressionElimination.enabled` and 
`spark.sql.subexpressionElimination.filterExec.enabled` on (all default), a 
filter whose conditions share a non-cheap common subexpression now computes 
each input column just before the first condition that reads it, as the code 
without elimination already does, instead of up front. For an input column 
whose code the child leaves lazy (an alias that the child projection computes, 
such as a UDF result, or a column decoded from the child's row or batch):
   
   - A query like the one above returns rows instead of failing, when the 
column raised on a row an earlier check or condition drops. A query that still 
fails can raise a different error: with `g(f) + 1 > 6 AND g(f) + 1 < 100 AND r 
> 0` over the same projection, where the UDF `g` raises for `f <= 5`, the 4.2.1 
release raised `r(0)` and this PR raises `g(0)`, the same as with the config 
off (one partition).
   - A UDF or other computation behind such a column is no longer invoked, and 
such a column is no longer decoded, on rows an earlier check or condition drops.
   
   The rows returned change only for a query that failed before. Where the 
common subexpressions are evaluated does not change, so a query whose failure 
comes from a common subexpression first referenced in a conditional branch of 
an earlier condition still fails with the config on (SPARK-60774).
   
   ### How was this patch tested?
   
   The `SPARK-61377` test, as #60557 left it on master, is added to 
`WholeStageCodegenSuite`, without the 
`spark.sql.optimizer.splitProjectionForExpensiveFilters=false` setting, which 
`branch-4.2` does not have. `WholeStageCodegenSuite` passes on `branch-4.2` (53 
tests), and the `SPARK-61377` test also passes with `SPARK_ANSI_SQL_MODE=false`.
   
   Each of these mutants of the CSE branch fails the `SPARK-61377`, 
`SPARK-56032` or `SPARK-56431` tests: loading every input column of the 
conditions up front, as before this PR (`r(0)` from the `SPARK-61377` test); 
generating the states over `input` itself, or over copies that keep the code of 
the columns (with the states split, the new assertion fails; kept inline, the 
generated code does not compile); not loading the columns of each condition; 
loading them after the states the condition first references; and loading them 
before the `IsNotNull` checks of the condition (the last shape of the 
`SPARK-61377` test, `r(0)`).
   
   For a column decoded from the child's batch, the generated code of `a + 1 > 
6 AND a + 1 < 100 AND b > ''` over a Parquet table `(a bigint, b string)` was 
checked: the 4.2.1 release reads `b` before the `a + 1 < 100` check, and this 
PR reads it after.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Kiro CLI 3.3.0 (Claude Opus 5.5)
   


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