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


##########
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,

Review Comment:
   Fixed in 558bf3e9cba: renamed to `isHintedDirection` and `isHintedSource`, 
and `appliedHint` is declared where it is first set.



##########
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")

Review Comment:
   Pre-existing: `canPruneLeft` and `canPruneRight` also gate DPP and the 
heuristics, so matching `InnerLike` changes unhinted plans. Leaving it out of 
this PR.



##########
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
+              case None =>
+                injectFilter(applicationSideKey, currentApplicationSide, 
FilterCreationSide(
+                  creationSideKey, creationSide, useMaterializedThreshold = 
false, hinted = true))
+            }
+          } else if (creationHinted || !(hasShuffle || 
probablyHasShuffle(applicationSide)) ||
+              hasBloomFilter(currentApplicationSide, applicationSideKey)) {
+            currentApplicationSide
+          } else {
+            extractBeneficialFilterCreatePlan(
+              applicationSide, creationSide, applicationSideKey, 
creationSideKey)
+              // Checked last, as computing the constraints may be costly.
+              .filterNot(_ => isFixedByLiteral(applicationSide, 
applicationSideKey))
+              .map(injectFilter(applicationSideKey, currentApplicationSide, _))
+              .getOrElse(currentApplicationSide)
+          }
+        }
+        // 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 = leftKeys.lazyZip(rightKeys).map { (l, r) =>

Review Comment:
   Fixed in 558bf3e9cba: each join analyzes its hinted side once, in both 
rules, and checks every key against that.



##########
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:
   Fixed in 558bf3e9cba: a hinted side rejected on every key leaves the join as 
without the hint, in both rules, and the hint is still reported. The join order 
stays fixed by design, as for join strategy hints, and the reference now notes 
the cartesian product this can leave.



##########
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:
   Fixed in 558bf3e9cba: cleanup replaces a dropped DPP filter with a fresh 
literal.



-- 
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