spark-test commented on code in PR #60363:
URL: https://github.com/apache/spark/pull/60363#discussion_r4546465093
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -618,6 +621,11 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
case _ =>
}
}
+ // The common subexpressions first referenced here are part of
this conjunct, and
+ // the ones they contain read a subset of their columns, so
the columns of the
+ // conjunct cover the ones they read.
+ parts.append(
+ evaluateRequiredVariables(child.output, input,
orig.references))
Review Comment:
**Nit (P3):** This call runs once per condition, and `genNotNull` also calls
it for each IS NOT NULL check. The helper walks every input and evaluates
`ev.code.nonEmpty` before `required.contains(attributes(i))`
(WholeStageCodegenExec.scala:308), and `Block.nonEmpty` re-runs
`code.stripMargin(c).trim` on each call (javaCode.scala:143-155). Every column
whose code is still deferred, both those later conditions read and those only
the parent reads, is therefore rendered about once per condition, where the old
prologue rendered it once. The IS NOT NULL checks now see more pending columns
too. This is driver-side work, paid on each generation of the stage rather than
per row, and the generated code doesn't need it, because only this condition's
own references can be emitted here.
**Recommended change:** In `CodegenSupport.evaluateRequiredVariables`, test
whether a column is required before testing whether its code is empty. Look up
the column's attribute in constant time, for example from an indexed copy of
`attributes` or by walking `attributes` and `variables` together, so list-typed
outputs do not pay an O(i) lookup per column.
**Why this works:** `required.contains` is a constant-time lookup, while
`ev.code.nonEmpty` renders the code. With `required` tested first, a call
renders only the code of columns it may emit. The CSE branch's per-condition
calls and its IS NOT NULL checks then stop re-rendering every pending column,
and the generated code and its order stay the same.
**Scope:** Reorder the two checks in the shared helper that emits deferred
column code. This reduces code-generation work for both FilterExec branches and
the helper's other callers without changing generated code.
**Compatibility:** The generated code of every operator, including the order
in which deferred columns are emitted and cleared.
**Risks:** Every whole-stage codegen operator that calls the helper does
less code-generation work. The generated code is identical, and restoring the
old check order rolls the change back.
**Constraints:** Emit and clear the same columns' code in the same order as
today. Read each column's attribute in constant time; calling `attributes(i)`
for every column on a List-typed output would add quadratic work.
**Success:** `evaluateRequiredVariables` renders a column's code only when
that column is required. The generated Java source of every operator is
unchanged. Generating a CSE-branch filter no longer renders each pending input
column's code once per condition.
**Verification:**
- **Inspection:** The helper tests that a column is required before
rendering or testing its code, reads each column's attribute in constant time,
and emits and clears exactly the same columns in the same order as before, so
generated code is unchanged for every caller.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -487,45 +488,47 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
// without consulting `isNull_X`. The (b) interleaving gives us that
ordering
// for free, since the IsNotNull check fires before the CSE
precompute keyed
// off the same reference.
- // Only take the CSE path when there is actually a common subexpression to
eliminate. That
- // path emits the `inputVarsEvalCode` prologue below, which eagerly
evaluates every
- // `otherPreds` input column at the top of the row loop -- required so
eliminated
- // subexpressions can be materialized into shared variables, but it
defeats the
- // short-circuiting the non-CSE path gets from loading columns lazily,
just before the
- // predicate that needs them. With no common subexpression the prologue is
pure overhead
- // (e.g. decoding a decimal column for rows a cheaper earlier predicate
would reject), so we
- // fall back to `generatePredicateCode`.
+ // (d) Input columns: the code of each input column a check reads is
emitted just before
+ // that check, as in `generatePredicateCode`, so a column, e.g. an
alias the child
+ // projection computes, is not computed on a row an earlier check
drops. The CSE
+ // analysis is run with the columns' code hidden so it does not move
it, see below.
+ // Only take the CSE path when there is actually a common subexpression to
eliminate. With
+ // no common subexpression the CSE path saves nothing, so we fall back to
+ // `generatePredicateCode`.
//
// A *cheap* common subexpression does not count either. Caching a cheap
load saves nothing:
- // the non-CSE path already loads each column lazily into a variable on
demand, so taking the
- // CSE path for it would only add the eager prologue that decodes every
referenced column up
- // front. Note bare columns never reach this point:
`EquivalentExpressions` skips
- // `LeafExpression`s (which includes `BoundReference`/`Attribute`), and
+ // the non-CSE path already loads each column lazily into a variable on
demand. Note bare
+ // columns never reach this point: `EquivalentExpressions` skips
`LeafExpression`s (which
+ // includes `BoundReference`/`Attribute`), and
// `splitConjunctivePredicates` feeds each conjunct to a separate
`addExprTree` call, so a
// column repeated across conjuncts (e.g. the `c >= lo` / `c <= hi` that
`c BETWEEN lo AND hi`
// lowers to) is never recorded as a common subexpression. The
cheap-but-recorded case is a
// shared *non-leaf* such as a struct field access -- `s.x > 5 AND s.x <
100` shares
// `GetStructField(s, x)` -- which is just a slot read. Require a
non-cheap common
- // subexpression (per `CollapseProject.isCheap`) so such filters keep the
lazy,
- // short-circuiting path and only genuine repeated computation takes the
CSE path.
+ // subexpression (per `CollapseProject.isCheap`) so such filters keep the
non-CSE path and
+ // only genuine repeated computation takes the CSE path.
//
// `subexpressionElimination.filterExec.enabled` additionally gates this
path so it can be
// turned off independently of subexpression elimination elsewhere.
- val (prologueCode, predicateCode) =
+ val predicateCode =
if (conf.subexpressionEliminationEnabled &&
conf.subexpressionEliminationFilterExecEnabled &&
otherPreds.nonEmpty &&
otherPredsEquivalentExpressions.getCommonSubexpressions
.exists(!CollapseProject.isCheap(_))) {
- // Pre-evaluate input variables before CSE analysis: CSE clears
- // ctx.currentVars[i].code as a side effect; without this
pre-evaluation, Janino
- // fails when otherPreds reference the same input columns that CSE
already
- // consumed.
- val otherPredInputAttrs =
AttributeSet(otherPreds.flatMap(_.references))
- val inputVarsEvalCode = evaluateRequiredVariables(
- child.output, input, otherPredInputAttrs)
-
+ // Hide the code of the input columns from the CSE analysis, and put
it back after. When
+ // it generates a common subexpression, the code of each column the
subexpression reads is
+ // copied into the subexpression's code (and, when the subexpressions
are split into
+ // functions, into `exprCodesNeedEvaluate`), and the analysis then
clears that code in
+ // `input`. This branch emits neither, so without hiding the code a
conjunct before the
+ // first use of the subexpression would read a column that is not
declared yet, and two
+ // subexpressions reading the same column would declare it twice. With
the code put back,
+ // each column is computed just before the first check that reads it,
see (d), and the
+ // subexpressions read the variable of the column.
+ val inputCode = input.map(_.code)
Review Comment:
**Non-blocking (P2):** With a lazy `input` this line doesn't snapshot
anything. `CodegenSupport.consume` forces a `LazyList` or `Stream` of output
variables but passes that same collection on as `input`
(WholeStageCodegenExec.scala:183-184 and 213). In Scala 2.13.18, `LazyList.map`
defers each `f(head)`, and `zip` pulls the mapped elements only while the
`foreach` on line 531 traverses them. That happens after line 528 has set every
code to `EmptyBlock`, so each column comes back as `EmptyBlock`; for a
`Stream`, whose `map` evaluates only its head, every column after the first
does.
Reading the code, this plan reaches the branch with default configs:
```scala
spark.range(100)
.select(LazyList(col("id"), (col("id") * 2).as("x"), rand(1).as("r")): _*)
.filter(col("x") + 1 > 5 && col("x") + 1 < 100)
```
The `LazyList` projection list survives analysis and planning into
ProjectExec, `rand` keeps the filter above the projection, and the shared `x +
1` is not cheap, so the CSE branch runs. With `x`'s code lost, the
per-condition `evaluateRequiredVariables` emits nothing for it, and the `x + 1`
state, both conditions and the output row read a variable that is never
declared. Janino rejects the class. The stage then falls back to interpreted
execution, which also computes every projection column before the filter, or
the query fails with `spark.sql.codegen.fallback=false` and in tests. The old
prologue declared `x` before the analysis, so the same plan ran under
whole-stage codegen. Strict sequences (`ArraySeq`, `List`, `Vector`) are
unaffected. Materializing the snapshot before the codes are blanked fixes it:
```suggestion
val inputCode = input.map(_.code).toIndexedSeq
```
**Verification:**
- **Regression:** A filter whose child projection is built from a LazyList
of columns runs as one whole-stage codegen stage on the CSE branch without a
compile failure. The projection includes a computed alias that the conditions
read through a shared non-cheap subexpression, placed after the first projected
column, and a nondeterministic column that keeps the filter above it. The
filter returns the same rows as with the FilterExec subexpression-elimination
config off. The same holds when the projection is built from a Stream of
columns, whose first element keeps its code even without the fix, so only an
alias after it shows the failure.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -487,45 +488,47 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
// without consulting `isNull_X`. The (b) interleaving gives us that
ordering
// for free, since the IsNotNull check fires before the CSE
precompute keyed
// off the same reference.
- // Only take the CSE path when there is actually a common subexpression to
eliminate. That
- // path emits the `inputVarsEvalCode` prologue below, which eagerly
evaluates every
- // `otherPreds` input column at the top of the row loop -- required so
eliminated
- // subexpressions can be materialized into shared variables, but it
defeats the
- // short-circuiting the non-CSE path gets from loading columns lazily,
just before the
- // predicate that needs them. With no common subexpression the prologue is
pure overhead
- // (e.g. decoding a decimal column for rows a cheaper earlier predicate
would reject), so we
- // fall back to `generatePredicateCode`.
+ // (d) Input columns: the code of each input column a check reads is
emitted just before
Review Comment:
**Nit (P3):** With (d) added, the list's lead-in at line 460 ("...
interleaving. Three invariants:") undercounts it. It should say "Four
invariants:", or drop the number.
**Verification:**
- **Inspection:** The lead-in of FilterExec.doConsume's invariant list
agrees with the number of items it introduces.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -487,45 +488,47 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
// without consulting `isNull_X`. The (b) interleaving gives us that
ordering
// for free, since the IsNotNull check fires before the CSE
precompute keyed
// off the same reference.
- // Only take the CSE path when there is actually a common subexpression to
eliminate. That
- // path emits the `inputVarsEvalCode` prologue below, which eagerly
evaluates every
- // `otherPreds` input column at the top of the row loop -- required so
eliminated
- // subexpressions can be materialized into shared variables, but it
defeats the
- // short-circuiting the non-CSE path gets from loading columns lazily,
just before the
- // predicate that needs them. With no common subexpression the prologue is
pure overhead
- // (e.g. decoding a decimal column for rows a cheaper earlier predicate
would reject), so we
- // fall back to `generatePredicateCode`.
+ // (d) Input columns: the code of each input column a check reads is
emitted just before
+ // that check, as in `generatePredicateCode`, so a column, e.g. an
alias the child
+ // projection computes, is not computed on a row an earlier check
drops. The CSE
+ // analysis is run with the columns' code hidden so it does not move
it, see below.
+ // Only take the CSE path when there is actually a common subexpression to
eliminate. With
+ // no common subexpression the CSE path saves nothing, so we fall back to
+ // `generatePredicateCode`.
//
// A *cheap* common subexpression does not count either. Caching a cheap
load saves nothing:
- // the non-CSE path already loads each column lazily into a variable on
demand, so taking the
- // CSE path for it would only add the eager prologue that decodes every
referenced column up
- // front. Note bare columns never reach this point:
`EquivalentExpressions` skips
- // `LeafExpression`s (which includes `BoundReference`/`Attribute`), and
+ // the non-CSE path already loads each column lazily into a variable on
demand. Note bare
+ // columns never reach this point: `EquivalentExpressions` skips
`LeafExpression`s (which
+ // includes `BoundReference`/`Attribute`), and
// `splitConjunctivePredicates` feeds each conjunct to a separate
`addExprTree` call, so a
// column repeated across conjuncts (e.g. the `c >= lo` / `c <= hi` that
`c BETWEEN lo AND hi`
// lowers to) is never recorded as a common subexpression. The
cheap-but-recorded case is a
// shared *non-leaf* such as a struct field access -- `s.x > 5 AND s.x <
100` shares
// `GetStructField(s, x)` -- which is just a slot read. Require a
non-cheap common
- // subexpression (per `CollapseProject.isCheap`) so such filters keep the
lazy,
- // short-circuiting path and only genuine repeated computation takes the
CSE path.
+ // subexpression (per `CollapseProject.isCheap`) so such filters keep the
non-CSE path and
+ // only genuine repeated computation takes the CSE path.
//
// `subexpressionElimination.filterExec.enabled` additionally gates this
path so it can be
// turned off independently of subexpression elimination elsewhere.
- val (prologueCode, predicateCode) =
+ val predicateCode =
if (conf.subexpressionEliminationEnabled &&
conf.subexpressionEliminationFilterExecEnabled &&
otherPreds.nonEmpty &&
otherPredsEquivalentExpressions.getCommonSubexpressions
.exists(!CollapseProject.isCheap(_))) {
- // Pre-evaluate input variables before CSE analysis: CSE clears
- // ctx.currentVars[i].code as a side effect; without this
pre-evaluation, Janino
- // fails when otherPreds reference the same input columns that CSE
already
- // consumed.
- val otherPredInputAttrs =
AttributeSet(otherPreds.flatMap(_.references))
- val inputVarsEvalCode = evaluateRequiredVariables(
- child.output, input, otherPredInputAttrs)
-
+ // Hide the code of the input columns from the CSE analysis, and put
it back after. When
+ // it generates a common subexpression, the code of each column the
subexpression reads is
+ // copied into the subexpression's code (and, when the subexpressions
are split into
+ // functions, into `exprCodesNeedEvaluate`), and the analysis then
clears that code in
+ // `input`. This branch emits neither, so without hiding the code a
conjunct before the
+ // first use of the subexpression would read a column that is not
declared yet, and two
+ // subexpressions reading the same column would declare it twice. With
the code put back,
+ // each column is computed just before the first check that reads it,
see (d), and the
+ // subexpressions read the variable of the column.
Review Comment:
**Nit (P3):** "Emits neither" doesn't hold. This branch does emit each
subexpression's code, through `ctx.evaluateSubExprEliminationState(states)`
just before the first condition that references it (line 630); only
`exprCodesNeedEvaluate` is never emitted. The sentence's own "would declare it
twice" depends on that code being emitted. Suggested wording:
```suggestion
// `input`. This branch emits a subexpression's code only just
before the first conjunct
// that references it and never emits `exprCodesNeedEvaluate`, so
without hiding the code
// a conjunct before the first use of the subexpression would read a
column that is not
// declared yet, and two subexpressions reading the same column
would declare it twice.
// With the code put back, each column is computed just before the
first check that reads
// it, see (d), and the subexpressions read the variable of the
column.
```
**Verification:**
- **Inspection:** The comment above the hide-and-restore describes what the
CSE branch emits: each subexpression's code just before the first condition
that references it, and never `exprCodesNeedEvaluate`.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -1775,7 +1851,7 @@ class WholeStageCodegenSuite extends SharedSparkSession
val enabledCount =
addExactPattern.findAllIn(filterCode(filterExecCseEnabled = true)).length
val disabledCount =
addExactPattern.findAllIn(filterCode(filterExecCseEnabled = false)).length
// With the gate on, CSE collapses the repeated `a + b` evaluations; with
the gate off,
- // FilterExec falls back to the lazy path that re-evaluates per use.
+ // FilterExec falls back to the non-CSE path that re-evaluates per use.
Review Comment:
**Nit (P3):** Line 1829 of this test still says "the CSE path evaluates it
once, the lazy path per use." Both branches load columns lazily now, so it
should say "the non-CSE path per use", to match this line and line 1817.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -1668,8 +1745,7 @@ class WholeStageCodegenSuite extends SharedSparkSession
// each conjunct to a separate `addExprTree` call. The realistic
cheap-but-recorded case is a
// shared *non-leaf* slot read such as a struct field access: `s.x > 5 AND
s.x < 100` shares
// `GetStructField(s, x)`. Caching that gains nothing over the non-CSE
path's lazy load, so the
- // gate must fall back. (Pre-`isCheap`-gate this took the CSE path,
emitting the eager
- // prologue.)
+ // gate must fall back. (Pre-`isCheap`-gate this took the CSE path.)
Review Comment:
**Nit (P3):** This test's own assertion message at lines 1775-1777 still
says "(i.e. fall back to the lazy, short-circuiting non-CSE path)". The CSE
branch now loads columns lazily too, so drop "lazy, short-circuiting" there, as
line 1739 already does.
See **Shared repair plan 1** in the review body.
--
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]