dongjoon-hyun commented on code in PR #60363:
URL: https://github.com/apache/spark/pull/60363#discussion_r4570402197
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -506,28 +510,39 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
val numOutput = metricTerm(ctx, "numOutputRows")
// Eliminate the common subexpressions of `otherPreds` only when one of
them is not cheap,
- // per `CollapseProject.isCheap`. Elimination has a cost: the input
columns of `otherPreds`
- // are all evaluated at the top of the row loop, below, while without it
each column is
- // loaded lazily, just before the first conjunct that needs it, and not at
all on a row that
- // an earlier conjunct drops. Sharing a cheap subexpression, such as the
struct field of
- // `s.x > 5 AND s.x < 100`, does not pay for that. A column that conjuncts
share is never a
- // common subexpression, as `EquivalentExpressions` skips leaf expressions.
- // `subexpressionElimination.filterExec.enabled` turns this off
independently of
- // subexpression elimination elsewhere.
+ // per `CollapseProject.isCheap`. Elimination has a cost: a state adds a
local variable, or
+ // with the split above `methodSplitThreshold` a method and two mutable
fields, per common
+ // subexpression. Sharing a cheap subexpression, such as the struct field
of
+ // `s.x > 5 AND s.x < 100`, does not pay for that, since computing it
again is a slot read.
+ // A column that conjuncts share is never a common subexpression, as
`EquivalentExpressions`
+ // skips leaf expressions. `subexpressionElimination.filterExec.enabled`
turns this off
+ // independently of subexpression elimination elsewhere.
val eliminateSubExprs = conf.subexpressionEliminationEnabled &&
conf.subexpressionEliminationFilterExecEnabled && otherPreds.nonEmpty &&
otherPredsEquivalentExpressions.getCommonSubexpressions.exists(!CollapseProject.isCheap(_))
- val (inputVarsEvalCode, subExprStates) = if (eliminateSubExprs) {
- // Evaluate the input variables before the states are generated:
generating a state takes
- // the code of the input variables it reads, and the conjuncts read the
same variables.
- val otherPredInputAttrs = AttributeSet(otherPreds.flatMap(_.references))
- val evalCode = evaluateRequiredVariables(child.output, input,
otherPredInputAttrs)
+ val subExprStates = if (eliminateSubExprs) {
+ // Generating a state takes the code of the input columns it reads:
inline it embeds a copy,
+ // which the conjunct that reads the column would then declare again,
and split it moves the
+ // code to `exprCodesNeedEvaluate`, which this does not emit, so the
column is never
+ // declared. The conjuncts read the same columns. Hide the code from the
state generation
+ // and put it back after, so `generatePredicateCode` loads each column
lazily, just before
+ // the first conjunct that reads it, and not on a row that an earlier
conjunct drops, rather
+ // than all at the top of the row loop. `.toIndexedSeq` forces the
snapshot now, while the
+ // code is still there: `input` can be a lazy sequence (a `LazyList`
that `consume` forced
+ // but whose `map` defers each element again), and a lazy `map` would
read each column's
+ // code only during the restore below, after it has been blanked.
+ val inputCode = input.map(_.code).toIndexedSeq
+ input.foreach(_.code = EmptyBlock)
Review Comment:
This mutates the shared `ExprCode`s of `input` in place, which is why the
`.toIndexedSeq` snapshot and the restore loop are required. Since
`ctx.currentVars` holds the same `input` here, what about swapping it instead?
```scala
val savedVars = ctx.currentVars
ctx.currentVars = input.map(_.copy(code = EmptyBlock)).toIndexedSeq
val subExprs = try {
ctx.subexpressionEliminationForWholeStageCodegen(otherPredsEquivalentExpressions)
} finally {
ctx.currentVars = savedVars
}
```
Then, `input` is never touched, so we don't need the snapshot and the
restore loop.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -283,7 +283,11 @@ trait GeneratePredicateHelper extends PredicateHelper {
* The caller binds `otherPreds` against the output with the checked
columns, those of
* `nonNullAttrExprIds`, tightened to non-nullable, in `boundOtherPreds`.
`subExprStates` holds
* the states of the common subexpressions to eliminate from
`boundOtherPreds`, if any. The
- * caller must have evaluated the input variables they read before this code.
+ * caller must have generated them with the code of the input columns
hidden, so no state
Review Comment:
This adds a precondition to the callers of this shared helper, but it is
only documented. Currently, only `FilterExec` passes `subExprStates`. However,
if a future caller (e.g., `AggregateCodegenSupport` or `MergeRowsExec`) passes
the plain `ctx.subexpressionEliminationForWholeStageCodegen(...).states`, it
will hit a Java compilation failure at runtime. Could we move the hiding and
the state generation into a single helper method of this trait so that callers
cannot violate it?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -506,28 +510,39 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
val numOutput = metricTerm(ctx, "numOutputRows")
// Eliminate the common subexpressions of `otherPreds` only when one of
them is not cheap,
- // per `CollapseProject.isCheap`. Elimination has a cost: the input
columns of `otherPreds`
- // are all evaluated at the top of the row loop, below, while without it
each column is
- // loaded lazily, just before the first conjunct that needs it, and not at
all on a row that
- // an earlier conjunct drops. Sharing a cheap subexpression, such as the
struct field of
- // `s.x > 5 AND s.x < 100`, does not pay for that. A column that conjuncts
share is never a
- // common subexpression, as `EquivalentExpressions` skips leaf expressions.
- // `subexpressionElimination.filterExec.enabled` turns this off
independently of
- // subexpression elimination elsewhere.
+ // per `CollapseProject.isCheap`. Elimination has a cost: a state adds a
local variable, or
+ // with the split above `methodSplitThreshold` a method and two mutable
fields, per common
+ // subexpression. Sharing a cheap subexpression, such as the struct field
of
+ // `s.x > 5 AND s.x < 100`, does not pay for that, since computing it
again is a slot read.
+ // A column that conjuncts share is never a common subexpression, as
`EquivalentExpressions`
+ // skips leaf expressions. `subexpressionElimination.filterExec.enabled`
turns this off
+ // independently of subexpression elimination elsewhere.
val eliminateSubExprs = conf.subexpressionEliminationEnabled &&
conf.subexpressionEliminationFilterExecEnabled && otherPreds.nonEmpty &&
otherPredsEquivalentExpressions.getCommonSubexpressions.exists(!CollapseProject.isCheap(_))
- val (inputVarsEvalCode, subExprStates) = if (eliminateSubExprs) {
- // Evaluate the input variables before the states are generated:
generating a state takes
- // the code of the input variables it reads, and the conjuncts read the
same variables.
- val otherPredInputAttrs = AttributeSet(otherPreds.flatMap(_.references))
- val evalCode = evaluateRequiredVariables(child.output, input,
otherPredInputAttrs)
+ val subExprStates = if (eliminateSubExprs) {
+ // Generating a state takes the code of the input columns it reads:
inline it embeds a copy,
+ // which the conjunct that reads the column would then declare again,
and split it moves the
+ // code to `exprCodesNeedEvaluate`, which this does not emit, so the
column is never
+ // declared. The conjuncts read the same columns. Hide the code from the
state generation
+ // and put it back after, so `generatePredicateCode` loads each column
lazily, just before
+ // the first conjunct that reads it, and not on a row that an earlier
conjunct drops, rather
+ // than all at the top of the row loop. `.toIndexedSeq` forces the
snapshot now, while the
+ // code is still there: `input` can be a lazy sequence (a `LazyList`
that `consume` forced
+ // but whose `map` defers each element again), and a lazy `map` would
read each column's
+ // code only during the restore below, after it has been blanked.
+ val inputCode = input.map(_.code).toIndexedSeq
+ input.foreach(_.code = EmptyBlock)
val subExprs =
ctx.subexpressionEliminationForWholeStageCodegen(otherPredsEquivalentExpressions)
- (evalCode, subExprs.states)
+ input.zip(inputCode).foreach { case (ev, code) => ev.code = code }
+ // Every input column's code was hidden, so no column was hoisted to be
evaluated before the
+ // states; `generatePredicateCode` loads them all.
+ assert(subExprs.exprCodesNeedEvaluate.isEmpty)
Review Comment:
This invariant holds only because each element of `ctx.currentVars` is the
same object as the one in `input`. If a future change breaks it, the
`AssertionError` is thrown in `doCodeGen()`, which
`WholeStageCodegenExec.doExecute` calls outside of the `try`, so
`spark.sql.codegen.fallback` cannot fall back to the interpreted path and the
query fails. Shall we emit `evaluateVariables(subExprs.exprCodesNeedEvaluate)`
defensively instead of asserting?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -506,28 +510,39 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
val numOutput = metricTerm(ctx, "numOutputRows")
// Eliminate the common subexpressions of `otherPreds` only when one of
them is not cheap,
- // per `CollapseProject.isCheap`. Elimination has a cost: the input
columns of `otherPreds`
- // are all evaluated at the top of the row loop, below, while without it
each column is
- // loaded lazily, just before the first conjunct that needs it, and not at
all on a row that
- // an earlier conjunct drops. Sharing a cheap subexpression, such as the
struct field of
- // `s.x > 5 AND s.x < 100`, does not pay for that. A column that conjuncts
share is never a
- // common subexpression, as `EquivalentExpressions` skips leaf expressions.
- // `subexpressionElimination.filterExec.enabled` turns this off
independently of
- // subexpression elimination elsewhere.
+ // per `CollapseProject.isCheap`. Elimination has a cost: a state adds a
local variable, or
+ // with the split above `methodSplitThreshold` a method and two mutable
fields, per common
+ // subexpression. Sharing a cheap subexpression, such as the struct field
of
+ // `s.x > 5 AND s.x < 100`, does not pay for that, since computing it
again is a slot read.
+ // A column that conjuncts share is never a common subexpression, as
`EquivalentExpressions`
+ // skips leaf expressions. `subexpressionElimination.filterExec.enabled`
turns this off
+ // independently of subexpression elimination elsewhere.
val eliminateSubExprs = conf.subexpressionEliminationEnabled &&
conf.subexpressionEliminationFilterExecEnabled && otherPreds.nonEmpty &&
otherPredsEquivalentExpressions.getCommonSubexpressions.exists(!CollapseProject.isCheap(_))
- val (inputVarsEvalCode, subExprStates) = if (eliminateSubExprs) {
- // Evaluate the input variables before the states are generated:
generating a state takes
- // the code of the input variables it reads, and the conjuncts read the
same variables.
- val otherPredInputAttrs = AttributeSet(otherPreds.flatMap(_.references))
- val evalCode = evaluateRequiredVariables(child.output, input,
otherPredInputAttrs)
+ val subExprStates = if (eliminateSubExprs) {
+ // Generating a state takes the code of the input columns it reads:
inline it embeds a copy,
+ // which the conjunct that reads the column would then declare again,
and split it moves the
+ // code to `exprCodesNeedEvaluate`, which this does not emit, so the
column is never
+ // declared. The conjuncts read the same columns. Hide the code from the
state generation
+ // and put it back after, so `generatePredicateCode` loads each column
lazily, just before
+ // the first conjunct that reads it, and not on a row that an earlier
conjunct drops, rather
+ // than all at the top of the row loop. `.toIndexedSeq` forces the
snapshot now, while the
+ // code is still there: `input` can be a lazy sequence (a `LazyList`
that `consume` forced
+ // but whose `map` defers each element again), and a lazy `map` would
read each column's
+ // code only during the restore below, after it has been blanked.
+ val inputCode = input.map(_.code).toIndexedSeq
+ input.foreach(_.code = EmptyBlock)
val subExprs =
ctx.subexpressionEliminationForWholeStageCodegen(otherPredsEquivalentExpressions)
- (evalCode, subExprs.states)
+ input.zip(inputCode).foreach { case (ev, code) => ev.code = code }
Review Comment:
If `subexpressionEliminationForWholeStageCodegen` throws (e.g., the
`internalError` for the JVM parameter length limit in testing mode), this
restore is skipped and the code of `input` stays blank. It's harmless today
because each generation creates fresh `ExprCode`s, but shall we use
`try`/`finally` here?
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -1843,6 +1838,120 @@ class WholeStageCodegenSuite extends SharedSparkSession
"sinh(v) should be evaluated only once per input row without function
splitting")
}
+ test("SPARK-61377: FilterExec CSE computes an input column just before the
first conjunct " +
+ "that reads it") {
+ // Each input column of the filter is a UDF alias the child `ProjectExec`
computes in the same
+ // codegen stage; `r`, `rb`, `rc` and `u` all throw for the rows that an
earlier condition
+ // drops. The common `f + 1` (or `r + 1`) makes the filter take the CSE
path, which must still
+ // compute a column just before the first condition that reads it, not up
front. The
+ // projection split is turned off so the filter over the aliases stays
above the projection.
+ val f = udf((x: Long) => x)
+ // Returns a primitive, so `r` is non-nullable and gets no inferred
IsNotNull: it is first
+ // read by a plain condition (`r > 0` or the common `r + 1`).
+ val r = udf((x: Long) => { if (x <= 5) throw new
IllegalStateException(s"r($x)"); x })
+ // Returns a boxed Long, so `rb` is nullable and is first read by its own
IsNotNull check.
+ val rb = udf { (x: Long) =>
+ if (x <= 5) throw new IllegalStateException(s"rb($x)");
java.lang.Long.valueOf(x) }
+ // Read only by an IsNotNull check that lands after all conditions
(leftover notNullPreds).
+ val rc = udf { (x: Long) =>
+ if (x <= 5) throw new IllegalStateException(s"rc($x)");
java.lang.Long.valueOf(x) }
+ // Not read by the filter at all, so the parent's `consume` loads it.
+ val u = udf((x: Long) => { if (x <= 5) throw new
IllegalStateException(s"u($x)"); x })
+
+ def firstFilterOverProject(df: DataFrame): FilterExec = {
+ val plan = df.queryExecution.executedPlan
+ val fe = plan.collectFirst { case w: WholeStageCodegenExec =>
+ w.child.collectFirst { case fe @ FilterExec(_, _: ProjectExec) => fe }
+ }.flatten
+ assert(fe.isDefined, s"Filter over Project should be in one codegen
stage:\n$plan")
+ fe.get
+ }
+ // Each `select` mints fresh exprIds that appear in the codegen dump's
plan header but not in
+ // the generated Java; normalize them away to compare the generated code.
+ def normalize(code: String): String = code.replaceAll("#\\d+", "#")
+
+ // `methodSplitThreshold` 1 exercises the path that splits each common
subexpression into its
+ // own function, whose parameters are the input columns' variables;
Int.MaxValue keeps the
+ // common subexpressions inline (no split).
+ Seq(Int.MaxValue.toString, "1").foreach { threshold =>
+ withSQLConf(
+ SQLConf.SUBEXPRESSION_ELIMINATION_ENABLED.key -> "true",
+ SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key -> "true",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.CODEGEN_METHOD_SPLIT_THRESHOLD.key -> threshold,
+ SQLConf.SPLIT_PROJECTION_FOR_EXPENSIVE_FILTERS.key -> "false") {
+ val df = spark.range(10).select(
+ f($"id").as("f"), r($"id").as("r"), rb($"id").as("rb"),
+ rc($"id").as("rc"), u($"id").as("u"))
+ Seq(
+ // `r` (non-nullable, no IsNotNull) first read by `r > 0`, after the
dropping `f + 1 > 6`.
+ "f >= 0 AND f + 1 > 6 AND f + 1 < 100 AND r > 0",
+ // `rb` (nullable) first read by its IsNotNull check, just before
`rb > 0`.
+ "f + 1 > 6 AND f + 1 < 100 AND rb IS NOT NULL AND rb > 0",
+ // `r` first read by the common subexpression `r + 1`, referenced
after `f + 1 > 6`.
+ "f + 1 > 6 AND r + 1 > 0 AND r + 1 < 100 AND f + 1 < 100",
+ // `rc` read only by a leftover IsNotNull; `rb` and `u` are not read
by the filter.
+ "f + 1 > 6 AND f + 1 < 100 AND r > 0 AND rc IS NOT NULL"
+ ).foreach { predicate =>
+ val filtered = df.where(predicate)
+ firstFilterOverProject(filtered)
+ checkAnswer(filtered,
+ (6L to 9L).map(i => Row(i, i, i, i, i)))
+ // With the config off the same query returns the same rows (non-CSE
path).
+
withSQLConf(SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key ->
"false") {
+ checkAnswer(df.where(predicate), (6L to 9L).map(i => Row(i, i, i,
i, i)))
+ }
+ }
+
+ // The CSE path is actually taken: eliminating the shared `f + 1`
makes the generated code
+ // differ from the non-CSE path (the sibling "takes CSE codegen" test
asserts the same).
+ val csePredicate = "f + 1 > 6 AND f + 1 < 100 AND r > 0"
Review Comment:
The CSE path is verified only for `csePredicate`. The four predicate shapes
above compare only the result rows, so if one of them stops taking the CSE path
(e.g., due to an optimizer change), this test still passes silently and loses
its coverage. Could we check that the generated code differs between CSE on and
off for each of them?
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -1843,6 +1838,120 @@ class WholeStageCodegenSuite extends SharedSparkSession
"sinh(v) should be evaluated only once per input row without function
splitting")
}
+ test("SPARK-61377: FilterExec CSE computes an input column just before the
first conjunct " +
+ "that reads it") {
+ // Each input column of the filter is a UDF alias the child `ProjectExec`
computes in the same
+ // codegen stage; `r`, `rb`, `rc` and `u` all throw for the rows that an
earlier condition
+ // drops. The common `f + 1` (or `r + 1`) makes the filter take the CSE
path, which must still
+ // compute a column just before the first condition that reads it, not up
front. The
+ // projection split is turned off so the filter over the aliases stays
above the projection.
+ val f = udf((x: Long) => x)
+ // Returns a primitive, so `r` is non-nullable and gets no inferred
IsNotNull: it is first
+ // read by a plain condition (`r > 0` or the common `r + 1`).
+ val r = udf((x: Long) => { if (x <= 5) throw new
IllegalStateException(s"r($x)"); x })
+ // Returns a boxed Long, so `rb` is nullable and is first read by its own
IsNotNull check.
+ val rb = udf { (x: Long) =>
+ if (x <= 5) throw new IllegalStateException(s"rb($x)");
java.lang.Long.valueOf(x) }
+ // Read only by an IsNotNull check that lands after all conditions
(leftover notNullPreds).
+ val rc = udf { (x: Long) =>
+ if (x <= 5) throw new IllegalStateException(s"rc($x)");
java.lang.Long.valueOf(x) }
+ // Not read by the filter at all, so the parent's `consume` loads it.
+ val u = udf((x: Long) => { if (x <= 5) throw new
IllegalStateException(s"u($x)"); x })
+
+ def firstFilterOverProject(df: DataFrame): FilterExec = {
+ val plan = df.queryExecution.executedPlan
+ val fe = plan.collectFirst { case w: WholeStageCodegenExec =>
+ w.child.collectFirst { case fe @ FilterExec(_, _: ProjectExec) => fe }
+ }.flatten
+ assert(fe.isDefined, s"Filter over Project should be in one codegen
stage:\n$plan")
+ fe.get
+ }
+ // Each `select` mints fresh exprIds that appear in the codegen dump's
plan header but not in
+ // the generated Java; normalize them away to compare the generated code.
+ def normalize(code: String): String = code.replaceAll("#\\d+", "#")
+
+ // `methodSplitThreshold` 1 exercises the path that splits each common
subexpression into its
+ // own function, whose parameters are the input columns' variables;
Int.MaxValue keeps the
+ // common subexpressions inline (no split).
+ Seq(Int.MaxValue.toString, "1").foreach { threshold =>
+ withSQLConf(
+ SQLConf.SUBEXPRESSION_ELIMINATION_ENABLED.key -> "true",
+ SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key -> "true",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.CODEGEN_METHOD_SPLIT_THRESHOLD.key -> threshold,
+ SQLConf.SPLIT_PROJECTION_FOR_EXPENSIVE_FILTERS.key -> "false") {
+ val df = spark.range(10).select(
+ f($"id").as("f"), r($"id").as("r"), rb($"id").as("rb"),
+ rc($"id").as("rc"), u($"id").as("u"))
+ Seq(
+ // `r` (non-nullable, no IsNotNull) first read by `r > 0`, after the
dropping `f + 1 > 6`.
+ "f >= 0 AND f + 1 > 6 AND f + 1 < 100 AND r > 0",
+ // `rb` (nullable) first read by its IsNotNull check, just before
`rb > 0`.
+ "f + 1 > 6 AND f + 1 < 100 AND rb IS NOT NULL AND rb > 0",
+ // `r` first read by the common subexpression `r + 1`, referenced
after `f + 1 > 6`.
+ "f + 1 > 6 AND r + 1 > 0 AND r + 1 < 100 AND f + 1 < 100",
+ // `rc` read only by a leftover IsNotNull; `rb` and `u` are not read
by the filter.
+ "f + 1 > 6 AND f + 1 < 100 AND r > 0 AND rc IS NOT NULL"
+ ).foreach { predicate =>
+ val filtered = df.where(predicate)
+ firstFilterOverProject(filtered)
+ checkAnswer(filtered,
+ (6L to 9L).map(i => Row(i, i, i, i, i)))
+ // With the config off the same query returns the same rows (non-CSE
path).
+
withSQLConf(SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key ->
"false") {
+ checkAnswer(df.where(predicate), (6L to 9L).map(i => Row(i, i, i,
i, i)))
+ }
+ }
+
+ // The CSE path is actually taken: eliminating the shared `f + 1`
makes the generated code
+ // differ from the non-CSE path (the sibling "takes CSE codegen" test
asserts the same).
+ val csePredicate = "f + 1 > 6 AND f + 1 < 100 AND r > 0"
+ def filterCode(cse: Boolean): String =
+
withSQLConf(SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key ->
cse.toString) {
+ codegenString(df.where(csePredicate).queryExecution.executedPlan)
+ }
+ val cseCode = filterCode(cse = true)
+ assert(normalize(cseCode) != normalize(filterCode(cse = false)),
+ "CSE path should eliminate the shared f + 1 and differ from the
non-CSE codegen")
+ // `subExpr` names appear only when the states are split into
functions, so they confirm
+ // the split threshold is exercised: present at threshold 1, absent
when kept inline.
+ if (threshold == "1") {
+ assert(cseCode.contains("subExpr"), "states should be split into
functions at 1")
+ } else {
+ assert(!cseCode.contains("subExpr"), "states should be kept inline
at Int.MaxValue")
+ }
+
+ // A lazy `input` sequence: `select` over a `LazyList` of columns
keeps the projection
+ // list lazy into `ProjectExec`, so the output variables FilterExec
receives are a lazy
+ // sequence. Snapshotting their code before the CSE analysis must
force the snapshot, or
+ // the restore reads the already-blanked code and the stage fails to
compile. The shared
+ // `f + 1` and `r + 1` make the filter take the CSE path; `r` fails on
the rows
+ // `f + 1 > 6` drops and is first read by `r + 1`. The single-pass
resolver is pinned off,
+ // as in the "create union with LazyList of children" PlannerSuite
test, so its own
+ // handling of a lazy project list does not turn the projection strict.
+ withSQLConf(
+ SQLConf.ANALYZER_SINGLE_PASS_RESOLVER_ENABLED.key -> "false",
+ SQLConf.ANALYZER_DUAL_RUN_LEGACY_AND_SINGLE_PASS_RESOLVER.key ->
"false") {
+ val lazyPredicate = "f + 1 > 6 AND r + 1 > 0 AND r + 1 < 100 AND f +
1 < 100"
+ val lazyCols = LazyList(f($"id").as("f"), r($"id").as("r"))
+ val lazyDf = spark.range(10).select(lazyCols:
_*).where(lazyPredicate)
+ val fe = firstFilterOverProject(lazyDf)
+
assert(fe.child.asInstanceOf[ProjectExec].projectList.isInstanceOf[LazyList[_]],
Review Comment:
This asserts an internal state, i.e., `ProjectExec.projectList` remains a
`LazyList` after the analyzer and the optimizer, and pins two resolver
configurations. Any unrelated change that makes the project list strict will
break this test. If we take the `ctx.currentVars` swap approach suggested
above, we don't need this sub-test.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -1807,10 +1807,10 @@ object SQLConf {
buildConf("spark.sql.subexpressionElimination.filterExec.enabled")
.internal()
.doc("When true (and subexpression elimination is enabled), FilterExec
whole-stage " +
- "codegen eliminates common subexpressions shared across its
predicates. When false, " +
- "FilterExec falls back to the predicate codegen that loads input
columns lazily and " +
- "short-circuits, avoiding eager materialization of all
predicate-referenced columns on " +
- "every row. Only affects FilterExec; subexpression elimination
elsewhere is unaffected.")
+ "codegen eliminates the common subexpressions shared across its
predicates when one of " +
+ "them is not cheap. When false, " +
Review Comment:
nit. `"them is not cheap. When false, " +` looks like a leftover. Shall we
reflow this with the next line?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -506,28 +510,39 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
val numOutput = metricTerm(ctx, "numOutputRows")
// Eliminate the common subexpressions of `otherPreds` only when one of
them is not cheap,
- // per `CollapseProject.isCheap`. Elimination has a cost: the input
columns of `otherPreds`
- // are all evaluated at the top of the row loop, below, while without it
each column is
- // loaded lazily, just before the first conjunct that needs it, and not at
all on a row that
- // an earlier conjunct drops. Sharing a cheap subexpression, such as the
struct field of
- // `s.x > 5 AND s.x < 100`, does not pay for that. A column that conjuncts
share is never a
- // common subexpression, as `EquivalentExpressions` skips leaf expressions.
- // `subexpressionElimination.filterExec.enabled` turns this off
independently of
- // subexpression elimination elsewhere.
+ // per `CollapseProject.isCheap`. Elimination has a cost: a state adds a
local variable, or
+ // with the split above `methodSplitThreshold` a method and two mutable
fields, per common
+ // subexpression. Sharing a cheap subexpression, such as the struct field
of
+ // `s.x > 5 AND s.x < 100`, does not pay for that, since computing it
again is a slot read.
+ // A column that conjuncts share is never a common subexpression, as
`EquivalentExpressions`
+ // skips leaf expressions. `subexpressionElimination.filterExec.enabled`
turns this off
+ // independently of subexpression elimination elsewhere.
val eliminateSubExprs = conf.subexpressionEliminationEnabled &&
conf.subexpressionEliminationFilterExecEnabled && otherPreds.nonEmpty &&
otherPredsEquivalentExpressions.getCommonSubexpressions.exists(!CollapseProject.isCheap(_))
- val (inputVarsEvalCode, subExprStates) = if (eliminateSubExprs) {
- // Evaluate the input variables before the states are generated:
generating a state takes
- // the code of the input variables it reads, and the conjuncts read the
same variables.
- val otherPredInputAttrs = AttributeSet(otherPreds.flatMap(_.references))
- val evalCode = evaluateRequiredVariables(child.output, input,
otherPredInputAttrs)
+ val subExprStates = if (eliminateSubExprs) {
+ // Generating a state takes the code of the input columns it reads:
inline it embeds a copy,
Review Comment:
The description of the inline case looks inaccurate.
`getLocalInputVariableValues` runs for every common subexpression before the
`needSplit` decision and clears `input.code` in both cases, so the conjunct
that reads the column does not declare it again. Without hiding, the actual
failures are (1) a condition before the first use of the state reads an
undeclared column, and (2) two states reading the same column embed its
declaration twice. The PR description explains this correctly. Could you update
this comment accordingly?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -506,28 +510,39 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
val numOutput = metricTerm(ctx, "numOutputRows")
// Eliminate the common subexpressions of `otherPreds` only when one of
them is not cheap,
- // per `CollapseProject.isCheap`. Elimination has a cost: the input
columns of `otherPreds`
- // are all evaluated at the top of the row loop, below, while without it
each column is
- // loaded lazily, just before the first conjunct that needs it, and not at
all on a row that
- // an earlier conjunct drops. Sharing a cheap subexpression, such as the
struct field of
- // `s.x > 5 AND s.x < 100`, does not pay for that. A column that conjuncts
share is never a
- // common subexpression, as `EquivalentExpressions` skips leaf expressions.
- // `subexpressionElimination.filterExec.enabled` turns this off
independently of
- // subexpression elimination elsewhere.
+ // per `CollapseProject.isCheap`. Elimination has a cost: a state adds a
local variable, or
+ // with the split above `methodSplitThreshold` a method and two mutable
fields, per common
Review Comment:
nit. In the split path, a non-nullable common subexpression gets only one
mutable field because `subExprIsNull` is not added when `eval.isNull` is a
literal. Maybe, `a method and up to two mutable fields`?
--
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]