pan3793 commented on code in PR #58635:
URL: https://github.com/apache/spark/pull/58635#discussion_r4542595596
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -653,3 +718,346 @@ 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, a file metadata column, some of whose fields depend on how a
scan splits its
+ * files, 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")
+
+ // `V2ScanRelationPushDown` marks a scan repeatable unless the source
absorbed an operator from
+ // the hinted side that picks its rows, which the reason names as the
likely cause. A scan built
+ // elsewhere, such as the target scan of a copy-on-write DELETE, UPDATE or
MERGE, is not marked.
+ case s: DataSourceV2ScanRelation if !s.isOutputRepeatable =>
+ Left(s"the hinted side reads ${s.name}, which may return different rows
when evaluated " +
+ "again, e.g. with an aggregate, limit, offset, top-N or sample pushed
into the source")
+
+ case r: CTERelationRef if r.recursive =>
+ Left("the hinted side reads a recursive CTE, which cannot be checked for
repeatability")
+
+ case r: CTERelationRef => cteDefs.get(r.cteId) 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(OuterCte)
+ }
+
+ case l: LeafNode =>
+ if (l.isOutputRepeatable) {
+ // A file metadata column has fields, such as
`_metadata.file_block_start`, that depend on
+ // how the scan splits its files, which the filter's own scan of the
side can do
+ // differently.
+ Right(Taint(AttributeSet(
+ l.output.filter(a =>
FileSourceMetadataAttribute.isValid(a.metadata)))))
+ } 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
Review Comment:
Fixed in `99045dc259c` as suggested: a grouping column of a collated type
that the aggregate passes on is kept apart from the other unstable columns, and
a key, a filter or a join condition that reads it only through `CollationKey`
is stable. Your two grouped sides are new cases in the collation test.
--
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]