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


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

Review Comment:
   Fixed in 558bf3e9cba: neither runtime filter prunes a stream with a stateful 
operator, with or without the hint. DPP had the same gap on a partitioned file 
stream and gets the same guard. The heuristics had this bug already; the hint 
reached it at default settings. Your stream case is tested, and so is DPP on a 
partitioned file stream.



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

Review Comment:
   Fixed in 558bf3e9cba: the hinted Bloom path refuses a key that does not 
compare by its bytes and reports why. A plain collated column still gets its 
filter. Your `substr` case is tested.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -379,29 +432,49 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with 
PredicateHelper with J
     }
   }
 
-  // This checks if there is already a DPP filter, as this rule is called just 
after DPP.
-  @tailrec
-  private def hasDynamicPruningSubquery(
-      left: LogicalPlan,
-      right: LogicalPlan,
-      leftKey: Expression,
-      rightKey: Expression): Boolean = {
-    (left, right) match {
-      case (Filter(DynamicPruningSubquery(pruningKey, _, _, _, _, _, _), 
plan), _) =>
-        pruningKey.fastEquals(leftKey) || hasDynamicPruningSubquery(plan, 
right, leftKey, rightKey)
-      case (_, Filter(DynamicPruningSubquery(pruningKey, _, _, _, _, _, _), 
plan)) =>
-        pruningKey.fastEquals(rightKey) ||
-          hasDynamicPruningSubquery(left, plan, leftKey, rightKey)
+  /**
+   * The DPP filters on `applicationKey` built from `creationKey` that prune 
`plan`. This rule runs
+   * after the DPP filters are pushed down and cleaned up, so only a surviving 
one is found,
+   * wherever the pushdown left it; it is the one [[PartitionPruning]] 
inserted for the same join
+   * key pair, whose pruning key it rewrote on the way down as the lineage 
tracking does.
+   */
+  private def dynamicPruningFilters(
+      plan: LogicalPlan,
+      applicationKey: Expression,
+      creationKey: Expression): Seq[DynamicPruningSubquery] = {
+    if (!plan.containsPattern(DYNAMIC_PRUNING_SUBQUERY)) return Nil
+    findExpressionAndTrackLineageDown(applicationKey, plan).toSeq.flatMap { 
case (trackedKey, _) =>
+      plan.flatMap {
+        case Filter(condition, _) => condition.collect {
+          case d: DynamicPruningSubquery if 
d.pruningKey.semanticEquals(trackedKey) &&
+            d.broadcastKeyIndices.exists(i => 
d.buildKeys(i).semanticEquals(creationKey)) => d
+        }
+        case _ => Nil
+      }
+    }
+  }
+
+  /**
+   * Whether `plan` constrains `key` to a literal, e.g. a partition key fixed 
by a static partition
+   * filter. Every row then has the same key, so a filter on it prunes next to 
nothing.
+   */
+  private def isFixedByLiteral(plan: LogicalPlan, key: Expression): Boolean = {

Review Comment:
   Fixed in 558bf3e9cba: the literal skip is removed, so a key fixed by a 
literal gets its Bloom filter again, and SPARK-58272's test is back to `c2 = 
8`. A regression of this PR.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/LogicalRelation.scala:
##########
@@ -53,6 +53,8 @@ case class LogicalRelation(
     output = output.map(QueryPlan.normalizeExpressions(_, output)),
     catalogTable = None)
 
+  override def isOutputRepeatable: Boolean = !isStreaming

Review Comment:
   Fixed in 558bf3e9cba as you sketched: only a `HadoopFsRelation` counts as 
repeatable. A regression of this PR. Tested with an H2 JDBC relation.



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