dongjoon-hyun commented on code in PR #60672:
URL: https://github.com/apache/spark/pull/60672#discussion_r4635897369
##########
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:
**[8] A deterministic pushed aggregate may still compute other values on a
second read.**
`hasDeterministicAggregate` closes [1] for a function that declares itself
non-deterministic. But a source can also give other values for an aggregate
that Spark calls deterministic. A pushed `SUM`, `AVG`, `STDDEV_*`, `VAR_*`,
`COVAR_*`, `CORR` or `REGR_*` over a `DOUBLE` or `FLOAT` column is computed by
the source, often in parallel, and the order in which it adds partial results
can change the last bits between two reads. For example, with the aggregate
fully pushed,
```sql
SELECT f.* FROM (SELECT g, SUM(d) AS s FROM cat.db.src GROUP BY g) a
JOIN fact f ON a.g = f.k WHERE a.s > 100
```
the bloom filter's subquery can see an `s` just below 100 for a `g` whose
`s` the join sees just above it, and drop that `g`'s fact rows. A `GROUP BY` on
a string column that the source compares case-insensitively can likewise return
`'Bob'` on one read and `'BOB'` on the other. Like [1], this predates this PR,
and Spark's own JDBC scan does not reach it, since it reports no statistics and
its default size keeps it from being a creation side. But the doc of
`repeatableRead` now says that a scan with a pushed aggregate reads the same
rows again, for any source. Could the doc say that this relies on the source
computing a deterministic aggregate the same way on each read? To be strict
instead, this site could set `repeatableRead` only when every pushed aggregate
gives an exact result, such as `MIN`, `MAX`, `COUNT` and a `SUM` over integral
or decimal input.
##########
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:
**[9] nit: `V2Aggregator.deterministic` could take `isDeterministic()`
instead of a special case here.**
`hasDeterministicAggregate` reads as "has a deterministic aggregate", but it
asks that every pushed group-by expression and aggregate function be
deterministic, so a name like `isDeterministicAggregation` would read closer.
The special case is needed because `V2Aggregator` does not override
`deterministic`, while `ApplyFunctionExpression`, its scalar counterpart, has
```scala
override lazy val deterministic: Boolean = function.isDeterministic &&
children.forall(_.deterministic)
```
The same override in `V2Aggregator` would reduce this helper to
`holder.pushedAggOutputMap.values.forall(_.deterministic)`, and every other
rule that reads `deterministic` would see it too. That changes plans outside
this fix, for example a `Filter` would no longer be pushed below such an
`Aggregate` ([Optimizer.scala
L2914-L2916](https://github.com/apache/spark/blob/37c60a2f9a198de3e6d2dc665e4c98fd5fafcca5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala#L2914-L2916)),
so it fits a separate JIRA better. A TODO here pointing to it would be enough
for this PR.
##########
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:
**[10] nit: the new test checks a sample on the left side only.**
`hasRowSelectingOperators` checks every entry of
`joinedRelationPushedDownOperators`, but every sample here is on `t1`, the left
side, so a check that looked at the first side only would pass too. The two
SPARK-56504 tests above already build the plain join and a left, a right and a
both-sides sample with the same catalog setup (`dfNoSample`, `dfWithSample`,
`rightSample` and `bothSamples`). An `isRepeatableRead` assert on each would
cover the right side without a third copy of the setup, and only the nested
join would need to stay here.
##########
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:
**[11] nit: nothing runs a non-deterministic pushed aggregate through
`InjectRuntimeFilter`.**
This test checks the flag that the aggregate build site sets, and the new
`InjectRuntimeFilterSuite` test checks what `extract` does with a flag set by
`copy`, so each half is covered. But unlike the pushed limit, which
`RotatingLimitDataSourceV2` runs end to end with `checkAnswer`, no test joins a
scan with a non-deterministic pushed aggregate and checks that it gives no
bloom filter. A JDBC scan reports no statistics, so such a test would need a
source that takes the aggregate and reports statistics. If that is more than
this PR needs, the two halves are fine as they are.
--
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]