dongjoon-hyun commented on code in PR #60387:
URL: https://github.com/apache/spark/pull/60387#discussion_r4560012324
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -244,6 +245,18 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
targetKey,
currentPlan,
useMaterializedThreshold = false))
+ // A DSv2 scan can take a filter in fully and leave no `Filter` for it,
as a built-in file
+ // scan does with its partition filters. With no selective `Filter`
above the scan, its
+ // pushed filters count as such a `Filter` would, but only for a scan
whose pushed operations
+ // all work on each row by itself, since the bloom filter's subquery
reads it again. A pushed
+ // limit, for example, lets the source pick other rows on a second read.
+ case scan: DataSourceV2ScanRelation if scan.onlyRowWisePushdowns &&
+ scan.pushedFilters.forall(isSimpleExpression) &&
Review Comment:
`pushedFilters.forall(isSimpleExpression)` is checked only in this branch.
With a selective post-scan `Filter`, `case _: LeafNode if
hasHitSelectiveFilter` above matches the V2 scan first, so a non-simple pushed
filter still passes there.
For example, with `d.ds LIKE 'a_' AND d.v > 2` (`ds` is a partition column),
V1 keeps the `LIKE` in the `Filter` and builds no bloom filter, while V2 pushes
the `LIKE` into the scan, keeps `v > 2` above it, and builds one. This behavior
exists before this PR too, but this PR applies the new `cannotFail` check on
`pushedFilters` to both paths (in `canEvaluateAgain`) and the
`isSimpleExpression` check to only one. Should the `isSimpleExpression` check
on `pushedFilters` also apply under a selective `Filter`, to match V1 as the PR
description says?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -244,6 +245,18 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
targetKey,
currentPlan,
useMaterializedThreshold = false))
+ // A DSv2 scan can take a filter in fully and leave no `Filter` for it,
as a built-in file
+ // scan does with its partition filters. With no selective `Filter`
above the scan, its
+ // pushed filters count as such a `Filter` would, but only for a scan
whose pushed operations
+ // all work on each row by itself, since the bloom filter's subquery
reads it again. A pushed
+ // limit, for example, lets the source pick other rows on a second read.
+ case scan: DataSourceV2ScanRelation if scan.onlyRowWisePushdowns &&
Review Comment:
This branch hands the V2 scan to `injectBloomFilter`, which compares
`filterCreationSidePlan.stats.sizeInBytes` with the creation side threshold
(10MB by default). For a V2 file scan, `FileScan.estimateStatistics` reports
`fileIndex.sizeInBytes` of the whole table, not the size after the pushed
partition filters, while V1 gets the pruned size from
`PruneFileSourcePartitions`. So the parity with V1 holds only when the whole
dimension table is under the threshold, as in the test.
For example, for a 1GB V2 Parquet dimension with 100 partitions where `dp =
1` selects 10MB, V1 builds a bloom filter but V2 does not. Also, with no row
count, the bloom filter falls back to its default size. Could we address the
size estimate, or at least mention this limitation in the comment and the PR
description?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -447,7 +461,8 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
case Project(projectList, _) => !projectList.forall(e =>
cannotFail(trimAliases(e)))
case Filter(condition, _) =>
!splitConjunctivePredicates(condition).forall(cannotFail)
case _: CTERelationRef => true
- case scan: DataSourceV2ScanRelation => !scan.onlyRowWisePushdowns
+ case scan: DataSourceV2ScanRelation =>
+ !scan.onlyRowWisePushdowns || !scan.pushedFilters.forall(cannotFail)
Review Comment:
This also changes the existing path. For a key whose DPP filters are
dropped, a V2 creation side with any fully pushed filter outside the
`cannotFail` allowlist is now rejected, even under a selective `Filter`, where
master builds a bloom filter.
For a source that evaluates pushed filters itself and supports no runtime
filtering (e.g. JDBC), no DPP or bloom filter can narrow the join's read of the
scan below its pushed filters. So both reads evaluate them on the same rows,
and the bloom filter's subquery adds no failure risk; the change only costs the
bloom filter (more scan and shuffle on the application side). Could we limit
this check to scans whose read the join can narrow, e.g. by runtime filtering,
or confirm that this trade-off is intended?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -447,7 +461,8 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
case Project(projectList, _) => !projectList.forall(e =>
cannotFail(trimAliases(e)))
case Filter(condition, _) =>
!splitConjunctivePredicates(condition).forall(cannotFail)
case _: CTERelationRef => true
- case scan: DataSourceV2ScanRelation => !scan.onlyRowWisePushdowns
+ case scan: DataSourceV2ScanRelation =>
+ !scan.onlyRowWisePushdowns || !scan.pushedFilters.forall(cannotFail)
Review Comment:
Both this guard and the new branch in `extract` assume that the fully pushed
filters are recorded in `pushedFilters`. However,
`V2ScanRelationPushDown.buildScanWithPushedVariants` (used for the Parquet
variant pushdown) builds the scan with `onlyRowWisePushdowns =
!hasRowSelectingPushdown(holder)` but without `pushedFilters`, as its note on
`holder.pushedFilterExpressions` says.
So for a V2 Parquet dimension with a variant extraction and a fully pushed
partition filter that `cannotFail` rejects (e.g. `ds RLIKE '^a'`), under a
selective `Filter` and for a key whose DPP filter is dropped,
`pushedFilters.forall(cannotFail)` passes trivially. That is the SPARK-60842
case this check guards against. Without a selective `Filter`, the new branch
sees no pushed filters and builds no bloom filter, unlike V1. Could we handle
this path, or at least document and test it?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -244,6 +245,18 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
targetKey,
currentPlan,
useMaterializedThreshold = false))
+ // A DSv2 scan can take a filter in fully and leave no `Filter` for it,
as a built-in file
+ // scan does with its partition filters. With no selective `Filter`
above the scan, its
+ // pushed filters count as such a `Filter` would, but only for a scan
whose pushed operations
+ // all work on each row by itself, since the bloom filter's subquery
reads it again. A pushed
+ // limit, for example, lets the source pick other rows on a second read.
+ case scan: DataSourceV2ScanRelation if scan.onlyRowWisePushdowns &&
+ scan.pushedFilters.forall(isSimpleExpression) &&
+ scan.pushedFilters.exists(isLikelySelective) =>
Review Comment:
nit: `onlyRowWisePushdowns && pushedFilters.exists(isLikelySelective)`
duplicates the V2 case of `PartitionPruning.hasSelectivePredicate`
(`PartitionPruning.scala` L240-241). How about a small helper on
`DataSourceV2ScanRelation` in catalyst, which both rules can reach? Otherwise,
when one of them changes (e.g. a new row-selecting pushdown or a change to the
`isSimpleExpression` condition), the V2 eligibility for DPP and for the bloom
filter can drift apart silently.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -244,6 +245,18 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
targetKey,
currentPlan,
useMaterializedThreshold = false))
+ // A DSv2 scan can take a filter in fully and leave no `Filter` for it,
as a built-in file
+ // scan does with its partition filters. With no selective `Filter`
above the scan, its
+ // pushed filters count as such a `Filter` would, but only for a scan
whose pushed operations
+ // all work on each row by itself, since the bloom filter's subquery
reads it again. A pushed
+ // limit, for example, lets the source pick other rows on a second read.
+ case scan: DataSourceV2ScanRelation if scan.onlyRowWisePushdowns &&
+ scan.pushedFilters.forall(isSimpleExpression) &&
+ scan.pushedFilters.exists(isLikelySelective) =>
+ Some(FilterCreationSide(
Review Comment:
nit: This body is the same as the one of `case _: LeafNode if
hasHitSelectiveFilter` right above. Could we merge the two cases with one
guard, e.g. `case leaf: LeafNode if hasHitSelectiveFilter ||
hasSelectivePushedFilters(leaf) =>`, with the helper suggested on L255? Then a
later change to `FilterCreationSide` needs only one place.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -244,6 +245,18 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
targetKey,
currentPlan,
useMaterializedThreshold = false))
+ // A DSv2 scan can take a filter in fully and leave no `Filter` for it,
as a built-in file
Review Comment:
Not a blocker, but on the direction: a filter that a V2 scan took in fully
is now special-cased in each consumer
(`PartitionPruning.hasSelectivePredicate`, `extract` here, and
`canEvaluateAgain`). Would a leaf-level hook be a better long-term fix? For
example, the TODO in `DataSourceV2ScanRelation` to expose `pushedFilters` as
`validConstraints`, or a `hasSelectivePredicate`-like notion on leaves, as
`MaterializedLeafNode` has. Otherwise each selectivity-based heuristic needs
the same special case, and each build site that does not record `pushedFilters`
(see the variant scan comment on L465) leaves a gap in all of them.
##########
sql/core/src/test/scala/org/apache/spark/sql/InjectRuntimeFilterSuite.scala:
##########
@@ -2047,6 +2049,87 @@ class InjectRuntimeFilterSuite extends SharedSparkSession
}
}
+ test("SPARK-61173: a DSv2 scan that took a selective filter in fully can be
the creation " +
+ "side, as in V1") {
+ // `FileScanBuilder` takes a partition filter in fully and leaves no
`Filter` for it above the
+ // V2 scan, while V1 keeps the `Filter`. With no selective `Filter` above
the V2 scan, the rule
+ // counts the pushed filters as it counts the condition of that `Filter`.
V1 is the reference.
+ withTempDir { dir =>
+ val factPath = new File(dir, "fact").getCanonicalPath
+ val dimPath = new File(dir, "dim").getCanonicalPath
+ spark.range(100).selectExpr("id", "CAST(id % 10 AS INT) AS part")
+ .write.partitionBy("part").parquet(factPath)
+ spark.range(10).selectExpr("CAST(id AS INT) AS k", "CAST(id AS INT) AS
v",
+ "CAST(id % 2 AS INT) AS dp", "IF(id < 5, 'a1', 'b1') AS ds")
+ .write.partitionBy("dp", "ds").parquet(dimPath)
+ def createViews(): Unit = {
+ // A temp view keeps the relation it was created with, so create both
under the conf.
+ spark.read.parquet(factPath).createOrReplaceTempView("rf_fact")
+ spark.read.parquet(dimPath).createOrReplaceTempView("rf_dim")
+ }
+ def query(condition: String): String =
+ s"SELECT f.id FROM rf_fact f JOIN rf_dim d ON f.part = d.k WHERE
$condition"
+ // (condition, the fact partitions it keeps, the columns the bloom
filters check without DPP
+ // and with a DPP filter that the shuffle join drops). A `LIKE` is not
simple: V1 keeps it in
+ // the `Filter`, and V2 pushes it with no selective `Filter` above the
scan, so neither builds
+ // a bloom filter. For a key with a dropped DPP filter, the pushed
filters must pass
+ // `cannotFail`, which does not take `RLIKE`, also under a selective
`Filter` on `v`.
+ val cases = Seq(
+ ("d.dp = 1", (p: Int) => p % 2 == 1, Seq("part"), Seq("part")),
+ ("d.ds RLIKE '^a'", (p: Int) => p < 5, Seq("part"), Nil),
+ ("d.ds RLIKE '^a' AND d.v > 2", (p: Int) => p == 3 || p == 4,
Seq("part"), Nil),
+ ("d.ds LIKE 'a_'", (p: Int) => p < 5, Nil, Nil))
+ withTempView("rf_fact", "rf_dim") {
+ withDppTestConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+
SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1") {
+ for {
+ (condition, keeps, withoutDpp, withDroppedDpp) <- cases
+ dpp <- Seq(false, true)
+ v1Sources <- Seq("parquet", "")
+ } {
+ withSQLConf(SQLConf.USE_V1_SOURCE_LIST.key -> v1Sources,
+ SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> dpp.toString)
{
+ createViews()
+ val optimized =
sql(query(condition)).queryExecution.optimizedPlan
+
assert(optimized.exists(_.isInstanceOf[DataSourceV2ScanRelation]) ===
+ v1Sources.isEmpty, s"wrong source version for
'$v1Sources':\n$optimized")
+ assert(optimized.exists(_.expressions.exists(
+ _.exists(_.isInstanceOf[DynamicPruningSubquery]))) === dpp,
+ s"`$condition` with dpp = $dpp, v1 sources
'$v1Sources':\n$optimized")
+ assert(bloomFilterKeyNames(query(condition)) ==
Review Comment:
nit: Each iteration analyzes and optimizes the same query three times
(`optimizedPlan` on L2093, `sql()` inside `bloomFilterKeyNames`, and
`checkAnswer`), over 4 cases x 2 DPP modes x 2 sources x 2 AQE modes = 32
iterations. Since `bloomFilterKeys` reads `optimizedPlan` too, we can collect
the `BloomFilterMightContain` keys from `optimized` directly. Also, the second
block (L2107-L2126) does not depend on AQE, so it can move out of
`withDppTestConf` and run once.
##########
sql/core/src/test/scala/org/apache/spark/sql/InjectRuntimeFilterSuite.scala:
##########
@@ -2047,6 +2049,87 @@ class InjectRuntimeFilterSuite extends SharedSparkSession
}
}
+ test("SPARK-61173: a DSv2 scan that took a selective filter in fully can be
the creation " +
+ "side, as in V1") {
+ // `FileScanBuilder` takes a partition filter in fully and leaves no
`Filter` for it above the
+ // V2 scan, while V1 keeps the `Filter`. With no selective `Filter` above
the V2 scan, the rule
+ // counts the pushed filters as it counts the condition of that `Filter`.
V1 is the reference.
+ withTempDir { dir =>
+ val factPath = new File(dir, "fact").getCanonicalPath
+ val dimPath = new File(dir, "dim").getCanonicalPath
+ spark.range(100).selectExpr("id", "CAST(id % 10 AS INT) AS part")
+ .write.partitionBy("part").parquet(factPath)
+ spark.range(10).selectExpr("CAST(id AS INT) AS k", "CAST(id AS INT) AS
v",
+ "CAST(id % 2 AS INT) AS dp", "IF(id < 5, 'a1', 'b1') AS ds")
+ .write.partitionBy("dp", "ds").parquet(dimPath)
+ def createViews(): Unit = {
+ // A temp view keeps the relation it was created with, so create both
under the conf.
+ spark.read.parquet(factPath).createOrReplaceTempView("rf_fact")
+ spark.read.parquet(dimPath).createOrReplaceTempView("rf_dim")
+ }
+ def query(condition: String): String =
+ s"SELECT f.id FROM rf_fact f JOIN rf_dim d ON f.part = d.k WHERE
$condition"
+ // (condition, the fact partitions it keeps, the columns the bloom
filters check without DPP
+ // and with a DPP filter that the shuffle join drops). A `LIKE` is not
simple: V1 keeps it in
+ // the `Filter`, and V2 pushes it with no selective `Filter` above the
scan, so neither builds
+ // a bloom filter. For a key with a dropped DPP filter, the pushed
filters must pass
+ // `cannotFail`, which does not take `RLIKE`, also under a selective
`Filter` on `v`.
+ val cases = Seq(
+ ("d.dp = 1", (p: Int) => p % 2 == 1, Seq("part"), Seq("part")),
+ ("d.ds RLIKE '^a'", (p: Int) => p < 5, Seq("part"), Nil),
+ ("d.ds RLIKE '^a' AND d.v > 2", (p: Int) => p == 3 || p == 4,
Seq("part"), Nil),
+ ("d.ds LIKE 'a_'", (p: Int) => p < 5, Nil, Nil))
+ withTempView("rf_fact", "rf_dim") {
+ withDppTestConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+
SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1") {
+ for {
+ (condition, keeps, withoutDpp, withDroppedDpp) <- cases
+ dpp <- Seq(false, true)
+ v1Sources <- Seq("parquet", "")
+ } {
+ withSQLConf(SQLConf.USE_V1_SOURCE_LIST.key -> v1Sources,
+ SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> dpp.toString)
{
+ createViews()
+ val optimized =
sql(query(condition)).queryExecution.optimizedPlan
+
assert(optimized.exists(_.isInstanceOf[DataSourceV2ScanRelation]) ===
+ v1Sources.isEmpty, s"wrong source version for
'$v1Sources':\n$optimized")
+ assert(optimized.exists(_.expressions.exists(
+ _.exists(_.isInstanceOf[DynamicPruningSubquery]))) === dpp,
+ s"`$condition` with dpp = $dpp, v1 sources
'$v1Sources':\n$optimized")
+ assert(bloomFilterKeyNames(query(condition)) ==
+ (if (dpp) withDroppedDpp else withoutDpp),
+ s"`$condition` with dpp = $dpp, v1 sources
'$v1Sources':\n$optimized")
+ checkAnswer(sql(query(condition)),
+ (0 until 100).filter(i => keeps(i % 10)).map(i =>
Row(i.toLong)))
+ }
+ }
+
+ // The bloom filter's subquery reads the dimension scan again, so a
scan with a
+ // row-selecting pushdown, such as a limit, does not count. A file
scan takes none, so
+ // the flag is set by hand, on a plan without DPP so that only this
check decides.
+ withSQLConf(SQLConf.USE_V1_SOURCE_LIST.key -> "") {
+ createViews()
+ val plan =
withSQLConf(SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "false",
+ SQLConf.RUNTIME_BLOOM_FILTER_ENABLED.key -> "false") {
+ sql(query("d.dp = 1")).queryExecution.optimizedPlan
+ }
+ Seq(true, false).foreach { rowWise =>
+ val rewritten = plan.transform {
+ case r: DataSourceV2ScanRelation if r.output.exists(_.name ==
"k") =>
+ r.copy(onlyRowWisePushdowns = rowWise)
Review Comment:
The new branch applies to every DSv2 source, but the test covers only V2
file scans and simulates a row-selecting pushdown with
`r.copy(onlyRowWisePushdowns = ...)`. Could we add an end-to-end case with a V2
source that actually takes a pushed LIMIT or top-N, so that
`V2ScanRelationPushDown` turns the flag off and we check that no bloom filter
is built? Otherwise, if a build site sets `onlyRowWisePushdowns` or
`pushedFilters` differently later, this test keeps passing while a bloom filter
over a limited scan could miss keys and drop join rows. A case mixing a simple
selective pushed filter with a non-simple one (e.g. `d.dp = 1 AND d.ds LIKE
'a_'`) would also pin the `forall(isSimpleExpression)` part.
--
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]