LuciferYang commented on code in PR #60387:
URL: https://github.com/apache/spark/pull/60387#discussion_r4573099441


##########
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:
   Done in 04f8a85e9ce. Each run optimizes the query once and reads the bloom 
filter keys from that plan. The limit check is now end to end, over a source 
that takes a limit (item 9), and runs once outside `withDppTestConf`. One block 
still sets `repeatableRead` by hand, to show that a repeatable scan that is not 
row-wise still counts under a selective `Filter`. The aggregate, join, variant 
and copy-on-write build sites are checked in their own suites. The first group 
has more conditions, for items 2 and 9, and a new group covers item 3.



##########
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:
   Done in 04f8a85e9ce. The test reads `CatalystFilterLimitDataSourceV2`, which 
takes a Catalyst filter and a limit in fully: once with the selective filter 
pushed into the scan, and once with it above a pushed limit. It checks that no 
`Limit` stays, that the scan is marked neither row-wise nor `repeatableRead`, 
and that `f.part` gets no bloom filter in either case. `JDBCV2Suite`, the join 
pushdown suite, `DataSourceV2Suite` (a sample below one or two pushed joins), 
`StorageFilterPushDownSuite` and `GroupBasedUpdateTableSuite` check the flag at 
the aggregate, join, variant and copy-on-write build sites. The test also has 
`d.dp = 1 AND d.ds LIKE 'a_'`, which gets none.



##########
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:
   Done in 20f53216f26. A side found through pushed filters now counts only 
when both join keys compare by their bytes (`UnsafeRowUtils.isBinaryStable`), 
the condition `extractBeneficialFilterCreatePlan` already computes. The new 
test reads a V2 parquet dimension partitioned by `dp` with a `UTF8_LCASE` key 
and `dp = 1` taken in fully, and checks that the `IN` subquery, on the key and 
on a struct holding it, gets no bloom filter and returns the row whose key 
matches only under the collation. The selective-`Filter` path keeps the gap for 
a key without a DPP filter, as on master.



-- 
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]

Reply via email to