peter-toth commented on code in PR #58635:
URL: https://github.com/apache/spark/pull/58635#discussion_r4529239582
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/dynamicpruning/PartitionPruning.scala:
##########
@@ -327,6 +340,31 @@ object PartitionPruning extends Rule[LogicalPlan] with
PredicateHelper with Join
case _ => (Nil, Nil)
}
+ // A side hinted as the runtime filter source is the filtering side,
so the other side is
+ // the one pruned, and the hinted side is never itself pruned. The
hint is ignored, as by
+ // [[InjectRuntimeFilter]], which reports it, when it is ambiguous or
when the hinted side
+ // cannot be a runtime filter source on any join key.
+ val hintedSource = runtimeFilterSourceSide(hint)
+ lazy val hintCheck = hintedSource.map { side =>
+ runtimeFilterHintCheck(if (side == BuildLeft) left else right,
cteDefs)
+ }
+ // Why the hinted side cannot prune the other side on the key pair `l`
and `r`. A DPP
+ // filter's subquery runs the hinted side as it is, so it checks the
functions the whole
+ // side calls (`checkFunctions`).
+ def hintRejection(l: Expression, r: Expression, checkFunctions:
Boolean): Option[String] =
+ hintCheck.flatMap { check =>
+ if (hintedSource.contains(BuildRight)) check.rejection(l, r,
checkFunctions)
+ else check.rejection(r, l, checkFunctions)
+ }
+ val declined = hintedSource.isDefined &&
+ leftKeys.lazyZip(rightKeys).forall(hintRejection(_, _,
checkFunctions = false).isDefined)
+ val pruneLeftHinted = !declined && hintedSource.contains(BuildRight)
+ val pruneRightHinted = !declined && hintedSource.contains(BuildLeft)
+ // Whether the hinted side honors the hint for pruning on the key
pair. Otherwise DPP
+ // decides from its own estimates, as without the hint.
+ def honorsHint(l: Expression, r: Expression): Boolean =
+ hintRejection(l, r, checkFunctions = true).isEmpty
Review Comment:
**Finding 23.** `honorsHint` rejects a hinted side for its own reasons, but
it does not ask whether the pruning key can fail. A hinted DPP filter is
inserted without a selectivity requirement, and on a partition column it is a
partition filter, which evaluates the key on every partition before the data
filters.
With DPP on (the default), the query from finding 22 gets one DPP filter and
no Bloom filter at this head, and it fails with `CAST_OVERFLOW`, AQE on and
off. Without the hint, the plan has no DPP filter and returns 30 rows. So a fix
for finding 22 alone does not cover this.
The heuristic DPP filter has the same exposure, tracked as SPARK-60809, but
there it needs a selective predicate and a benefit estimate. A check that the
pruning key cannot fail, the way `InjectRuntimeFilter.cannotFail` treats a
Bloom filter key, would keep the hint from introducing the failure. The hint
would then be reported as not applied, with that reason.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -533,71 +647,277 @@ object InjectRuntimeFilter extends Rule[LogicalPlan]
with PredicateHelper with J
cannotFail(leafKey) && !reused.exists(_.exists(_.fastEquals(leaf)))
}
}
+ val bloomFilterEnabled = conf.runtimeFilterBloomFilterEnabled
+ lazy val cteDefs = cteDefinitions(plan)
plan transformUp {
+ case join: Join if isRuntimeFilterHintDecided(join.hint) => join
+ // Only a hinted join has anything to do with Bloom filters disabled or
once the number of
+ // filters is reached.
+ case join: Join if !hasRuntimeFilterHint(join.hint) &&
+ (!bloomFilterEnabled || filterCounter >= numFilterThreshold) => join
case join @ ExtractEquiJoinKeys(joinType, leftKeys, rightKeys, _, _,
left, right, hint) =>
var newLeft = left
var newRight = right
- leftKeys.lazyZip(rightKeys).foreach((l, r) => {
- lazy val keyDpps = dynamicPruningSubqueries(left, l) ++
dynamicPruningSubqueries(right, r)
- // Check if:
- // 1. The keys are simple cheap expressions
- // 2. There is no DPP filter on the key that physical planning may
keep
- if (filterCounter < numFilterThreshold &&
- isSimpleExpression(l) && isSimpleExpression(r) &&
!keyDpps.exists(isKept)) {
- val oldLeft = newLeft
- val oldRight = newRight
- // The creation side for a bloom filter on `key` of `side`. It
leaves out the key's own
- // DPP filters, which physical planning drops. An expression such
as a UDF or a `LIKE`
- // in their build plan would also stop the search for the creation
side, since
- // `isSimpleExpression` sees the plan of a subquery too. If the
key has DPP filters,
- // they are all dropped, so step 3 above applies. The bloom filter
evaluates its
- // creation side again, apart from the join. Its subquery can also
read more of that
- // side than the join does, since filters on other keys, DPP
filters or bloom filters,
- // can narrow only the join's side. And the bloom filter hashes
the bytes of the key, so
- // its type must compare by its bytes, which a collated string
does not.
- def creationSide(
- side: LogicalPlan,
- key: Expression,
- other: LogicalPlan,
- otherKey: Expression): Option[FilterCreationSide] =
- extractBeneficialFilterCreatePlan(
- side, withoutDppFilters(other, keyDpps.contains), key,
otherKey).filter { c =>
- keyDpps.isEmpty ||
(UnsafeRowUtils.isBinaryStable(key.dataType) &&
- canPushDown(key, side) && canEvaluateAgain(c))
+ if (isRuntimeFilterHintAmbiguous(hint)) {
+ reportHintNotApplied(join,
+ "the runtime filter source is ambiguous as both join sides are
hinted")
+ }
+ // 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 ignored, leaving
the heuristics to
+ // decide, and so is a hinted side that cannot be a runtime filter
source on any join key.
+ val hintedSource = runtimeFilterSourceSide(hint)
+ lazy val hintCheck = hintedSource.map { side =>
+ runtimeFilterHintCheck(if (side == BuildLeft) left else right,
cteDefs)
+ }
+ // Why the hinted side cannot prune the other side on the key pair `l`
and `r`.
+ def hintRejection(l: Expression, r: Expression, checkFunctions:
Boolean): Option[String] =
+ hintCheck.flatMap { check =>
+ if (hintedSource.contains(BuildRight)) check.rejection(l, r,
checkFunctions)
+ else check.rejection(r, l, checkFunctions)
+ }
+ // The DPP filters on each key pair that prune the left side and the
right side.
+ val keyFilters = leftKeys.lazyZip(rightKeys).map { (l, r) =>
+ (l, r, dynamicPruningFilters(left, l, r),
dynamicPruningFilters(right, r, l))
+ }
+ def honorHint(filters: Seq[DynamicPruningSubquery]): Boolean =
+
filters.exists(_.getTagValue(DynamicPruning.HONORS_RUNTIME_FILTER_HINT).isDefined)
+ // A key whose DPP filter honors the hint was accepted by
[[PartitionPruning]], before a
+ // filter pushed into the hinted side could change its analysis. A
Bloom filter's subquery
+ // is checked for the functions it calls once it is built.
+ val declinedReason = hintedSource.flatMap { side =>
+ val reasons = keyFilters.map { case (l, r, leftFilters,
rightFilters) =>
+ if (honorHint(if (side == BuildRight) leftFilters else
rightFilters)) None
+ else hintRejection(l, r, checkFunctions = false)
+ }
+ if (reasons.forall(_.isDefined)) reasons.head else None
+ }
+ declinedReason.foreach(reportHintNotApplied(join, _))
+ val hinted = hintedSource.isDefined && declinedReason.isEmpty
+ val injectLeftHinted = hinted && hintedSource.contains(BuildRight)
+ val injectRightHinted = hinted && hintedSource.contains(BuildLeft)
+ // 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 (`isHintedDirection`).
Requirements:
+ // 1. The application side is not a stream with a stateful operator
(`isStatefulStream`)
+ // 2. The join type supports pruning the application side
+ // 3. The application side is not the hinted source
(`isHintedSource`), which is never
+ // itself filtered
+ // 4. 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
+ // 5. There is no Bloom filter on the application side's key yet,
unless the creation side
+ // is hinted and the filter on the key was built from another
creation side
+ def tryInject(
+ applicationSide: LogicalPlan,
+ currentApplicationSide: LogicalPlan,
+ applicationSideKey: Expression,
+ creationSide: LogicalPlan,
+ creationSideKey: Expression,
+ canPrune: Boolean,
+ isHintedDirection: Boolean,
+ isHintedSource: Boolean,
+ sideName: String,
+ keyDpps: Seq[DynamicPruningSubquery]): LogicalPlan = {
+ if (isStatefulStream(applicationSide)) {
+ if (isHintedDirection) {
+ hintBlocked(s"the $sideName side is a stream with a stateful
operator")
+ }
+ currentApplicationSide
+ } else if (!canPrune) {
+ if (isHintedDirection) {
+ // `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)}"
}
- // 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)) {
- creationSide(left, l, right, r).foreach(c => newLeft =
injectFilter(l, newLeft, c))
+ hintBlocked(s"the $sideName side of $joinDescription join cannot
be pruned")
+ }
+ currentApplicationSide
+ } else if (isHintedDirection) {
+ injectHintedFilter(applicationSide, currentApplicationSide,
applicationSideKey,
+ creationSide, creationSideKey, keyDpps)
+ } else if (isHintedSource || !(hasShuffle ||
probablyHasShuffle(applicationSide)) ||
+ hasBloomFilter(currentApplicationSide, applicationSideKey)) {
+ currentApplicationSide
+ } else {
+ // The creation side leaves out the key's own DPP filters, which
physical planning
+ // drops, and every `onlyInBroadcast` DPP filter, e.g. one a join
above pushed into it:
+ // it finds no broadcast in the bloom filter's subquery and is
`true` there. An
+ // expression such as a UDF or a `LIKE` in their build plan would
also stop the search
+ // for the creation side, since `isSimpleExpression` sees the plan
of a subquery too.
+ // If the key has DPP filters, they are all dropped, so step 3
above applies. The
+ // bloom filter evaluates its creation side again, apart from the
join. Its subquery
+ // can also read more of that side than the join does, since
filters on other keys, DPP
+ // filters or bloom filters, can narrow only the join's side. And
the bloom filter
+ // hashes the bytes of the key, so its type must compare by its
bytes, which a collated
+ // string does not.
+ val creationPlan =
+ withoutDppFilters(creationSide, dpp => dpp.onlyInBroadcast ||
keyDpps.contains(dpp))
+ extractBeneficialFilterCreatePlan(
+ applicationSide, creationPlan, applicationSideKey,
creationSideKey)
+ .filter(c => keyDpps.isEmpty ||
+ (UnsafeRowUtils.isBinaryStable(applicationSideKey.dataType) &&
+ canPushDown(applicationSideKey, applicationSide) &&
canEvaluateAgain(c)))
+ .map(injectFilter(applicationSideKey, currentApplicationSide, _))
+ .getOrElse(currentApplicationSide)
+ }
+ }
+ // Filters `applicationSide` with a Bloom filter built from the hinted
`creationSide`.
+ def injectHintedFilter(
+ applicationSide: LogicalPlan,
+ currentApplicationSide: LogicalPlan,
+ applicationSideKey: Expression,
+ creationSide: LogicalPlan,
+ creationSideKey: Expression,
+ keyDpps: Seq[DynamicPruningSubquery]): LogicalPlan = {
+ lazy val creation = FilterCreationSide(
+ creationSideKey, creationSide, useMaterializedThreshold = false,
hinted = true)
+ if (!UnsafeRowUtils.isBinaryStable(applicationSideKey.dataType) ||
+ !UnsafeRowUtils.isBinaryStable(creationSideKey.dataType)) {
+ // The Bloom filter hashes the bytes of a key, which a collation
can compare as equal
+ // to other bytes (SPARK-58486).
+ hintBlocked("the join key has a collation the Bloom filter hash
does not follow")
+ currentApplicationSide
+ } else if (hasBloomFilter(currentApplicationSide,
applicationSideKey) &&
+ !hasBloomFilter(applicationSide, applicationSideKey)) {
+ // Unlike the heuristics, a hinted side adds its own filter even
on a key that already
+ // has one, but only one: this key got it on another key pair of
this join.
+ currentApplicationSide
+ } else if (keyDpps.nonEmpty && !canPushDown(applicationSideKey,
applicationSide)) {
Review Comment:
**Finding 22.** This check runs only when the key has DPP filters
(`keyDpps.nonEmpty`). A key with no DPP filter goes straight on, e.g. when DPP
is off, or when `PartitionPruning` neither honors the hint nor adds a DPP
filter of its own. On a partition column, the Bloom filter then becomes a
partition filter, which evaluates the key on every partition before the data
filters. That is the
[SPARK-60809](https://issues.apache.org/jira/browse/SPARK-60809) mechanism. The
ticket covers the heuristic filters, which reach it only through their
selectivity and size gates. The hint waives those gates.
What I ran, with ANSI on, broadcast off and
`spark.sql.optimizer.dynamicPartitionPruning.enabled=false`:
- `rt_part` is partitioned by `f` in `{1, 2, 200}`, 10 rows each, and every
row of `f = 200` has `a >= 100`;
- `rt_dim(c TINYINT)` holds 0, 1, 2, 0, 1.
```sql
SELECT /*+ RUNTIME_FILTER(t) */ * FROM rt_part p JOIN rt_dim t
ON CAST(p.f AS TINYINT) = t.c WHERE p.a < 50
```
| | AQE on | AQE off |
|---|---|---|
| without the hint | 30 rows, no runtime filter | 30 rows, no runtime filter
|
| with the hint | one Bloom filter, `CAST_OVERFLOW` (200 to TINYINT) | one
Bloom filter, `CAST_OVERFLOW` |
The docs say the hint overrides Spark's decision "but not the requirements
that make the filter correct".
I tried gating every hinted Bloom filter on `canPushDown`, as the `keyDpps`
case does. That fixes this query, but three tests fail with it:
- `waives the application side's single-leaf lineage requirement`;
- `is honored by a DPP filter only when that filter reaches the scan`;
- `refuses a collated key that is not a plain column`.
`canPushDown` also requires the key to be traceable to its leaves, which the
hint deliberately waives. So this case needs only the key part of
`canPushDown`: whether the key can fail at a leaf where it would become a
partition filter.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -533,71 +647,277 @@ object InjectRuntimeFilter extends Rule[LogicalPlan]
with PredicateHelper with J
cannotFail(leafKey) && !reused.exists(_.exists(_.fastEquals(leaf)))
}
}
+ val bloomFilterEnabled = conf.runtimeFilterBloomFilterEnabled
+ lazy val cteDefs = cteDefinitions(plan)
plan transformUp {
+ case join: Join if isRuntimeFilterHintDecided(join.hint) => join
+ // Only a hinted join has anything to do with Bloom filters disabled or
once the number of
+ // filters is reached.
+ case join: Join if !hasRuntimeFilterHint(join.hint) &&
+ (!bloomFilterEnabled || filterCounter >= numFilterThreshold) => join
case join @ ExtractEquiJoinKeys(joinType, leftKeys, rightKeys, _, _,
left, right, hint) =>
var newLeft = left
var newRight = right
- leftKeys.lazyZip(rightKeys).foreach((l, r) => {
- lazy val keyDpps = dynamicPruningSubqueries(left, l) ++
dynamicPruningSubqueries(right, r)
- // Check if:
- // 1. The keys are simple cheap expressions
- // 2. There is no DPP filter on the key that physical planning may
keep
- if (filterCounter < numFilterThreshold &&
- isSimpleExpression(l) && isSimpleExpression(r) &&
!keyDpps.exists(isKept)) {
- val oldLeft = newLeft
- val oldRight = newRight
- // The creation side for a bloom filter on `key` of `side`. It
leaves out the key's own
- // DPP filters, which physical planning drops. An expression such
as a UDF or a `LIKE`
- // in their build plan would also stop the search for the creation
side, since
- // `isSimpleExpression` sees the plan of a subquery too. If the
key has DPP filters,
- // they are all dropped, so step 3 above applies. The bloom filter
evaluates its
- // creation side again, apart from the join. Its subquery can also
read more of that
- // side than the join does, since filters on other keys, DPP
filters or bloom filters,
- // can narrow only the join's side. And the bloom filter hashes
the bytes of the key, so
- // its type must compare by its bytes, which a collated string
does not.
- def creationSide(
- side: LogicalPlan,
- key: Expression,
- other: LogicalPlan,
- otherKey: Expression): Option[FilterCreationSide] =
- extractBeneficialFilterCreatePlan(
- side, withoutDppFilters(other, keyDpps.contains), key,
otherKey).filter { c =>
- keyDpps.isEmpty ||
(UnsafeRowUtils.isBinaryStable(key.dataType) &&
- canPushDown(key, side) && canEvaluateAgain(c))
+ if (isRuntimeFilterHintAmbiguous(hint)) {
+ reportHintNotApplied(join,
+ "the runtime filter source is ambiguous as both join sides are
hinted")
+ }
+ // 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 ignored, leaving
the heuristics to
+ // decide, and so is a hinted side that cannot be a runtime filter
source on any join key.
+ val hintedSource = runtimeFilterSourceSide(hint)
+ lazy val hintCheck = hintedSource.map { side =>
+ runtimeFilterHintCheck(if (side == BuildLeft) left else right,
cteDefs)
+ }
+ // Why the hinted side cannot prune the other side on the key pair `l`
and `r`.
+ def hintRejection(l: Expression, r: Expression, checkFunctions:
Boolean): Option[String] =
+ hintCheck.flatMap { check =>
+ if (hintedSource.contains(BuildRight)) check.rejection(l, r,
checkFunctions)
+ else check.rejection(r, l, checkFunctions)
+ }
+ // The DPP filters on each key pair that prune the left side and the
right side.
+ val keyFilters = leftKeys.lazyZip(rightKeys).map { (l, r) =>
+ (l, r, dynamicPruningFilters(left, l, r),
dynamicPruningFilters(right, r, l))
+ }
+ def honorHint(filters: Seq[DynamicPruningSubquery]): Boolean =
+
filters.exists(_.getTagValue(DynamicPruning.HONORS_RUNTIME_FILTER_HINT).isDefined)
+ // A key whose DPP filter honors the hint was accepted by
[[PartitionPruning]], before a
+ // filter pushed into the hinted side could change its analysis. A
Bloom filter's subquery
+ // is checked for the functions it calls once it is built.
+ val declinedReason = hintedSource.flatMap { side =>
+ val reasons = keyFilters.map { case (l, r, leftFilters,
rightFilters) =>
+ if (honorHint(if (side == BuildRight) leftFilters else
rightFilters)) None
+ else hintRejection(l, r, checkFunctions = false)
+ }
+ if (reasons.forall(_.isDefined)) reasons.head else None
+ }
+ declinedReason.foreach(reportHintNotApplied(join, _))
+ val hinted = hintedSource.isDefined && declinedReason.isEmpty
+ val injectLeftHinted = hinted && hintedSource.contains(BuildRight)
+ val injectRightHinted = hinted && hintedSource.contains(BuildLeft)
+ // 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 (`isHintedDirection`).
Requirements:
+ // 1. The application side is not a stream with a stateful operator
(`isStatefulStream`)
+ // 2. The join type supports pruning the application side
+ // 3. The application side is not the hinted source
(`isHintedSource`), which is never
+ // itself filtered
+ // 4. 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
+ // 5. There is no Bloom filter on the application side's key yet,
unless the creation side
+ // is hinted and the filter on the key was built from another
creation side
+ def tryInject(
+ applicationSide: LogicalPlan,
+ currentApplicationSide: LogicalPlan,
+ applicationSideKey: Expression,
+ creationSide: LogicalPlan,
+ creationSideKey: Expression,
+ canPrune: Boolean,
+ isHintedDirection: Boolean,
+ isHintedSource: Boolean,
+ sideName: String,
+ keyDpps: Seq[DynamicPruningSubquery]): LogicalPlan = {
+ if (isStatefulStream(applicationSide)) {
+ if (isHintedDirection) {
+ hintBlocked(s"the $sideName side is a stream with a stateful
operator")
+ }
+ currentApplicationSide
+ } else if (!canPrune) {
+ if (isHintedDirection) {
+ // `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)}"
}
- // 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)) {
- creationSide(left, l, right, r).foreach(c => newLeft =
injectFilter(l, newLeft, c))
+ hintBlocked(s"the $sideName side of $joinDescription join cannot
be pruned")
+ }
+ currentApplicationSide
+ } else if (isHintedDirection) {
+ injectHintedFilter(applicationSide, currentApplicationSide,
applicationSideKey,
+ creationSide, creationSideKey, keyDpps)
+ } else if (isHintedSource || !(hasShuffle ||
probablyHasShuffle(applicationSide)) ||
+ hasBloomFilter(currentApplicationSide, applicationSideKey)) {
+ currentApplicationSide
+ } else {
+ // The creation side leaves out the key's own DPP filters, which
physical planning
+ // drops, and every `onlyInBroadcast` DPP filter, e.g. one a join
above pushed into it:
+ // it finds no broadcast in the bloom filter's subquery and is
`true` there. An
+ // expression such as a UDF or a `LIKE` in their build plan would
also stop the search
+ // for the creation side, since `isSimpleExpression` sees the plan
of a subquery too.
+ // If the key has DPP filters, they are all dropped, so step 3
above applies. The
+ // bloom filter evaluates its creation side again, apart from the
join. Its subquery
+ // can also read more of that side than the join does, since
filters on other keys, DPP
+ // filters or bloom filters, can narrow only the join's side. And
the bloom filter
+ // hashes the bytes of the key, so its type must compare by its
bytes, which a collated
+ // string does not.
+ val creationPlan =
+ withoutDppFilters(creationSide, dpp => dpp.onlyInBroadcast ||
keyDpps.contains(dpp))
+ extractBeneficialFilterCreatePlan(
+ applicationSide, creationPlan, applicationSideKey,
creationSideKey)
+ .filter(c => keyDpps.isEmpty ||
+ (UnsafeRowUtils.isBinaryStable(applicationSideKey.dataType) &&
+ canPushDown(applicationSideKey, applicationSide) &&
canEvaluateAgain(c)))
+ .map(injectFilter(applicationSideKey, currentApplicationSide, _))
+ .getOrElse(currentApplicationSide)
+ }
+ }
+ // Filters `applicationSide` with a Bloom filter built from the hinted
`creationSide`.
+ def injectHintedFilter(
+ applicationSide: LogicalPlan,
+ currentApplicationSide: LogicalPlan,
+ applicationSideKey: Expression,
+ creationSide: LogicalPlan,
+ creationSideKey: Expression,
+ keyDpps: Seq[DynamicPruningSubquery]): LogicalPlan = {
+ lazy val creation = FilterCreationSide(
+ creationSideKey, creationSide, useMaterializedThreshold = false,
hinted = true)
+ if (!UnsafeRowUtils.isBinaryStable(applicationSideKey.dataType) ||
+ !UnsafeRowUtils.isBinaryStable(creationSideKey.dataType)) {
+ // The Bloom filter hashes the bytes of a key, which a collation
can compare as equal
+ // to other bytes (SPARK-58486).
+ hintBlocked("the join key has a collation the Bloom filter hash
does not follow")
+ currentApplicationSide
+ } else if (hasBloomFilter(currentApplicationSide,
applicationSideKey) &&
+ !hasBloomFilter(applicationSide, applicationSideKey)) {
+ // Unlike the heuristics, a hinted side adds its own filter even
on a key that already
+ // has one, but only one: this key got it on another key pair of
this join.
+ currentApplicationSide
+ } else if (keyDpps.nonEmpty && !canPushDown(applicationSideKey,
applicationSide)) {
+ // The key's DPP filters, which [[PartitionPruning]] added without
the hint, are all
+ // dropped, so step 3 above applies to the Bloom filter as without
the hint.
+ hintBlocked("a Bloom filter pushed down on the join key could fail
or change a " +
+ "broadcast that a DPP filter reuses")
+ currentApplicationSide
+ } else {
+ hintCheck.flatMap(_.rejection(applicationSideKey, creationSideKey,
+ checkFunctions = false)) match {
+ case Some(reason) =>
+ hintBlocked(reason)
+ currentApplicationSide
+ case None =>
+ val filtered = injectFilter(applicationSideKey,
currentApplicationSide, creation)
+ if (filtered eq currentApplicationSide) {
+ hintBlocked(if
(containsExtractedFunction(bloomFilterAggregate(creation))) {
+ RuntimeFilterSourceAnalysis.ExtractedFunction
+ } else {
+ "the runtime filter's subquery over the hinted side is not
deterministic"
+ })
+ }
+ filtered
+ }
+ }
+ }
+ // A DPP filter prunes by whole partitions rather than by rows, so it
is preferred: a key
+ // it prunes gets no Bloom filter, while the other keys still may. The
hint is honored by
+ // a DPP filter that [[PartitionPruning]] marked as honoring it. A
hinted side that cannot
+ // honor the hint on a key gets DPP from its own estimates, as without
the hint, so such a
+ // DPP filter does not count as the hint applied.
+ val prunedKeys = keyFilters.map { case (l, r, leftFilters,
rightFilters) =>
+ val filters = if (hinted) {
+ if (injectLeftHinted) leftFilters else rightFilters
+ } else {
+ leftFilters ++ rightFilters
+ }
+ (l, r, filters, hinted && honorHint(filters))
+ }
+ var appliedHint = prunedKeys.exists(_._4)
+ prunedKeys.foreach { case (l, r, keyDpps, honorsHint) =>
+ // Physical planning can still drop the key's DPP filters, and a key
whose DPP filters
+ // are all dropped can get a Bloom filter.
+ if (keyDpps.exists(isKept)) {
+ // Already pruned by partition pruning: no Bloom filter for the
key.
+ if (hinted && !honorsHint) {
+ hintRejection(l, r, checkFunctions =
true).foreach(hintBlocked(_))
}
+ } else if (!bloomFilterEnabled) {
+ hintBlocked(s"${SQLConf.RUNTIME_BLOOM_FILTER_ENABLED.key} is
false")
+ } else if (filterCounter >= numFilterThreshold) {
+ hintBlocked(
+ s"${SQLConf.RUNTIME_FILTER_NUMBER_THRESHOLD.key}
($numFilterThreshold) is reached")
+ } else if (!isSimpleExpression(l) || !isSimpleExpression(r)) {
+ // The keys become the filter's input and must be cheap to
evaluate.
+ hintBlocked("the join key is not a simple expression")
+ } else {
+ val oldLeft = newLeft
+ val oldRight = newRight
+ newLeft = tryInject(left, newLeft, l, right, r,
canPruneLeft(joinType),
+ injectLeftHinted, injectRightHinted, "left", keyDpps)
// Did we actually inject on the left? If not, try on the right
- // Check if:
- // 1. The current join type supports prune the right 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 right key yet
- if (newLeft.fastEquals(oldLeft) && canPruneRight(joinType) &&
- (hasShuffle || probablyHasShuffle(right)) &&
!hasBloomFilter(newRight, r)) {
- creationSide(right, r, left, l).foreach(c => newRight =
injectFilter(r, newRight, c))
+ if (newLeft.fastEquals(oldLeft)) {
+ newRight = tryInject(right, newRight, r, left, l,
canPruneRight(joinType),
+ injectRightHinted, injectLeftHinted, "right", keyDpps)
}
if (!newLeft.fastEquals(oldLeft) ||
!newRight.fastEquals(oldRight)) {
filterCounter = filterCounter + 1
+ appliedHint = appliedHint || hinted
}
}
+ }
+ if (hinted && !appliedHint) {
+ reportHintNotApplied(join,
+ notAppliedReason.getOrElse("no runtime filter could be built from
the hinted side"))
+ }
+ val result = join.withNewChildren(Seq(newLeft,
newRight)).asInstanceOf[Join]
+ if (hasRuntimeFilterHint(hint)) markRuntimeFilterHintDecided(result)
else result
Review Comment:
**Finding 24.** For an uncorrelated IN subquery, `OptimizeSubqueries` runs
this rule on the subquery's own `Subquery` plan first:
1. A materialized CTE that the subquery reads is defined in the main query,
so `cteDefinitions(plan)` has no entry for it.
2. The source analysis then declines the hint with "reads a recursive CTE or
one defined outside the plan being optimized" (`joins.scala:849`).
3. This line marks the join decided.
4. After `RewritePredicateSubquery` moves the join into the main plan, where
the definition is visible, line 653 skips it.
What I ran, with `applicationSideScanSizeThreshold=3000` and broadcast off:
```sql
WITH d AS MATERIALIZED (SELECT c2 FROM bf2 WHERE a2 < 60)
SELECT * FROM bf4 WHERE bf4.c4 IN
(SELECT /*+ RUNTIME_FILTER(d) */ bf3.c3 FROM bf3 JOIN d ON bf3.c3 = d.c2)
```
- This query gets no Bloom filter and logs that warning.
- The same join at the top level gets its Bloom filter.
- The same IN subquery with `d` as a plain subquery gets two.
In a `Subquery` plan, `isKept` already leaves DPP decisions to the main
pass. Leaving the hint undecided there, when the only rejection is a CTE
defined outside the plan, would let the main pass decide it, without the
warning.
--
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]