LuciferYang commented on code in PR #60387:
URL: https://github.com/apache/spark/pull/60387#discussion_r4612256132
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -239,11 +251,23 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
useMaterializedThreshold = false))
case _ => None
}
- case _: LeafNode if hasHitSelectiveFilter =>
+ // The bloom filter's subquery reads a DSv2 scan again, so only a scan
marked with
+ // `repeatableRead` counts, with or without a selective `Filter` above
it. A pushed limit, for
+ // example, lets the source pick other rows on a second read. The pushed
filters it records
+ // must be simple, as the condition of a `Filter` must.
+ case scan: DataSourceV2ScanRelation
Review Comment:
Thanks, opened SPARK-61870 with the `correctness` label, and added it to the
title. The new test "SPARK-61870: no bloom filter from a DSv2 scan whose pushed
limit returns other rows when read again" reads `RotatingLimitDataSourceV2` and
fails on master with a missing join row, with AQE on and off. This PR, an
improvement, goes to master and branch-4.x. Branch-4.0 through branch-4.4 have
the same leaf case and get their own change under SPARK-61870.
##########
sql/core/src/test/scala/org/apache/spark/sql/InjectRuntimeFilterSuite.scala:
##########
@@ -2162,6 +2165,251 @@ 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`. The rule counts a selective
pushed filter as it counts
+ // 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",
+ "parse_json(CONCAT('{\"a\": ', id, '}')) AS j", "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 keyNames(plan: LogicalPlan): Seq[String] =
plan.flatMap(_.expressions)
+ .flatMap(_.collect { case BloomFilterMightContain(_,
XxHash64(Seq(key), _)) => key })
+ .flatMap(_.references.map(_.name))
+ // Runs `query` with DPP off and on, under V1 and V2. Checks that DPP
adds its filter only
+ // when on, that the bloom filters check `withoutDpp`, or
`withDroppedDpp` when the shuffle
+ // join drops the DPP filter, and that the query returns `expected`.
+ def check(
+ query: String,
+ withoutDpp: Seq[String],
+ withDroppedDpp: Seq[String],
+ expected: Seq[Row],
+ checkPlan: LogicalPlan => Unit = _ => ()): Unit = {
+ for (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 df = sql(query)
+ val optimized = df.queryExecution.optimizedPlan
+ val clue = s"`$query` with dpp = $dpp, v1 sources
'$v1Sources':\n$optimized"
+ assert(optimized.exists(_.isInstanceOf[DataSourceV2ScanRelation])
===
+ v1Sources.isEmpty, clue)
+ assert(optimized.exists(_.expressions.exists(
+ _.exists(_.isInstanceOf[DynamicPruningSubquery]))) === dpp, clue)
+ assert(keyNames(optimized) == (if (dpp) withDroppedDpp else
withoutDpp), clue)
+ if (v1Sources.isEmpty) {
+ // The dimension's scan takes its selective filter on partition
columns in fully.
+ assert(optimized.exists {
+ case r: DataSourceV2ScanRelation =>
+ r.output.exists(_.name == "k") && r.hasSelectivePushedFilters
+ case _ => false
+ }, clue)
+ checkPlan(optimized)
+ }
+ checkAnswer(df, expected)
+ }
+ }
+ }
+ def factRows(keeps: Int => Boolean): Seq[Row] =
+ (0 until 100).filter(i => keeps(i % 10)).map(i => Row(i.toLong))
+ withTempView("rf_fact", "rf_dim") {
+ withDppTestConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+
SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1") {
+ // A bloom filter's subquery takes only simple filters, which `LIKE`
is not, pushed into
+ // the scan or not. For a key with a dropped DPP filter, the filters
must pass
+ // `cannotFail`, which does not take `RLIKE`, pushed into the scan
or not.
+ 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),
+ ("d.ds LIKE 'a_' AND d.v > 2", (p: Int) => p == 3 || p == 4, Nil,
Nil),
+ ("d.dp = 1 AND d.ds LIKE 'a_'", (p: Int) => p == 1 || p == 3, Nil,
Nil)
+ ).foreach { case (condition, keeps, withoutDpp, withDroppedDpp) =>
+ check(s"SELECT f.id FROM rf_fact f JOIN rf_dim d ON f.part = d.k
WHERE $condition",
+ withoutDpp, withDroppedDpp, factRows(keeps))
+ }
+
+ // A variant extraction pushed into the V2 scan builds it at another
site, with new
+ // output attributes. That scan records its pushed filters too, so
they count, and must
+ // pass `cannotFail`.
+ Seq(
+ ("d.dp = 1", (p: Int) => p % 2 == 1, Seq("part"), Seq("part")),
+ ("d.ds RLIKE '^a' AND d.v > 2", (p: Int) => p == 3 || p == 4,
Seq("part"), Nil)
+ ).foreach { case (condition, keeps, withoutDpp, withDroppedDpp) =>
+ check("SELECT f.id, variant_get(d.j, '$.a', 'int') FROM rf_fact f
" +
+ s"JOIN rf_dim d ON f.part = d.k WHERE $condition", withoutDpp,
withDroppedDpp,
+ (0 until 100).filter(i => keeps(i % 10)).map(i => Row(i.toLong,
i % 10)),
+ plan => assert(plan.exists {
+ case r: DataSourceV2ScanRelation =>
+ r.output.exists(_.name == "j") &&
r.output.intersect(r.relation.output).isEmpty
+ case _ => false
+ }, s"expected a scan with a pushed variant extraction:\n$plan"))
+ }
+
+ // A side found through pushed filters that a later check rejects
does not stop the
+ // search: the join that side is in gives the bloom filter from its
other side, which the
+ // selective `b2 = 23` filters. For a key whose DPP filter is
dropped, `canEvaluateAgain`
+ // rejects the dimension side. Without DPP, the bloom filter's
subquery is not
+ // deterministic.
+ withSQLConf(SQLConf.USE_V1_SOURCE_LIST.key -> "") {
+ createViews()
+ Seq(
+ ("rf_dim d", "d.ds RLIKE '^b' AND", true),
Review Comment:
Done in ffe633321db. The inner join has a `BROADCAST(bf2)` hint, so the rule
puts no bloom filter on `d.k` for that join. A control row `d.ds = 'b1'` passes
`cannotFail` and gets the bloom filter on `part` from `rf_dim`, and the `RLIKE`
row from `bf2`. Each row checks which leaf the bloom filter's subquery reads.
Removing `!scan.pushedFilters.forall(cannotFail)` now fails the `RLIKE` row.
##########
sql/core/src/test/scala/org/apache/spark/sql/InjectRuntimeFilterSuite.scala:
##########
@@ -2162,6 +2165,251 @@ 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`. The rule counts a selective
pushed filter as it counts
+ // 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",
+ "parse_json(CONCAT('{\"a\": ', id, '}')) AS j", "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 keyNames(plan: LogicalPlan): Seq[String] =
plan.flatMap(_.expressions)
+ .flatMap(_.collect { case BloomFilterMightContain(_,
XxHash64(Seq(key), _)) => key })
+ .flatMap(_.references.map(_.name))
+ // Runs `query` with DPP off and on, under V1 and V2. Checks that DPP
adds its filter only
+ // when on, that the bloom filters check `withoutDpp`, or
`withDroppedDpp` when the shuffle
+ // join drops the DPP filter, and that the query returns `expected`.
+ def check(
+ query: String,
+ withoutDpp: Seq[String],
+ withDroppedDpp: Seq[String],
+ expected: Seq[Row],
+ checkPlan: LogicalPlan => Unit = _ => ()): Unit = {
+ for (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 df = sql(query)
+ val optimized = df.queryExecution.optimizedPlan
+ val clue = s"`$query` with dpp = $dpp, v1 sources
'$v1Sources':\n$optimized"
+ assert(optimized.exists(_.isInstanceOf[DataSourceV2ScanRelation])
===
+ v1Sources.isEmpty, clue)
+ assert(optimized.exists(_.expressions.exists(
+ _.exists(_.isInstanceOf[DynamicPruningSubquery]))) === dpp, clue)
+ assert(keyNames(optimized) == (if (dpp) withDroppedDpp else
withoutDpp), clue)
+ if (v1Sources.isEmpty) {
+ // The dimension's scan takes its selective filter on partition
columns in fully.
+ assert(optimized.exists {
+ case r: DataSourceV2ScanRelation =>
+ r.output.exists(_.name == "k") && r.hasSelectivePushedFilters
+ case _ => false
+ }, clue)
+ checkPlan(optimized)
+ }
+ checkAnswer(df, expected)
+ }
+ }
+ }
+ def factRows(keeps: Int => Boolean): Seq[Row] =
+ (0 until 100).filter(i => keeps(i % 10)).map(i => Row(i.toLong))
+ withTempView("rf_fact", "rf_dim") {
+ withDppTestConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+
SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1") {
+ // A bloom filter's subquery takes only simple filters, which `LIKE`
is not, pushed into
+ // the scan or not. For a key with a dropped DPP filter, the filters
must pass
+ // `cannotFail`, which does not take `RLIKE`, pushed into the scan
or not.
+ 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),
+ ("d.ds LIKE 'a_' AND d.v > 2", (p: Int) => p == 3 || p == 4, Nil,
Nil),
+ ("d.dp = 1 AND d.ds LIKE 'a_'", (p: Int) => p == 1 || p == 3, Nil,
Nil)
+ ).foreach { case (condition, keeps, withoutDpp, withDroppedDpp) =>
+ check(s"SELECT f.id FROM rf_fact f JOIN rf_dim d ON f.part = d.k
WHERE $condition",
+ withoutDpp, withDroppedDpp, factRows(keeps))
+ }
+
+ // A variant extraction pushed into the V2 scan builds it at another
site, with new
+ // output attributes. That scan records its pushed filters too, so
they count, and must
+ // pass `cannotFail`.
+ Seq(
+ ("d.dp = 1", (p: Int) => p % 2 == 1, Seq("part"), Seq("part")),
+ ("d.ds RLIKE '^a' AND d.v > 2", (p: Int) => p == 3 || p == 4,
Seq("part"), Nil)
+ ).foreach { case (condition, keeps, withoutDpp, withDroppedDpp) =>
+ check("SELECT f.id, variant_get(d.j, '$.a', 'int') FROM rf_fact f
" +
+ s"JOIN rf_dim d ON f.part = d.k WHERE $condition", withoutDpp,
withDroppedDpp,
+ (0 until 100).filter(i => keeps(i % 10)).map(i => Row(i.toLong,
i % 10)),
+ plan => assert(plan.exists {
+ case r: DataSourceV2ScanRelation =>
+ r.output.exists(_.name == "j") &&
r.output.intersect(r.relation.output).isEmpty
+ case _ => false
+ }, s"expected a scan with a pushed variant extraction:\n$plan"))
+ }
+
+ // A side found through pushed filters that a later check rejects
does not stop the
+ // search: the join that side is in gives the bloom filter from its
other side, which the
+ // selective `b2 = 23` filters. For a key whose DPP filter is
dropped, `canEvaluateAgain`
+ // rejects the dimension side. Without DPP, the bloom filter's
subquery is not
+ // deterministic.
+ withSQLConf(SQLConf.USE_V1_SOURCE_LIST.key -> "") {
+ createViews()
+ Seq(
+ ("rf_dim d", "d.ds RLIKE '^b' AND", true),
+ ("(SELECT CAST(k + rand() * 0 AS INT) AS k FROM rf_dim WHERE dp
= 1) d", "", false)
+ ).foreach { case (dim, condition, dpp) =>
+ withSQLConf(SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key ->
dpp.toString) {
+ val df = sql(s"SELECT f.id FROM rf_fact f JOIN (SELECT d.k
FROM $dim JOIN bf2 " +
+ s"ON d.k = bf2.a2 WHERE $condition bf2.b2 = 23) x ON f.part
= x.k")
+ val optimized = df.queryExecution.optimizedPlan
+ val clue = s"`$dim`:\n$optimized"
+ assert(optimized.exists {
+ case r: DataSourceV2ScanRelation =>
+ r.output.exists(_.name == "k") &&
r.hasSelectivePushedFilters
+ case _ => false
+ }, clue)
+ assert(optimized.exists(_.expressions.exists(
+ _.exists(_.isInstanceOf[DynamicPruningSubquery]))) === dpp,
clue)
+ assert(keyNames(optimized).contains("part"), clue)
+ checkAnswer(df, factRows(_ == 5))
+ }
+ }
+ }
+ }
+ }
+
+ // The bloom filter's subquery reads the scan again, so a scan with a
row-selecting pushdown,
+ // such as a limit, is not a creation side, whether its selective filter
is pushed into it or
+ // stays above it. Then `f.part` gets no bloom filter, and the fact,
which the inferred
+ // `part > 3` filters, gives one on `d.i`.
+ withTempView("rf_fact", "rf_lim") {
+ withSQLConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+
SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1",
+ SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "false",
+ SQLConf.USE_V1_SOURCE_LIST.key -> "") {
+ spark.read.parquet(factPath).createOrReplaceTempView("rf_fact")
+ // It takes Catalyst filters in fully, and a limit. Its size comes
from the row count.
+ spark.read.format(classOf[CatalystFilterLimitDataSourceV2].getName)
+ .option(CatalystFilterScanBuilder.REPORTED_ROW_COUNT, "10").load()
+ .createOrReplaceTempView("rf_lim")
+ // (dimension, whether its scan is row-wise and repeatable, whether
it took `i > 3` in,
+ // the columns the bloom filters check, the fact partitions the join
keeps)
+ Seq(
+ ("SELECT i FROM rf_lim WHERE i > 3", true, true, Seq("part"), 4 to
9),
Review Comment:
Done in ffe633321db. The `rf_lim` reader of these rows sets
`REFLECTS_FULLY_PUSHED_DOWN_FILTERS`, and each row asserts that a `Filter` on
`i > 3` stays above the scan only when the scan did not take it in. Removing
`|| hasSelectivePushedFilters(leaf)` now fails the first row. The doc of
`hasSelectivePushedFilters` and the comment on the leaf case now say a `Filter`
can come back when `reflectsFullyPushedDownFilters` is false.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala:
##########
@@ -279,6 +287,15 @@ case class DataSourceV2ScanRelation(
// skip adding IsNotNull when the scan already implies it, or infer new
filters across
// joins), so plan stability testing is needed first.
+ /**
+ * Whether a rule that reads this scan again in a subquery, as DPP and a
runtime bloom filter
+ * do, can count its pushed filters as a selective `Filter` above it: one of
them is likely
+ * selective, and every operation pushed into the scan works on each row by
itself. A filter
+ * the scan took in fully leaves no `Filter` above it, where V1 keeps one.
+ */
+ def hasSelectivePushedFilters: Boolean =
Review Comment:
Done in ffe633321db: `DataSourceV2ScanRelation` now requires
`!onlyRowWisePushdowns || repeatableRead`, and both param docs say so. That
also keeps SPARK-61811's check in `PartitionPruning`, which reads only
`onlyRowWisePushdowns`, in line with `repeatableRead`. No build site in Spark
creates that pair, and the tests that copy `onlyRowWisePushdowns` into a scan
copy a repeatable one. `DataSourceV2RelationSuite` checks that the constructor
rejects the pair.
--
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]