peter-toth commented on code in PR #58635:
URL: https://github.com/apache/spark/pull/58635#discussion_r4515508734
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -99,6 +122,55 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
Filter(filter, filterApplicationSidePlan)
}
+ // The aggregate that the Bloom filter's subquery evaluates over the
creation side.
+ private def bloomFilterAggregate(filterCreationSide: FilterCreationSide):
LogicalPlan = {
+ val filterCreationSideKey = filterCreationSide.key
+ val filterCreationSidePlan = filterCreationSide.plan
+ val rowCount = filterCreationSide.materializedRowCount
+ .orElse(filterCreationSidePlan.stats.rowCount)
+ val bloomFilterAgg =
+ if (rowCount.isDefined && rowCount.get.longValue > 0L) {
+ new BloomFilterAggregate(new XxHash64(Seq(filterCreationSideKey)),
rowCount.get.longValue)
+ } else {
+ new BloomFilterAggregate(new XxHash64(Seq(filterCreationSideKey)))
+ }
+
+ val alias = Alias(bloomFilterAgg.toAggregateExpression(), "bloomFilter")()
+ ConstantFolding(if (filterCreationSide.hinted) {
+ pruneColumns(Aggregate(Nil, Seq(alias), filterCreationSidePlan))
+ } else {
+ ColumnPruning(Aggregate(Nil, Seq(alias), filterCreationSidePlan))
+ })
+ }
+
+ // Prunes the columns of the new subquery to a fixed point. A hinted
creation side can have any
+ // shape, e.g. an aggregate or a window whose extra columns take more than
one pass to remove.
+ private def pruneColumns(plan: LogicalPlan): LogicalPlan = {
+ def prune(p: LogicalPlan) = withoutUnreadOuterGenerates(ColumnPruning(p))
+ var current = plan
+ var pruned = prune(current)
+ var iteration = 1
+ while (!pruned.fastEquals(current) && iteration <
conf.optimizerMaxIterations) {
+ current = pruned
+ pruned = prune(current)
+ iteration += 1
+ }
+ pruned
+ }
+
+ // An outer generate keeps every row of its child and only repeats some,
which a Bloom filter
+ // does not depend on. So one whose output nothing else in the subquery
reads is dropped, together
+ // with its generator, which column pruning keeps and which need not be
deterministic.
+ private def withoutUnreadOuterGenerates(plan: LogicalPlan): LogicalPlan = {
+ def isRead(g: Generate): Boolean = {
+ val generated = AttributeSet(g.generatorOutput)
+ plan.exists(node => !(node eq g) &&
node.references.intersect(generated).nonEmpty)
+ }
+ plan transformDown {
+ case g: Generate if g.outer && !isRead(g) => g.child
Review Comment:
**Finding 13.** The fix for finding 6 drops an outer `Generate` that nothing
in the filter's subquery reads. That holds for the filter's own key, but not
when an operator above the generate counts its repeated rows.
`RuntimeFilterSourceAnalysis` accepts a deterministic generator here, since it
leaves the multiplicity stable, so this side passes:
```sql
-- gdim: (1, array(1, 2)), (2, array(1)); gfact: (1, 10), (2, 20)
SELECT /*+ RUNTIME_FILTER(d) */ f.k, f.v FROM gfact f JOIN
(SELECT k FROM (SELECT k, count(*) c FROM gdim
LATERAL VIEW OUTER explode(arr) e AS x GROUP BY k) WHERE c > 1) d
ON f.k = d.k
```
- On master, which ignores the hint, and at this head without the hint: `[1,
10]`.
- At this head with the hint, AQE on and off: no rows. The filter's subquery
counts one row per `k`, so `c > 1` keeps no key, and the Bloom filter prunes
every row of `gfact`.
- With the suggestion: `[1, 10]` with the Bloom filter, AQE on and off, and
`InjectRuntimeFilterSuite` passes.
Only a generate over an unstable generator needs dropping. For that one, the
analysis already rejects anything above it that counts rows
(`unstableMultiplicity`). The comment above would then say so, and this query
with `checkAnswer` pins it.
```suggestion
case g: Generate if g.outer && !g.generator.deterministic &&
!isRead(g) => g.child
```
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -533,71 +628,269 @@ object InjectRuntimeFilter extends Rule[LogicalPlan]
with PredicateHelper with J
cannotFail(leafKey) && !reused.exists(_.exists(_.fastEquals(leaf)))
}
}
+ val bloomFilterEnabled = conf.runtimeFilterBloomFilterEnabled
+ lazy val cteDefs = cteDefinitions(plan)
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) => {
- 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)
+ // A key whose DPP filter honors the hint was accepted by
[[PartitionPruning]], before a
+ // filter pushed into the hinted side could change its analysis. A
Bloom filter's subquery
+ // is checked for the functions it calls once it is built.
+ val declinedReason = hintedSource.flatMap { side =>
+ val reasons = keyFilters.map { case (l, r, leftFilters,
rightFilters) =>
+ if (honorHint(if (side == BuildRight) leftFilters else
rightFilters)) None
+ else hintRejection(l, r, checkFunctions = false)
+ }
+ if (reasons.forall(_.isDefined)) reasons.head else None
+ }
+ 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)
+ } 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. 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.
+ val creationPlan = if (keyDpps.isEmpty) {
+ creationSide
+ } else {
+ withoutDppFilters(creationSide, keyDpps.contains)
+ }
Review Comment:
**Finding 14.** Now that the rule runs after DPP pushdown, a lower join's
creation side can carry a DPP filter that an upper join pushed into it.
`extractSelectiveFilterOverScan` then stops at that filter whenever
`isSimpleExpression` rejects something in its build plan, which it sees through
the subquery. With the suite's tables:
```sql
SELECT * FROM bf1 JOIN bf5part ON bf1.c1 = bf5part.c5
JOIN bf2 ON bf5part.f5 = bf2.c2
WHERE bf5part.a5 = 5 AND bf2.a2 = 62 AND CAST(bf2.b2 AS STRING) LIKE '%1%2%'
```
With `applicationSideScanSizeThreshold=3000`,
`autoBroadcastJoinThreshold=2000` and the default `reuseBroadcastOnly`, AQE on
and off:
- Master: Bloom filters on `c1` and `c2`.
- This head: only on `c2`, so `bf1` loses its filter. Without the `LIKE`,
both build the one on `c1`.
- With the suggestion: `c1` and `c2` again, and `InjectRuntimeFilterSuite`
passes.
An `onlyInBroadcast` DPP filter finds no broadcast in the filter's subquery
and is `true` there, as the `cannotFail` comment says. So leaving it out
changes nothing the subquery computes. A DPP filter that runs as its own
subquery stays in, as "SPARK-60702: do not add bloom filter whose creation side
keeps a dpp filter that runs as its own subquery" expects. The comment above
would need the same update.
```suggestion
val creationPlan =
withoutDppFilters(creationSide, dpp => dpp.onlyInBroadcast ||
keyDpps.contains(dpp))
```
##########
sql/core/src/test/scala/org/apache/spark/sql/InjectRuntimeFilterSuite.scala:
##########
@@ -1832,6 +1911,43 @@ class InjectRuntimeFilterSuite extends SharedSparkSession
}
}
+ test("Runtime bloom filter join: add bloom filter if the dpp filter cannot
reach the scan") {
+
withSQLConf(SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key
-> "3000",
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "2000") {
Review Comment:
**Finding 15.** This test passes on master too, so it doesn't pin the change
it is named for. Since SPARK-60702, master already adds the Bloom filter for a
DPP filter that is `onlyInBroadcast` with no broadcast to reuse. With
`reuseBroadcastOnly` at its default, that is the case here. Running
`InjectRuntimeFilter` after cleanup changes the result only for a DPP filter
that is not broadcast-only. I ran this query on master and at this head:
- `reuseBroadcastOnly` on: one Bloom filter on both.
- `reuseBroadcastOnly` off: no Bloom filter and no DPP filter on master, and
one Bloom filter at this head.
Turning it off here makes the test fail on master and pass at this head:
```suggestion
SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "2000",
SQLConf.DYNAMIC_PARTITION_PRUNING_REUSE_BROADCAST_ONLY.key -> "false")
{
```
##########
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:
**Finding 18.** A leaf that repeats its rows doesn't repeat
`_metadata.file_block_start` or `file_block_length`. They depend on how the
scan splits its files, and the filter's own scan can split them differently,
e.g. when another join's DPP filter narrows only the join's scan.
`canEvaluateAgain` rejects them on the heuristic path for this reason
(`InjectRuntimeFilter.scala:516`).
With `applicationSideScanSizeThreshold=1GB`, so that only the hint builds a
filter, this query still gets a Bloom filter on `bf4.c4`:
```sql
SELECT /*+ RUNTIME_FILTER(d) */ * FROM bf4 JOIN
(SELECT c2 FROM bf2 WHERE a2 = 62 AND _metadata.file_block_start = 0) d ON
bf4.c4 = d.c2
```
I haven't produced wrong rows with it, since that needs the two scans to
split a file differently. Treating the metadata columns as unstable would
decline the hint there:
```suggestion
if (l.isOutputRepeatable) {
// A file metadata column, such as `_metadata.file_block_start`,
depends 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)))))
```
##########
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:
**Finding 19.** After [finding
4](https://github.com/apache/spark/pull/58635#discussion_r4510801691),
`LogicalRelation` trusts only a `HadoopFsRelation`, because a JDBC query or a
Kafka batch read up to the latest offsets can return other rows
(`LogicalRelation.scala:56`). The DSv2 versions of the same sources pass,
though:
- `V2ScanRelationPushDown` sets `repeatableScan` for any scan without a
pushed aggregate, limit, offset, top-N or sample.
- The new `JDBCV2Suite` test expects a hinted, filtered JDBC v2 side to get
its filter.
- With `kafka` taken out of `spark.sql.sources.useV1SourceList`, a Kafka
DSv2 batch read with `endingOffsets=latest` resolves the offsets in each
`BatchScanExec`, so the filter's scan and the join's can read different records.
Either the DSv2 path needs a signal from the source, or the V1 restriction
goes and the docs' "must produce the same set of rows" covers both. This comes
from reading the code.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -402,14 +478,19 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
case _ => Nil
}
- // `plan` without the DPP filters on top of it that `drop` picks, by default
all of them.
+ // `plan` without the DPP filters that `drop` picks, by default all of them.
This rule runs after
+ // the DPP filters are pushed down, so they can be conjuncts of any filter
in `plan`.
private def withoutDppFilters(
plan: LogicalPlan,
- drop: DynamicPruningSubquery => Boolean = _ => true): LogicalPlan = plan
match {
- case f @ Filter(dpp: DynamicPruningSubquery, child) =>
- val newChild = withoutDppFilters(child, drop)
- if (drop(dpp)) newChild else f.withNewChildren(Seq(newChild))
- case _ => plan
+ drop: DynamicPruningSubquery => Boolean = _ => true): LogicalPlan = plan
transform {
Review Comment:
**Finding 16.** For a `Filter` whose conjuncts are all dropped DPP filters,
this returns `child`, and `transform` goes on with the children of what it
returned. So `Filter(dpp1, Filter(dpp2, x))`, the stack `PartitionPruning`
builds for two keys, keeps `dpp2`. Master's recursion stripped it.
A DPP filter's `buildQuery` is taken before pushdown combines such a stack,
while `broadcastablePlans` strips the combined filter of a join side. So a
stack in a `buildQuery` makes `reusablePlans` miss the broadcast in
`sameResult`, and `isKept` then treats a DPP filter that physical planning
keeps as dropped. That chain comes from reading the code. A two-key join whose
build side is itself pruned by DPP on two keys would show it. `transformUp`
strips the stack:
```suggestion
drop: DynamicPruningSubquery => Boolean = _ => true): LogicalPlan =
plan transformUp {
```
##########
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:
**Finding 20.** A plain collated column still gets its Bloom filter, since
it is joined on its collation key, which compares by its bytes. Only a key
computed from a collated string is refused, as the "RUNTIME_FILTER hint refuses
a collated key that is not a plain column" test shows. As written, this reads
as if a `UTF8_LCASE` join column could not be hinted at all:
```suggestion
their bytes: a collated string column qualifies, but a key computed from
one, such as
`substr(k, 1, 3)`, does not. The filter
```
##########
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:
**Finding 21.** `isKept` calls this for every DPP filter of every key, and
each call runs `withoutDppFilters` over the DPP filter's build query again.
Computing it once per DPP filter, e.g. in a map next to the lazy `reused`,
avoids rebuilding the same plans per key and per join.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -533,71 +628,269 @@ object InjectRuntimeFilter extends Rule[LogicalPlan]
with PredicateHelper with J
cannotFail(leafKey) && !reused.exists(_.exists(_.fastEquals(leaf)))
}
}
+ val bloomFilterEnabled = conf.runtimeFilterBloomFilterEnabled
+ lazy val cteDefs = cteDefinitions(plan)
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) => {
- 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)
+ // A key whose DPP filter honors the hint was accepted by
[[PartitionPruning]], before a
+ // filter pushed into the hinted side could change its analysis. A
Bloom filter's subquery
+ // is checked for the functions it calls once it is built.
+ val declinedReason = hintedSource.flatMap { side =>
+ val reasons = keyFilters.map { case (l, r, leftFilters,
rightFilters) =>
+ if (honorHint(if (side == BuildRight) leftFilters else
rightFilters)) None
+ else hintRejection(l, r, checkFunctions = false)
+ }
+ if (reasons.forall(_.isDefined)) reasons.head else None
+ }
+ 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)
+ } 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. 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.
+ val creationPlan = if (keyDpps.isEmpty) {
+ creationSide
+ } else {
+ withoutDppFilters(creationSide, keyDpps.contains)
+ }
+ 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): 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) &&
Review Comment:
**Finding 17.** For a key whose DPP filters are all dropped, the heuristic
path builds its Bloom filter only if `canPushDown(applicationSideKey,
applicationSide)` holds (`InjectRuntimeFilter.scala:746`). That check does two
things:
- It keeps a key that can fail out of a partition filter, which would
evaluate it on every partition before the data filters (SPARK-60809).
- It keeps the filter out of a broadcast that another DPP filter reuses.
`injectHintedFilter` doesn't check it. It reaches such a key when
`PartitionPruning` declines the hint and inserts a heuristic `onlyInBroadcast`
DPP filter. That happens, e.g., for a Python UDF on the hinted side, which only
the DPP side checks for (`checkFunctions`).
This comes from reading the code. A test would need a Python UDF on the
hinted side, a key such as `CAST(p AS TINYINT)` on a partition column, and ANSI
mode. Passing `keyDpps` into `injectHintedFilter` would allow the same check:
```scala
} else if (keyDpps.nonEmpty && !canPushDown(applicationSideKey,
applicationSide)) {
hintBlocked("the join key can fail on rows the join does not
read")
currentApplicationSide
```
--
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]