dongjoon-hyun commented on code in PR #60387:
URL: https://github.com/apache/spark/pull/60387#discussion_r4589428922


##########
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:
   **[10] This arm also fixes a wrong-result bug that has existed since 3.4.0. 
Could it get its own `correctness` JIRA?**
   
   For a key without a DPP filter, master takes a DSv2 scan with a fully pushed 
LIMIT, OFFSET or top-N as the creation side when a selective `Filter` sits 
above it (`case _: LeafNode if hasHitSelectiveFilter`). The bloom filter's 
subquery reads the scan again. If the source returns other rows on that read, 
e.g. for a LIMIT without ORDER BY or a top-N with ties, the bloom filter misses 
keys that the join's own read has, and the join drops those rows silently. The 
SPARK-60702 top-N test pinned that creation side (`Seq("f5")` without DPP), and 
this PR changes it to `Seq("k")`.
   
   For example, in a shuffle join with a connector that takes the limit in 
fully and reports at most 10MB, or with a JDBC catalog table and a lowered 
`spark.sql.defaultSizeInBytes`:
   
   ```sql
   SELECT f.* FROM fact f
   JOIN (SELECT * FROM (SELECT * FROM cat.dim LIMIT 100) WHERE v > 1) d ON f.k 
= d.k
   ```
   
   The runtime bloom filter is enabled by default since 3.4.0, and every 
release since then has this leaf arm. Here the fix shows up only as one bullet 
in the user-facing section of an improvement PR. As with SPARK-60808, the same 
class of bug, which was backported to 4.0 through 4.3, a separate JIRA with the 
`correctness` label and a "Fix wrong results ..." title would make it visible 
and backportable. The backports need their own small change anyway, since 
`repeatableRead` does not exist on those branches.



##########
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:
   **[12] These rows reach the creation side through an adjustment `Filter`, 
not through the new pushed-filter arm.**
   
   `CatalystFilterScanBuilder` reports `reflectsFullyPushedDownFilters() = 
false` unless `REFLECTS_FULLY_PUSHED_DOWN_FILTERS` is set, so `pruneColumns` 
puts the fully pushed `isnotnull(i) AND i > 3` back as a post-pushdown 
adjustment `Filter` above the scan (`withPostPushdownAdjustmentFilters`). This 
row then gets `Seq("part")` through `hasHitSelectiveFilter`, the path master 
already has, and it still passes if `|| hasSelectivePushedFilters(leaf)` is 
removed from the leaf arm. The `LIMIT 3` row has the same `Filter` above its 
scan, so "whether its selective filter is pushed into it or stays above it" 
(L2291-L2293) is not a difference this block exercises, and no test with a 
non-file DSv2 source shows a scan with no `Filter` left becoming a creation 
side.
   
   Could we set 
`.option(CatalystFilterScanBuilder.REFLECTS_FULLY_PUSHED_DOWN_FILTERS, "true")` 
on the `rf_lim` readers and assert that no `Filter` holds `i > 3`? Also, 
"leaves no `Filter` above it" in the doc of `hasSelectivePushedFilters` 
(`DataSourceV2Relation.scala:294`) and in the comment at 
`InjectRuntimeFilter.scala:260` holds only for a scan whose statistics reflect 
its pushed filters.



##########
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:
   **[13] `hasSelectivePushedFilters` does not check `repeatableRead`, so DPP 
and the bloom filter can disagree on the same scan.**
   
   Its doc says it is for "a rule that reads this scan again in a subquery, as 
DPP and a runtime bloom filter do", but it checks only `onlyRowWisePushdowns`, 
and `repeatableRead` is a separate field that defaults to false. Take a scan 
built with `onlyRowWisePushdowns = true` and without `repeatableRead`, as the 
`MergeSubplansSuite` helpers were before this PR, or as a rule in an extension 
may build one. `PartitionPruning` counts its pushed filters 
(`PartitionPruning.scala:236`) and inserts a DPP filter whose subquery may read 
the scan again, while `InjectRuntimeFilter` rejects the same scan 
(`InjectRuntimeFilter.scala:258-259`). That is the drift between the two rules 
that the shared helper was meant to rule out. No build site in Spark creates 
that pair today, so a `require(!onlyRowWisePushdowns || repeatableRead)` in the 
relation, or checking both flags here, would keep it that way.



