pan3793 commented on code in PR #58635:
URL: https://github.com/apache/spark/pull/58635#discussion_r4534764453


##########
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:
   Fixed in 55be0d65970: a hinted filter needs a key that cannot fail in any 
form pushdown rewrites it to, through aliases and union branches; the lineage 
requirement stays waived. Your query and a union variant are a new test, with 
DPP and AQE on and off. `cannotFail` now takes the collation key of a collated 
column, with or without the hint, and two tests that derived the pruned key 
with `CAST(id AS INT)` use `TRY_CAST`. A regression of this PR, through the 
SPARK-60809 mechanism.
   



##########
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:
   Fixed in 55be0d65970 as suggested: `honorsHint` requires the same key check. 
A key that fails it leaves DPP to its own estimates, as without the hint, and 
the hint is reported with that reason. The same test covers it. A regression of 
this PR.
   



##########
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:
   Fixed in 55be0d65970 as suggested: in a subquery, a hint whose side reads a 
CTE of the outer query is neither reported nor marked as decided, and the pass 
over the outer query decides it. Your query is a new test. A subquery that is 
planned on its own, such as a scalar subquery, is not visited again: its join 
stays as without the hint, with no warning. The test pins that, and the PR 
description lists 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]

Reply via email to