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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -653,3 +718,336 @@ trait JoinSelectionHelper extends Logging {
       conf.getConfString("spark.sql.join.forceApplyShuffledHashJoin", "false") 
== "true"
   }
 }
+
+/**
+ * Checks a join side as the source of hinted runtime filters, see 
[[RuntimeFilterSourceAnalysis]].
+ */
+private[sql] trait RuntimeFilterHintCheck {
+
+  /**
+   * Why a runtime filter built from the side on `creationKey` cannot prune on 
`applicationKey`, or
+   * None when it can. The filter evaluates the side and both keys separately 
from the join, so all
+   * of them have to be repeatable. With `checkFunctions`, the side may call 
no function the
+   * filter's subquery cannot evaluate, wherever it calls it: a DPP filter's 
subquery runs the side
+   * as it is, while a Bloom filter's is column-pruned first and checked again.
+   */
+  def rejection(
+      applicationKey: Expression,
+      creationKey: Expression,
+      checkFunctions: Boolean = true): Option[String]
+}
+
+/**
+ * Decides whether a plan can serve as the source of a runtime filter on a 
join key. A runtime
+ * filter evaluates its source separately from the join, so the rows the 
source produces and the
+ * key values they carry must be the same in both evaluations, or the filter 
could prune rows the
+ * join itself matches. `deterministic` is not enough for that: Spark flags 
order-dependent
+ * computations such as first, last, row_number or an unordered LIMIT as 
deterministic, and a leaf
+ * such as an RDD that is not checkpointed may return different rows on each 
computation.
+ *
+ * The plan is walked bottom-up, tracking:
+ *   1. output attributes whose values are unstable: they come from a 
non-deterministic expression,
+ *      an order-dependent aggregate or window function, a subquery whose plan 
fails this same
+ *      analysis, or an expression over such an attribute;
+ *   2. whether the row multiplicity is unstable, i.e. every row is still 
present but may be
+ *      repeated a different number of times, which an outer generate with an 
unstable generator,
+ *      or an aggregate grouping on an unstable value, causes and which makes 
every aggregate over
+ *      the rows unstable.
+ *
+ * The plan is rejected outright when its row set is unstable (a filter or 
join condition consumes
+ * an unstable attribute, an inner generate uses an unstable generator, any 
limit, offset or
+ * sample), when a leaf cannot promise the same rows again, and, each with its 
own reason, when it
+ * calls a function the filter subquery cannot evaluate, when an operator 
would duplicate an
+ * observation or is not analyzed. The source qualifies when the key references
+ * no unstable attribute. Values that are unstable but only carried to the 
output (a `first(name)`
+ * next to a `GROUP BY id`, a row number next to the key) do not disqualify 
it. A CTE that is not
+ * inlined is evaluated from its definition wherever it is read, unless 
exchange reuse shares one
+ * evaluation, so it is analyzed through its definition in `cteDefs`.
+ */
+private[optimizer] class RuntimeFilterSourceAnalysis(
+    side: LogicalPlan,
+    cteDefs: Map[Long, CTERelationDef]) extends RuntimeFilterHintCheck {
+  import RuntimeFilterSourceAnalysis._
+
+  private lazy val sideCallsExtractedFunction = containsExtractedFunction(side)
+
+  private lazy val sideTaint = analyze(side)
+
+  override def rejection(
+      applicationKey: Expression,
+      creationKey: Expression,
+      checkFunctions: Boolean): Option[String] = {
+    if (!isStable(applicationKey, AttributeSet.empty)) {
+      Some("the join key may take different values when evaluated again")
+    } else if (side.isStreaming) {
+      Some("the hinted side is a stream")
+    } else if ((checkFunctions && sideCallsExtractedFunction) ||
+        // A DPP filter evaluates the key in its own subquery, which no UDF 
extraction rewrites.
+        creationKey.containsAnyPattern(PYTHON_UDF, EXTERNAL_UDF)) {
+      Some(ExtractedFunction)
+    } else {
+      sideTaint match {
+        case Left(reason) => Some(reason)
+        case Right(t) if !isStable(creationKey, t.unstable) => 
Some(NotRepeatable)
+        case _ => None
+      }
+    }
+  }
+
+  /**
+   * Whether `e` yields the same value on every evaluation. A subquery counts 
as deterministic
+   * when its plan is, which is the very check this analysis replaces, so its 
plan is analyzed
+   * too.
+   */
+  private def isStable(e: Expression, unstable: AttributeSet): Boolean = {
+    e.deterministic && e.references.intersect(unstable).isEmpty && !e.exists {
+      case s: SubqueryExpression => !isRepeatableSubquery(s)
+      case _ => false
+    }
+  }
+
+  /**
+   * A subquery is repeatable when its row set is, and so is whatever of its 
output the subquery
+   * exposes: the build keys of a DPP filter, nothing but existence for 
EXISTS, the output columns
+   * otherwise. A scalar subquery fails on more than one row, so its 
multiplicity counts too.
+   */
+  private def isRepeatableSubquery(s: SubqueryExpression): Boolean = {
+    !s.plan.isStreaming && analyze(s.plan).exists { t =>
+      s match {
+        case d: DynamicPruningSubquery =>
+          d.broadcastKeyIndices.forall(i => isStable(d.buildKeys(i), 
t.unstable))
+        case _: Exists => true
+        case _: ScalarSubquery =>
+          !t.unstableMultiplicity && 
s.plan.outputSet.intersect(t.unstable).isEmpty
+        case _ => s.plan.outputSet.intersect(t.unstable).isEmpty
+      }
+    }
+  }
+
+  /** Returns the taint of `plan`'s output, or the reason its row set is not 
repeatable. */
+  private def analyze(plan: LogicalPlan): Either[String, Taint] = plan match {
+    // Whether a materialized leaf returns the same rows is known only once it 
is materialized.
+    case m: MaterializedLeafNode if m.materializedMetadata.isEmpty =>
+      Left(s"the hinted side reads ${m.nodeName}, which is not materialized 
yet")
+
+    // The source may have absorbed an operator from the hinted side, so name 
that rather than the
+    // scan the user did not write.
+    case s: DataSourceV2ScanRelation if !s.isOutputRepeatable =>
+      Left(s"the hinted side reads ${s.name} with an aggregate, limit, offset, 
top-N or sample " +
+        "pushed into the source, which may return different rows when 
evaluated again")
+
+    case r: CTERelationRef => cteDefs.get(r.cteId).filterNot(_ => r.recursive) 
match {
+      case Some(cteDef) => analyze(cteDef.child).map { t =>
+        val unstable = r.output.zip(cteDef.child.output).collect {
+          case (attr, defAttr) if t.unstable.contains(defAttr) => attr
+        }
+        Taint(AttributeSet(unstable), t.unstableMultiplicity)
+      }
+      case None =>
+        Left("the hinted side reads a recursive CTE or one defined outside the 
plan being " +
+          "optimized, which cannot be checked for repeatability")
+    }
+
+    case l: LeafNode =>
+      if (l.isOutputRepeatable) {
+        Right(Taint(AttributeSet.empty))

Review Comment:
   Fixed in 9d14a7f8525 as suggested. Your query is a new case in the 
repeatable-source test. A regression of this PR.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala:
##########
@@ -311,6 +317,8 @@ case class DataSourceV2ScanRelation(
     s"RelationV2$outputString $nameWithTimeTravelSpec"
   }
 
+  override def isOutputRepeatable: Boolean = repeatableScan

Review Comment:
   Done in 9d14a7f8525: a V1 relation counts as repeatable again, like a DSv2 
scan without a pushed limit, sample or aggregate. The docs say Spark cannot 
check a source that picks its own rows, such as a JDBC query with a `LIMIT` or 
a Kafka read up to the latest offsets.
   



##########
docs/sql-ref-syntax-qry-select-hints.md:
##########
@@ -172,6 +172,76 @@ SELECT /*+ SHUFFLE_REPLICATE_NL(t1) */ * FROM t1 INNER 
JOIN t2 ON t1.key = t2.ke
 SELECT /*+ BROADCAST(t1), MERGE(t1, t2) */ * FROM t1 INNER JOIN t2 ON t1.key = 
t2.key;
 ```
 
+### Runtime Filter Hints
+
+Runtime filter hints allow users to suggest which side of a join Spark should 
build a runtime
+filter from, to prune the other side. Spark decides on its own whether a 
runtime filter is worth
+building, based on statistics; the hint overrides that decision, but not the 
requirements that make
+the filter correct, so Spark is not guaranteed to follow it and issues a 
warning when it cannot.
+Spark may also decline the hint because of configured limits on runtime 
filters; the warning names
+the reason. When the hinted side cannot be the source of a runtime filter, 
Spark plans the join as
+without the hint; when Spark declines the hint for another reason, it does not 
build a filter in the
+other direction instead.
+
+#### Runtime Filter Hints Types
+
+* **RUNTIME_FILTER**
+
+    Suggests that Spark build a runtime filter from the hinted relation and 
use it to prune the
+    other side of the join. Use it when the hinted side matches only a small 
fraction of the other
+    side but Spark does not choose a runtime filter on its own, e.g. because 
table statistics are
+    missing or misleading. The hinted side must produce the same set of rows, 
with the same join key
+    values, whenever it is evaluated; its other columns may differ, and it 
cannot be a stream, though
+    the static side of a stream-static join can be hinted to prune a stream 
without a stateful
+    operator, such as an aggregation, below the join. `RUNTIME_FILTER` can be 
combined with a join
+    strategy hint.
+
+    For a Bloom filter, the hint overrides
+    `spark.sql.optimizer.runtime.bloomFilter.creationSideThreshold`,
+    
`spark.sql.optimizer.runtime.bloomFilter.applicationSideScanSizeThreshold`, and 
the requirements
+    that the hinted side have a selective predicate and that the join involve 
a shuffle. It still
+    obeys `spark.sql.optimizer.runtime.bloomFilter.enabled` and
+    `spark.sql.optimizer.runtimeFilter.number.threshold`, requires simple join 
keys that compare by
+    their bytes, unlike a string with a case- or accent-insensitive collation, 
and the filter

Review Comment:
   Fixed in 9d14a7f8525 as suggested.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -455,27 +536,41 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with 
PredicateHelper with J
   }
 
   // The plans whose broadcast a DPP filter may reuse: its build plan, and for 
an `onlyInBroadcast`
-  // filter, the source plan of its broadcast value projection.
+  // filter, the source plan of its broadcast value projection. Each is taken 
without its DPP
+  // filters, as the join sides it is compared with are.
   private def reusablePlans(dpp: DynamicPruningSubquery): Seq[LogicalPlan] =

Review Comment:
   Fixed in 9d14a7f8525: each DPP filter's plans are built once, in a map next 
to `reused`.
   



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