spark-test commented on code in PR #58635:
URL: https://github.com/apache/spark/pull/58635#discussion_r4508394347
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/dynamicpruning/PartitionPruning.scala:
##########
@@ -113,18 +114,26 @@ object PartitionPruning extends Rule[LogicalPlan] with
PredicateHelper with Join
} else {
None
}
- lazy val hasBenefit = pruningHasBenefit(
+ // A [[RuntimeFilterHint]] on the filtering side asserts the benefit
`pruningHasBenefit`
+ // estimates, so take it as given rather than guessing from statistics and
filter ratios.
+ lazy val hasBenefit = hinted || pruningHasBenefit(
pruningKey, partScan, filteringKeys.head, filteringPlan,
hasSelectivePredicate(filteringPlan))
if (reuseEnabled || hasBenefit) {
+ // `reuseBroadcastOnly` keeps DPP from re-executing the filtering side
unless a broadcast
+ // can be reused, i.e. unless pruning is free. That is a cost bound, and
the cost is what
+ // a [[RuntimeFilterHint]] asks to spend: a hinted filter is applied
whether or not a
+ // broadcast turns up, rather than degrading to `true` in
[[PlanDynamicPruningFilters]].
+ val onlyInBroadcast = !hinted &&
+ (conf.dynamicPartitionPruningReuseBroadcastOnly || !hasBenefit)
// insert a DynamicPruning wrapper to identify the subquery during query
planning
- Filter(
- DynamicPruningSubquery(
- pruningKey,
- filteringPlan,
- joinKeys,
- indices,
- conf.dynamicPartitionPruningReuseBroadcastOnly ||
!hasBenefit)(broadcastValueProjection),
- pruningPlan)
+ val pruning = DynamicPruningSubquery(
+ pruningKey,
+ filteringPlan,
+ joinKeys,
+ indices,
+ onlyInBroadcast)(broadcastValueProjection)
+ if (hinted)
pruning.setTagValue(DynamicPruning.HONORS_RUNTIME_FILTER_HINT, ())
Review Comment:
**Nit (P3):** When `CleanupDynamicPruningFilters` removes a DPP filter
tagged here, for example because `f.part = 1` already fixes the partition key
or the filter never reached a scan, it replaces the filter with the shared
`Literal.TrueLiteral`, and `transformDownWithPruning` copies the removed node's
tags onto that replacement. The tag then lives on a constant every query
shares, written through `copyTagsFrom`'s unsynchronized lazy allocation by
optimizer threads of concurrent sessions, and later transforms can copy it onto
nodes that replace the literal. Nothing reads the tag outside
`DynamicPruningSubquery` today, so results are unaffected, but the tag no
longer stays with its plan.
**Verification:**
- **Regression:** After optimizing a hinted join whose DPP filter cleanup
removes because a literal fixes the partition key, the shared true literal has
no tags.
- **Compatibility:** Plans in which cleanup replaces a DPP filter with true
simplify exactly as before.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -411,56 +484,191 @@ object InjectRuntimeFilter extends Rule[LogicalPlan]
with PredicateHelper with J
private def tryInjectRuntimeFilter(plan: LogicalPlan): LogicalPlan = {
var filterCounter = 0
val numFilterThreshold =
conf.getConf(SQLConf.RUNTIME_FILTER_NUMBER_THRESHOLD)
+ val bloomFilterEnabled = conf.runtimeFilterBloomFilterEnabled
plan transformUp {
+ case join: Join if isRuntimeFilterHintDecided(join.hint) => join
+ // Only a hinted join has anything to do with Bloom filters disabled.
+ case join: Join if !bloomFilterEnabled &&
!hasRuntimeFilterHint(join.hint) => join
case join @ ExtractEquiJoinKeys(joinType, leftKeys, rightKeys, _, _,
left, right, hint) =>
var newLeft = left
var newRight = right
- leftKeys.lazyZip(rightKeys).foreach((l, r) => {
- // Check if:
- // 1. There is already a DPP filter on the key
- // 2. The keys are simple cheap expressions
- if (filterCounter < numFilterThreshold &&
- !hasDynamicPruningSubquery(left, right, l, r) &&
- isSimpleExpression(l) && isSimpleExpression(r)) {
- val oldLeft = newLeft
- val oldRight = newRight
- // Check if:
- // 1. The current join type supports prune the left side with
runtime filter
- // 2. The current join is a shuffle join or a broadcast join that
- // has a shuffle below it
- // 3. There is no bloom filter on the left key yet
- val hasShuffle = isProbablyShuffleJoin(left, right, hint)
- if (canPruneLeft(joinType) && (hasShuffle ||
probablyHasShuffle(left)) &&
- !hasBloomFilter(newLeft, l)) {
- extractBeneficialFilterCreatePlan(left, right, l, r).foreach {
creationSide =>
- newLeft = injectFilter(l, newLeft, creationSide)
+ // A side hinted as the runtime filter source is the creation side, so
the filter is
+ // applied to the other side. An ambiguous hint is reported and
otherwise ignored, leaving
+ // the heuristics to decide.
+ val hintedSource = runtimeFilterSourceSide(hint)
+ val hinted = hintedSource.isDefined
+ val injectLeftHinted = hintedSource.contains(BuildRight)
+ val injectRightHinted = hintedSource.contains(BuildLeft)
+ if (isRuntimeFilterHintAmbiguous(hint)) {
+ reportHintNotApplied(join,
+ "the runtime filter source is ambiguous as both join sides are
hinted")
+ }
+ var appliedHint = false
+ // The first reason the hint could not be applied on a key. The hinted
side is the same
+ // for every key, so the first reason is as representative as any.
+ var notAppliedReason: Option[String] = None
+ def hintBlocked(reason: => String): Unit = {
+ if (notAppliedReason.isEmpty) notAppliedReason = Some(reason)
+ }
+ lazy val hasShuffle = isProbablyShuffleJoin(left, right, hint)
+ // Tries to filter `applicationSide` with a filter built from
`creationSide`. Returns the
+ // filtered side, or `currentApplicationSide` when no filter was
added, recording the
+ // reason when this direction is the hinted one. Requirements:
+ // 1. The join type supports pruning the application side
+ // 2. The application side is not the hinted source, which is never
itself filtered
+ // 3. The join is a shuffle join, or a broadcast join with a shuffle
below it -- an
+ // estimate of whether the filter pays off, so a hint waives it
+ // 4. There is no Bloom filter on the application side's key yet, and
the key is not fixed
+ // by a literal, unless the creation side is hinted
+ def tryInject(
+ applicationSide: LogicalPlan,
+ currentApplicationSide: LogicalPlan,
+ applicationSideKey: Expression,
+ creationSide: LogicalPlan,
+ creationSideKey: Expression,
+ canPrune: Boolean,
+ applicationHinted: Boolean,
+ creationHinted: Boolean,
+ sideName: String): LogicalPlan = {
+ if (!canPrune) {
+ if (applicationHinted) {
+ // `ExistenceJoin.sql` throws, as the type never appears in SQL.
+ val joinDescription = joinType match {
+ case _: ExistenceJoin => "an existence"
+ case _ => s"a ${joinType.sql.toLowerCase(Locale.ROOT)}"
}
+ hintBlocked(s"the $sideName side of $joinDescription join cannot
be pruned")
}
+ currentApplicationSide
+ } else if (applicationHinted) {
+ // Unlike the heuristics below, a hinted side adds its own filter
even on a key that
+ // already has one.
+ runtimeFilterHintRejection(applicationSideKey, creationSide,
creationSideKey) match {
+ case Some(reason) =>
+ hintBlocked(reason)
+ currentApplicationSide
Review Comment:
**Blocking (P1):** When `runtimeFilterHintRejection` declines the hinted
side, this returns the application side unchanged without trying the
heuristics, the opposite direction is skipped because its application side is
the hinted source, and `PartitionPruning`'s `!pruneRightHinted` and
`!pruneLeftHinted` guards keep DPP off the hinted side. So a hint Spark cannot
apply removes the runtime filters the base branch builds for the same join,
where the hint name is simply dropped. For example, a hinted `t = SELECT k -
100 AS k, py_identity(k) AS x FROM dim WHERE attr = 'x'` is declined for the
UDF in the unused column `x`, and the fact side loses the Bloom filter the
heuristics build from `dim` without the hint. The runtime filter facet also
keeps `ReorderJoin` and `CostBasedJoinReorder` away from the join before the
hint is decided, so `SELECT /*+ RUNTIME_FILTER(t) */ * FROM d1, (SELECT k FROM
d2 LIMIT 10) t, f WHERE f.k1 = d1.k AND f.k2 = t.k` keeps `d1 x t` as a
cartesian product t
hat the base branch reorders into equi-joins. The same happens for a hint that
names both sides, which the reference says is ignored.
This extends an [existing
discussion](https://github.com/apache/spark/pull/58635#pullrequestreview-5152493283).
**Recommended change:** When the hint's eligibility check rejects the hinted
side on every key of a join, plan the join as if it had no hint: let
InjectRuntimeFilter try the heuristic Bloom filter in both directions and let
PartitionPruning prune either side from its own estimates, while still
reporting the reason. So that such a hint, or one that names both sides, does
not fix the join order either, let ReorderJoin's flattening and
CostBasedJoinReorder treat a join whose runtime filter facet is ambiguous, or
sits on a side that fails the part of the check that depends neither on the
join keys nor on the filter path, as a join without a hint, and report the hint
there. Update the SQL reference and the runtime filter test that now asserts
that a declined hint builds no filter in the other direction.
**Why this works:** The suppression of the heuristics, of the opposite
direction and of DPP on the hinted side becomes conditional on the hinted side
being eligible, and the reorder rules ignore a facet that Spark will not apply
for a reason no join order removes, so a declined or ignored hint reproduces
the plan built without it.
**Scope:** Make a declined or ignored hint leave the join's runtime filters
and order as they are without the hint.
**Compatibility:** An applied hint keeps its semantics, including that its
hinted side is never pruned and that it fixes the join order around the hinted
relation.
**Risks:** A join whose hint is rejected may now get a filter in the
opposite direction, DPP on the hinted side or a different join order, which the
SQL reference and a test currently rule out; this reproduces the base branch's
plan. In the hinted direction the restored heuristics can build the filter the
base branch builds from a side the warning calls not repeatable, such as one
whose selective filter calls rand() or that reads an uncheckpointed RDD; that
exposure is the base branch's and reaches the same query without the hint, so
it is left to a separate change. A hint the reorder rules drop is reported
there, a second place that has to keep a single warning per hint.
**Constraints:** A hint that is applied still never prunes its hinted side
and still fixes the join order around the hinted relation. The not-applied
warning still names the reason, once per hint.
**Exclusions:**
- DPP on the hinted side for a hint that passes the eligibility check but is
then declined by a Bloom filter limit, such as the filter count or a non-simple
key, which PartitionPruning cannot foresee; leave a TODO there.
- The written join order for a hint that passes the key-independent part of
the check when the joins are reordered and is declined later, for a join key, a
limit or a function, which the reorder rules cannot foresee; leave a TODO there.
- The heuristics' own exposure to a creation side that does not repeat,
which exists on the base branch for the same query without the hint.
**Success:** A join whose hinted side Spark rejects has the runtime filters
Spark builds for the same query without the hint, plus the not-applied warning.
A hint on a side that fails the key-independent part of the check, or that
names both sides, leaves the join order as without the hint, so a comma join it
touches is reordered into equi-joins, and the hint is reported once. An applied
hint keeps building its filter from the hinted side, never prunes that side and
still fixes the join order.
**Verification:**
- **Regression:** A hinted side rejected as not repeatable, opposite a
selective side, gets the Bloom filter that the heuristics build onto it without
the hint.
- **Regression:** A hinted side rejected for a property outside the
heuristic filter's extracted plan gets the heuristic Bloom filter in the hinted
direction when the heuristics build one without the hint, and the warning is
still logged.
- **Regression:** A rejected hinted side that is a partitioned table,
opposite a selective side, is pruned by DPP from its own estimates as without
the hint.
- **Regression:** A comma join whose hinted relation is not next to its
equi-join partner is reordered into equi-joins, as without the hint, when that
relation is rejected as not repeatable or the hint names both sides, and the
hint is reported once.
- **Compatibility:** An applied hint still builds its filter from the hinted
side, never prunes that side, by Bloom filter or DPP, and keeps the join order
around the hinted relation.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -578,3 +640,286 @@ trait JoinSelectionHelper extends Logging {
conf.getConfString("spark.sql.join.forceApplyShuffledHashJoin", "false")
== "true"
}
}
+
+/**
+ * Decides whether a plan can serve as the source of a runtime filter on a
join key. A runtime
+ * filter evaluates its source separately from the join, so the rows the
source produces and the
+ * key values they carry must be the same in both evaluations, or the filter
could prune rows the
+ * join itself matches. `deterministic` is not enough for that: Spark flags
order-dependent
+ * computations such as first, last, row_number or an unordered LIMIT as
deterministic, and a leaf
+ * such as an RDD that is not checkpointed may return different rows on each
computation.
+ *
+ * The plan is walked bottom-up, tracking:
+ * 1. output attributes whose values are unstable: they come from a
non-deterministic expression,
+ * an order-dependent aggregate or window function, a subquery whose plan
fails this same
+ * analysis, or an expression over such an attribute;
+ * 2. whether the row multiplicity is unstable, i.e. every row is still
present but may be
+ * repeated a different number of times, which an outer generate with an
unstable generator,
+ * or an aggregate over an unstable value, causes and which makes every
aggregate over the
+ * rows unstable.
+ *
+ * The plan is rejected outright when its row set is unstable (a filter or
join condition consumes
+ * an unstable attribute, an inner generate uses an unstable generator, any
limit, offset or
+ * sample), when a leaf cannot promise the same rows again, and, each with its
own reason, when it
+ * calls a function the filter subquery cannot evaluate, when an operator
would duplicate an
+ * observation or is not analyzed. The source qualifies when the key references
+ * no unstable attribute. Values that are unstable but only carried to the
output (a `first(name)`
+ * next to a `GROUP BY id`, a row number next to the key) do not disqualify it.
+ */
+private[optimizer] object RuntimeFilterSourceAnalysis {
+
+ /**
+ * @param unstable output attributes whose values depend on evaluation order
or on chance.
+ * @param unstableMultiplicity whether rows may be repeated a different
number of times per
+ * evaluation, while each row stays present.
+ */
+ private case class Taint(unstable: AttributeSet, unstableMultiplicity:
Boolean = false)
+
+ private val NotRepeatable =
+ "the hinted side may produce different rows or join keys when evaluated
again"
+
+ /** Why `plan` is not a repeatable source of `key`, or None when it is. */
+ def rejection(plan: LogicalPlan, key: Expression): Option[String] = {
+ if (plan.isStreaming) {
+ Some("the hinted side is a stream")
+ } else if (containsExtractedFunction(plan) ||
+ // A DPP filter evaluates the key in its own subquery, which no UDF
extraction rewrites.
+ key.containsAnyPattern(PYTHON_UDF, EXTERNAL_UDF)) {
+ Some("the hinted side contains a Python UDF, Python UDTF or external
UDF, which a runtime " +
+ "filter cannot evaluate")
+ } else {
+ analyze(plan) match {
+ case Left(reason) => Some(reason)
+ case Right(t) if !isStable(key, t.unstable) => Some(NotRepeatable)
+ case _ => None
+ }
+ }
+ }
+
+ def isRepeatableExpression(e: Expression): Boolean = isStable(e,
AttributeSet.empty)
+
+ def containsExtractedFunction(plan: LogicalPlan): Boolean = {
+ plan.containsAnyPattern(PYTHON_UDF, EXTERNAL_UDF) || plan.exists {
+ case g: Generate => g.generator.isInstanceOf[PythonUDTF]
+ case _ => false
+ }
+ }
+
+ /**
+ * Whether `e` yields the same value on every evaluation. A subquery counts
as deterministic
+ * when its plan is, which is the very check this analysis replaces, so its
plan is analyzed
+ * too.
+ */
+ private def isStable(e: Expression, unstable: AttributeSet): Boolean = {
+ e.deterministic && e.references.intersect(unstable).isEmpty && !e.exists {
+ case s: SubqueryExpression => !isRepeatableSubquery(s)
+ case _ => false
+ }
+ }
+
+ /**
+ * A subquery is repeatable when its row set is, and so is whatever of its
output the subquery
+ * exposes: the build keys of a DPP filter, nothing but existence for
EXISTS, the output columns
+ * otherwise. A scalar subquery fails on more than one row, so its
multiplicity counts too.
+ */
+ private def isRepeatableSubquery(s: SubqueryExpression): Boolean = {
+ !s.plan.isStreaming && analyze(s.plan).exists { t =>
+ s match {
+ case d: DynamicPruningSubquery =>
+ d.broadcastKeyIndices.forall(i => isStable(d.buildKeys(i),
t.unstable))
+ case _: Exists => true
+ case _: ScalarSubquery =>
+ !t.unstableMultiplicity &&
s.plan.outputSet.intersect(t.unstable).isEmpty
+ case _ => s.plan.outputSet.intersect(t.unstable).isEmpty
+ }
+ }
+ }
+
+ /** Returns the taint of `plan`'s output, or the reason its row set is not
repeatable. */
+ private def analyze(plan: LogicalPlan): Either[String, Taint] = plan match {
+ // Whether a materialized leaf returns the same rows is known only once it
is materialized.
+ case m: MaterializedLeafNode if m.materializedMetadata.isEmpty =>
+ Left(s"the hinted side reads ${m.nodeName}, which is not materialized
yet")
+
+ // The source may have absorbed an operator from the hinted side, so name
that rather than the
+ // scan the user did not write.
+ case s: DataSourceV2ScanRelation if !s.isOutputRepeatable =>
+ Left(s"the hinted side reads ${s.name} with an aggregate, limit, offset,
top-N or sample " +
+ "pushed into the source, which may return different rows when
evaluated again")
+
+ case l: LeafNode =>
+ if (l.isOutputRepeatable) {
+ Right(Taint(AttributeSet.empty))
+ } else {
+ Left(s"the hinted side reads ${l.nodeName}, which may return different
rows when " +
+ "evaluated again")
+ }
+
+ case p: Project => analyze(p.child).map { t =>
+ t.copy(unstable =
+ AttributeSet(p.projectList.filterNot(isStable(_,
t.unstable)).map(_.toAttribute)))
+ }
+
+ case f: Filter => analyze(f.child).flatMap { t =>
+ if (isStable(f.condition, t.unstable)) Right(t) else Left(NotRepeatable)
+ }
+
+ case j: Join => analyze(j.left).flatMap { l =>
+ analyze(j.right).flatMap { r =>
+ val unstable = l.unstable ++ r.unstable
+ if (j.condition.forall(isStable(_, unstable))) {
+ Right(Taint(unstable, l.unstableMultiplicity ||
r.unstableMultiplicity))
+ } else {
+ Left(NotRepeatable)
+ }
+ }
+ }
+
+ case a: Aggregate => analyze(a.child).map { t =>
+ // Grouping on an unstable value changes which rows form a group, and
unstable multiplicity
+ // changes how many rows each group has, so every aggregate result then
depends on them; a
+ // grouping expression's own value is as stable as its input. With
stable grouping the
+ // groups occur once each, whatever the input multiplicity; with
unstable grouping, the
+ // number of groups that share the stable grouping values varies.
+ val stableGroups = a.groupingExpressions.forall(isStable(_, t.unstable))
+ // A group of values that are equal but not identical, e.g. under a
case-insensitive
+ // collation, outputs whichever of them arrives first.
+ val representatives = AttributeSet(a.groupingExpressions
+ .filterNot(e =>
UnsafeRowUtils.isBinaryStable(e.dataType)).flatMap(_.references))
+ val unstable = a.aggregateExpressions.filter { e =>
+ !isStable(e, t.unstable) ||
+ referencesOutsideAggregates(e).intersect(representatives).nonEmpty ||
+ (e.exists(_.isInstanceOf[AggregateExpression]) &&
+ (!stableGroups || t.unstableMultiplicity || !isOrderIrrelevant(e)))
+ }
+ Taint(AttributeSet(unstable.map(_.toAttribute)), unstableMultiplicity =
!stableGroups)
+ }
+
+ case w: Window => analyze(w.child).map { t =>
+ val stablePartitions = w.partitionSpec.forall(isStable(_, t.unstable))
+ val unstable = w.windowExpressions.filter { e =>
+ !stablePartitions || t.unstableMultiplicity || !isStable(e,
t.unstable) ||
+ !isOrderIrrelevantWindow(e)
+ }
+ t.copy(unstable = t.unstable ++
AttributeSet(unstable.map(_.toAttribute)))
+ }
+
+ case u: Union =>
+ val taints = u.children.map(analyze)
+ taints.collectFirst { case Left(reason) => Left(reason) }.getOrElse {
+ val unstable = u.output.zipWithIndex.collect {
+ case (attr, i) if u.children.zip(taints).exists {
+ case (child, Right(taint)) =>
taint.unstable.contains(child.output(i))
Review Comment:
**Nit (P3):** For each of the union's output columns this zips the children
with their taints and evaluates `child.output(i)`, even when no child has an
unstable attribute. `output` is a `def` that rebuilds the attribute list for
the usual children, such as `Project` and `Aggregate`, so the case does O(k *
C^2) work for k children of width C, and the analysis repeats per join key in
`PartitionPruning.honorsHint` and in `InjectRuntimeFilter`. A hinted side that
unions ten 300-column branches rebuilds about 900,000 attributes where 3,000
suffice. Evaluating each child's output once before the loop, and returning
early when no child has an unstable attribute, gives the same result in linear
time.
**Verification:**
- **Behavior:** Hinted sides that are unions, including one with an unstable
value in a single branch and one with unstable multiplicity in a branch, are
accepted or rejected exactly as before.
- **Inspection:** The Union case evaluates each child's output a constant
number of times, independent of the number of output columns.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -578,3 +640,286 @@ trait JoinSelectionHelper extends Logging {
conf.getConfString("spark.sql.join.forceApplyShuffledHashJoin", "false")
== "true"
}
}
+
+/**
+ * Decides whether a plan can serve as the source of a runtime filter on a
join key. A runtime
+ * filter evaluates its source separately from the join, so the rows the
source produces and the
+ * key values they carry must be the same in both evaluations, or the filter
could prune rows the
+ * join itself matches. `deterministic` is not enough for that: Spark flags
order-dependent
+ * computations such as first, last, row_number or an unordered LIMIT as
deterministic, and a leaf
+ * such as an RDD that is not checkpointed may return different rows on each
computation.
+ *
+ * The plan is walked bottom-up, tracking:
+ * 1. output attributes whose values are unstable: they come from a
non-deterministic expression,
+ * an order-dependent aggregate or window function, a subquery whose plan
fails this same
+ * analysis, or an expression over such an attribute;
+ * 2. whether the row multiplicity is unstable, i.e. every row is still
present but may be
+ * repeated a different number of times, which an outer generate with an
unstable generator,
+ * or an aggregate over an unstable value, causes and which makes every
aggregate over the
Review Comment:
**Nit (P3):** This says an aggregate over an unstable value makes the row
multiplicity unstable, but the `Aggregate` case sets `unstableMultiplicity =
!stableGroups`, so only grouping on an unstable value does; an aggregate
function over an unstable input under stable grouping only marks its own output
attribute unstable, as that case's comment explains. For `SELECT k, sum(x) FROM
t GROUP BY k` with `x` unstable, the summary implies that a later `count(*)`
over the result is unstable, while the code correctly keeps it stable. Later
cases are written against this summary, so it should name an aggregate that
groups on an unstable value.
**Verification:**
- **Inspection:** The summary's causes of unstable multiplicity are an outer
generate with an unstable generator and an aggregate whose grouping expression
is unstable, matching the cases that set it.
--
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]