pan3793 commented on code in PR #58635:
URL: https://github.com/apache/spark/pull/58635#discussion_r4510804972
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -578,3 +640,286 @@ trait JoinSelectionHelper extends Logging {
conf.getConfString("spark.sql.join.forceApplyShuffledHashJoin", "false")
== "true"
}
}
+
+/**
+ * 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 over an unstable value, causes and which makes every
aggregate over the
Review Comment:
Fixed in 558bf3e9cba.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -578,3 +640,286 @@ trait JoinSelectionHelper extends Logging {
conf.getConfString("spark.sql.join.forceApplyShuffledHashJoin", "false")
== "true"
}
}
+
+/**
+ * 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 over 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.
+ */
+private[optimizer] object RuntimeFilterSourceAnalysis {
+
+ /**
+ * @param unstable output attributes whose values depend on evaluation order
or on chance.
+ * @param unstableMultiplicity whether rows may be repeated a different
number of times per
+ * evaluation, while each row stays present.
+ */
+ private case class Taint(unstable: AttributeSet, unstableMultiplicity:
Boolean = false)
+
+ private val NotRepeatable =
+ "the hinted side may produce different rows or join keys when evaluated
again"
+
+ /** Why `plan` is not a repeatable source of `key`, or None when it is. */
+ def rejection(plan: LogicalPlan, key: Expression): Option[String] = {
+ if (plan.isStreaming) {
+ Some("the hinted side is a stream")
+ } else if (containsExtractedFunction(plan) ||
+ // A DPP filter evaluates the key in its own subquery, which no UDF
extraction rewrites.
+ key.containsAnyPattern(PYTHON_UDF, EXTERNAL_UDF)) {
+ Some("the hinted side contains a Python UDF, Python UDTF or external
UDF, which a runtime " +
+ "filter cannot evaluate")
+ } else {
+ analyze(plan) match {
+ case Left(reason) => Some(reason)
+ case Right(t) if !isStable(key, t.unstable) => Some(NotRepeatable)
+ case _ => None
+ }
+ }
+ }
+
+ def isRepeatableExpression(e: Expression): Boolean = isStable(e,
AttributeSet.empty)
+
+ def containsExtractedFunction(plan: LogicalPlan): Boolean = {
+ plan.containsAnyPattern(PYTHON_UDF, EXTERNAL_UDF) || plan.exists {
+ case g: Generate => g.generator.isInstanceOf[PythonUDTF]
+ case _ => false
+ }
+ }
+
+ /**
+ * 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 l: LeafNode =>
+ if (l.isOutputRepeatable) {
+ Right(Taint(AttributeSet.empty))
+ } else {
+ Left(s"the hinted side reads ${l.nodeName}, which may return different
rows when " +
+ "evaluated again")
+ }
+
+ case p: Project => analyze(p.child).map { t =>
+ t.copy(unstable =
+ AttributeSet(p.projectList.filterNot(isStable(_,
t.unstable)).map(_.toAttribute)))
+ }
+
+ case f: Filter => analyze(f.child).flatMap { t =>
+ if (isStable(f.condition, t.unstable)) Right(t) else Left(NotRepeatable)
+ }
+
+ case j: Join => analyze(j.left).flatMap { l =>
+ analyze(j.right).flatMap { r =>
+ val unstable = l.unstable ++ r.unstable
+ if (j.condition.forall(isStable(_, unstable))) {
+ Right(Taint(unstable, l.unstableMultiplicity ||
r.unstableMultiplicity))
+ } else {
+ Left(NotRepeatable)
+ }
+ }
+ }
+
+ case a: Aggregate => analyze(a.child).map { t =>
+ // Grouping on an unstable value changes which rows form a group, and
unstable multiplicity
+ // changes how many rows each group has, so every aggregate result then
depends on them; a
+ // grouping expression's own value is as stable as its input. With
stable grouping the
+ // groups occur once each, whatever the input multiplicity; with
unstable grouping, the
+ // number of groups that share the stable grouping values varies.
+ val stableGroups = a.groupingExpressions.forall(isStable(_, t.unstable))
+ // A group of values that are equal but not identical, e.g. under a
case-insensitive
+ // collation, outputs whichever of them arrives first.
+ val representatives = AttributeSet(a.groupingExpressions
+ .filterNot(e =>
UnsafeRowUtils.isBinaryStable(e.dataType)).flatMap(_.references))
+ val unstable = a.aggregateExpressions.filter { e =>
+ !isStable(e, t.unstable) ||
+ referencesOutsideAggregates(e).intersect(representatives).nonEmpty ||
+ (e.exists(_.isInstanceOf[AggregateExpression]) &&
+ (!stableGroups || t.unstableMultiplicity || !isOrderIrrelevant(e)))
+ }
+ Taint(AttributeSet(unstable.map(_.toAttribute)), unstableMultiplicity =
!stableGroups)
+ }
+
+ case w: Window => analyze(w.child).map { t =>
+ val stablePartitions = w.partitionSpec.forall(isStable(_, t.unstable))
+ val unstable = w.windowExpressions.filter { e =>
+ !stablePartitions || t.unstableMultiplicity || !isStable(e,
t.unstable) ||
+ !isOrderIrrelevantWindow(e)
+ }
+ t.copy(unstable = t.unstable ++
AttributeSet(unstable.map(_.toAttribute)))
+ }
+
+ case u: Union =>
+ val taints = u.children.map(analyze)
+ taints.collectFirst { case Left(reason) => Left(reason) }.getOrElse {
+ val unstable = u.output.zipWithIndex.collect {
+ case (attr, i) if u.children.zip(taints).exists {
+ case (child, Right(taint)) =>
taint.unstable.contains(child.output(i))
Review Comment:
Fixed in 558bf3e9cba: each child's output is built once, and nothing is
mapped when no child has an unstable value.
--
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]