peter-toth commented on code in PR #58635:
URL: https://github.com/apache/spark/pull/58635#discussion_r4551349604


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/dynamicpruning/PartitionPruning.scala:
##########
@@ -327,6 +343,38 @@ 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)

Review Comment:
   **Finding 30.** The settling that fixes 25 runs only inside 
`InjectRuntimeFilter`. `PartitionPruning` adds the hinted DPP filter on its 
own, with a `buildQuery` copied before pushdown. When 
`spark.sql.optimizer.excludedRules` names `InjectRuntimeFilter`, nothing 
settles that filter. Its subquery then reads the partition of `wd` that the 
join's own DPP filter prunes.
   
   What I ran: my round 4 query, with ANSI on, broadcast off and 
`InjectRuntimeFilter` excluded.
   
   | | AQE on | AQE off |
   |---|---|---|
   | hinted, Bloom filters on | `CAST_INVALID_INPUT` | `CAST_INVALID_INPUT` |
   | hinted, Bloom filters off | `CAST_INVALID_INPUT` | `CAST_INVALID_INPUT` |
   | without the hint | 2000 rows | 2000 rows |
   
   With the rule included, all of these return 2000 rows. Master doesn't know 
the hint, so it runs the unhinted query.
   
   Since only `InjectRuntimeFilter` can settle a hinted filter, 
`PartitionPruning` could leave the hint alone while that rule is excluded. With 
this change, all eight arms return 2000 rows, and `InjectRuntimeFilterSuite` 
passes (`Utils` is `org.apache.spark.util.Utils`):
   
   ```scala
           val hintedSource = runtimeFilterSourceSide(hint).filter(_ => 
!conf.optimizerExcludedRules
             
.toSeq.flatMap(Utils.stringToSeq).contains(InjectRuntimeFilter.ruleName))
   ```
   
   This query with the rule excluded could be a case of the test for 25.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -533,71 +729,530 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] 
with PredicateHelper with J
         cannotFail(leafKey) && !reused.exists(_.exists(_.fastEquals(leaf)))
       }
     }
