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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanRelationPushDown.scala:
##########
@@ -931,7 +949,8 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] 
with PredicateHelper {
       // changes to aggregate columns. When validConstraints is wired up, this 
needs revisiting.
       // A pushed aggregate cannot be reproduced by rebuilding the scan, so 
this scan stays
       // not-mergeable (the default `mergeableScan = false`).
-      val scanRelation = DataSourceV2ScanRelation(holder.relation, 
wrappedScan, realOutput)
+      val scanRelation = DataSourceV2ScanRelation(holder.relation, 
wrappedScan, realOutput,
+        repeatableRead = !hasRowSelectingPushdown(holder) && 
hasDeterministicAggregate(holder))

Review Comment:
   Thanks. In 05f4aa8daa7 the doc of `repeatableRead` now says that, for a 
pushed aggregate, it relies on the source computing the aggregate, including 
its groups, the same way on each read, for example adding floating point values 
in the same order. I'd keep it to the doc rather than a list of exact 
aggregates. Such a list would still miss your `GROUP BY` example, since the 
source does the grouping too, and such a scan could already be a creation side 
before this PR.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanRelationPushDown.scala:
##########
@@ -891,31 +891,49 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] 
with PredicateHelper {
    * `SupportsPushDownRequiredColumns`) and `pushedPredicates` / 
`pushedFilterExpressions`
    * (deterministic filters, re-pushed via `SupportsPushDownV2Filters`). A 
pushed aggregate, join or
    * variant never reaches here -- their build rules run first. When a new 
pushdown capability adds
-   * plain-scan state to [[ScanBuilderHolder]], list it in 
[[hasRowSelectingPushdown]] when it
-   * decides which rows the scan returns, which keeps the scan not-mergeable 
too. List it here when
-   * a merge cannot reproduce it but it works on each row by itself.
+   * plain-scan state to [[ScanBuilderHolder]], record it in 
`getPushedDownOperators` and list it
+   * in [[hasRowSelectingOperators]] when it decides which rows the scan 
returns, which keeps the
+   * scan not-mergeable too. List it here when a merge cannot reproduce it but 
it works on each row
+   * by itself.
    */
   private def hasBlockingPushdown(holder: ScanBuilderHolder): Boolean =
     hasRowSelectingPushdown(holder)
 
   /**
    * Whether the scan took a pushed operation that decides which rows it 
returns, rather than one
-   * that works on each row by itself:
-   *   - `pushedLimit`            -- pushed LIMIT
-   *   - `pushedOffset`           -- pushed OFFSET
-   *   - `pushedSample`           -- pushed table sample
-   *   - `sortOrders`             -- pushed sort order (top-N / ordering)
+   * that works on each row by itself: a pushed LIMIT, OFFSET, table sample or 
sort order (top-N),
+   * also in a side of a pushed join. It reads the operators that 
`getPushedDownOperators` records.
    *
    * 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. The aggregate and the join builds set 
`repeatableRead` from it
+   * instead, the aggregate build together with [[hasDeterministicAggregate]], 
see
+   * [[DataSourceV2ScanRelation.repeatableRead]]. Limit, offset and top-N 
pushdowns run before the
+   * aggregate and the join builds, so those builds see a limit, offset or 
top-N pushed above an
+   * aggregate or join. An operation pushed into a side of a pushed join is 
kept with that side's
+   * pushed operators, whichever pushdowns run before `pushDownJoin`.
    */
   private def hasRowSelectingPushdown(holder: ScanBuilderHolder): Boolean =
-    holder.pushedLimit.isDefined ||
-      holder.pushedOffset.isDefined ||
-      holder.pushedSample.isDefined ||
-      holder.sortOrders.nonEmpty
+    hasRowSelectingOperators(getPushedDownOperators(holder))
+
+  private def hasRowSelectingOperators(operators: PushedDownOperators): 
Boolean =
+    operators.limit.isDefined ||
+      operators.offset.isDefined ||
+      operators.sample.isDefined ||
+      operators.sortValues.nonEmpty ||
+      
operators.joinedRelationPushedDownOperators.exists(hasRowSelectingOperators)
+
+  // Whether every pushed group-by expression and aggregate function is 
deterministic.
+  // `V2Aggregator` does not take `BoundFunction.isDeterministic` into its 
`deterministic`, so it is
+  // checked here.
+  private def hasDeterministicAggregate(holder: ScanBuilderHolder): Boolean =

Review Comment:
   Done in 05f4aa8daa7: the helper is now `isDeterministicAggregation`, with a 
TODO for SPARK-62133, which tracks making `V2Aggregator.deterministic` take 
`isDeterministic()`. Besides the `Filter` pushdown, a probe shows that two 
calls of such a function in one `SELECT` are merged into one aggregate 
expression today, while a non-deterministic Spark UDAF gets two. Both are in 
the JIRA.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DataSourceV2TableSampleSuite.scala:
##########
@@ -313,6 +313,36 @@ class DataSourceV2TableSampleSuite extends 
DatasourceV2SQLBase
     }
   }
 
+  test("SPARK-61870: a pushed join reads the same rows again unless a side 
took a sample") {

Review Comment:
   Done in 05f4aa8daa7: the two SPARK-56504 tests now assert `isRepeatableRead` 
on the plain join and on the left, the right and the both-sides samples, and 
the SPARK-61870 test keeps only the nested join.



##########
sql/core/src/test/scala/org/apache/spark/sql/jdbc/JDBCV2Suite.scala:
##########
@@ -1016,6 +1019,29 @@ class JDBCV2Suite extends SharedSparkSession with 
ExplainSuiteHelper {
     checkAnswer(df2, Seq(Row(2, "david", 10000.00)))
   }
 
+  test("SPARK-61870: a scan with a pushed aggregate reads the same rows 
again") {
+    val agg = 
spark.read.table("h2.test.employee").groupBy("DEPT").sum("SALARY")
+    checkAggregateRemoved(agg)
+    val scan = scanOf(agg)
+    assert(scan.repeatableRead && !scan.onlyRowWisePushdowns)
+  }
+
+  test("SPARK-61870: a scan with a pushed aggregate function that is not 
deterministic does not " +
+    "read the same rows again") {
+    JdbcDialects.unregisterDialect(h2Dialect)
+    try {
+      JdbcDialects.registerDialect(testH2Dialect)
+      Seq("my_avg" -> true, "my_nondeterministic_avg" -> false).foreach { case 
(f, repeatable) =>
+        val df = sql(s"SELECT name, h2.$f(id) FROM h2.test.people GROUP BY 
name")
+        checkAggregateRemoved(df)
+        assert(scanOf(df).isRepeatableRead == repeatable, f)

Review Comment:
   Done in 05f4aa8daa7. The `JDBCV2Suite` test now also joins each aggregate 
scan with a Parquet table under `v > 0`, with a small 
`spark.sql.defaultSizeInBytes` so that the JDBC scan can be a creation side, 
and checks that only the `my_avg` scan gives a bloom filter. Without the 
`isRepeatableRead` case in `extract`, it fails for `my_nondeterministic_avg`.



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