This is an automated email from the ASF dual-hosted git repository.
viirya pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 460ba253cfff [SPARK-61556][SQL] Generate FilterExec predicate code
with and without subexpression elimination from one implementation
460ba253cfff is described below
commit 460ba253cfff9c235658c3008f6ef494f050f579
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Thu Nov 12 15:34:59 2026 -0800
[SPARK-61556][SQL] Generate FilterExec predicate code with and without
subexpression elimination from one implementation
### What changes were proposed in this pull request?
`GeneratePredicateHelper.generatePredicateCode` becomes the only
implementation of the algorithm that orders the conjuncts of a filter condition
and its `IsNotNull` checks in the generated code.
- `generatePredicateCode` takes a new optional argument, the states of the
common subexpressions to eliminate from the conjuncts. It evaluates each state
right before the first conjunct that references it, after the `IsNotNull`
checks of that conjunct, generates the conjuncts with the states, and generates
the checks without them.
- `FilterExec.doConsume` keeps what is specific to it: the decision to
eliminate (a non-cheap common subexpression exists and the configs allow it),
the evaluation of the input variables that the states read, and the creation of
the states. It then calls `generatePredicateCode` in both cases.
- The comments that described the two copies and how they had to be kept in
sync are replaced by a list of the invariants on the single implementation.
The aggregate `FILTER` clause (`AggregateCodegenSupport`), the other caller
of `generatePredicateCode`, passes no states and is not affected.
### Why are the changes needed?
`FilterExec.doConsume` re-implemented this algorithm for the conditions it
eliminates common subexpressions from, and the two copies were kept in sync
only by comments ("Any change to this algorithm must be mirrored there (and
vice versa)"). Fixes such as SPARK-51356 and SPARK-60315 had to be applied to
both, and a change to one copy alone silently makes a filter behave differently
depending on whether a common subexpression is eliminated.
The copies had no behavioral difference, but they were not the same either:
with subexpression elimination, the checks on the columns a conjunct references
were generated with the states visible, while the other checks were explicitly
generated without them. All checks are now generated without the states.
### Does this PR introduce _any_ user-facing change?
No. The generated code without subexpression elimination is the same as
before. With it, the code differs in whitespace only.
### How was this patch tested?
- A new test in `WholeStageCodegenSuite` runs 23 conjunctions, mixing
columns that can be NULL, written and inferred `IS NOT NULL` checks on columns
and on expressions, conjuncts that can be NULL, common subexpressions and
conjuncts that can raise an error, including the cases of SPARK-51356,
SPARK-60315 and SPARK-60332. For each, it compares the rows, or the error
condition, across the subexpression elimination configs, with whole-stage
codegen on and off, in ANSI and non-ANSI mode, [...]
- Compared the whole-stage code generated before and after this change for
21 conditions, as a filter and as an aggregate `FILTER`, under the combinations
of ANSI mode, the legacy behavior and
`spark.sql.subexpressionElimination.filterExec.enabled`: identical without
subexpression elimination, and identical up to whitespace with it, apart from
the parameter order of two split subexpression functions, which also varies
between two runs of the same code.
- Existing tests: `WholeStageCodegenSuite`, `DataFrameAggregateSuite`,
`DataFrameSuite`, `MergeIntoDataFrameSuite`,
`CodegenSubexpressionEliminationSuite`, `SubexpressionEliminationSuite`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code
Closes #60399 from viirya/filterexec-predicate-codegen-single-source-994978.
Authored-by: Liang-Chi Hsieh <[email protected]>
Signed-off-by: Liang-Chi Hsieh <[email protected]>
skip-checks: true
---
.../sql/execution/basicPhysicalOperators.scala | 337 +++++++--------------
.../sql/execution/WholeStageCodegenSuite.scala | 117 ++++++-
2 files changed, 222 insertions(+), 232 deletions(-)
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
index da4a4678b1aa..90b0933f73e5 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
@@ -275,6 +275,36 @@ trait GeneratePredicateHelper extends PredicateHelper {
}
}
+ /**
+ * Generates the code that jumps out of the enclosing loop body, with
`continue`, unless every
+ * conjunct of a condition, split by `splitNotNullPreds`, is TRUE on the
row. This is the only
+ * place that decides the order in which the conjuncts and the IsNotNull
checks are evaluated.
+ *
+ * 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.
+ *
+ * The conjuncts are generated one by one, loading a column only when it is
needed, so that a
+ * FALSE conjunct skips the rest. This is very perf sensitive. The
invariants:
+ * 1. Before a conjunct, the check on each column it references is
generated, as the conjunct
+ * is bound with the column non-nullable. A column that only a check on
an expression over
+ * it covers gets a synthetic check instead, so that the expression,
which may be expensive
+ * or raise an error, is not evaluated on a row that an earlier conjunct
drops.
+ * 2. A check on an expression that a conjunct contains is generated before
the conjunct
+ * (SPARK-51356).
+ * 3. With the NULL-conjunct flag, once a conjunct that can be NULL is
generated, the checks
+ * are evaluated in the order of the condition, as `And.eval` does
(SPARK-60315): the ones
+ * written before a conjunct go before it, see `precedingNotNullChecks`,
and (2) does not
+ * move a check written after it.
+ * 4. A common subexpression is evaluated right before the first conjunct
that references it,
+ * so not on a row that an earlier conjunct drops, and after the checks
of that conjunct:
+ * its state is computed with the checked columns non-nullable, and
would otherwise hold
+ * the NULL of such a column, which the code reading the state does not
expect.
+ * 5. The checks are bound with the nullability the child produced, unlike
the states, so they
+ * are generated without the states.
+ * 6. The checks left are generated after all the conjuncts.
+ */
protected def generatePredicateCode(
ctx: CodegenContext,
inputAttrs: Seq[Attribute],
@@ -283,18 +313,47 @@ trait GeneratePredicateHelper extends PredicateHelper {
otherPreds: Seq[Expression],
boundOtherPreds: Seq[Expression],
precedingNotNulls: Seq[Int],
- nonNullAttrExprIds: Seq[ExprId]): String = {
- // The IsNotNull checks are never NULL, so only `otherPreds` can need the
flag. The caller
- // binds them against the output with the checked columns tightened to
non-nullable, in
- // `boundOtherPreds`.
+ nonNullAttrExprIds: Seq[ExprId],
+ subExprStates: Map[ExpressionEquals, SubExprEliminationState] =
Map.empty): String = {
+ // The IsNotNull checks are never NULL, so only `otherPreds` can need the
flag.
val nullFlag = nullConjunctFlag(ctx, otherPreds, boundOtherPreds,
notNullPreds)
+ // The states by the index of the first conjunct that references them.
Evaluating a state
+ // evaluates the states it depends on first and clears the code of each,
so a state that an
+ // earlier conjunct evaluated is not evaluated again.
+ val statesByFirstUse: Map[Int, Seq[SubExprEliminationState]] =
+ subExprStates.toSeq.groupBy { case (subExpr, _) =>
+ ctx.firstReferencingExpression(boundOtherPreds, subExpr)
+ }.map { case (k, states) => k -> states.map(_._2) }
+
+ /** Generates code with `states` as the common subexpressions that it
reads. */
+ def withSubExprStates(states: Map[ExpressionEquals,
SubExprEliminationState])(
+ gen: => String): String = {
+ if (subExprStates.isEmpty) {
+ // No subexpression is eliminated here: leave the context as the
caller set it.
+ gen
+ } else {
+ var code: String = null
+ ctx.withSubExprEliminationExprs(states) {
+ code = gen
+ Seq.empty
+ }
+ code
+ }
+ }
+
/**
* Generates code for `c`, given as `bound` after binding against the
attributes whose
- * nullability it is generated with. A NULL value sets `flag`, or drops
the row if None.
+ * nullability it is generated with, after `subExprsCode`, the code of the
states it is the
+ * first to reference. A NULL value sets `flag`, or drops the row if None.
*/
- def genPredicate(c: Expression, bound: Expression, flag: Option[String]):
String = {
- val evaluated = evaluateRequiredVariables(inputAttrs, inputExprCode,
c.references)
+ def genPredicate(
+ c: Expression,
+ bound: Expression,
+ flag: Option[String],
+ subExprsCode: String = ""): String = {
+ val evaluated =
+ evaluateRequiredVariables(inputAttrs, inputExprCode, c.references) +
subExprsCode
// Generate the code for the predicate.
val ev = ExpressionCanonicalizer.execute(bound).genCode(ctx)
@@ -307,28 +366,14 @@ trait GeneratePredicateHelper extends PredicateHelper {
}
/**
- * Generates an IsNotNull check with the nullability the child produced.
The check is never
- * NULL, and must drop the row before the conjuncts bound with its column
non-nullable, so
- * it does not get the flag.
+ * Generates an IsNotNull check with the nullability the child produced,
and so without the
+ * states, see (5). The check is never NULL, and must drop the row before
the conjuncts and
+ * the states bound with its column non-nullable, so it does not get the
flag.
*/
- def genNotNull(c: Expression): String =
+ def genNotNull(c: Expression): String = withSubExprStates(Map.empty) {
genPredicate(c, BindReferences.bindReference(c, inputAttrs), None)
+ }
- // To generate the predicates we will follow this algorithm.
- // For each predicate that is not IsNotNull, we will generate them one by
one loading attributes
- // as necessary. For each of both attributes, if there is an IsNotNull
predicate we will
- // generate that check *before* the predicate. After all of these
predicates, we will generate
- // the remaining IsNotNull checks that were not part of other predicates.
- // This has the property of not doing redundant IsNotNull checks and
taking better advantage of
- // short-circuiting, not loading attributes until they are needed.
- // This is very perf sensitive.
- // With the NULL-conjunct flag, once a predicate that can be NULL is
generated, the IsNotNull
- // checks that precede a later predicate in the condition are generated
before it, see
- // `precedingNotNullChecks`, and a check on an expression that is written
after the predicate
- // is not generated before it, see the nested checks below.
- // NOTE: `FilterExec.doConsume`'s CSE branch inlines the same interleaving
so it can
- // emit CSE state precomputes between the IsNotNull checks and each
otherPred body.
- // Any change to this algorithm must be mirrored there (and vice versa).
// TODO: revisit this. We can consider reordering predicates as well.
val generatedIsNotNullChecks = new Array[Boolean](notNullPreds.length)
val extraIsNotNullAttrs = mutable.Set[Attribute]()
@@ -376,16 +421,25 @@ trait GeneratePredicateHelper extends PredicateHelper {
genNotNull(p)
}.mkString("\n").trim
+ val subExprsCode = statesByFirstUse.get(k).map { states =>
+ ctx.evaluateSubExprEliminationState(states) + "\n"
+ }.getOrElse("")
+
// Here we use *this* operator's output with this output's nullability
since we already
// enforced them with the IsNotNull checks above.
+ val predicate = withSubExprStates(subExprStates) {
+ genPredicate(c, bound, nullFlag, subExprsCode)
+ }
s"""
|$precedingChecks
|$nullChecks
|$nestedNullChecks
- |${genPredicate(c, bound, nullFlag)}
+ |$predicate
""".stripMargin.trim
}.mkString("\n")
+ // A check on an expression is also left here when its columns got
synthetic checks: those
+ // only make the tightened binding safe, and the expression itself can
still be NULL.
val nullChecks = notNullPreds.zipWithIndex.map { case (c, idx) =>
if (!generatedIsNotNullChecks(idx)) {
genNotNull(c)
@@ -416,9 +470,8 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
private val notNullAttributes =
notNullPreds.flatMap(_.references).distinct.map(_.exprId)
// `otherPreds` bound against this operator's `output`, shared by the CSE
gate in `doConsume`
- // and both predicate code paths, the CSE branch and
`generatePredicateCode`. Codegen-only
- // derived state, so `@transient`: it is computed on the driver during code
generation and
- // never accessed on executors.
+ // and `generatePredicateCode`. Codegen-only derived state, so `@transient`:
it is computed on
+ // the driver during code generation and never accessed on executors.
@transient private lazy val boundOtherPreds: Seq[Expression] =
otherPreds.map(BindReferences.bindReference(_, output))
@@ -452,202 +505,34 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
override def doConsume(ctx: CodegenContext, input: Seq[ExprCode], row:
ExprCode): String = {
val numOutput = metricTerm(ctx, "numOutputRows")
- // Apply CSE to otherPreds, mirroring the non-CSE branch's ordering so we
preserve
- // short-circuit semantics. The non-CSE branch lives in
`generatePredicateCode`
- // above; any future change to that algorithm should be reflected here
(and vice
- // versa) -- the two paths must stay in lockstep on notNullPreds/otherPreds
- // interleaving. Three invariants:
- // (a) Between otherPreds: emit each common subexpression's precompute
*just
- // before* the first otherPred that references it, not at the top of
the
- // `do { }` block. A later otherPred still reuses the cached value
-- it just
- // doesn't pay the cost for rows an earlier otherPred rejected. See
#55471.
- // (b) Between notNullPreds and otherPreds: `notNullPreds` may include
- // `IsNotNull(expensive_or_throwing)` inferred by
`InferFiltersFromConstraints`,
- // so emitting all notNullPreds up front would evaluate the inner
expression
- // on rows an earlier-ordered otherPred would have rejected -- same
class of
- // bug as (a) but across the notNullPreds / otherPreds boundary.
Per-otherPred,
- // for each reference `r`: if `notNullPreds` has a direct
`IsNotNull(r)`, emit
- // it; else if `r` is covered by `notNullAttributes` through some
complex
- // `IsNotNull(expr(r))` in `notNullPreds`, emit a synthetic
`IsNotNull(r)` so
- // the tightened-output binding below is safe without evaluating the
- // throw-capable inner expression. Then emit the otherPred's CSE
precompute
- // and body. Remaining notNullPreds (including complex-child forms
whose refs
- // got synthetic coverage) emit after all otherPreds. With the
NULL-conjunct
- // flag, once an otherPred that can be NULL is emitted, the
notNullPreds that
- // precede a later otherPred in the condition are emitted before it
first, when it
- // or one of them can raise (`precedingNotNullChecks`), and a complex
- // `IsNotNull(expr)` written after the otherPred is left to the
remaining
- // notNullPreds, so it does not raise on a row the otherPred
rejects, as in the
- // non-CSE branch (SPARK-60315).
- // (c) CSE state materialization: binding otherPreds (and the CSE
analysis)
- // against `output` (with `notNullAttributes` tightened to
non-nullable)
- // requires that the matching IsNotNull has already short-circuited
-- else
- // CSE's `value_X = isNull ? default : compute` materializes `null`
into
- // `value_X` for non-primitive types, which downstream accessors may
NPE on
- // 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`.
- //
- // 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
- // `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.
- //
- // `subexpressionElimination.filterExec.enabled` additionally gates this
path so it can be
- // turned off independently of subexpression elimination elsewhere.
- val (prologueCode, 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)
-
- val subExprs =
-
ctx.subexpressionEliminationForWholeStageCodegen(otherPredsEquivalentExpressions)
-
- val nullFlag = nullConjunctFlag(ctx, otherPreds, boundOtherPreds,
notNullPreds)
-
- // Group CSE states by the index of the first otherPred that
references them.
- // `evaluateSubExprEliminationState` recursively emits each state's
children
- // before the state itself and marks emitted code as `EmptyBlock`, so
emitting
- // a later group whose states depend on an earlier group's states is a
no-op
- // for the already-emitted dependencies.
- val statesByFirstUse: Map[Int, Seq[SubExprEliminationState]] =
- subExprs.states.toSeq.groupBy { case (exprEq, _) =>
- ctx.firstReferencingExpression(boundOtherPreds, exprEq)
- }.map { case (idx, kvs) => idx -> kvs.map(_._2) }
-
- // Emit an IsNotNull check, binding against child.output so the inner
expression
- // is evaluated with its original nullability (the
tightened-nullability `output`
- // is only appropriate inside otherPreds, where the required checks
have fired).
- // Passing `bound.nullable` to `conjunctCheck` is defensive --
`IsNotNull` always
- // produces a non-nullable Boolean, so its NULL handling is
unreachable here; the
- // non-CSE helper generates its IsNotNull checks the same way. The
check does not get
- // the NULL-conjunct flag: it must drop the row before the otherPreds
and CSE
- // precomputes bound with its column non-nullable, see (c).
- def genNotNull(pred: Expression): String = {
- val bound = BindReferences.bindReference(pred, child.output)
- val evaluated = evaluateRequiredVariables(child.output, input,
pred.references)
- val ev = ExpressionCanonicalizer.execute(bound).genCode(ctx)
- s"""
- |$evaluated
- |${ev.code}
- |${conjunctCheck(ev, bound.nullable, None)}
- """.stripMargin
- }
-
- // Emit a check on a complex expression with no CSE state: the
expression is bound
- // against child.output, with its original nullability, while the CSE
states are
- // computed over `boundOtherPreds`, bound against the tightened
`output`, and a state
- // precomputed for the check could materialize a NULL into a shared
variable, see (c).
- def genNotNullWithoutCSE(pred: Expression): String = {
- var checkCode: String = null
- ctx.withSubExprEliminationExprs(Map.empty) {
- checkCode = genNotNull(pred)
- Seq.empty
- }
- checkCode
- }
-
- val generatedIsNotNullChecks = new Array[Boolean](notNullPreds.length)
- val extraIsNotNullAttrs = mutable.Set[Attribute]()
- var nullableSeen = false
-
- val predCode: String = {
- val parts = new StringBuilder
- ctx.withSubExprEliminationExprs(subExprs.states) {
- otherPreds.zip(boundOtherPreds).zipWithIndex.foreach {
- case ((orig, bound), idx) =>
- val afterNullable = nullFlag.isDefined && nullableSeen
- precedingNotNullChecks(
- notNullPreds, precedingNotNulls, idx, orig, afterNullable,
- generatedIsNotNullChecks).foreach { p =>
- parts.append(genNotNullWithoutCSE(p))
- parts.append('\n')
- }
- nullableSeen ||= bound.nullable
- orig.references.foreach { r =>
- val ni = notNullPreds.indexWhere {
- case IsNotNull(c) => c.semanticEquals(r)
- case _ => false
- }
- if (ni != -1 && !generatedIsNotNullChecks(ni)) {
- generatedIsNotNullChecks(ni) = true
- parts.append(genNotNull(notNullPreds(ni)))
- parts.append('\n')
- } else if ((ni == -1 || !afterNullable) &&
notNullAttributes.contains(r.exprId) &&
- !extraIsNotNullAttrs.contains(r)) {
- // As in `generatePredicateCode`: after a nullable
otherPred, a check
- // generated by `precedingNotNullChecks` already covers
the column.
- extraIsNotNullAttrs += r
- parts.append(genNotNull(IsNotNull(r)))
- parts.append('\n')
- }
- }
- // A complex `IsNotNull(expr)` is skipped after a nullable
otherPred, see (b).
- if (!afterNullable) {
- notNullPreds.zipWithIndex.foreach {
- case (p @ IsNotNull(n), ni)
- if !generatedIsNotNullChecks(ni) &&
!n.isInstanceOf[Attribute] &&
- orig.exists(_.semanticEquals(n)) =>
- generatedIsNotNullChecks(ni) = true
- parts.append(genNotNullWithoutCSE(p))
- parts.append('\n')
- case _ =>
- }
- }
- statesByFirstUse.get(idx).foreach { states =>
- parts.append(ctx.evaluateSubExprEliminationState(states))
- parts.append('\n')
- }
- val ev = ExpressionCanonicalizer.execute(bound).genCode(ctx)
- parts.append(ev.code.toString)
- parts.append(s"\n${conjunctCheck(ev, bound.nullable,
nullFlag)}\n")
- }
- Seq.empty
- }
- parts.toString
- }
+ // 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.
+ 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 subExprs =
+
ctx.subexpressionEliminationForWholeStageCodegen(otherPredsEquivalentExpressions)
+ (evalCode, subExprs.states)
+ } else {
+ ("", Map.empty[ExpressionEquals, SubExprEliminationState])
+ }
- // Leftover notNullPreds: any IsNotNull that no otherPred's reference
matched by
- // `semanticEquals`. These run after all otherPreds to match the
non-CSE ordering.
- // Note: a complex `IsNotNull(expr(r))` can still land here even when
the (b) path
- // already emitted a synthetic `IsNotNull(r)` ahead of some otherPred
-- the
- // synthetic check only guards the tightened-output binding; the inner
expression
- // itself may still need its null check (e.g. under non-ANSI `cast(s
as int)` can
- // return null for unparseable strings, so we must filter the
resulting row).
- val leftoverNotNull = notNullPreds.zipWithIndex.collect {
- case (p, i) if !generatedIsNotNullChecks(i) => genNotNull(p)
- }.mkString("\n")
-
- (inputVarsEvalCode, withNullConjunctFlag(predCode + "\n" +
leftoverNotNull, nullFlag))
- } else {
- ("", generatePredicateCode(
- ctx, child.output, input, notNullPreds, otherPreds, boundOtherPreds,
- precedingNotNulls, notNullAttributes))
- }
+ val predicateCode = generatePredicateCode(
+ ctx, child.output, input, notNullPreds, otherPreds, boundOtherPreds,
precedingNotNulls,
+ notNullAttributes, subExprStates)
// Reset the isNull to false for the not-null columns, then the followed
operators could
// generate better code (remove dead branches).
@@ -661,7 +546,7 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
// Note: wrap in "do { } while (false);", so the generated checks can jump
out with "continue;"
s"""
|do {
- | $prologueCode
+ | $inputVarsEvalCode
| $predicateCode
| $numOutput.add(1);
| ${consume(ctx, resultVars)}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
index 0444471df733..67f19edc95d5 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
@@ -26,7 +26,7 @@ import scala.util.{Failure, Success, Try}
import org.apache.logging.log4j.Level
import org.scalatest.time.SpanSugar._
-import org.apache.spark.{SparkArithmeticException, SparkException,
SparkNumberFormatException}
+import org.apache.spark.{SparkArithmeticException, SparkException,
SparkNumberFormatException, SparkThrowable}
import org.apache.spark.metrics.source.CodegenMetrics
import org.apache.spark.rdd.{MapPartitionsWithEvaluatorRDD, RDD}
import org.apache.spark.sql.{DataFrame, Dataset, Row, SaveMode}
@@ -1503,11 +1503,10 @@ class WholeStageCodegenSuite extends SharedSparkSession
}
test("SPARK-51356: FilterExec CSE emits IsNotNull on a nested field before
its otherPred") {
- // Same defect as above, on the CSE branch of `FilterExec.doConsume`,
which inlines its own
- // copy of the interleaving. Two otherPreds share the non-cheap `f(c)`, so
the branch is
- // taken (a bare `b.c` is cheap and would fall back to
`generatePredicateCode`). The
- // guarding `IsNotNull(b.c)` has to be emitted ahead of the shared CSE
precompute, not after
- // the predicates that consume it.
+ // Same defect as above, with a common subexpression eliminated in
`FilterExec.doConsume`.
+ // Two otherPreds share the non-cheap `f(c)`, so it is eliminated (a bare
`b.c` is cheap
+ // and would not be). The guarding `IsNotNull(b.c)` has to be emitted
ahead of the shared CSE
+ // precompute, not after the predicates that consume it.
val data = Seq(
Spark51356Outer(null),
Spark51356Outer(Spark51356Mid(null)), // the row that used to trigger
the failure
@@ -3382,6 +3381,112 @@ class WholeStageCodegenSuite extends SharedSparkSession
}
}
+ // The conditions of the test below, with whether FilterExec eliminates a
common subexpression
+ // from them. They mix columns that can be NULL, IS NOT NULL checks that are
written or inferred,
+ // on columns and on expressions, before and after the conjuncts that
reference them, conjuncts
+ // that can be NULL, common subexpressions, and conjuncts that can raise an
error.
+ private val filterConjunctions: Seq[(String, Boolean)] = Seq(
+ "NOT (a > 0 AND b > 0) AND y + 1 > 0" -> false,
+ "NOT (a > 0 AND b > 0) AND y + 1 > 0 AND y + 1 > -1" -> true,
+ "(a > 0 OR b < 0) AND y + 1 > 0" -> false,
+ "b > 0 AND y > -1" -> false,
+ "(a > 0 OR b > 0) AND x = 1 AND y + 1 > 0" -> false,
+ "x IS NOT NULL AND NOT (a > 0 AND b > 0) AND y + 1 > 0 AND b * 2 > 0 AND b
* 2 > -1" -> true,
+ "NOT (a > 0 AND b > 0) AND y + 1 > 0 AND x > 0" -> false,
+ "NOT (a > 0 AND b > 0) AND y + 1 > 0 AND x IS NOT NULL" -> false,
+ "NOT (a > 0 AND b > 0) AND y + 1 > 0 AND x IS NOT NULL AND b * 2 > 0 AND b
* 2 > -1" -> true,
+ "NOT (a > 0 AND b > 0) AND b * 2 > 0 AND b * 2 > -1 AND " +
+ "coalesce(b, cast(s AS INT)) < 2 AND cast(s AS INT) IS NOT NULL" -> true,
+ "NOT (a > 0 AND b > 0) AND coalesce(b, cast(s AS INT)) < 2 AND " +
+ "cast(s AS INT) IS NOT NULL" -> false,
+ "NOT (a > 0 AND b > 0) AND b * 2 > 0 AND b * 2 > -1 AND " +
+ "coalesce(b, cast(s AS INT)) < 0 AND cast(s AS INT) IS NOT NULL" -> true,
+ "NOT (a > 0 AND b > 0) AND coalesce(b, cast(s AS INT)) < 0 AND " +
+ "cast(s AS INT) IS NOT NULL" -> false,
+ "cast(s AS INT) IS NOT NULL AND (a > 0 OR b > 0) AND y < 0" -> false,
+ "x IS NOT NULL AND NOT (a > 0 AND b > 0) AND y + 1 > 0 AND y + 1 > -1" ->
true,
+ "b < 0 AND y + 1 > 0 AND y + 1 > -1" -> true,
+ "a > 0 AND x > 0 AND a * x > 3 AND a * x < 100" -> true,
+ "cast(s AS INT) > 0 AND cast(s AS INT) < 10 AND a > 0" -> true,
+ "a > 1 AND cast(s AS INT) + x > 0 AND cast(s AS INT) + x < 10 AND " +
+ "cast(s AS INT) IS NOT NULL" -> true,
+ "st.c.d > 0 AND st.c.d < 100" -> false,
+ "st.c.d > 0 AND st.c.d * a > 3 AND st.c.d * a < 100" -> true,
+ "st.c IS NOT NULL AND st.c.d + y > 0 AND st.c.d + y < 5 AND x IS NOT NULL"
-> true,
+ "upper(s) = 'X' AND length(upper(s)) > 0 AND a IS NOT NULL" -> true)
+
+ test("SPARK-61556: a filter gives the same result with and without
subexpression " +
+ "elimination") {
+ // The rows of a query, or the error condition that it fails with.
+ def outcome(query: String): Either[String, Seq[String]] = {
+ try {
+ Right(sql(query).collect().map(_.toString).sorted.toSeq)
+ } catch {
+ case e: Throwable =>
+ val error = Iterator.iterate(e)(_.getCause).takeWhile(_ !=
null).collectFirst {
+ case t: SparkThrowable if t.getCondition != null => t.getCondition
+ }
+ Left(error.getOrElse(throw e))
+ }
+ }
+ // With whole-stage codegen, FilterExec eliminates the common
subexpressions under both
+ // configs. Without it, the condition is a generated predicate under the
first config alone.
+ val subExprConfs = Seq(("true", "true"), ("true", "false"), ("false",
"false"))
+ // On the first set of rows, `y + 1` overflows and `cast(s AS INT)` fails
in ANSI mode.
+ val rowSets = Seq(
+ s"(NULL, 1, ${Int.MaxValue}, NULL, 'x'), (0, 1, 0, 1, '1'), (1, NULL, 3,
2, '2'), " +
+ s"(2, 5, ${Int.MaxValue}, 1, NULL), (3, 2, 1, NULL, '7'), (1, 1, 1, 1,
'x')",
+ "(NULL, 1, 5, NULL, '3'), (0, 1, 0, 1, '1'), (1, NULL, 3, 2, '2'), (2,
5, 7, 1, NULL), " +
+ "(3, 2, 1, NULL, '7'), (1, 1, 1, 1, '4'), (2, 3, -1, 2, 'X'), " +
+ "(NULL, NULL, NULL, NULL, NULL)")
+ rowSets.foreach { rows =>
+ withTable("t") {
+ // A Parquet table, so that the optimizer does not evaluate the
filter. A single file
+ // keeps the order of the rows, and so the first row that a query
fails on.
+ sql("CREATE TABLE t USING parquet AS SELECT /*+ COALESCE(1) */ *, " +
+ "IF(a = 3, NULL, named_struct('c', named_struct('d', b))) AS st " +
+ s"FROM VALUES $rows AS v(a, b, y, x, s)")
+ for (ansi <- Seq(true, false); legacy <- Seq(true, false);
+ (condition, eliminates) <- filterConjunctions) {
+ val query = s"SELECT a, b, y, x, s FROM t WHERE $condition"
+ def run(wholeStage: Boolean, subExprConf: (String, String)):
Either[String, Seq[String]] =
+ withSQLConf(
+ SQLConf.ANSI_ENABLED.key -> ansi.toString,
+ SQLConf.LEGACY_FILTER_SHORT_CIRCUIT_ON_NULL_CONJUNCT.key ->
legacy.toString,
+ SQLConf.PARQUET_FILTER_PUSHDOWN_ENABLED.key -> "false",
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage.toString,
+ SQLConf.SUBEXPRESSION_ELIMINATION_ENABLED.key ->
subExprConf._1,
+ SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key ->
subExprConf._2) {
+ outcome(query)
+ }
+ withClue(s"ansi=$ansi, legacy=$legacy, condition=$condition: ") {
+ val outcomes = Seq(true, false).map { wholeStage =>
+ val results = subExprConfs.map(run(wholeStage, _))
+ assert(results.distinct.size == 1, s"wholeStage=$wholeStage")
+ results.head
+ }
+ // The legacy behavior drops a row at its first NULL conjunct with
whole-stage
+ // codegen alone, so the two can differ under it.
+ if (!legacy) {
+ assert(outcomes.distinct.size == 1)
+ }
+ // The conditions take the code path that they are meant to cover.
+ val codes = Seq("true", "false").map { filterExecCSE =>
+ withSQLConf(
+ SQLConf.ANSI_ENABLED.key -> ansi.toString,
+ SQLConf.LEGACY_FILTER_SHORT_CIRCUIT_ON_NULL_CONJUNCT.key ->
legacy.toString,
+ SQLConf.PARQUET_FILTER_PUSHDOWN_ENABLED.key -> "false",
+ SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key ->
filterExecCSE) {
+ genCode(sql(query)).map(_.body)
+ }
+ }
+ assert((codes.head != codes.last) == eliminates)
+ }
+ }
+ }
+ }
+ }
+
test("SPARK-60403: full outer joins compile with their functions spilled to
nested classes") {
// A full outer join outputs its rows through a function of its own, and
generates the code of
// the operators above it, for the body of that function, before adding
the function: here a
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]