##########
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
+          if !scan.repeatableRead || 
!scan.pushedFilters.forall(isSimpleExpression) => None
+      // A filter that a DSv2 scan took in fully leaves no `Filter` for it, as 
a built-in file scan
+      // does with its partition filters, so a selective one counts as a 
selective `Filter` does.
+      // The size check of `bloomFilterAggregate` uses the scan's estimate, 
which for a V2 file
+      // scan covers all its partitions.
+      case leaf: LeafNode if hasHitSelectiveFilter || 
hasSelectivePushedFilters(leaf) =>
         Some(FilterCreationSide(
           targetKey,
           currentPlan,
-          useMaterializedThreshold = false))
+          useMaterializedThreshold = false)).filter { side =>
+          hasHitSelectiveFilter || (bloomFilterAggregate(side).isDefined && 
takes(side))

Review Comment:
   **[15] nit: a side found through pushed filters runs these checks twice.**
   
   `bloomFilterAggregate(side)` builds the aggregate here, and 
`injectBloomFilter` builds it again for the same side. `takes(side)` also runs 
`canEvaluateAgain`, which applies `ColumnPruning` to the side, here and again 
in the `.filter(takes)` of `creationSide` (L609). The cost is small, but 
returning the checked aggregate with the side would avoid most of it.



##########
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:
   **[11] This row passes whatever the pushed filter is, so it does not pin the 
`cannotFail` fallback.**
   
   `transformUp` handles the inner join `rf_dim d JOIN bf2` first and injects a 
bloom filter on `d.k`, built from `bf2 WHERE b2 = 23`. When the outer join then 
searches `x`, the `rf_dim` side carries 
`BloomFilterMightContain(ScalarSubquery(...), xxhash64(k))`. That filter is not 
likely selective, so the side goes through the pushed-filter path, where 
`takes` calls `canEvaluateAgain`. It rejects the side because the 
`ScalarSubquery` fails `cannotFail` (`PLAN_EXPRESSION`), not because of the 
`RLIKE`. So with `d.ds = 'b1'` in place of `d.ds RLIKE '^b'`, or with 
`!scan.pushedFilters.forall(cannotFail)` removed from `canEvaluateAgain`, all 
four assertions still hold, and the case the PR description names (a pushed 
side that fails `cannotFail`, falling back to its join's other side) has no 
test that would catch a regression.
   
   Could we use a shape whose key side has no bloom filter of its own when the 
outer join is searched, and add a control row whose pushed filter passes 
`cannotFail` (e.g. `d.ds = 'b1'`)? Then `part` would get its bloom filter from 
`rf_dim` in the control row and from `bf2` with `RLIKE`, and checking which 
leaf the bloom filter's subquery reads would make the difference visible.



##########
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",

Review Comment:
   **[16] nit: this block runs 136 query executions, and about a quarter gives 
the same coverage.**
   
   Here `withDppTestConf` adds only the AQE on/off loop, since this call 
overrides both of its thresholds and `reuseBroadcastOnly` is already true by 
default. The assertions read `optimizedPlan`, which does not depend on AQE for 
these inner joins. That makes 2 AQE modes x (8 conditions x 2 DPP modes x 2 
source modes + 2 fallback rows) = 68 iterations, and each runs `checkAnswer`, 
which executes the query twice. `check` also calls `createViews()` in every 
iteration, so each iteration lists the files and runs a schema-inference job 
for both parquet reads.
   
   Could we use `withSQLConf` here (or pass `ADAPTIVE_EXECUTION_ENABLED -> 
"false"`, as the SPARK-60702 top-N test does), create the views once per source 
mode, and drop the `d.ds LIKE 'a_'` row, which takes the same path as `d.dp = 1 
AND d.ds LIKE 'a_'`?



##########
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:
   **[18] nit: `InMemoryTableWithJoinAndSample` already covers a pushed join 
with a sampled side.**
   
   That table is documented as "Used to test join pushdown when a side has a 
pushed sample", and `DataSourceV2TableSampleSuite` already pushes a sample on 
either side of a join and checks it with `checkJoinPushed`. The three 
assertions of the new test could run there against that table, without a new 
source that accepts a sample without sampling. If this class stays, its 
`isOtherSideCompatibleForJoin` override (L2368-L2369) repeats the inherited 
body (L2412-L2413) and can go.



##########
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:
   **[17] nit: this test optimizes each query three times.**
   
   `sql(query)` runs at L2400, inside `bloomFilterKeys(query)` here, and in 
`checkAnswer(sql(query), ...)` at L2406, the pattern item 8 removed from the 
first test. The first test's local `keyNames(plan)` (L2186) also repeats the 
body of `bloomFilterKeys` and `bloomFilterKeyNames` (L353-L359). `LogicalPlan` 
overloads of those two helpers would serve the callers of `keyNames` and this 
line, with one `val df = sql(query)` reused for `checkAnswer`.



##########
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:
   **[20] nit: this list repeats the one in the test above (L482-L487).**
   
   One `private val` with the row-selecting pushdowns, used by both tests, 
would keep the two in sync when a new one is added.



##########
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:
   **[19] nit: this checks a flag that does not depend on the dialect, in five 
suites.**
   
   `buildScanWithPushedJoin` sets `repeatableRead` from Spark-side holder 
state, so the dialect only decides whether the join is pushed. As a trait 
member, this test runs in `JDBCV2JoinPushdownSuite` and in the MySQL, Postgres, 
Oracle and MsSqlServer docker suites, while `DataSourceV2Suite` already checks 
the same build site. Also, `scans.size == 1` infers the pushdown; 
`checkJoinPushed(df)`, which the trait already uses, would fail with a clearer 
message if a dialect stopped pushing the join.



##########
sql/core/src/test/scala/org/apache/spark/sql/jdbc/JDBCV2Suite.scala:
##########
@@ -1014,6 +1014,20 @@ class JDBCV2Suite extends SharedSparkSession with 
ExplainSuiteHelper {
     checkAnswer(df2, Seq(Row(2, "david", 10000.00)))
   }
 
+  test("SPARK-61173: a scan with a pushed aggregate reads the same rows again, 
unless a top N " +
+    "follows it") {
+    def scanOf(df: DataFrame): DataSourceV2ScanRelation =
+      df.queryExecution.optimizedPlan.collectFirst { case r: 
DataSourceV2ScanRelation => r }
+        .getOrElse(fail(s"no scan in:\n${df.queryExecution.optimizedPlan}"))
+    val agg = 
spark.read.table("h2.test.employee").groupBy("DEPT").sum("SALARY")
+    checkAggregateRemoved(agg)
+    assert(scanOf(agg).repeatableRead && !scanOf(agg).onlyRowWisePushdowns)
+    val topN = agg.orderBy("DEPT").limit(1)

Review Comment:
   **[21] nit: the `topN` half repeats the next test.**
   
   `agg.orderBy("DEPT").limit(1)` is `topN1` of the next test ("scan with 
aggregate push-down, top N push-down and offset push-down"), which already pins 
its pushdown with `checkSortRemoved`, `checkLimitRemoved` and 
`checkPushedInfo`. Only `assert(!scanOf(topN).repeatableRead)` is new here, and 
it could go there. The aggregate half is the only check of `repeatableRead` at 
the aggregate build site, so it is worth keeping.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanRelationPushDown.scala:
##########
@@ -905,17 +905,26 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] 
with PredicateHelper {
    *   - `pushedOffset`           -- pushed OFFSET
    *   - `pushedSample`           -- pushed table sample
    *   - `sortOrders`             -- pushed sort order (top-N / ordering)
+   *   - `joinedRelationsPushedDownOperators` -- table sample pushed into a 
side of a pushed join
    *
    * It decides the `onlyRowWisePushdowns` flag of the plain and the 
variant-extraction scans, see
    * [[DataSourceV2ScanRelation.onlyRowWisePushdowns]], and blocks merging, see
    * [[hasBlockingPushdown]]. A pushed aggregate or join never reaches those 
builds, and their scans
-   * keep the flag's default.
+   * keep the flag's default. It also decides the `repeatableRead` flag of 
every scan this rule
+   * builds, see [[DataSourceV2ScanRelation.repeatableRead]]. Limit, offset 
and top-N pushdowns run
+   * before the aggregate and the join builds, so they see one pushed after an 
aggregate or join. A
+   * sample pushed into a side of a pushed join is kept with that side's 
pushed operators.
    */
   private def hasRowSelectingPushdown(holder: ScanBuilderHolder): Boolean =
     holder.pushedLimit.isDefined ||
       holder.pushedOffset.isDefined ||
       holder.pushedSample.isDefined ||
-      holder.sortOrders.nonEmpty
+      holder.sortOrders.nonEmpty ||
+      holder.joinedRelationsPushedDownOperators.exists(hasPushedSample)
+
+  private def hasPushedSample(operators: PushedDownOperators): Boolean =

Review Comment:
   **[14] nit: `hasPushedSample` relies on the rule order.**
   
   It checks only `sample` in `joinedRelationPushedDownOperators`. A join side 
carries no pushed limit, offset or top-N only because `pushDownLimitAndOffset` 
runs after `pushDownJoin`, which nothing asserts. If that changes, a pushed 
join would keep `repeatableRead = true` with a row-selecting side and pass the 
new arm in `InjectRuntimeFilter`. One recursive check over `limit`, `offset`, 
`sortValues` and `sample` would not depend on the order.



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