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


##########
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),
+            ("SELECT i FROM rf_lim WHERE i > 3 LIMIT 3", false, true, 
Seq("i"), 4 to 6),
+            ("SELECT i FROM (SELECT i FROM rf_lim LIMIT 5) WHERE i > 3", 
false, false, Seq("i"),
+              Seq(4))
+          ).foreach { case (dim, rowWiseAndRepeatable, pushed, 
bloomFilterColumns, parts) =>
+            val df = sql(s"SELECT f.id FROM rf_fact f JOIN ($dim) d ON f.part 
= d.i")
+            val optimized = df.queryExecution.optimizedPlan
+            val clue = s"`$dim`:\n$optimized"
+            // The source takes the limit in fully, so no `Limit` stays above 
its scan.
+            assert(!optimized.exists(_.isInstanceOf[LocalLimit]), clue)
+            val scan = optimized.collectFirst {
+              case r: DataSourceV2ScanRelation if r.output.exists(_.name == 
"i") => r
+            }.getOrElse(fail(s"no dimension scan in $clue"))
+            assert(scan.onlyRowWisePushdowns == rowWiseAndRepeatable, clue)
+            assert(scan.repeatableRead == rowWiseAndRepeatable, clue)
+            assert(scan.pushedFilters.exists(_.isInstanceOf[GreaterThan]) == 
pushed, clue)
+            assert(keyNames(optimized) == bloomFilterColumns, clue)
+            checkAnswer(df, factRows(p => parts.contains(p)))
+          }
+
+          // A scan that reads the same rows again but is not row-wise, as 
with a pushed aggregate
+          // or join or as the target read of a copy-on-write UPDATE, still 
counts under a selective
+          // `Filter`, but not for a key whose DPP filter is dropped: such a 
scan records no pushed
+          // filters for `cannotFail` to check. The source keeps `i > 3` in a 
`Filter` above its
+          // scan here.
+          spark.read.format(classOf[CatalystFilterLimitDataSourceV2].getName)
+            .option(CatalystFilterScanBuilder.REPORTED_ROW_COUNT, "10")
+            .option(CatalystFilterScanBuilder.KEEP_RESIDUAL_FILTERS, 
"true").load()
+            .createOrReplaceTempView("rf_lim")
+          Seq(false, true).foreach { dpp =>
+            val plan = withSQLConf(SQLConf.RUNTIME_BLOOM_FILTER_ENABLED.key -> 
"false",
+                SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> dpp.toString) 
{
+              sql("SELECT f.id FROM rf_fact f JOIN rf_lim d ON f.part = d.i 
WHERE d.i > 3")
+                .queryExecution.optimizedPlan
+            }
+            assert(plan.exists(_.expressions.exists(
+              _.exists(_.isInstanceOf[DynamicPruningSubquery]))) === dpp, 
s"dpp = $dpp:\n$plan")
+            Seq(true, false).foreach { repeatable =>
+              val rewritten = plan.transform {
+                case r: DataSourceV2ScanRelation if r.output.exists(_.name == 
"i") =>
+                  r.copy(onlyRowWisePushdowns = false, repeatableRead = 
repeatable)
+              }
+              val expected = if (repeatable && !dpp) Seq("part") else Seq("i")
+              assert(keyNames(InjectRuntimeFilter(rewritten)) == expected,
+                s"dpp = $dpp, repeatableRead = $repeatable:\n$rewritten")
+            }
+          }
+
+          // A scan whose pushed filters are selective but which is too large 
for the creation side
+          // does not stop the search: the join it is in gives the bloom 
filter from its other side,
+          // which the selective `b2 = 23` filters. The source's size comes 
from its row count.
+          spark.read.format(classOf[CatalystFilterLimitDataSourceV2].getName)
+            .option(CatalystFilterScanBuilder.REPORTED_ROW_COUNT, 
"1000000000").load()
+            .createOrReplaceTempView("rf_lim")
+          val nested = sql("SELECT f.id FROM rf_fact f JOIN (SELECT l.i FROM 
rf_lim l " +
+            "JOIN bf2 ON l.i = bf2.a2 WHERE l.j < -3 AND bf2.b2 = 23) x ON 
f.part = x.i")
+          val nestedPlan = nested.queryExecution.optimizedPlan
+          val large = nestedPlan.collectFirst {
+            case r: DataSourceV2ScanRelation if r.output.exists(_.name == "i") 
=> r
+          }.getOrElse(fail(s"no scan of rf_lim in\n$nestedPlan"))
+          assert(large.hasSelectivePushedFilters && large.stats.sizeInBytes >
+            spark.sessionState.conf.runtimeFilterCreationSideThreshold, 
nestedPlan)
+          assert(keyNames(nestedPlan).contains("part"), s"expected a bloom 
filter on part:\n" +
+            nestedPlan)
+          checkAnswer(nested, factRows(_ == 5))
+        }
+      }
+    }
+  }
+
+  test("SPARK-61173: no bloom filter from pushed filters on a key that does 
not compare by its " +
+    "bytes") {
+    // The bloom filter hashes the bytes of the key, so `'abc'` and `'ABC'` 
would not match. The
+    // V2 dimension's only selective filter is the partition filter its scan 
takes in fully.
+    withTempDir { dir =>
+      val factPath = new File(dir, "fact").getCanonicalPath
+      val dimPath = new File(dir, "dim").getCanonicalPath
+      spark.sql("SELECT 'abc' AS k, 1 AS v").write.parquet(factPath)
+      spark.sql("SELECT * FROM VALUES ('ABC', 1), ('zzz', 0) AS t(k, dp)")
+        .write.partitionBy("dp").parquet(dimPath)
+      withTempView("cf", "cd") {
+        withSQLConf(SQLConf.USE_V1_SOURCE_LIST.key -> "",
+            SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+            
SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "0",
+            SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "false") {
+          spark.read.schema("k string collate utf8_lcase, v 
int").parquet(factPath)
+            .createOrReplaceTempView("cf")
+          spark.read.schema("k string collate utf8_lcase, dp 
int").parquet(dimPath)
+            .createOrReplaceTempView("cd")
+          // A plain collated key, and one in a struct.
+          Seq("k", "named_struct('s', k)").foreach { key =>
+            val query = s"select v from cf where $key in (select $key from cd 
where dp = 1)"
+            val optimized = sql(query).queryExecution.optimizedPlan
+            assert(optimized.exists {
+              case r: DataSourceV2ScanRelation => r.hasSelectivePushedFilters
+              case _ => false
+            }, s"expected the dimension to take `dp = 1` in 
fully:\n$optimized")
+            assert(bloomFilterKeys(query).isEmpty, s"$key:\n$optimized")

Review Comment:
   Done in ffe633321db. `bloomFilterKeys` and `bloomFilterKeyNames` have 
`LogicalPlan` overloads, which replace the local `keyNames`, and the 
collated-key test calls `sql(query)` once.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DataSourceV2Suite.scala:
##########
@@ -2341,6 +2360,24 @@ class CatalystFilterJoinDataSourceV2 extends 
TestingV2Source {
   }
 }
 
+class CatalystFilterJoinSampleDataSourceV2 extends TestingV2Source {

Review Comment:
   Done in ffe633321db. The test moved to `DataSourceV2TableSampleSuite` over 
`InMemoryTableWithJoinAndSample`, with `checkJoinPushed` before each assertion, 
and `CatalystFilterJoinSampleDataSourceV2` is gone.



##########
sql/core/src/test/scala/org/apache/spark/sql/jdbc/v2/JDBCV2JoinPushdownIntegrationSuiteBase.scala:
##########
@@ -358,6 +358,18 @@ trait JDBCV2JoinPushdownIntegrationSuiteBase
     }
   }
 
+  test("SPARK-61173: a scan with a pushed join reads the same rows again") {
+    withSQLConf(SQLConf.DATA_SOURCE_V2_JOIN_PUSHDOWN.key -> "true") {
+      val df = sql(s"""
+        |SELECT * FROM $catalogAndNamespace.$casedJoinTableName1 a
+        |JOIN $catalogAndNamespace.$casedJoinTableName1 b
+        |ON a.id = b.id + 1""".stripMargin)
+      val scans = df.queryExecution.optimizedPlan.collect { case r: 
DataSourceV2ScanRelation => r }
+      assert(scans.size == 1 && scans.head.repeatableRead && 
!scans.head.onlyRowWisePushdowns,

Review Comment:
   Done in ffe633321db: removed from the trait. The test in 
`DataSourceV2TableSampleSuite` checks the join build site, including 
`!onlyRowWisePushdowns`.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/StorageFilterPushDownSuite.scala:
##########
@@ -497,6 +497,29 @@ class StorageFilterPushDownSuite
     }
   }
 
+  test("SPARK-61173: a scan with a pushed variant extraction and a 
row-selecting pushdown is " +
+    "neither row-wise nor repeatable") {
+    // The variant build site gives the scan new output attributes.
+    def variantScan(push: String, apply: DataFrame => DataFrame): 
DataSourceV2ScanRelation = {
+      val df = apply(v2Probe("variant" -> "true", "push" -> push)
+        .selectExpr("k", "v", "variant_get(j, '$.a', 'long') AS a"))
+      df.queryExecution.optimizedPlan.collectFirst {
+        case r: DataSourceV2ScanRelation if 
r.output.intersect(r.relation.output).isEmpty => r
+      }.getOrElse(fail(s"no variant scan 
in:\n${df.queryExecution.optimizedPlan}"))
+    }
+    val unrestricted = variantScan("", identity)
+    assert(unrestricted.onlyRowWisePushdowns && unrestricted.repeatableRead)
+    Seq[(String, DataFrame => DataFrame)](
+      "limit" -> (_.limit(100)),

Review Comment:
   Done in ffe633321db: one `private val rowSelectingPushdowns`, used by both 
tests.



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