-    plan transformUp {
+    val bloomFilterEnabled = conf.runtimeFilterBloomFilterEnabled
+    lazy val cteDefs = cteDefinitions(plan)
+    // The subquery of a hinted filter evaluates a copy of the hinted side, 
apart from the join.
+    // The join's own side still changes after the copy is made: pushdown 
moves the filters of the
+    // joins within it and brings in the filters of the joins above it, also 
in a later pass, over
+    // the query that a subquery is joined with. The copy would then read rows 
that the join does
+    // not read, and an expression of the hinted side that can fail could fail 
a query that
+    // succeeds without the hint (SPARK-60842). So the filters are pushed down 
here, and each
+    // hinted filter whose hinted side has changed is built again from it, 
until none changes. A
+    // hinted filter follows its join's side unless:
+    // 1. The changed side is no source of the filter as the hinted side was, 
e.g. another join
+    //    filters it on a value that another evaluation can assign 
differently. The join loses its
+    //    hinted filters and its hint, as a join whose hinted side is declined 
to begin with.
+    // 2. A DPP filter that prunes the hinted side is built from a plan 
outside it, or reuses a
+    //    broadcast from outside it, which the subquery does not have 
(`missesPruning`). The join
+    //    loses its hinted filters.
+    // A hint is reported once its join has no hinted filter left.
+    def withSettledHintedFilters(injected: LogicalPlan): LogicalPlan = {
+      def hintedAndPrunedSide(join: Join): Option[(LogicalPlan, LogicalPlan)] =
+        runtimeFilterSourceSide(join.hint).filter(_ => 
isRuntimeFilterHintDecided(join.hint)).map {
+          case BuildLeft => (join.left, join.right)
+          case BuildRight => (join.right, join.left)
+        }
+      val hasHintedJoin = injected.exists {
+        case join: Join => hintedAndPrunedSide(join).isDefined
+        case _ => false
+      }
+      if (!hasHintedJoin) return injected
+      // Whether a subquery that evaluates `copy` misses the pruning of a DPP 
filter in it: one
+      // that reuses a broadcast that `copy` does not build, or that is built 
from a plan outside
+      // `copy`. A DPP filter in a subquery counts only if it prunes by what 
this pass sees, unlike
+      // for `isKept`: the pass over the outer query settles the hinted 
filters again, against all
+      // the broadcasts.
+      def missesPruning(copy: LogicalPlan): Boolean = {
+        lazy val builtWithin = AttributeSet(copy.flatMap(_.output))
+        lazy val broadcastWithin = broadcastablePlans(copy)
+        copy.exists {
+          case Filter(condition, _) => 
splitConjunctivePredicates(condition).exists {
+            case dpp: DynamicPruningSubquery if prunes(dpp) =>
+              if (dpp.onlyInBroadcast) {
+                !reusablePlansOf(dpp).exists(p => 
broadcastWithin.exists(_.sameResult(p)))
+              } else {
+                !dpp.buildKeys.forall(_.references.subsetOf(builtWithin))
+              }
+            case _ => false
+          }
+          case _ => false
+        }
+      }
+      // Settles the hinted filters of `join` in `prunedSide` against 
`hintedSide`. Returns the new
+      // pruned side, why the hint is not applied if the join has no hinted 
filter left, and
+      // whether that is because the changed hinted side is no source of them.
+      def settleFilters(
+          join: Join,
+          hintedSide: LogicalPlan,
+          prunedSide: LogicalPlan): (LogicalPlan, Option[String], Boolean) = {
+        lazy val produced = AttributeSet(hintedSide.flatMap(_.output))
+        // Whether a filter that was built from `creationPlan` is one of this 
join. The pruned side
+        // also holds the hinted filters that pushdown brings in from the 
joins above. The plan
+        // can be an earlier form of the hinted side, whose leaves produce the 
same attributes.
+        def ofThisJoin(creationPlan: LogicalPlan): Boolean =
+          creationPlan.exists(_.outputSet.intersect(produced).nonEmpty)
+        // A key of `creationPlan`, an earlier form of the hinted side, as the 
hinted side outputs
+        // it now. Once a subquery is joined with the outer query, the 
optimizer can remove an
+        // alias that had to stay as the output of the subquery, which leaves 
the key with the id
+        // of the alias's child.
+        def currentKey(key: Expression, creationPlan: LogicalPlan): 
Option[Expression] = {
+          def isOutput(e: Expression) = 
e.references.subsetOf(hintedSide.outputSet)
+          if (isOutput(key)) {
+            Some(key)
+          } else {
+            val aliased = 
AttributeMap(creationPlan.flatMap(_.expressions).flatMap(_.collect {
+              case a @ Alias(child: Attribute, _) => a.toAttribute -> child
+            }))
+            Some(key.transform { case a: Attribute => aliased.getOrElse(a, a) 
}).filter(isOutput)
+          }
+        }
+        lazy val misses = missesPruning(hintedSide)
+        lazy val check = runtimeFilterHintCheck(hintedSide, cteDefs)
+        // The Bloom filters built for this join, by creation key and whether 
the subquery prunes
+        // the columns of the hinted side. Pushdown copies a filter into each 
branch of a union,
+        // and the copies share one subquery.
+        val bloomFilters =
+          mutable.HashMap.empty[(Expression, Boolean), Either[String, 
BloomFilterMightContain]]
+        var kept = 0
+        var notApplied: Option[String] = None
+        var declined = false
+        def keep(filter: Expression): Option[Expression] = {
+          kept += 1
+          Some(filter)
+        }
+        def drop(reason: String, asSource: Boolean = false): 
Option[Expression] = {
+          if (notApplied.isEmpty) notApplied = Some(reason)
+          declined ||= asSource
+          None
+        }
+        def settledConjunct(conjunct: Expression): Option[Expression] = 
conjunct match {
+          case filter: BloomFilterMightContain if 
filter.getTagValue(HINTED_CREATION_SIDE)
+              .exists(creation => ofThisJoin(creation.plan)) =>
+            val creation = filter.getTagValue(HINTED_CREATION_SIDE).get
+            val changed = !creation.plan.fastEquals(hintedSide)
+            // Constant folding leaves a literal for the hash of a literal key.
+            val value = filter.valueExpression
+            lazy val key = currentKey(creation.key, creation.plan)
+            lazy val rejection = key.filter(_ => changed)
+              .flatMap(check.rejection(value, _, checkFunctions = false))
+            if (misses) {
+              drop(CannotFollow)
+            } else if (key.isEmpty) {
+              drop(NoHintedFilter)
+            } else if (rejection.isDefined) {
+              drop(rejection.get, asSource = true)
+            } else {
+              val current = creation.copy(key = key.get, plan = hintedSide)
+              def bloomFilterOf(pruned: Boolean) = 
bloomFilters.getOrElseUpdate(
+                (key.get.canonicalized, pruned), bloomFilter(value, 
current.copy(pruned = pruned)))
+              // The subquery reads only the columns that it needs, unless it 
then misses the
+              // pruning of a DPP filter within the hinted side: without a 
column of a broadcast
+              // side, the subquery builds another broadcast than the one that 
the filter reuses.
+              def subqueryMissesPruning(f: BloomFilterMightContain) =
+                f.bloomFilterExpression.exists {
+                  case s: ScalarSubquery => missesPruning(s.plan)
+                  case _ => false
+                }
+              val built = bloomFilterOf(pruned = true) match {
+                case Right(f) if subqueryMissesPruning(f) => 
bloomFilterOf(pruned = false)
+                case other => other
+              }
+              built match {
+                case Left(reason) => drop(reason)
+                case Right(f) if !changed &&
+                    f.getTagValue(HINTED_CREATION_SIDE).exists(_.pruned == 
creation.pruned) =>
+                  keep(filter)
+                case Right(f) if f.valueExpression.fastEquals(value) => keep(f)
+                case Right(f) =>
+                  val copy = f.copy(valueExpression = value)
+                  copy.copyTagsFrom(f)
+                  keep(copy)
+              }
+            }
+          case dpp: DynamicPruningSubquery
+              if 
dpp.getTagValue(DynamicPruning.HONORS_RUNTIME_FILTER_HINT).isDefined &&
+                ofThisJoin(dpp.buildQuery) =>
+            lazy val keys = dpp.buildKeys.map(currentKey(_, dpp.buildQuery))
+            if (misses) {
+              drop(CannotFollow)
+            } else if (keys.exists(_.isEmpty)) {
+              drop(NoHintedFilter)
+            } else if (dpp.buildQuery.fastEquals(hintedSide)) {
+              keep(dpp)
+            } else {
+              val buildKeys = keys.map(_.get)
+              val key = buildKeys(dpp.broadcastKeyIndices.head)
+              // A DPP filter's subquery runs the hinted side as it is, 
functions included.
+              val rejection = check.rejection(dpp.pruningKey, key, 
checkFunctions = false)
+                .map(_ -> true)
+                .orElse(check.rejection(dpp.pruningKey, key, checkFunctions = 
true).map(_ -> false))
+              rejection match {
+                case Some((reason, asSource)) => drop(reason, asSource)
+                case None =>
+                  val newDpp = dpp.copy(buildQuery = hintedSide, buildKeys = 
buildKeys)(
+                    dpp.broadcastValueProjection)
+                  newDpp.copyTagsFrom(dpp)
+                  keep(newDpp)
+              }
+            }
+          case other => Some(other)
+        }
+        // `condition` with this join's hinted filters settled, if that 
changes any of them.
+        def settledCondition(condition: Expression): 
Option[Option[Expression]] = {
+          val conjuncts = splitConjunctivePredicates(condition)
+          val result = conjuncts.flatMap(settledConjunct)
+          if (result.length == conjuncts.length &&
+              result.zip(conjuncts).forall { case (a, b) => a eq b }) {
+            None
+          } else {
+            Some(result.reduceOption(And))
+          }
+        }
+        // Pushdown leaves a hinted filter in a filter, or in the condition of 
an inner join whose
+        // sides its key both reads.
+        val newPrunedSide = prunedSide transformUp {
+          case f @ Filter(condition, child) =>
+            settledCondition(condition).map(_.map(Filter(_, 
child)).getOrElse(child)).getOrElse(f)
+          case j @ Join(_, _, _, Some(condition), _)
+              if condition.exists(_.isInstanceOf[BloomFilterMightContain]) =>
+            settledCondition(condition).map { newCondition =>
+              val newJoin = j.copy(condition = newCondition)
+              newJoin.copyTagsFrom(j)
+              newJoin
+            }.getOrElse(j)
+        }
+        (newPrunedSide, notApplied.filter(_ => kept == 0), declined && kept == 
0)
+      }
+      // Settles the hinted joins of `plan`. The hinted filters of a join 
depend on the filters
+      // that pushdown brings into its hinted side from the joins above it, 
and on those of the
+      // joins within its hinted side. A filter that is dropped there leaves 
the hinted side as it
+      // was. So a join is settled after the joins above it and those within 
its hinted side, and
+      // before those within its pruned side.
+      def settle(plan: LogicalPlan): LogicalPlan = plan match {
+        case join: Join if hintedAndPrunedSide(join).isDefined =>
+          val (hintedSide, prunedSide) = hintedAndPrunedSide(join).get
+          val newHintedSide = settle(hintedSide)
+          val (ownSettled, notApplied, declined) = settleFilters(join, 
newHintedSide, prunedSide)
+          val newPrunedSide = settle(ownSettled)
+          notApplied.foreach(reportHintNotApplied(join, _))
+          if (newHintedSide.eq(hintedSide) && newPrunedSide.eq(prunedSide)) {
+            join
+          } else {
+            val newJoin = join.withNewChildren(
+              if (join.left eq hintedSide) Seq(newHintedSide, newPrunedSide)
+              else Seq(newPrunedSide, newHintedSide)).asInstanceOf[Join]
+            if (declined) withoutRuntimeFilterHint(newJoin) else newJoin
+          }
+        case _ => plan.mapChildren(settle)
+      }
+      def pushDown(plan: LogicalPlan): LogicalPlan = {
+        var current = plan
+        var pushed = PushDownPredicates(current)
+        var iteration = 1
+        while (!pushed.fastEquals(current) && iteration < 
conf.optimizerMaxIterations) {
+          current = pushed
+          pushed = PushDownPredicates(current)
+          iteration += 1
+        }
+        pushed
+      }
+      var current = injected
+      var settled = false
+      var iteration = 0
+      while (!settled && iteration < conf.optimizerMaxIterations) {
+        val pushed = pushDown(current)
+        current = settle(pushed)
+        settled = current eq pushed
+        iteration += 1
+      }
+      current
+    }
+    withSettledHintedFilters(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)
+        // Why the hinted side cannot prune the other side on each key pair. A 
key whose DPP
+        // filter honors the hint was accepted by [[PartitionPruning]]; a 
hinted side that a filter
+        // pushed into it has changed since is checked when the DPP filter is 
built again from it.
+        // A Bloom filter's subquery is checked for the functions it calls 
once it is built.
+        val keyRejections = hintedSource.map { side =>
+          keyFilters.map { case (l, r, leftFilters, rightFilters) =>
+            if (honorHint(if (side == BuildRight) leftFilters else 
rightFilters)) None
+            else hintRejection(l, r, checkFunctions = false)
+          }
+        }
+        val declinedReason =
+          keyRejections.flatMap(reasons => if (reasons.forall(_.isDefined)) 
reasons.head else None)
+        // A hint that is left to the pass over the outer query is neither 
reported nor marked as
+        // decided here, and the join gets no Bloom filter here: that pass 
decides the hint and
+        // adds the join's filters.
+        val leftToOuterQuery = 
keyRejections.exists(leavesRuntimeFilterHintToOuterQuery(plan, _))
+        if (!leftToOuterQuery) 
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. A DPP
+            // filter that runs as its own subquery stays, and the search for 
the creation side
+            // does not look at it: `isSimpleExpression` sees the plan of a 
subquery too, where an
+            // expression such as a UDF or a `LIKE` would stop the search.
+            // 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 if (!hintedKeyCannotFail(applicationSideKey, 
applicationSide)) {
+            hintBlocked("the join key could fail on rows the join does not 
read")
+            currentApplicationSide
+          } else {
+            hintCheck.flatMap(_.rejection(applicationSideKey, creationSideKey,
+                checkFunctions = false)) match {
+              case Some(reason) =>
+                hintBlocked(reason)
+                currentApplicationSide
+              case None =>
+                bloomFilter(new XxHash64(Seq(applicationSideKey)), creation) 
match {
+                  case Right(filter) => Filter(filter, currentApplicationSide)
+                  case Left(reason) =>
+                    hintBlocked(reason)
+                    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 = 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)
+        (if (leftToOuterQuery) Nil else 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) {
+              val (prunedKey, prunedSide) = if (injectLeftHinted) (l, left) 
else (r, right)
+              hintRejection(l, r, checkFunctions = true)
+                .orElse(Option.when(!hintedKeyCannotFail(prunedKey, 
prunedSide)) {
+                  "the join key could fail on rows the join does not read"
+                }).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) {

Review Comment:
   **Finding 31.** Since the fix for 26, the key loop above is skipped while 
the hint is left to the outer query. So `appliedHint` stays false, and this 
line reports the hint whenever only some keys read the outer CTE.
   
   What I ran, with `applicationSideScanSizeThreshold=3000` and broadcast off. 
Only `m` reads the CTE:
   
   ```sql
   WITH x AS MATERIALIZED (SELECT max(a1) AS m FROM bf1)
   SELECT * FROM bf4 WHERE bf4.c4 IN (SELECT /*+ RUNTIME_FILTER(d) */ bf3.c3 
FROM bf3
     JOIN (SELECT c2, (SELECT m FROM x) AS m FROM bf2) d ON bf3.c3 = d.c2 AND 
bf3.a3 <=> d.m)
   ```
   
   - The pass over the subquery warns "no runtime filter could be built from 
the hinted side".
   - The outer pass then builds the hinted Bloom filters on `c3` and `a3`.
   - The same join in a scalar subquery warns too, though the hints page says 
Spark ignores such a hint without a warning.
   
   With this, neither query warns, the IN subquery keeps its filters, and 
`InjectRuntimeFilterSuite` passes:
   
   ```suggestion
           if (hinted && !appliedHint && !leftToOuterQuery) {
   ```
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -533,71 +729,530 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] 
with PredicateHelper with J
         cannotFail(leafKey) && !reused.exists(_.exists(_.fastEquals(leaf)))
       }
     }
-    plan transformUp {
+    val bloomFilterEnabled = conf.runtimeFilterBloomFilterEnabled
+    lazy val cteDefs = cteDefinitions(plan)
+    // The subquery of a hinted filter evaluates a copy of the hinted side, 
apart from the join.
+    // The join's own side still changes after the copy is made: pushdown 
moves the filters of the
+    // joins within it and brings in the filters of the joins above it, also 
in a later pass, over
+    // the query that a subquery is joined with. The copy would then read rows 
that the join does
+    // not read, and an expression of the hinted side that can fail could fail 
a query that
+    // succeeds without the hint (SPARK-60842). So the filters are pushed down 
here, and each
+    // hinted filter whose hinted side has changed is built again from it, 
until none changes. A
+    // hinted filter follows its join's side unless:
+    // 1. The changed side is no source of the filter as the hinted side was, 
e.g. another join
+    //    filters it on a value that another evaluation can assign 
differently. The join loses its
+    //    hinted filters and its hint, as a join whose hinted side is declined 
to begin with.
+    // 2. A DPP filter that prunes the hinted side is built from a plan 
outside it, or reuses a
+    //    broadcast from outside it, which the subquery does not have 
(`missesPruning`). The join
+    //    loses its hinted filters.
+    // A hint is reported once its join has no hinted filter left.
+    def withSettledHintedFilters(injected: LogicalPlan): LogicalPlan = {
+      def hintedAndPrunedSide(join: Join): Option[(LogicalPlan, LogicalPlan)] =
+        runtimeFilterSourceSide(join.hint).filter(_ => 
isRuntimeFilterHintDecided(join.hint)).map {
+          case BuildLeft => (join.left, join.right)
+          case BuildRight => (join.right, join.left)
+        }
+      val hasHintedJoin = injected.exists {
+        case join: Join => hintedAndPrunedSide(join).isDefined
+        case _ => false
+      }
+      if (!hasHintedJoin) return injected
+      // Whether a subquery that evaluates `copy` misses the pruning of a DPP 
filter in it: one
+      // that reuses a broadcast that `copy` does not build, or that is built 
from a plan outside
+      // `copy`. A DPP filter in a subquery counts only if it prunes by what 
this pass sees, unlike
+      // for `isKept`: the pass over the outer query settles the hinted 
filters again, against all
+      // the broadcasts.
+      def missesPruning(copy: LogicalPlan): Boolean = {
+        lazy val builtWithin = AttributeSet(copy.flatMap(_.output))
+        lazy val broadcastWithin = broadcastablePlans(copy)
+        copy.exists {
+          case Filter(condition, _) => 
splitConjunctivePredicates(condition).exists {
+            case dpp: DynamicPruningSubquery if prunes(dpp) =>
+              if (dpp.onlyInBroadcast) {
+                !reusablePlansOf(dpp).exists(p => 
broadcastWithin.exists(_.sameResult(p)))
+              } else {
+                !dpp.buildKeys.forall(_.references.subsetOf(builtWithin))
+              }
+            case _ => false
+          }
+          case _ => false
+        }
+      }
+      // Settles the hinted filters of `join` in `prunedSide` against 
`hintedSide`. Returns the new
+      // pruned side, why the hint is not applied if the join has no hinted 
filter left, and
+      // whether that is because the changed hinted side is no source of them.
+      def settleFilters(
+          join: Join,
+          hintedSide: LogicalPlan,
+          prunedSide: LogicalPlan): (LogicalPlan, Option[String], Boolean) = {
+        lazy val produced = AttributeSet(hintedSide.flatMap(_.output))
+        // Whether a filter that was built from `creationPlan` is one of this 
join. The pruned side
+        // also holds the hinted filters that pushdown brings in from the 
joins above. The plan
+        // can be an earlier form of the hinted side, whose leaves produce the 
same attributes.
+        def ofThisJoin(creationPlan: LogicalPlan): Boolean =
+          creationPlan.exists(_.outputSet.intersect(produced).nonEmpty)
+        // A key of `creationPlan`, an earlier form of the hinted side, as the 
hinted side outputs
+        // it now. Once a subquery is joined with the outer query, the 
optimizer can remove an
+        // alias that had to stay as the output of the subquery, which leaves 
the key with the id
+        // of the alias's child.
+        def currentKey(key: Expression, creationPlan: LogicalPlan): 
Option[Expression] = {
+          def isOutput(e: Expression) = 
e.references.subsetOf(hintedSide.outputSet)
+          if (isOutput(key)) {
+            Some(key)
+          } else {
+            val aliased = 
AttributeMap(creationPlan.flatMap(_.expressions).flatMap(_.collect {
+              case a @ Alias(child: Attribute, _) => a.toAttribute -> child
+            }))
+            Some(key.transform { case a: Attribute => aliased.getOrElse(a, a) 
}).filter(isOutput)
+          }
+        }
+        lazy val misses = missesPruning(hintedSide)
+        lazy val check = runtimeFilterHintCheck(hintedSide, cteDefs)
+        // The Bloom filters built for this join, by creation key and whether 
the subquery prunes
+        // the columns of the hinted side. Pushdown copies a filter into each 
branch of a union,
+        // and the copies share one subquery.
+        val bloomFilters =
+          mutable.HashMap.empty[(Expression, Boolean), Either[String, 
BloomFilterMightContain]]
+        var kept = 0
+        var notApplied: Option[String] = None
+        var declined = false
+        def keep(filter: Expression): Option[Expression] = {
+          kept += 1
+          Some(filter)
+        }
+        def drop(reason: String, asSource: Boolean = false): 
Option[Expression] = {
+          if (notApplied.isEmpty) notApplied = Some(reason)
+          declined ||= asSource
+          None
+        }
+        def settledConjunct(conjunct: Expression): Option[Expression] = 
conjunct match {
+          case filter: BloomFilterMightContain if 
filter.getTagValue(HINTED_CREATION_SIDE)
+              .exists(creation => ofThisJoin(creation.plan)) =>
+            val creation = filter.getTagValue(HINTED_CREATION_SIDE).get
+            val changed = !creation.plan.fastEquals(hintedSide)
+            // Constant folding leaves a literal for the hash of a literal key.
+            val value = filter.valueExpression
+            lazy val key = currentKey(creation.key, creation.plan)
+            lazy val rejection = key.filter(_ => changed)
+              .flatMap(check.rejection(value, _, checkFunctions = false))
+            if (misses) {
+              drop(CannotFollow)
+            } else if (key.isEmpty) {
+              drop(NoHintedFilter)
+            } else if (rejection.isDefined) {
+              drop(rejection.get, asSource = true)
+            } else {
+              val current = creation.copy(key = key.get, plan = hintedSide)
+              def bloomFilterOf(pruned: Boolean) = 
bloomFilters.getOrElseUpdate(
+                (key.get.canonicalized, pruned), bloomFilter(value, 
current.copy(pruned = pruned)))
+              // The subquery reads only the columns that it needs, unless it 
then misses the
+              // pruning of a DPP filter within the hinted side: without a 
column of a broadcast
+              // side, the subquery builds another broadcast than the one that 
the filter reuses.
+              def subqueryMissesPruning(f: BloomFilterMightContain) =
+                f.bloomFilterExpression.exists {
+                  case s: ScalarSubquery => missesPruning(s.plan)
+                  case _ => false
+                }
+              val built = bloomFilterOf(pruned = true) match {
+                case Right(f) if subqueryMissesPruning(f) => 
bloomFilterOf(pruned = false)
+                case other => other
+              }
+              built match {
+                case Left(reason) => drop(reason)
+                case Right(f) if !changed &&
+                    f.getTagValue(HINTED_CREATION_SIDE).exists(_.pruned == 
creation.pruned) =>
+                  keep(filter)
+                case Right(f) if f.valueExpression.fastEquals(value) => keep(f)
+                case Right(f) =>
+                  val copy = f.copy(valueExpression = value)
+                  copy.copyTagsFrom(f)
+                  keep(copy)
+              }
+            }
+          case dpp: DynamicPruningSubquery
+              if 
dpp.getTagValue(DynamicPruning.HONORS_RUNTIME_FILTER_HINT).isDefined &&
+                ofThisJoin(dpp.buildQuery) =>
+            lazy val keys = dpp.buildKeys.map(currentKey(_, dpp.buildQuery))
+            if (misses) {
+              drop(CannotFollow)
+            } else if (keys.exists(_.isEmpty)) {
+              drop(NoHintedFilter)
+            } else if (dpp.buildQuery.fastEquals(hintedSide)) {
+              keep(dpp)
+            } else {
+              val buildKeys = keys.map(_.get)
+              val key = buildKeys(dpp.broadcastKeyIndices.head)
+              // A DPP filter's subquery runs the hinted side as it is, 
functions included.
+              val rejection = check.rejection(dpp.pruningKey, key, 
checkFunctions = false)
+                .map(_ -> true)
+                .orElse(check.rejection(dpp.pruningKey, key, checkFunctions = 
true).map(_ -> false))
+              rejection match {
+                case Some((reason, asSource)) => drop(reason, asSource)
+                case None =>
+                  val newDpp = dpp.copy(buildQuery = hintedSide, buildKeys = 
buildKeys)(
+                    dpp.broadcastValueProjection)
+                  newDpp.copyTagsFrom(dpp)
+                  keep(newDpp)
+              }
+            }
+          case other => Some(other)
+        }
+        // `condition` with this join's hinted filters settled, if that 
changes any of them.
+        def settledCondition(condition: Expression): 
Option[Option[Expression]] = {
+          val conjuncts = splitConjunctivePredicates(condition)
+          val result = conjuncts.flatMap(settledConjunct)
+          if (result.length == conjuncts.length &&
+              result.zip(conjuncts).forall { case (a, b) => a eq b }) {
+            None
+          } else {
+            Some(result.reduceOption(And))
+          }
+        }
+        // Pushdown leaves a hinted filter in a filter, or in the condition of 
an inner join whose
+        // sides its key both reads.
+        val newPrunedSide = prunedSide transformUp {
+          case f @ Filter(condition, child) =>
+            settledCondition(condition).map(_.map(Filter(_, 
child)).getOrElse(child)).getOrElse(f)
+          case j @ Join(_, _, _, Some(condition), _)
+              if condition.exists(_.isInstanceOf[BloomFilterMightContain]) =>
+            settledCondition(condition).map { newCondition =>
+              val newJoin = j.copy(condition = newCondition)
+              newJoin.copyTagsFrom(j)
+              newJoin
+            }.getOrElse(j)
+        }
+        (newPrunedSide, notApplied.filter(_ => kept == 0), declined && kept == 
0)
+      }
+      // Settles the hinted joins of `plan`. The hinted filters of a join 
depend on the filters
+      // that pushdown brings into its hinted side from the joins above it, 
and on those of the
+      // joins within its hinted side. A filter that is dropped there leaves 
the hinted side as it
+      // was. So a join is settled after the joins above it and those within 
its hinted side, and
+      // before those within its pruned side.
+      def settle(plan: LogicalPlan): LogicalPlan = plan match {
+        case join: Join if hintedAndPrunedSide(join).isDefined =>
+          val (hintedSide, prunedSide) = hintedAndPrunedSide(join).get
+          val newHintedSide = settle(hintedSide)
+          val (ownSettled, notApplied, declined) = settleFilters(join, 
newHintedSide, prunedSide)
+          val newPrunedSide = settle(ownSettled)
+          notApplied.foreach(reportHintNotApplied(join, _))
+          if (newHintedSide.eq(hintedSide) && newPrunedSide.eq(prunedSide)) {
+            join
+          } else {
+            val newJoin = join.withNewChildren(
+              if (join.left eq hintedSide) Seq(newHintedSide, newPrunedSide)
+              else Seq(newPrunedSide, newHintedSide)).asInstanceOf[Join]
+            if (declined) withoutRuntimeFilterHint(newJoin) else newJoin

Review Comment:
   **Finding 32.** A join whose hinted side is declined up front runs the 
heuristics, as fixed for 
[r4508394339](https://github.com/apache/spark/pull/58635#discussion_r4508394339).
 A join that settling declines only loses its hint here, after the transform 
that runs them. An IN subquery gets them back in the outer pass, as the test's 
`hoisted` case shows. In the main query, the join keeps no runtime filter.
   
   What I ran, with `applicationSideScanSizeThreshold=3000` and broadcast off:
   
   ```sql
   SELECT /*+ RUNTIME_FILTER(h2), RUNTIME_FILTER(h1) */ a.c1
   FROM (SELECT * FROM bf1 WHERE a1 = 5) a
   JOIN (SELECT c2 AS k, row_number() OVER (PARTITION BY b2 ORDER BY a2) AS rn 
FROM bf2) h2
     ON a.c1 = h2.k
   JOIN bf3 h1 ON h2.rn = h1.c3
   ```
   
   | hints | Bloom filters on |
   |---|---|
   | both | `rn` (the hint on `h2` is reported) |
   | `RUNTIME_FILTER(h1)` only | `k`, `rn` |
   | none | `k` |
   
   The hints page says the first should match the second: Spark "plans the join 
as without the hint". Either the joins that settling declines could get the 
heuristics, for example by visiting them again once settling is done, or the 
page and the description could say that such a join gets no runtime filter.
   



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